gerege-cli 0.26.5 → 0.26.7

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 (237) hide show
  1. package/README.md +8 -8
  2. package/chunks/{MaxSizedBox-VMVLMS4X.js → MaxSizedBox-LSNOJEKM.js} +1 -1
  3. package/chunks/{StandaloneSessionPicker-UNORCVYY.js → StandaloneSessionPicker-KSYGPMEV.js} +1 -1
  4. package/chunks/{acp-subagent-executor-623ZUTJT.js → acp-subagent-executor-NSW2MFUI.js} +1 -1
  5. package/chunks/{acpAgent-MTTDTK2C.js → acpAgent-3DTOHTDM.js} +3 -3
  6. package/chunks/{advisor-ANUGICJ5.js → advisor-7JGQPS7X.js} +1 -1
  7. package/chunks/{agent-GNCQDICJ.js → agent-PNKQJGDO.js} +1 -1
  8. package/chunks/{agent-headless-OPUXAXQM.js → agent-headless-7D33X7QQ.js} +1 -1
  9. package/chunks/{agent-host-client-K6GRPTFD.js → agent-host-client-3R2MAUVE.js} +1 -1
  10. package/chunks/{agent-host-connections-MF3YBZU2.js → agent-host-connections-2D7DECAE.js} +1 -1
  11. package/chunks/{anthropicContentGenerator-OK4PFE5Y.js → anthropicContentGenerator-MGTJJGEQ.js} +1 -1
  12. package/chunks/{autofix-pr-MABTGEHZ.js → autofix-pr-OIHHZSPQ.js} +1 -1
  13. package/chunks/{batch-V2NJT3M5.js → batch-6UDAMPAA.js} +1 -1
  14. package/chunks/{bridge-BJQ627CX.js → bridge-QXVXPNJ6.js} +1 -1
  15. package/chunks/{channel-settings-store-4JMCI4UR.js → channel-settings-store-P4W4R5SJ.js} +1 -1
  16. package/chunks/{chunk-ZN57TOVA.js → chunk-2DU2WMTL.js} +1 -1
  17. package/chunks/{chunk-ISGF3BVD.js → chunk-2J2BQ3PL.js} +2 -2
  18. package/chunks/{chunk-TQTIEK2W.js → chunk-2LMSDH6P.js} +1 -1
  19. package/chunks/{chunk-EIILQ6KT.js → chunk-3EZ5GCUT.js} +1 -1
  20. package/chunks/{chunk-UY2ET2AL.js → chunk-3ICJI5KW.js} +1 -1
  21. package/chunks/{chunk-VDRE7U3P.js → chunk-4A663FE6.js} +5 -5
  22. package/chunks/{chunk-2IGE2K5V.js → chunk-4AKTP4MM.js} +1 -1
  23. package/chunks/{chunk-NO26JN24.js → chunk-4LC4INFI.js} +1 -1
  24. package/chunks/{chunk-CKZRJP4F.js → chunk-4ME3BUJK.js} +1 -1
  25. package/chunks/{chunk-3XBJYUWP.js → chunk-4QOVM2LL.js} +1 -1
  26. package/chunks/{chunk-ZYTG6R7S.js → chunk-4VR4DUUD.js} +1 -1
  27. package/chunks/{chunk-DE53B2R7.js → chunk-4W27Z3OL.js} +1 -1
  28. package/chunks/{chunk-QOYRDEXR.js → chunk-53IB4U4E.js} +1 -1
  29. package/chunks/{chunk-CCOUFBOY.js → chunk-5R2JIZID.js} +1 -1
  30. package/chunks/{chunk-MPAR4JBP.js → chunk-5TWAP4OG.js} +1 -1
  31. package/chunks/{chunk-3NQESE5K.js → chunk-6JAXAFX7.js} +1 -1
  32. package/chunks/{chunk-POA4NX4N.js → chunk-6WV5RKYB.js} +1 -1
  33. package/chunks/{chunk-KN27BFXM.js → chunk-6YFNUVJR.js} +1 -1
  34. package/chunks/{chunk-2X3UF2CF.js → chunk-7HFFTOAD.js} +1 -1
  35. package/chunks/{chunk-KDYUZBZC.js → chunk-ATTJQLQV.js} +1 -1
  36. package/chunks/{chunk-USJFJZ23.js → chunk-BGELKSQ4.js} +1 -1
  37. package/chunks/{chunk-X4BFEDWU.js → chunk-BIPPD7W6.js} +1 -1
  38. package/chunks/{chunk-DEMXCA3K.js → chunk-BVV7UXES.js} +1 -1
  39. package/chunks/{chunk-2VCDJ6UF.js → chunk-BY46PCWY.js} +1 -1
  40. package/chunks/{chunk-CXGGC4NO.js → chunk-CDKBM72V.js} +1 -1
  41. package/chunks/{chunk-5WLKN3GD.js → chunk-CK3OKTTL.js} +1 -1
  42. package/chunks/{chunk-FHBGTZ4K.js → chunk-DEJ47KJE.js} +1 -1
  43. package/chunks/{chunk-DTTC4ZKY.js → chunk-DQQN2HOP.js} +1 -1
  44. package/chunks/{chunk-PN62SUYK.js → chunk-DTX2OVQW.js} +1 -1
  45. package/chunks/{chunk-IBYFSHBB.js → chunk-DVUKYOCJ.js} +1 -1
  46. package/chunks/{chunk-Q5E5SOY2.js → chunk-E3KWSRJN.js} +1 -1
  47. package/chunks/{chunk-IDUGQMTP.js → chunk-EEPNACXJ.js} +1 -1
  48. package/chunks/{chunk-E5YRAQXM.js → chunk-EKRUF347.js} +1 -1
  49. package/chunks/{chunk-HSYBIGMS.js → chunk-F5SLLEJY.js} +1 -1
  50. package/chunks/{chunk-5ZQWQ3RK.js → chunk-F7622ZRQ.js} +1 -1
  51. package/chunks/{chunk-KKBOCRPF.js → chunk-FKUDVIME.js} +1 -1
  52. package/chunks/{chunk-62NLMVVT.js → chunk-FRVXSKL4.js} +1 -1
  53. package/chunks/{chunk-FIM7MM25.js → chunk-FTF2NFLB.js} +1 -1
  54. package/chunks/{chunk-OHXQYU6S.js → chunk-G4MWPXNY.js} +1 -1
  55. package/chunks/{chunk-SELRSZFK.js → chunk-GA35LMSX.js} +1 -1
  56. package/chunks/{chunk-SMYBY353.js → chunk-H34KVVI4.js} +1 -1
  57. package/chunks/{chunk-NGOIJH7K.js → chunk-H5EXNXGW.js} +1 -1
  58. package/chunks/{chunk-UBXLQ6TP.js → chunk-HJLRKM3W.js} +1 -1
  59. package/chunks/{chunk-CAPG7UVH.js → chunk-HVP4UF2Q.js} +1 -1
  60. package/chunks/{chunk-H57IX45A.js → chunk-HXTYFGSQ.js} +1 -1
  61. package/chunks/{chunk-55RVKT4O.js → chunk-IIHUDJX7.js} +1 -1
  62. package/chunks/{chunk-XFLLE2J3.js → chunk-IQMKQKKD.js} +2 -2
  63. package/chunks/{chunk-SQQORHMS.js → chunk-ISQMHOCC.js} +1 -1
  64. package/chunks/{chunk-YLAI26PX.js → chunk-IY7M5HKF.js} +1 -1
  65. package/chunks/{chunk-FDUXQAGW.js → chunk-IZXHCHJD.js} +1 -1
  66. package/chunks/{chunk-ZOBX6C7E.js → chunk-JHC22BZH.js} +1 -1
  67. package/chunks/{chunk-26ISBUM7.js → chunk-K7GN4CMV.js} +6 -6
  68. package/chunks/{chunk-4GC5HJZO.js → chunk-L7LO3YRT.js} +1 -1
  69. package/chunks/{chunk-ZSVSRF4C.js → chunk-LT3J74BZ.js} +1 -1
  70. package/chunks/{chunk-2PY7R7GG.js → chunk-LY4XTBL4.js} +1 -1
  71. package/chunks/{chunk-7IERHQ63.js → chunk-LYFRGP42.js} +1 -1
  72. package/chunks/{chunk-FPZPCZFS.js → chunk-MDCA4I63.js} +1 -1
  73. package/chunks/{chunk-2LLPGSUK.js → chunk-MS2XCBPP.js} +1 -1
  74. package/chunks/{chunk-3Y6LSWEW.js → chunk-MXZXQUVP.js} +1 -1
  75. package/chunks/{chunk-IH2PFVWO.js → chunk-N4ZQC5HB.js} +1 -1
  76. package/chunks/{chunk-MTW3A3KT.js → chunk-N6EFYQ7M.js} +1 -1
  77. package/chunks/{chunk-AQWHCRKY.js → chunk-NHPKD7LY.js} +1 -1
  78. package/chunks/{chunk-ABJGFEES.js → chunk-NO7VTKRL.js} +1 -1
  79. package/chunks/{chunk-CNFA5UUM.js → chunk-NPAENNRO.js} +1 -1
  80. package/chunks/{chunk-IA4K4PGK.js → chunk-NYBYDW6R.js} +1 -1
  81. package/chunks/{chunk-FNB3DPQZ.js → chunk-O3TUZQP4.js} +1 -1
  82. package/chunks/{chunk-RVJJFDF3.js → chunk-OZFZBGZG.js} +1 -1
  83. package/chunks/{chunk-B6D3KTUK.js → chunk-P2MZZMCS.js} +1 -1
  84. package/chunks/{chunk-GSOBASYW.js → chunk-PMBI46K4.js} +1 -1
  85. package/chunks/{chunk-WI4UMN3Q.js → chunk-Q5RRVBTY.js} +1 -1
  86. package/chunks/{chunk-5UZT4SXG.js → chunk-QHYSRPQR.js} +1 -1
  87. package/chunks/{chunk-2NOMOJWE.js → chunk-QONPET6Y.js} +2 -2
  88. package/chunks/{chunk-MOPJNP5I.js → chunk-QSPXKBUX.js} +1 -1
  89. package/chunks/{chunk-C56YJIEI.js → chunk-QTKPC24L.js} +1 -1
  90. package/chunks/{chunk-6X73W4TL.js → chunk-QTVSPQZQ.js} +1 -1
  91. package/chunks/{chunk-ADZI3OFT.js → chunk-QVHDM6N7.js} +1 -1
  92. package/chunks/{chunk-NVSKOSFG.js → chunk-RT6J7PV4.js} +1 -1
  93. package/chunks/{chunk-7MTBINFX.js → chunk-RULGA7WE.js} +2 -2
  94. package/chunks/{chunk-AMTFJVDD.js → chunk-SAVYMUU3.js} +1 -1
  95. package/chunks/{chunk-Z5XENA4A.js → chunk-T3CQ72HC.js} +8 -7
  96. package/chunks/{chunk-OPYGNTZP.js → chunk-U5YOAOU3.js} +1 -1
  97. package/chunks/{chunk-HFV6CQWE.js → chunk-ULLW2AYD.js} +1 -1
  98. package/chunks/{chunk-KGJ47CI5.js → chunk-UM5KBBYP.js} +1 -1
  99. package/chunks/{chunk-F26LTWDZ.js → chunk-UVMLWDRU.js} +1 -1
  100. package/chunks/{chunk-BRPJ5EHA.js → chunk-VK7LOUOJ.js} +1 -1
  101. package/chunks/{chunk-4EQWJTJR.js → chunk-VUNHJ74J.js} +1 -1
  102. package/chunks/{chunk-WB34KMOT.js → chunk-W2CV36HT.js} +1 -1
  103. package/chunks/{chunk-ADTFKUH2.js → chunk-WCI33URB.js} +1 -1
  104. package/chunks/{chunk-4TYTJQWR.js → chunk-WEPC42YR.js} +1 -1
  105. package/chunks/{chunk-YGHM5CDT.js → chunk-WF7Q3ZSQ.js} +1 -1
  106. package/chunks/{chunk-UJYOILZR.js → chunk-WK666FGZ.js} +3 -3
  107. package/chunks/{chunk-3WQPUP5U.js → chunk-WMLYHZZX.js} +1 -1
  108. package/chunks/{chunk-OCBJCZC2.js → chunk-WSI4G7XC.js} +1 -1
  109. package/chunks/{chunk-Q6QS5JTK.js → chunk-WXK7Z45R.js} +1 -1
  110. package/chunks/{chunk-6NI33TVK.js → chunk-X2TY7VTY.js} +1 -1
  111. package/chunks/{chunk-BBOJUFMW.js → chunk-YWK3E4WJ.js} +1 -1
  112. package/chunks/{chunk-FNXO5KWB.js → chunk-YY4GWNTU.js} +2 -2
  113. package/chunks/{chunk-FLJLUMQF.js → chunk-ZFOEVHWG.js} +1 -1
  114. package/chunks/{codex-subagent-executor-EK3A2WBH.js → codex-subagent-executor-GPTKVP7H.js} +1 -1
  115. package/chunks/{config-utils-DLOK7OLM.js → config-utils-6B5FHBSF.js} +1 -1
  116. package/chunks/{contextCommand-AVCUCHQC.js → contextCommand-FGRDE3GA.js} +1 -1
  117. package/chunks/{core-runtime-QSS4ZTG6.js → core-runtime-OFEHSKDB.js} +1 -1
  118. package/chunks/{create-sub-session-PNF7QDKC.js → create-sub-session-D2KEWVHQ.js} +1 -1
  119. package/chunks/{cron-create-C6JOFIU4.js → cron-create-RFGGKTL7.js} +1 -1
  120. package/chunks/{daemon-git-worktree-guard-5XZAZ7D2.js → daemon-git-worktree-guard-AV752IOZ.js} +1 -1
  121. package/chunks/{daemon-status-provider-MRNELSNJ.js → daemon-status-provider-GHQBRDMC.js} +1 -1
  122. package/chunks/{daemon-trust-policy-26CMW3WY.js → daemon-trust-policy-24ENJNTQ.js} +1 -1
  123. package/chunks/{daemon-trust-policy-monitor-3DWO6NQY.js → daemon-trust-policy-monitor-NMSQAGWV.js} +1 -1
  124. package/chunks/{deferred-core-runtime-DEC3N46T.js → deferred-core-runtime-5BAMFFOI.js} +1 -1
  125. package/chunks/{edit-3HMQPCHN.js → edit-XCECLEH3.js} +1 -1
  126. package/chunks/{enterPlanMode-QHJF4JXZ.js → enterPlanMode-SEN2PMRM.js} +1 -1
  127. package/chunks/{environment-NGIBJWOT.js → environment-CCPQJYKS.js} +1 -1
  128. package/chunks/{errors-MSTGCVGJ.js → errors-Y6HHUTGK.js} +1 -1
  129. package/chunks/{execution-tool-VR4TGOI4.js → execution-tool-HADWGMIG.js} +1 -1
  130. package/chunks/{execution-worker-EJH7HIE2.js → execution-worker-GZS7WOQL.js} +1 -1
  131. package/chunks/{exitPlanMode-P25OHQJ6.js → exitPlanMode-76B5HDLT.js} +1 -1
  132. package/chunks/{fast-path-II433ZDP.js → fast-path-OEV7LQYV.js} +1 -1
  133. package/chunks/{glob-4Q6DCT3F.js → glob-NLWCQRMS.js} +1 -1
  134. package/chunks/{goal-tools-FFMAJW6V.js → goal-tools-43XV33BT.js} +1 -1
  135. package/chunks/{handleAutoUpdate-QNM26NZK.js → handleAutoUpdate-JDQWGSSP.js} +1 -1
  136. package/chunks/{i18n-L5URVOBB.js → i18n-JW6BVEGF.js} +1 -1
  137. package/chunks/{initializer-NQ2NECYP.js → initializer-UT6JLZ3O.js} +1 -1
  138. package/chunks/{installationInfo-BCTXASUM.js → installationInfo-LKWDV3S2.js} +1 -1
  139. package/chunks/{interactive-mod-session-PPTBI37E.js → interactive-mod-session-2KWKYVPC.js} +1 -1
  140. package/chunks/{list-7TE5TUZJ.js → list-BKINK3S2.js} +1 -1
  141. package/chunks/{llm-BWWKUBBZ.js → llm-3RWXAVM2.js} +4 -4
  142. package/chunks/{llm-content-generator-QOTGPBYC.js → llm-content-generator-MDRBSH73.js} +1 -1
  143. package/chunks/{loadedSettingsAdapter-THAGI5M2.js → loadedSettingsAdapter-WWJUKWUN.js} +1 -1
  144. package/chunks/{local-7BTAGV4J.js → local-TT4FLCTR.js} +1 -1
  145. package/chunks/{local-execution-environment-S3OR4KSC.js → local-execution-environment-OBA6VWYL.js} +1 -1
  146. package/chunks/{loggingContentGenerator-AXJ5E5RS.js → loggingContentGenerator-CK7IKYQH.js} +1 -1
  147. package/chunks/{loop-wakeup-AJTLMLRX.js → loop-wakeup-4MSRX3DY.js} +1 -1
  148. package/chunks/{manage-memory-JHTUVMDJ.js → manage-memory-PX5PZJKZ.js} +1 -1
  149. package/chunks/{managed-execution-engine-U6GNJ4U4.js → managed-execution-engine-WMAUR3ZK.js} +1 -1
  150. package/chunks/{managed-local-serve-P4ZXVRBU.js → managed-local-serve-X7REHGB4.js} +1 -1
  151. package/chunks/{managed-npm-update-UDUILNR5.js → managed-npm-update-6HUVAJH7.js} +1 -1
  152. package/chunks/{managed-runtime-attestation-worker-P34ZBNRG.js → managed-runtime-attestation-worker-F4AT53M5.js} +1 -1
  153. package/chunks/{managed-runtime-bootstrap-CLMYNPH5.js → managed-runtime-bootstrap-3BP5JRJX.js} +1 -1
  154. package/chunks/{managed-runtime-session-worker-7H7AZJBV.js → managed-runtime-session-worker-2PO7J5UK.js} +1 -1
  155. package/chunks/{managed-runtime-ssh-worker-5KEMC7FD.js → managed-runtime-ssh-worker-4N7EMRSV.js} +1 -1
  156. package/chunks/{managed-session-authority-CFUZ45HT.js → managed-session-authority-MYOYTUM2.js} +1 -1
  157. package/chunks/{mcp-YMG4RVMC.js → mcp-5OTEMZ7P.js} +1 -1
  158. package/chunks/{memory-7STURUXK.js → memory-TNW7RSAV.js} +1 -1
  159. package/chunks/mn-JMS6SWTO.js +8 -0
  160. package/chunks/{model-call-collection-WBWTO3EG.js → model-call-collection-KNTWFZQS.js} +1 -1
  161. package/chunks/{model-configuration-6KCZZSZD.js → model-configuration-U5C5P5UQ.js} +1 -1
  162. package/chunks/{modelConfigUtils-Z2EKFSPN.js → modelConfigUtils-R4KFI2WK.js} +1 -1
  163. package/chunks/{monitor-U5E33JO6.js → monitor-RD2PFK42.js} +1 -1
  164. package/chunks/{nonInteractiveCli-BVCL5I5R.js → nonInteractiveCli-QQ72HZSH.js} +1 -1
  165. package/chunks/{nonInteractiveToolExecutor-B4EUOMYF.js → nonInteractiveToolExecutor-QPQYR6IS.js} +1 -1
  166. package/chunks/{notebook-edit-MXKD5J2C.js → notebook-edit-YLRN3UZT.js} +1 -1
  167. package/chunks/{omni-I5YECZBW.js → omni-CUJ52EW5.js} +1 -1
  168. package/chunks/{openaiContentGenerator-Q5SINFJJ.js → openaiContentGenerator-6B5MAU54.js} +1 -1
  169. package/chunks/{openaiResponsesContentGenerator-R3XCZLZY.js → openaiResponsesContentGenerator-I245I3R7.js} +1 -1
  170. package/chunks/{pidfile-UOGUNUTK.js → pidfile-P2HIGAUA.js} +1 -1
  171. package/chunks/{processUtils-QGQGZHBA.js → processUtils-JSKN5UGS.js} +1 -1
  172. package/chunks/{prompt-terminal-ledger-L57JMVSR.js → prompt-terminal-ledger-F5TSXVGU.js} +1 -1
  173. package/chunks/{qwenContentGenerator-UKZ237LC.js → qwenContentGenerator-IEDZONWG.js} +1 -1
  174. package/chunks/{reactive-degrade-3OM3HWVA.js → reactive-degrade-FYZBJCF6.js} +1 -1
  175. package/chunks/{read-file-63ZLWMOW.js → read-file-VNZNSD6X.js} +1 -1
  176. package/chunks/{resumeHistoryUtils-R5YQS4YQ.js → resumeHistoryUtils-IDPE6N2N.js} +1 -1
  177. package/chunks/{review-AT6OWVDO.js → review-TBJRZWTD.js} +1 -1
  178. package/chunks/{ripGrep-7KBZGTPV.js → ripGrep-4W5B5FOE.js} +1 -1
  179. package/chunks/{run-qwen-serve-CLBG7W6F.js → run-qwen-serve-44X262G5.js} +1 -1
  180. package/chunks/{runtime-R3QIGB7U.js → runtime-6H6LKD73.js} +1 -1
  181. package/chunks/{sandboxConfig-PM3ZRQYV.js → sandboxConfig-SQXDRGVN.js} +1 -1
  182. package/chunks/{scheduled-tasks-PUMNN5XV.js → scheduled-tasks-62IZKHJG.js} +1 -1
  183. package/chunks/{scheduler-KTPM226B.js → scheduler-QUCXJYRL.js} +1 -1
  184. package/chunks/{search-memory-7I5MGDNV.js → search-memory-TC2Z34QN.js} +1 -1
  185. package/chunks/{send-message-J526AEBI.js → send-message-TFZX7KI7.js} +1 -1
  186. package/chunks/{serve-KLTMPK4W.js → serve-WSICDFGG.js} +1 -1
  187. package/chunks/{server-VLRNY6KG.js → server-GYYVTNGY.js} +3 -3
  188. package/chunks/{session-2EB57NXY.js → session-KF3O23ZJ.js} +1 -1
  189. package/chunks/{session-attachments-root-I7TESMWL.js → session-attachments-root-7HFUSONH.js} +1 -1
  190. package/chunks/{session-execution-engine-selector-5FAMSPSO.js → session-execution-engine-selector-NVILT6BR.js} +1 -1
  191. package/chunks/{session-pr-refresh-JCPVQPNJ.js → session-pr-refresh-3KDFTDEV.js} +1 -1
  192. package/chunks/{sessionService-YRW2IFPR.js → sessionService-XRTFLPDW.js} +1 -1
  193. package/chunks/{settings-KO2Q47JP.js → settings-QPPK6WXE.js} +1 -1
  194. package/chunks/{shell-OLZVNTQZ.js → shell-WYQDZWL7.js} +1 -1
  195. package/chunks/{skill-XW2AQS7M.js → skill-FYPT6AU7.js} +1 -1
  196. package/chunks/{skill-settings-TKAVQ4XP.js → skill-settings-OGFI5KZF.js} +1 -1
  197. package/chunks/{spawnChannel-MBGCTK2J.js → spawnChannel-ANOOVPG7.js} +1 -1
  198. package/chunks/{standalone-update-A3YLLIAN.js → standalone-update-45WTDY4E.js} +1 -1
  199. package/chunks/{start-opentui-ui-G5ROAR4V.js → start-opentui-ui-TL5WK33V.js} +1 -1
  200. package/chunks/{startInteractiveUI-PZQR4U53.js → startInteractiveUI-N2IREVBM.js} +1 -1
  201. package/chunks/{team-create-S5ZY2UMF.js → team-create-R77PRZ5U.js} +1 -1
  202. package/chunks/{team-plan-approval-KX6RXEST.js → team-plan-approval-6DCRKB5I.js} +1 -1
  203. package/chunks/{terminal-image-renderer-SCJREXE6.js → terminal-image-renderer-TB7EX2WW.js} +1 -1
  204. package/chunks/{theme-manager-DZSM4EBR.js → theme-manager-RQDXJGVR.js} +1 -1
  205. package/chunks/{tool-call-UK56SWCT.js → tool-call-LVB4NCDT.js} +1 -1
  206. package/chunks/{tool-result-media-JLLSLGFL.js → tool-result-media-LRBB2KS6.js} +1 -1
  207. package/chunks/{tool-search-OWPFLVV5.js → tool-search-OG73QAQZ.js} +1 -1
  208. package/chunks/{total-session-admission-NQU4ACKH.js → total-session-admission-A4CUF6AD.js} +1 -1
  209. package/chunks/{trustedFolders-N7GXFYSF.js → trustedFolders-LSGOYTU2.js} +1 -1
  210. package/chunks/{update-relaunch-5SPXXHM2.js → update-relaunch-OGC6BZO7.js} +1 -1
  211. package/chunks/{updateCheck-VXUIX2XG.js → updateCheck-7J3GXTER.js} +1 -1
  212. package/chunks/{upload-config-OWLL4SRQ.js → upload-config-ML5XEJIF.js} +1 -1
  213. package/chunks/{useAutoAcceptIndicator-OUYRR56F.js → useAutoAcceptIndicator-6DH6GQ2X.js} +1 -1
  214. package/chunks/{validateNonInterActiveAuth-PSVJO5HK.js → validateNonInterActiveAuth-KJDAGZCM.js} +1 -1
  215. package/chunks/{version-C26S7UAW.js → version-7JN2YXL2.js} +1 -1
  216. package/chunks/{web-fetch-AYOYV7R4.js → web-fetch-42ZR4FEZ.js} +1 -1
  217. package/chunks/{web-search-DAREKD3Z.js → web-search-74NLPMZJ.js} +1 -1
  218. package/chunks/{workflow-WBGPKVO6.js → workflow-WNPHX42I.js} +1 -1
  219. package/chunks/{workflow-ancestor-trust-GEEB53TB.js → workflow-ancestor-trust-HGF6G7LQ.js} +1 -1
  220. package/chunks/{workspace-agents-IMAQME4W.js → workspace-agents-3YFBFAK3.js} +1 -1
  221. package/chunks/{workspace-providers-status-VALHVEU2.js → workspace-providers-status-EPJI6KRV.js} +1 -1
  222. package/chunks/{workspace-recovery-worker-AIAVRDGU.js → workspace-recovery-worker-T3FK5YOD.js} +1 -1
  223. package/chunks/{workspace-registration-store-FXEGZG3L.js → workspace-registration-store-VEXYBDMA.js} +1 -1
  224. package/chunks/{workspace-registry-GYFFHWCD.js → workspace-registry-NRZYTP2X.js} +1 -1
  225. package/chunks/{workspace-runtime-coordinator-VZ462TLU.js → workspace-runtime-coordinator-USNSTP2V.js} +1 -1
  226. package/chunks/{workspace-service-5DIZM4IZ.js → workspace-service-USATWO56.js} +1 -1
  227. package/chunks/{workspace-skills-status-DOOBVL5N.js → workspace-skills-status-M5JTSFDL.js} +1 -1
  228. package/chunks/{workspace-trust-reconciler-LOICVUVW.js → workspace-trust-reconciler-ZUZ2O5WC.js} +1 -1
  229. package/chunks/{write-file-EJNMAHQD.js → write-file-UMJVKE4S.js} +1 -1
  230. package/chunks/{zoom-image-S3OARMYP.js → zoom-image-76XYHQ3Z.js} +1 -1
  231. package/cli.js +2 -2
  232. package/execution-worker.js +1 -1
  233. package/export-transcript-document.js +1 -1
  234. package/gerege.mjs +64 -15
  235. package/locales/mn.js +2702 -3774
  236. package/package.json +3 -3
  237. package/chunks/mn-YH2OTBWJ.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{isBidiControlChar,stripDisplayControlChars,stripTerminalControlSequences,truncateNotificationLabel}from"./chunk-R2EHHA2C.js";import{AjvJsonSchemaValidator,CallToolResultSchema,CompleteResultSchema,CreateMessageRequestSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,CreateTaskResultSchema,ElicitRequestSchema,ElicitResultSchema,EmptyResultSchema,ErrorCode,GetPromptResultSchema,InitializeResultSchema,JSONRPCMessageSchema,LATEST_PROTOCOL_VERSION,ListChangedOptionsBaseSchema,ListPromptsResultSchema,ListResourceTemplatesResultSchema,ListResourcesResultSchema,ListToolsResultSchema,McpError,PromptListChangedNotificationSchema,Protocol,ReadBuffer,ReadResourceResultSchema,ResourceListChangedNotificationSchema,SUPPORTED_PROTOCOL_VERSIONS,ToolListChangedNotificationSchema,assertClientRequestTaskCapability,assertToolsCallTaskCapability,getLiteralValue,getObjectShape,isInitializedNotification,isJSONRPCRequest,isJSONRPCResultResponse,mergeCapabilities,safeParse,serializeMessage}from"./chunk-YK7NDQKM.js";import{SshWorkspaceClient,SshWorkspaceError}from"./chunk-ZLZF2ZDD.js";import{MANAGED_SESSION_COMMIT_SUBTYPE,MANAGED_SESSION_DOMAINS,MANAGED_SESSION_ENVELOPE_DOMAINS,MANAGED_SESSION_EVENT_SUBTYPE,MANAGED_SESSION_FORMAT_VERSION,MANAGED_SESSION_HEADER_SUBTYPE,MANAGED_SESSION_LIMITS,MANAGED_SESSION_MINIMUM_READER,MANAGED_TOOL_RESULT_KINDS,ManagedSessionAppendUnsettledError,ManagedSessionRecordError,ManagedSessionWritesStoppedError,assertManagedBranchRecord,assertManagedSessionChannelAdapterEnabled,assertManagedSessionChildContinuationEnabled,assertManagedSessionChildRunKindEnabled,assertManagedSessionDigest,assertManagedSessionDomainEnabled,assertManagedSessionDurableRef,assertManagedSessionEventActor,assertManagedSessionKey,assertManagedSessionScheduleSessionModeEnabled,assertManagedSessionSequence,assertManagedSessionStableId,assertManagedSessionTime,assertManagedSessionTransaction,boundedString,collectPendingBranchToolCalls,isChildNotificationSource,managedSessionDomainCarriesRecord,managedSessionEventRefs,managedSessionEventsDigest,managedSessionKeysEqual,managedSessionReaderFacingBody,parseBranchCheckpointPayload,parseManagedSessionCommitMarker,parseManagedSessionEvent,parseManagedSessionHeader,parseManagedSessionRecordJson,parseToolResultManifestBytes,resolveBranchPoints,resolveCompletedTurnBranchCandidateFromRecords,safeErrorValue,updatePendingBranchToolCalls,validateManagedReaderFacingRecord}from"./chunk-OMSVOFTC.js";import{require_content_type}from"./chunk-PHIPLV2I.js";import{require_main,resolveEnvVarsInObject}from"./chunk-ZOTKZI2P.js";import{EXTRACT_CADENCE_MAX_PENDING_ENTRIES,EXTRACT_TAIL_ENTRIES,getExtractNoopSkipTurns}from"./chunk-A6G5TAIF.js";import{SessionExecutionEngineAccumulator,SessionExecutionEngineError,assertSessionExecutionEngine}from"./chunk-YVBHCSZD.js";import{ExecutionCleanupError,MANAGED_RUNTIME_TOOL_NAMES,ManagedRuntimeOutcomeUnknownError}from"./chunk-FIXDX63I.js";import{isShellResultDisplay,mapShellResultText,shellResultText}from"./chunk-T7CHK6C2.js";import{NEVER,ZodIssueCode,any,array,boolean,coerce_exports,literal,looseObject,number,object,string,url}from"./chunk-PT7NZBDY.js";import{external_exports}from"./chunk-TWP72VRH.js";import{claimTask,listTasks,onTasksUpdated,unassignTeammateTasks}from"./chunk-UYEWRLGD.js";import{humanReadableCron}from"./chunk-QVPT37XZ.js";import{backgroundFixAt,backgroundFixHolding,buildPermissionCheckContext,evaluatePermissionRules,forgetAutofixPrSession,hasUnattendedFixGrant,injectPermissionRulesIfMissing,isUnattendedFixConfig,markUnattendedFixConfig,openBackgroundFix,persistPermissionOutcome,settleBackgroundFix,unattendedFixGranted}from"./chunk-YVD4O5ZB.js";import{CRON_TASKS_DISPLAY_PATH,addCronTask,annotateCronRunSession,appendCronRun,cronTaskSessionDeletionId,generateCronTaskId,getCronFilePath,readCronTasks,removeCronTasks,taskHasLegacyCondition,taskHasLegacyRunMode,updateCronTasks,withTaskGate}from"./chunk-T6W33SET.js";import{consumeUnread,forwardApproval,getInboxPath,readInbox,sendStructuredMessage,wrapConfirmWithBadge,writeMessage}from"./chunk-WK2IBT6D.js";import{canUseRipgrep}from"./chunk-QZV4PFQK.js";import{AGENT_WORKTREE_SLUG_PATTERN,GitWorktreeService,MAX_DIFF_SIZE_BYTES,clearRuntimeStatus,generateAgentWorktreeSlug,gitEnv,gitRemoteEnv,loadSimpleGit,readRuntimeStatus,worktreeBranchForSlug,worktreeHasWork,writeRuntimeStatus,writeWorktreeSessionMarker}from"./chunk-ILECDNJX.js";import{hasVerifiableInode,isUnverifiableIdentityError,openNoFollow,openSyncNoFollow}from"./chunk-QXQGUM3Y.js";import{SESSION_ARTIFACT_PERSISTENCE_VERSION,SessionArtifactSnapshotAccumulator,deleteArtifactSnapshot,getWebPreviewSnapshotId,isSessionArtifactRecord,rebuildSessionArtifactSnapshot,remapSessionArtifactPayloadForFork,retainArtifactSnapshot,selectActiveSideArtifactRecordUuids}from"./chunk-UQ7IROJH.js";import{aggregateTranscriptRecordFragments,isInternalCodeModeToolResult,isTranscriptConversationRecord,isUserPromptSubmitContextPartText,prepareTranscriptRecords,projectUserTranscriptForDisplay,selectTranscriptLeaf,stripGeneratedAttachmentTokens,validateTranscriptRecord,walkTranscriptUuidChain,wrapUserPromptSubmitContext}from"./chunk-SZCBUCNH.js";import{buildModelIdContext,resolveModelId}from"./chunk-BEKROCWN.js";import{isToolHiddenBehindToolSearch,loadSkillsFromDir,parsePriorityField,readBundledReference,resolveBundledReferenceSurface,toolSearchBridgeSentence,validateConfig,validateSymlinkTarget}from"./chunk-5SUFJTQQ.js";import{SHARED_RECORD_SLOT,defangEnvelopeTags,deriveSessionName,flattenPeerLabel,patchSessionRecord,unregisterSession}from"./chunk-BYU42MLK.js";import{LEADER_NAME,MAX_TEAMMATES,assignTeammateColor,classifyShutdownResponse,findMemberByName,formatAgentId,generateUniqueTeammateName,sanitizeName,writeTeamFile}from"./chunk-JWQXU3SR.js";import{readLocalBootId,readPidNamespaceId}from"./chunk-5LZ2DPLH.js";import{SKILL_FILE_NAME,assertRealProjectSkillPath,getArchivedSkillsRoot,getPendingSkillsRoot,getProjectSkillsRoot,isProjectSkillPath,maybeRunAutoSkillCurator}from"./chunk-XQJOZDV7.js";import{SKILL_NAME_PATTERN,SkillError,SkillErrorCode,authoredSkillName,parseAllowedToolsField,parseModelField,parsePathsField,parseUserInvocableField,qualifySkillName,skillRestrictionNames,validateSkillName}from"./chunk-CV2UAEZA.js";import{AUTO_MEMORY_SCHEMA_VERSION,AUTO_MEMORY_SCOPES,AUTO_MEMORY_TREE_CATEGORIES,AUTO_MEMORY_TYPES,MAX_USAGE_SCENARIO_CHARS,createAutoMemoryTreeSnapshot,isImportedMemoryDocument,listTrustedMemoryMarkdownFiles,normalizeAutoMemoryKeyword,parseAutoMemoryTopicDocument,renderAutoMemoryFocusedSubtree,rereadAutoMemoryDocument,resolveTrustedMemoryFile,resolveTrustedMemoryRoot,sanitizeAutoMemoryPromptField,scanAllAutoMemoryTopicDocuments,scanAllUserAutoMemoryTopicDocuments,scanAutoMemoryIndexDocumentsFromRoot,scanAutoMemorySnapshot,scanAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments,toAutoMemoryRef,validateStructuredAutoMemoryDocument}from"./chunk-FUBDS3AV.js";import{AgentOutputMessageCapture,DEFAULT_OTLP_ENDPOINT,DEFAULT_TELEMETRY_TARGET,GOAL_DEFAULT_TOKEN_BUDGET,GOAL_INFEASIBLE_NEXT_STEP,GOAL_NO_PROGRESS_TURN_LIMIT,GOAL_PAUSE_REASON_NO_PROGRESS,GOAL_PAUSE_REASON_SESSION_TOKEN_LIMIT,GOAL_PAUSE_REASON_STOP_HOOK_CAP,GOAL_PAUSE_REASON_USER_INTERRUPT,GOAL_PROPOSAL_REASON_MAX_CHARACTERS,GOAL_STATE_VERSION,GoalConflictError,GoalInvalidTransitionError,PAUSED_GOAL_SYSTEM_REMINDER,addAgentInputMessageAttributes,addToolArgumentsAttributes,addToolCallResultAttributes,addUserPromptAttributes,elapsedActiveTime,goalActiveTimeBudgetReason,goalPauseReasonForFailure,goalPauseReasonForVerifierFailure,goalRequiresExactPermit,goalStateEventFromSnapshot,goalTokenBudgetReason,goalTurnBudgetReason,isGoalActiveTimeBudgetSpent,isGoalTokenBudgetSpent,isGoalTurnBudgetSpent,isRepeatedBlockerProposal,parseGoalStateRecordPayloadV2,reduceGoalControl,reduceGoalSpend,reduceGoalTurnFinished,validateGoalProposalReason}from"./chunk-HW6AWS7W.js";import{parse,require_dist,sanitizeValue,stringify}from"./chunk-KLC3OD2M.js";import{normalizeImageGenerationBaseUrl}from"./chunk-Q5IZXKUJ.js";import{restoreSessionSources}from"./chunk-G5PYYZMM.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{glob,globSync}from"./chunk-OBOU4ZZM.js";import{isTruthy}from"./chunk-D7XCQWP2.js";import{isOmniDeliveryActive}from"./chunk-OBV7RNHV.js";import{ToolMode,buildExecDeclaration,getToolExposure,isCodeModeToolCallAllowed,isDeferredToolBridgeAvailable,isDirectToolBridgeAvailable,planCodeModeBindings}from"./chunk-7CQMWEMY.js";import{EXCLUDED_TOOLS_FOR_SUBAGENTS,READ_ONLY_INSPECTION_TOOLS,buildSubagentPlanToolBlockedResult,getExcludedToolUnavailableMessage,getLeaderOnlyToolUnavailableMessage,getPlanRequiredTeammatePreApprovalMessage,getSubagentPlanToolUnavailableMessage,isLeaderOnlyToolUnavailableInSubagent,isPlanLifecycleToolUnavailableInSubagent,isPlanRequiredTeammateAwaitingApproval,isPlanRequiredTeammateContext,isPlanRequiredTeammatePreApprovalAllowedTool,isSubagentLikeExecutionContext,isToolExcludedForCurrentContext,matchesAgentToolBlocklist,shouldUsePlanOnlyReminderInSubagentContext,toolConfigAllowsSkill}from"./chunk-GOZYWU4B.js";import{SHELL_TOOL_NAMES,getToolNameAliases,hasAmbiguousMcpGrant,matchesRule,matchesToolPattern,parseRule,parseRules,require_picomatch,resolveToolName,splitCompoundCommand,splitCompoundCommandSegments,toolMatchesRuleToolName,warnDroppedPermissionRule}from"./chunk-OUC3WICA.js";import{APPROVAL_MODES,ApprovalMode}from"./chunk-JZK2WGXA.js";import{MediaResourceRegistry,evaluateMediaPolicyToolCall,isMediaPolicyToolHiddenFromModel,resolveMediaPolicyModelAccess}from"./chunk-S2ZKZXHX.js";import{BaseTokenStorage,KeychainTokenStorage}from"./chunk-4GP3PH7Z.js";import{AskUserQuestionTool,TrustedUserAnswers}from"./chunk-4QQKOW5M.js";import{assembleSystemPrompt,getArenaSystemReminder,getCompressionPrompt,getCoreSystemPrompt,getCustomSystemPrompt,getManualPlanExitSystemReminder,getOutputStyleTurnReminder,getPlanModeSystemReminder,resolveEffectiveOutputStyle,resolveInteractionMode,resolveMainSessionOutputStyle}from"./chunk-OV3EBH6J.js";import{NO_EXEC_CONFIG,findGitRoot,getCachedGitBranch,getGitBranch,getRecentGitStatus,isGitRepository}from"./chunk-EBMCWXGZ.js";import{executeSandbox}from"./chunk-LSASUDF2.js";import{admitShellSandbox,assertShellSandboxCwd,probeShellSandbox}from"./chunk-MOKVM4PT.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{ShellExecutionService,getShellAbortReasonKind,getShellContextEnvVars,getShellPagerEnv,isSignalTermination,normalizePathEnvForWindows}from"./chunk-NMY3PYNO.js";import{stripAnsi}from"./chunk-YGLM5XPP.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{promptIdContext,todoWorkChainContext}from"./chunk-MWGB5RCF.js";import{SHELL_SELF_KILL_REJECTION,backgroundsAnyPart,buildOutsideWorkspaceWarning,buildShellExecWarnings,classifyAwkCommandSafety,classifySedCommandSafety,detectSelfKillCommand,escapeShellArg,getCommandRoot,getCommandRoots,getShellConfiguration,hasShellPatternExpansion,hasShellSubstitution,hasUnsafeMonitorBackgroundOperator,isShellCommandReadOnly,normalizeMonitorCommand,runsOnlyComments,shouldDefaultToNodePty,splitCommands,stripShellWrapper}from"./chunk-SCD5TUBG.js";import{escapeJsonTagCharacters,formatMemoryUsage}from"./chunk-NTRFETZB.js";import{require_shell_quote}from"./chunk-TL3SF2GA.js";import{isInternalSecretEnvVar,sanitizeChildEnv}from"./chunk-LMJPU2JM.js";import{carryIncompleteArgumentsMarker,toolCallArgumentsWereIncomplete}from"./chunk-4JNHUZ7M.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX}from"./chunk-SW54YEPK.js";import{DashScopeOpenAICompatibleProvider,selectDashScopeThinkingKnob}from"./chunk-ZCRL73DT.js";import{InvalidStreamError,getToolCallPreparations,isFlushedToolCallPark,isRetryableStatuslessUpstreamError,isRetryableStreamTransportError,setToolCallPreparations}from"./chunk-A6LT3FIJ.js";import{assertHookExecutionOwner,captureHookExecutionOwner,childLaunchDepth,getCurrentAgentChat,getCurrentAgentConfiguredToolAllowlist,getCurrentAgentDepth,getCurrentAgentDisallowedTools,getCurrentAgentId,getHookExecutionOwner,getRuntimeContentGenerator,isTopLevelSession,resolveHookExecutionOwner,runOutsideAgentContext,runWithAgentChat,runWithAgentConfiguredToolAllowlist,runWithAgentContext,runWithAgentDisallowedTools,runWithHookExecutionOwner,runWithRuntimeContentGenerator,spawnBlockReason}from"./chunk-YZFNBUKG.js";import{getTeammateContext,isTeammate,runOutsideTeammateIdentity,runWithTeammateIdentity}from"./chunk-AGEDDL7Z.js";import{getResponsesMessage,sameResponsesMessage}from"./chunk-2NJJHZ52.js";import{supportsOpenAIPrefixCaching}from"./chunk-BN4FIQ77.js";import{InMemoryImagePayloadStore,REATTACH_BOUNDARY_METADATA,buildReattachParts,countAllInlineImages,hasImagePayloadReferences,replaceImagePayloadsInPlace}from"./chunk-X64RXJQQ.js";import{getThoughtSummary,getThoughtText}from"./chunk-HETUGUHE.js";import{ModelsConfig,captureReasoningSnapshot,getBuiltinDeepSeekReasoning,getRequestModel,isImageGenerationCapable,resolveProviderProtocol,resolveReasoningCapabilities,resolveReasoningForModel,stripRuntimeSnapshotPrefix,validateReasoningCapabilities}from"./chunk-ET2Z7ZGF.js";import{openBrowserSecurely,shouldAttemptBrowserLaunch}from"./chunk-3YWXKSOI.js";import{resolveNetworkTarget}from"./chunk-5CWTKFI4.js";import{beginRetryWait,bindRetryWaitObserver,delay,isUnattendedMode,retryWithBackoff,runWithRetryWaitObserver}from"./chunk-C4MVD5OI.js";import{QUOTA_EXHAUSTED_PREFIX,classifyRetryError,formatQuotaExhaustedMessage,getHeaderValue,getRateLimitErrorDetails,getRateLimitRetryDelayMs,isApiError,isFallbackEligible,isQuotaExhaustedError,isRateLimitError,isRetryableUpstreamError,isStructuredError,toRetryDiagnostics}from"./chunk-Z2W7S4O4.js";import{combineAbortSignals,createAbortController,createChildAbortController}from"./chunk-476F6QIM.js";import{ResponsesHttpError}from"./chunk-4R67LXKL.js";import{addDaemonRequestAttribute}from"./chunk-FQRF6B65.js";import{ApiRetryEvent,BUNDLED_GENERATED_UI_SERVER,BUNDLED_GENERATED_UI_TOOL,COMBINED_PASS_TOLERANCE_FACTOR,ContentRetryEvent,ContentRetryFailureEvent,DiscoveredMCPTool,ExtensionDisableEvent,ExtensionEnableEvent,ExtensionInstallEvent,ExtensionUninstallEvent,ExtensionUpdateEvent,FULL_OUTPUT_DIGEST_LABEL,HookCallEvent,LoopDetectedEvent,LoopDetectionDisabledEvent,LoopProtectionEvent,MemoryDreamEvent,MemoryExtractEvent,MemoryMigrationEvent,MemoryRecallDeliveryEvent,MemoryRecallEvent,MemoryRecallModeTransitionEvent,NextSpeakerCheckEvent,PREVIEW_SIZE_CHARS,RipgrepFallbackEvent,StartSessionEvent,SubagentExecutionEvent,TOOL_OUTPUT_TRUNCATED_PREFIX,ToolCallEvent,ToolResultSizeEvent,UiTelemetryService,WorkflowKeywordEvent,attachToolOutputProvenance,collectText,effectiveAppResourceMaxBytes,effectiveAppResourceTimeoutMs,formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,getMCPServerStatus,getQualifiedVisionModelId,getToolOutputProvenance,isAlreadyTruncated,isChatRecordingSuppressed,isFullTurnVisionCapable,isImagePart,isSkipSelectorOnUniqueStrongHitEnabled,logApiRetry,logArenaAgentCompleted,logArenaSessionEnded,logArenaSessionStarted,logChatCompression,logContentRetry,logContentRetryFailure,logExtensionDisable,logExtensionEnable,logExtensionInstallEvent,logExtensionUninstall,logExtensionUpdateEvent,logGoalState,logHookCall,logLoopDetected,logLoopDetectionDisabled,logLoopProtection,logMemoryDream,logMemoryExtract,logMemoryMigration,logMemoryRecall,logMemoryRecallDelivery,logMemoryRecallModeTransition,logNextSpeakerCheck,logRipgrepFallback,logSessionEnd,logStartSession,logSubagentExecution,logToolCall,logToolResultSize,logWorkflowKeyword,makeArenaAgentCompletedEvent,makeArenaSessionEndedEvent,makeArenaSessionStartedEvent,makeChatCompressionEvent,measureToolOutput,memoryAge,memoryFreshnessText,normalizeParts,normalizeToolResultCallId,persistAndTruncateToolResult,recordMCPServerLastError,removeMCPServerStatus,runVisionBridge,runWithChatRecordingSuppressed,selectVisionBridgeModel,shouldRunVisionBridge,subagentIdentityContext,subagentNameContext,truncateLlmContent,truncateToolOutput,uiTelemetryService,updateMCPServerStatus,updateToolOutputBudget}from"./chunk-ZWPSBU7K.js";import{_recoverObjectsFromLine,exists,parseLineTolerant,parseLineTolerantWithIntegrity,read,readLines,readLinesWithIntegrity,writeLine,writeLineSync}from"./chunk-UQFTXKEB.js";import{Mutex}from"./chunk-HDGTWJ24.js";import{extractCodeModeImageContent,getCurrentToolCallSource,runWithToolCallRuntime,runWithToolCallSource,runWithoutToolCallRuntime}from"./chunk-W5NWIGKO.js";import{AUTO_MEMORY_INDEX_FILENAME,AUTO_MEMORY_PINNED_DIRNAME,TEAM_AUTO_MEMORY_DIRNAME,getAutoMemoryConsolidationLockPath,getAutoMemoryExtractCursorPath,getAutoMemoryIndexPath,getAutoMemoryMetadataPath,getAutoMemoryRoot,getAutoMemoryTrustedAnchor,getImportedProjectMemoryRoot,getMemoryBaseDir,getMemoryRootTrustedAnchor,getProjectAutoMemoryRoots,getTeamAutoMemoryIndexPath,getTeamAutoMemoryRoot,getUserAutoMemoryConsolidationLockPath,getUserAutoMemoryIndexPath,getUserAutoMemoryMetadataPath,getUserAutoMemoryRoot,isAnyAutoMemPath,isAutoMemPath,isManagedMemoryPath,isTeamAutoMemPath,isUserAutoMemPath}from"./chunk-KVA6DHHF.js";import{runSideQuery}from"./chunk-K7JCVESI.js";import{FileExclusions,FileReadOpenError,LOCAL_CONTEXT_FILENAME,digestFileReadSource,getAllMemoryFilenames,isUtf8CompatibleEncoding,loadIconvLite,readFileHandleBytes,readFileWithLineAndLimit,readTextCursorWindowFromHandle,readTextRangeFromHandle,setMemoryFilename}from"./chunk-Y6HHV4LC.js";import{normalizeMcpToolName,sanitizeToolNameForProvider}from"./chunk-7DOOXUDG.js";import{getSystemEncoding}from"./chunk-7U7CWMP7.js";import{getInvocationContext,runWithInvocationContext}from"./chunk-EFTJIDS3.js";import{DEFAULT_IMAGE_TOKEN_ESTIMATE,TOKEN_TO_CHAR_RATIO,clampInlineMediaPart,estimateContentChars,getFunctionResponseParts,resolveCompactionTuning,resolveSlimmingConfig,sanitizeMimeForPlaceholder,slimCompactionInput}from"./chunk-Q6UAOTP3.js";import{createContentGenerator,resetPreloadedContentGenerator,resolveContentGeneratorConfigWithSources}from"./chunk-NGOIJH7K.js";import{AUTH_ENV_MAPPINGS,CATALOG_MODALITIES,DEFAULT_MODELS,DEFAULT_QWEN_EMBEDDING_MODEL,DEFAULT_TOKEN_LIMIT,MIN_AUTO_DETECTED_CONTEXT_WINDOW,MODELS_DEV_URL,MODEL_CATALOG_PROJECTION_VERSION,MODEL_CATALOG_URL_ENV,MODEL_GENERATION_CONFIG_FIELDS,OUTPUT_TOKEN_CEILING,QWEN_OAUTH_ALLOWED_MODELS,REASONING_EFFORT_TIERS,clampOutputTokensToWindow,clampReasoningEffort,defaultModalities,defaultOutputCeiling,getGptReasoningCapabilities,getModelCatalogCachePath,hasExplicitOutputLimit,isModelCatalogDisabled,isModelCatalogKey,isTieredEffortWireModel,knownTokenLimit,normalize,normalizeReasoningEffort,parseModelCatalog,parsePositiveIntegerEnvValue,reasoningEffortsForCapability,setGeneratorReasoningEffort,tokenLimit,versionSpellingAlias}from"./chunk-GOR7FFVE.js";import{DEFAULT_QWEN_MODEL}from"./chunk-4ZBZL23U.js";import{atomicWriteFile,atomicWriteFileSync,atomicWriteJSON,renameWithRetry}from"./chunk-BMHYEQTI.js";import{getOrCreateMcpDispatcher,loadUndici,preloadRuntimeFetchModule,redactProxyError,setResolvedProxyUrlForRuntimeFetch}from"./chunk-ZZZAYAJW.js";import{safeJsonStringify}from"./chunk-XMANRGPK.js";import{DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH,SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT,TOOL_FAILURE_KIND_ATTRIBUTE,TOOL_FAILURE_KIND_BACKGROUND_AGENT_DENIED,TOOL_FAILURE_KIND_CANCELLED,TOOL_FAILURE_KIND_INVOCATION_GUARD_DENIED,TOOL_FAILURE_KIND_NON_INTERACTIVE_DENIED,TOOL_FAILURE_KIND_PERMISSION_DENIED,TOOL_FAILURE_KIND_PERMISSION_HOOK_DENIED,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_FAILURE_KIND_POST_HOOK_STOPPED,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_FAILURE_KIND_TIMEOUT,TOOL_FAILURE_KIND_TOOL_ERROR,TOOL_FAILURE_KIND_TOOL_EXCEPTION,endHookSpan,endInteractionSpan,endSubagentSpan,endToolBlockedOnUserSpan,endToolExecutionSpan,endToolSpan,getActiveInteractionSpan,initializeTelemetry,isPerformanceMonitoringActive,isTelemetrySdkInitialized,isValidSensitiveSpanAttributeMaxLength,recordCpuUsage,recordInteractionActivity,recordMemoryUsage,redactUrlCredentials,refreshSessionContext,runInSubagentSpanContext,runInToolSpanContext,safeSetStatus,shutdownTelemetry,startHookSpan,startInteractionSpan,startSubagentSpan,startToolBlockedOnUserSpan,startToolExecutionSpan,startToolSpan,truncateSpanError}from"./chunk-3XVPZY7X.js";import{STRUCTURED_OUTPUT_REDACTED_ARGS}from"./chunk-URNNJMIC.js";import{require_src}from"./chunk-GU22I6TY.js";import{normalizeContent,stripAnsiAndControl,stripHtmlComments}from"./chunk-DBRQGEEI.js";import{AUTO_MEMORY_SNAPSHOT_METADATA,BUBBLE_APPROVAL_MODE,FORK_AGENT,FORK_DEFAULT_MAX_TURNS,FORK_PLACEHOLDER_RESULT,FORK_SUBAGENT_TYPE,SubagentError,SubagentErrorCode,buildAvailableSkillsReminder,buildChangedAgentsReminder,buildChangedMcpToolsReminder,buildChangedSkillsReminder,buildChildMessage,buildDeferredToolsReminder,buildForkExecutionAllowlist,buildForkedMessages,buildFunctionResponseParts,buildMcpServerInstructionsReminder,buildMcpServerInstructionsReminderFromEntries,buildPinnedWorktreeNotice,buildWorktreeNotice,clearApiHistoryDirectoryContext,cloneApiHistory,formatDateForContext,getApiHistoryPromptId,getDirectoryContextString,getInitialChatHistory,getStartupContextLength,isApiHistoryDirectoryContext,isSystemReminderContent,markApiHistoryDirectoryContext,markApiHistoryPrompt,markCompressedHistory,normalizeForkTurns,registerForkDisplayImageForCache,resolveForkExecutionAllowedTools,runInForkContext,selectForkHistory,stripSystemReminderBlocks,validateForkToolList,wrapSystemReminder}from"./chunk-B3ZFUGTC.js";import{SESSION_SKILL_MANAGER,SKILLS_ACTIVATED_OPENER,clearLoadedSkillTracking,collectAvailableSkillEntries,renderAvailableSkillsBlock,sessionSkillManager}from"./chunk-IRINPFG7.js";import{DefaultHookOutput,HOOKS_CONFIG_FIELDS,HookEventName,PermissionRequestHookOutput,PostToolBatchHookOutput,PostToolUseFailureHookOutput,PostToolUseHookOutput,PreToolUseHookOutput,StopHookOutput,UserPromptExpansionHookOutput,createHookOutput,escapeSystemReminderTags,escapeXml,escapeXmlElementText,escapeXmlWithinBudget,getHookKey,isBlockingHookOutput,isToolArtifactLike,toUpdatedToolInput}from"./chunk-6GTPLW7K.js";import{DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES,QwenIgnoreParser,formatQwenIgnoreFileNames,require_ignore}from"./chunk-5DTFN37U.js";import{WorkspaceContext,isPathWithinRoot}from"./chunk-2YUBAWQ6.js";import{AgentStatistics,BaseDeclarativeTool,BaseToolInvocation,CONCURRENCY_SAFE_KINDS,StructuredToolError,hasCycleInSchema,isShellProgressData}from"./chunk-O5EKX7LG.js";import{AGENT_HOST_TOOL_NAMES,ToolDisplayNames,ToolDisplayNamesMigration,ToolNames,ToolNamesMigration,canonicalToolName,resolveBuiltinToolName,resolveRegisteredToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger,isDebugLogFileEnabled,registerSessionModel,registerSessionProjectDir,sessionIdContext,setDebugLogSession,unregisterSessionModel,unregisterSessionProjectDir}from"./chunk-JAUJI56S.js";import{SpanStatusCode,context,init_esm,trace}from"./chunk-I4H7NUVP.js";import{SKILL_PROVIDER_CONFIG_DIRS,Storage}from"./chunk-EPODBRBP.js";import{PATH_ARG_KEYS,QWEN_DIR,expandHomeDir,getProjectHash,isSubpath,isSubpaths,makeRelative,resolvePath,shortenPath,tildeifyPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{FatalConfigError,UnauthorizedError,getErrorMessage,getErrorStatus,getErrorType,isAbortError,isNodeError,toFriendlyError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__commonJS,__export,__name,__require,__toESM}from"./chunk-KBWJGX7I.js";var require_windows=__commonJS({"node_modules/isexe/windows.js"(exports2,module2){init_esbuild_shims();module2.exports=isexe;isexe.sync=sync;var fs81=__require("fs");function checkPathExt(path89,options2){var pathext=options2.pathExt!==void 0?options2.pathExt:process.env.PATHEXT;if(!pathext){return true}pathext=pathext.split(";");if(pathext.indexOf("")!==-1){return true}for(var i=0;i<pathext.length;i++){var p2=pathext[i].toLowerCase();if(p2&&path89.substr(-p2.length).toLowerCase()===p2){return true}}return false}__name(checkPathExt,"checkPathExt");function checkStat(stat15,path89,options2){if(!stat15.isSymbolicLink()&&!stat15.isFile()){return false}return checkPathExt(path89,options2)}__name(checkStat,"checkStat");function isexe(path89,options2,cb){fs81.stat(path89,function(er2,stat15){cb(er2,er2?false:checkStat(stat15,path89,options2))})}__name(isexe,"isexe");function sync(path89,options2){return checkStat(fs81.statSync(path89),path89,options2)}__name(sync,"sync")}});var require_mode=__commonJS({"node_modules/isexe/mode.js"(exports2,module2){init_esbuild_shims();module2.exports=isexe;isexe.sync=sync;var fs81=__require("fs");function isexe(path89,options2,cb){fs81.stat(path89,function(er2,stat15){cb(er2,er2?false:checkStat(stat15,options2))})}__name(isexe,"isexe");function sync(path89,options2){return checkStat(fs81.statSync(path89),options2)}__name(sync,"sync");function checkStat(stat15,options2){return stat15.isFile()&&checkMode(stat15,options2)}__name(checkStat,"checkStat");function checkMode(stat15,options2){var mod=stat15.mode;var uid=stat15.uid;var gid=stat15.gid;var myUid=options2.uid!==void 0?options2.uid:process.getuid&&process.getuid();var myGid=options2.gid!==void 0?options2.gid:process.getgid&&process.getgid();var u2=parseInt("100",8);var g2=parseInt("010",8);var o=parseInt("001",8);var ug=u2|g2;var ret=mod&o||mod&g2&&gid===myGid||mod&u2&&uid===myUid||mod&ug&&myUid===0;return ret}__name(checkMode,"checkMode")}});var require_isexe=__commonJS({"node_modules/isexe/index.js"(exports2,module2){init_esbuild_shims();var fs81=__require("fs");var core;if(process.platform==="win32"||globalThis.TESTING_WINDOWS){core=require_windows()}else{core=require_mode()}module2.exports=isexe;isexe.sync=sync;function isexe(path89,options2,cb){if(typeof options2==="function"){cb=options2;options2={}}if(!cb){if(typeof Promise!=="function"){throw new TypeError("callback not provided")}return new Promise(function(resolve36,reject){isexe(path89,options2||{},function(er2,is2){if(er2){reject(er2)}else{resolve36(is2)}})})}core(path89,options2||{},function(er2,is2){if(er2){if(er2.code==="EACCES"||options2&&options2.ignoreErrors){er2=null;is2=false}}cb(er2,is2)})}__name(isexe,"isexe");function sync(path89,options2){try{return core.sync(path89,options2||{})}catch(er2){if(options2&&options2.ignoreErrors||er2.code==="EACCES"){return false}else{throw er2}}}__name(sync,"sync")}});var require_which=__commonJS({"node_modules/cross-spawn/node_modules/which/which.js"(exports2,module2){init_esbuild_shims();var isWindows2=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys";var path89=__require("path");var COLON=isWindows2?";":":";var isexe=require_isexe();var getNotFoundError=__name(cmd=>Object.assign(new Error(`not found: ${cmd}`),{code:"ENOENT"}),"getNotFoundError");var getPathInfo=__name((cmd,opt)=>{const colon=opt.colon||COLON;const pathEnv=cmd.match(/\//)||isWindows2&&cmd.match(/\\/)?[""]:[...isWindows2?[process.cwd()]:[],...(opt.path||process.env.PATH||"").split(colon)];const pathExtExe=isWindows2?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"";const pathExt=isWindows2?pathExtExe.split(colon):[""];if(isWindows2){if(cmd.indexOf(".")!==-1&&pathExt[0]!=="")pathExt.unshift("")}return{pathEnv,pathExt,pathExtExe}},"getPathInfo");var which=__name((cmd,opt,cb)=>{if(typeof opt==="function"){cb=opt;opt={}}if(!opt)opt={};const{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt);const found=[];const step=__name(i=>new Promise((resolve36,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve36(found):reject(getNotFoundError(cmd));const ppRaw=pathEnv[i];const pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw;const pCmd=path89.join(pathPart,cmd);const p2=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;resolve36(subStep(p2,i,0))}),"step");const subStep=__name((p2,i,ii2)=>new Promise((resolve36,reject)=>{if(ii2===pathExt.length)return resolve36(step(i+1));const ext=pathExt[ii2];isexe(p2+ext,{pathExt:pathExtExe},(er2,is2)=>{if(!er2&&is2){if(opt.all)found.push(p2+ext);else return resolve36(p2+ext)}return resolve36(subStep(p2,i,ii2+1))})}),"subStep");return cb?step(0).then(res=>cb(null,res),cb):step(0)},"which");var whichSync=__name((cmd,opt)=>{opt=opt||{};const{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt);const found=[];for(let i=0;i<pathEnv.length;i++){const ppRaw=pathEnv[i];const pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw;const pCmd=path89.join(pathPart,cmd);const p2=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;for(let j2=0;j2<pathExt.length;j2++){const cur=p2+pathExt[j2];try{const is2=isexe.sync(cur,{pathExt:pathExtExe});if(is2){if(opt.all)found.push(cur);else return cur}}catch(ex){}}}if(opt.all&&found.length)return found;if(opt.nothrow)return null;throw getNotFoundError(cmd)},"whichSync");module2.exports=which;which.sync=whichSync}});var require_path_key=__commonJS({"node_modules/path-key/index.js"(exports2,module2){"use strict";init_esbuild_shims();var pathKey=__name((options2={})=>{const environment=options2.env||process.env;const platform2=options2.platform||process.platform;if(platform2!=="win32"){return"PATH"}return Object.keys(environment).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"},"pathKey");module2.exports=pathKey;module2.exports.default=pathKey}});var require_resolveCommand=__commonJS({"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2,module2){"use strict";init_esbuild_shims();var path89=__require("path");var which=require_which();var getPathKey=require_path_key();function resolveCommandAttempt(parsed,withoutPathExt){const env=parsed.options.env||process.env;const cwd=process.cwd();const hasCustomCwd=parsed.options.cwd!=null;const shouldSwitchCwd=hasCustomCwd&&process.chdir!==void 0&&!process.chdir.disabled;if(shouldSwitchCwd){try{process.chdir(parsed.options.cwd)}catch(err){}}let resolved;try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path89.delimiter:void 0})}catch(e){}finally{if(shouldSwitchCwd){process.chdir(cwd)}}if(resolved){resolved=path89.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)}return resolved}__name(resolveCommandAttempt,"resolveCommandAttempt");function resolveCommand(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,true)}__name(resolveCommand,"resolveCommand");module2.exports=resolveCommand}});var require_escape=__commonJS({"node_modules/cross-spawn/lib/util/escape.js"(exports2,module2){"use strict";init_esbuild_shims();var metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(arg){arg=arg.replace(metaCharsRegExp,"^$1");return arg}__name(escapeCommand,"escapeCommand");function escapeArgument(arg,doubleEscapeMetaChars){arg=`${arg}`;arg=arg.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"');arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1");arg=`"${arg}"`;arg=arg.replace(metaCharsRegExp,"^$1");if(doubleEscapeMetaChars){arg=arg.replace(metaCharsRegExp,"^$1")}return arg}__name(escapeArgument,"escapeArgument");module2.exports.command=escapeCommand;module2.exports.argument=escapeArgument}});var require_shebang_regex=__commonJS({"node_modules/shebang-regex/index.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"node_modules/shebang-command/index.js"(exports2,module2){"use strict";init_esbuild_shims();var shebangRegex=require_shebang_regex();module2.exports=(string7="")=>{const match=string7.match(shebangRegex);if(!match){return null}const[path89,argument]=match[0].replace(/#! ?/,"").split(" ");const binary=path89.split("/").pop();if(binary==="env"){return argument}return argument?`${binary} ${argument}`:binary}}});var require_readShebang=__commonJS({"node_modules/cross-spawn/lib/util/readShebang.js"(exports2,module2){"use strict";init_esbuild_shims();var fs81=__require("fs");var shebangCommand=require_shebang_command();function readShebang(command){const size=150;const buffer=Buffer.alloc(size);let fd;try{fd=fs81.openSync(command,"r");fs81.readSync(fd,buffer,0,size,0);fs81.closeSync(fd)}catch(e){}return shebangCommand(buffer.toString())}__name(readShebang,"readShebang");module2.exports=readShebang}});var require_parse=__commonJS({"node_modules/cross-spawn/lib/parse.js"(exports2,module2){"use strict";init_esbuild_shims();var path89=__require("path");var resolveCommand=require_resolveCommand();var escape3=require_escape();var readShebang=require_readShebang();var isWin=process.platform==="win32";var isExecutableRegExp=/\.(?:com|exe)$/i;var isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand(parsed);const shebang=parsed.file&&readShebang(parsed.file);if(shebang){parsed.args.unshift(parsed.file);parsed.command=shebang;return resolveCommand(parsed)}return parsed.file}__name(detectShebang,"detectShebang");function parseNonShell(parsed){if(!isWin){return parsed}const commandFile=detectShebang(parsed);const needsShell=!isExecutableRegExp.test(commandFile);if(parsed.options.forceShell||needsShell){const needsDoubleEscapeMetaChars=isCmdShimRegExp.test(commandFile);parsed.command=path89.normalize(parsed.command);parsed.command=escape3.command(parsed.command);parsed.args=parsed.args.map(arg=>escape3.argument(arg,needsDoubleEscapeMetaChars));const shellCommand=[parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`];parsed.command=process.env.comspec||"cmd.exe";parsed.options.windowsVerbatimArguments=true}return parsed}__name(parseNonShell,"parseNonShell");function parse15(command,args,options2){if(args&&!Array.isArray(args)){options2=args;args=null}args=args?args.slice(0):[];options2=Object.assign({},options2);const parsed={command,args,options:options2,file:void 0,original:{command,args}};return options2.shell?parsed:parseNonShell(parsed)}__name(parse15,"parse");module2.exports=parse15}});var require_enoent=__commonJS({"node_modules/cross-spawn/lib/enoent.js"(exports2,module2){"use strict";init_esbuild_shims();var isWin=process.platform==="win32";function notFoundError(original,syscall){return Object.assign(new Error(`${syscall} ${original.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${syscall} ${original.command}`,path:original.command,spawnargs:original.args})}__name(notFoundError,"notFoundError");function hookChildProcess(cp,parsed){if(!isWin){return}const originalEmit=cp.emit;cp.emit=function(name2,arg1){if(name2==="exit"){const err=verifyENOENT(arg1,parsed);if(err){return originalEmit.call(cp,"error",err)}}return originalEmit.apply(cp,arguments)}}__name(hookChildProcess,"hookChildProcess");function verifyENOENT(status,parsed){if(isWin&&status===1&&!parsed.file){return notFoundError(parsed.original,"spawn")}return null}__name(verifyENOENT,"verifyENOENT");function verifyENOENTSync(status,parsed){if(isWin&&status===1&&!parsed.file){return notFoundError(parsed.original,"spawnSync")}return null}__name(verifyENOENTSync,"verifyENOENTSync");module2.exports={hookChildProcess,verifyENOENT,verifyENOENTSync,notFoundError}}});var require_cross_spawn=__commonJS({"node_modules/cross-spawn/index.js"(exports2,module2){"use strict";init_esbuild_shims();var cp=__require("child_process");var parse15=require_parse();var enoent=require_enoent();function spawn8(command,args,options2){const parsed=parse15(command,args,options2);const spawned=cp.spawn(parsed.command,parsed.args,parsed.options);enoent.hookChildProcess(spawned,parsed);return spawned}__name(spawn8,"spawn");function spawnSync3(command,args,options2){const parsed=parse15(command,args,options2);const result=cp.spawnSync(parsed.command,parsed.args,parsed.options);result.error=result.error||enoent.verifyENOENTSync(result.status,parsed);return result}__name(spawnSync3,"spawnSync");module2.exports=spawn8;module2.exports.spawn=spawn8;module2.exports.sync=spawnSync3;module2.exports._parse=parse15;module2.exports._enoent=enoent}});var require_levenshtein=__commonJS({"node_modules/fast-levenshtein/levenshtein.js"(exports2,module2){init_esbuild_shims();(function(){"use strict";var collator;try{collator=typeof Intl!=="undefined"&&typeof Intl.Collator!=="undefined"?Intl.Collator("generic",{sensitivity:"base"}):null}catch(err){console.log("Collator could not be initialized and wouldn't be used")}var prevRow=[],str2Char=[];var Levenshtein={get:__name(function(str1,str2,options2){var useCollator=options2&&collator&&options2.useCollator;var str1Len=str1.length,str2Len=str2.length;if(str1Len===0)return str2Len;if(str2Len===0)return str1Len;var curCol,nextCol,i,j2,tmp;for(i=0;i<str2Len;++i){prevRow[i]=i;str2Char[i]=str2.charCodeAt(i)}prevRow[str2Len]=str2Len;var strCmp;if(useCollator){for(i=0;i<str1Len;++i){nextCol=i+1;for(j2=0;j2<str2Len;++j2){curCol=nextCol;strCmp=0===collator.compare(str1.charAt(i),String.fromCharCode(str2Char[j2]));nextCol=prevRow[j2]+(strCmp?0:1);tmp=curCol+1;if(nextCol>tmp){nextCol=tmp}tmp=prevRow[j2+1]+1;if(nextCol>tmp){nextCol=tmp}prevRow[j2]=curCol}prevRow[j2]=nextCol}}else{for(i=0;i<str1Len;++i){nextCol=i+1;for(j2=0;j2<str2Len;++j2){curCol=nextCol;strCmp=str1.charCodeAt(i)===str2Char[j2];nextCol=prevRow[j2]+(strCmp?0:1);tmp=curCol+1;if(nextCol>tmp){nextCol=tmp}tmp=prevRow[j2+1]+1;if(nextCol>tmp){nextCol=tmp}prevRow[j2]=curCol}prevRow[j2]=nextCol}}return nextCol},"get")};if(typeof define!=="undefined"&&define!==null&&define.amd){define(function(){return Levenshtein})}else if(typeof module2!=="undefined"&&module2!==null&&typeof exports2!=="undefined"&&module2.exports===exports2){module2.exports=Levenshtein}else if(typeof self!=="undefined"&&typeof self.postMessage==="function"&&typeof self.importScripts==="function"){self.Levenshtein=Levenshtein}else if(typeof window!=="undefined"&&window!==null){window.Levenshtein=Levenshtein}})()}});var require_parser=__commonJS({"node_modules/@iarna/toml/lib/parser.js"(exports2,module2){"use strict";init_esbuild_shims();var ParserEND=1114112;var ParserError=class _ParserError extends Error{static{__name(this,"ParserError")}constructor(msg,filename,linenumber){super("[ParserError] "+msg,filename,linenumber);this.name="ParserError";this.code="ParserError";if(Error.captureStackTrace)Error.captureStackTrace(this,_ParserError)}};var State=class{static{__name(this,"State")}constructor(parser2){this.parser=parser2;this.buf="";this.returned=null;this.result=null;this.resultTable=null;this.resultArr=null}};var Parser3=class{static{__name(this,"Parser")}constructor(){this.pos=0;this.col=0;this.line=0;this.obj={};this.ctx=this.obj;this.stack=[];this._buf="";this.char=null;this.ii=0;this.state=new State(this.parseStart)}parse(str){if(str.length===0||str.length==null)return;this._buf=String(str);this.ii=-1;this.char=-1;let getNext;while(getNext===false||this.nextChar()){getNext=this.runOne()}this._buf=null}nextChar(){if(this.char===10){++this.line;this.col=-1}++this.ii;this.char=this._buf.codePointAt(this.ii);++this.pos;++this.col;return this.haveBuffer()}haveBuffer(){return this.ii<this._buf.length}runOne(){return this.state.parser.call(this,this.state.returned)}finish(){this.char=ParserEND;let last;do{last=this.state.parser;this.runOne()}while(this.state.parser!==last);this.ctx=null;this.state=null;this._buf=null;return this.obj}next(fn){if(typeof fn!=="function")throw new ParserError("Tried to set state to non-existent state: "+JSON.stringify(fn));this.state.parser=fn}goto(fn){this.next(fn);return this.runOne()}call(fn,returnWith){if(returnWith)this.next(returnWith);this.stack.push(this.state);this.state=new State(fn)}callNow(fn,returnWith){this.call(fn,returnWith);return this.runOne()}return(value){if(this.stack.length===0)throw this.error(new ParserError("Stack underflow"));if(value===void 0)value=this.state.buf;this.state=this.stack.pop();this.state.returned=value}returnNow(value){this.return(value);return this.runOne()}consume(){if(this.char===ParserEND)throw this.error(new ParserError("Unexpected end-of-buffer"));this.state.buf+=this._buf[this.ii]}error(err){err.line=this.line;err.col=this.col;err.pos=this.pos;return err}parseStart(){throw new ParserError("Must declare a parseStart method")}};Parser3.END=ParserEND;Parser3.Error=ParserError;module2.exports=Parser3}});var require_create_datetime=__commonJS({"node_modules/@iarna/toml/lib/create-datetime.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=value=>{const date6=new Date(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_format_num=__commonJS({"node_modules/@iarna/toml/lib/format-num.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=(d,num)=>{num=String(num);while(num.length<d)num="0"+num;return num}}});var require_create_datetime_float=__commonJS({"node_modules/@iarna/toml/lib/create-datetime-float.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var FloatingDateTime=class extends Date{static{__name(this,"FloatingDateTime")}constructor(value){super(value+"Z");this.isFloating=true}toISOString(){const date6=`${this.getUTCFullYear()}-${f2(2,this.getUTCMonth()+1)}-${f2(2,this.getUTCDate())}`;const time5=`${f2(2,this.getUTCHours())}:${f2(2,this.getUTCMinutes())}:${f2(2,this.getUTCSeconds())}.${f2(3,this.getUTCMilliseconds())}`;return`${date6}T${time5}`}};module2.exports=value=>{const date6=new FloatingDateTime(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_create_date=__commonJS({"node_modules/@iarna/toml/lib/create-date.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var DateTime=globalThis.Date;var Date2=class extends DateTime{static{__name(this,"Date")}constructor(value){super(value);this.isDate=true}toISOString(){return`${this.getUTCFullYear()}-${f2(2,this.getUTCMonth()+1)}-${f2(2,this.getUTCDate())}`}};module2.exports=value=>{const date6=new Date2(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_create_time=__commonJS({"node_modules/@iarna/toml/lib/create-time.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var Time=class extends Date{static{__name(this,"Time")}constructor(value){super(`0000-01-01T${value}Z`);this.isTime=true}toISOString(){return`${f2(2,this.getUTCHours())}:${f2(2,this.getUTCMinutes())}:${f2(2,this.getUTCSeconds())}.${f2(3,this.getUTCMilliseconds())}`}};module2.exports=value=>{const date6=new Time(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_toml_parser=__commonJS({"node_modules/@iarna/toml/lib/toml-parser.js"(exports,module){"use strict";init_esbuild_shims();module.exports=makeParserClass(require_parser());module.exports.makeParserClass=makeParserClass;var TomlError=class _TomlError extends Error{static{__name(this,"TomlError")}constructor(msg){super(msg);this.name="TomlError";if(Error.captureStackTrace)Error.captureStackTrace(this,_TomlError);this.fromTOML=true;this.wrapped=null}};TomlError.wrap=err=>{const terr=new TomlError(err.message);terr.code=err.code;terr.wrapped=err;return terr};module.exports.TomlError=TomlError;var createDateTime=require_create_datetime();var createDateTimeFloat=require_create_datetime_float();var createDate=require_create_date();var createTime=require_create_time();var CTRL_I=9;var CTRL_J=10;var CTRL_M=13;var CTRL_CHAR_BOUNDARY=31;var CHAR_SP=32;var CHAR_QUOT=34;var CHAR_NUM=35;var CHAR_APOS=39;var CHAR_PLUS=43;var CHAR_COMMA=44;var CHAR_HYPHEN=45;var CHAR_PERIOD=46;var CHAR_0=48;var CHAR_1=49;var CHAR_7=55;var CHAR_9=57;var CHAR_COLON=58;var CHAR_EQUALS=61;var CHAR_A=65;var CHAR_E=69;var CHAR_F=70;var CHAR_T=84;var CHAR_U=85;var CHAR_Z=90;var CHAR_LOWBAR=95;var CHAR_a=97;var CHAR_b=98;var CHAR_e=101;var CHAR_f=102;var CHAR_i=105;var CHAR_l=108;var CHAR_n=110;var CHAR_o=111;var CHAR_r=114;var CHAR_s=115;var CHAR_t=116;var CHAR_u=117;var CHAR_x=120;var CHAR_z=122;var CHAR_LCUB=123;var CHAR_RCUB=125;var CHAR_LSQB=91;var CHAR_BSOL=92;var CHAR_RSQB=93;var CHAR_DEL=127;var SURROGATE_FIRST=55296;var SURROGATE_LAST=57343;var escapes={[CHAR_b]:"\b",[CHAR_t]:" ",[CHAR_n]:"\n",[CHAR_f]:"\f",[CHAR_r]:"\r",[CHAR_QUOT]:'"',[CHAR_BSOL]:"\\"};function isDigit(cp){return cp>=CHAR_0&&cp<=CHAR_9}__name(isDigit,"isDigit");function isHexit(cp){return cp>=CHAR_A&&cp<=CHAR_F||cp>=CHAR_a&&cp<=CHAR_f||cp>=CHAR_0&&cp<=CHAR_9}__name(isHexit,"isHexit");function isBit(cp){return cp===CHAR_1||cp===CHAR_0}__name(isBit,"isBit");function isOctit(cp){return cp>=CHAR_0&&cp<=CHAR_7}__name(isOctit,"isOctit");function isAlphaNumQuoteHyphen(cp){return cp>=CHAR_A&&cp<=CHAR_Z||cp>=CHAR_a&&cp<=CHAR_z||cp>=CHAR_0&&cp<=CHAR_9||cp===CHAR_APOS||cp===CHAR_QUOT||cp===CHAR_LOWBAR||cp===CHAR_HYPHEN}__name(isAlphaNumQuoteHyphen,"isAlphaNumQuoteHyphen");function isAlphaNumHyphen(cp){return cp>=CHAR_A&&cp<=CHAR_Z||cp>=CHAR_a&&cp<=CHAR_z||cp>=CHAR_0&&cp<=CHAR_9||cp===CHAR_LOWBAR||cp===CHAR_HYPHEN}__name(isAlphaNumHyphen,"isAlphaNumHyphen");var _type=Symbol("type");var _declared=Symbol("declared");var hasOwnProperty=Object.prototype.hasOwnProperty;var defineProperty=Object.defineProperty;var descriptor={configurable:true,enumerable:true,writable:true,value:void 0};function hasKey(obj,key){if(hasOwnProperty.call(obj,key))return true;if(key==="__proto__")defineProperty(obj,"__proto__",descriptor);return false}__name(hasKey,"hasKey");var INLINE_TABLE=Symbol("inline-table");function InlineTable(){return Object.defineProperties({},{[_type]:{value:INLINE_TABLE}})}__name(InlineTable,"InlineTable");function isInlineTable(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INLINE_TABLE}__name(isInlineTable,"isInlineTable");var TABLE=Symbol("table");function Table(){return Object.defineProperties({},{[_type]:{value:TABLE},[_declared]:{value:false,writable:true}})}__name(Table,"Table");function isTable(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===TABLE}__name(isTable,"isTable");var _contentType=Symbol("content-type");var INLINE_LIST=Symbol("inline-list");function InlineList(type){return Object.defineProperties([],{[_type]:{value:INLINE_LIST},[_contentType]:{value:type}})}__name(InlineList,"InlineList");function isInlineList(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INLINE_LIST}__name(isInlineList,"isInlineList");var LIST=Symbol("list");function List(){return Object.defineProperties([],{[_type]:{value:LIST}})}__name(List,"List");function isList(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===LIST}__name(isList,"isList");var _custom;try{const utilInspect=eval("require('util').inspect");_custom=utilInspect.custom}catch(_2){}var _inspect=_custom||"inspect";var BoxedBigInt=class{static{__name(this,"BoxedBigInt")}constructor(value){try{this.value=globalThis.BigInt.asIntN(64,value)}catch(_2){this.value=null}Object.defineProperty(this,_type,{value:INTEGER})}isNaN(){return this.value===null}toString(){return String(this.value)}[_inspect](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}};var INTEGER=Symbol("integer");function Integer(value){let num=Number(value);if(Object.is(num,-0))num=0;if(globalThis.BigInt&&!Number.isSafeInteger(num)){return new BoxedBigInt(value)}else{return Object.defineProperties(new Number(num),{isNaN:{value:__name(function(){return isNaN(this)},"value")},[_type]:{value:INTEGER},[_inspect]:{value:__name(()=>`[Integer: ${value}]`,"value")}})}}__name(Integer,"Integer");function isInteger(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INTEGER}__name(isInteger,"isInteger");var FLOAT=Symbol("float");function Float(value){return Object.defineProperties(new Number(value),{[_type]:{value:FLOAT},[_inspect]:{value:__name(()=>`[Float: ${value}]`,"value")}})}__name(Float,"Float");function isFloat(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===FLOAT}__name(isFloat,"isFloat");function tomlType(value){const type=typeof value;if(type==="object"){if(value===null)return"null";if(value instanceof Date)return"datetime";if(_type in value){switch(value[_type]){case INLINE_TABLE:return"inline-table";case INLINE_LIST:return"inline-list";case TABLE:return"table";case LIST:return"list";case FLOAT:return"float";case INTEGER:return"integer"}}}return type}__name(tomlType,"tomlType");function makeParserClass(Parser3){class TOMLParser extends Parser3{static{__name(this,"TOMLParser")}constructor(){super();this.ctx=this.obj=Table()}atEndOfWord(){return this.char===CHAR_NUM||this.char===CTRL_I||this.char===CHAR_SP||this.atEndOfLine()}atEndOfLine(){return this.char===Parser3.END||this.char===CTRL_J||this.char===CTRL_M}parseStart(){if(this.char===Parser3.END){return null}else if(this.char===CHAR_LSQB){return this.call(this.parseTableOrList)}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else if(isAlphaNumQuoteHyphen(this.char)){return this.callNow(this.parseAssignStatement)}else{throw this.error(new TomlError(`Unknown character "${this.char}"`))}}parseWhitespaceToEOL(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else if(this.char===CHAR_NUM){return this.goto(this.parseComment)}else if(this.char===Parser3.END||this.char===CTRL_J){return this.return()}else{throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"))}}parseAssignStatement(){return this.callNow(this.parseAssign,this.recordAssignStatement)}recordAssignStatement(kv){let target=this.ctx;let finalKey=kv.key.pop();for(let kw2 of kv.key){if(hasKey(target,kw2)&&(!isTable(target[kw2])||target[kw2][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}target=target[kw2]=target[kw2]||Table()}if(hasKey(target,finalKey)){throw this.error(new TomlError("Can't redefine existing key"))}if(isInteger(kv.value)||isFloat(kv.value)){target[finalKey]=kv.value.valueOf()}else{target[finalKey]=kv.value}return this.goto(this.parseWhitespaceToEOL)}parseAssign(){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}recordAssignKeyword(key){if(this.state.resultTable){this.state.resultTable.push(key)}else{this.state.resultTable=[key]}return this.goto(this.parseAssignKeywordPreDot)}parseAssignKeywordPreDot(){if(this.char===CHAR_PERIOD){return this.next(this.parseAssignKeywordPostDot)}else if(this.char!==CHAR_SP&&this.char!==CTRL_I){return this.goto(this.parseAssignEqual)}}parseAssignKeywordPostDot(){if(this.char!==CHAR_SP&&this.char!==CTRL_I){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}}parseAssignEqual(){if(this.char===CHAR_EQUALS){return this.next(this.parseAssignPreValue)}else{throw this.error(new TomlError('Invalid character, expected "="'))}}parseAssignPreValue(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseValue,this.recordAssignValue)}}recordAssignValue(value){return this.returnNow({key:this.state.resultTable,value})}parseComment(){do{if(this.char===Parser3.END||this.char===CTRL_J){return this.return()}}while(this.nextChar())}parseTableOrList(){if(this.char===CHAR_LSQB){this.next(this.parseList)}else{return this.goto(this.parseTable)}}parseTable(){this.ctx=this.obj;return this.goto(this.parseTableNext)}parseTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseKeyword,this.parseTableMore)}}parseTableMore(keyword){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CHAR_RSQB){if(hasKey(this.ctx,keyword)&&(!isTable(this.ctx[keyword])||this.ctx[keyword][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}else{this.ctx=this.ctx[keyword]=this.ctx[keyword]||Table();this.ctx[_declared]=true}return this.next(this.parseWhitespaceToEOL)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,keyword)){this.ctx=this.ctx[keyword]=Table()}else if(isTable(this.ctx[keyword])){this.ctx=this.ctx[keyword]}else if(isList(this.ctx[keyword])){this.ctx=this.ctx[keyword][this.ctx[keyword].length-1]}else{throw this.error(new TomlError("Can't redefine existing key"))}return this.next(this.parseTableNext)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseList(){this.ctx=this.obj;return this.goto(this.parseListNext)}parseListNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseKeyword,this.parseListMore)}}parseListMore(keyword){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CHAR_RSQB){if(!hasKey(this.ctx,keyword)){this.ctx[keyword]=List()}if(isInlineList(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline array"))}else if(isList(this.ctx[keyword])){const next=Table();this.ctx[keyword].push(next);this.ctx=next}else{throw this.error(new TomlError("Can't redefine an existing key"))}return this.next(this.parseListEnd)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,keyword)){this.ctx=this.ctx[keyword]=Table()}else if(isInlineList(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline array"))}else if(isInlineTable(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline table"))}else if(isList(this.ctx[keyword])){this.ctx=this.ctx[keyword][this.ctx[keyword].length-1]}else if(isTable(this.ctx[keyword])){this.ctx=this.ctx[keyword]}else{throw this.error(new TomlError("Can't redefine an existing key"))}return this.next(this.parseListNext)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseListEnd(keyword){if(this.char===CHAR_RSQB){return this.next(this.parseWhitespaceToEOL)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseValue(){if(this.char===Parser3.END){throw this.error(new TomlError("Key without value"))}else if(this.char===CHAR_QUOT){return this.next(this.parseDoubleString)}if(this.char===CHAR_APOS){return this.next(this.parseSingleString)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){return this.goto(this.parseNumberSign)}else if(this.char===CHAR_i){return this.next(this.parseInf)}else if(this.char===CHAR_n){return this.next(this.parseNan)}else if(isDigit(this.char)){return this.goto(this.parseNumberOrDateTime)}else if(this.char===CHAR_t||this.char===CHAR_f){return this.goto(this.parseBoolean)}else if(this.char===CHAR_LSQB){return this.call(this.parseInlineList,this.recordValue)}else if(this.char===CHAR_LCUB){return this.call(this.parseInlineTable,this.recordValue)}else{throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"))}}recordValue(value){return this.returnNow(value)}parseInf(){if(this.char===CHAR_n){return this.next(this.parseInf2)}else{throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}}parseInf2(){if(this.char===CHAR_f){if(this.state.buf==="-"){return this.return(-Infinity)}else{return this.return(Infinity)}}else{throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}}parseNan(){if(this.char===CHAR_a){return this.next(this.parseNan2)}else{throw this.error(new TomlError('Unexpected character, expected "nan"'))}}parseNan2(){if(this.char===CHAR_n){return this.return(NaN)}else{throw this.error(new TomlError('Unexpected character, expected "nan"'))}}parseKeyword(){if(this.char===CHAR_QUOT){return this.next(this.parseBasicString)}else if(this.char===CHAR_APOS){return this.next(this.parseLiteralString)}else{return this.goto(this.parseBareKey)}}parseBareKey(){do{if(this.char===Parser3.END){throw this.error(new TomlError("Key ended without value"))}else if(isAlphaNumHyphen(this.char)){this.consume()}else if(this.state.buf.length===0){throw this.error(new TomlError("Empty bare keys are not allowed"))}else{return this.returnNow()}}while(this.nextChar())}parseSingleString(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiStringMaybe)}else{return this.goto(this.parseLiteralString)}}parseLiteralString(){do{if(this.char===CHAR_APOS){return this.return()}else if(this.atEndOfLine()){throw this.error(new TomlError("Unterminated string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}parseLiteralMultiStringMaybe(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiString)}else{return this.returnNow()}}parseLiteralMultiString(){if(this.char===CTRL_M){return null}else if(this.char===CTRL_J){return this.next(this.parseLiteralMultiStringContent)}else{return this.goto(this.parseLiteralMultiStringContent)}}parseLiteralMultiStringContent(){do{if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiEnd)}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated multi-line string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}parseLiteralMultiEnd(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiEnd2)}else{this.state.buf+="'";return this.goto(this.parseLiteralMultiStringContent)}}parseLiteralMultiEnd2(){if(this.char===CHAR_APOS){return this.return()}else{this.state.buf+="''";return this.goto(this.parseLiteralMultiStringContent)}}parseDoubleString(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiStringMaybe)}else{return this.goto(this.parseBasicString)}}parseBasicString(){do{if(this.char===CHAR_BSOL){return this.call(this.parseEscape,this.recordEscapeReplacement)}else if(this.char===CHAR_QUOT){return this.return()}else if(this.atEndOfLine()){throw this.error(new TomlError("Unterminated string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}recordEscapeReplacement(replacement){this.state.buf+=replacement;return this.goto(this.parseBasicString)}parseMultiStringMaybe(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiString)}else{return this.returnNow()}}parseMultiString(){if(this.char===CTRL_M){return null}else if(this.char===CTRL_J){return this.next(this.parseMultiStringContent)}else{return this.goto(this.parseMultiStringContent)}}parseMultiStringContent(){do{if(this.char===CHAR_BSOL){return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement)}else if(this.char===CHAR_QUOT){return this.next(this.parseMultiEnd)}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated multi-line string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}errorControlCharInString(){let displayCode="\\u00";if(this.char<16){displayCode+="0"}displayCode+=this.char.toString(16);return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`))}recordMultiEscapeReplacement(replacement){this.state.buf+=replacement;return this.goto(this.parseMultiStringContent)}parseMultiEnd(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiEnd2)}else{this.state.buf+='"';return this.goto(this.parseMultiStringContent)}}parseMultiEnd2(){if(this.char===CHAR_QUOT){return this.return()}else{this.state.buf+='""';return this.goto(this.parseMultiStringContent)}}parseMultiEscape(){if(this.char===CTRL_M||this.char===CTRL_J){return this.next(this.parseMultiTrim)}else if(this.char===CHAR_SP||this.char===CTRL_I){return this.next(this.parsePreMultiTrim)}else{return this.goto(this.parseEscape)}}parsePreMultiTrim(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CTRL_M||this.char===CTRL_J){return this.next(this.parseMultiTrim)}else{throw this.error(new TomlError("Can't escape whitespace"))}}parseMultiTrim(){if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else{return this.returnNow()}}parseEscape(){if(this.char in escapes){return this.return(escapes[this.char])}else if(this.char===CHAR_u){return this.call(this.parseSmallUnicode,this.parseUnicodeReturn)}else if(this.char===CHAR_U){return this.call(this.parseLargeUnicode,this.parseUnicodeReturn)}else{throw this.error(new TomlError("Unknown escape character: "+this.char))}}parseUnicodeReturn(char){try{const codePoint=parseInt(char,16);if(codePoint>=SURROGATE_FIRST&&codePoint<=SURROGATE_LAST){throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"))}return this.returnNow(String.fromCodePoint(codePoint))}catch(err){throw this.error(TomlError.wrap(err))}}parseSmallUnicode(){if(!isHexit(this.char)){throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}else{this.consume();if(this.state.buf.length>=4)return this.return()}}parseLargeUnicode(){if(!isHexit(this.char)){throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}else{this.consume();if(this.state.buf.length>=8)return this.return()}}parseNumberSign(){this.consume();return this.next(this.parseMaybeSignedInfOrNan)}parseMaybeSignedInfOrNan(){if(this.char===CHAR_i){return this.next(this.parseInf)}else if(this.char===CHAR_n){return this.next(this.parseNan)}else{return this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}}parseNumberIntegerStart(){if(this.char===CHAR_0){this.consume();return this.next(this.parseNumberIntegerExponentOrDecimal)}else{return this.goto(this.parseNumberInteger)}}parseNumberIntegerExponentOrDecimal(){if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else{return this.returnNow(Integer(this.state.buf))}}parseNumberInteger(){if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseNoUnder(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD||this.char===CHAR_E||this.char===CHAR_e){throw this.error(new TomlError("Unexpected character, expected digit"))}else if(this.atEndOfWord()){throw this.error(new TomlError("Incomplete number"))}return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD){throw this.error(new TomlError("Unexpected character, expected digit"))}else if(this.atEndOfWord()){throw this.error(new TomlError("Incomplete number"))}return this.returnNow()}parseNumberFloat(){if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else{return this.returnNow(Float(this.state.buf))}}parseNumberExponentSign(){if(isDigit(this.char)){return this.goto(this.parseNumberExponent)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.call(this.parseNoUnder,this.parseNumberExponent)}else{throw this.error(new TomlError("Unexpected character, expected -, + or digit"))}}parseNumberExponent(){if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder)}else{return this.returnNow(Float(this.state.buf))}}parseNumberOrDateTime(){if(this.char===CHAR_0){this.consume();return this.next(this.parseNumberBaseOrDateTime)}else{return this.goto(this.parseNumberOrDateTimeOnly)}}parseNumberOrDateTimeOnly(){if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder,this.parseNumberInteger)}else if(isDigit(this.char)){this.consume();if(this.state.buf.length>4)this.next(this.parseNumberInteger)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(this.char===CHAR_HYPHEN){return this.goto(this.parseDateTime)}else if(this.char===CHAR_COLON){return this.goto(this.parseOnlyTimeHour)}else{return this.returnNow(Integer(this.state.buf))}}parseDateTimeOnly(){if(this.state.buf.length<4){if(isDigit(this.char)){return this.consume()}else if(this.char===CHAR_COLON){return this.goto(this.parseOnlyTimeHour)}else{throw this.error(new TomlError("Expected digit while parsing year part of a date"))}}else{if(this.char===CHAR_HYPHEN){return this.goto(this.parseDateTime)}else{throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"))}}}parseNumberBaseOrDateTime(){if(this.char===CHAR_b){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin)}else if(this.char===CHAR_o){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct)}else if(this.char===CHAR_x){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex)}else if(this.char===CHAR_PERIOD){return this.goto(this.parseNumberInteger)}else if(isDigit(this.char)){return this.goto(this.parseDateTimeOnly)}else{return this.returnNow(Integer(this.state.buf))}}parseIntegerHex(){if(isHexit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseIntegerOct(){if(isOctit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseIntegerBin(){if(isBit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseDateTime(){if(this.state.buf.length<4){throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"))}this.state.result=this.state.buf;this.state.buf="";return this.next(this.parseDateMonth)}parseDateMonth(){if(this.char===CHAR_HYPHEN){if(this.state.buf.length<2){throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"))}this.state.result+="-"+this.state.buf;this.state.buf="";return this.next(this.parseDateDay)}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseDateDay(){if(this.char===CHAR_T||this.char===CHAR_SP){if(this.state.buf.length<2){throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"))}this.state.result+="-"+this.state.buf;this.state.buf="";return this.next(this.parseStartTimeHour)}else if(this.atEndOfWord()){return this.returnNow(createDate(this.state.result+"-"+this.state.buf))}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseStartTimeHour(){if(this.atEndOfWord()){return this.returnNow(createDate(this.state.result))}else{return this.goto(this.parseTimeHour)}}parseTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2){throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"))}this.state.result+="T"+this.state.buf;this.state.buf="";return this.next(this.parseTimeMin)}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseTimeMin(){if(this.state.buf.length<2&&isDigit(this.char)){this.consume()}else if(this.state.buf.length===2&&this.char===CHAR_COLON){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseTimeSec)}else{throw this.error(new TomlError("Incomplete datetime"))}}parseTimeSec(){if(isDigit(this.char)){this.consume();if(this.state.buf.length===2){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseTimeZoneOrFraction)}}else{throw this.error(new TomlError("Incomplete datetime"))}}parseOnlyTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2){throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"))}this.state.result=this.state.buf;this.state.buf="";return this.next(this.parseOnlyTimeMin)}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeMin(){if(this.state.buf.length<2&&isDigit(this.char)){this.consume()}else if(this.state.buf.length===2&&this.char===CHAR_COLON){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseOnlyTimeSec)}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeSec(){if(isDigit(this.char)){this.consume();if(this.state.buf.length===2){return this.next(this.parseOnlyTimeFractionMaybe)}}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeFractionMaybe(){this.state.result+=":"+this.state.buf;if(this.char===CHAR_PERIOD){this.state.buf="";this.next(this.parseOnlyTimeFraction)}else{return this.return(createTime(this.state.result))}}parseOnlyTimeFraction(){if(isDigit(this.char)){this.consume()}else if(this.atEndOfWord()){if(this.state.buf.length===0)throw this.error(new TomlError("Expected digit in milliseconds"));return this.returnNow(createTime(this.state.result+"."+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseTimeZoneOrFraction(){if(this.char===CHAR_PERIOD){this.consume();this.next(this.parseDateTimeFraction)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.next(this.parseTimeZoneHour)}else if(this.char===CHAR_Z){this.consume();return this.return(createDateTime(this.state.result+this.state.buf))}else if(this.atEndOfWord()){return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseDateTimeFraction(){if(isDigit(this.char)){this.consume()}else if(this.state.buf.length===1){throw this.error(new TomlError("Expected digit in milliseconds"))}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.next(this.parseTimeZoneHour)}else if(this.char===CHAR_Z){this.consume();return this.return(createDateTime(this.state.result+this.state.buf))}else if(this.atEndOfWord()){return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseTimeZoneHour(){if(isDigit(this.char)){this.consume();if(/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else{throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}}parseTimeZoneSep(){if(this.char===CHAR_COLON){this.consume();this.next(this.parseTimeZoneMin)}else{throw this.error(new TomlError("Unexpected character in datetime, expected colon"))}}parseTimeZoneMin(){if(isDigit(this.char)){this.consume();if(/\d\d$/.test(this.state.buf))return this.return(createDateTime(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}}parseBoolean(){if(this.char===CHAR_t){this.consume();return this.next(this.parseTrue_r)}else if(this.char===CHAR_f){this.consume();return this.next(this.parseFalse_a)}}parseTrue_r(){if(this.char===CHAR_r){this.consume();return this.next(this.parseTrue_u)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseTrue_u(){if(this.char===CHAR_u){this.consume();return this.next(this.parseTrue_e)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseTrue_e(){if(this.char===CHAR_e){return this.return(true)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_a(){if(this.char===CHAR_a){this.consume();return this.next(this.parseFalse_l)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_l(){if(this.char===CHAR_l){this.consume();return this.next(this.parseFalse_s)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_s(){if(this.char===CHAR_s){this.consume();return this.next(this.parseFalse_e)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_e(){if(this.char===CHAR_e){return this.return(false)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseInlineList(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J){return null}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CHAR_RSQB){return this.return(this.state.resultArr||InlineList())}else{return this.callNow(this.parseValue,this.recordInlineListValue)}}recordInlineListValue(value){if(this.state.resultArr){const listType=this.state.resultArr[_contentType];const valueType=tomlType(value);if(listType!==valueType){throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`))}}else{this.state.resultArr=InlineList(tomlType(value))}if(isFloat(value)||isInteger(value)){this.state.resultArr.push(value.valueOf())}else{this.state.resultArr.push(value)}return this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J){return null}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CHAR_COMMA){return this.next(this.parseInlineList)}else if(this.char===CHAR_RSQB){return this.goto(this.parseInlineList)}else{throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}parseInlineTable(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===Parser3.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_RCUB){return this.return(this.state.resultTable||InlineTable())}else{if(!this.state.resultTable)this.state.resultTable=InlineTable();return this.callNow(this.parseAssign,this.recordInlineTableValue)}}recordInlineTableValue(kv){let target=this.state.resultTable;let finalKey=kv.key.pop();for(let kw2 of kv.key){if(hasKey(target,kw2)&&(!isTable(target[kw2])||target[kw2][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}target=target[kw2]=target[kw2]||Table()}if(hasKey(target,finalKey)){throw this.error(new TomlError("Can't redefine existing key"))}if(isInteger(kv.value)||isFloat(kv.value)){target[finalKey]=kv.value.valueOf()}else{target[finalKey]=kv.value}return this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===Parser3.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_COMMA){return this.next(this.parseInlineTable)}else if(this.char===CHAR_RCUB){return this.goto(this.parseInlineTable)}else{throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}}return TOMLParser}__name(makeParserClass,"makeParserClass")}});var require_parse_pretty_error=__commonJS({"node_modules/@iarna/toml/parse-pretty-error.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=prettyError;function prettyError(err,buf){if(err.pos==null||err.line==null)return err;let msg=err.message;msg+=` at row ${err.line+1}, col ${err.col+1}, pos ${err.pos}:
3
+ import{isBidiControlChar,stripDisplayControlChars,stripTerminalControlSequences,truncateNotificationLabel}from"./chunk-R2EHHA2C.js";import{AjvJsonSchemaValidator,CallToolResultSchema,CompleteResultSchema,CreateMessageRequestSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,CreateTaskResultSchema,ElicitRequestSchema,ElicitResultSchema,EmptyResultSchema,ErrorCode,GetPromptResultSchema,InitializeResultSchema,JSONRPCMessageSchema,LATEST_PROTOCOL_VERSION,ListChangedOptionsBaseSchema,ListPromptsResultSchema,ListResourceTemplatesResultSchema,ListResourcesResultSchema,ListToolsResultSchema,McpError,PromptListChangedNotificationSchema,Protocol,ReadBuffer,ReadResourceResultSchema,ResourceListChangedNotificationSchema,SUPPORTED_PROTOCOL_VERSIONS,ToolListChangedNotificationSchema,assertClientRequestTaskCapability,assertToolsCallTaskCapability,getLiteralValue,getObjectShape,isInitializedNotification,isJSONRPCRequest,isJSONRPCResultResponse,mergeCapabilities,safeParse,serializeMessage}from"./chunk-YK7NDQKM.js";import{SshWorkspaceClient,SshWorkspaceError}from"./chunk-ZLZF2ZDD.js";import{MANAGED_SESSION_COMMIT_SUBTYPE,MANAGED_SESSION_DOMAINS,MANAGED_SESSION_ENVELOPE_DOMAINS,MANAGED_SESSION_EVENT_SUBTYPE,MANAGED_SESSION_FORMAT_VERSION,MANAGED_SESSION_HEADER_SUBTYPE,MANAGED_SESSION_LIMITS,MANAGED_SESSION_MINIMUM_READER,MANAGED_TOOL_RESULT_KINDS,ManagedSessionAppendUnsettledError,ManagedSessionRecordError,ManagedSessionWritesStoppedError,assertManagedBranchRecord,assertManagedSessionChannelAdapterEnabled,assertManagedSessionChildContinuationEnabled,assertManagedSessionChildRunKindEnabled,assertManagedSessionDigest,assertManagedSessionDomainEnabled,assertManagedSessionDurableRef,assertManagedSessionEventActor,assertManagedSessionKey,assertManagedSessionScheduleSessionModeEnabled,assertManagedSessionSequence,assertManagedSessionStableId,assertManagedSessionTime,assertManagedSessionTransaction,boundedString,collectPendingBranchToolCalls,isChildNotificationSource,managedSessionDomainCarriesRecord,managedSessionEventRefs,managedSessionEventsDigest,managedSessionKeysEqual,managedSessionReaderFacingBody,parseBranchCheckpointPayload,parseManagedSessionCommitMarker,parseManagedSessionEvent,parseManagedSessionHeader,parseManagedSessionRecordJson,parseToolResultManifestBytes,resolveBranchPoints,resolveCompletedTurnBranchCandidateFromRecords,safeErrorValue,updatePendingBranchToolCalls,validateManagedReaderFacingRecord}from"./chunk-OMSVOFTC.js";import{require_content_type}from"./chunk-PHIPLV2I.js";import{require_main,resolveEnvVarsInObject}from"./chunk-ZOTKZI2P.js";import{EXTRACT_CADENCE_MAX_PENDING_ENTRIES,EXTRACT_TAIL_ENTRIES,getExtractNoopSkipTurns}from"./chunk-A6G5TAIF.js";import{SessionExecutionEngineAccumulator,SessionExecutionEngineError,assertSessionExecutionEngine}from"./chunk-YVBHCSZD.js";import{ExecutionCleanupError,MANAGED_RUNTIME_TOOL_NAMES,ManagedRuntimeOutcomeUnknownError}from"./chunk-FIXDX63I.js";import{isShellResultDisplay,mapShellResultText,shellResultText}from"./chunk-T7CHK6C2.js";import{NEVER,ZodIssueCode,any,array,boolean,coerce_exports,literal,looseObject,number,object,string,url}from"./chunk-PT7NZBDY.js";import{external_exports}from"./chunk-TWP72VRH.js";import{claimTask,listTasks,onTasksUpdated,unassignTeammateTasks}from"./chunk-UYEWRLGD.js";import{humanReadableCron}from"./chunk-QVPT37XZ.js";import{backgroundFixAt,backgroundFixHolding,buildPermissionCheckContext,evaluatePermissionRules,forgetAutofixPrSession,hasUnattendedFixGrant,injectPermissionRulesIfMissing,isUnattendedFixConfig,markUnattendedFixConfig,openBackgroundFix,persistPermissionOutcome,settleBackgroundFix,unattendedFixGranted}from"./chunk-YVD4O5ZB.js";import{CRON_TASKS_DISPLAY_PATH,addCronTask,annotateCronRunSession,appendCronRun,cronTaskSessionDeletionId,generateCronTaskId,getCronFilePath,readCronTasks,removeCronTasks,taskHasLegacyCondition,taskHasLegacyRunMode,updateCronTasks,withTaskGate}from"./chunk-T6W33SET.js";import{consumeUnread,forwardApproval,getInboxPath,readInbox,sendStructuredMessage,wrapConfirmWithBadge,writeMessage}from"./chunk-WK2IBT6D.js";import{canUseRipgrep}from"./chunk-QZV4PFQK.js";import{AGENT_WORKTREE_SLUG_PATTERN,GitWorktreeService,MAX_DIFF_SIZE_BYTES,clearRuntimeStatus,generateAgentWorktreeSlug,gitEnv,gitRemoteEnv,loadSimpleGit,readRuntimeStatus,worktreeBranchForSlug,worktreeHasWork,writeRuntimeStatus,writeWorktreeSessionMarker}from"./chunk-ILECDNJX.js";import{hasVerifiableInode,isUnverifiableIdentityError,openNoFollow,openSyncNoFollow}from"./chunk-QXQGUM3Y.js";import{SESSION_ARTIFACT_PERSISTENCE_VERSION,SessionArtifactSnapshotAccumulator,deleteArtifactSnapshot,getWebPreviewSnapshotId,isSessionArtifactRecord,rebuildSessionArtifactSnapshot,remapSessionArtifactPayloadForFork,retainArtifactSnapshot,selectActiveSideArtifactRecordUuids}from"./chunk-UQ7IROJH.js";import{aggregateTranscriptRecordFragments,isInternalCodeModeToolResult,isTranscriptConversationRecord,isUserPromptSubmitContextPartText,prepareTranscriptRecords,projectUserTranscriptForDisplay,selectTranscriptLeaf,stripGeneratedAttachmentTokens,validateTranscriptRecord,walkTranscriptUuidChain,wrapUserPromptSubmitContext}from"./chunk-SZCBUCNH.js";import{buildModelIdContext,resolveModelId}from"./chunk-BEKROCWN.js";import{isToolHiddenBehindToolSearch,loadSkillsFromDir,parsePriorityField,readBundledReference,resolveBundledReferenceSurface,toolSearchBridgeSentence,validateConfig,validateSymlinkTarget}from"./chunk-5SUFJTQQ.js";import{SHARED_RECORD_SLOT,defangEnvelopeTags,deriveSessionName,flattenPeerLabel,patchSessionRecord,unregisterSession}from"./chunk-BYU42MLK.js";import{LEADER_NAME,MAX_TEAMMATES,assignTeammateColor,classifyShutdownResponse,findMemberByName,formatAgentId,generateUniqueTeammateName,sanitizeName,writeTeamFile}from"./chunk-JWQXU3SR.js";import{readLocalBootId,readPidNamespaceId}from"./chunk-5LZ2DPLH.js";import{SKILL_FILE_NAME,assertRealProjectSkillPath,getArchivedSkillsRoot,getPendingSkillsRoot,getProjectSkillsRoot,isProjectSkillPath,maybeRunAutoSkillCurator}from"./chunk-XQJOZDV7.js";import{SKILL_NAME_PATTERN,SkillError,SkillErrorCode,authoredSkillName,parseAllowedToolsField,parseModelField,parsePathsField,parseUserInvocableField,qualifySkillName,skillRestrictionNames,validateSkillName}from"./chunk-CV2UAEZA.js";import{AUTO_MEMORY_SCHEMA_VERSION,AUTO_MEMORY_SCOPES,AUTO_MEMORY_TREE_CATEGORIES,AUTO_MEMORY_TYPES,MAX_USAGE_SCENARIO_CHARS,createAutoMemoryTreeSnapshot,isImportedMemoryDocument,listTrustedMemoryMarkdownFiles,normalizeAutoMemoryKeyword,parseAutoMemoryTopicDocument,renderAutoMemoryFocusedSubtree,rereadAutoMemoryDocument,resolveTrustedMemoryFile,resolveTrustedMemoryRoot,sanitizeAutoMemoryPromptField,scanAllAutoMemoryTopicDocuments,scanAllUserAutoMemoryTopicDocuments,scanAutoMemoryIndexDocumentsFromRoot,scanAutoMemorySnapshot,scanAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments,toAutoMemoryRef,validateStructuredAutoMemoryDocument}from"./chunk-FUBDS3AV.js";import{AgentOutputMessageCapture,DEFAULT_OTLP_ENDPOINT,DEFAULT_TELEMETRY_TARGET,GOAL_DEFAULT_TOKEN_BUDGET,GOAL_INFEASIBLE_NEXT_STEP,GOAL_NO_PROGRESS_TURN_LIMIT,GOAL_PAUSE_REASON_NO_PROGRESS,GOAL_PAUSE_REASON_SESSION_TOKEN_LIMIT,GOAL_PAUSE_REASON_STOP_HOOK_CAP,GOAL_PAUSE_REASON_USER_INTERRUPT,GOAL_PROPOSAL_REASON_MAX_CHARACTERS,GOAL_STATE_VERSION,GoalConflictError,GoalInvalidTransitionError,PAUSED_GOAL_SYSTEM_REMINDER,addAgentInputMessageAttributes,addToolArgumentsAttributes,addToolCallResultAttributes,addUserPromptAttributes,elapsedActiveTime,goalActiveTimeBudgetReason,goalPauseReasonForFailure,goalPauseReasonForVerifierFailure,goalRequiresExactPermit,goalStateEventFromSnapshot,goalTokenBudgetReason,goalTurnBudgetReason,isGoalActiveTimeBudgetSpent,isGoalTokenBudgetSpent,isGoalTurnBudgetSpent,isRepeatedBlockerProposal,parseGoalStateRecordPayloadV2,reduceGoalControl,reduceGoalSpend,reduceGoalTurnFinished,validateGoalProposalReason}from"./chunk-HW6AWS7W.js";import{parse,require_dist,sanitizeValue,stringify}from"./chunk-KLC3OD2M.js";import{normalizeImageGenerationBaseUrl}from"./chunk-Q5IZXKUJ.js";import{restoreSessionSources}from"./chunk-G5PYYZMM.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{glob,globSync}from"./chunk-OBOU4ZZM.js";import{isTruthy}from"./chunk-D7XCQWP2.js";import{isOmniDeliveryActive}from"./chunk-OBV7RNHV.js";import{ToolMode,buildExecDeclaration,getToolExposure,isCodeModeToolCallAllowed,isDeferredToolBridgeAvailable,isDirectToolBridgeAvailable,planCodeModeBindings}from"./chunk-7CQMWEMY.js";import{EXCLUDED_TOOLS_FOR_SUBAGENTS,READ_ONLY_INSPECTION_TOOLS,buildSubagentPlanToolBlockedResult,getExcludedToolUnavailableMessage,getLeaderOnlyToolUnavailableMessage,getPlanRequiredTeammatePreApprovalMessage,getSubagentPlanToolUnavailableMessage,isLeaderOnlyToolUnavailableInSubagent,isPlanLifecycleToolUnavailableInSubagent,isPlanRequiredTeammateAwaitingApproval,isPlanRequiredTeammateContext,isPlanRequiredTeammatePreApprovalAllowedTool,isSubagentLikeExecutionContext,isToolExcludedForCurrentContext,matchesAgentToolBlocklist,shouldUsePlanOnlyReminderInSubagentContext,toolConfigAllowsSkill}from"./chunk-GOZYWU4B.js";import{SHELL_TOOL_NAMES,getToolNameAliases,hasAmbiguousMcpGrant,matchesRule,matchesToolPattern,parseRule,parseRules,require_picomatch,resolveToolName,splitCompoundCommand,splitCompoundCommandSegments,toolMatchesRuleToolName,warnDroppedPermissionRule}from"./chunk-OUC3WICA.js";import{APPROVAL_MODES,ApprovalMode}from"./chunk-JZK2WGXA.js";import{MediaResourceRegistry,evaluateMediaPolicyToolCall,isMediaPolicyToolHiddenFromModel,resolveMediaPolicyModelAccess}from"./chunk-S2ZKZXHX.js";import{BaseTokenStorage,KeychainTokenStorage}from"./chunk-4GP3PH7Z.js";import{AskUserQuestionTool,TrustedUserAnswers}from"./chunk-4QQKOW5M.js";import{assembleSystemPrompt,getArenaSystemReminder,getCompressionPrompt,getCoreSystemPrompt,getCustomSystemPrompt,getManualPlanExitSystemReminder,getOutputStyleTurnReminder,getPlanModeSystemReminder,resolveEffectiveOutputStyle,resolveInteractionMode,resolveMainSessionOutputStyle}from"./chunk-OV3EBH6J.js";import{NO_EXEC_CONFIG,findGitRoot,getCachedGitBranch,getGitBranch,getRecentGitStatus,isGitRepository}from"./chunk-EBMCWXGZ.js";import{executeSandbox}from"./chunk-LSASUDF2.js";import{admitShellSandbox,assertShellSandboxCwd,probeShellSandbox}from"./chunk-MOKVM4PT.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{ShellExecutionService,getShellAbortReasonKind,getShellContextEnvVars,getShellPagerEnv,isSignalTermination,normalizePathEnvForWindows}from"./chunk-NMY3PYNO.js";import{stripAnsi}from"./chunk-YGLM5XPP.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{promptIdContext,todoWorkChainContext}from"./chunk-MWGB5RCF.js";import{SHELL_SELF_KILL_REJECTION,backgroundsAnyPart,buildOutsideWorkspaceWarning,buildShellExecWarnings,classifyAwkCommandSafety,classifySedCommandSafety,detectSelfKillCommand,escapeShellArg,getCommandRoot,getCommandRoots,getShellConfiguration,hasShellPatternExpansion,hasShellSubstitution,hasUnsafeMonitorBackgroundOperator,isShellCommandReadOnly,normalizeMonitorCommand,runsOnlyComments,shouldDefaultToNodePty,splitCommands,stripShellWrapper}from"./chunk-SCD5TUBG.js";import{escapeJsonTagCharacters,formatMemoryUsage}from"./chunk-NTRFETZB.js";import{require_shell_quote}from"./chunk-TL3SF2GA.js";import{isInternalSecretEnvVar,sanitizeChildEnv}from"./chunk-LMJPU2JM.js";import{carryIncompleteArgumentsMarker,toolCallArgumentsWereIncomplete}from"./chunk-4JNHUZ7M.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX}from"./chunk-SW54YEPK.js";import{DashScopeOpenAICompatibleProvider,selectDashScopeThinkingKnob}from"./chunk-ZCRL73DT.js";import{InvalidStreamError,getToolCallPreparations,isFlushedToolCallPark,isRetryableStatuslessUpstreamError,isRetryableStreamTransportError,setToolCallPreparations}from"./chunk-A6LT3FIJ.js";import{assertHookExecutionOwner,captureHookExecutionOwner,childLaunchDepth,getCurrentAgentChat,getCurrentAgentConfiguredToolAllowlist,getCurrentAgentDepth,getCurrentAgentDisallowedTools,getCurrentAgentId,getHookExecutionOwner,getRuntimeContentGenerator,isTopLevelSession,resolveHookExecutionOwner,runOutsideAgentContext,runWithAgentChat,runWithAgentConfiguredToolAllowlist,runWithAgentContext,runWithAgentDisallowedTools,runWithHookExecutionOwner,runWithRuntimeContentGenerator,spawnBlockReason}from"./chunk-YZFNBUKG.js";import{getTeammateContext,isTeammate,runOutsideTeammateIdentity,runWithTeammateIdentity}from"./chunk-AGEDDL7Z.js";import{getResponsesMessage,sameResponsesMessage}from"./chunk-2NJJHZ52.js";import{supportsOpenAIPrefixCaching}from"./chunk-BN4FIQ77.js";import{InMemoryImagePayloadStore,REATTACH_BOUNDARY_METADATA,buildReattachParts,countAllInlineImages,hasImagePayloadReferences,replaceImagePayloadsInPlace}from"./chunk-X64RXJQQ.js";import{getThoughtSummary,getThoughtText}from"./chunk-HETUGUHE.js";import{ModelsConfig,captureReasoningSnapshot,getBuiltinDeepSeekReasoning,getRequestModel,isImageGenerationCapable,resolveProviderProtocol,resolveReasoningCapabilities,resolveReasoningForModel,stripRuntimeSnapshotPrefix,validateReasoningCapabilities}from"./chunk-ET2Z7ZGF.js";import{openBrowserSecurely,shouldAttemptBrowserLaunch}from"./chunk-3YWXKSOI.js";import{resolveNetworkTarget}from"./chunk-5CWTKFI4.js";import{beginRetryWait,bindRetryWaitObserver,delay,isUnattendedMode,retryWithBackoff,runWithRetryWaitObserver}from"./chunk-C4MVD5OI.js";import{QUOTA_EXHAUSTED_PREFIX,classifyRetryError,formatQuotaExhaustedMessage,getHeaderValue,getRateLimitErrorDetails,getRateLimitRetryDelayMs,isApiError,isFallbackEligible,isQuotaExhaustedError,isRateLimitError,isRetryableUpstreamError,isStructuredError,toRetryDiagnostics}from"./chunk-Z2W7S4O4.js";import{combineAbortSignals,createAbortController,createChildAbortController}from"./chunk-476F6QIM.js";import{ResponsesHttpError}from"./chunk-4R67LXKL.js";import{addDaemonRequestAttribute}from"./chunk-FQRF6B65.js";import{ApiRetryEvent,BUNDLED_GENERATED_UI_SERVER,BUNDLED_GENERATED_UI_TOOL,COMBINED_PASS_TOLERANCE_FACTOR,ContentRetryEvent,ContentRetryFailureEvent,DiscoveredMCPTool,ExtensionDisableEvent,ExtensionEnableEvent,ExtensionInstallEvent,ExtensionUninstallEvent,ExtensionUpdateEvent,FULL_OUTPUT_DIGEST_LABEL,HookCallEvent,LoopDetectedEvent,LoopDetectionDisabledEvent,LoopProtectionEvent,MemoryDreamEvent,MemoryExtractEvent,MemoryMigrationEvent,MemoryRecallDeliveryEvent,MemoryRecallEvent,MemoryRecallModeTransitionEvent,NextSpeakerCheckEvent,PREVIEW_SIZE_CHARS,RipgrepFallbackEvent,StartSessionEvent,SubagentExecutionEvent,TOOL_OUTPUT_TRUNCATED_PREFIX,ToolCallEvent,ToolResultSizeEvent,UiTelemetryService,WorkflowKeywordEvent,attachToolOutputProvenance,collectText,effectiveAppResourceMaxBytes,effectiveAppResourceTimeoutMs,formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,getMCPServerStatus,getQualifiedVisionModelId,getToolOutputProvenance,isAlreadyTruncated,isChatRecordingSuppressed,isFullTurnVisionCapable,isImagePart,isSkipSelectorOnUniqueStrongHitEnabled,logApiRetry,logArenaAgentCompleted,logArenaSessionEnded,logArenaSessionStarted,logChatCompression,logContentRetry,logContentRetryFailure,logExtensionDisable,logExtensionEnable,logExtensionInstallEvent,logExtensionUninstall,logExtensionUpdateEvent,logGoalState,logHookCall,logLoopDetected,logLoopDetectionDisabled,logLoopProtection,logMemoryDream,logMemoryExtract,logMemoryMigration,logMemoryRecall,logMemoryRecallDelivery,logMemoryRecallModeTransition,logNextSpeakerCheck,logRipgrepFallback,logSessionEnd,logStartSession,logSubagentExecution,logToolCall,logToolResultSize,logWorkflowKeyword,makeArenaAgentCompletedEvent,makeArenaSessionEndedEvent,makeArenaSessionStartedEvent,makeChatCompressionEvent,measureToolOutput,memoryAge,memoryFreshnessText,normalizeParts,normalizeToolResultCallId,persistAndTruncateToolResult,recordMCPServerLastError,removeMCPServerStatus,runVisionBridge,runWithChatRecordingSuppressed,selectVisionBridgeModel,shouldRunVisionBridge,subagentIdentityContext,subagentNameContext,truncateLlmContent,truncateToolOutput,uiTelemetryService,updateMCPServerStatus,updateToolOutputBudget}from"./chunk-ZWPSBU7K.js";import{_recoverObjectsFromLine,exists,parseLineTolerant,parseLineTolerantWithIntegrity,read,readLines,readLinesWithIntegrity,writeLine,writeLineSync}from"./chunk-UQFTXKEB.js";import{Mutex}from"./chunk-HDGTWJ24.js";import{extractCodeModeImageContent,getCurrentToolCallSource,runWithToolCallRuntime,runWithToolCallSource,runWithoutToolCallRuntime}from"./chunk-W5NWIGKO.js";import{AUTO_MEMORY_INDEX_FILENAME,AUTO_MEMORY_PINNED_DIRNAME,TEAM_AUTO_MEMORY_DIRNAME,getAutoMemoryConsolidationLockPath,getAutoMemoryExtractCursorPath,getAutoMemoryIndexPath,getAutoMemoryMetadataPath,getAutoMemoryRoot,getAutoMemoryTrustedAnchor,getImportedProjectMemoryRoot,getMemoryBaseDir,getMemoryRootTrustedAnchor,getProjectAutoMemoryRoots,getTeamAutoMemoryIndexPath,getTeamAutoMemoryRoot,getUserAutoMemoryConsolidationLockPath,getUserAutoMemoryIndexPath,getUserAutoMemoryMetadataPath,getUserAutoMemoryRoot,isAnyAutoMemPath,isAutoMemPath,isManagedMemoryPath,isTeamAutoMemPath,isUserAutoMemPath}from"./chunk-KVA6DHHF.js";import{runSideQuery}from"./chunk-K7JCVESI.js";import{FileExclusions,FileReadOpenError,LOCAL_CONTEXT_FILENAME,digestFileReadSource,getAllMemoryFilenames,isUtf8CompatibleEncoding,loadIconvLite,readFileHandleBytes,readFileWithLineAndLimit,readTextCursorWindowFromHandle,readTextRangeFromHandle,setMemoryFilename}from"./chunk-Y6HHV4LC.js";import{normalizeMcpToolName,sanitizeToolNameForProvider}from"./chunk-7DOOXUDG.js";import{getSystemEncoding}from"./chunk-7U7CWMP7.js";import{getInvocationContext,runWithInvocationContext}from"./chunk-EFTJIDS3.js";import{DEFAULT_IMAGE_TOKEN_ESTIMATE,TOKEN_TO_CHAR_RATIO,clampInlineMediaPart,estimateContentChars,getFunctionResponseParts,resolveCompactionTuning,resolveSlimmingConfig,sanitizeMimeForPlaceholder,slimCompactionInput}from"./chunk-Q6UAOTP3.js";import{createContentGenerator,resetPreloadedContentGenerator,resolveContentGeneratorConfigWithSources}from"./chunk-H5EXNXGW.js";import{AUTH_ENV_MAPPINGS,CATALOG_MODALITIES,DEFAULT_MODELS,DEFAULT_QWEN_EMBEDDING_MODEL,DEFAULT_TOKEN_LIMIT,MIN_AUTO_DETECTED_CONTEXT_WINDOW,MODELS_DEV_URL,MODEL_CATALOG_PROJECTION_VERSION,MODEL_CATALOG_URL_ENV,MODEL_GENERATION_CONFIG_FIELDS,OUTPUT_TOKEN_CEILING,QWEN_OAUTH_ALLOWED_MODELS,REASONING_EFFORT_TIERS,clampOutputTokensToWindow,clampReasoningEffort,defaultModalities,defaultOutputCeiling,getGptReasoningCapabilities,getModelCatalogCachePath,hasExplicitOutputLimit,isModelCatalogDisabled,isModelCatalogKey,isTieredEffortWireModel,knownTokenLimit,normalize,normalizeReasoningEffort,parseModelCatalog,parsePositiveIntegerEnvValue,reasoningEffortsForCapability,setGeneratorReasoningEffort,tokenLimit,versionSpellingAlias}from"./chunk-GOR7FFVE.js";import{DEFAULT_QWEN_MODEL}from"./chunk-4ZBZL23U.js";import{atomicWriteFile,atomicWriteFileSync,atomicWriteJSON,renameWithRetry}from"./chunk-BMHYEQTI.js";import{getOrCreateMcpDispatcher,loadUndici,preloadRuntimeFetchModule,redactProxyError,setResolvedProxyUrlForRuntimeFetch}from"./chunk-ZZZAYAJW.js";import{safeJsonStringify}from"./chunk-XMANRGPK.js";import{DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH,SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT,TOOL_FAILURE_KIND_ATTRIBUTE,TOOL_FAILURE_KIND_BACKGROUND_AGENT_DENIED,TOOL_FAILURE_KIND_CANCELLED,TOOL_FAILURE_KIND_INVOCATION_GUARD_DENIED,TOOL_FAILURE_KIND_NON_INTERACTIVE_DENIED,TOOL_FAILURE_KIND_PERMISSION_DENIED,TOOL_FAILURE_KIND_PERMISSION_HOOK_DENIED,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_FAILURE_KIND_POST_HOOK_STOPPED,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_FAILURE_KIND_TIMEOUT,TOOL_FAILURE_KIND_TOOL_ERROR,TOOL_FAILURE_KIND_TOOL_EXCEPTION,endHookSpan,endInteractionSpan,endSubagentSpan,endToolBlockedOnUserSpan,endToolExecutionSpan,endToolSpan,getActiveInteractionSpan,initializeTelemetry,isPerformanceMonitoringActive,isTelemetrySdkInitialized,isValidSensitiveSpanAttributeMaxLength,recordCpuUsage,recordInteractionActivity,recordMemoryUsage,redactUrlCredentials,refreshSessionContext,runInSubagentSpanContext,runInToolSpanContext,safeSetStatus,shutdownTelemetry,startHookSpan,startInteractionSpan,startSubagentSpan,startToolBlockedOnUserSpan,startToolExecutionSpan,startToolSpan,truncateSpanError}from"./chunk-3XVPZY7X.js";import{STRUCTURED_OUTPUT_REDACTED_ARGS}from"./chunk-URNNJMIC.js";import{require_src}from"./chunk-GU22I6TY.js";import{normalizeContent,stripAnsiAndControl,stripHtmlComments}from"./chunk-DBRQGEEI.js";import{AUTO_MEMORY_SNAPSHOT_METADATA,BUBBLE_APPROVAL_MODE,FORK_AGENT,FORK_DEFAULT_MAX_TURNS,FORK_PLACEHOLDER_RESULT,FORK_SUBAGENT_TYPE,SubagentError,SubagentErrorCode,buildAvailableSkillsReminder,buildChangedAgentsReminder,buildChangedMcpToolsReminder,buildChangedSkillsReminder,buildChildMessage,buildDeferredToolsReminder,buildForkExecutionAllowlist,buildForkedMessages,buildFunctionResponseParts,buildMcpServerInstructionsReminder,buildMcpServerInstructionsReminderFromEntries,buildPinnedWorktreeNotice,buildWorktreeNotice,clearApiHistoryDirectoryContext,cloneApiHistory,formatDateForContext,getApiHistoryPromptId,getDirectoryContextString,getInitialChatHistory,getStartupContextLength,isApiHistoryDirectoryContext,isSystemReminderContent,markApiHistoryDirectoryContext,markApiHistoryPrompt,markCompressedHistory,normalizeForkTurns,registerForkDisplayImageForCache,resolveForkExecutionAllowedTools,runInForkContext,selectForkHistory,stripSystemReminderBlocks,validateForkToolList,wrapSystemReminder}from"./chunk-B3ZFUGTC.js";import{SESSION_SKILL_MANAGER,SKILLS_ACTIVATED_OPENER,clearLoadedSkillTracking,collectAvailableSkillEntries,renderAvailableSkillsBlock,sessionSkillManager}from"./chunk-IRINPFG7.js";import{DefaultHookOutput,HOOKS_CONFIG_FIELDS,HookEventName,PermissionRequestHookOutput,PostToolBatchHookOutput,PostToolUseFailureHookOutput,PostToolUseHookOutput,PreToolUseHookOutput,StopHookOutput,UserPromptExpansionHookOutput,createHookOutput,escapeSystemReminderTags,escapeXml,escapeXmlElementText,escapeXmlWithinBudget,getHookKey,isBlockingHookOutput,isToolArtifactLike,toUpdatedToolInput}from"./chunk-6GTPLW7K.js";import{DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES,QwenIgnoreParser,formatQwenIgnoreFileNames,require_ignore}from"./chunk-5DTFN37U.js";import{WorkspaceContext,isPathWithinRoot}from"./chunk-2YUBAWQ6.js";import{AgentStatistics,BaseDeclarativeTool,BaseToolInvocation,CONCURRENCY_SAFE_KINDS,StructuredToolError,hasCycleInSchema,isShellProgressData}from"./chunk-O5EKX7LG.js";import{AGENT_HOST_TOOL_NAMES,ToolDisplayNames,ToolDisplayNamesMigration,ToolNames,ToolNamesMigration,canonicalToolName,resolveBuiltinToolName,resolveRegisteredToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger,isDebugLogFileEnabled,registerSessionModel,registerSessionProjectDir,sessionIdContext,setDebugLogSession,unregisterSessionModel,unregisterSessionProjectDir}from"./chunk-JAUJI56S.js";import{SpanStatusCode,context,init_esm,trace}from"./chunk-I4H7NUVP.js";import{SKILL_PROVIDER_CONFIG_DIRS,Storage}from"./chunk-EPODBRBP.js";import{PATH_ARG_KEYS,QWEN_DIR,expandHomeDir,getProjectHash,isSubpath,isSubpaths,makeRelative,resolvePath,shortenPath,tildeifyPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{FatalConfigError,UnauthorizedError,getErrorMessage,getErrorStatus,getErrorType,isAbortError,isNodeError,toFriendlyError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__commonJS,__export,__name,__require,__toESM}from"./chunk-KBWJGX7I.js";var require_windows=__commonJS({"node_modules/isexe/windows.js"(exports2,module2){init_esbuild_shims();module2.exports=isexe;isexe.sync=sync;var fs81=__require("fs");function checkPathExt(path89,options2){var pathext=options2.pathExt!==void 0?options2.pathExt:process.env.PATHEXT;if(!pathext){return true}pathext=pathext.split(";");if(pathext.indexOf("")!==-1){return true}for(var i=0;i<pathext.length;i++){var p2=pathext[i].toLowerCase();if(p2&&path89.substr(-p2.length).toLowerCase()===p2){return true}}return false}__name(checkPathExt,"checkPathExt");function checkStat(stat15,path89,options2){if(!stat15.isSymbolicLink()&&!stat15.isFile()){return false}return checkPathExt(path89,options2)}__name(checkStat,"checkStat");function isexe(path89,options2,cb){fs81.stat(path89,function(er2,stat15){cb(er2,er2?false:checkStat(stat15,path89,options2))})}__name(isexe,"isexe");function sync(path89,options2){return checkStat(fs81.statSync(path89),path89,options2)}__name(sync,"sync")}});var require_mode=__commonJS({"node_modules/isexe/mode.js"(exports2,module2){init_esbuild_shims();module2.exports=isexe;isexe.sync=sync;var fs81=__require("fs");function isexe(path89,options2,cb){fs81.stat(path89,function(er2,stat15){cb(er2,er2?false:checkStat(stat15,options2))})}__name(isexe,"isexe");function sync(path89,options2){return checkStat(fs81.statSync(path89),options2)}__name(sync,"sync");function checkStat(stat15,options2){return stat15.isFile()&&checkMode(stat15,options2)}__name(checkStat,"checkStat");function checkMode(stat15,options2){var mod=stat15.mode;var uid=stat15.uid;var gid=stat15.gid;var myUid=options2.uid!==void 0?options2.uid:process.getuid&&process.getuid();var myGid=options2.gid!==void 0?options2.gid:process.getgid&&process.getgid();var u2=parseInt("100",8);var g2=parseInt("010",8);var o=parseInt("001",8);var ug=u2|g2;var ret=mod&o||mod&g2&&gid===myGid||mod&u2&&uid===myUid||mod&ug&&myUid===0;return ret}__name(checkMode,"checkMode")}});var require_isexe=__commonJS({"node_modules/isexe/index.js"(exports2,module2){init_esbuild_shims();var fs81=__require("fs");var core;if(process.platform==="win32"||globalThis.TESTING_WINDOWS){core=require_windows()}else{core=require_mode()}module2.exports=isexe;isexe.sync=sync;function isexe(path89,options2,cb){if(typeof options2==="function"){cb=options2;options2={}}if(!cb){if(typeof Promise!=="function"){throw new TypeError("callback not provided")}return new Promise(function(resolve36,reject){isexe(path89,options2||{},function(er2,is2){if(er2){reject(er2)}else{resolve36(is2)}})})}core(path89,options2||{},function(er2,is2){if(er2){if(er2.code==="EACCES"||options2&&options2.ignoreErrors){er2=null;is2=false}}cb(er2,is2)})}__name(isexe,"isexe");function sync(path89,options2){try{return core.sync(path89,options2||{})}catch(er2){if(options2&&options2.ignoreErrors||er2.code==="EACCES"){return false}else{throw er2}}}__name(sync,"sync")}});var require_which=__commonJS({"node_modules/cross-spawn/node_modules/which/which.js"(exports2,module2){init_esbuild_shims();var isWindows2=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys";var path89=__require("path");var COLON=isWindows2?";":":";var isexe=require_isexe();var getNotFoundError=__name(cmd=>Object.assign(new Error(`not found: ${cmd}`),{code:"ENOENT"}),"getNotFoundError");var getPathInfo=__name((cmd,opt)=>{const colon=opt.colon||COLON;const pathEnv=cmd.match(/\//)||isWindows2&&cmd.match(/\\/)?[""]:[...isWindows2?[process.cwd()]:[],...(opt.path||process.env.PATH||"").split(colon)];const pathExtExe=isWindows2?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"";const pathExt=isWindows2?pathExtExe.split(colon):[""];if(isWindows2){if(cmd.indexOf(".")!==-1&&pathExt[0]!=="")pathExt.unshift("")}return{pathEnv,pathExt,pathExtExe}},"getPathInfo");var which=__name((cmd,opt,cb)=>{if(typeof opt==="function"){cb=opt;opt={}}if(!opt)opt={};const{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt);const found=[];const step=__name(i=>new Promise((resolve36,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve36(found):reject(getNotFoundError(cmd));const ppRaw=pathEnv[i];const pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw;const pCmd=path89.join(pathPart,cmd);const p2=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;resolve36(subStep(p2,i,0))}),"step");const subStep=__name((p2,i,ii2)=>new Promise((resolve36,reject)=>{if(ii2===pathExt.length)return resolve36(step(i+1));const ext=pathExt[ii2];isexe(p2+ext,{pathExt:pathExtExe},(er2,is2)=>{if(!er2&&is2){if(opt.all)found.push(p2+ext);else return resolve36(p2+ext)}return resolve36(subStep(p2,i,ii2+1))})}),"subStep");return cb?step(0).then(res=>cb(null,res),cb):step(0)},"which");var whichSync=__name((cmd,opt)=>{opt=opt||{};const{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt);const found=[];for(let i=0;i<pathEnv.length;i++){const ppRaw=pathEnv[i];const pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw;const pCmd=path89.join(pathPart,cmd);const p2=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;for(let j2=0;j2<pathExt.length;j2++){const cur=p2+pathExt[j2];try{const is2=isexe.sync(cur,{pathExt:pathExtExe});if(is2){if(opt.all)found.push(cur);else return cur}}catch(ex){}}}if(opt.all&&found.length)return found;if(opt.nothrow)return null;throw getNotFoundError(cmd)},"whichSync");module2.exports=which;which.sync=whichSync}});var require_path_key=__commonJS({"node_modules/path-key/index.js"(exports2,module2){"use strict";init_esbuild_shims();var pathKey=__name((options2={})=>{const environment=options2.env||process.env;const platform2=options2.platform||process.platform;if(platform2!=="win32"){return"PATH"}return Object.keys(environment).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"},"pathKey");module2.exports=pathKey;module2.exports.default=pathKey}});var require_resolveCommand=__commonJS({"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2,module2){"use strict";init_esbuild_shims();var path89=__require("path");var which=require_which();var getPathKey=require_path_key();function resolveCommandAttempt(parsed,withoutPathExt){const env=parsed.options.env||process.env;const cwd=process.cwd();const hasCustomCwd=parsed.options.cwd!=null;const shouldSwitchCwd=hasCustomCwd&&process.chdir!==void 0&&!process.chdir.disabled;if(shouldSwitchCwd){try{process.chdir(parsed.options.cwd)}catch(err){}}let resolved;try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path89.delimiter:void 0})}catch(e){}finally{if(shouldSwitchCwd){process.chdir(cwd)}}if(resolved){resolved=path89.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)}return resolved}__name(resolveCommandAttempt,"resolveCommandAttempt");function resolveCommand(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,true)}__name(resolveCommand,"resolveCommand");module2.exports=resolveCommand}});var require_escape=__commonJS({"node_modules/cross-spawn/lib/util/escape.js"(exports2,module2){"use strict";init_esbuild_shims();var metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(arg){arg=arg.replace(metaCharsRegExp,"^$1");return arg}__name(escapeCommand,"escapeCommand");function escapeArgument(arg,doubleEscapeMetaChars){arg=`${arg}`;arg=arg.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"');arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1");arg=`"${arg}"`;arg=arg.replace(metaCharsRegExp,"^$1");if(doubleEscapeMetaChars){arg=arg.replace(metaCharsRegExp,"^$1")}return arg}__name(escapeArgument,"escapeArgument");module2.exports.command=escapeCommand;module2.exports.argument=escapeArgument}});var require_shebang_regex=__commonJS({"node_modules/shebang-regex/index.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"node_modules/shebang-command/index.js"(exports2,module2){"use strict";init_esbuild_shims();var shebangRegex=require_shebang_regex();module2.exports=(string7="")=>{const match=string7.match(shebangRegex);if(!match){return null}const[path89,argument]=match[0].replace(/#! ?/,"").split(" ");const binary=path89.split("/").pop();if(binary==="env"){return argument}return argument?`${binary} ${argument}`:binary}}});var require_readShebang=__commonJS({"node_modules/cross-spawn/lib/util/readShebang.js"(exports2,module2){"use strict";init_esbuild_shims();var fs81=__require("fs");var shebangCommand=require_shebang_command();function readShebang(command){const size=150;const buffer=Buffer.alloc(size);let fd;try{fd=fs81.openSync(command,"r");fs81.readSync(fd,buffer,0,size,0);fs81.closeSync(fd)}catch(e){}return shebangCommand(buffer.toString())}__name(readShebang,"readShebang");module2.exports=readShebang}});var require_parse=__commonJS({"node_modules/cross-spawn/lib/parse.js"(exports2,module2){"use strict";init_esbuild_shims();var path89=__require("path");var resolveCommand=require_resolveCommand();var escape3=require_escape();var readShebang=require_readShebang();var isWin=process.platform==="win32";var isExecutableRegExp=/\.(?:com|exe)$/i;var isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand(parsed);const shebang=parsed.file&&readShebang(parsed.file);if(shebang){parsed.args.unshift(parsed.file);parsed.command=shebang;return resolveCommand(parsed)}return parsed.file}__name(detectShebang,"detectShebang");function parseNonShell(parsed){if(!isWin){return parsed}const commandFile=detectShebang(parsed);const needsShell=!isExecutableRegExp.test(commandFile);if(parsed.options.forceShell||needsShell){const needsDoubleEscapeMetaChars=isCmdShimRegExp.test(commandFile);parsed.command=path89.normalize(parsed.command);parsed.command=escape3.command(parsed.command);parsed.args=parsed.args.map(arg=>escape3.argument(arg,needsDoubleEscapeMetaChars));const shellCommand=[parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`];parsed.command=process.env.comspec||"cmd.exe";parsed.options.windowsVerbatimArguments=true}return parsed}__name(parseNonShell,"parseNonShell");function parse15(command,args,options2){if(args&&!Array.isArray(args)){options2=args;args=null}args=args?args.slice(0):[];options2=Object.assign({},options2);const parsed={command,args,options:options2,file:void 0,original:{command,args}};return options2.shell?parsed:parseNonShell(parsed)}__name(parse15,"parse");module2.exports=parse15}});var require_enoent=__commonJS({"node_modules/cross-spawn/lib/enoent.js"(exports2,module2){"use strict";init_esbuild_shims();var isWin=process.platform==="win32";function notFoundError(original,syscall){return Object.assign(new Error(`${syscall} ${original.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${syscall} ${original.command}`,path:original.command,spawnargs:original.args})}__name(notFoundError,"notFoundError");function hookChildProcess(cp,parsed){if(!isWin){return}const originalEmit=cp.emit;cp.emit=function(name2,arg1){if(name2==="exit"){const err=verifyENOENT(arg1,parsed);if(err){return originalEmit.call(cp,"error",err)}}return originalEmit.apply(cp,arguments)}}__name(hookChildProcess,"hookChildProcess");function verifyENOENT(status,parsed){if(isWin&&status===1&&!parsed.file){return notFoundError(parsed.original,"spawn")}return null}__name(verifyENOENT,"verifyENOENT");function verifyENOENTSync(status,parsed){if(isWin&&status===1&&!parsed.file){return notFoundError(parsed.original,"spawnSync")}return null}__name(verifyENOENTSync,"verifyENOENTSync");module2.exports={hookChildProcess,verifyENOENT,verifyENOENTSync,notFoundError}}});var require_cross_spawn=__commonJS({"node_modules/cross-spawn/index.js"(exports2,module2){"use strict";init_esbuild_shims();var cp=__require("child_process");var parse15=require_parse();var enoent=require_enoent();function spawn8(command,args,options2){const parsed=parse15(command,args,options2);const spawned=cp.spawn(parsed.command,parsed.args,parsed.options);enoent.hookChildProcess(spawned,parsed);return spawned}__name(spawn8,"spawn");function spawnSync3(command,args,options2){const parsed=parse15(command,args,options2);const result=cp.spawnSync(parsed.command,parsed.args,parsed.options);result.error=result.error||enoent.verifyENOENTSync(result.status,parsed);return result}__name(spawnSync3,"spawnSync");module2.exports=spawn8;module2.exports.spawn=spawn8;module2.exports.sync=spawnSync3;module2.exports._parse=parse15;module2.exports._enoent=enoent}});var require_levenshtein=__commonJS({"node_modules/fast-levenshtein/levenshtein.js"(exports2,module2){init_esbuild_shims();(function(){"use strict";var collator;try{collator=typeof Intl!=="undefined"&&typeof Intl.Collator!=="undefined"?Intl.Collator("generic",{sensitivity:"base"}):null}catch(err){console.log("Collator could not be initialized and wouldn't be used")}var prevRow=[],str2Char=[];var Levenshtein={get:__name(function(str1,str2,options2){var useCollator=options2&&collator&&options2.useCollator;var str1Len=str1.length,str2Len=str2.length;if(str1Len===0)return str2Len;if(str2Len===0)return str1Len;var curCol,nextCol,i,j2,tmp;for(i=0;i<str2Len;++i){prevRow[i]=i;str2Char[i]=str2.charCodeAt(i)}prevRow[str2Len]=str2Len;var strCmp;if(useCollator){for(i=0;i<str1Len;++i){nextCol=i+1;for(j2=0;j2<str2Len;++j2){curCol=nextCol;strCmp=0===collator.compare(str1.charAt(i),String.fromCharCode(str2Char[j2]));nextCol=prevRow[j2]+(strCmp?0:1);tmp=curCol+1;if(nextCol>tmp){nextCol=tmp}tmp=prevRow[j2+1]+1;if(nextCol>tmp){nextCol=tmp}prevRow[j2]=curCol}prevRow[j2]=nextCol}}else{for(i=0;i<str1Len;++i){nextCol=i+1;for(j2=0;j2<str2Len;++j2){curCol=nextCol;strCmp=str1.charCodeAt(i)===str2Char[j2];nextCol=prevRow[j2]+(strCmp?0:1);tmp=curCol+1;if(nextCol>tmp){nextCol=tmp}tmp=prevRow[j2+1]+1;if(nextCol>tmp){nextCol=tmp}prevRow[j2]=curCol}prevRow[j2]=nextCol}}return nextCol},"get")};if(typeof define!=="undefined"&&define!==null&&define.amd){define(function(){return Levenshtein})}else if(typeof module2!=="undefined"&&module2!==null&&typeof exports2!=="undefined"&&module2.exports===exports2){module2.exports=Levenshtein}else if(typeof self!=="undefined"&&typeof self.postMessage==="function"&&typeof self.importScripts==="function"){self.Levenshtein=Levenshtein}else if(typeof window!=="undefined"&&window!==null){window.Levenshtein=Levenshtein}})()}});var require_parser=__commonJS({"node_modules/@iarna/toml/lib/parser.js"(exports2,module2){"use strict";init_esbuild_shims();var ParserEND=1114112;var ParserError=class _ParserError extends Error{static{__name(this,"ParserError")}constructor(msg,filename,linenumber){super("[ParserError] "+msg,filename,linenumber);this.name="ParserError";this.code="ParserError";if(Error.captureStackTrace)Error.captureStackTrace(this,_ParserError)}};var State=class{static{__name(this,"State")}constructor(parser2){this.parser=parser2;this.buf="";this.returned=null;this.result=null;this.resultTable=null;this.resultArr=null}};var Parser3=class{static{__name(this,"Parser")}constructor(){this.pos=0;this.col=0;this.line=0;this.obj={};this.ctx=this.obj;this.stack=[];this._buf="";this.char=null;this.ii=0;this.state=new State(this.parseStart)}parse(str){if(str.length===0||str.length==null)return;this._buf=String(str);this.ii=-1;this.char=-1;let getNext;while(getNext===false||this.nextChar()){getNext=this.runOne()}this._buf=null}nextChar(){if(this.char===10){++this.line;this.col=-1}++this.ii;this.char=this._buf.codePointAt(this.ii);++this.pos;++this.col;return this.haveBuffer()}haveBuffer(){return this.ii<this._buf.length}runOne(){return this.state.parser.call(this,this.state.returned)}finish(){this.char=ParserEND;let last;do{last=this.state.parser;this.runOne()}while(this.state.parser!==last);this.ctx=null;this.state=null;this._buf=null;return this.obj}next(fn){if(typeof fn!=="function")throw new ParserError("Tried to set state to non-existent state: "+JSON.stringify(fn));this.state.parser=fn}goto(fn){this.next(fn);return this.runOne()}call(fn,returnWith){if(returnWith)this.next(returnWith);this.stack.push(this.state);this.state=new State(fn)}callNow(fn,returnWith){this.call(fn,returnWith);return this.runOne()}return(value){if(this.stack.length===0)throw this.error(new ParserError("Stack underflow"));if(value===void 0)value=this.state.buf;this.state=this.stack.pop();this.state.returned=value}returnNow(value){this.return(value);return this.runOne()}consume(){if(this.char===ParserEND)throw this.error(new ParserError("Unexpected end-of-buffer"));this.state.buf+=this._buf[this.ii]}error(err){err.line=this.line;err.col=this.col;err.pos=this.pos;return err}parseStart(){throw new ParserError("Must declare a parseStart method")}};Parser3.END=ParserEND;Parser3.Error=ParserError;module2.exports=Parser3}});var require_create_datetime=__commonJS({"node_modules/@iarna/toml/lib/create-datetime.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=value=>{const date6=new Date(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_format_num=__commonJS({"node_modules/@iarna/toml/lib/format-num.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=(d,num)=>{num=String(num);while(num.length<d)num="0"+num;return num}}});var require_create_datetime_float=__commonJS({"node_modules/@iarna/toml/lib/create-datetime-float.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var FloatingDateTime=class extends Date{static{__name(this,"FloatingDateTime")}constructor(value){super(value+"Z");this.isFloating=true}toISOString(){const date6=`${this.getUTCFullYear()}-${f2(2,this.getUTCMonth()+1)}-${f2(2,this.getUTCDate())}`;const time5=`${f2(2,this.getUTCHours())}:${f2(2,this.getUTCMinutes())}:${f2(2,this.getUTCSeconds())}.${f2(3,this.getUTCMilliseconds())}`;return`${date6}T${time5}`}};module2.exports=value=>{const date6=new FloatingDateTime(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_create_date=__commonJS({"node_modules/@iarna/toml/lib/create-date.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var DateTime=globalThis.Date;var Date2=class extends DateTime{static{__name(this,"Date")}constructor(value){super(value);this.isDate=true}toISOString(){return`${this.getUTCFullYear()}-${f2(2,this.getUTCMonth()+1)}-${f2(2,this.getUTCDate())}`}};module2.exports=value=>{const date6=new Date2(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_create_time=__commonJS({"node_modules/@iarna/toml/lib/create-time.js"(exports2,module2){"use strict";init_esbuild_shims();var f2=require_format_num();var Time=class extends Date{static{__name(this,"Time")}constructor(value){super(`0000-01-01T${value}Z`);this.isTime=true}toISOString(){return`${f2(2,this.getUTCHours())}:${f2(2,this.getUTCMinutes())}:${f2(2,this.getUTCSeconds())}.${f2(3,this.getUTCMilliseconds())}`}};module2.exports=value=>{const date6=new Time(value);if(isNaN(date6)){throw new TypeError("Invalid Datetime")}else{return date6}}}});var require_toml_parser=__commonJS({"node_modules/@iarna/toml/lib/toml-parser.js"(exports,module){"use strict";init_esbuild_shims();module.exports=makeParserClass(require_parser());module.exports.makeParserClass=makeParserClass;var TomlError=class _TomlError extends Error{static{__name(this,"TomlError")}constructor(msg){super(msg);this.name="TomlError";if(Error.captureStackTrace)Error.captureStackTrace(this,_TomlError);this.fromTOML=true;this.wrapped=null}};TomlError.wrap=err=>{const terr=new TomlError(err.message);terr.code=err.code;terr.wrapped=err;return terr};module.exports.TomlError=TomlError;var createDateTime=require_create_datetime();var createDateTimeFloat=require_create_datetime_float();var createDate=require_create_date();var createTime=require_create_time();var CTRL_I=9;var CTRL_J=10;var CTRL_M=13;var CTRL_CHAR_BOUNDARY=31;var CHAR_SP=32;var CHAR_QUOT=34;var CHAR_NUM=35;var CHAR_APOS=39;var CHAR_PLUS=43;var CHAR_COMMA=44;var CHAR_HYPHEN=45;var CHAR_PERIOD=46;var CHAR_0=48;var CHAR_1=49;var CHAR_7=55;var CHAR_9=57;var CHAR_COLON=58;var CHAR_EQUALS=61;var CHAR_A=65;var CHAR_E=69;var CHAR_F=70;var CHAR_T=84;var CHAR_U=85;var CHAR_Z=90;var CHAR_LOWBAR=95;var CHAR_a=97;var CHAR_b=98;var CHAR_e=101;var CHAR_f=102;var CHAR_i=105;var CHAR_l=108;var CHAR_n=110;var CHAR_o=111;var CHAR_r=114;var CHAR_s=115;var CHAR_t=116;var CHAR_u=117;var CHAR_x=120;var CHAR_z=122;var CHAR_LCUB=123;var CHAR_RCUB=125;var CHAR_LSQB=91;var CHAR_BSOL=92;var CHAR_RSQB=93;var CHAR_DEL=127;var SURROGATE_FIRST=55296;var SURROGATE_LAST=57343;var escapes={[CHAR_b]:"\b",[CHAR_t]:" ",[CHAR_n]:"\n",[CHAR_f]:"\f",[CHAR_r]:"\r",[CHAR_QUOT]:'"',[CHAR_BSOL]:"\\"};function isDigit(cp){return cp>=CHAR_0&&cp<=CHAR_9}__name(isDigit,"isDigit");function isHexit(cp){return cp>=CHAR_A&&cp<=CHAR_F||cp>=CHAR_a&&cp<=CHAR_f||cp>=CHAR_0&&cp<=CHAR_9}__name(isHexit,"isHexit");function isBit(cp){return cp===CHAR_1||cp===CHAR_0}__name(isBit,"isBit");function isOctit(cp){return cp>=CHAR_0&&cp<=CHAR_7}__name(isOctit,"isOctit");function isAlphaNumQuoteHyphen(cp){return cp>=CHAR_A&&cp<=CHAR_Z||cp>=CHAR_a&&cp<=CHAR_z||cp>=CHAR_0&&cp<=CHAR_9||cp===CHAR_APOS||cp===CHAR_QUOT||cp===CHAR_LOWBAR||cp===CHAR_HYPHEN}__name(isAlphaNumQuoteHyphen,"isAlphaNumQuoteHyphen");function isAlphaNumHyphen(cp){return cp>=CHAR_A&&cp<=CHAR_Z||cp>=CHAR_a&&cp<=CHAR_z||cp>=CHAR_0&&cp<=CHAR_9||cp===CHAR_LOWBAR||cp===CHAR_HYPHEN}__name(isAlphaNumHyphen,"isAlphaNumHyphen");var _type=Symbol("type");var _declared=Symbol("declared");var hasOwnProperty=Object.prototype.hasOwnProperty;var defineProperty=Object.defineProperty;var descriptor={configurable:true,enumerable:true,writable:true,value:void 0};function hasKey(obj,key){if(hasOwnProperty.call(obj,key))return true;if(key==="__proto__")defineProperty(obj,"__proto__",descriptor);return false}__name(hasKey,"hasKey");var INLINE_TABLE=Symbol("inline-table");function InlineTable(){return Object.defineProperties({},{[_type]:{value:INLINE_TABLE}})}__name(InlineTable,"InlineTable");function isInlineTable(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INLINE_TABLE}__name(isInlineTable,"isInlineTable");var TABLE=Symbol("table");function Table(){return Object.defineProperties({},{[_type]:{value:TABLE},[_declared]:{value:false,writable:true}})}__name(Table,"Table");function isTable(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===TABLE}__name(isTable,"isTable");var _contentType=Symbol("content-type");var INLINE_LIST=Symbol("inline-list");function InlineList(type){return Object.defineProperties([],{[_type]:{value:INLINE_LIST},[_contentType]:{value:type}})}__name(InlineList,"InlineList");function isInlineList(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INLINE_LIST}__name(isInlineList,"isInlineList");var LIST=Symbol("list");function List(){return Object.defineProperties([],{[_type]:{value:LIST}})}__name(List,"List");function isList(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===LIST}__name(isList,"isList");var _custom;try{const utilInspect=eval("require('util').inspect");_custom=utilInspect.custom}catch(_2){}var _inspect=_custom||"inspect";var BoxedBigInt=class{static{__name(this,"BoxedBigInt")}constructor(value){try{this.value=globalThis.BigInt.asIntN(64,value)}catch(_2){this.value=null}Object.defineProperty(this,_type,{value:INTEGER})}isNaN(){return this.value===null}toString(){return String(this.value)}[_inspect](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}};var INTEGER=Symbol("integer");function Integer(value){let num=Number(value);if(Object.is(num,-0))num=0;if(globalThis.BigInt&&!Number.isSafeInteger(num)){return new BoxedBigInt(value)}else{return Object.defineProperties(new Number(num),{isNaN:{value:__name(function(){return isNaN(this)},"value")},[_type]:{value:INTEGER},[_inspect]:{value:__name(()=>`[Integer: ${value}]`,"value")}})}}__name(Integer,"Integer");function isInteger(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===INTEGER}__name(isInteger,"isInteger");var FLOAT=Symbol("float");function Float(value){return Object.defineProperties(new Number(value),{[_type]:{value:FLOAT},[_inspect]:{value:__name(()=>`[Float: ${value}]`,"value")}})}__name(Float,"Float");function isFloat(obj){if(obj===null||typeof obj!=="object")return false;return obj[_type]===FLOAT}__name(isFloat,"isFloat");function tomlType(value){const type=typeof value;if(type==="object"){if(value===null)return"null";if(value instanceof Date)return"datetime";if(_type in value){switch(value[_type]){case INLINE_TABLE:return"inline-table";case INLINE_LIST:return"inline-list";case TABLE:return"table";case LIST:return"list";case FLOAT:return"float";case INTEGER:return"integer"}}}return type}__name(tomlType,"tomlType");function makeParserClass(Parser3){class TOMLParser extends Parser3{static{__name(this,"TOMLParser")}constructor(){super();this.ctx=this.obj=Table()}atEndOfWord(){return this.char===CHAR_NUM||this.char===CTRL_I||this.char===CHAR_SP||this.atEndOfLine()}atEndOfLine(){return this.char===Parser3.END||this.char===CTRL_J||this.char===CTRL_M}parseStart(){if(this.char===Parser3.END){return null}else if(this.char===CHAR_LSQB){return this.call(this.parseTableOrList)}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else if(isAlphaNumQuoteHyphen(this.char)){return this.callNow(this.parseAssignStatement)}else{throw this.error(new TomlError(`Unknown character "${this.char}"`))}}parseWhitespaceToEOL(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else if(this.char===CHAR_NUM){return this.goto(this.parseComment)}else if(this.char===Parser3.END||this.char===CTRL_J){return this.return()}else{throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"))}}parseAssignStatement(){return this.callNow(this.parseAssign,this.recordAssignStatement)}recordAssignStatement(kv){let target=this.ctx;let finalKey=kv.key.pop();for(let kw2 of kv.key){if(hasKey(target,kw2)&&(!isTable(target[kw2])||target[kw2][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}target=target[kw2]=target[kw2]||Table()}if(hasKey(target,finalKey)){throw this.error(new TomlError("Can't redefine existing key"))}if(isInteger(kv.value)||isFloat(kv.value)){target[finalKey]=kv.value.valueOf()}else{target[finalKey]=kv.value}return this.goto(this.parseWhitespaceToEOL)}parseAssign(){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}recordAssignKeyword(key){if(this.state.resultTable){this.state.resultTable.push(key)}else{this.state.resultTable=[key]}return this.goto(this.parseAssignKeywordPreDot)}parseAssignKeywordPreDot(){if(this.char===CHAR_PERIOD){return this.next(this.parseAssignKeywordPostDot)}else if(this.char!==CHAR_SP&&this.char!==CTRL_I){return this.goto(this.parseAssignEqual)}}parseAssignKeywordPostDot(){if(this.char!==CHAR_SP&&this.char!==CTRL_I){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}}parseAssignEqual(){if(this.char===CHAR_EQUALS){return this.next(this.parseAssignPreValue)}else{throw this.error(new TomlError('Invalid character, expected "="'))}}parseAssignPreValue(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseValue,this.recordAssignValue)}}recordAssignValue(value){return this.returnNow({key:this.state.resultTable,value})}parseComment(){do{if(this.char===Parser3.END||this.char===CTRL_J){return this.return()}}while(this.nextChar())}parseTableOrList(){if(this.char===CHAR_LSQB){this.next(this.parseList)}else{return this.goto(this.parseTable)}}parseTable(){this.ctx=this.obj;return this.goto(this.parseTableNext)}parseTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseKeyword,this.parseTableMore)}}parseTableMore(keyword){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CHAR_RSQB){if(hasKey(this.ctx,keyword)&&(!isTable(this.ctx[keyword])||this.ctx[keyword][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}else{this.ctx=this.ctx[keyword]=this.ctx[keyword]||Table();this.ctx[_declared]=true}return this.next(this.parseWhitespaceToEOL)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,keyword)){this.ctx=this.ctx[keyword]=Table()}else if(isTable(this.ctx[keyword])){this.ctx=this.ctx[keyword]}else if(isList(this.ctx[keyword])){this.ctx=this.ctx[keyword][this.ctx[keyword].length-1]}else{throw this.error(new TomlError("Can't redefine existing key"))}return this.next(this.parseTableNext)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseList(){this.ctx=this.obj;return this.goto(this.parseListNext)}parseListNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else{return this.callNow(this.parseKeyword,this.parseListMore)}}parseListMore(keyword){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CHAR_RSQB){if(!hasKey(this.ctx,keyword)){this.ctx[keyword]=List()}if(isInlineList(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline array"))}else if(isList(this.ctx[keyword])){const next=Table();this.ctx[keyword].push(next);this.ctx=next}else{throw this.error(new TomlError("Can't redefine an existing key"))}return this.next(this.parseListEnd)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,keyword)){this.ctx=this.ctx[keyword]=Table()}else if(isInlineList(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline array"))}else if(isInlineTable(this.ctx[keyword])){throw this.error(new TomlError("Can't extend an inline table"))}else if(isList(this.ctx[keyword])){this.ctx=this.ctx[keyword][this.ctx[keyword].length-1]}else if(isTable(this.ctx[keyword])){this.ctx=this.ctx[keyword]}else{throw this.error(new TomlError("Can't redefine an existing key"))}return this.next(this.parseListNext)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseListEnd(keyword){if(this.char===CHAR_RSQB){return this.next(this.parseWhitespaceToEOL)}else{throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}}parseValue(){if(this.char===Parser3.END){throw this.error(new TomlError("Key without value"))}else if(this.char===CHAR_QUOT){return this.next(this.parseDoubleString)}if(this.char===CHAR_APOS){return this.next(this.parseSingleString)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){return this.goto(this.parseNumberSign)}else if(this.char===CHAR_i){return this.next(this.parseInf)}else if(this.char===CHAR_n){return this.next(this.parseNan)}else if(isDigit(this.char)){return this.goto(this.parseNumberOrDateTime)}else if(this.char===CHAR_t||this.char===CHAR_f){return this.goto(this.parseBoolean)}else if(this.char===CHAR_LSQB){return this.call(this.parseInlineList,this.recordValue)}else if(this.char===CHAR_LCUB){return this.call(this.parseInlineTable,this.recordValue)}else{throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"))}}recordValue(value){return this.returnNow(value)}parseInf(){if(this.char===CHAR_n){return this.next(this.parseInf2)}else{throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}}parseInf2(){if(this.char===CHAR_f){if(this.state.buf==="-"){return this.return(-Infinity)}else{return this.return(Infinity)}}else{throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}}parseNan(){if(this.char===CHAR_a){return this.next(this.parseNan2)}else{throw this.error(new TomlError('Unexpected character, expected "nan"'))}}parseNan2(){if(this.char===CHAR_n){return this.return(NaN)}else{throw this.error(new TomlError('Unexpected character, expected "nan"'))}}parseKeyword(){if(this.char===CHAR_QUOT){return this.next(this.parseBasicString)}else if(this.char===CHAR_APOS){return this.next(this.parseLiteralString)}else{return this.goto(this.parseBareKey)}}parseBareKey(){do{if(this.char===Parser3.END){throw this.error(new TomlError("Key ended without value"))}else if(isAlphaNumHyphen(this.char)){this.consume()}else if(this.state.buf.length===0){throw this.error(new TomlError("Empty bare keys are not allowed"))}else{return this.returnNow()}}while(this.nextChar())}parseSingleString(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiStringMaybe)}else{return this.goto(this.parseLiteralString)}}parseLiteralString(){do{if(this.char===CHAR_APOS){return this.return()}else if(this.atEndOfLine()){throw this.error(new TomlError("Unterminated string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}parseLiteralMultiStringMaybe(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiString)}else{return this.returnNow()}}parseLiteralMultiString(){if(this.char===CTRL_M){return null}else if(this.char===CTRL_J){return this.next(this.parseLiteralMultiStringContent)}else{return this.goto(this.parseLiteralMultiStringContent)}}parseLiteralMultiStringContent(){do{if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiEnd)}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated multi-line string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}parseLiteralMultiEnd(){if(this.char===CHAR_APOS){return this.next(this.parseLiteralMultiEnd2)}else{this.state.buf+="'";return this.goto(this.parseLiteralMultiStringContent)}}parseLiteralMultiEnd2(){if(this.char===CHAR_APOS){return this.return()}else{this.state.buf+="''";return this.goto(this.parseLiteralMultiStringContent)}}parseDoubleString(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiStringMaybe)}else{return this.goto(this.parseBasicString)}}parseBasicString(){do{if(this.char===CHAR_BSOL){return this.call(this.parseEscape,this.recordEscapeReplacement)}else if(this.char===CHAR_QUOT){return this.return()}else if(this.atEndOfLine()){throw this.error(new TomlError("Unterminated string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}recordEscapeReplacement(replacement){this.state.buf+=replacement;return this.goto(this.parseBasicString)}parseMultiStringMaybe(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiString)}else{return this.returnNow()}}parseMultiString(){if(this.char===CTRL_M){return null}else if(this.char===CTRL_J){return this.next(this.parseMultiStringContent)}else{return this.goto(this.parseMultiStringContent)}}parseMultiStringContent(){do{if(this.char===CHAR_BSOL){return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement)}else if(this.char===CHAR_QUOT){return this.next(this.parseMultiEnd)}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated multi-line string"))}else if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M){throw this.errorControlCharInString()}else{this.consume()}}while(this.nextChar())}errorControlCharInString(){let displayCode="\\u00";if(this.char<16){displayCode+="0"}displayCode+=this.char.toString(16);return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`))}recordMultiEscapeReplacement(replacement){this.state.buf+=replacement;return this.goto(this.parseMultiStringContent)}parseMultiEnd(){if(this.char===CHAR_QUOT){return this.next(this.parseMultiEnd2)}else{this.state.buf+='"';return this.goto(this.parseMultiStringContent)}}parseMultiEnd2(){if(this.char===CHAR_QUOT){return this.return()}else{this.state.buf+='""';return this.goto(this.parseMultiStringContent)}}parseMultiEscape(){if(this.char===CTRL_M||this.char===CTRL_J){return this.next(this.parseMultiTrim)}else if(this.char===CHAR_SP||this.char===CTRL_I){return this.next(this.parsePreMultiTrim)}else{return this.goto(this.parseEscape)}}parsePreMultiTrim(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===CTRL_M||this.char===CTRL_J){return this.next(this.parseMultiTrim)}else{throw this.error(new TomlError("Can't escape whitespace"))}}parseMultiTrim(){if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M){return null}else{return this.returnNow()}}parseEscape(){if(this.char in escapes){return this.return(escapes[this.char])}else if(this.char===CHAR_u){return this.call(this.parseSmallUnicode,this.parseUnicodeReturn)}else if(this.char===CHAR_U){return this.call(this.parseLargeUnicode,this.parseUnicodeReturn)}else{throw this.error(new TomlError("Unknown escape character: "+this.char))}}parseUnicodeReturn(char){try{const codePoint=parseInt(char,16);if(codePoint>=SURROGATE_FIRST&&codePoint<=SURROGATE_LAST){throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"))}return this.returnNow(String.fromCodePoint(codePoint))}catch(err){throw this.error(TomlError.wrap(err))}}parseSmallUnicode(){if(!isHexit(this.char)){throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}else{this.consume();if(this.state.buf.length>=4)return this.return()}}parseLargeUnicode(){if(!isHexit(this.char)){throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}else{this.consume();if(this.state.buf.length>=8)return this.return()}}parseNumberSign(){this.consume();return this.next(this.parseMaybeSignedInfOrNan)}parseMaybeSignedInfOrNan(){if(this.char===CHAR_i){return this.next(this.parseInf)}else if(this.char===CHAR_n){return this.next(this.parseNan)}else{return this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}}parseNumberIntegerStart(){if(this.char===CHAR_0){this.consume();return this.next(this.parseNumberIntegerExponentOrDecimal)}else{return this.goto(this.parseNumberInteger)}}parseNumberIntegerExponentOrDecimal(){if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else{return this.returnNow(Integer(this.state.buf))}}parseNumberInteger(){if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseNoUnder(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD||this.char===CHAR_E||this.char===CHAR_e){throw this.error(new TomlError("Unexpected character, expected digit"))}else if(this.atEndOfWord()){throw this.error(new TomlError("Incomplete number"))}return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD){throw this.error(new TomlError("Unexpected character, expected digit"))}else if(this.atEndOfWord()){throw this.error(new TomlError("Incomplete number"))}return this.returnNow()}parseNumberFloat(){if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else{return this.returnNow(Float(this.state.buf))}}parseNumberExponentSign(){if(isDigit(this.char)){return this.goto(this.parseNumberExponent)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.call(this.parseNoUnder,this.parseNumberExponent)}else{throw this.error(new TomlError("Unexpected character, expected -, + or digit"))}}parseNumberExponent(){if(isDigit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder)}else{return this.returnNow(Float(this.state.buf))}}parseNumberOrDateTime(){if(this.char===CHAR_0){this.consume();return this.next(this.parseNumberBaseOrDateTime)}else{return this.goto(this.parseNumberOrDateTimeOnly)}}parseNumberOrDateTimeOnly(){if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnder,this.parseNumberInteger)}else if(isDigit(this.char)){this.consume();if(this.state.buf.length>4)this.next(this.parseNumberInteger)}else if(this.char===CHAR_E||this.char===CHAR_e){this.consume();return this.next(this.parseNumberExponentSign)}else if(this.char===CHAR_PERIOD){this.consume();return this.call(this.parseNoUnder,this.parseNumberFloat)}else if(this.char===CHAR_HYPHEN){return this.goto(this.parseDateTime)}else if(this.char===CHAR_COLON){return this.goto(this.parseOnlyTimeHour)}else{return this.returnNow(Integer(this.state.buf))}}parseDateTimeOnly(){if(this.state.buf.length<4){if(isDigit(this.char)){return this.consume()}else if(this.char===CHAR_COLON){return this.goto(this.parseOnlyTimeHour)}else{throw this.error(new TomlError("Expected digit while parsing year part of a date"))}}else{if(this.char===CHAR_HYPHEN){return this.goto(this.parseDateTime)}else{throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"))}}}parseNumberBaseOrDateTime(){if(this.char===CHAR_b){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin)}else if(this.char===CHAR_o){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct)}else if(this.char===CHAR_x){this.consume();return this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex)}else if(this.char===CHAR_PERIOD){return this.goto(this.parseNumberInteger)}else if(isDigit(this.char)){return this.goto(this.parseDateTimeOnly)}else{return this.returnNow(Integer(this.state.buf))}}parseIntegerHex(){if(isHexit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseIntegerOct(){if(isOctit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseIntegerBin(){if(isBit(this.char)){this.consume()}else if(this.char===CHAR_LOWBAR){return this.call(this.parseNoUnderHexOctBinLiteral)}else{const result=Integer(this.state.buf);if(result.isNaN()){throw this.error(new TomlError("Invalid number"))}else{return this.returnNow(result)}}}parseDateTime(){if(this.state.buf.length<4){throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"))}this.state.result=this.state.buf;this.state.buf="";return this.next(this.parseDateMonth)}parseDateMonth(){if(this.char===CHAR_HYPHEN){if(this.state.buf.length<2){throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"))}this.state.result+="-"+this.state.buf;this.state.buf="";return this.next(this.parseDateDay)}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseDateDay(){if(this.char===CHAR_T||this.char===CHAR_SP){if(this.state.buf.length<2){throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"))}this.state.result+="-"+this.state.buf;this.state.buf="";return this.next(this.parseStartTimeHour)}else if(this.atEndOfWord()){return this.returnNow(createDate(this.state.result+"-"+this.state.buf))}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseStartTimeHour(){if(this.atEndOfWord()){return this.returnNow(createDate(this.state.result))}else{return this.goto(this.parseTimeHour)}}parseTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2){throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"))}this.state.result+="T"+this.state.buf;this.state.buf="";return this.next(this.parseTimeMin)}else if(isDigit(this.char)){this.consume()}else{throw this.error(new TomlError("Incomplete datetime"))}}parseTimeMin(){if(this.state.buf.length<2&&isDigit(this.char)){this.consume()}else if(this.state.buf.length===2&&this.char===CHAR_COLON){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseTimeSec)}else{throw this.error(new TomlError("Incomplete datetime"))}}parseTimeSec(){if(isDigit(this.char)){this.consume();if(this.state.buf.length===2){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseTimeZoneOrFraction)}}else{throw this.error(new TomlError("Incomplete datetime"))}}parseOnlyTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2){throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"))}this.state.result=this.state.buf;this.state.buf="";return this.next(this.parseOnlyTimeMin)}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeMin(){if(this.state.buf.length<2&&isDigit(this.char)){this.consume()}else if(this.state.buf.length===2&&this.char===CHAR_COLON){this.state.result+=":"+this.state.buf;this.state.buf="";return this.next(this.parseOnlyTimeSec)}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeSec(){if(isDigit(this.char)){this.consume();if(this.state.buf.length===2){return this.next(this.parseOnlyTimeFractionMaybe)}}else{throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeFractionMaybe(){this.state.result+=":"+this.state.buf;if(this.char===CHAR_PERIOD){this.state.buf="";this.next(this.parseOnlyTimeFraction)}else{return this.return(createTime(this.state.result))}}parseOnlyTimeFraction(){if(isDigit(this.char)){this.consume()}else if(this.atEndOfWord()){if(this.state.buf.length===0)throw this.error(new TomlError("Expected digit in milliseconds"));return this.returnNow(createTime(this.state.result+"."+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseTimeZoneOrFraction(){if(this.char===CHAR_PERIOD){this.consume();this.next(this.parseDateTimeFraction)}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.next(this.parseTimeZoneHour)}else if(this.char===CHAR_Z){this.consume();return this.return(createDateTime(this.state.result+this.state.buf))}else if(this.atEndOfWord()){return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseDateTimeFraction(){if(isDigit(this.char)){this.consume()}else if(this.state.buf.length===1){throw this.error(new TomlError("Expected digit in milliseconds"))}else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS){this.consume();this.next(this.parseTimeZoneHour)}else if(this.char===CHAR_Z){this.consume();return this.return(createDateTime(this.state.result+this.state.buf))}else if(this.atEndOfWord()){return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseTimeZoneHour(){if(isDigit(this.char)){this.consume();if(/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else{throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}}parseTimeZoneSep(){if(this.char===CHAR_COLON){this.consume();this.next(this.parseTimeZoneMin)}else{throw this.error(new TomlError("Unexpected character in datetime, expected colon"))}}parseTimeZoneMin(){if(isDigit(this.char)){this.consume();if(/\d\d$/.test(this.state.buf))return this.return(createDateTime(this.state.result+this.state.buf))}else{throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}}parseBoolean(){if(this.char===CHAR_t){this.consume();return this.next(this.parseTrue_r)}else if(this.char===CHAR_f){this.consume();return this.next(this.parseFalse_a)}}parseTrue_r(){if(this.char===CHAR_r){this.consume();return this.next(this.parseTrue_u)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseTrue_u(){if(this.char===CHAR_u){this.consume();return this.next(this.parseTrue_e)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseTrue_e(){if(this.char===CHAR_e){return this.return(true)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_a(){if(this.char===CHAR_a){this.consume();return this.next(this.parseFalse_l)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_l(){if(this.char===CHAR_l){this.consume();return this.next(this.parseFalse_s)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_s(){if(this.char===CHAR_s){this.consume();return this.next(this.parseFalse_e)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseFalse_e(){if(this.char===CHAR_e){return this.return(false)}else{throw this.error(new TomlError("Invalid boolean, expected true or false"))}}parseInlineList(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J){return null}else if(this.char===Parser3.END){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CHAR_RSQB){return this.return(this.state.resultArr||InlineList())}else{return this.callNow(this.parseValue,this.recordInlineListValue)}}recordInlineListValue(value){if(this.state.resultArr){const listType=this.state.resultArr[_contentType];const valueType=tomlType(value);if(listType!==valueType){throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`))}}else{this.state.resultArr=InlineList(tomlType(value))}if(isFloat(value)||isInteger(value)){this.state.resultArr.push(value.valueOf())}else{this.state.resultArr.push(value)}return this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J){return null}else if(this.char===CHAR_NUM){return this.call(this.parseComment)}else if(this.char===CHAR_COMMA){return this.next(this.parseInlineList)}else if(this.char===CHAR_RSQB){return this.goto(this.parseInlineList)}else{throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}parseInlineTable(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===Parser3.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_RCUB){return this.return(this.state.resultTable||InlineTable())}else{if(!this.state.resultTable)this.state.resultTable=InlineTable();return this.callNow(this.parseAssign,this.recordInlineTableValue)}}recordInlineTableValue(kv){let target=this.state.resultTable;let finalKey=kv.key.pop();for(let kw2 of kv.key){if(hasKey(target,kw2)&&(!isTable(target[kw2])||target[kw2][_declared])){throw this.error(new TomlError("Can't redefine existing key"))}target=target[kw2]=target[kw2]||Table()}if(hasKey(target,finalKey)){throw this.error(new TomlError("Can't redefine existing key"))}if(isInteger(kv.value)||isFloat(kv.value)){target[finalKey]=kv.value.valueOf()}else{target[finalKey]=kv.value}return this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I){return null}else if(this.char===Parser3.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M){throw this.error(new TomlError("Unterminated inline array"))}else if(this.char===CHAR_COMMA){return this.next(this.parseInlineTable)}else if(this.char===CHAR_RCUB){return this.goto(this.parseInlineTable)}else{throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}}return TOMLParser}__name(makeParserClass,"makeParserClass")}});var require_parse_pretty_error=__commonJS({"node_modules/@iarna/toml/parse-pretty-error.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=prettyError;function prettyError(err,buf){if(err.pos==null||err.line==null)return err;let msg=err.message;msg+=` at row ${err.line+1}, col ${err.col+1}, pos ${err.pos}:
4
4
  `;if(buf&&buf.split){const lines=buf.split(/\n/);const lineNumWidth=String(Math.min(lines.length,err.line+3)).length;let linePadding=" ";while(linePadding.length<lineNumWidth)linePadding+=" ";for(let ii2=Math.max(0,err.line-1);ii2<Math.min(lines.length,err.line+2);++ii2){let lineNum=String(ii2+1);if(lineNum.length<lineNumWidth)lineNum=" "+lineNum;if(err.line===ii2){msg+=lineNum+"> "+lines[ii2]+"\n";msg+=linePadding+" ";for(let hh=0;hh<err.col;++hh){msg+=" "}msg+="^\n"}else{msg+=lineNum+": "+lines[ii2]+"\n"}}}err.message=msg+"\n";return err}__name(prettyError,"prettyError")}});var require_parse_string=__commonJS({"node_modules/@iarna/toml/parse-string.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=parseString;var TOMLParser=require_toml_parser();var prettyError=require_parse_pretty_error();function parseString(str){if(globalThis.Buffer&&globalThis.Buffer.isBuffer(str)){str=str.toString("utf8")}const parser2=new TOMLParser;try{parser2.parse(str);return parser2.finish()}catch(err){throw prettyError(err,str)}}__name(parseString,"parseString")}});var require_parse_async=__commonJS({"node_modules/@iarna/toml/parse-async.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=parseAsync5;var TOMLParser=require_toml_parser();var prettyError=require_parse_pretty_error();function parseAsync5(str,opts){if(!opts)opts={};const index=0;const blocksize=opts.blocksize||40960;const parser2=new TOMLParser;return new Promise((resolve36,reject)=>{setImmediate(parseAsyncNext,index,blocksize,resolve36,reject)});function parseAsyncNext(index2,blocksize2,resolve36,reject){if(index2>=str.length){try{return resolve36(parser2.finish())}catch(err){return reject(prettyError(err,str))}}try{parser2.parse(str.slice(index2,index2+blocksize2));setImmediate(parseAsyncNext,index2+blocksize2,blocksize2,resolve36,reject)}catch(err){reject(prettyError(err,str))}}__name(parseAsyncNext,"parseAsyncNext")}__name(parseAsync5,"parseAsync")}});var require_parse_stream=__commonJS({"node_modules/@iarna/toml/parse-stream.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=parseStream;var stream=__require("stream");var TOMLParser=require_toml_parser();function parseStream(stm){if(stm){return parseReadable(stm)}else{return parseTransform(stm)}}__name(parseStream,"parseStream");function parseReadable(stm){const parser2=new TOMLParser;stm.setEncoding("utf8");return new Promise((resolve36,reject)=>{let readable;let ended=false;let errored=false;function finish(){ended=true;if(readable)return;try{resolve36(parser2.finish())}catch(err){reject(err)}}__name(finish,"finish");function error3(err){errored=true;reject(err)}__name(error3,"error");stm.once("end",finish);stm.once("error",error3);readNext();function readNext(){readable=true;let data2;while((data2=stm.read())!==null){try{parser2.parse(data2)}catch(err){return error3(err)}}readable=false;if(ended)return finish();if(errored)return;stm.once("readable",readNext)}__name(readNext,"readNext")})}__name(parseReadable,"parseReadable");function parseTransform(){const parser2=new TOMLParser;return new stream.Transform({objectMode:true,transform(chunk,encoding,cb){try{parser2.parse(chunk.toString(encoding))}catch(err){this.emit("error",err)}cb()},flush(cb){try{this.push(parser2.finish())}catch(err){this.emit("error",err)}cb()}})}__name(parseTransform,"parseTransform")}});var require_parse2=__commonJS({"node_modules/@iarna/toml/parse.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=require_parse_string();module2.exports.async=require_parse_async();module2.exports.stream=require_parse_stream();module2.exports.prettyError=require_parse_pretty_error()}});var require_stringify=__commonJS({"node_modules/@iarna/toml/stringify.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=stringify2;module2.exports.value=stringifyInline;function stringify2(obj){if(obj===null)throw typeError("null");if(obj===void 0)throw typeError("undefined");if(typeof obj!=="object")throw typeError(typeof obj);if(typeof obj.toJSON==="function")obj=obj.toJSON();if(obj==null)return null;const type=tomlType2(obj);if(type!=="table")throw typeError(type);return stringifyObject("","",obj)}__name(stringify2,"stringify");function typeError(type){return new Error("Can only stringify objects, not "+type)}__name(typeError,"typeError");function arrayOneTypeError(){return new Error("Array values can't have mixed types")}__name(arrayOneTypeError,"arrayOneTypeError");function getInlineKeys(obj){return Object.keys(obj).filter(key=>isInline(obj[key]))}__name(getInlineKeys,"getInlineKeys");function getComplexKeys(obj){return Object.keys(obj).filter(key=>!isInline(obj[key]))}__name(getComplexKeys,"getComplexKeys");function toJSON(obj){let nobj=Array.isArray(obj)?[]:Object.prototype.hasOwnProperty.call(obj,"__proto__")?{["__proto__"]:void 0}:{};for(let prop of Object.keys(obj)){if(obj[prop]&&typeof obj[prop].toJSON==="function"&&!("toISOString"in obj[prop])){nobj[prop]=obj[prop].toJSON()}else{nobj[prop]=obj[prop]}}return nobj}__name(toJSON,"toJSON");function stringifyObject(prefix2,indent,obj){obj=toJSON(obj);var inlineKeys;var complexKeys;inlineKeys=getInlineKeys(obj);complexKeys=getComplexKeys(obj);var result=[];var inlineIndent=indent||"";inlineKeys.forEach(key=>{var type=tomlType2(obj[key]);if(type!=="undefined"&&type!=="null"){result.push(inlineIndent+stringifyKey(key)+" = "+stringifyAnyInline(obj[key],true))}});if(result.length>0)result.push("");var complexIndent=prefix2&&inlineKeys.length>0?indent+" ":"";complexKeys.forEach(key=>{result.push(stringifyComplex(prefix2,complexIndent,key,obj[key]))});return result.join("\n")}__name(stringifyObject,"stringifyObject");function isInline(value){switch(tomlType2(value)){case"undefined":case"null":case"integer":case"nan":case"float":case"boolean":case"string":case"datetime":return true;case"array":return value.length===0||tomlType2(value[0])!=="table";case"table":return Object.keys(value).length===0;default:return false}}__name(isInline,"isInline");function tomlType2(value){if(value===void 0){return"undefined"}else if(value===null){return"null"}else if(typeof value==="bigint"||Number.isInteger(value)&&!Object.is(value,-0)){return"integer"}else if(typeof value==="number"){return"float"}else if(typeof value==="boolean"){return"boolean"}else if(typeof value==="string"){return"string"}else if("toISOString"in value){return isNaN(value)?"undefined":"datetime"}else if(Array.isArray(value)){return"array"}else{return"table"}}__name(tomlType2,"tomlType");function stringifyKey(key){var keyStr=String(key);if(/^[-A-Za-z0-9_]+$/.test(keyStr)){return keyStr}else{return stringifyBasicString(keyStr)}}__name(stringifyKey,"stringifyKey");function stringifyBasicString(str){return'"'+escapeString(str).replace(/"/g,'\\"')+'"'}__name(stringifyBasicString,"stringifyBasicString");function stringifyLiteralString(str){return"'"+str+"'"}__name(stringifyLiteralString,"stringifyLiteralString");function numpad(num,str){while(str.length<num)str="0"+str;return str}__name(numpad,"numpad");function escapeString(str){return str.replace(/\\/g,"\\\\").replace(/[\b]/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/([\u0000-\u001f\u007f])/,c=>"\\u"+numpad(4,c.codePointAt(0).toString(16)))}__name(escapeString,"escapeString");function stringifyMultilineString(str){let escaped=str.split(/\n/).map(str2=>{return escapeString(str2).replace(/"(?="")/g,'\\"')}).join("\n");if(escaped.slice(-1)==='"')escaped+="\\\n";return'"""\n'+escaped+'"""'}__name(stringifyMultilineString,"stringifyMultilineString");function stringifyAnyInline(value,multilineOk){let type=tomlType2(value);if(type==="string"){if(multilineOk&&/\n/.test(value)){type="string-multiline"}else if(!/[\b\t\n\f\r']/.test(value)&&/"/.test(value)){type="string-literal"}}return stringifyInline(value,type)}__name(stringifyAnyInline,"stringifyAnyInline");function stringifyInline(value,type){if(!type)type=tomlType2(value);switch(type){case"string-multiline":return stringifyMultilineString(value);case"string":return stringifyBasicString(value);case"string-literal":return stringifyLiteralString(value);case"integer":return stringifyInteger(value);case"float":return stringifyFloat(value);case"boolean":return stringifyBoolean(value);case"datetime":return stringifyDatetime(value);case"array":return stringifyInlineArray(value.filter(_2=>tomlType2(_2)!=="null"&&tomlType2(_2)!=="undefined"&&tomlType2(_2)!=="nan"));case"table":return stringifyInlineTable(value);default:throw typeError(type)}}__name(stringifyInline,"stringifyInline");function stringifyInteger(value){return String(value).replace(/\B(?=(\d{3})+(?!\d))/g,"_")}__name(stringifyInteger,"stringifyInteger");function stringifyFloat(value){if(value===Infinity){return"inf"}else if(value===-Infinity){return"-inf"}else if(Object.is(value,NaN)){return"nan"}else if(Object.is(value,-0)){return"-0.0"}var chunks=String(value).split(".");var int3=chunks[0];var dec=chunks[1]||0;return stringifyInteger(int3)+"."+dec}__name(stringifyFloat,"stringifyFloat");function stringifyBoolean(value){return String(value)}__name(stringifyBoolean,"stringifyBoolean");function stringifyDatetime(value){return value.toISOString()}__name(stringifyDatetime,"stringifyDatetime");function isNumber(type){return type==="float"||type==="integer"}__name(isNumber,"isNumber");function arrayType(values){var contentType2=tomlType2(values[0]);if(values.every(_2=>tomlType2(_2)===contentType2))return contentType2;if(values.every(_2=>isNumber(tomlType2(_2))))return"float";return"mixed"}__name(arrayType,"arrayType");function validateArray(values){const type=arrayType(values);if(type==="mixed"){throw arrayOneTypeError()}return type}__name(validateArray,"validateArray");function stringifyInlineArray(values){values=toJSON(values);const type=validateArray(values);var result="[";var stringified=values.map(_2=>stringifyInline(_2,type));if(stringified.join(", ").length>60||/\n/.test(stringified)){result+="\n "+stringified.join(",\n ")+"\n"}else{result+=" "+stringified.join(", ")+(stringified.length>0?" ":"")}return result+"]"}__name(stringifyInlineArray,"stringifyInlineArray");function stringifyInlineTable(value){value=toJSON(value);var result=[];Object.keys(value).forEach(key=>{result.push(stringifyKey(key)+" = "+stringifyAnyInline(value[key],false))});return"{ "+result.join(", ")+(result.length>0?" ":"")+"}"}__name(stringifyInlineTable,"stringifyInlineTable");function stringifyComplex(prefix2,indent,key,value){var valueType=tomlType2(value);if(valueType==="array"){return stringifyArrayOfTables(prefix2,indent,key,value)}else if(valueType==="table"){return stringifyComplexTable(prefix2,indent,key,value)}else{throw typeError(valueType)}}__name(stringifyComplex,"stringifyComplex");function stringifyArrayOfTables(prefix2,indent,key,values){values=toJSON(values);validateArray(values);var firstValueType=tomlType2(values[0]);if(firstValueType!=="table")throw typeError(firstValueType);var fullKey=prefix2+stringifyKey(key);var result="";values.forEach(table=>{if(result.length>0)result+="\n";result+=indent+"[["+fullKey+"]]\n";result+=stringifyObject(fullKey+".",indent,table)});return result}__name(stringifyArrayOfTables,"stringifyArrayOfTables");function stringifyComplexTable(prefix2,indent,key,value){var fullKey=prefix2+stringifyKey(key);var result="";if(getInlineKeys(value).length>0){result+=indent+"["+fullKey+"]\n"}return result+stringifyObject(fullKey+".",indent,value)}__name(stringifyComplexTable,"stringifyComplexTable")}});var require_toml=__commonJS({"node_modules/@iarna/toml/toml.js"(exports2){"use strict";init_esbuild_shims();exports2.parse=require_parse2();exports2.stringify=require_stringify()}});var require_pend=__commonJS({"node_modules/pend/index.js"(exports2,module2){init_esbuild_shims();module2.exports=Pend;function Pend(){this.pending=0;this.max=Infinity;this.listeners=[];this.waiting=[];this.error=null}__name(Pend,"Pend");Pend.prototype.go=function(fn){if(this.pending<this.max){pendGo(this,fn)}else{this.waiting.push(fn)}};Pend.prototype.wait=function(cb){if(this.pending===0){cb(this.error)}else{this.listeners.push(cb)}};Pend.prototype.hold=function(){return pendHold(this)};function pendHold(self2){self2.pending+=1;var called=false;return onCb;function onCb(err){if(called)throw new Error("callback called twice");called=true;self2.error=self2.error||err;self2.pending-=1;if(self2.waiting.length>0&&self2.pending<self2.max){pendGo(self2,self2.waiting.shift())}else if(self2.pending===0){var listeners=self2.listeners;self2.listeners=[];listeners.forEach(cbListener)}}__name(onCb,"onCb");function cbListener(listener){listener(self2.error)}__name(cbListener,"cbListener")}__name(pendHold,"pendHold");function pendGo(self2,fn){fn(pendHold(self2))}__name(pendGo,"pendGo")}});var require_fd_slicer=__commonJS({"node_modules/fd-slicer/index.js"(exports2){init_esbuild_shims();var fs81=__require("fs");var util=__require("util");var stream=__require("stream");var Readable2=stream.Readable;var Writable=stream.Writable;var PassThrough3=stream.PassThrough;var Pend=require_pend();var EventEmitter7=__require("events").EventEmitter;exports2.createFromBuffer=createFromBuffer;exports2.createFromFd=createFromFd;exports2.BufferSlicer=BufferSlicer;exports2.FdSlicer=FdSlicer;util.inherits(FdSlicer,EventEmitter7);function FdSlicer(fd,options2){options2=options2||{};EventEmitter7.call(this);this.fd=fd;this.pend=new Pend;this.pend.max=1;this.refCount=0;this.autoClose=!!options2.autoClose}__name(FdSlicer,"FdSlicer");FdSlicer.prototype.read=function(buffer,offset2,length,position,callback){var self2=this;self2.pend.go(function(cb){fs81.read(self2.fd,buffer,offset2,length,position,function(err,bytesRead,buffer2){cb();callback(err,bytesRead,buffer2)})})};FdSlicer.prototype.write=function(buffer,offset2,length,position,callback){var self2=this;self2.pend.go(function(cb){fs81.write(self2.fd,buffer,offset2,length,position,function(err,written,buffer2){cb();callback(err,written,buffer2)})})};FdSlicer.prototype.createReadStream=function(options2){return new ReadStream(this,options2)};FdSlicer.prototype.createWriteStream=function(options2){return new WriteStream(this,options2)};FdSlicer.prototype.ref=function(){this.refCount+=1};FdSlicer.prototype.unref=function(){var self2=this;self2.refCount-=1;if(self2.refCount>0)return;if(self2.refCount<0)throw new Error("invalid unref");if(self2.autoClose){fs81.close(self2.fd,onCloseDone)}function onCloseDone(err){if(err){self2.emit("error",err)}else{self2.emit("close")}}__name(onCloseDone,"onCloseDone")};util.inherits(ReadStream,Readable2);function ReadStream(context2,options2){options2=options2||{};Readable2.call(this,options2);this.context=context2;this.context.ref();this.start=options2.start||0;this.endOffset=options2.end;this.pos=this.start;this.destroyed=false}__name(ReadStream,"ReadStream");ReadStream.prototype._read=function(n){var self2=this;if(self2.destroyed)return;var toRead=Math.min(self2._readableState.highWaterMark,n);if(self2.endOffset!=null){toRead=Math.min(toRead,self2.endOffset-self2.pos)}if(toRead<=0){self2.destroyed=true;self2.push(null);self2.context.unref();return}self2.context.pend.go(function(cb){if(self2.destroyed)return cb();var buffer=new Buffer(toRead);fs81.read(self2.context.fd,buffer,0,toRead,self2.pos,function(err,bytesRead){if(err){self2.destroy(err)}else if(bytesRead===0){self2.destroyed=true;self2.push(null);self2.context.unref()}else{self2.pos+=bytesRead;self2.push(buffer.slice(0,bytesRead))}cb()})})};ReadStream.prototype.destroy=function(err){if(this.destroyed)return;err=err||new Error("stream destroyed");this.destroyed=true;this.emit("error",err);this.context.unref()};util.inherits(WriteStream,Writable);function WriteStream(context2,options2){options2=options2||{};Writable.call(this,options2);this.context=context2;this.context.ref();this.start=options2.start||0;this.endOffset=options2.end==null?Infinity:+options2.end;this.bytesWritten=0;this.pos=this.start;this.destroyed=false;this.on("finish",this.destroy.bind(this))}__name(WriteStream,"WriteStream");WriteStream.prototype._write=function(buffer,encoding,callback){var self2=this;if(self2.destroyed)return;if(self2.pos+buffer.length>self2.endOffset){var err=new Error("maximum file length exceeded");err.code="ETOOBIG";self2.destroy();callback(err);return}self2.context.pend.go(function(cb){if(self2.destroyed)return cb();fs81.write(self2.context.fd,buffer,0,buffer.length,self2.pos,function(err2,bytes){if(err2){self2.destroy();cb();callback(err2)}else{self2.bytesWritten+=bytes;self2.pos+=bytes;self2.emit("progress");cb();callback()}})})};WriteStream.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=true;this.context.unref()};util.inherits(BufferSlicer,EventEmitter7);function BufferSlicer(buffer,options2){EventEmitter7.call(this);options2=options2||{};this.refCount=0;this.buffer=buffer;this.maxChunkSize=options2.maxChunkSize||Number.MAX_SAFE_INTEGER}__name(BufferSlicer,"BufferSlicer");BufferSlicer.prototype.read=function(buffer,offset2,length,position,callback){var end=position+length;var delta=end-this.buffer.length;var written=delta>0?delta:length;this.buffer.copy(buffer,offset2,position,end);setImmediate(function(){callback(null,written)})};BufferSlicer.prototype.write=function(buffer,offset2,length,position,callback){buffer.copy(this.buffer,position,offset2,offset2+length);setImmediate(function(){callback(null,length,buffer)})};BufferSlicer.prototype.createReadStream=function(options2){options2=options2||{};var readStream=new PassThrough3(options2);readStream.destroyed=false;readStream.start=options2.start||0;readStream.endOffset=options2.end;readStream.pos=readStream.endOffset||this.buffer.length;var entireSlice=this.buffer.slice(readStream.start,readStream.pos);var offset2=0;while(true){var nextOffset=offset2+this.maxChunkSize;if(nextOffset>=entireSlice.length){if(offset2<entireSlice.length){readStream.write(entireSlice.slice(offset2,entireSlice.length))}break}readStream.write(entireSlice.slice(offset2,nextOffset));offset2=nextOffset}readStream.end();readStream.destroy=function(){readStream.destroyed=true};return readStream};BufferSlicer.prototype.createWriteStream=function(options2){var bufferSlicer=this;options2=options2||{};var writeStream=new Writable(options2);writeStream.start=options2.start||0;writeStream.endOffset=options2.end==null?this.buffer.length:+options2.end;writeStream.bytesWritten=0;writeStream.pos=writeStream.start;writeStream.destroyed=false;writeStream._write=function(buffer,encoding,callback){if(writeStream.destroyed)return;var end=writeStream.pos+buffer.length;if(end>writeStream.endOffset){var err=new Error("maximum file length exceeded");err.code="ETOOBIG";writeStream.destroyed=true;callback(err);return}buffer.copy(bufferSlicer.buffer,writeStream.pos,0,buffer.length);writeStream.bytesWritten+=buffer.length;writeStream.pos=end;writeStream.emit("progress");callback()};writeStream.destroy=function(){writeStream.destroyed=true};return writeStream};BufferSlicer.prototype.ref=function(){this.refCount+=1};BufferSlicer.prototype.unref=function(){this.refCount-=1;if(this.refCount<0){throw new Error("invalid unref")}};function createFromBuffer(buffer,options2){return new BufferSlicer(buffer,options2)}__name(createFromBuffer,"createFromBuffer");function createFromFd(fd,options2){return new FdSlicer(fd,options2)}__name(createFromFd,"createFromFd")}});var require_buffer_crc32=__commonJS({"node_modules/buffer-crc32/index.js"(exports2,module2){init_esbuild_shims();var Buffer3=__require("buffer").Buffer;var CRC_TABLE=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array!=="undefined"){CRC_TABLE=new Int32Array(CRC_TABLE)}function ensureBuffer(input){if(Buffer3.isBuffer(input)){return input}var hasNewBufferAPI=typeof Buffer3.alloc==="function"&&typeof Buffer3.from==="function";if(typeof input==="number"){return hasNewBufferAPI?Buffer3.alloc(input):new Buffer3(input)}else if(typeof input==="string"){return hasNewBufferAPI?Buffer3.from(input):new Buffer3(input)}else{throw new Error("input must be buffer, number, or string, received "+typeof input)}}__name(ensureBuffer,"ensureBuffer");function bufferizeInt(num){var tmp=ensureBuffer(4);tmp.writeInt32BE(num,0);return tmp}__name(bufferizeInt,"bufferizeInt");function _crc32(buf,previous){buf=ensureBuffer(buf);if(Buffer3.isBuffer(previous)){previous=previous.readUInt32BE(0)}var crc=~~previous^-1;for(var n=0;n<buf.length;n++){crc=CRC_TABLE[(crc^buf[n])&255]^crc>>>8}return crc^-1}__name(_crc32,"_crc32");function crc32(){return bufferizeInt(_crc32.apply(null,arguments))}__name(crc32,"crc32");crc32.signed=function(){return _crc32.apply(null,arguments)};crc32.unsigned=function(){return _crc32.apply(null,arguments)>>>0};module2.exports=crc32}});var require_yauzl=__commonJS({"packages/core/node_modules/yauzl/index.js"(exports2){init_esbuild_shims();var fs81=__require("fs");var zlib=__require("zlib");var fd_slicer=require_fd_slicer();var crc32=require_buffer_crc32();var util=__require("util");var EventEmitter7=__require("events").EventEmitter;var Transform=__require("stream").Transform;var PassThrough3=__require("stream").PassThrough;var Writable=__require("stream").Writable;exports2.open=open8;exports2.fromFd=fromFd;exports2.fromBuffer=fromBuffer;exports2.fromRandomAccessReader=fromRandomAccessReader;exports2.dosDateTimeToDate=dosDateTimeToDate;exports2.validateFileName=validateFileName;exports2.ZipFile=ZipFile;exports2.Entry=Entry;exports2.RandomAccessReader=RandomAccessReader;function open8(path89,options2,callback){if(typeof options2==="function"){callback=options2;options2=null}if(options2==null)options2={};if(options2.autoClose==null)options2.autoClose=true;if(options2.lazyEntries==null)options2.lazyEntries=false;if(options2.decodeStrings==null)options2.decodeStrings=true;if(options2.validateEntrySizes==null)options2.validateEntrySizes=true;if(options2.strictFileNames==null)options2.strictFileNames=false;if(callback==null)callback=defaultCallback;fs81.open(path89,"r",function(err,fd){if(err)return callback(err);fromFd(fd,options2,function(err2,zipfile){if(err2)fs81.close(fd,defaultCallback);callback(err2,zipfile)})})}__name(open8,"open");function fromFd(fd,options2,callback){if(typeof options2==="function"){callback=options2;options2=null}if(options2==null)options2={};if(options2.autoClose==null)options2.autoClose=false;if(options2.lazyEntries==null)options2.lazyEntries=false;if(options2.decodeStrings==null)options2.decodeStrings=true;if(options2.validateEntrySizes==null)options2.validateEntrySizes=true;if(options2.strictFileNames==null)options2.strictFileNames=false;if(callback==null)callback=defaultCallback;fs81.fstat(fd,function(err,stats){if(err)return callback(err);var reader=fd_slicer.createFromFd(fd,{autoClose:true});fromRandomAccessReader(reader,stats.size,options2,callback)})}__name(fromFd,"fromFd");function fromBuffer(buffer,options2,callback){if(typeof options2==="function"){callback=options2;options2=null}if(options2==null)options2={};options2.autoClose=false;if(options2.lazyEntries==null)options2.lazyEntries=false;if(options2.decodeStrings==null)options2.decodeStrings=true;if(options2.validateEntrySizes==null)options2.validateEntrySizes=true;if(options2.strictFileNames==null)options2.strictFileNames=false;var reader=fd_slicer.createFromBuffer(buffer,{maxChunkSize:65536});fromRandomAccessReader(reader,buffer.length,options2,callback)}__name(fromBuffer,"fromBuffer");function fromRandomAccessReader(reader,totalSize,options2,callback){if(typeof options2==="function"){callback=options2;options2=null}if(options2==null)options2={};if(options2.autoClose==null)options2.autoClose=true;if(options2.lazyEntries==null)options2.lazyEntries=false;if(options2.decodeStrings==null)options2.decodeStrings=true;var decodeStrings=!!options2.decodeStrings;if(options2.validateEntrySizes==null)options2.validateEntrySizes=true;if(options2.strictFileNames==null)options2.strictFileNames=false;if(callback==null)callback=defaultCallback;if(typeof totalSize!=="number")throw new Error("expected totalSize parameter to be a number");if(totalSize>Number.MAX_SAFE_INTEGER){throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.")}reader.ref();var eocdrWithoutCommentSize=22;var maxCommentSize=65535;var bufferSize=Math.min(eocdrWithoutCommentSize+maxCommentSize,totalSize);var buffer=newBuffer(bufferSize);var bufferReadStart=totalSize-buffer.length;readAndAssertNoEof(reader,buffer,0,bufferSize,bufferReadStart,function(err){if(err)return callback(err);for(var i=bufferSize-eocdrWithoutCommentSize;i>=0;i-=1){if(buffer.readUInt32LE(i)!==101010256)continue;var eocdrBuffer=buffer.slice(i);var diskNumber=eocdrBuffer.readUInt16LE(4);if(diskNumber!==0){return callback(new Error("multi-disk zip files are not supported: found disk number: "+diskNumber))}var entryCount=eocdrBuffer.readUInt16LE(10);var centralDirectoryOffset=eocdrBuffer.readUInt32LE(16);var commentLength=eocdrBuffer.readUInt16LE(20);var expectedCommentLength=eocdrBuffer.length-eocdrWithoutCommentSize;if(commentLength!==expectedCommentLength){return callback(new Error("invalid comment length. expected: "+expectedCommentLength+". found: "+commentLength))}var comment=decodeStrings?decodeBuffer(eocdrBuffer,22,eocdrBuffer.length,false):eocdrBuffer.slice(22);if(!(entryCount===65535||centralDirectoryOffset===4294967295)){return callback(null,new ZipFile(reader,centralDirectoryOffset,totalSize,entryCount,comment,options2.autoClose,options2.lazyEntries,decodeStrings,options2.validateEntrySizes,options2.strictFileNames))}var zip64EocdlBuffer=newBuffer(20);var zip64EocdlOffset=bufferReadStart+i-zip64EocdlBuffer.length;readAndAssertNoEof(reader,zip64EocdlBuffer,0,zip64EocdlBuffer.length,zip64EocdlOffset,function(err2){if(err2)return callback(err2);if(zip64EocdlBuffer.readUInt32LE(0)!==117853008){return callback(new Error("invalid zip64 end of central directory locator signature"))}var zip64EocdrOffset=readUInt64LE(zip64EocdlBuffer,8);var zip64EocdrBuffer=newBuffer(56);readAndAssertNoEof(reader,zip64EocdrBuffer,0,zip64EocdrBuffer.length,zip64EocdrOffset,function(err3){if(err3)return callback(err3);if(zip64EocdrBuffer.readUInt32LE(0)!==101075792){return callback(new Error("invalid zip64 end of central directory record signature"))}entryCount=readUInt64LE(zip64EocdrBuffer,32);centralDirectoryOffset=readUInt64LE(zip64EocdrBuffer,48);return callback(null,new ZipFile(reader,centralDirectoryOffset,totalSize,entryCount,comment,options2.autoClose,options2.lazyEntries,decodeStrings,options2.validateEntrySizes,options2.strictFileNames))})});return}callback(new Error("end of central directory record signature not found"))})}__name(fromRandomAccessReader,"fromRandomAccessReader");util.inherits(ZipFile,EventEmitter7);function ZipFile(reader,centralDirectoryOffset,fileSize,entryCount,comment,autoClose,lazyEntries,decodeStrings,validateEntrySizes,strictFileNames){var self2=this;EventEmitter7.call(self2);self2.reader=reader;self2.reader.on("error",function(err){emitError(self2,err)});self2.reader.once("close",function(){self2.emit("close")});self2.readEntryCursor=centralDirectoryOffset;self2.fileSize=fileSize;self2.entryCount=entryCount;self2.comment=comment;self2.entriesRead=0;self2.autoClose=!!autoClose;self2.lazyEntries=!!lazyEntries;self2.decodeStrings=!!decodeStrings;self2.validateEntrySizes=!!validateEntrySizes;self2.strictFileNames=!!strictFileNames;self2.isOpen=true;self2.emittedError=false;if(!self2.lazyEntries)self2._readEntry()}__name(ZipFile,"ZipFile");ZipFile.prototype.close=function(){if(!this.isOpen)return;this.isOpen=false;this.reader.unref()};function emitErrorAndAutoClose(self2,err){if(self2.autoClose)self2.close();emitError(self2,err)}__name(emitErrorAndAutoClose,"emitErrorAndAutoClose");function emitError(self2,err){if(self2.emittedError)return;self2.emittedError=true;self2.emit("error",err)}__name(emitError,"emitError");ZipFile.prototype.readEntry=function(){if(!this.lazyEntries)throw new Error("readEntry() called without lazyEntries:true");this._readEntry()};ZipFile.prototype._readEntry=function(){var self2=this;if(self2.entryCount===self2.entriesRead){setImmediate(function(){if(self2.autoClose)self2.close();if(self2.emittedError)return;self2.emit("end")});return}if(self2.emittedError)return;var buffer=newBuffer(46);readAndAssertNoEof(self2.reader,buffer,0,buffer.length,self2.readEntryCursor,function(err){if(err)return emitErrorAndAutoClose(self2,err);if(self2.emittedError)return;var entry=new Entry;var signature=buffer.readUInt32LE(0);if(signature!==33639248)return emitErrorAndAutoClose(self2,new Error("invalid central directory file header signature: 0x"+signature.toString(16)));entry.versionMadeBy=buffer.readUInt16LE(4);entry.versionNeededToExtract=buffer.readUInt16LE(6);entry.generalPurposeBitFlag=buffer.readUInt16LE(8);entry.compressionMethod=buffer.readUInt16LE(10);entry.lastModFileTime=buffer.readUInt16LE(12);entry.lastModFileDate=buffer.readUInt16LE(14);entry.crc32=buffer.readUInt32LE(16);entry.compressedSize=buffer.readUInt32LE(20);entry.uncompressedSize=buffer.readUInt32LE(24);entry.fileNameLength=buffer.readUInt16LE(28);entry.extraFieldLength=buffer.readUInt16LE(30);entry.fileCommentLength=buffer.readUInt16LE(32);entry.internalFileAttributes=buffer.readUInt16LE(36);entry.externalFileAttributes=buffer.readUInt32LE(38);entry.relativeOffsetOfLocalHeader=buffer.readUInt32LE(42);if(entry.generalPurposeBitFlag&64)return emitErrorAndAutoClose(self2,new Error("strong encryption is not supported"));self2.readEntryCursor+=46;buffer=newBuffer(entry.fileNameLength+entry.extraFieldLength+entry.fileCommentLength);readAndAssertNoEof(self2.reader,buffer,0,buffer.length,self2.readEntryCursor,function(err2){if(err2)return emitErrorAndAutoClose(self2,err2);if(self2.emittedError)return;var isUtf8=(entry.generalPurposeBitFlag&2048)!==0;entry.fileName=self2.decodeStrings?decodeBuffer(buffer,0,entry.fileNameLength,isUtf8):buffer.slice(0,entry.fileNameLength);var fileCommentStart=entry.fileNameLength+entry.extraFieldLength;var extraFieldBuffer=buffer.slice(entry.fileNameLength,fileCommentStart);entry.extraFields=[];var i=0;while(i<extraFieldBuffer.length-3){var headerId=extraFieldBuffer.readUInt16LE(i+0);var dataSize=extraFieldBuffer.readUInt16LE(i+2);var dataStart=i+4;var dataEnd=dataStart+dataSize;if(dataEnd>extraFieldBuffer.length)return emitErrorAndAutoClose(self2,new Error("extra field length exceeds extra field buffer size"));var dataBuffer=newBuffer(dataSize);extraFieldBuffer.copy(dataBuffer,0,dataStart,dataEnd);entry.extraFields.push({id:headerId,data:dataBuffer});i=dataEnd}entry.fileComment=self2.decodeStrings?decodeBuffer(buffer,fileCommentStart,fileCommentStart+entry.fileCommentLength,isUtf8):buffer.slice(fileCommentStart,fileCommentStart+entry.fileCommentLength);entry.comment=entry.fileComment;self2.readEntryCursor+=buffer.length;self2.entriesRead+=1;if(entry.uncompressedSize===4294967295||entry.compressedSize===4294967295||entry.relativeOffsetOfLocalHeader===4294967295){var zip64EiefBuffer=null;for(var i=0;i<entry.extraFields.length;i++){var extraField=entry.extraFields[i];if(extraField.id===1){zip64EiefBuffer=extraField.data;break}}if(zip64EiefBuffer==null){return emitErrorAndAutoClose(self2,new Error("expected zip64 extended information extra field"))}var index=0;if(entry.uncompressedSize===4294967295){if(index+8>zip64EiefBuffer.length){return emitErrorAndAutoClose(self2,new Error("zip64 extended information extra field does not include uncompressed size"))}entry.uncompressedSize=readUInt64LE(zip64EiefBuffer,index);index+=8}if(entry.compressedSize===4294967295){if(index+8>zip64EiefBuffer.length){return emitErrorAndAutoClose(self2,new Error("zip64 extended information extra field does not include compressed size"))}entry.compressedSize=readUInt64LE(zip64EiefBuffer,index);index+=8}if(entry.relativeOffsetOfLocalHeader===4294967295){if(index+8>zip64EiefBuffer.length){return emitErrorAndAutoClose(self2,new Error("zip64 extended information extra field does not include relative header offset"))}entry.relativeOffsetOfLocalHeader=readUInt64LE(zip64EiefBuffer,index);index+=8}}if(self2.decodeStrings){for(var i=0;i<entry.extraFields.length;i++){var extraField=entry.extraFields[i];if(extraField.id===28789){if(extraField.data.length<6){continue}if(extraField.data.readUInt8(0)!==1){continue}var oldNameCrc32=extraField.data.readUInt32LE(1);if(crc32.unsigned(buffer.slice(0,entry.fileNameLength))!==oldNameCrc32){continue}entry.fileName=decodeBuffer(extraField.data,5,extraField.data.length,true);break}}}if(self2.validateEntrySizes&&entry.compressionMethod===0){var expectedCompressedSize=entry.uncompressedSize;if(entry.isEncrypted()){expectedCompressedSize+=12}if(entry.compressedSize!==expectedCompressedSize){var msg="compressed/uncompressed size mismatch for stored file: "+entry.compressedSize+" != "+entry.uncompressedSize;return emitErrorAndAutoClose(self2,new Error(msg))}}if(self2.decodeStrings){if(!self2.strictFileNames){entry.fileName=entry.fileName.replace(/\\/g,"/")}var errorMessage=validateFileName(entry.fileName,self2.validateFileNameOptions);if(errorMessage!=null)return emitErrorAndAutoClose(self2,new Error(errorMessage))}self2.emit("entry",entry);if(!self2.lazyEntries)self2._readEntry()})})};ZipFile.prototype.openReadStream=function(entry,options2,callback){var self2=this;var relativeStart=0;var relativeEnd=entry.compressedSize;if(callback==null){callback=options2;options2={}}else{if(options2.decrypt!=null){if(!entry.isEncrypted()){throw new Error("options.decrypt can only be specified for encrypted entries")}if(options2.decrypt!==false)throw new Error("invalid options.decrypt value: "+options2.decrypt);if(entry.isCompressed()){if(options2.decompress!==false)throw new Error("entry is encrypted and compressed, and options.decompress !== false")}}if(options2.decompress!=null){if(!entry.isCompressed()){throw new Error("options.decompress can only be specified for compressed entries")}if(!(options2.decompress===false||options2.decompress===true)){throw new Error("invalid options.decompress value: "+options2.decompress)}}if(options2.start!=null||options2.end!=null){if(entry.isCompressed()&&options2.decompress!==false){throw new Error("start/end range not allowed for compressed entry without options.decompress === false")}if(entry.isEncrypted()&&options2.decrypt!==false){throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false")}}if(options2.start!=null){relativeStart=options2.start;if(relativeStart<0)throw new Error("options.start < 0");if(relativeStart>entry.compressedSize)throw new Error("options.start > entry.compressedSize")}if(options2.end!=null){relativeEnd=options2.end;if(relativeEnd<0)throw new Error("options.end < 0");if(relativeEnd>entry.compressedSize)throw new Error("options.end > entry.compressedSize");if(relativeEnd<relativeStart)throw new Error("options.end < options.start")}}if(!self2.isOpen)return callback(new Error("closed"));if(entry.isEncrypted()){if(options2.decrypt!==false)return callback(new Error("entry is encrypted, and options.decrypt !== false"))}self2.reader.ref();var buffer=newBuffer(30);readAndAssertNoEof(self2.reader,buffer,0,buffer.length,entry.relativeOffsetOfLocalHeader,function(err){try{if(err)return callback(err);var signature=buffer.readUInt32LE(0);if(signature!==67324752){return callback(new Error("invalid local file header signature: 0x"+signature.toString(16)))}var fileNameLength=buffer.readUInt16LE(26);var extraFieldLength=buffer.readUInt16LE(28);var localFileHeaderEnd=entry.relativeOffsetOfLocalHeader+buffer.length+fileNameLength+extraFieldLength;var decompress;if(entry.compressionMethod===0){decompress=false}else if(entry.compressionMethod===8){decompress=options2.decompress!=null?options2.decompress:true}else{return callback(new Error("unsupported compression method: "+entry.compressionMethod))}var fileDataStart=localFileHeaderEnd;var fileDataEnd=fileDataStart+entry.compressedSize;if(entry.compressedSize!==0){if(fileDataEnd>self2.fileSize){return callback(new Error("file data overflows file bounds: "+fileDataStart+" + "+entry.compressedSize+" > "+self2.fileSize))}}var readStream=self2.reader.createReadStream({start:fileDataStart+relativeStart,end:fileDataStart+relativeEnd});var endpointStream=readStream;if(decompress){var destroyed=false;var inflateFilter=zlib.createInflateRaw();readStream.on("error",function(err2){setImmediate(function(){if(!destroyed)inflateFilter.emit("error",err2)})});readStream.pipe(inflateFilter);if(self2.validateEntrySizes){endpointStream=new AssertByteCountStream(entry.uncompressedSize);inflateFilter.on("error",function(err2){setImmediate(function(){if(!destroyed)endpointStream.emit("error",err2)})});inflateFilter.pipe(endpointStream)}else{endpointStream=inflateFilter}endpointStream.destroy=function(){destroyed=true;if(inflateFilter!==endpointStream)inflateFilter.unpipe(endpointStream);readStream.unpipe(inflateFilter);readStream.destroy()}}callback(null,endpointStream)}finally{self2.reader.unref()}})};function Entry(){}__name(Entry,"Entry");Entry.prototype.getLastModDate=function(){return dosDateTimeToDate(this.lastModFileDate,this.lastModFileTime)};Entry.prototype.isEncrypted=function(){return(this.generalPurposeBitFlag&1)!==0};Entry.prototype.isCompressed=function(){return this.compressionMethod===8};function dosDateTimeToDate(date6,time5){var day=date6&31;var month=(date6>>5&15)-1;var year=(date6>>9&127)+1980;var millisecond=0;var second=(time5&31)*2;var minute=time5>>5&63;var hour=time5>>11&31;return new Date(year,month,day,hour,minute,second,millisecond)}__name(dosDateTimeToDate,"dosDateTimeToDate");function validateFileName(fileName){if(fileName.indexOf("\\")!==-1){return"invalid characters in fileName: "+fileName}if(/^[a-zA-Z]:/.test(fileName)||/^\//.test(fileName)){return"absolute path: "+fileName}if(fileName.split("/").indexOf("..")!==-1){return"invalid relative path: "+fileName}return null}__name(validateFileName,"validateFileName");function readAndAssertNoEof(reader,buffer,offset2,length,position,callback){if(length===0){return setImmediate(function(){callback(null,newBuffer(0))})}reader.read(buffer,offset2,length,position,function(err,bytesRead){if(err)return callback(err);if(bytesRead<length){return callback(new Error("unexpected EOF"))}callback()})}__name(readAndAssertNoEof,"readAndAssertNoEof");util.inherits(AssertByteCountStream,Transform);function AssertByteCountStream(byteCount){Transform.call(this);this.actualByteCount=0;this.expectedByteCount=byteCount}__name(AssertByteCountStream,"AssertByteCountStream");AssertByteCountStream.prototype._transform=function(chunk,encoding,cb){this.actualByteCount+=chunk.length;if(this.actualByteCount>this.expectedByteCount){var msg="too many bytes in the stream. expected "+this.expectedByteCount+". got at least "+this.actualByteCount;return cb(new Error(msg))}cb(null,chunk)};AssertByteCountStream.prototype._flush=function(cb){if(this.actualByteCount<this.expectedByteCount){var msg="not enough bytes in the stream. expected "+this.expectedByteCount+". got only "+this.actualByteCount;return cb(new Error(msg))}cb()};util.inherits(RandomAccessReader,EventEmitter7);function RandomAccessReader(){EventEmitter7.call(this);this.refCount=0}__name(RandomAccessReader,"RandomAccessReader");RandomAccessReader.prototype.ref=function(){this.refCount+=1};RandomAccessReader.prototype.unref=function(){var self2=this;self2.refCount-=1;if(self2.refCount>0)return;if(self2.refCount<0)throw new Error("invalid unref");self2.close(onCloseDone);function onCloseDone(err){if(err)return self2.emit("error",err);self2.emit("close")}__name(onCloseDone,"onCloseDone")};RandomAccessReader.prototype.createReadStream=function(options2){var start=options2.start;var end=options2.end;if(start===end){var emptyStream=new PassThrough3;setImmediate(function(){emptyStream.end()});return emptyStream}var stream=this._readStreamForRange(start,end);var destroyed=false;var refUnrefFilter=new RefUnrefFilter(this);stream.on("error",function(err){setImmediate(function(){if(!destroyed)refUnrefFilter.emit("error",err)})});refUnrefFilter.destroy=function(){stream.unpipe(refUnrefFilter);refUnrefFilter.unref();stream.destroy()};var byteCounter=new AssertByteCountStream(end-start);refUnrefFilter.on("error",function(err){setImmediate(function(){if(!destroyed)byteCounter.emit("error",err)})});byteCounter.destroy=function(){destroyed=true;refUnrefFilter.unpipe(byteCounter);refUnrefFilter.destroy()};return stream.pipe(refUnrefFilter).pipe(byteCounter)};RandomAccessReader.prototype._readStreamForRange=function(start,end){throw new Error("not implemented")};RandomAccessReader.prototype.read=function(buffer,offset2,length,position,callback){var readStream=this.createReadStream({start:position,end:position+length});var writeStream=new Writable;var written=0;writeStream._write=function(chunk,encoding,cb){chunk.copy(buffer,offset2+written,0,chunk.length);written+=chunk.length;cb()};writeStream.on("finish",callback);readStream.on("error",function(error3){callback(error3)});readStream.pipe(writeStream)};RandomAccessReader.prototype.close=function(callback){setImmediate(callback)};util.inherits(RefUnrefFilter,PassThrough3);function RefUnrefFilter(context2){PassThrough3.call(this);this.context=context2;this.context.ref();this.unreffedYet=false}__name(RefUnrefFilter,"RefUnrefFilter");RefUnrefFilter.prototype._flush=function(cb){this.unref();cb()};RefUnrefFilter.prototype.unref=function(cb){if(this.unreffedYet)return;this.unreffedYet=true;this.context.unref()};var cp437="\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0";function decodeBuffer(buffer,start,end,isUtf8){if(isUtf8){return buffer.toString("utf8",start,end)}else{var result="";for(var i=start;i<end;i++){result+=cp437[buffer[i]]}return result}}__name(decodeBuffer,"decodeBuffer");function readUInt64LE(buffer,offset2){var lower32=buffer.readUInt32LE(offset2);var upper32=buffer.readUInt32LE(offset2+4);return upper32*4294967296+lower32}__name(readUInt64LE,"readUInt64LE");var newBuffer;if(typeof Buffer.allocUnsafe==="function"){newBuffer=__name(function(len){return Buffer.allocUnsafe(len)},"newBuffer")}else{newBuffer=__name(function(len){return new Buffer(len)},"newBuffer")}function defaultCallback(err){if(err)throw err}__name(defaultCallback,"defaultCallback")}});var require_kleur=__commonJS({"node_modules/kleur/index.js"(exports2,module2){"use strict";init_esbuild_shims();var{FORCE_COLOR,NODE_DISABLE_COLORS,TERM}=process.env;var $2={enabled:!NODE_DISABLE_COLORS&&TERM!=="dumb"&&FORCE_COLOR!=="0",reset:init(0,0),bold:init(1,22),dim:init(2,22),italic:init(3,23),underline:init(4,24),inverse:init(7,27),hidden:init(8,28),strikethrough:init(9,29),black:init(30,39),red:init(31,39),green:init(32,39),yellow:init(33,39),blue:init(34,39),magenta:init(35,39),cyan:init(36,39),white:init(37,39),gray:init(90,39),grey:init(90,39),bgBlack:init(40,49),bgRed:init(41,49),bgGreen:init(42,49),bgYellow:init(43,49),bgBlue:init(44,49),bgMagenta:init(45,49),bgCyan:init(46,49),bgWhite:init(47,49)};function run(arr,str){let i=0,tmp,beg="",end="";for(;i<arr.length;i++){tmp=arr[i];beg+=tmp.open;end+=tmp.close;if(str.includes(tmp.close)){str=str.replace(tmp.rgx,tmp.close+tmp.open)}}return beg+str+end}__name(run,"run");function chain(has,keys2){let ctx={has,keys:keys2};ctx.reset=$2.reset.bind(ctx);ctx.bold=$2.bold.bind(ctx);ctx.dim=$2.dim.bind(ctx);ctx.italic=$2.italic.bind(ctx);ctx.underline=$2.underline.bind(ctx);ctx.inverse=$2.inverse.bind(ctx);ctx.hidden=$2.hidden.bind(ctx);ctx.strikethrough=$2.strikethrough.bind(ctx);ctx.black=$2.black.bind(ctx);ctx.red=$2.red.bind(ctx);ctx.green=$2.green.bind(ctx);ctx.yellow=$2.yellow.bind(ctx);ctx.blue=$2.blue.bind(ctx);ctx.magenta=$2.magenta.bind(ctx);ctx.cyan=$2.cyan.bind(ctx);ctx.white=$2.white.bind(ctx);ctx.gray=$2.gray.bind(ctx);ctx.grey=$2.grey.bind(ctx);ctx.bgBlack=$2.bgBlack.bind(ctx);ctx.bgRed=$2.bgRed.bind(ctx);ctx.bgGreen=$2.bgGreen.bind(ctx);ctx.bgYellow=$2.bgYellow.bind(ctx);ctx.bgBlue=$2.bgBlue.bind(ctx);ctx.bgMagenta=$2.bgMagenta.bind(ctx);ctx.bgCyan=$2.bgCyan.bind(ctx);ctx.bgWhite=$2.bgWhite.bind(ctx);return ctx}__name(chain,"chain");function init(open8,close){let blk={open:`\x1B[${open8}m`,close:`\x1B[${close}m`,rgx:new RegExp(`\\x1b\\[${close}m`,"g")};return function(txt){if(this!==void 0&&this.has!==void 0){this.has.includes(open8)||(this.has.push(open8),this.keys.push(blk));return txt===void 0?this:$2.enabled?run(this.keys,txt+""):txt+""}return txt===void 0?chain([open8],[blk]):$2.enabled?run([blk],txt+""):txt+""}}__name(init,"init");module2.exports=$2}});var require_action=__commonJS({"node_modules/prompts/dist/util/action.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=(key,isSelect)=>{if(key.meta&&key.name!=="escape")return;if(key.ctrl){if(key.name==="a")return"first";if(key.name==="c")return"abort";if(key.name==="d")return"abort";if(key.name==="e")return"last";if(key.name==="g")return"reset"}if(isSelect){if(key.name==="j")return"down";if(key.name==="k")return"up"}if(key.name==="return")return"submit";if(key.name==="enter")return"submit";if(key.name==="backspace")return"delete";if(key.name==="delete")return"deleteForward";if(key.name==="abort")return"abort";if(key.name==="escape")return"exit";if(key.name==="tab")return"next";if(key.name==="pagedown")return"nextPage";if(key.name==="pageup")return"prevPage";if(key.name==="home")return"home";if(key.name==="end")return"end";if(key.name==="up")return"up";if(key.name==="down")return"down";if(key.name==="right")return"right";if(key.name==="left")return"left";return false}}});var require_strip=__commonJS({"node_modules/prompts/dist/util/strip.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=str=>{const pattern=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|");const RGX=new RegExp(pattern,"g");return typeof str==="string"?str.replace(RGX,""):str}}});var require_src2=__commonJS({"node_modules/sisteransi/src/index.js"(exports2,module2){"use strict";init_esbuild_shims();var ESC="\x1B";var CSI=`${ESC}[`;var beep="\x07";var cursor={to(x,y){if(!y)return`${CSI}${x+1}G`;return`${CSI}${y+1};${x+1}H`},move(x,y){let ret="";if(x<0)ret+=`${CSI}${-x}D`;else if(x>0)ret+=`${CSI}${x}C`;if(y<0)ret+=`${CSI}${-y}A`;else if(y>0)ret+=`${CSI}${y}B`;return ret},up:__name((count4=1)=>`${CSI}${count4}A`,"up"),down:__name((count4=1)=>`${CSI}${count4}B`,"down"),forward:__name((count4=1)=>`${CSI}${count4}C`,"forward"),backward:__name((count4=1)=>`${CSI}${count4}D`,"backward"),nextLine:__name((count4=1)=>`${CSI}E`.repeat(count4),"nextLine"),prevLine:__name((count4=1)=>`${CSI}F`.repeat(count4),"prevLine"),left:`${CSI}G`,hide:`${CSI}?25l`,show:`${CSI}?25h`,save:`${ESC}7`,restore:`${ESC}8`};var scroll={up:__name((count4=1)=>`${CSI}S`.repeat(count4),"up"),down:__name((count4=1)=>`${CSI}T`.repeat(count4),"down")};var erase={screen:`${CSI}2J`,up:__name((count4=1)=>`${CSI}1J`.repeat(count4),"up"),down:__name((count4=1)=>`${CSI}J`.repeat(count4),"down"),line:`${CSI}2K`,lineEnd:`${CSI}K`,lineStart:`${CSI}1K`,lines(count4){let clear="";for(let i=0;i<count4;i++)clear+=this.line+(i<count4-1?cursor.up():"");if(count4)clear+=cursor.left;return clear}};module2.exports={cursor,scroll,erase,beep}}});var require_clear=__commonJS({"node_modules/prompts/dist/util/clear.js"(exports2,module2){"use strict";init_esbuild_shims();function _createForOfIteratorHelper(o,allowArrayLike){var it2=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it2){if(Array.isArray(o)||(it2=_unsupportedIterableToArray2(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it2)o=it2;var i=0;var F2=__name(function F3(){},"F");return{s:F2,n:__name(function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},"n"),e:__name(function e(_e2){throw _e2},"e"),f:F2}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:__name(function s3(){it2=it2.call(o)},"s"),n:__name(function n(){var step=it2.next();normalCompletion=step.done;return step},"n"),e:__name(function e(_e2){didErr=true;err=_e2},"e"),f:__name(function f2(){try{if(!normalCompletion&&it2.return!=null)it2.return()}finally{if(didErr)throw err}},"f")}}__name(_createForOfIteratorHelper,"_createForOfIteratorHelper");function _unsupportedIterableToArray2(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray2(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray2(o,minLen)}__name(_unsupportedIterableToArray2,"_unsupportedIterableToArray");function _arrayLikeToArray2(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}__name(_arrayLikeToArray2,"_arrayLikeToArray");var strip=require_strip();var _require=require_src2();var erase=_require.erase;var cursor=_require.cursor;var width=__name(str=>[...strip(str)].length,"width");module2.exports=function(prompt,perLine){if(!perLine)return erase.line+cursor.to(0);let rows=0;const lines=prompt.split(/\r?\n/);var _iterator=_createForOfIteratorHelper(lines),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){let line2=_step.value;rows+=1+Math.floor(Math.max(width(line2)-1,0)/perLine)}}catch(err){_iterator.e(err)}finally{_iterator.f()}return erase.lines(rows)}}});var require_figures=__commonJS({"node_modules/prompts/dist/util/figures.js"(exports2,module2){"use strict";init_esbuild_shims();var main={arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",radioOn:"\u25C9",radioOff:"\u25EF",tick:"\u2714",cross:"\u2716",ellipsis:"\u2026",pointerSmall:"\u203A",line:"\u2500",pointer:"\u276F"};var win={arrowUp:main.arrowUp,arrowDown:main.arrowDown,arrowLeft:main.arrowLeft,arrowRight:main.arrowRight,radioOn:"(*)",radioOff:"( )",tick:"\u221A",cross:"\xD7",ellipsis:"...",pointerSmall:"\xBB",line:"\u2500",pointer:">"};var figures=process.platform==="win32"?win:main;module2.exports=figures}});var require_style=__commonJS({"node_modules/prompts/dist/util/style.js"(exports2,module2){"use strict";init_esbuild_shims();var c=require_kleur();var figures=require_figures();var styles=Object.freeze({password:{scale:1,render:__name(input=>"*".repeat(input.length),"render")},emoji:{scale:2,render:__name(input=>"\u{1F603}".repeat(input.length),"render")},invisible:{scale:0,render:__name(input=>"","render")},default:{scale:1,render:__name(input=>`${input}`,"render")}});var render=__name(type=>styles[type]||styles.default,"render");var symbols=Object.freeze({aborted:c.red(figures.cross),done:c.green(figures.tick),exited:c.yellow(figures.cross),default:c.cyan("?")});var symbol=__name((done,aborted3,exited)=>aborted3?symbols.aborted:exited?symbols.exited:done?symbols.done:symbols.default,"symbol");var delimiter3=__name(completing=>c.gray(completing?figures.ellipsis:figures.pointerSmall),"delimiter");var item=__name((expandable,expanded)=>c.gray(expandable?expanded?figures.pointerSmall:"+":figures.line),"item");module2.exports={styles,render,symbols,symbol,delimiter:delimiter3,item}}});var require_lines=__commonJS({"node_modules/prompts/dist/util/lines.js"(exports2,module2){"use strict";init_esbuild_shims();var strip=require_strip();module2.exports=function(msg,perLine){let lines=String(strip(msg)||"").split(/\r?\n/);if(!perLine)return lines.length;return lines.map(l=>Math.ceil(l.length/perLine)).reduce((a,b2)=>a+b2)}}});var require_wrap=__commonJS({"node_modules/prompts/dist/util/wrap.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=(msg,opts={})=>{const tab=Number.isSafeInteger(parseInt(opts.margin))?new Array(parseInt(opts.margin)).fill(" ").join(""):opts.margin||"";const width=opts.width;return(msg||"").split(/\r?\n/g).map(line2=>line2.split(/\s+/g).reduce((arr,w2)=>{if(w2.length+tab.length>=width||arr[arr.length-1].length+w2.length+1<width)arr[arr.length-1]+=` ${w2}`;else arr.push(`${tab}${w2}`);return arr},[tab]).join("\n")).join("\n")}}});var require_entriesToDisplay=__commonJS({"node_modules/prompts/dist/util/entriesToDisplay.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports=(cursor,total,maxVisible)=>{maxVisible=maxVisible||total;let startIndex=Math.min(total-maxVisible,cursor-Math.floor(maxVisible/2));if(startIndex<0)startIndex=0;let endIndex=Math.min(startIndex+maxVisible,total);return{startIndex,endIndex}}}});var require_util2=__commonJS({"node_modules/prompts/dist/util/index.js"(exports2,module2){"use strict";init_esbuild_shims();module2.exports={action:require_action(),clear:require_clear(),style:require_style(),strip:require_strip(),figures:require_figures(),lines:require_lines(),wrap:require_wrap(),entriesToDisplay:require_entriesToDisplay()}}});var require_prompt=__commonJS({"node_modules/prompts/dist/elements/prompt.js"(exports2,module2){"use strict";init_esbuild_shims();var readline2=__require("readline");var _require=require_util2();var action=_require.action;var EventEmitter7=__require("events");var _require2=require_src2();var beep=_require2.beep;var cursor=_require2.cursor;var color=require_kleur();var Prompt=class extends EventEmitter7{static{__name(this,"Prompt")}constructor(opts={}){super();this.firstRender=true;this.in=opts.stdin||process.stdin;this.out=opts.stdout||process.stdout;this.onRender=(opts.onRender||(()=>void 0)).bind(this);const rl=readline2.createInterface({input:this.in,escapeCodeTimeout:50});readline2.emitKeypressEvents(this.in,rl);if(this.in.isTTY)this.in.setRawMode(true);const isSelect=["SelectPrompt","MultiselectPrompt"].indexOf(this.constructor.name)>-1;const keypress=__name((str,key)=>{let a=action(key,isSelect);if(a===false){this._&&this._(str,key)}else if(typeof this[a]==="function"){this[a](key)}else{this.bell()}},"keypress");this.close=()=>{this.out.write(cursor.show);this.in.removeListener("keypress",keypress);if(this.in.isTTY)this.in.setRawMode(false);rl.close();this.emit(this.aborted?"abort":this.exited?"exit":"submit",this.value);this.closed=true};this.in.on("keypress",keypress)}fire(){this.emit("state",{value:this.value,aborted:!!this.aborted,exited:!!this.exited})}bell(){this.out.write(beep)}render(){this.onRender(color);if(this.firstRender)this.firstRender=false}};module2.exports=Prompt}});var require_text=__commonJS({"node_modules/prompts/dist/elements/text.js"(exports2,module2){"use strict";init_esbuild_shims();function asyncGeneratorStep(gen,resolve36,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value}catch(error3){reject(error3);return}if(info.done){resolve36(value)}else{Promise.resolve(value).then(_next,_throw)}}__name(asyncGeneratorStep,"asyncGeneratorStep");function _asyncToGenerator(fn){return function(){var self2=this,args=arguments;return new Promise(function(resolve36,reject){var gen=fn.apply(self2,args);function _next(value){asyncGeneratorStep(gen,resolve36,reject,_next,_throw,"next",value)}__name(_next,"_next");function _throw(err){asyncGeneratorStep(gen,resolve36,reject,_next,_throw,"throw",err)}__name(_throw,"_throw");_next(void 0)})}}__name(_asyncToGenerator,"_asyncToGenerator");var color=require_kleur();var Prompt=require_prompt();var _require=require_src2();var erase=_require.erase;var cursor=_require.cursor;var _require2=require_util2();var style=_require2.style;var clear=_require2.clear;var lines=_require2.lines;var figures=_require2.figures;var TextPrompt=class extends Prompt{static{__name(this,"TextPrompt")}constructor(opts={}){super(opts);this.transform=style.render(opts.style);this.scale=this.transform.scale;this.msg=opts.message;this.initial=opts.initial||``;this.validator=opts.validate||(()=>true);this.value=``;this.errorMsg=opts.error||`Please Enter A Valid Value`;this.cursor=Number(!!this.initial);this.cursorOffset=0;this.clear=clear(``,this.out.columns);this.render()}set value(v2){if(!v2&&this.initial){this.placeholder=true;this.rendered=color.gray(this.transform.render(this.initial))}else{this.placeholder=false;this.rendered=this.transform.render(v2)}this._value=v2;this.fire()}get value(){return this._value}reset(){this.value=``;this.cursor=Number(!!this.initial);this.cursorOffset=0;this.fire();this.render()}exit(){this.abort()}abort(){this.value=this.value||this.initial;this.done=this.aborted=true;this.error=false;this.red=false;this.fire();this.render();this.out.write("\n");this.close()}validate(){var _this=this;return _asyncToGenerator(function*(){let valid=yield _this.validator(_this.value);if(typeof valid===`string`){_this.errorMsg=valid;valid=false}_this.error=!valid})()}submit(){var _this2=this;return _asyncToGenerator(function*(){_this2.value=_this2.value||_this2.initial;_this2.cursorOffset=0;_this2.cursor=_this2.rendered.length;yield _this2.validate();if(_this2.error){_this2.red=true;_this2.fire();_this2.render();return}_this2.done=true;_this2.aborted=false;_this2.fire();_this2.render();_this2.out.write("\n");_this2.close()})()}next(){if(!this.placeholder)return this.bell();this.value=this.initial;this.cursor=this.rendered.length;this.fire();this.render()}moveCursor(n){if(this.placeholder)return;this.cursor=this.cursor+n;this.cursorOffset+=n}_(c,key){let s1=this.value.slice(0,this.cursor);let s22=this.value.slice(this.cursor);this.value=`${s1}${c}${s22}`;this.red=false;this.cursor=this.placeholder?0:s1.length+1;this.render()}delete(){if(this.isCursorAtStart())return this.bell();let s1=this.value.slice(0,this.cursor-1);let s22=this.value.slice(this.cursor);this.value=`${s1}${s22}`;this.red=false;if(this.isCursorAtStart()){this.cursorOffset=0}else{this.cursorOffset++;this.moveCursor(-1)}this.render()}deleteForward(){if(this.cursor*this.scale>=this.rendered.length||this.placeholder)return this.bell();let s1=this.value.slice(0,this.cursor);let s22=this.value.slice(this.cursor+1);this.value=`${s1}${s22}`;this.red=false;if(this.isCursorAtEnd()){this.cursorOffset=0}else{this.cursorOffset++}this.render()}first(){this.cursor=0;this.render()}last(){this.cursor=this.value.length;this.render()}left(){if(this.cursor<=0||this.placeholder)return this.bell();this.moveCursor(-1);this.render()}right(){if(this.cursor*this.scale>=this.rendered.length||this.placeholder)return this.bell();this.moveCursor(1);this.render()}isCursorAtStart(){return this.cursor===0||this.placeholder&&this.cursor===1}isCursorAtEnd(){return this.cursor===this.rendered.length||this.placeholder&&this.cursor===this.rendered.length+1}render(){if(this.closed)return;if(!this.firstRender){if(this.outputError)this.out.write(cursor.down(lines(this.outputError,this.out.columns)-1)+clear(this.outputError,this.out.columns));this.out.write(clear(this.outputText,this.out.columns))}super.render();this.outputError="";this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(this.done),this.red?color.red(this.rendered):this.rendered].join(` `);if(this.error){this.outputError+=this.errorMsg.split(`
5
5
  `).reduce((a,l,i)=>a+`
6
6
  ${i?" ":figures.pointerSmall} ${color.red().italic(l)}`,``)}this.out.write(erase.line+cursor.to(0)+this.outputText+cursor.save+this.outputError+cursor.restore+cursor.move(this.cursorOffset,0))}};module2.exports=TextPrompt}});var require_select=__commonJS({"node_modules/prompts/dist/elements/select.js"(exports2,module2){"use strict";init_esbuild_shims();var color=require_kleur();var Prompt=require_prompt();var _require=require_util2();var style=_require.style;var clear=_require.clear;var figures=_require.figures;var wrap=_require.wrap;var entriesToDisplay=_require.entriesToDisplay;var _require2=require_src2();var cursor=_require2.cursor;var SelectPrompt=class extends Prompt{static{__name(this,"SelectPrompt")}constructor(opts={}){super(opts);this.msg=opts.message;this.hint=opts.hint||"- Use arrow-keys. Return to submit.";this.warn=opts.warn||"- This option is disabled";this.cursor=opts.initial||0;this.choices=opts.choices.map((ch,idx)=>{if(typeof ch==="string")ch={title:ch,value:idx};return{title:ch&&(ch.title||ch.value||ch),value:ch&&(ch.value===void 0?idx:ch.value),description:ch&&ch.description,selected:ch&&ch.selected,disabled:ch&&ch.disabled}});this.optionsPerPage=opts.optionsPerPage||10;this.value=(this.choices[this.cursor]||{}).value;this.clear=clear("",this.out.columns);this.render()}moveCursor(n){this.cursor=n;this.value=this.choices[n].value;this.fire()}reset(){this.moveCursor(0);this.fire();this.render()}exit(){this.abort()}abort(){this.done=this.aborted=true;this.fire();this.render();this.out.write("\n");this.close()}submit(){if(!this.selection.disabled){this.done=true;this.aborted=false;this.fire();this.render();this.out.write("\n");this.close()}else this.bell()}first(){this.moveCursor(0);this.render()}last(){this.moveCursor(this.choices.length-1);this.render()}up(){if(this.cursor===0){this.moveCursor(this.choices.length-1)}else{this.moveCursor(this.cursor-1)}this.render()}down(){if(this.cursor===this.choices.length-1){this.moveCursor(0)}else{this.moveCursor(this.cursor+1)}this.render()}next(){this.moveCursor((this.cursor+1)%this.choices.length);this.render()}_(c,key){if(c===" ")return this.submit()}get selection(){return this.choices[this.cursor]}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));super.render();let _entriesToDisplay=entriesToDisplay(this.cursor,this.choices.length,this.optionsPerPage),startIndex=_entriesToDisplay.startIndex,endIndex=_entriesToDisplay.endIndex;this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(false),this.done?this.selection.title:this.selection.disabled?color.yellow(this.warn):color.gray(this.hint)].join(" ");if(!this.done){this.outputText+="\n";for(let i=startIndex;i<endIndex;i++){let title,prefix2,desc="",v2=this.choices[i];if(i===startIndex&&startIndex>0){prefix2=figures.arrowUp}else if(i===endIndex-1&&endIndex<this.choices.length){prefix2=figures.arrowDown}else{prefix2=" "}if(v2.disabled){title=this.cursor===i?color.gray().underline(v2.title):color.strikethrough().gray(v2.title);prefix2=(this.cursor===i?color.bold().gray(figures.pointer)+" ":" ")+prefix2}else{title=this.cursor===i?color.cyan().underline(v2.title):v2.title;prefix2=(this.cursor===i?color.cyan(figures.pointer)+" ":" ")+prefix2;if(v2.description&&this.cursor===i){desc=` - ${v2.description}`;if(prefix2.length+title.length+desc.length>=this.out.columns||v2.description.split(/\r?\n/).length>1){desc="\n"+wrap(v2.description,{margin:3,width:this.out.columns})}}}this.outputText+=`${prefix2} ${title}${color.gray(desc)}
@@ -65,7 +65,8 @@ Recently used tools: ${recentTools.join(", ")}`:"";const contents=[{role:"user",
65
65
  Available memories:
66
66
  ${manifest}${toolsSection}`}]}];const validFilePaths=new Set(includedDocs.map(doc=>doc.filePath));const byFilePath=new Map(includedDocs.map(doc=>[doc.filePath,doc]));const response=await runSideQuery(config3,{purpose:"auto-memory-recall",contents,schema:RESPONSE_SCHEMA,skipOutputLanguagePreference:true,abortSignal:callerAbortSignal?AbortSignal.any([AbortSignal.timeout(3e4),callerAbortSignal]):AbortSignal.timeout(3e4),systemInstruction:SELECT_MEMORIES_SYSTEM_PROMPT,config:{temperature:0},validate:__name(value=>{if(!Array.isArray(value.selected_memories)){return"Recall selector must return selected_memories array"}if(value.selected_memories.length>limit){return`Recall selector returned too many documents: ${value.selected_memories.length}`}if(value.selected_memories.some(filePath=>!validFilePaths.has(filePath))){return"Recall selector returned unknown file path"}return null},"validate")});return response.selected_memories.map(filePath=>byFilePath.get(filePath)).filter(doc=>doc!==void 0).slice(0,limit)}__name(selectRelevantAutoMemoryDocumentsByModel,"selectRelevantAutoMemoryDocumentsByModel");var MAX_RELEVANT_DOCS=5;var MAX_FAST_RECALL_DOCS=2;var MAX_DOC_BODY_CHARS=1200;var MAX_HEURISTIC_QUERY_TOKENS=64;var MAX_MODEL_CANDIDATE_DOCS=200;var RECENT_MODEL_CANDIDATE_RESERVE=20;var debugLogger9=createDebugLogger("AUTO_MEMORY_RECALL");var ACTIVE_TOOL_USAGE_MEMORY_MARKERS=["api docs","api documentation","failed call","failed tool call","failed tool-call","field mapping","field mappings","guessed call","guessed tool","mcp tool","parameter schema","parameter schemas","tool schema","tool schemas","tool usage","usage reference"];var DURABLE_ACTIVE_TOOL_MEMORY_MARKERS=["credential","credentials","escalation","gotcha","gotchas","known issue","known issues","owner","ownership","warning","warnings","workaround","workarounds"];var TYPE_KEYWORDS={user:["user","preference","preferences","background","role","terse"],feedback:["feedback","rule","rules","avoid","style","summary"],project:["project","goal","goals","incident","deadline","release"],reference:["reference","dashboard","ticket","docs","doc","link"]};var CJK_CLASS="[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script_Extensions=Katakana}\\p{Script=Hangul}]";var RECALL_TOKEN_RUN=new RegExp(`${CJK_CLASS}+|(?!${CJK_CLASS})[\\p{L}\\p{N}](?:(?!${CJK_CLASS})[\\p{L}\\p{M}\\p{N}]){2,}`,"gu");var CJK_RUN_START=new RegExp(`^${CJK_CLASS}`,"u");var CJK_RUN_END=new RegExp(`${CJK_CLASS}$`,"u");var CJK_BIGRAM=new RegExp(`^${CJK_CLASS}{2}$`,"u");function normalizeRecallText(text3){return text3.normalize("NFKC").toLowerCase()}__name(normalizeRecallText,"normalizeRecallText");function*recallTokenRuns(text3){for(const match of normalizeRecallText(text3).matchAll(RECALL_TOKEN_RUN)){const run=match[0];if(!CJK_RUN_START.test(run)){yield run;continue}let previous="";for(const codePoint of run){if(previous)yield previous+codePoint;previous=codePoint}}}__name(recallTokenRuns,"recallTokenRuns");function tokenizeMemoryRecallText(text3){const edgeSize=MAX_HEURISTIC_QUERY_TOKENS/2;const headTokens=new Set;const tailTokens=new Set;const addToken=__name(token=>{if(headTokens.has(token))return;if(tailTokens.delete(token)){tailTokens.add(token);return}if(headTokens.size<edgeSize){headTokens.add(token);return}tailTokens.add(token);if(tailTokens.size>edgeSize){const oldest=tailTokens.values().next();if(!oldest.done)tailTokens.delete(oldest.value)}},"addToken");for(const run of recallTokenRuns(text3))addToken(run);return[...headTokens,...tailTokens]}__name(tokenizeMemoryRecallText,"tokenizeMemoryRecallText");function tokenizeMemoryRecallTerms(text3){return new Set(recallTokenRuns(text3))}__name(tokenizeMemoryRecallTerms,"tokenizeMemoryRecallTerms");function normalizeBody(body){const trimmed=body.trim();if(trimmed==="_No entries yet._"){return""}return trimmed}__name(normalizeBody,"normalizeBody");function toolAliases(toolName){const normalized=toolName.trim().toLowerCase();const aliases=[normalized];if(normalized.includes("::")){aliases.push(normalized.split("::").at(-1)??"")}if(normalized.startsWith("mcp__")){const parts=normalized.split("__");if(parts.length>=3){aliases.push(parts.slice(2).join("__"));aliases.push(parts.at(-1)??"")}}return Array.from(new Set(aliases.map(alias=>alias.trim()).filter(Boolean)))}__name(toolAliases,"toolAliases");function createActiveToolUsageFilter(recentTools,useStructuredMetadata=true){if(recentTools.length===0){return()=>false}const aliases=Array.from(new Set(recentTools.flatMap(toolAliases)));if(aliases.length===0){return()=>false}return doc=>{const rawHaystack=[doc.title,doc.description,...useStructuredMetadata?doc.keywords:[],...useStructuredMetadata?doc.usageScenarios:[],normalizeBody(doc.body)].join(" ");const haystack=(useStructuredMetadata?rawHaystack.normalize("NFKC"):rawHaystack).toLowerCase();if(!aliases.some(alias=>haystack.includes(alias))){return false}if(DURABLE_ACTIVE_TOOL_MEMORY_MARKERS.some(marker=>haystack.includes(marker))){return false}return ACTIVE_TOOL_USAGE_MEMORY_MARKERS.some(marker=>haystack.includes(marker))}}__name(createActiveToolUsageFilter,"createActiveToolUsageFilter");function scoreDocument(queryTokens,doc,useStructuredMetadata=true){const title=normalizeRecallText(doc.title);const description=normalizeRecallText(doc.description);const descriptionAsScenario=normalizeRecallText(sanitizeAutoMemoryPromptField(doc.description,MAX_USAGE_SCENARIO_CHARS));const keywords2=normalizeRecallText(doc.keywords.filter(keyword=>normalizeRecallText(keyword)!==title).join(" "));const usageScenarios=normalizeRecallText(doc.usageScenarios.filter(scenario=>{const normalized=normalizeRecallText(scenario);return normalized!==description&&normalized!==descriptionAsScenario}).join(" "));const body=normalizeRecallText(normalizeBody(doc.body).slice(0,MAX_DOC_BODY_CHARS));let lexicalScore=0;for(const token of queryTokens){if(title.includes(token)){lexicalScore+=4}if(description.includes(token)){lexicalScore+=3}if(useStructuredMetadata&&keywords2.includes(token)){lexicalScore+=4}if(useStructuredMetadata&&usageScenarios.includes(token)){lexicalScore+=3}const cjkBigram=CJK_BIGRAM.test(token);if((!useStructuredMetadata||!cjkBigram)&&body.includes(token)){lexicalScore+=1}}if(lexicalScore===0){return 0}const typeBoost=Math.min(queryTokens.filter(token=>TYPE_KEYWORDS[doc.type]?.includes(token)).length,2);return lexicalScore+typeBoost}__name(scoreDocument,"scoreDocument");function matchesTitleOrKeyword(query,doc,requireTokenBoundary=false){const normalizedQuery=normalizeRecallText(query);const title=normalizeRecallText(doc.title).trim();const keywords2=doc.keywords.map(keyword=>normalizeRecallText(keyword).trim()).filter(Boolean);const includesValue=__name(value=>{const escaped=value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const boundary=requireTokenBoundary?`(?:${CJK_CLASS}|[^\\p{L}\\p{N}])`:"[^\\p{L}\\p{N}]";const leftBoundary=CJK_RUN_START.test(value)?"":`(?:^|${boundary})`;const rightBoundary=CJK_RUN_END.test(value)?"":`(?:$|${boundary})`;return new RegExp(`${leftBoundary}${escaped}${rightBoundary}`,"u").test(normalizedQuery)},"includesValue");const includesKeyword=__name(keyword=>requireTokenBoundary||/^[a-z0-9]{1,2}$/.test(keyword)?includesValue(keyword):normalizedQuery.includes(keyword),"includesKeyword");return title.length>0&&(requireTokenBoundary?includesValue(title):normalizedQuery.includes(title))||keywords2.some(includesKeyword)}__name(matchesTitleOrKeyword,"matchesTitleOrKeyword");function isStrongFastMatch(query,doc){if(matchesTitleOrKeyword(query,doc))return true;const queryTokens=tokenizeMemoryRecallText(query);const metadata=normalizeRecallText([doc.title,doc.description,...doc.keywords,...doc.usageScenarios].join(" "));return queryTokens.filter(token=>metadata.includes(token)).length>=2}__name(isStrongFastMatch,"isStrongFastMatch");function hasStaleBodyInHistory(doc,bodyPresentVersions){const presentVersion=bodyPresentVersions?.get(toAutoMemoryRef(doc));return presentVersion!==void 0&&presentVersion!==doc.mtimeMs}__name(hasStaleBodyInHistory,"hasStaleBodyInHistory");function selectRelevantAutoMemoryDocuments(query,docs,limit=MAX_RELEVANT_DOCS,useStructuredMetadata=true){const queryTokens=tokenizeMemoryRecallText(query);if(queryTokens.length===0){return[]}return docs.map(doc=>({doc,score:scoreDocument(queryTokens,doc,useStructuredMetadata)})).filter(({score})=>score>0).sort((a,b2)=>b2.score-a.score||b2.doc.mtimeMs-a.doc.mtimeMs).slice(0,limit).map(({doc})=>doc)}__name(selectRelevantAutoMemoryDocuments,"selectRelevantAutoMemoryDocuments");function selectModelCandidateDocuments(query,docs,recentTools,fallbackLimit,useStructuredMetadata=true){const isActiveToolNoise=createActiveToolUsageFilter(recentTools,useStructuredMetadata);const eligible=docs.filter(doc=>!isActiveToolNoise(doc));const lexical=selectRelevantAutoMemoryDocuments(query,eligible,Math.max(MAX_MODEL_CANDIDATE_DOCS-RECENT_MODEL_CANDIDATE_RESERVE,fallbackLimit),useStructuredMetadata);const modelLexical=lexical.slice(0,MAX_MODEL_CANDIDATE_DOCS-RECENT_MODEL_CANDIDATE_RESERVE);const selected=new Set(modelLexical.map(doc=>doc.filePath));const recent=eligible.filter(doc=>!selected.has(doc.filePath)).sort((a,b2)=>b2.mtimeMs-a.mtimeMs).slice(0,MAX_MODEL_CANDIDATE_DOCS-modelLexical.length);const modelCandidates=modelLexical.flatMap((doc,index)=>{const recentDoc=recent[index];return recentDoc?[doc,recentDoc]:[doc]});modelCandidates.push(...recent.slice(modelLexical.length));return{modelCandidates,fallbackDocs:lexical.slice(0,fallbackLimit)}}__name(selectModelCandidateDocuments,"selectModelCandidateDocuments");function buildLegacyRelevantAutoMemoryPrompt(docs){if(docs.length===0)return"";return["## Relevant memory","","Use the following memories only when they are directly relevant to the current request. Verify file/function claims before relying on them.","",...docs.flatMap(doc=>{const normalized=normalizeBody(doc.body);const body=normalized.length<=MAX_DOC_BODY_CHARS?normalized:`${normalized.slice(0,MAX_DOC_BODY_CHARS).trimEnd()}
67
67
 
68
- > NOTE: Relevant memory truncated for prompt budget.`;const staleness=memoryFreshnessText(doc.mtimeMs);return[`### ${doc.title} (${doc.relativePath||path4.basename(doc.filePath)})`,`Saved ${memoryAge(doc.mtimeMs)}.`,doc.description,"",body||"_No detailed entries yet._",...staleness?["",`> NOTE: ${staleness}`]:[],""]})].join("\n")}__name(buildLegacyRelevantAutoMemoryPrompt,"buildLegacyRelevantAutoMemoryPrompt");function createRecallResult(treeSnapshot,selectedDocs,strategy,bodyPresentVersions,legacy=false){if(legacy){const focusedPrompt=buildLegacyRelevantAutoMemoryPrompt(selectedDocs);return{focusedPrompt,prompt:focusedPrompt,selectedDocs,strategy}}const rendered=renderAutoMemoryFocusedSubtree(selectedDocs,{bodyPresentVersions});return{treeSnapshot,focusedPrompt:rendered.prompt,prompt:rendered.prompt,selectedDocs:selectedDocs.slice(0,rendered.displayed),strategy}}__name(createRecallResult,"createRecallResult");function filterExcludedAutoMemoryDocuments(docs,excludedFilePaths){if(!excludedFilePaths)return docs;const excluded=new Set(excludedFilePaths);return excluded.size===0?docs:docs.filter(doc=>!excluded.has(doc.filePath))}__name(filterExcludedAutoMemoryDocuments,"filterExcludedAutoMemoryDocuments");async function rereadSelectedDocuments(docs){const reread=await Promise.all(docs.map(rereadAutoMemoryDocument));const dropped=docs.filter((_2,index)=>reread[index]===null);if(dropped.length>0){debugLogger9.warn(`Selected memory dropped before injection (unavailable or changed during the read): ${dropped.map(toAutoMemoryRef).join(", ")}`)}return reread.filter(doc=>doc!==null)}__name(rereadSelectedDocuments,"rereadSelectedDocuments");function logRecallResult(config3,abortSignal,queryLength,docsScanned,result,startedAt,timings,selectorDecided){if(!config3||abortSignal?.aborted)return;const legacy=(config3.getMemoryRecallMode?.()??"legacy")==="legacy";logMemoryRecall(config3,new MemoryRecallEvent({query_length:queryLength,docs_scanned:docsScanned,docs_selected:result.selectedDocs.length,strategy:result.strategy,duration_ms:Date.now()-startedAt,scan_duration_ms:timings.scanDurationMs,fast_duration_ms:timings.fastDurationMs,selector_duration_ms:timings.selectorDurationMs,...legacy||!selectorDecided?{}:{selector_skipped:result.selectorSkipped===true}}))}__name(logRecallResult,"logRecallResult");async function resolveRelevantAutoMemoryPromptForQuery(projectRoot,query,options2={}){const t0=Date.now();const legacy=(options2.config?.getMemoryRecallMode?.()??"legacy")==="legacy";const teamMemoryEnabled=options2.config?.getTeamMemoryEnabled?.()??false;const snapshot=legacy?await Promise.all([scanAllAutoMemoryTopicDocuments(projectRoot,options2.documentCache,options2.config?.isTrustedFolder?.()??false,true),scanAllUserAutoMemoryTopicDocuments(options2.documentCache).catch(error3=>{debugLogger9.warn(`User-level auto-memory scan failed; project-level recall continues: ${error3 instanceof Error?error3.message:String(error3)}`);return[]})]).then(([projectDocs,userDocs])=>{const sourceStatus={requestedScopes:["project","user"],searchedScopes:["project","user"],unavailableScopes:[],complete:true,incompleteScopes:[]};return{docs:[...projectDocs,...userDocs],sourceStatus}}):await scanAutoMemorySnapshot(projectRoot,{scopes:teamMemoryEnabled?[...AUTO_MEMORY_SCOPES]:void 0,teamMemoryEnabled,trustedProject:options2.config?.isTrustedFolder?.()??false,uncapped:true,documentCache:options2.documentCache});const scanDurationMs=Date.now()-t0;let fastDurationMs=0;let selectorDurationMs=0;let selectorStartedAt;const timings=__name(()=>({scanDurationMs,fastDurationMs,selectorDurationMs}),"timings");const bodyPresentVersions=options2.config?.getMemoryManager?.().getBodyPresentVersionsInHistory();const docs=legacy?filterExcludedAutoMemoryDocuments(snapshot.docs,options2.excludedFilePaths):snapshot.docs;const treeSnapshot=legacy?void 0:createAutoMemoryTreeSnapshot(docs,snapshot.sourceStatus);const limit=legacy?options2.limit??MAX_RELEVANT_DOCS:Math.min(options2.limit??MAX_RELEVANT_DOCS,MAX_RELEVANT_DOCS);if(query.trim().length===0||docs.length===0||limit<=0){const result2=createRecallResult(treeSnapshot,[],"none",bodyPresentVersions,legacy);if(!legacy&&options2.onFastResult&&!options2.abortSignal?.aborted){options2.onFastResult(result2)}logRecallResult(options2.config,options2.abortSignal,query.length,docs.length,result2,t0,timings(),false);return result2}let fallbackDocs;if(options2.config){try{const fastStartedAt=Date.now();const skipGateEnabled=!legacy&&isSkipSelectorOnUniqueStrongHitEnabled();const candidates=selectModelCandidateDocuments(query,docs,options2.recentTools??[],limit,!legacy);fallbackDocs=candidates.fallbackDocs;let publishedFast;let fastCandidateCount=0;if(options2.onFastResult&&!options2.abortSignal?.aborted){const fastDocs=legacy?fallbackDocs.slice(0,MAX_FAST_RECALL_DOCS):[...fallbackDocs.filter(doc=>hasStaleBodyInHistory(doc,bodyPresentVersions)),...fallbackDocs.filter(doc=>!hasStaleBodyInHistory(doc,bodyPresentVersions)&&isStrongFastMatch(query,doc))].slice(0,MAX_FAST_RECALL_DOCS);fastCandidateCount=fastDocs.length;if(!legacy||fastDocs.length>0){publishedFast=createRecallResult(treeSnapshot,fastDocs,fastDocs.length>0?"heuristic":"none",bodyPresentVersions,legacy);options2.onFastResult(publishedFast)}}fastDurationMs=Date.now()-fastStartedAt;const uniqueStrongHit=publishedFast?.selectedDocs[0];if(skipGateEnabled&&fastCandidateCount===1&&publishedFast?.selectedDocs.length===1&&uniqueStrongHit!==void 0&&matchesTitleOrKeyword(query,uniqueStrongHit,true)&&!bodyPresentVersions?.has(toAutoMemoryRef(uniqueStrongHit))&&!options2.abortSignal?.aborted&&candidates.modelCandidates.filter(doc=>matchesTitleOrKeyword(query,doc)||matchesTitleOrKeyword(query,doc,true)).length===1&&(await rereadSelectedDocuments([uniqueStrongHit]))[0]?.mtimeMs===uniqueStrongHit.mtimeMs&&!bodyPresentVersions?.has(toAutoMemoryRef(uniqueStrongHit))&&!options2.abortSignal?.aborted){const result3={...publishedFast,selectorSkipped:true};logRecallResult(options2.config,options2.abortSignal,query.length,docs.length,result3,t0,timings(),true);return result3}selectorStartedAt=Date.now();const modelSelectedDocs=await selectRelevantAutoMemoryDocumentsByModel(options2.config,query,candidates.modelCandidates,limit,options2.recentTools??[],options2.abortSignal);selectorDurationMs=Date.now()-selectorStartedAt;const selectedDocs2=legacy?modelSelectedDocs:await rereadSelectedDocuments(modelSelectedDocs);const strategy2=selectedDocs2.length>0?"model":"none";const result2=createRecallResult(treeSnapshot,selectedDocs2,strategy2,bodyPresentVersions,legacy);logRecallResult(options2.config,options2.abortSignal,query.length,docs.length,result2,t0,timings(),true);return result2}catch(error3){if(selectorStartedAt!==void 0&&selectorDurationMs===0){selectorDurationMs=Date.now()-selectorStartedAt}if(error3 instanceof DOMException&&error3.name==="AbortError"){if(options2.abortSignal?.aborted){debugLogger9.debug("Model-driven auto-memory recall aborted.")}else{debugLogger9.debug("Model-driven auto-memory recall timed out; using heuristic fallback.")}}else{debugLogger9.warn("Model-driven auto-memory recall failed; using heuristic fallback.",error3)}}}if(options2.abortSignal?.aborted){return{...treeSnapshot?{treeSnapshot}:{},focusedPrompt:"",prompt:"",selectedDocs:[],strategy:"none"}}const isActiveToolNoise=createActiveToolUsageFilter(options2.recentTools??[],!legacy);const selectedDocs=fallbackDocs??selectRelevantAutoMemoryDocuments(query,docs.filter(doc=>!isActiveToolNoise(doc)),limit,!legacy);const freshSelectedDocs=legacy?selectedDocs:await rereadSelectedDocuments(selectedDocs);const strategy=freshSelectedDocs.length>0?"heuristic":"none";const result=createRecallResult(treeSnapshot,freshSelectedDocs,strategy,bodyPresentVersions,legacy);logRecallResult(options2.config,options2.abortSignal,query.length,docs.length,result,t0,timings(),selectorStartedAt!==void 0);return result}__name(resolveRelevantAutoMemoryPromptForQuery,"resolveRelevantAutoMemoryPromptForQuery");init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();var RATE_LIMIT_MESSAGE_BY_AUTH={["gemini"]:"\nPlease wait and try again later. To increase your limits, request a quota increase through AI Studio, or switch to another /auth method",["vertex-ai"]:"\nPlease wait and try again later. To increase your limits, request a quota increase through Vertex, or switch to another /auth method",default:"\nPossible quota limitations in place or slow response times detected. Please wait and try again later."};var RATE_LIMIT_SUFFIXES=Object.values(RATE_LIMIT_MESSAGE_BY_AUTH);function getRateLimitMessage(authType){if(authType==="gemini"){return RATE_LIMIT_MESSAGE_BY_AUTH["gemini"]}if(authType==="vertex-ai"){return RATE_LIMIT_MESSAGE_BY_AUTH["vertex-ai"]}return RATE_LIMIT_MESSAGE_BY_AUTH.default}__name(getRateLimitMessage,"getRateLimitMessage");var API_ERROR_PREFIX="[API Error: ";var REQUEST_ID_HEADER="x-request-id";var MAX_REQUEST_ID_LENGTH=128;var SAFE_REQUEST_ID=/^[A-Za-z0-9._-]+$/;var MAX_REQUEST_ID_CAUSE_DEPTH=4;function nonBlank(value){return typeof value==="string"&&value.trim()?value.trim():void 0}__name(nonBlank,"nonBlank");function readRequestIdCandidate(error3){const record4=error3;return nonBlank(record4.requestId)??nonBlank(getHeaderValue(error3,REQUEST_ID_HEADER))??nonBlank(getHeaderValue(record4.response,REQUEST_ID_HEADER))??nonBlank(record4.requestID)??nonBlank(record4.request_id)??nonBlank(record4.response_id)??nonBlank(getRateLimitErrorDetails(error3).requestId)}__name(readRequestIdCandidate,"readRequestIdCandidate");function resolveApiErrorRequestId(error3){for(let current2=error3,depth=0;typeof current2==="object"&&current2!==null;current2=current2.cause,depth++){if(depth>MAX_REQUEST_ID_CAUSE_DEPTH)return void 0;const candidate=readRequestIdCandidate(current2);if(candidate===void 0)continue;return SAFE_REQUEST_ID.test(candidate)?candidate.substring(0,MAX_REQUEST_ID_LENGTH):void 0}return void 0}__name(resolveApiErrorRequestId,"resolveApiErrorRequestId");function isAlreadyFormatted(value){const trimmed=value.trimEnd();if(trimmed.startsWith(QUOTA_EXHAUSTED_PREFIX)){return true}if(!trimmed.startsWith(API_ERROR_PREFIX)){return false}if(trimmed.endsWith("]")){return true}return RATE_LIMIT_SUFFIXES.some(suffix=>trimmed.includes(`]${suffix}`))}__name(isAlreadyFormatted,"isAlreadyFormatted");function parseAndFormatApiError(error3,authType){if(isStructuredError(error3)){if(error3.message.startsWith("Qwen OAuth quota exceeded:")||error3.message.startsWith("Qwen OAuth free tier has been discontinued")){return error3.message}if(isAlreadyFormatted(error3.message)){return error3.message}const message=error3 instanceof Error?getErrorMessage(error3):error3.message;const requestId=resolveApiErrorRequestId(error3);const embedsRequestId=requestId!==void 0&&(message.includes(`(request_id: ${requestId})`)||message.includes(`"request_id":"${requestId}"`));let text3=requestId&&!embedsRequestId?`[API Error: ${message} (request_id: ${requestId})]`:`[API Error: ${message}]`;if(error3.status===429){text3+=getRateLimitMessage(authType)}return text3}if(typeof error3==="string"){if(isAlreadyFormatted(error3)){return error3}const jsonStart=error3.indexOf("{");if(jsonStart===-1){return`[API Error: ${error3}]`}const jsonString=error3.substring(jsonStart);try{const parsedError=JSON.parse(jsonString);if(isApiError(parsedError)){let finalMessage=parsedError.error.message;try{const nestedError=JSON.parse(finalMessage);if(isApiError(nestedError)){finalMessage=nestedError.error.message}}catch(_e2){}const statusText=parsedError.error.status?` (Status: ${parsedError.error.status})`:"";let text3=`[API Error: ${finalMessage}${statusText}]`;if(parsedError.error.code===429){text3+=getRateLimitMessage(authType)}return text3}}catch(_e2){}return`[API Error: ${error3}]`}return"[API Error: An unknown error occurred.]"}__name(parseAndFormatApiError,"parseAndFormatApiError");init_esbuild_shims();import{createHash as createHash15}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual4}from"node:util";init_esbuild_shims();init_esbuild_shims();var PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE="Tool call skipped because enter_plan_mode is an execution boundary. Retry it in the next model turn after observing the resulting approval mode.";var PLAN_MODE_LIFECYCLE_REMINDERS=[getPlanModeSystemReminder(false),getPlanModeSystemReminder(true)];function getPlanModeLifecyclePrefix(toolName,output){if(toolName!==ToolNames.ENTER_PLAN_MODE)return void 0;for(const reminder of PLAN_MODE_LIFECYCLE_REMINDERS){if(output===reminder)return reminder;const prefix2=`${reminder}
68
+ > NOTE: Relevant memory truncated for prompt budget.`;const staleness=memoryFreshnessText(doc.mtimeMs);return[`### ${doc.title} (${doc.relativePath||path4.basename(doc.filePath)})`,`Saved ${memoryAge(doc.mtimeMs)}.`,doc.description,"",body||"_No detailed entries yet._",...staleness?["",`> NOTE: ${staleness}`]:[],""]})].join("\n")}__name(buildLegacyRelevantAutoMemoryPrompt,"buildLegacyRelevantAutoMemoryPrompt");function createRecallResult(treeSnapshot,selectedDocs,strategy,bodyPresentVersions,legacy=false){if(legacy){const focusedPrompt=buildLegacyRelevantAutoMemoryPrompt(selectedDocs);return{focusedPrompt,prompt:focusedPrompt,selectedDocs,strategy}}const rendered=renderAutoMemoryFocusedSubtree(selectedDocs,{bodyPresentVersions});return{treeSnapshot,focusedPrompt:rendered.prompt,prompt:rendered.prompt,selectedDocs:selectedDocs.slice(0,rendered.displayed),strategy}}__name(createRecallResult,"createRecallResult");function filterExcludedAutoMemoryDocuments(docs,excludedFilePaths){if(!excludedFilePaths)return docs;const excluded=new Set(excludedFilePaths);return excluded.size===0?docs:docs.filter(doc=>!excluded.has(doc.filePath))}__name(filterExcludedAutoMemoryDocuments,"filterExcludedAutoMemoryDocuments");async function rereadSelectedDocuments(docs){const reread=await Promise.all(docs.map(rereadAutoMemoryDocument));const dropped=docs.filter((_2,index)=>reread[index]===null);if(dropped.length>0){debugLogger9.warn(`Selected memory dropped before injection (unavailable or changed during the read): ${dropped.map(toAutoMemoryRef).join(", ")}`)}return reread.filter(doc=>doc!==null)}__name(rereadSelectedDocuments,"rereadSelectedDocuments");function logRecallResult(config3,abortSignal,queryLength,docsScanned,result,startedAt,timings,selectorDecided){if(!config3||abortSignal?.aborted)return;const legacy=(config3.getMemoryRecallMode?.()??"legacy")==="legacy";logMemoryRecall(config3,new MemoryRecallEvent({query_length:queryLength,docs_scanned:docsScanned,docs_selected:result.selectedDocs.length,strategy:result.strategy,duration_ms:Date.now()-startedAt,scan_duration_ms:timings.scanDurationMs,fast_duration_ms:timings.fastDurationMs,selector_duration_ms:timings.selectorDurationMs,...legacy||!selectorDecided?{}:{selector_skipped:result.selectorSkipped===true}}))}__name(logRecallResult,"logRecallResult");async function resolveRelevantAutoMemoryPromptForQuery(projectRoot,query,options2={}){const t0=Date.now();const legacy=(options2.config?.getMemoryRecallMode?.()??"legacy")==="legacy";const teamMemoryEnabled=options2.config?.getTeamMemoryEnabled?.()??false;const snapshot=legacy?await Promise.all([scanAllAutoMemoryTopicDocuments(projectRoot,options2.documentCache,options2.config?.isTrustedFolder?.()??false,true),scanAllUserAutoMemoryTopicDocuments(options2.documentCache).catch(error3=>{debugLogger9.warn(`User-level auto-memory scan failed; project-level recall continues: ${error3 instanceof Error?error3.message:String(error3)}`);return[]})]).then(([projectDocs,userDocs])=>{const sourceStatus={requestedScopes:["project","user"],searchedScopes:["project","user"],unavailableScopes:[],complete:true,incompleteScopes:[]};return{docs:[...projectDocs,...userDocs],sourceStatus}}):await scanAutoMemorySnapshot(projectRoot,{scopes:teamMemoryEnabled?[...AUTO_MEMORY_SCOPES]:void 0,teamMemoryEnabled,trustedProject:options2.config?.isTrustedFolder?.()??false,uncapped:true,documentCache:options2.documentCache});const scanDurationMs=Date.now()-t0;let fastDurationMs=0;let selectorDurationMs=0;let selectorStartedAt;const timings=__name(()=>({scanDurationMs,fastDurationMs,selectorDurationMs}),"timings");const bodyPresentVersions=options2.config?.getMemoryManager?.().getBodyPresentVersionsInHistory();const docs=legacy?filterExcludedAutoMemoryDocuments(snapshot.docs,options2.excludedFilePaths):snapshot.docs;const treeSnapshot=legacy?void 0:createAutoMemoryTreeSnapshot(docs,snapshot.sourceStatus);const limit=legacy?options2.limit??MAX_RELEVANT_DOCS:Math.min(options2.limit??MAX_RELEVANT_DOCS,MAX_RELEVANT_DOCS);if(query.trim().length===0||docs.length===0||limit<=0){const result2=createRecallResult(treeSnapshot,[],"none",bodyPresentVersions,legacy);if(!legacy&&options2.onFastResult&&!options2.abortSignal?.aborted){options2.onFastResult(result2)}logRecallResult(options2.config,options2.abortSignal,query.length,docs.length,result2,t0,timings(),false);return result2}let fallbackDocs;if(options2.config){try{const fastStartedAt=Date.now();const skipGateEnabled=!legacy&&isSkipSelectorOnUniqueStrongHitEnabled();const candidates=selectModelCandidateDocuments(query,docs,options2.recentTools??[],limit,!legacy);fallbackDocs=candidates.fallbackDocs;let publishedFast;let fastCandidateCount=0;if(options2.onFastResult&&!options2.abortSignal?.aborted){const fastDocs=legacy?fallbackDocs.slice(0,MAX_FAST_RECALL_DOCS):[...fallbackDocs.filter(doc=>hasStaleBodyInHistory(doc,bodyPresentVersions)),...fallbackDocs.filter(doc=>!hasStaleBodyInHistory(doc,bodyPresentVersions)&&isStrongFastMatch(query,doc))].slice(0,MAX_FAST_RECALL_DOCS);fastCandidateCount=fastDocs.length;if(!legacy||fastDocs.length>0){publishedFast=createRecallResult(treeSnapshot,fastDocs,fastDocs.length>0?"heuristic":"none",bodyPresentVersions,legacy);options2.onFastResult(publishedFast)}}fastDurationMs=Date.now()-fastStartedAt;const uniqueStrongHit=publishedFast?.selectedDocs[0];if(skipGateEnabled&&fastCandidateCount===1&&publishedFast?.selectedDocs.length===1&&uniqueStrongHit!==void 0&&matchesTitleOrKeyword(query,uniqueStrongHit,true)&&!bodyPresentVersions?.has(toAutoMemoryRef(uniqueStrongHit))&&!options2.abortSignal?.aborted&&candidates.modelCandidates.filter(doc=>matchesTitleOrKeyword(query,doc)||matchesTitleOrKeyword(query,doc,true)).length===1&&(await rereadSelectedDocuments([uniqueStrongHit]))[0]?.mtimeMs===uniqueStrongHit.mtimeMs&&!bodyPresentVersions?.has(toAutoMemoryRef(uniqueStrongHit))&&!options2.abortSignal?.aborted){const result3={...publishedFast,selectorSkipped:true};logRecallResult(options2.config,options2.abortSignal,query.length,docs.length,result3,t0,timings(),true);return result3}selectorStartedAt=Date.now();const modelSelectedDocs=await selectRelevantAutoMemoryDocumentsByModel(options2.config,query,candidates.modelCandidates,limit,options2.recentTools??[],options2.abortSignal);selectorDurationMs=Date.now()-selectorStartedAt;const selectedDocs2=legacy?modelSelectedDocs:await rereadSelectedDocuments(modelSelectedDocs);const strategy2=selectedDocs2.length>0?"model":"none";const result2=createRecallResult(treeSnapshot,selectedDocs2,strategy2,bodyPresentVersions,legacy);logRecallResult(options2.config,options2.abortSignal,query.length,docs.length,result2,t0,timings(),true);return result2}catch(error3){if(selectorStartedAt!==void 0&&selectorDurationMs===0){selectorDurationMs=Date.now()-selectorStartedAt}if(error3 instanceof DOMException&&error3.name==="AbortError"){if(options2.abortSignal?.aborted){debugLogger9.debug("Model-driven auto-memory recall aborted.")}else{debugLogger9.debug("Model-driven auto-memory recall timed out; using heuristic fallback.")}}else{debugLogger9.warn("Model-driven auto-memory recall failed; using heuristic fallback.",error3)}}}if(options2.abortSignal?.aborted){return{...treeSnapshot?{treeSnapshot}:{},focusedPrompt:"",prompt:"",selectedDocs:[],strategy:"none"}}const isActiveToolNoise=createActiveToolUsageFilter(options2.recentTools??[],!legacy);const selectedDocs=fallbackDocs??selectRelevantAutoMemoryDocuments(query,docs.filter(doc=>!isActiveToolNoise(doc)),limit,!legacy);const freshSelectedDocs=legacy?selectedDocs:await rereadSelectedDocuments(selectedDocs);const strategy=freshSelectedDocs.length>0?"heuristic":"none";const result=createRecallResult(treeSnapshot,freshSelectedDocs,strategy,bodyPresentVersions,legacy);logRecallResult(options2.config,options2.abortSignal,query.length,docs.length,result,t0,timings(),selectorStartedAt!==void 0);return result}__name(resolveRelevantAutoMemoryPromptForQuery,"resolveRelevantAutoMemoryPromptForQuery");init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();var RATE_LIMIT_MESSAGE_BY_AUTH={["gemini"]:"\nPlease wait and try again later. To increase your limits, request a quota increase through AI Studio, or switch to another /auth method",["vertex-ai"]:"\nPlease wait and try again later. To increase your limits, request a quota increase through Vertex, or switch to another /auth method",default:"\nPossible quota limitations in place or slow response times detected. Please wait and try again later."};var RATE_LIMIT_SUFFIXES=Object.values(RATE_LIMIT_MESSAGE_BY_AUTH);function getRateLimitMessage(authType){if(authType==="gemini"){return RATE_LIMIT_MESSAGE_BY_AUTH["gemini"]}if(authType==="vertex-ai"){return RATE_LIMIT_MESSAGE_BY_AUTH["vertex-ai"]}return RATE_LIMIT_MESSAGE_BY_AUTH.default}__name(getRateLimitMessage,"getRateLimitMessage");var API_ERROR_PREFIX="[API Error: ";var REQUEST_ID_HEADER="x-request-id";var MAX_REQUEST_ID_LENGTH=128;var SAFE_REQUEST_ID=/^[A-Za-z0-9._-]+$/;var MAX_REQUEST_ID_CAUSE_DEPTH=4;function nonBlank(value){return typeof value==="string"&&value.trim()?value.trim():void 0}__name(nonBlank,"nonBlank");function readRequestIdCandidate(error3){const record4=error3;return nonBlank(record4.requestId)??nonBlank(getHeaderValue(error3,REQUEST_ID_HEADER))??nonBlank(getHeaderValue(record4.response,REQUEST_ID_HEADER))??nonBlank(record4.requestID)??nonBlank(record4.request_id)??nonBlank(record4.response_id)??nonBlank(getRateLimitErrorDetails(error3).requestId)}__name(readRequestIdCandidate,"readRequestIdCandidate");function resolveApiErrorRequestId(error3){for(let current2=error3,depth=0;typeof current2==="object"&&current2!==null;current2=current2.cause,depth++){if(depth>MAX_REQUEST_ID_CAUSE_DEPTH)return void 0;const candidate=readRequestIdCandidate(current2);if(candidate===void 0)continue;return SAFE_REQUEST_ID.test(candidate)?candidate.substring(0,MAX_REQUEST_ID_LENGTH):void 0}return void 0}__name(resolveApiErrorRequestId,"resolveApiErrorRequestId");function isAlreadyFormatted(value){const trimmed=value.trimEnd();if(trimmed.startsWith(QUOTA_EXHAUSTED_PREFIX)||trimmed.startsWith(FRIENDLY_ERROR_PREFIX)){return true}if(!trimmed.startsWith(API_ERROR_PREFIX)){return false}if(trimmed.endsWith("]")){return true}return RATE_LIMIT_SUFFIXES.some(suffix=>trimmed.includes(`]${suffix}`))}__name(isAlreadyFormatted,"isAlreadyFormatted");var FRIENDLY_ERROR_PREFIX="\u0410\u043B\u0434\u0430\u0430: ";var TOP_UP_URL="https://ali.gerege.mn/wallet";var FRIENDLY_ERRORS=[[/用户额度不足|Үлдэгдэл хүрэлцэхгүй|预扣费额度失败|insufficient user quota|insufficient_user_quota/i,`\u0422\u0430\u043D\u044B \u04AF\u043B\u0434\u044D\u0433\u0434\u044D\u043B \u0434\u0443\u0443\u0441\u0441\u0430\u043D \u0431\u0430\u0439\u043D\u0430. ${TOP_UP_URL} \u0445\u0430\u044F\u0433\u0430\u0430\u0440 \u0446\u044D\u043D\u044D\u0433\u043B\u044D\u044D\u0434 \u0434\u0430\u0445\u0438\u043D \u043E\u0440\u043E\u043B\u0434\u043E\u043D\u043E \u0443\u0443.`],[/令牌额度|token quota|insufficient_token_quota/i,"\u042D\u043D\u044D API \u0442\u04AF\u043B\u0445\u04AF\u04AF\u0440\u0438\u0439\u043D \u0445\u044F\u0437\u0433\u0430\u0430\u0440 \u0434\u0443\u0443\u0441\u0441\u0430\u043D. \u0421\u0430\u0439\u0442\u044B\u043D API \u0442\u04AF\u043B\u0445\u04AF\u04AF\u0440 \u0445\u044D\u0441\u044D\u0433\u0442 \u0445\u044F\u0437\u0433\u0430\u0430\u0440\u044B\u0433 \u043D\u044D\u043C\u044D\u0445 \u044D\u0441\u0432\u044D\u043B `gerege login` \u0430\u0436\u0438\u043B\u043B\u0443\u0443\u043B\u0436 \u0448\u0438\u043D\u044D \u0442\u04AF\u043B\u0445\u04AF\u04AF\u0440 \u0430\u0432\u043D\u0430 \u0443\u0443."],[/无效的令牌|令牌已过期|令牌已被禁用|invalid token|invalid api key|incorrect api key|\b401\b/i,"API \u0442\u04AF\u043B\u0445\u04AF\u04AF\u0440 \u0445\u04AF\u0447\u0438\u043D\u0433\u04AF\u0439, \u0438\u0434\u044D\u0432\u0445\u0433\u04AF\u0439 \u044D\u0441\u0432\u044D\u043B \u0445\u0443\u0433\u0430\u0446\u0430\u0430 \u043D\u044C \u0434\u0443\u0443\u0441\u0441\u0430\u043D \u0431\u0430\u0439\u043D\u0430. `gerege login` \u0430\u0436\u0438\u043B\u043B\u0443\u0443\u043B\u0436 \u0434\u0430\u0445\u0438\u043D \u043D\u044D\u0432\u0442\u044D\u0440\u043D\u044D \u04AF\u04AF."],[/订阅额度不足|Захиалгын эрх дууссан|no active subscription/i,"\u0417\u0430\u0445\u0438\u0430\u043B\u0433\u044B\u043D \u044D\u0440\u0445 \u0434\u0443\u0443\u0441\u0441\u0430\u043D \u044D\u0441\u0432\u044D\u043B \u0438\u0434\u044D\u0432\u0445\u0442\u044D\u0439 \u0437\u0430\u0445\u0438\u0430\u043B\u0433\u0430 \u0430\u043B\u0433\u0430. \u0421\u0430\u0439\u0442\u0430\u0430\u0441 \u0437\u0430\u0445\u0438\u0430\u043B\u0433\u0430\u0430 \u0448\u0430\u043B\u0433\u0430\u043D\u0430 \u0443\u0443."],[/无可用渠道|可用渠道不存在|no available channel|model_not_found|model.*does not exist/i,"\u042D\u043D\u044D \u0437\u0430\u0433\u0432\u0430\u0440 \u043E\u0434\u043E\u043E\u0433\u043E\u043E\u0440 \u0430\u0448\u0438\u0433\u043B\u0430\u0445 \u0431\u043E\u043B\u043E\u043C\u0436\u0433\u04AF\u0439 \u0431\u0430\u0439\u043D\u0430. /model \u043A\u043E\u043C\u0430\u043D\u0434\u0430\u0430\u0440 \u04E9\u04E9\u0440 \u0437\u0430\u0433\u0432\u0430\u0440 \u0441\u043E\u043D\u0433\u043E\u043D\u043E \u0443\u0443."],[/过于频繁|rate limit|too many requests|\b429\b/i,"\u0425\u044D\u0442 \u043E\u043B\u043E\u043D \u0445\u04AF\u0441\u044D\u043B\u0442 \u0438\u043B\u0433\u044D\u044D\u0441\u044D\u043D \u0431\u0430\u0439\u043D\u0430. \u0422\u04AF\u0440 \u0445\u04AF\u043B\u044D\u044D\u0433\u044D\u044D\u0434 \u0434\u0430\u0445\u0438\u043D \u043E\u0440\u043E\u043B\u0434\u043E\u043D\u043E \u0443\u0443."],[/context length|input length|maximum context|too many tokens|reduce the length/i,"\u042F\u0440\u0438\u0430 \u044D\u043D\u044D \u0437\u0430\u0433\u0432\u0430\u0440\u0442 \u0445\u044D\u0442 \u0443\u0440\u0442 \u0431\u043E\u043B\u0441\u043E\u043D. /compress \u044D\u0441\u0432\u044D\u043B /clear \u0430\u0436\u0438\u043B\u043B\u0443\u0443\u043B\u0430\u0430\u0434 \u0434\u0430\u0445\u0438\u043D \u043E\u0440\u043E\u043B\u0434\u043E\u043D\u043E \u0443\u0443."],[/data_inspection_failed|inappropriate content|content.?filter/i,"\u0410\u0433\u0443\u0443\u043B\u0433\u044B\u043D \u0431\u043E\u0434\u043B\u043E\u0433\u044B\u043D \u0443\u043B\u043C\u0430\u0430\u0441 \u0445\u04AF\u0441\u044D\u043B\u0442\u0438\u0439\u0433 \u0445\u0430\u0430\u0441\u0430\u043D. \u0410\u0441\u0443\u0443\u043B\u0442\u0430\u0430 \u04E9\u04E9\u0440\u04E9\u04E9\u0440 \u0442\u043E\u043C\u044A\u0451\u043E\u043B\u043D\u043E \u0443\u0443."],[/fetch failed|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|ECONNRESET|EAI_AGAIN|socket hang up|network error/i,"\u0421\u0435\u0440\u0432\u0435\u0440\u0442\u044D\u0439 \u0445\u043E\u043B\u0431\u043E\u0433\u0434\u043E\u0436 \u0447\u0430\u0434\u0441\u0430\u043D\u0433\u04AF\u0439. \u0418\u043D\u0442\u0435\u0440\u043D\u044D\u0442 \u0445\u043E\u043B\u0431\u043E\u043B\u0442\u043E\u043E \u0448\u0430\u043B\u0433\u0430\u0430\u0434 \u0434\u0430\u0445\u0438\u043D \u043E\u0440\u043E\u043B\u0434\u043E\u043D\u043E \u0443\u0443."],[/\b50[0-4]\b|bad gateway|service unavailable|gateway timeout/i,"\u0421\u0435\u0440\u0432\u0435\u0440\u0442 \u0442\u04AF\u0440 \u0437\u0443\u0443\u0440\u044B\u043D \u0430\u043B\u0434\u0430\u0430 \u0433\u0430\u0440\u043B\u0430\u0430. \u0425\u044D\u0441\u044D\u0433 \u0445\u04AF\u043B\u044D\u044D\u0433\u044D\u044D\u0434 \u0434\u0430\u0445\u0438\u043D \u043E\u0440\u043E\u043B\u0434\u043E\u043D\u043E \u0443\u0443."]];function parseAndFormatApiError(error3,authType){const input=isStructuredError(error3)?error3.message:error3;if(typeof input==="string"&&isAlreadyFormatted(input))return input;const text3=formatApiError(error3,authType);const known=FRIENDLY_ERRORS.find(([pattern])=>pattern.test(text3));return known?`${FRIENDLY_ERROR_PREFIX}${known[1]}
69
+ ${text3}`:text3}__name(parseAndFormatApiError,"parseAndFormatApiError");function formatApiError(error3,authType){if(isStructuredError(error3)){if(error3.message.startsWith("Qwen OAuth quota exceeded:")||error3.message.startsWith("Qwen OAuth free tier has been discontinued")){return error3.message}if(isAlreadyFormatted(error3.message)){return error3.message}const message=error3 instanceof Error?getErrorMessage(error3):error3.message;const requestId=resolveApiErrorRequestId(error3);const embedsRequestId=requestId!==void 0&&(message.includes(`(request_id: ${requestId})`)||message.includes(`"request_id":"${requestId}"`));let text3=requestId&&!embedsRequestId?`[API Error: ${message} (request_id: ${requestId})]`:`[API Error: ${message}]`;if(error3.status===429){text3+=getRateLimitMessage(authType)}return text3}if(typeof error3==="string"){if(isAlreadyFormatted(error3)){return error3}const jsonStart=error3.indexOf("{");if(jsonStart===-1){return`[API Error: ${error3}]`}const jsonString=error3.substring(jsonStart);try{const parsedError=JSON.parse(jsonString);if(isApiError(parsedError)){let finalMessage=parsedError.error.message;try{const nestedError=JSON.parse(finalMessage);if(isApiError(nestedError)){finalMessage=nestedError.error.message}}catch(_e2){}const statusText=parsedError.error.status?` (Status: ${parsedError.error.status})`:"";let text3=`[API Error: ${finalMessage}${statusText}]`;if(parsedError.error.code===429){text3+=getRateLimitMessage(authType)}return text3}}catch(_e2){}return`[API Error: ${error3}]`}return"[API Error: An unknown error occurred.]"}__name(formatApiError,"formatApiError");init_esbuild_shims();import{createHash as createHash15}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual4}from"node:util";init_esbuild_shims();init_esbuild_shims();var PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE="Tool call skipped because enter_plan_mode is an execution boundary. Retry it in the next model turn after observing the resulting approval mode.";var PLAN_MODE_LIFECYCLE_REMINDERS=[getPlanModeSystemReminder(false),getPlanModeSystemReminder(true)];function getPlanModeLifecyclePrefix(toolName,output){if(toolName!==ToolNames.ENTER_PLAN_MODE)return void 0;for(const reminder of PLAN_MODE_LIFECYCLE_REMINDERS){if(output===reminder)return reminder;const prefix2=`${reminder}
69
70
 
70
71
  `;if(output.startsWith(prefix2))return prefix2}return void 0}__name(getPlanModeLifecyclePrefix,"getPlanModeLifecyclePrefix");function findPlanModeEntryBatchBoundaryIndex(toolNames){if(toolNames.length<=1)return void 0;const index=toolNames.indexOf(ToolNames.ENTER_PLAN_MODE);return index===-1?void 0:index}__name(findPlanModeEntryBatchBoundaryIndex,"findPlanModeEntryBatchBoundaryIndex");init_esbuild_shims();import{Buffer as Buffer2}from"node:buffer";import{createHmac,randomBytes}from"node:crypto";var TOOL_RESULT_BOUNDARY_EVENT_NAME="qwen-code.tool_result.boundary";var TOOL_RESULT_BOUNDARY_JSON_BYTE_THRESHOLD=65536;var TOOL_RESULT_BOUNDARY_LOG_LIMIT=50;var TOOL_RESULT_BOUNDARY_LOG_WINDOW_MS=6e4;var boundaryLogger=createDebugLogger("TOOL_RESULT_BOUNDARY");var artifactKindRecord={file:true,link:true,html:true,image:true,video:true,audio:true,pdf:true,notebook:true,document:true,other:true};var artifactKinds=new Set(Object.keys(artifactKindRecord));function isToolResultBoundaryDiagnosticsEnabled(){try{return isDebugLogFileEnabled()&&boundaryLogger.isEnabled()}catch{return false}}__name(isToolResultBoundaryDiagnosticsEnabled,"isToolResultBoundaryDiagnosticsEnabled");function toolResultArtifactState(persistedOutputFiles){if(persistedOutputFiles===void 0)return"undecided";return persistedOutputFiles.length===0?"none":"reusable"}__name(toolResultArtifactState,"toolResultArtifactState");function toolResultBoundaryArtifact(persistedOutputFiles,artifacts){try{const kinds=new Set;if(persistedOutputFiles&&persistedOutputFiles.length>0){kinds.add("file")}for(const artifact of artifacts??[]){const kind=artifact.kind;kinds.add(typeof kind==="string"&&artifactKinds.has(kind)?kind:"unknown")}return{state:toolResultArtifactState(persistedOutputFiles),kinds:[...kinds]}}catch{return{state:"undecided",kinds:[]}}}__name(toolResultBoundaryArtifact,"toolResultBoundaryArtifact");function toolResultPartDiagnosticValues(value){const values=[];const parts=Array.isArray(value)?value:[value??""];for(const candidate of parts){if(typeof candidate==="string"){values.push({representation:"model_text",value:candidate});continue}const part=candidate;if(typeof part.text==="string"){values.push({representation:"model_text",value:part.text})}const response=part.functionResponse?.response;const output=response?.["output"];const error3=response?.["error"];if(typeof output==="string"){values.push({representation:"model_text",value:output})}if(typeof error3==="string"){values.push({representation:"model_text",value:error3})}}return values}__name(toolResultPartDiagnosticValues,"toolResultPartDiagnosticValues");function createToolResultBoundaryObserver(options2={}){const logger6=options2.logger??boundaryLogger;const enabled=options2.enabled??(logger6===boundaryLogger?isToolResultBoundaryDiagnosticsEnabled:()=>isDebugLogFileEnabled()&&logger6.isEnabled());let hmacKey=options2.hmacKey?Buffer2.from(options2.hmacKey):void 0;const thresholdBytes=options2.thresholdBytes??TOOL_RESULT_BOUNDARY_JSON_BYTE_THRESHOLD;const logLimit=options2.logLimit??TOOL_RESULT_BOUNDARY_LOG_LIMIT;const windowMs=options2.windowMs??TOOL_RESULT_BOUNDARY_LOG_WINDOW_MS;const now=options2.now??Date.now;let windowStartedAt=now();let emittedInWindow=0;let suppressedCount=0;return observation=>{try{if(!enabled())return false;const mutated=typeof observation.mutated==="function"?observation.mutated():observation.mutated===true;const currentTime=now();if(currentTime<windowStartedAt||currentTime-windowStartedAt>=windowMs){windowStartedAt=currentTime;emittedInWindow=0}if(mutated&&emittedInWindow>=logLimit){suppressedCount++;return true}const values=typeof observation.values==="function"?observation.values():observation.values;const oversized=!mutated&&values.some(({value})=>jsonStringExceedsByteLength(value,thresholdBytes));if(!mutated&&!oversized)return false;if(emittedInWindow>=logLimit){suppressedCount++;return true}const measuredValues=measureValues(values);hmacKey??=randomBytes(32);const activeHmacKey=hmacKey;const valueHmacs=new Map;const summaries=measuredValues.map(({value,...summary})=>{let hmacSha256=valueHmacs.get(value);if(hmacSha256===void 0){hmacSha256=hmacString(value,activeHmacKey);valueHmacs.set(value,hmacSha256)}return{...summary,hmacSha256}});const event={eventName:TOOL_RESULT_BOUNDARY_EVENT_NAME,stage:observation.stage,mutated,values:summaries,...observation.artifacts!==void 0?{artifacts:observation.artifacts.map(artifact=>({state:artifact.state==="none"||artifact.state==="reusable"?artifact.state:"undecided",kinds:[...new Set(artifact.kinds.map(kind=>kind==="unknown"||artifactKinds.has(kind)?kind:"unknown"))]}))}:{},...hmacIdentifier("sessionHmacSha256",observation.sessionId,activeHmacKey),...hmacIdentifier("promptHmacSha256",observation.promptId,activeHmacKey),...hmacIdentifier("toolCallHmacSha256",observation.toolCallId,activeHmacKey),...observation.toolCallIds!==void 0?{toolCallHmacSha256s:observation.toolCallIds.map(id6=>hmacString(id6,activeHmacKey))}:{},...hmacIdentifier("toolNameHmacSha256",observation.toolName===void 0?void 0:canonicalToolName(observation.toolName),activeHmacKey),...observation.wireUtf8Bytes!==void 0?{wireUtf8Bytes:observation.wireUtf8Bytes}:{},...suppressedCount>0?{suppressedCount}:{}};suppressedCount=0;emittedInWindow++;logger6.debug(`${TOOL_RESULT_BOUNDARY_EVENT_NAME} ${JSON.stringify(event)}`);return true}catch{return false}}}__name(createToolResultBoundaryObserver,"createToolResultBoundaryObserver");var observeBoundary=createToolResultBoundaryObserver();function observeToolResultBoundary(observation){return observeBoundary({...observation,sessionId:observation.sessionId??sessionIdContext.getStore(),promptId:observation.promptId??promptIdContext.getStore()})}__name(observeToolResultBoundary,"observeToolResultBoundary");function measureValues(values){const slots=new Map;const measurements=new Map;return values.map(({representation,value})=>{const slot=slots.get(representation)??0;slots.set(representation,slot+1);const measurement=measurements.get(value)??{codeUnits:value.length,rawUtf8Bytes:Buffer2.byteLength(value,"utf8"),jsonUtf8Bytes:jsonStringByteLength(value)};measurements.set(value,measurement);return{representation,slot,...measurement,value}})}__name(measureValues,"measureValues");function hmacIdentifier(key,value,hmacKey){return value===void 0?{}:{[key]:hmacString(value,hmacKey)}}__name(hmacIdentifier,"hmacIdentifier");function hmacString(value,hmacKey){const byteLength2=value.length*2;const prefix2=Buffer2.alloc(8);prefix2.writeBigUInt64BE(BigInt(byteLength2));return createHmac("sha256",hmacKey).update(prefix2).update(value,"utf16le").digest("hex")}__name(hmacString,"hmacString");function jsonStringByteLength(value,stopAfterBytes=Number.POSITIVE_INFINITY){let bytes=2;for(let index=0;index<value.length&&bytes<=stopAfterBytes;index++){const code=value.charCodeAt(index);if(code===34||code===92){bytes+=2}else if(code<=31){bytes+=code===8||code===9||code===10||code===12||code===13?2:6}else if(code<=127){bytes+=1}else if(code<=2047){bytes+=2}else if(code>=55296&&code<=56319){const next=value.charCodeAt(index+1);if(next>=56320&&next<=57343){bytes+=4;index++}else{bytes+=6}}else if(code>=56320&&code<=57343){bytes+=6}else{bytes+=3}}return bytes}__name(jsonStringByteLength,"jsonStringByteLength");function jsonStringExceedsByteLength(value,threshold){return jsonStringByteLength(value,threshold)>threshold}__name(jsonStringExceedsByteLength,"jsonStringExceedsByteLength");init_esbuild_shims();var recoveryKey=Symbol("tool-output-recovery");function defineRecovery(part,recovery){Object.defineProperty(part,recoveryKey,{value:recovery,enumerable:false,writable:true,configurable:true});return part}__name(defineRecovery,"defineRecovery");function getToolOutputRecovery(part){return part[recoveryKey]}__name(getToolOutputRecovery,"getToolOutputRecovery");function setToolOutputRecovery(part,recovery){defineRecovery(part,recovery)}__name(setToolOutputRecovery,"setToolOutputRecovery");function attachToolOutputRecovery(parts,recovery){return parts.map(part=>defineRecovery({...part},recovery))}__name(attachToolOutputRecovery,"attachToolOutputRecovery");var debugLogger10=createDebugLogger("TOOL_RESPONSE_FINALIZER");var TOOL_OUTPUT_TRUNCATED_NOTICE="Tool output truncated.";var associatedFinalizerResponses=new WeakSet;function consumeAssociatedFinalizerEntries(entries){const associated=new Set;for(let index=0;index<entries.length;index++){const responseParts=entries[index].responseParts;if(associatedFinalizerResponses.has(responseParts)){associated.add(index);associatedFinalizerResponses.delete(responseParts)}}return associated}__name(consumeAssociatedFinalizerEntries,"consumeAssociatedFinalizerEntries");function associateFinalizerEntries(entries,indexes){for(const index of indexes){associatedFinalizerResponses.add(entries[index].responseParts)}}__name(associateFinalizerEntries,"associateFinalizerEntries");function observeFinalizerEntries(config3,stage,entries,mutatedEntryIndexes,promptIds,entryIndexes){for(let index=0;index<entries.length;index++){if(entryIndexes&&!entryIndexes.has(index))continue;const entry=entries[index];try{observeToolResultBoundary({stage,sessionId:config3.getSessionId?.(),promptId:promptIds?.get(entry.callId),toolCallId:entry.callId,toolName:entry.toolName,mutated:mutatedEntryIndexes.has(index),artifacts:[toolResultBoundaryArtifact(entry.persistedOutputFiles,entry.artifacts)],values:__name(()=>toolResultPartDiagnosticValues(entry.responseParts),"values")})}catch{}}}__name(observeFinalizerEntries,"observeFinalizerEntries");function recoveryOf(entry,part){const recovery=getToolOutputRecovery(part);return{...recovery,persistedOutputFiles:entry.persistedOutputFiles??recovery?.persistedOutputFiles}}__name(recoveryOf,"recoveryOf");function recoveryHeader(files){return files?.length?files.length===1?`Tool output truncated. Persisted tool-output artifact: ${files[0]}`:`Tool output truncated. Persisted tool-output artifacts:
71
72
  ${files.map(file=>`- ${file}`).join("\n")}`:TOOL_OUTPUT_TRUNCATED_NOTICE}__name(recoveryHeader,"recoveryHeader");function minimumRecoveryBudget(slot){const text3=slot.recovery?.text;return recoveryHeader(slot.recovery?.persistedOutputFiles).length+(text3?text3.length+2:0)+3}__name(minimumRecoveryBudget,"minimumRecoveryBudget");function isBudgetExemptOutputName(name2){const canonical=canonicalToolName(name2??"");return canonical===ToolNames.SEARCH_MEMORY||canonical===ToolNames.TOOL_SEARCH}__name(isBudgetExemptOutputName,"isBudgetExemptOutputName");function isBudgetShrinkablePart(part){return collectTextSlots([{callId:"",toolName:"",responseParts:[part]}],false).length>0}__name(isBudgetShrinkablePart,"isBudgetShrinkablePart");function collectTextSlots(entries,includeTopLevelText=true,excludeBudgetExemptOutput=true){const slots=[];for(let entryIndex=0;entryIndex<entries.length;entryIndex++){const entry=entries[entryIndex];const entryName=canonicalToolName(entry.toolName);if(entryName===ToolNames.SEARCH_MEMORY||entryName===ToolNames.TOOL_SEARCH)continue;const parts=entry.responseParts;for(let partIndex=0;partIndex<parts.length;partIndex++){const part=parts[partIndex];if(entry.persistedOutputFiles!==void 0){setToolOutputRecovery(part,recoveryOf(entry,part))}if(includeTopLevelText&&typeof part.text==="string"){const recovery=recoveryOf(entry,part);slots.push({entryIndex,partIndex,field:"text",text:part.text,recovery})}const response=part.functionResponse?.response;const output=response?.["output"];const error3=response?.["error"];const responseName=canonicalToolName(part.functionResponse?.name??entry.toolName);const budgetExemptOutput=excludeBudgetExemptOutput&&isBudgetExemptOutputName(responseName);if(typeof output==="string"&&!budgetExemptOutput){const protectedPrefix=excludeBudgetExemptOutput?getPlanModeLifecyclePrefix(part.functionResponse?.name??entry.toolName,output):void 0;const budgetedOutput=protectedPrefix?output.slice(protectedPrefix.length):output;if(budgetedOutput.length>0){const recovery=recoveryOf(entry,part);slots.push({entryIndex,partIndex,field:"output",text:budgetedOutput,...protectedPrefix?{protectedPrefix}:{},recovery})}}if(typeof error3==="string"){const recovery=recoveryOf(entry,part);slots.push({entryIndex,partIndex,field:"error",text:error3,recovery})}}}return slots}__name(collectTextSlots,"collectTextSlots");function allocateTextBudget(lengths,budget){const allocations=new Array(lengths.length).fill(0);let remaining=Math.max(0,Math.floor(budget));let active=lengths.map((_2,index)=>index);while(active.length>0){const share=Math.floor(remaining/active.length);const fixed2=active.filter(index=>lengths[index]<=share);if(fixed2.length===0){for(const index of active){allocations[index]=share}let remainder=remaining-share*active.length;for(const index of active){if(remainder===0)break;allocations[index]++;remainder--}break}const fixedSet=new Set(fixed2);for(const index of fixed2){allocations[index]=lengths[index];remaining-=lengths[index]}active=active.filter(index=>!fixedSet.has(index))}return allocations}__name(allocateTextBudget,"allocateTextBudget");function sliceStartWithoutBrokenSurrogate(text3,length){let end=Math.min(Math.max(0,length),text3.length);if(end>0){const last=text3.charCodeAt(end-1);if(last>=55296&&last<=56319)end--}return text3.slice(0,end)}__name(sliceStartWithoutBrokenSurrogate,"sliceStartWithoutBrokenSurrogate");function sliceEndWithoutBrokenSurrogate(text3,length){let start=Math.max(0,text3.length-Math.max(0,length));if(start<text3.length){const first=text3.charCodeAt(start);if(first>=56320&&first<=57343)start++}return text3.slice(start)}__name(sliceEndWithoutBrokenSurrogate,"sliceEndWithoutBrokenSurrogate");function fitText(text3,maxChars,persistedOutputFiles,recovery){if(text3.length<=maxChars)return text3;if(maxChars<=0)return"";const preserved=recovery?.text??"";const preservedSize=preserved?preserved.length+2:0;const pointer=recoveryHeader(persistedOutputFiles);const header=pointer.length+preservedSize+3<=maxChars?pointer:TOOL_OUTPUT_TRUNCATED_NOTICE;if(header.length>maxChars){return sliceStartWithoutBrokenSurrogate(TOOL_OUTPUT_TRUNCATED_NOTICE,maxChars)}const separator="\n\n";const marker="\n...\n";let body=text3;for(const owned of[pointer,preserved,...recovery?.persistedOutputFiles??[]]){if(owned)body=body.split(owned).join("")}const preservedBlock=preserved?`${separator}${preserved}`:"";const previewBudget=maxChars-header.length-preservedBlock.length-separator.length;if(previewBudget<=0){return header}if(body.length<=previewBudget){return`${header}${preservedBlock}${separator}${body}`}if(previewBudget<=marker.length){return`${header}${preservedBlock}${separator}${sliceStartWithoutBrokenSurrogate(body,previewBudget)}`}const contentBudget=previewBudget-marker.length;const headBudget=Math.floor(contentBudget/5);const tailBudget=contentBudget-headBudget;return`${header}${preservedBlock}${separator}${sliceStartWithoutBrokenSurrogate(body,headBudget)}${marker}${sliceEndWithoutBrokenSurrogate(body,tailBudget)}`}__name(fitText,"fitText");function replaceTextSlots(entries,slots,allocations){const result=entries.map(entry=>({...entry,responseParts:[...entry.responseParts]}));for(let index=0;index<slots.length;index++){const slot=slots[index];if(slot.text.length<=allocations[index])continue;const entry=result[slot.entryIndex];const part=entry.responseParts[slot.partIndex];const files=entry.persistedOutputFiles??slot.recovery?.persistedOutputFiles;const recovery={...slot.recovery,persistedOutputFiles:files};const replacement=fitText(slot.text,allocations[index],files,slot.recovery);const updated={...part};if(slot.field==="text"){updated.text=replacement}else{const functionResponse=part.functionResponse;if(!functionResponse)continue;updated.functionResponse={...functionResponse,response:{...functionResponse.response,[slot.field]:slot.protectedPrefix?`${slot.protectedPrefix}${replacement}`:replacement}}}setToolOutputRecovery(updated,recovery);entry.responseParts[slot.partIndex]=updated}return result}__name(replaceTextSlots,"replaceTextSlots");function toolResponseTextLength(parts){return collectTextSlots([{callId:"",toolName:"",responseParts:parts}],true,false).reduce((total,slot)=>total+slot.text.length,0)}__name(toolResponseTextLength,"toolResponseTextLength");function minimumFunctionResponseContent(parts){const entries=[{callId:"",toolName:"",responseParts:parts}];const slots=collectTextSlots(entries,false);const allocations=slots.map(slot=>slot.recovery?.text||slot.recovery?.persistedOutputFiles?.length?Math.min(slot.text.length,minimumRecoveryBudget(slot)):0);return{parts:replaceTextSlots(entries,slots,allocations)[0].responseParts,budgetedChars:allocations.reduce((sum,value)=>sum+value,0)}}__name(minimumFunctionResponseContent,"minimumFunctionResponseContent");function enforceFunctionResponseBudget(entries,budget,allowZeroBudget=false,stampProvenance=true){if(!Number.isFinite(budget)||budget<0||budget===0&&!allowZeroBudget)return entries;const slots=collectTextSlots(entries,false);const total=slots.reduce((sum,slot)=>sum+slot.text.length,0);if(total<=budget)return entries;const allocations=allocateTextBudget(slots.map(slot=>slot.text.length),budget);if(slots.some((slot,index)=>slot.text.length>allocations[index]&&(slot.recovery?.text||slot.recovery?.persistedOutputFiles?.length)&&allocations[index]<minimumRecoveryBudget(slot)))return entries;const reduced=replaceTextSlots(entries,slots,allocations);for(let index=0;index<reduced.length;index++)for(let partIndex=0;partIndex<reduced[index].responseParts.length;partIndex++){const part=reduced[index].responseParts[partIndex];if(stampProvenance&&part!==entries[index].responseParts[partIndex])updateToolOutputBudget([part],budget,"send_guard")}return reduced}__name(enforceFunctionResponseBudget,"enforceFunctionResponseBudget");async function finalizeToolResponses(config3,entries,promptIds,observeBoundary2=true,associateBoundary=false,budgetOverride,includeTopLevelText=true,budgetSource="batch",logResultSize=true){const shouldAssociateBoundary=observeBoundary2&&associateBoundary;const associatedEntryIndexes=observeBoundary2?consumeAssociatedFinalizerEntries(entries):new Set;const observationIndexes=__name(mutatedEntryIndexes=>new Set(entries.flatMap((_2,index)=>mutatedEntryIndexes.has(index)||!associatedEntryIndexes.has(index)?[index]:[])),"observationIndexes");const observeUnchangedEntries=__name(()=>{if(!observeBoundary2)return;const unchanged=new Set;const indexes2=observationIndexes(unchanged);observeFinalizerEntries(config3,"finalizer_input",entries,unchanged,promptIds,indexes2);observeFinalizerEntries(config3,"finalizer_output",entries,unchanged,promptIds,indexes2)},"observeUnchangedEntries");const budget=budgetOverride??config3.getToolOutputBatchBudget?.()??Number.POSITIVE_INFINITY;if(!Number.isFinite(budget)||budget<0||budget===0&&budgetOverride===void 0){observeUnchangedEntries();if(shouldAssociateBoundary)associateFinalizerEntries(entries,new Set(entries.keys()));return entries}const slots=collectTextSlots(entries,includeTopLevelText);const total=slots.reduce((sum,slot)=>sum+slot.text.length,0);if(total<=budget){observeUnchangedEntries();if(shouldAssociateBoundary)associateFinalizerEntries(entries,new Set(entries.keys()));return entries}const allocations=allocateTextBudget(slots.map(slot=>slot.text.length),budget);if(slots.some((slot,index)=>slot.text.length>allocations[index]&&(budgetOverride!==void 0||slot.recovery?.text||slot.recovery?.persistedOutputFiles?.length)&&allocations[index]<minimumRecoveryBudget(slot))){observeUnchangedEntries();if(shouldAssociateBoundary)associateFinalizerEntries(entries,new Set(entries.keys()));return entries}const entriesToPersist=new Set;for(let index=0;index<slots.length;index++){if(slots[index].text.length>allocations[index]){entriesToPersist.add(slots[index].entryIndex)}}const indexes=observationIndexes(entriesToPersist);if(observeBoundary2)observeFinalizerEntries(config3,"finalizer_input",entries,entriesToPersist,promptIds,indexes);const withPersistence=[...entries];const normalizedCallIds=entries.map(entry=>normalizeToolResultCallId(entry.callId));const normalizedCallIdCounts=new Map;for(const callId of normalizedCallIds){if(!callId)continue;normalizedCallIdCounts.set(callId,(normalizedCallIdCounts.get(callId)??0)+1)}const reservedCallIds=new Set(normalizedCallIds.filter(callId=>!!callId));const usedCallIds=new Set;for(const entryIndex of entriesToPersist){const entry=withPersistence[entryIndex];const previousFiles=entry.persistedOutputFiles??entry.responseParts.map(getToolOutputRecovery).find(recovery=>recovery?.persistedOutputFiles!==void 0)?.persistedOutputFiles;if(previousFiles!==void 0){withPersistence[entryIndex]={...entry,persistedOutputFiles:previousFiles};continue}const content=slots.filter(slot=>slot.entryIndex===entryIndex).map(slot=>slot.text).join("\n\n");try{const normalizedCallId=normalizedCallIds[entryIndex];let persistenceCallId=entry.callId;if(normalizedCallId){if(normalizedCallIdCounts.get(normalizedCallId)===1&&!usedCallIds.has(normalizedCallId)){persistenceCallId=normalizedCallId}else{let suffix=1;let candidate=`${normalizedCallId}-${suffix}`;while(reservedCallIds.has(candidate)||usedCallIds.has(candidate)){suffix++;candidate=`${normalizedCallId}-${suffix}`}persistenceCallId=candidate}usedCallIds.add(persistenceCallId)}const persisted=await persistAndTruncateToolResult(persistenceCallId,entry.toolName,content,config3,promptIds?.get(entry.callId));withPersistence[entryIndex]={...entry,persistedOutputFiles:persisted.outputFile?[persisted.outputFile]:[]}}catch{withPersistence[entryIndex]={...entry,persistedOutputFiles:[]}}}const finalized=replaceTextSlots(withPersistence,slots,allocations);for(let index=0;index<finalized.length;index++){if(!entriesToPersist.has(index))continue;const entry=finalized[index];for(let partIndex=0;partIndex<entry.responseParts.length;partIndex++){const part=entry.responseParts[partIndex];if(part!==entries[index].responseParts[partIndex])updateToolOutputBudget([part],budget,budgetSource)}if(!logResultSize)continue;try{const before=measureToolOutput(entries[index].responseParts,config3);const after=measureToolOutput(entry.responseParts,config3);const provenance=entry.responseParts.map(getToolOutputProvenance).find(Boolean);logToolResultSize(config3,new ToolResultSizeEvent(provenance?.toolName??entry.toolName,provenance?.toolType??(entry.toolName.startsWith("mcp__")?"mcp":"native"),"batch",before.chars,after.chars,before.estimatedTokens,after.estimatedTokens,true,budget,budgetSource,entry.callId,promptIds?.get(entry.callId)))}catch{}}if(observeBoundary2)observeFinalizerEntries(config3,"finalizer_output",finalized,entriesToPersist,promptIds,indexes);if(shouldAssociateBoundary){associateFinalizerEntries(finalized,new Set(finalized.keys()))}const finalizedTotal=collectTextSlots(finalized,includeTopLevelText).reduce((sum,slot)=>sum+slot.text.length,0);debugLogger10.info(`Tool response budget (${budget} chars): reduced ${entriesToPersist.size} result(s) from ${total} to ${finalizedTotal} chars.`);return finalized}__name(finalizeToolResponses,"finalizeToolResponses");init_esbuild_shims();init_esbuild_shims();function _getDefaults(){return{async:false,breaks:false,extensions:null,gfm:true,hooks:null,pedantic:false,renderer:null,silent:false,tokenizer:null,walkTokens:null}}__name(_getDefaults,"_getDefaults");var _defaults=_getDefaults();function changeDefaults(newDefaults){_defaults=newDefaults}__name(changeDefaults,"changeDefaults");var noopTest={exec:__name(()=>null,"exec")};function edit(regex,opt=""){let source=typeof regex==="string"?regex:regex.source;const obj={replace:__name((name2,val)=>{let valSource=typeof val==="string"?val:val.source;valSource=valSource.replace(other.caret,"$1");source=source.replace(name2,valSource);return obj},"replace"),getRegex:__name(()=>{return new RegExp(source,opt)},"getRegex")};return obj}__name(edit,"edit");var other={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:__name(bull=>new RegExp(`^( {0,3}${bull})((?:[ ][^\\n]*)?(?:\\n|$))`),"listItemRegex"),nextBulletRegex:__name(indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),"nextBulletRegex"),hrRegex:__name(indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),"hrRegex"),fencesBeginRegex:__name(indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:\`\`\`|~~~)`),"fencesBeginRegex"),headingBeginRegex:__name(indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}#`),"headingBeginRegex"),htmlBeginRegex:__name(indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}<(?:[a-z].*>|!--)`,"i"),"htmlBeginRegex")};var newline=/^(?:[ \t]*(?:\n|$))+/;var blockCode=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;var fences=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;var hr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;var heading=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;var bullet=/(?:[*+-]|\d{1,9}[.)])/;var lheadingCore=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/;var lheading=edit(lheadingCore).replace(/bull/g,bullet).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex();var lheadingGfm=edit(lheadingCore).replace(/bull/g,bullet).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex();var _paragraph=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;var blockText=/^[^\n]+/;var _blockLabel=/(?!\s*\])(?:\\.|[^\[\]\\])+/;var def=edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",_blockLabel).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();var list=edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,bullet).getRegex();var _tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";var _comment=/<!--(?:-?>|[\s\S]*?(?:-->|$))/;var html=edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",_comment).replace("tag",_tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();var paragraph=edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex();var blockquote=edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",paragraph).getRegex();var blockNormal={blockquote,code:blockCode,def,fences,heading,hr,html,lheading,list,newline,paragraph,table:noopTest,text:blockText};var gfmTable=edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex();var blockGfm={...blockNormal,lheading:lheadingGfm,table:gfmTable,paragraph:edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",gfmTable).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex()};var blockPedantic={...blockNormal,html:edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:noopTest,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:edit(_paragraph).replace("hr",hr).replace("heading"," *#{1,6} *[^\n]").replace("lheading",lheading).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()};var escape2=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;var inlineCode=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;var br=/^( {2,}|\\)\n(?!\s*$)/;var inlineText=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;var _punctuation=/[\p{P}\p{S}]/u;var _punctuationOrSpace=/[\s\p{P}\p{S}]/u;var _notPunctuationOrSpace=/[^\s\p{P}\p{S}]/u;var punctuation=edit(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,_punctuationOrSpace).getRegex();var _punctuationGfmStrongEm=/(?!~)[\p{P}\p{S}]/u;var _punctuationOrSpaceGfmStrongEm=/(?!~)[\s\p{P}\p{S}]/u;var _notPunctuationOrSpaceGfmStrongEm=/(?:[^\s\p{P}\p{S}]|~)/u;var blockSkip=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g;var emStrongLDelimCore=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/;var emStrongLDelim=edit(emStrongLDelimCore,"u").replace(/punct/g,_punctuation).getRegex();var emStrongLDelimGfm=edit(emStrongLDelimCore,"u").replace(/punct/g,_punctuationGfmStrongEm).getRegex();var emStrongRDelimAstCore="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)";var emStrongRDelimAst=edit(emStrongRDelimAstCore,"gu").replace(/notPunctSpace/g,_notPunctuationOrSpace).replace(/punctSpace/g,_punctuationOrSpace).replace(/punct/g,_punctuation).getRegex();var emStrongRDelimAstGfm=edit(emStrongRDelimAstCore,"gu").replace(/notPunctSpace/g,_notPunctuationOrSpaceGfmStrongEm).replace(/punctSpace/g,_punctuationOrSpaceGfmStrongEm).replace(/punct/g,_punctuationGfmStrongEm).getRegex();var emStrongRDelimUnd=edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,_notPunctuationOrSpace).replace(/punctSpace/g,_punctuationOrSpace).replace(/punct/g,_punctuation).getRegex();var anyPunctuation=edit(/\\(punct)/,"gu").replace(/punct/g,_punctuation).getRegex();var autolink=edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();var _inlineComment=edit(_comment).replace("(?:-->|$)","-->").getRegex();var tag=edit("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",_inlineComment).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();var _inlineLabel=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;var link=edit(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",_inlineLabel).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();var reflink=edit(/^!?\[(label)\]\[(ref)\]/).replace("label",_inlineLabel).replace("ref",_blockLabel).getRegex();var nolink=edit(/^!?\[(ref)\](?:\[\])?/).replace("ref",_blockLabel).getRegex();var reflinkSearch=edit("reflink|nolink(?!\\()","g").replace("reflink",reflink).replace("nolink",nolink).getRegex();var inlineNormal={_backpedal:noopTest,anyPunctuation,autolink,blockSkip,br,code:inlineCode,del:noopTest,emStrongLDelim,emStrongRDelimAst,emStrongRDelimUnd,escape:escape2,link,nolink,punctuation,reflink,reflinkSearch,tag,text:inlineText,url:noopTest};var inlinePedantic={...inlineNormal,link:edit(/^!?\[(label)\]\((.*?)\)/).replace("label",_inlineLabel).getRegex(),reflink:edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",_inlineLabel).getRegex()};var inlineGfm={...inlineNormal,emStrongRDelimAst:emStrongRDelimAstGfm,emStrongLDelim:emStrongLDelimGfm,url:edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/};var inlineBreaks={...inlineGfm,br:edit(br).replace("{2,}","*").getRegex(),text:edit(inlineGfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};var block={normal:blockNormal,gfm:blockGfm,pedantic:blockPedantic};var inline={normal:inlineNormal,gfm:inlineGfm,breaks:inlineBreaks,pedantic:inlinePedantic};var escapeReplacements={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};var getEscapeReplacement=__name(ch=>escapeReplacements[ch],"getEscapeReplacement");function escape22(html2,encode3){if(encode3){if(other.escapeTest.test(html2)){return html2.replace(other.escapeReplace,getEscapeReplacement)}}else{if(other.escapeTestNoEncode.test(html2)){return html2.replace(other.escapeReplaceNoEncode,getEscapeReplacement)}}return html2}__name(escape22,"escape2");function cleanUrl(href){try{href=encodeURI(href).replace(other.percentDecode,"%")}catch{return null}return href}__name(cleanUrl,"cleanUrl");function splitCells(tableRow,count4){const row=tableRow.replace(other.findPipe,(match,offset2,str)=>{let escaped=false;let curr=offset2;while(--curr>=0&&str[curr]==="\\")escaped=!escaped;if(escaped){return"|"}else{return" |"}}),cells=row.split(other.splitPipe);let i=0;if(!cells[0].trim()){cells.shift()}if(cells.length>0&&!cells.at(-1)?.trim()){cells.pop()}if(count4){if(cells.length>count4){cells.splice(count4)}else{while(cells.length<count4)cells.push("")}}for(;i<cells.length;i++){cells[i]=cells[i].trim().replace(other.slashPipe,"|")}return cells}__name(splitCells,"splitCells");function rtrim(str,c,invert){const l=str.length;if(l===0){return""}let suffLen=0;while(suffLen<l){const currChar=str.charAt(l-suffLen-1);if(currChar===c&&!invert){suffLen++}else if(currChar!==c&&invert){suffLen++}else{break}}return str.slice(0,l-suffLen)}__name(rtrim,"rtrim");function findClosingBracket(str,b2){if(str.indexOf(b2[1])===-1){return-1}let level=0;for(let i=0;i<str.length;i++){if(str[i]==="\\"){i++}else if(str[i]===b2[0]){level++}else if(str[i]===b2[1]){level--;if(level<0){return i}}}if(level>0){return-2}return-1}__name(findClosingBracket,"findClosingBracket");function outputLink(cap,link22,raw,lexer2,rules){const href=link22.href;const title=link22.title||null;const text3=cap[1].replace(rules.other.outputLinkReplace,"$1");lexer2.state.inLink=true;const token={type:cap[0].charAt(0)==="!"?"image":"link",raw,href,title,text:text3,tokens:lexer2.inlineTokens(text3)};lexer2.state.inLink=false;return token}__name(outputLink,"outputLink");function indentCodeCompensation(raw,text3,rules){const matchIndentToCode=raw.match(rules.other.indentCodeCompensation);if(matchIndentToCode===null){return text3}const indentToCode=matchIndentToCode[1];return text3.split("\n").map(node=>{const matchIndentInNode=node.match(rules.other.beginningSpace);if(matchIndentInNode===null){return node}const[indentInNode]=matchIndentInNode;if(indentInNode.length>=indentToCode.length){return node.slice(indentToCode.length)}return node}).join("\n")}__name(indentCodeCompensation,"indentCodeCompensation");var _Tokenizer=class{static{__name(this,"_Tokenizer")}options;rules;lexer;constructor(options2){this.options=options2||_defaults}space(src){const cap=this.rules.block.newline.exec(src);if(cap&&cap[0].length>0){return{type:"space",raw:cap[0]}}}code(src){const cap=this.rules.block.code.exec(src);if(cap){const text3=cap[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:cap[0],codeBlockStyle:"indented",text:!this.options.pedantic?rtrim(text3,"\n"):text3}}}fences(src){const cap=this.rules.block.fences.exec(src);if(cap){const raw=cap[0];const text3=indentCodeCompensation(raw,cap[3]||"",this.rules);return{type:"code",raw,lang:cap[2]?cap[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):cap[2],text:text3}}}heading(src){const cap=this.rules.block.heading.exec(src);if(cap){let text3=cap[2].trim();if(this.rules.other.endingHash.test(text3)){const trimmed=rtrim(text3,"#");if(this.options.pedantic){text3=trimmed.trim()}else if(!trimmed||this.rules.other.endingSpaceChar.test(trimmed)){text3=trimmed.trim()}}return{type:"heading",raw:cap[0],depth:cap[1].length,text:text3,tokens:this.lexer.inline(text3)}}}hr(src){const cap=this.rules.block.hr.exec(src);if(cap){return{type:"hr",raw:rtrim(cap[0],"\n")}}}blockquote(src){const cap=this.rules.block.blockquote.exec(src);if(cap){let lines=rtrim(cap[0],"\n").split("\n");let raw="";let text3="";const tokens=[];while(lines.length>0){let inBlockquote=false;const currentLines=[];let i;for(i=0;i<lines.length;i++){if(this.rules.other.blockquoteStart.test(lines[i])){currentLines.push(lines[i]);inBlockquote=true}else if(!inBlockquote){currentLines.push(lines[i])}else{break}}lines=lines.slice(i);const currentRaw=currentLines.join("\n");const currentText=currentRaw.replace(this.rules.other.blockquoteSetextReplace,"\n $1").replace(this.rules.other.blockquoteSetextReplace2,"");raw=raw?`${raw}
@@ -96,7 +97,7 @@ ${safeBody}
96
97
  `}return`
97
98
  [... truncated from ${value.length} characters for CLI history display ...]
98
99
  `}__name(buildStringCompactionMarker,"buildStringCompactionMarker");function buildAnsiOutputCompactionMarker(omitted,purpose){const target=purpose==="recording"?"saved session preview":"CLI history display";return`[... ${omitted} terminal lines omitted from ${target} ...]`}__name(buildAnsiOutputCompactionMarker,"buildAnsiOutputCompactionMarker");function compactString(value,purpose,limit=MAX_RETAINED_TOOL_RESULT_DISPLAY_CHARS){if(value.length<=limit){return value}const marker=buildStringCompactionMarker(value,purpose);if(marker.length>=limit){return copyString(value.slice(0,safeHeadEnd(value,Math.max(0,limit))))}const contentBudget=Math.max(0,limit-marker.length);const headLength=Math.ceil(contentBudget*.6);const tailLength=contentBudget-headLength;const headEnd=safeHeadEnd(value,headLength);const tailStart=safeTailStart(value,value.length-tailLength);const head=copyString(value.slice(0,headEnd));const tail=tailLength>0?copyString(value.slice(tailStart)):"";return head+marker+tail}__name(compactString,"compactString");function isFileDiffDisplay(resultDisplay){if(typeof resultDisplay!=="object"||resultDisplay===null||!("fileDiff"in resultDisplay)||!("fileName"in resultDisplay)||!("originalContent"in resultDisplay)||!("newContent"in resultDisplay)){return false}const display=resultDisplay;const originalContent=display["originalContent"];return typeof display["fileDiff"]==="string"&&typeof display["fileName"]==="string"&&typeof display["newContent"]==="string"&&(originalContent===null||typeof originalContent==="string")}__name(isFileDiffDisplay,"isFileDiffDisplay");function compactFileDiff(display,purpose){const fileDiffLength=display.fileDiff.length;const originalContentLength=typeof display.originalContent==="string"?display.originalContent.length:0;const newContentLength=display.newContent.length;const fileDiffTruncated=fileDiffLength>MAX_RETAINED_FILE_DIFF_CHARS;const originalContentTruncated=originalContentLength>MAX_RETAINED_FILE_CONTENT_CHARS;const newContentTruncated=newContentLength>MAX_RETAINED_FILE_CONTENT_CHARS;if(!fileDiffTruncated&&!originalContentTruncated&&!newContentTruncated){return display}return{...display,fileDiff:compactString(display.fileDiff,purpose,MAX_RETAINED_FILE_DIFF_CHARS),originalContent:typeof display.originalContent==="string"?compactString(display.originalContent,purpose,MAX_RETAINED_FILE_CONTENT_CHARS):display.originalContent,newContent:compactString(display.newContent,purpose,MAX_RETAINED_FILE_CONTENT_CHARS),truncatedForSession:true,fileDiffLength,originalContentLength,newContentLength,fileDiffTruncated,originalContentTruncated,newContentTruncated}}__name(compactFileDiff,"compactFileDiff");function isAnsiOutputDisplay(resultDisplay){return typeof resultDisplay==="object"&&resultDisplay!==null&&"ansiOutput"in resultDisplay&&Array.isArray(resultDisplay.ansiOutput)}__name(isAnsiOutputDisplay,"isAnsiOutputDisplay");function markerAnsiLine(text3){return[{text:text3,bold:false,italic:false,underline:false,dim:true,inverse:false,fg:"",bg:""}]}__name(markerAnsiLine,"markerAnsiLine");function compactAnsiLine(line2,purpose){let changed=false;const compactedLine=line2.map(token=>{const compactedText=compactString(token.text,purpose);if(compactedText!==token.text){changed=true;return{...token,text:compactedText}}return token});return changed?compactedLine:line2}__name(compactAnsiLine,"compactAnsiLine");function compactAnsiOutput(output,purpose){if(output.length<=MAX_RETAINED_ANSI_OUTPUT_LINES){let changed=false;const compactedOutput=output.map(line2=>{const compactedLine=compactAnsiLine(line2,purpose);if(compactedLine!==line2){changed=true}return compactedLine});return changed?compactedOutput:output}const omitted=output.length-MAX_RETAINED_ANSI_OUTPUT_LINES+1;return[markerAnsiLine(buildAnsiOutputCompactionMarker(omitted,purpose)),...output.slice(-(MAX_RETAINED_ANSI_OUTPUT_LINES-1)).map(line2=>compactAnsiLine(line2,purpose))]}__name(compactAnsiOutput,"compactAnsiOutput");function compactAnsiOutputDisplay(display,purpose){const ansiOutput=compactAnsiOutput(display.ansiOutput,purpose);if(ansiOutput===display.ansiOutput){return display}return{...display,ansiOutput}}__name(compactAnsiOutputDisplay,"compactAnsiOutputDisplay");function isAgentResultDisplay(resultDisplay){return typeof resultDisplay==="object"&&resultDisplay!==null&&"type"in resultDisplay&&resultDisplay.type==="task_execution"}__name(isAgentResultDisplay,"isAgentResultDisplay");function compactAgentResultDisplay(display,purpose){return{...display,taskDescription:compactString(display.taskDescription,purpose,MAX_RETAINED_AGENT_FIELD_CHARS),taskPrompt:compactString(display.taskPrompt,purpose,MAX_RETAINED_AGENT_FIELD_CHARS),...display.terminateReason!==void 0&&{terminateReason:compactString(display.terminateReason,purpose,MAX_RETAINED_AGENT_FIELD_CHARS)},...display.result!==void 0&&{result:compactString(display.result,purpose,MAX_RETAINED_TOOL_RESULT_DISPLAY_CHARS)},...display.toolCalls!==void 0&&{toolCalls:display.toolCalls.map(toolCall=>{const{args:_args,responseParts:_responseParts,result:_result,resultDisplay,error:error3,description,...rest}=toolCall;return{...rest,...description!==void 0&&{description:compactString(description,purpose,MAX_RETAINED_AGENT_FIELD_CHARS)},...error3!==void 0&&{error:compactString(error3,purpose,MAX_RETAINED_AGENT_FIELD_CHARS)},...resultDisplay!==void 0&&{resultDisplay:compactString(resultDisplay,purpose)}}})}}}__name(compactAgentResultDisplay,"compactAgentResultDisplay");function isTodoResultDisplay(resultDisplay){return typeof resultDisplay==="object"&&resultDisplay!==null&&"type"in resultDisplay&&resultDisplay.type==="todo_list"}__name(isTodoResultDisplay,"isTodoResultDisplay");function compactTodoResultDisplay(display,purpose){return{...display,todos:display.todos.map(todo=>({...todo,content:compactString(todo.content,purpose,MAX_RETAINED_AGENT_FIELD_CHARS)}))}}__name(compactTodoResultDisplay,"compactTodoResultDisplay");function isFindingsResultDisplay(resultDisplay){return typeof resultDisplay==="object"&&resultDisplay!==null&&"type"in resultDisplay&&resultDisplay.type==="findings_list"}__name(isFindingsResultDisplay,"isFindingsResultDisplay");function findingRetainedSize(finding){return(finding.id?.length??0)+finding.severity.length+(finding.confidence?.length??0)+(finding.source?.length??0)+finding.file.length+String(finding.line??"").length+finding.summary.length+finding.shortSummary.length+finding.failureScenario.length+(finding.category?.length??0)+(finding.direction?.length??0)+(finding.baseline?.length??0)+(finding.outcome?.length??0)+(finding.outcomeNote?.length??0)+20}__name(findingRetainedSize,"findingRetainedSize");function compactFindingsResultDisplay(display,purpose){const compacted={...display,findings:display.findings.map(finding=>({...finding,summary:compactString(finding.summary,purpose,MAX_RETAINED_AGENT_FIELD_CHARS),failureScenario:compactString(finding.failureScenario,purpose,MAX_RETAINED_AGENT_FIELD_CHARS),...finding.outcomeNote!==void 0&&{outcomeNote:compactString(finding.outcomeNote,purpose,MAX_RETAINED_AGENT_FIELD_CHARS)}}))};let total=0;let kept=0;for(const finding of compacted.findings){const size=findingRetainedSize(finding);if(total+size>MAX_RETAINED_TOOL_RESULT_DISPLAY_CHARS){break}total+=size;kept+=1}if(kept===compacted.findings.length){return compacted}return{...compacted,findings:compacted.findings.slice(0,kept),omittedFindings:compacted.findings.length-kept}}__name(compactFindingsResultDisplay,"compactFindingsResultDisplay");function isPlanResultDisplay(resultDisplay){return typeof resultDisplay==="object"&&resultDisplay!==null&&"type"in resultDisplay&&resultDisplay.type==="plan_summary"}__name(isPlanResultDisplay,"isPlanResultDisplay");function compactPlanResultDisplay(display,purpose){return{...display,message:compactString(display.message,purpose,MAX_RETAINED_AGENT_FIELD_CHARS),plan:compactString(display.plan,purpose,MAX_RETAINED_TOOL_RESULT_DISPLAY_CHARS)}}__name(compactPlanResultDisplay,"compactPlanResultDisplay");function isMcpToolProgressData(resultDisplay){return typeof resultDisplay==="object"&&resultDisplay!==null&&"type"in resultDisplay&&resultDisplay.type==="mcp_tool_progress"}__name(isMcpToolProgressData,"isMcpToolProgressData");function compactMcpToolProgressData(display,purpose){return{...display,...display.message!==void 0&&{message:compactString(display.message,purpose,MAX_RETAINED_AGENT_FIELD_CHARS)}}}__name(compactMcpToolProgressData,"compactMcpToolProgressData");function isTeamResultDisplay(resultDisplay){return typeof resultDisplay==="object"&&resultDisplay!==null&&"type"in resultDisplay&&resultDisplay.type==="team_result"}__name(isTeamResultDisplay,"isTeamResultDisplay");function compactTeamResultDisplay(display,purpose){return{...display,teamName:compactString(display.teamName,purpose,MAX_RETAINED_AGENT_FIELD_CHARS)}}__name(compactTeamResultDisplay,"compactTeamResultDisplay");function isTaskListResultDisplay(resultDisplay){return typeof resultDisplay==="object"&&resultDisplay!==null&&"type"in resultDisplay&&resultDisplay.type==="task_list"}__name(isTaskListResultDisplay,"isTaskListResultDisplay");function isMcpAppResultDisplay(resultDisplay){return typeof resultDisplay==="object"&&resultDisplay!==null&&"type"in resultDisplay&&resultDisplay.type==="mcp_app"}__name(isMcpAppResultDisplay,"isMcpAppResultDisplay");function compactMcpAppResultDisplay(display,purpose){const retainAppPayload=purpose==="recording";const retainedToolResult=retainAppPayload&&(JSON.stringify(display.toolResult)??"").length<=MAX_RETAINED_TOOL_RESULT_DISPLAY_CHARS?display.toolResult:{};return{...display,html:retainAppPayload?display.html:"",toolResult:retainedToolResult,fallbackText:compactString(display.fallbackText,purpose,MAX_RETAINED_TOOL_RESULT_DISPLAY_CHARS)}}__name(compactMcpAppResultDisplay,"compactMcpAppResultDisplay");function compactTaskListResultDisplay(display,purpose){return{...display,tasks:display.tasks.map(task=>({...task,subject:compactString(task.subject,purpose,MAX_RETAINED_AGENT_FIELD_CHARS),...task.owner!==void 0&&{owner:compactString(task.owner,purpose,MAX_RETAINED_AGENT_FIELD_CHARS)}}))}}__name(compactTaskListResultDisplay,"compactTaskListResultDisplay");function compactToolResultDisplay(resultDisplay,purpose){if(isShellResultDisplay(resultDisplay)){return mapShellResultText(resultDisplay,value=>compactString(value,purpose))}if(typeof resultDisplay==="string"){return compactString(resultDisplay,purpose)}if(resultDisplay===void 0){return resultDisplay}if(typeof resultDisplay==="object"&&resultDisplay!==null&&"type"in resultDisplay&&resultDisplay.type==="ask_user_question_answers"){if(typeof resultDisplay.text!=="string"||!Array.isArray(resultDisplay.answers)||!resultDisplay.answers.every(entry=>typeof entry==="object"&&entry!==null&&typeof entry.question==="string"&&typeof entry.answer==="string")){return resultDisplay}return{...resultDisplay,text:compactString(resultDisplay.text,purpose),answers:resultDisplay.answers.map(({question,answer})=>({question:compactString(question,purpose),answer:compactString(answer,purpose)}))}}if(isFileDiffDisplay(resultDisplay)){return compactFileDiff(resultDisplay,purpose)}if(isAgentResultDisplay(resultDisplay)){return compactAgentResultDisplay(resultDisplay,purpose)}if(isAnsiOutputDisplay(resultDisplay)){return compactAnsiOutputDisplay(resultDisplay,purpose)}if(isTodoResultDisplay(resultDisplay)){return compactTodoResultDisplay(resultDisplay,purpose)}if(isFindingsResultDisplay(resultDisplay)){return compactFindingsResultDisplay(resultDisplay,purpose)}if(isPlanResultDisplay(resultDisplay)){return compactPlanResultDisplay(resultDisplay,purpose)}if(isMcpToolProgressData(resultDisplay)){return compactMcpToolProgressData(resultDisplay,purpose)}if(isTeamResultDisplay(resultDisplay)){return compactTeamResultDisplay(resultDisplay,purpose)}if(isTaskListResultDisplay(resultDisplay)){return compactTaskListResultDisplay(resultDisplay,purpose)}if(isMcpAppResultDisplay(resultDisplay)){return compactMcpAppResultDisplay(resultDisplay,purpose)}return resultDisplay}__name(compactToolResultDisplay,"compactToolResultDisplay");function compactToolResultDisplayForHistory(resultDisplay){return compactToolResultDisplay(resultDisplay,"history")}__name(compactToolResultDisplayForHistory,"compactToolResultDisplayForHistory");function compactToolResultDisplayForRecording(resultDisplay){return compactToolResultDisplay(resultDisplay,"recording")}__name(compactToolResultDisplayForRecording,"compactToolResultDisplayForRecording");init_esbuild_shims();init_esbuild_shims();var userPromptSubmitContextReceipt=Symbol("userPromptSubmitContextReceipt");function createUserPromptSubmitContextPart(context2){return{text:wrapUserPromptSubmitContext(context2),[userPromptSubmitContextReceipt]:true}}__name(createUserPromptSubmitContextPart,"createUserPromptSubmitContextPart");function restoreUserPromptSubmitContextReceipt(entry,context2){const candidate=entry;const parts=candidate?.parts;if(!Array.isArray(parts)||parts.length===0){return}const last=parts[parts.length-1];if(last?.text===wrapUserPromptSubmitContext(context2)){last[userPromptSubmitContextReceipt]=true}}__name(restoreUserPromptSubmitContextReceipt,"restoreUserPromptSubmitContextReceipt");function stripTrailingUserPromptSubmitContextPart(parts){if(parts.length<=1){return parts}const last=parts[parts.length-1];if(!last||typeof last.text!=="string"||!isUserPromptSubmitContextPartText(last.text)){return parts}return parts.slice(0,-1)}__name(stripTrailingUserPromptSubmitContextPart,"stripTrailingUserPromptSubmitContextPart");function hasUserPromptSubmitContext(entry,context2){const candidate=entry;if(candidate?.role!=="user"||!Array.isArray(candidate.parts)){return false}const parts=candidate.parts;if(parts.length===0){return false}const wrapped=wrapUserPromptSubmitContext(context2);return parts.some((part,index)=>(index>0||parts.length===1)&&part?.text===wrapped&&part[userPromptSubmitContextReceipt]===true)}__name(hasUserPromptSubmitContext,"hasUserPromptSubmitContext");init_esbuild_shims();init_esbuild_shims();import fs6 from"node:fs";import path7 from"node:path";var debugLogger12=createDebugLogger("USAGE_HISTORY");var MS_PER_DAY=24*60*60*1e3;var LIVE_REBUILD_WINDOW_DAYS=35;function getUsageHistoryPath(){return path7.join(Storage.getGlobalQwenDir(),"usage_record.jsonl")}__name(getUsageHistoryPath,"getUsageHistoryPath");function persistSessionUsage(params){const{sessionId,startTime,endTime,project,metrics}=params;const record4=metricsToUsageRecord(sessionId,project,startTime.getTime(),endTime.getTime(),metrics);writeLineSync(getUsageHistoryPath(),record4)}__name(persistSessionUsage,"persistSessionUsage");function metricsToUsageRecord(sessionId,project,startTime,endTime,metrics){const models={};let totalLatencyMs=0;for(const[name2,m2]of Object.entries(metrics.models)){totalLatencyMs+=m2.api.totalLatencyMs;models[name2]={requests:m2.api.totalRequests,inputTokens:m2.tokens.prompt,outputTokens:m2.tokens.candidates,cachedTokens:m2.tokens.cached,thoughtsTokens:m2.tokens.thoughts,totalTokens:m2.tokens.total||m2.tokens.prompt+m2.tokens.candidates+m2.tokens.thoughts,totalLatencyMs:m2.api.totalLatencyMs}}const toolsByName={};for(const[name2,stats]of Object.entries(metrics.tools.byName)){toolsByName[name2]={count:stats.count,success:stats.success,fail:stats.fail,totalDurationMs:stats.durationMs}}return{version:1,sessionId,timestamp:endTime,startTime,project,durationMs:endTime-startTime,totalLatencyMs,models,tools:{totalCalls:metrics.tools.totalCalls,totalSuccess:metrics.tools.totalSuccess,totalFail:metrics.tools.totalFail,byName:toolsByName},files:{linesAdded:metrics.files.totalLinesAdded,linesRemoved:metrics.files.totalLinesRemoved},...metrics.skills?{skills:{totalCalls:metrics.skills.totalCalls,totalSuccess:metrics.skills.totalSuccess,totalFail:metrics.skills.totalFail,byName:Object.fromEntries(Object.entries(metrics.skills.byName).map(([name2,s3])=>[name2,{count:s3.count,success:s3.success,fail:s3.fail}]))}}:{}}}__name(metricsToUsageRecord,"metricsToUsageRecord");function summarizeTranscript(records){if(records.length===0)return null;const firstRecord=records[0];const sessionId=firstRecord.sessionId;if(!sessionId)return null;const project=firstRecord.cwd;const telemetry=new UiTelemetryService;let hasEvents=false;for(const record4 of records){if(record4.type==="system"&&record4.subtype==="ui_telemetry"){const payload=record4.systemPayload;if(payload?.uiEvent&&payload.uiEvent["event.name"]!=="request_lifecycle"&&payload.uiEvent["event.name"]!=="tool_lifecycle"){telemetry.addEvent(payload.uiEvent);hasEvents=true}}}if(!hasEvents)return{sessionId,record:null};const startTime=new Date(firstRecord.timestamp).getTime();const endTime=new Date(records[records.length-1].timestamp).getTime();if(isNaN(startTime)||isNaN(endTime)){return{sessionId,record:null}}return{sessionId,record:metricsToUsageRecord(sessionId,project,startTime,endTime,telemetry.getMetrics())}}__name(summarizeTranscript,"summarizeTranscript");async function prepareUsageBeforeTranscriptDeletion(transcriptPath){try{const records=await read(transcriptPath);const summarized=summarizeTranscript(records);if(!summarized?.record)return null;const usagePath=getUsageHistoryPath();try{if(fs6.existsSync(usagePath)){const existing=await read(usagePath);if(existing.some(r=>r?.sessionId===summarized.sessionId)){return null}}}catch(e){debugLogger12.debug(`persistUsageBeforeTranscriptDeletion: cannot read history: ${e}`)}return{usagePath,record:summarized.record}}catch(e){debugLogger12.debug(`prepareUsageBeforeTranscriptDeletion: ${e}`);return null}}__name(prepareUsageBeforeTranscriptDeletion,"prepareUsageBeforeTranscriptDeletion");function commitUsageBeforeTranscriptDeletion(prepared){try{if(fs6.existsSync(prepared.usagePath)){const alreadyPersisted=fs6.readFileSync(prepared.usagePath,"utf8").split(/\r?\n/).some(line2=>{const trimmed=line2.trim();return trimmed.length>0&&parseLineTolerant(trimmed,prepared.usagePath).some(record4=>record4.sessionId===prepared.record.sessionId)});if(alreadyPersisted)return false}writeLineSync(prepared.usagePath,prepared.record);return true}catch(e){debugLogger12.debug(`commitUsageBeforeTranscriptDeletion: ${e}`);return false}}__name(commitUsageBeforeTranscriptDeletion,"commitUsageBeforeTranscriptDeletion");async function rebuildFromSessionJsonl(options2={}){const{skipSessionInRebuild,persist=true,sinceMs,skipSessionIds}=options2;const projectsDir=path7.join(Storage.getGlobalQwenDir(),"projects");try{if(!fs6.existsSync(projectsDir))return[]}catch(e){debugLogger12.debug(`rebuildFromSessionJsonl: cannot access projectsDir: ${e}`);return[]}const results=[];const seenSessionIds=new Set;let projectDirs;try{projectDirs=fs6.readdirSync(projectsDir)}catch(e){debugLogger12.debug(`rebuildFromSessionJsonl: cannot read projectsDir: ${e}`);return[]}for(const projDir of projectDirs){const chatsDir=path7.join(projectsDir,projDir,"chats");let files;try{files=fs6.readdirSync(chatsDir).filter(f2=>f2.endsWith(".jsonl")&&!f2.endsWith(".ledger.jsonl"))}catch(e){debugLogger12.debug(`rebuildFromSessionJsonl: cannot read chatsDir ${chatsDir}: ${e}`);continue}for(const file of files){try{const filePath=path7.join(chatsDir,file);let stats;try{stats=fs6.statSync(filePath)}catch(e){debugLogger12.debug(`rebuildFromSessionJsonl: cannot stat ${filePath}: ${e}`);continue}if(!stats.isFile()){debugLogger12.debug(`rebuildFromSessionJsonl: skipping non-regular entry ${filePath}`);continue}if(sinceMs!==void 0&&stats.mtimeMs<sinceMs)continue;if(skipSessionIds&&skipSessionIds.size>0){const fileSessionId=path7.basename(file,".jsonl");if(skipSessionIds.has(fileSessionId))continue}const records=await read(filePath);const summarized=summarizeTranscript(records);if(!summarized)continue;if(seenSessionIds.has(summarized.sessionId))continue;seenSessionIds.add(summarized.sessionId);if(!summarized.record)continue;results.push(summarized.record)}catch(e){debugLogger12.debug(`rebuildFromSessionJsonl: failed to process ${file}: ${e}`);continue}}}if(persist&&results.length>0){const usagePath=getUsageHistoryPath();for(const record4 of results){if(skipSessionInRebuild&&record4.sessionId===skipSessionInRebuild)continue;writeLineSync(usagePath,record4)}}return results}__name(rebuildFromSessionJsonl,"rebuildFromSessionJsonl");function dedupBySessionId(records){const map=new Map;for(const r of records)map.set(r.sessionId,r);if(map.size<records.length){debugLogger12.debug(`dedupBySessionId: removed ${records.length-map.size} duplicate record(s)`)}return[...map.values()]}__name(dedupBySessionId,"dedupBySessionId");async function loadUsageHistory(skipSessionInRebuild,options2){try{const records=await read(getUsageHistoryPath());const filtered=records.filter(r=>r.version===1);if(filtered.length>0)return dedupBySessionId(filtered)}catch(e){debugLogger12.debug(`loadUsageHistory: failed to read usage file: ${e}`)}return dedupBySessionId(await rebuildFromSessionJsonl({skipSessionInRebuild,persist:options2?.persistRebuild??true}))}__name(loadUsageHistory,"loadUsageHistory");async function loadUsageHistoryWithLive(options2){let persisted=[];try{const records=await read(getUsageHistoryPath());persisted=records.filter(r=>r.version===1)}catch(e){debugLogger12.debug(`loadUsageHistoryWithLive: failed to read usage file: ${e}`)}const persistedIds=new Set(persisted.map(r=>r.sessionId));const sinceMs=options2?.sinceMs??(persistedIds.size>0?Date.now()-LIVE_REBUILD_WINDOW_DAYS*MS_PER_DAY:void 0);const rebuilt=await rebuildFromSessionJsonl({persist:false,sinceMs,skipSessionIds:persistedIds});return dedupBySessionId([...rebuilt,...persisted])}__name(loadUsageHistoryWithLive,"loadUsageHistoryWithLive");function getTimeRangeBounds(range){const now=new Date;const end=now;let start;switch(range){case"today":{start=new Date(now.getFullYear(),now.getMonth(),now.getDate());break}case"week":{start=new Date(now.getTime()-7*24*60*60*1e3);break}case"month":{start=new Date(now.getTime()-30*24*60*60*1e3);break}case"all":start=new Date(0);break;default:start=new Date(0);break}return{start,end}}__name(getTimeRangeBounds,"getTimeRangeBounds");function aggregateUsage(records,range){const{start,end}=getTimeRangeBounds(range);const filtered=records.filter(r=>{const ts2=r.timestamp;return ts2>=start.getTime()&&ts2<=end.getTime()});const models=Object.create(null);let totalCalls=0;let totalSuccess=0;let totalFail=0;let totalDurationMs=0;let totalLatencyMs=0;let totalRequests=0;let linesAdded=0;let linesRemoved=0;const toolCounts=new Map;const skillCounts=new Map;let totalSkillCalls=0;const projectMap=new Map;for(const r of filtered){if(!r.models||!r.tools?.byName||!r.files)continue;totalDurationMs+=r.durationMs;totalLatencyMs+=r.totalLatencyMs??0;totalCalls+=r.tools.totalCalls;totalSuccess+=r.tools.totalSuccess;totalFail+=r.tools.totalFail;linesAdded+=r.files.linesAdded;linesRemoved+=r.files.linesRemoved;for(const[name2,m2]of Object.entries(r.models)){totalRequests+=m2.requests;const existing=models[name2];if(existing){existing.requests+=m2.requests;existing.inputTokens+=m2.inputTokens;existing.outputTokens+=m2.outputTokens;existing.cachedTokens+=m2.cachedTokens;existing.thoughtsTokens+=m2.thoughtsTokens;existing.totalTokens+=m2.totalTokens;existing.totalLatencyMs+=m2.totalLatencyMs??0}else{models[name2]={...m2,totalLatencyMs:m2.totalLatencyMs??0}}}for(const[name2,stats]of Object.entries(r.tools.byName)){const existing=toolCounts.get(name2);if(existing){existing.count+=stats.count;existing.success+=stats.success;existing.fail+=stats.fail;existing.totalDurationMs+=stats.totalDurationMs??0}else{toolCounts.set(name2,{count:stats.count,success:stats.success,fail:stats.fail,totalDurationMs:stats.totalDurationMs??0})}}if(r.skills){totalSkillCalls+=r.skills.totalCalls;for(const[name2,s3]of Object.entries(r.skills.byName)){const existing=skillCounts.get(name2);if(existing){existing.count+=s3.count;existing.success+=s3.success;existing.fail+=s3.fail}else{skillCounts.set(name2,{count:s3.count,success:s3.success,fail:s3.fail})}}}let sessionTokens=0;for(const m2 of Object.values(r.models)){sessionTokens+=m2.totalTokens}const proj=projectMap.get(r.project);if(proj){proj.sessionCount++;proj.totalDurationMs+=r.durationMs;proj.totalTokens+=sessionTokens}else{projectMap.set(r.project,{sessionCount:1,totalDurationMs:r.durationMs,totalTokens:sessionTokens})}}const topTools=[...toolCounts.entries()].map(([name2,stats])=>({name:name2,...stats})).sort((a,b2)=>b2.count-a.count).slice(0,10);const topSkills=[...skillCounts.entries()].map(([name2,s3])=>({name:name2,...s3})).sort((a,b2)=>b2.count-a.count).slice(0,25);const projects=[...projectMap.entries()].map(([p2,stats])=>({path:p2,...stats})).sort((a,b2)=>b2.totalTokens-a.totalTokens);return{timeRange:range,periodStart:start,periodEnd:end,sessionCount:filtered.length,totalDurationMs,totalLatencyMs,totalRequests,models,tools:{totalCalls,totalSuccess,totalFail,topTools},files:{linesAdded,linesRemoved},skills:{totalCalls:totalSkillCalls,topSkills},projects}}__name(aggregateUsage,"aggregateUsage");import path18 from"node:path";import fs13 from"node:fs";import{randomUUID as randomUUID9}from"node:crypto";import readline from"node:readline";init_esbuild_shims();import{createHash as createHash4}from"node:crypto";import{chmod,copyFile,mkdir as mkdir2,open,readFile as readFile2,stat,unlink as unlink3}from"node:fs/promises";import{dirname as dirname2,isAbsolute,join as join5,relative,resolve,sep}from"node:path";init_esbuild_shims();function Diff(){}__name(Diff,"Diff");Diff.prototype={diff:__name(function diff(oldString,newString){var _options$timeout;var options2=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var callback=options2.callback;if(typeof options2==="function"){callback=options2;options2={}}var self2=this;function done(value){value=self2.postProcess(value,options2);if(callback){setTimeout(function(){callback(value)},0);return true}else{return value}}__name(done,"done");oldString=this.castInput(oldString,options2);newString=this.castInput(newString,options2);oldString=this.removeEmpty(this.tokenize(oldString,options2));newString=this.removeEmpty(this.tokenize(newString,options2));var newLen=newString.length,oldLen=oldString.length;var editLength=1;var maxEditLength=newLen+oldLen;if(options2.maxEditLength!=null){maxEditLength=Math.min(maxEditLength,options2.maxEditLength)}var maxExecutionTime=(_options$timeout=options2.timeout)!==null&&_options$timeout!==void 0?_options$timeout:Infinity;var abortAfterTimestamp=Date.now()+maxExecutionTime;var bestPath=[{oldPos:-1,lastComponent:void 0}];var newPos=this.extractCommon(bestPath[0],newString,oldString,0,options2);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen){return done(buildValues(self2,bestPath[0].lastComponent,newString,oldString,self2.useLongestToken))}var minDiagonalToConsider=-Infinity,maxDiagonalToConsider=Infinity;function execEditLength(){for(var diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){var basePath=void 0;var removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];if(removePath){bestPath[diagonalPath-1]=void 0}var canAdd=false;if(addPath){var addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}var canRemove=removePath&&removePath.oldPos+1<oldLen;if(!canAdd&&!canRemove){bestPath[diagonalPath]=void 0;continue}if(!canRemove||canAdd&&removePath.oldPos<addPath.oldPos){basePath=self2.addToPath(addPath,true,false,0,options2)}else{basePath=self2.addToPath(removePath,false,true,1,options2)}newPos=self2.extractCommon(basePath,newString,oldString,diagonalPath,options2);if(basePath.oldPos+1>=oldLen&&newPos+1>=newLen){return done(buildValues(self2,basePath.lastComponent,newString,oldString,self2.useLongestToken))}else{bestPath[diagonalPath]=basePath;if(basePath.oldPos+1>=oldLen){maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)}if(newPos+1>=newLen){minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1)}}}editLength++}__name(execEditLength,"execEditLength");if(callback){__name((function exec2(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp){return callback()}if(!execEditLength()){exec2()}},0)}),"exec")()}else{while(editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp){var ret=execEditLength();if(ret){return ret}}}},"diff"),addToPath:__name(function addToPath(path89,added,removed,oldPosInc,options2){var last=path89.lastComponent;if(last&&!options2.oneChangePerToken&&last.added===added&&last.removed===removed){return{oldPos:path89.oldPos+oldPosInc,lastComponent:{count:last.count+1,added,removed,previousComponent:last.previousComponent}}}else{return{oldPos:path89.oldPos+oldPosInc,lastComponent:{count:1,added,removed,previousComponent:last}}}},"addToPath"),extractCommon:__name(function extractCommon(basePath,newString,oldString,diagonalPath,options2){var newLen=newString.length,oldLen=oldString.length,oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;while(newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldString[oldPos+1],newString[newPos+1],options2)){newPos++;oldPos++;commonCount++;if(options2.oneChangePerToken){basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:false,removed:false}}}if(commonCount&&!options2.oneChangePerToken){basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:false,removed:false}}basePath.oldPos=oldPos;return newPos},"extractCommon"),equals:__name(function equals(left,right,options2){if(options2.comparator){return options2.comparator(left,right)}else{return left===right||options2.ignoreCase&&left.toLowerCase()===right.toLowerCase()}},"equals"),removeEmpty:__name(function removeEmpty(array4){var ret=[];for(var i=0;i<array4.length;i++){if(array4[i]){ret.push(array4[i])}}return ret},"removeEmpty"),castInput:__name(function castInput(value){return value},"castInput"),tokenize:__name(function tokenize(value){return Array.from(value)},"tokenize"),join:__name(function join4(chars){return chars.join("")},"join"),postProcess:__name(function postProcess(changeObjects){return changeObjects},"postProcess")};function buildValues(diff2,lastComponent,newString,oldString,useLongestToken){var components=[];var nextComponent;while(lastComponent){components.push(lastComponent);nextComponent=lastComponent.previousComponent;delete lastComponent.previousComponent;lastComponent=nextComponent}components.reverse();var componentPos=0,componentLen=components.length,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){var component=components[componentPos];if(!component.removed){if(!component.added&&useLongestToken){var value=newString.slice(newPos,newPos+component.count);value=value.map(function(value2,i){var oldValue=oldString[oldPos+i];return oldValue.length>value2.length?oldValue:value2});component.value=diff2.join(value)}else{component.value=diff2.join(newString.slice(newPos,newPos+component.count))}newPos+=component.count;if(!component.added){oldPos+=component.count}}else{component.value=diff2.join(oldString.slice(oldPos,oldPos+component.count));oldPos+=component.count}}return components}__name(buildValues,"buildValues");var characterDiff=new Diff;function longestCommonPrefix(str1,str2){var i;for(i=0;i<str1.length&&i<str2.length;i++){if(str1[i]!=str2[i]){return str1.slice(0,i)}}return str1.slice(0,i)}__name(longestCommonPrefix,"longestCommonPrefix");function longestCommonSuffix(str1,str2){var i;if(!str1||!str2||str1[str1.length-1]!=str2[str2.length-1]){return""}for(i=0;i<str1.length&&i<str2.length;i++){if(str1[str1.length-(i+1)]!=str2[str2.length-(i+1)]){return str1.slice(-i)}}return str1.slice(-i)}__name(longestCommonSuffix,"longestCommonSuffix");function replacePrefix(string7,oldPrefix,newPrefix){if(string7.slice(0,oldPrefix.length)!=oldPrefix){throw Error("string ".concat(JSON.stringify(string7)," doesn't start with prefix ").concat(JSON.stringify(oldPrefix),"; this is a bug"))}return newPrefix+string7.slice(oldPrefix.length)}__name(replacePrefix,"replacePrefix");function replaceSuffix(string7,oldSuffix,newSuffix){if(!oldSuffix){return string7+newSuffix}if(string7.slice(-oldSuffix.length)!=oldSuffix){throw Error("string ".concat(JSON.stringify(string7)," doesn't end with suffix ").concat(JSON.stringify(oldSuffix),"; this is a bug"))}return string7.slice(0,-oldSuffix.length)+newSuffix}__name(replaceSuffix,"replaceSuffix");function removePrefix(string7,oldPrefix){return replacePrefix(string7,oldPrefix,"")}__name(removePrefix,"removePrefix");function removeSuffix(string7,oldSuffix){return replaceSuffix(string7,oldSuffix,"")}__name(removeSuffix,"removeSuffix");function maximumOverlap(string1,string22){return string22.slice(0,overlapCount(string1,string22))}__name(maximumOverlap,"maximumOverlap");function overlapCount(a,b2){var startA=0;if(a.length>b2.length){startA=a.length-b2.length}var endB=b2.length;if(a.length<b2.length){endB=a.length}var map=Array(endB);var k2=0;map[0]=0;for(var j2=1;j2<endB;j2++){if(b2[j2]==b2[k2]){map[j2]=map[k2]}else{map[j2]=k2}while(k2>0&&b2[j2]!=b2[k2]){k2=map[k2]}if(b2[j2]==b2[k2]){k2++}}k2=0;for(var i=startA;i<a.length;i++){while(k2>0&&a[i]!=b2[k2]){k2=map[k2]}if(a[i]==b2[k2]){k2++}}return k2}__name(overlapCount,"overlapCount");var extendedWordChars="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}";var tokenizeIncludingWhitespace=new RegExp("[".concat(extendedWordChars,"]+|\\s+|[^").concat(extendedWordChars,"]"),"ug");var wordDiff=new Diff;wordDiff.equals=function(left,right,options2){if(options2.ignoreCase){left=left.toLowerCase();right=right.toLowerCase()}return left.trim()===right.trim()};wordDiff.tokenize=function(value){var options2=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var parts;if(options2.intlSegmenter){if(options2.intlSegmenter.resolvedOptions().granularity!="word"){throw new Error('The segmenter passed must have a granularity of "word"')}parts=Array.from(options2.intlSegmenter.segment(value),function(segment){return segment.segment})}else{parts=value.match(tokenizeIncludingWhitespace)||[]}var tokens=[];var prevPart=null;parts.forEach(function(part){if(/\s/.test(part)){if(prevPart==null){tokens.push(part)}else{tokens.push(tokens.pop()+part)}}else if(/\s/.test(prevPart)){if(tokens[tokens.length-1]==prevPart){tokens.push(tokens.pop()+part)}else{tokens.push(prevPart+part)}}else{tokens.push(part)}prevPart=part});return tokens};wordDiff.join=function(tokens){return tokens.map(function(token,i){if(i==0){return token}else{return token.replace(/^\s+/,"")}}).join("")};wordDiff.postProcess=function(changes,options2){if(!changes||options2.oneChangePerToken){return changes}var lastKeep=null;var insertion=null;var deletion=null;changes.forEach(function(change){if(change.added){insertion=change}else if(change.removed){deletion=change}else{if(insertion||deletion){dedupeWhitespaceInChangeObjects(lastKeep,deletion,insertion,change)}lastKeep=change;insertion=null;deletion=null}});if(insertion||deletion){dedupeWhitespaceInChangeObjects(lastKeep,deletion,insertion,null)}return changes};function dedupeWhitespaceInChangeObjects(startKeep,deletion,insertion,endKeep){if(deletion&&insertion){var oldWsPrefix=deletion.value.match(/^\s*/)[0];var oldWsSuffix=deletion.value.match(/\s*$/)[0];var newWsPrefix=insertion.value.match(/^\s*/)[0];var newWsSuffix=insertion.value.match(/\s*$/)[0];if(startKeep){var commonWsPrefix=longestCommonPrefix(oldWsPrefix,newWsPrefix);startKeep.value=replaceSuffix(startKeep.value,newWsPrefix,commonWsPrefix);deletion.value=removePrefix(deletion.value,commonWsPrefix);insertion.value=removePrefix(insertion.value,commonWsPrefix)}if(endKeep){var commonWsSuffix=longestCommonSuffix(oldWsSuffix,newWsSuffix);endKeep.value=replacePrefix(endKeep.value,newWsSuffix,commonWsSuffix);deletion.value=removeSuffix(deletion.value,commonWsSuffix);insertion.value=removeSuffix(insertion.value,commonWsSuffix)}}else if(insertion){if(startKeep){insertion.value=insertion.value.replace(/^\s*/,"")}if(endKeep){endKeep.value=endKeep.value.replace(/^\s*/,"")}}else if(startKeep&&endKeep){var newWsFull=endKeep.value.match(/^\s*/)[0],delWsStart=deletion.value.match(/^\s*/)[0],delWsEnd=deletion.value.match(/\s*$/)[0];var newWsStart=longestCommonPrefix(newWsFull,delWsStart);deletion.value=removePrefix(deletion.value,newWsStart);var newWsEnd=longestCommonSuffix(removePrefix(newWsFull,newWsStart),delWsEnd);deletion.value=removeSuffix(deletion.value,newWsEnd);endKeep.value=replacePrefix(endKeep.value,newWsFull,newWsEnd);startKeep.value=replaceSuffix(startKeep.value,newWsFull,newWsFull.slice(0,newWsFull.length-newWsEnd.length))}else if(endKeep){var endKeepWsPrefix=endKeep.value.match(/^\s*/)[0];var deletionWsSuffix=deletion.value.match(/\s*$/)[0];var overlap=maximumOverlap(deletionWsSuffix,endKeepWsPrefix);deletion.value=removeSuffix(deletion.value,overlap)}else if(startKeep){var startKeepWsSuffix=startKeep.value.match(/\s*$/)[0];var deletionWsPrefix=deletion.value.match(/^\s*/)[0];var _overlap=maximumOverlap(startKeepWsSuffix,deletionWsPrefix);deletion.value=removePrefix(deletion.value,_overlap)}}__name(dedupeWhitespaceInChangeObjects,"dedupeWhitespaceInChangeObjects");var wordWithSpaceDiff=new Diff;wordWithSpaceDiff.tokenize=function(value){var regex=new RegExp("(\\r?\\n)|[".concat(extendedWordChars,"]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars,"]"),"ug");return value.match(regex)||[]};var lineDiff=new Diff;lineDiff.tokenize=function(value,options2){if(options2.stripTrailingCr){value=value.replace(/\r\n/g,"\n")}var retLines=[],linesAndNewlines=value.split(/(\n|\r\n)/);if(!linesAndNewlines[linesAndNewlines.length-1]){linesAndNewlines.pop()}for(var i=0;i<linesAndNewlines.length;i++){var line2=linesAndNewlines[i];if(i%2&&!options2.newlineIsToken){retLines[retLines.length-1]+=line2}else{retLines.push(line2)}}return retLines};lineDiff.equals=function(left,right,options2){if(options2.ignoreWhitespace){if(!options2.newlineIsToken||!left.includes("\n")){left=left.trim()}if(!options2.newlineIsToken||!right.includes("\n")){right=right.trim()}}else if(options2.ignoreNewlineAtEof&&!options2.newlineIsToken){if(left.endsWith("\n")){left=left.slice(0,-1)}if(right.endsWith("\n")){right=right.slice(0,-1)}}return Diff.prototype.equals.call(this,left,right,options2)};function diffLines(oldStr,newStr,callback){return lineDiff.diff(oldStr,newStr,callback)}__name(diffLines,"diffLines");var sentenceDiff=new Diff;sentenceDiff.tokenize=function(value){return value.split(/(\S.+?[.!?])(?=\s+|$)/)};var cssDiff=new Diff;cssDiff.tokenize=function(value){return value.split(/([{}:;,]|\s+)/)};function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r2){return Object.getOwnPropertyDescriptor(e,r2).enumerable})),t.push.apply(t,o)}return t}__name(ownKeys,"ownKeys");function _objectSpread2(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),true).forEach(function(r2){_defineProperty(e,r2,t[r2])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r2){Object.defineProperty(e,r2,Object.getOwnPropertyDescriptor(t,r2))})}return e}__name(_objectSpread2,"_objectSpread2");function _toPrimitive(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}__name(_toPrimitive,"_toPrimitive");function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==typeof i?i:i+""}__name(_toPropertyKey,"_toPropertyKey");function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o2){return typeof o2}:function(o2){return o2&&"function"==typeof Symbol&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},_typeof(o)}__name(_typeof,"_typeof");function _defineProperty(obj,key,value){key=_toPropertyKey(key);if(key in obj){Object.defineProperty(obj,key,{value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}__name(_defineProperty,"_defineProperty");function _toConsumableArray(arr){return _arrayWithoutHoles(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||_nonIterableSpread()}__name(_toConsumableArray,"_toConsumableArray");function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr)}__name(_arrayWithoutHoles,"_arrayWithoutHoles");function _iterableToArray(iter){if(typeof Symbol!=="undefined"&&iter[Symbol.iterator]!=null||iter["@@iterator"]!=null)return Array.from(iter)}__name(_iterableToArray,"_iterableToArray");function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}__name(_unsupportedIterableToArray,"_unsupportedIterableToArray");function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}__name(_arrayLikeToArray,"_arrayLikeToArray");function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}__name(_nonIterableSpread,"_nonIterableSpread");var jsonDiff=new Diff;jsonDiff.useLongestToken=true;jsonDiff.tokenize=lineDiff.tokenize;jsonDiff.castInput=function(value,options2){var undefinedReplacement=options2.undefinedReplacement,_options$stringifyRep=options2.stringifyReplacer,stringifyReplacer=_options$stringifyRep===void 0?function(k2,v2){return typeof v2==="undefined"?undefinedReplacement:v2}:_options$stringifyRep;return typeof value==="string"?value:JSON.stringify(canonicalize(value,null,null,stringifyReplacer),stringifyReplacer," ")};jsonDiff.equals=function(left,right,options2){return Diff.prototype.equals.call(jsonDiff,left.replace(/,([\r\n])/g,"$1"),right.replace(/,([\r\n])/g,"$1"),options2)};function canonicalize(obj,stack,replacementStack,replacer,key){stack=stack||[];replacementStack=replacementStack||[];if(replacer){obj=replacer(key,obj)}var i;for(i=0;i<stack.length;i+=1){if(stack[i]===obj){return replacementStack[i]}}var canonicalizedObj;if("[object Array]"===Object.prototype.toString.call(obj)){stack.push(obj);canonicalizedObj=new Array(obj.length);replacementStack.push(canonicalizedObj);for(i=0;i<obj.length;i+=1){canonicalizedObj[i]=canonicalize(obj[i],stack,replacementStack,replacer,key)}stack.pop();replacementStack.pop();return canonicalizedObj}if(obj&&obj.toJSON){obj=obj.toJSON()}if(_typeof(obj)==="object"&&obj!==null){stack.push(obj);canonicalizedObj={};replacementStack.push(canonicalizedObj);var sortedKeys=[],_key;for(_key in obj){if(Object.prototype.hasOwnProperty.call(obj,_key)){sortedKeys.push(_key)}}sortedKeys.sort();for(i=0;i<sortedKeys.length;i+=1){_key=sortedKeys[i];canonicalizedObj[_key]=canonicalize(obj[_key],stack,replacementStack,replacer,_key)}stack.pop();replacementStack.pop()}else{canonicalizedObj=obj}return canonicalizedObj}__name(canonicalize,"canonicalize");var arrayDiff=new Diff;arrayDiff.tokenize=function(value){return value.slice()};arrayDiff.join=arrayDiff.removeEmpty=function(value){return value};function structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options2){if(!options2){options2={}}if(typeof options2==="function"){options2={callback:options2}}if(typeof options2.context==="undefined"){options2.context=4}if(options2.newlineIsToken){throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions")}if(!options2.callback){return diffLinesResultToPatch(diffLines(oldStr,newStr,options2))}else{var _options=options2,_callback=_options.callback;diffLines(oldStr,newStr,_objectSpread2(_objectSpread2({},options2),{},{callback:__name(function callback(diff2){var patch=diffLinesResultToPatch(diff2);_callback(patch)},"callback")}))}function diffLinesResultToPatch(diff2){if(!diff2){return}diff2.push({value:"",lines:[]});function contextLines(lines){return lines.map(function(entry){return" "+entry})}__name(contextLines,"contextLines");var hunks=[];var oldRangeStart=0,newRangeStart=0,curRange=[],oldLine=1,newLine=1;var _loop=__name(function _loop2(){var current2=diff2[i],lines=current2.lines||splitLines(current2.value);current2.lines=lines;if(current2.added||current2.removed){var _curRange;if(!oldRangeStart){var prev=diff2[i-1];oldRangeStart=oldLine;newRangeStart=newLine;if(prev){curRange=options2.context>0?contextLines(prev.lines.slice(-options2.context)):[];oldRangeStart-=curRange.length;newRangeStart-=curRange.length}}(_curRange=curRange).push.apply(_curRange,_toConsumableArray(lines.map(function(entry){return(current2.added?"+":"-")+entry})));if(current2.added){newLine+=lines.length}else{oldLine+=lines.length}}else{if(oldRangeStart){if(lines.length<=options2.context*2&&i<diff2.length-2){var _curRange2;(_curRange2=curRange).push.apply(_curRange2,_toConsumableArray(contextLines(lines)))}else{var _curRange3;var contextSize=Math.min(lines.length,options2.context);(_curRange3=curRange).push.apply(_curRange3,_toConsumableArray(contextLines(lines.slice(0,contextSize))));var _hunk={oldStart:oldRangeStart,oldLines:oldLine-oldRangeStart+contextSize,newStart:newRangeStart,newLines:newLine-newRangeStart+contextSize,lines:curRange};hunks.push(_hunk);oldRangeStart=0;newRangeStart=0;curRange=[]}}oldLine+=lines.length;newLine+=lines.length}},"_loop");for(var i=0;i<diff2.length;i++){_loop()}for(var _i2=0,_hunks=hunks;_i2<_hunks.length;_i2++){var hunk=_hunks[_i2];for(var _i22=0;_i22<hunk.lines.length;_i22++){if(hunk.lines[_i22].endsWith("\n")){hunk.lines[_i22]=hunk.lines[_i22].slice(0,-1)}else{hunk.lines.splice(_i22+1,0,"\");_i22++}}}return{oldFileName,newFileName,oldHeader,newHeader,hunks}}__name(diffLinesResultToPatch,"diffLinesResultToPatch")}__name(structuredPatch,"structuredPatch");function formatPatch(diff2){if(Array.isArray(diff2)){return diff2.map(formatPatch).join("\n")}var ret=[];if(diff2.oldFileName==diff2.newFileName){ret.push("Index: "+diff2.oldFileName)}ret.push("===================================================================");ret.push("--- "+diff2.oldFileName+(typeof diff2.oldHeader==="undefined"?"":" "+diff2.oldHeader));ret.push("+++ "+diff2.newFileName+(typeof diff2.newHeader==="undefined"?"":" "+diff2.newHeader));for(var i=0;i<diff2.hunks.length;i++){var hunk=diff2.hunks[i];if(hunk.oldLines===0){hunk.oldStart-=1}if(hunk.newLines===0){hunk.newStart-=1}ret.push("@@ -"+hunk.oldStart+","+hunk.oldLines+" +"+hunk.newStart+","+hunk.newLines+" @@");ret.push.apply(ret,hunk.lines)}return ret.join("\n")+"\n"}__name(formatPatch,"formatPatch");function createTwoFilesPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options2){var _options2;if(typeof options2==="function"){options2={callback:options2}}if(!((_options2=options2)!==null&&_options2!==void 0&&_options2.callback)){var patchObj=structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options2);if(!patchObj){return}return formatPatch(patchObj)}else{var _options3=options2,_callback2=_options3.callback;structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,_objectSpread2(_objectSpread2({},options2),{},{callback:__name(function callback(patchObj2){if(!patchObj2){_callback2()}else{_callback2(formatPatch(patchObj2))}},"callback")}))}}__name(createTwoFilesPatch,"createTwoFilesPatch");function createPatch(fileName,oldStr,newStr,oldHeader,newHeader,options2){return createTwoFilesPatch(fileName,fileName,oldStr,newStr,oldHeader,newHeader,options2)}__name(createPatch,"createPatch");function splitLines(text3){var hasTrailingNl=text3.endsWith("\n");var result=text3.split("\n").map(function(line2){return line2+"\n"});if(hasTrailingNl){result.pop()}else{result.push(result.pop().slice(0,-1))}return result}__name(splitLines,"splitLines");init_esbuild_shims();var MAX_SNAPSHOTS=100;var debugLogger13=createDebugLogger("FILE_HISTORY");async function readRetainedText(source){if(!source)return{kind:"ok",content:"",exists:false};if(source.stats.size>MAX_DIFF_SIZE_BYTES)return{kind:"oversized",exists:true};const bytes=await readFileHandleBytes(source.fileHandle,source.stats.size);if(bytes.length!==source.stats.size)throw new Error("Retained file changed while reading.");return{kind:"ok",content:bytes.toString("utf8"),exists:true}}__name(readRetainedText,"readRetainedText");var FILE_HISTORY_DIR="file-history";function serializeBackups(backups){return Object.fromEntries(Object.entries(backups).map(([path89,backup])=>[path89,{backupFileName:backup.backupFileName,version:backup.version,backupTime:backup.backupTime.toISOString(),failed:backup.failed||void 0}]))}__name(serializeBackups,"serializeBackups");function serializeSnapshot(s3){return{promptId:s3.promptId,timestamp:s3.timestamp.toISOString(),trackedFileBackups:serializeBackups(s3.trackedFileBackups),...s3.diffAfterBackups?{diffAfterBackups:serializeBackups(s3.diffAfterBackups)}:{}}}__name(serializeSnapshot,"serializeSnapshot");function safeParseDate(iso){const d=new Date(iso);return Number.isNaN(d.getTime())?new Date(0):d}__name(safeParseDate,"safeParseDate");function deserializeBackups(backups){return Object.fromEntries(Object.entries(backups).map(([path89,backup])=>[path89,{backupFileName:backup.backupFileName,version:backup.version,backupTime:safeParseDate(backup.backupTime),failed:backup.failed}]))}__name(deserializeBackups,"deserializeBackups");function deserializeSnapshots(arr){return arr.map(s3=>({promptId:s3.promptId,timestamp:safeParseDate(s3.timestamp),trackedFileBackups:deserializeBackups(s3.trackedFileBackups),...s3.diffAfterBackups?{diffAfterBackups:deserializeBackups(s3.diffAfterBackups)}:{}}))}__name(deserializeSnapshots,"deserializeSnapshots");var MAX_TURN_DIFF_FILES=500;var BINARY_SNIFF_BYTES=8*1024;function isENOENT(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}__name(isENOENT,"isENOENT");async function pathExists(filePath){try{await stat(filePath);return true}catch{return false}}__name(pathExists,"pathExists");async function readFileOrNull(filePath){try{return await readFile2(filePath,"utf-8")}catch{return null}}__name(readFileOrNull,"readFileOrNull");function getBackupFileName(filePath,version4){const fileNameHash=createHash4("sha256").update(filePath).digest("hex").slice(0,16);return`${fileNameHash}@v${version4}`}__name(getBackupFileName,"getBackupFileName");function resolveBackupPath(backupFileName,sessionId){const baseDir=resolve(Storage.getGlobalQwenDir(),FILE_HISTORY_DIR,sessionId);const backupPath=resolve(baseDir,backupFileName);if(!backupPath.startsWith(baseDir+sep)){throw new Error(`backupFileName escapes base directory: ${backupFileName}`)}return backupPath}__name(resolveBackupPath,"resolveBackupPath");async function safeCopyFile(src,dst){try{await copyFile(src,dst);return"ok"}catch(e){if(!isENOENT(e))throw e;if(!await pathExists(src))return"src-missing";await mkdir2(dirname2(dst),{recursive:true});await copyFile(src,dst);return"ok"}}__name(safeCopyFile,"safeCopyFile");async function createBackup(filePath,version4,sessionId){const backupFileName=getBackupFileName(filePath,version4);const backupPath=resolveBackupPath(backupFileName,sessionId);let srcStats;try{srcStats=await stat(filePath)}catch(e){if(isENOENT(e)){return{backupFileName:null,version:version4,backupTime:new Date}}throw e}const result=await safeCopyFile(filePath,backupPath);if(result==="src-missing"){return{backupFileName:null,version:version4,backupTime:new Date}}await chmod(backupPath,srcStats.mode);return{backupFileName,version:version4,backupTime:new Date}}__name(createBackup,"createBackup");async function restoreBackup(filePath,backupFileName,sessionId){const backupPath=resolveBackupPath(backupFileName,sessionId);let backupStats;try{backupStats=await stat(backupPath)}catch(e){if(isENOENT(e)){debugLogger13.error(`FileHistory: Backup file not found: ${backupPath}`);return false}throw e}const result=await safeCopyFile(backupPath,filePath);if(result==="src-missing"){debugLogger13.error(`FileHistory: Backup file disappeared during restore: ${backupPath}`);return false}await chmod(filePath,backupStats.mode);return true}__name(restoreBackup,"restoreBackup");async function checkOriginFileChanged(originalFile,backupFileName,sessionId,originalStatsHint,retainedStorage){if(retainedStorage)return retainedStorage.withBackupFile(backupFileName,async backup=>retainedStorage.withWorkingFile(originalFile,async original=>!original||original.stats.mode!==backup.stats.mode||original.stats.size!==backup.stats.size||await digestFileReadSource(original)!==await digestFileReadSource(backup)));const backupPath=resolveBackupPath(backupFileName,sessionId);let originalStats=originalStatsHint??null;if(!originalStats){try{originalStats=await stat(originalFile)}catch(e){if(!isENOENT(e))return true}}let backupStats;try{backupStats=await stat(backupPath)}catch{return true}if(originalStats===null)return true;if(originalStats.mode!==backupStats.mode||originalStats.size!==backupStats.size){return true}try{const[originalContent,backupContent]=await Promise.all([readFile2(originalFile),readFile2(backupPath)]);return!originalContent.equals(backupContent)}catch{return true}}__name(checkOriginFileChanged,"checkOriginFileChanged");async function computeDiffStatsForFile(originalFile,backupFileName,sessionId,retainedStorage){const filesChanged=[];let insertions=0;let deletions=0;try{let originalContent;let backupContent;if(retainedStorage){const original=await retainedStorage.withWorkingFile(originalFile,readRetainedText);const backup=backupFileName?await retainedStorage.withBackupFile(backupFileName,readRetainedText):{kind:"ok",content:"",exists:false};if(original.kind!=="ok"||backup.kind!=="ok")throw new Error("Retained diff stats exceed the content limit.");originalContent=original.exists?original.content:null;backupContent=backup.exists?backup.content:null}else{const backupPath=backupFileName?resolveBackupPath(backupFileName,sessionId):void 0;[originalContent,backupContent]=await Promise.all([readFileOrNull(originalFile),backupPath?readFileOrNull(backupPath):null])}if(originalContent===null&&backupContent===null){return{filesChanged,insertions,deletions}}filesChanged.push(originalFile);const changes=diffLines(backupContent??"",originalContent??"");for(const c of changes){if(c.added)insertions+=c.count||0;if(c.removed)deletions+=c.count||0}}catch(error3){if(retainedStorage)throw error3;debugLogger13.error(`FileHistory: Error generating diffStats: ${error3}`)}return{filesChanged,insertions,deletions}}__name(computeDiffStatsForFile,"computeDiffStatsForFile");async function readEndpointContent(backup,worktreePath,sessionId,retainedStorage){if(retainedStorage){if(backup?.failed)throw new Error("Retained backup is unavailable.");if(worktreePath!==void 0)return retainedStorage.withWorkingFile(worktreePath,readRetainedText);if(!backup||backup.backupFileName===null)return{kind:"ok",content:"",exists:false};return retainedStorage.withBackupFile(backup.backupFileName,readRetainedText)}if(worktreePath!==void 0){return readPathWithSizeGuard(worktreePath,"worktree")}if(!backup)return{kind:"ok",content:"",exists:false};if(backup.backupFileName===null){return{kind:"ok",content:"",exists:false}}const backupPath=resolveBackupPath(backup.backupFileName,sessionId);return readPathWithSizeGuard(backupPath,"backup")}__name(readEndpointContent,"readEndpointContent");async function readPathWithSizeGuard(path89,kind){let fh;try{fh=await open(path89,"r")}catch(e){if(isENOENT(e)){if(kind==="worktree"){return{kind:"ok",content:"",exists:false}}return{kind:"unreadable"}}debugLogger13.error(`FileHistory: ${kind} open failed for ${path89}: ${e}`);return{kind:"unreadable"}}try{const st2=await fh.stat();if(st2.size>MAX_DIFF_SIZE_BYTES){return{kind:"oversized",exists:true}}try{const text3=await fh.readFile("utf-8");return{kind:"ok",content:text3,exists:true}}catch(e){debugLogger13.error(`FileHistory: ${kind} read failed for ${path89}: ${e}`);return{kind:"unreadable"}}}finally{await fh.close().catch(()=>void 0)}}__name(readPathWithSizeGuard,"readPathWithSizeGuard");function looksBinary(content){const len=content.length;if(len===0)return false;const headEnd=Math.min(len,BINARY_SNIFF_BYTES);for(let i=0;i<headEnd;i++){if(content.charCodeAt(i)===0)return true}if(len>BINARY_SNIFF_BYTES){const tailStart=Math.max(headEnd,len-BINARY_SNIFF_BYTES);for(let i=tailStart;i<len;i++){if(content.charCodeAt(i)===0)return true}}return false}__name(looksBinary,"looksBinary");function countLines(text3){if(text3==="")return 0;let count4=1;for(let i=0;i<text3.length;i++){if(text3.charCodeAt(i)===10)count4++}if(text3.charCodeAt(text3.length-1)===10)count4--;return count4}__name(countLines,"countLines");var FileHistoryService=class{constructor(sessionId,enabled,cwd,onSnapshotUpdated,retainedStorage){this.retainedStorage=retainedStorage;this.sessionId=sessionId;this.enabled=enabled;this.cwd=cwd;this.onSnapshotUpdated=onSnapshotUpdated}static{__name(this,"FileHistoryService")}state={snapshots:[],trackedFiles:new Set};sessionId;enabled;cwd;onSnapshotUpdated;isEnabled(){return this.enabled}getSnapshots(){return this.state.snapshots}recordSnapshotUpdate(snapshot){try{this.onSnapshotUpdated?.(snapshot)}catch(error3){if(this.retainedStorage)throw error3;debugLogger13.error(`FileHistory: recordSnapshotUpdate failed: ${error3}`)}}restoreFromSnapshots(snapshots){if(this.retainedStorage&&snapshots.length>MAX_SNAPSHOTS)throw new Error("Retained history exceeds its snapshot limit.");const trackedFiles=new Set;const migrated=[];for(const snapshot of snapshots){const trackedFileBackups=Object.create(null);for(const[p2,backup]of Object.entries(snapshot.trackedFileBackups)){const trackingPath=this.maybeShortenFilePath(p2);trackedFiles.add(trackingPath);trackedFileBackups[trackingPath]=backup}migrated.push({...snapshot,trackedFileBackups,...snapshot.diffAfterBackups?{diffAfterBackups:Object.fromEntries(Object.entries(snapshot.diffAfterBackups).map(([p2,backup])=>{const trackingPath=this.maybeShortenFilePath(p2);trackedFiles.add(trackingPath);return[trackingPath,backup]}))}:{}})}this.state={snapshots:migrated,trackedFiles}}async validateRestoredSnapshots(){const uniqueNames=new Set;for(const snapshot of this.state.snapshots){for(const backup of[...Object.values(snapshot.trackedFileBackups),...Object.values(snapshot.diffAfterBackups??{})]){if(this.retainedStorage&&backup.failed)throw new Error("Retained backup is unavailable.");if(backup.backupFileName!==null&&!backup.failed){uniqueNames.add(backup.backupFileName)}}}if(uniqueNames.size===0)return;const BATCH_SIZE=200;const missing=new Set;const names=[...uniqueNames];for(let i=0;i<names.length;i+=BATCH_SIZE){const batch=names.slice(i,i+BATCH_SIZE);const results=await this.joinOperations(batch.map(async name2=>{if(this.retainedStorage){await this.retainedStorage.withBackupFile(name2,async()=>{});return true}let backupPath;try{backupPath=resolveBackupPath(name2,this.sessionId)}catch(e){debugLogger13.error(`FileHistory: rejected backupFileName during validation: ${name2}: ${e}`);return false}try{await stat(backupPath);return true}catch(error3){if(isENOENT(error3))return false;throw error3}}));for(let j2=0;j2<batch.length;j2++){if(!results[j2])missing.add(batch[j2])}}if(missing.size===0)return;const affectedSnapshots=new Set;for(const snapshot of this.state.snapshots){for(const backup of[...Object.values(snapshot.trackedFileBackups),...Object.values(snapshot.diffAfterBackups??{})]){if(backup.backupFileName&&missing.has(backup.backupFileName)){backup.failed=true;affectedSnapshots.add(snapshot)}}}for(const snapshot of affectedSnapshots){this.recordSnapshotUpdate(snapshot)}debugLogger13.warn(`FileHistory: ${missing.size} restored backup file(s) missing on disk`)}async trackEdit(filePath){if(!this.enabled)return;const trackingPath=this.maybeShortenFilePath(filePath);const mostRecent=this.state.snapshots.at(-1);if(!mostRecent){if(this.retainedStorage)throw new Error("Retained history requires a current snapshot.");debugLogger13.error("FileHistory: Missing most recent snapshot");return}const existing=mostRecent.trackedFileBackups[trackingPath];if(this.retainedStorage&&existing?.failed)throw new Error("Retained backup is unavailable.");if(existing&&!existing.failed){if(this.retainedStorage&&existing.backupFileName!==null)await this.retainedStorage.withBackupFile(existing.backupFileName,async()=>{});return}const maxVersion=this.getMaxVersion(trackingPath);let backup;try{backup=this.retainedStorage?await this.retainedStorage.createBackup(filePath,maxVersion+1):await createBackup(filePath,maxVersion+1,this.sessionId)}catch(error3){if(this.retainedStorage)throw error3;debugLogger13.error(`FileHistory: trackEdit failed: ${error3}`);return}if(!this.state.snapshots.includes(mostRecent)){return}const current2=mostRecent.trackedFileBackups[trackingPath];if(!current2||current2.failed){mostRecent.trackedFileBackups[trackingPath]=backup;this.state.trackedFiles.add(trackingPath);this.recordSnapshotUpdate(mostRecent);debugLogger13.debug(`FileHistory: Tracked file modification for ${filePath}`)}}async makeSnapshot(promptId){if(!this.enabled)return;if(this.retainedStorage&&this.state.snapshots.length>=MAX_SNAPSHOTS)throw new Error("Retained history has reached its snapshot limit.");const trackedFileBackups=Object.create(null);const mostRecent=this.state.snapshots.at(-1);if(mostRecent){await this.joinOperations(Array.from(this.state.trackedFiles,async trackingPath=>{try{const filePath=this.maybeExpandFilePath(trackingPath);const latestBackup=mostRecent.trackedFileBackups[trackingPath];const nextVersion=this.getMaxVersion(trackingPath)+1;if(this.retainedStorage){if(latestBackup?.failed)throw new Error("Retained backup is unavailable.");if(latestBackup&&latestBackup.backupFileName!==null&&!await checkOriginFileChanged(filePath,latestBackup.backupFileName,this.sessionId,void 0,this.retainedStorage)){trackedFileBackups[trackingPath]=latestBackup}else{trackedFileBackups[trackingPath]=await this.retainedStorage.createBackup(filePath,nextVersion)}return}let fileStats;try{fileStats=await stat(filePath)}catch(e){if(!isENOENT(e))throw e}if(!fileStats){trackedFileBackups[trackingPath]={backupFileName:null,version:nextVersion,backupTime:new Date};return}if(latestBackup&&!latestBackup.failed&&latestBackup.backupFileName!==null&&!await checkOriginFileChanged(filePath,latestBackup.backupFileName,this.sessionId,fileStats)){trackedFileBackups[trackingPath]=latestBackup;return}trackedFileBackups[trackingPath]=await createBackup(filePath,nextVersion,this.sessionId)}catch(error3){if(this.retainedStorage)throw error3;debugLogger13.error(`FileHistory: Failed to backup file ${trackingPath}: ${error3}`);const previous=mostRecent?.trackedFileBackups[trackingPath];trackedFileBackups[trackingPath]={backupFileName:previous?.backupFileName??null,version:this.getMaxVersion(trackingPath)+1,backupTime:new Date,failed:true}}}))}for(const trackingPath of this.state.trackedFiles){if(trackingPath in trackedFileBackups)continue;const inherited=mostRecent?.trackedFileBackups[trackingPath];if(inherited)trackedFileBackups[trackingPath]=inherited}const newSnapshot={promptId,trackedFileBackups,timestamp:new Date};this.state.snapshots.push(newSnapshot);if(this.state.snapshots.length>MAX_SNAPSHOTS){const overflow=this.state.snapshots.length-MAX_SNAPSHOTS;const removed=this.state.snapshots.slice(0,overflow);this.state.snapshots=this.state.snapshots.slice(overflow);await this.cleanupOrphanedBackups(removed)}debugLogger13.debug(`FileHistory: Added snapshot for ${promptId}, tracking ${this.state.trackedFiles.size} files`)}async rewind(promptId,truncateHistory=true){if(this.retainedStorage)throw new Error("Retained history cannot rewind.");if(!this.enabled)return{filesChanged:[],filesFailed:[]};let matches2=0;for(const snapshot of this.state.snapshots){if(snapshot.promptId===promptId)matches2++}if(matches2>1){throw new Error("The selected snapshot shares its checkpoint identity with another turn")}const targetSnapshot=this.findSnapshot(promptId);if(!targetSnapshot){throw new Error("The selected snapshot was not found")}debugLogger13.debug(`FileHistory: Rewinding to snapshot for ${promptId}`);const result=await this.applySnapshot(targetSnapshot);if(truncateHistory&&result.filesFailed.length===0){const targetIdx=this.state.snapshots.indexOf(targetSnapshot);if(targetIdx>=0){const removed=this.state.snapshots.slice(targetIdx+1);this.state.snapshots=this.state.snapshots.slice(0,targetIdx+1);this.state.trackedFiles=new Set(this.state.snapshots.flatMap(s3=>[...Object.keys(s3.trackedFileBackups),...Object.keys(s3.diffAfterBackups??{})]));await this.cleanupOrphanedBackups(removed)}}debugLogger13.debug(`FileHistory: Finished rewinding to ${promptId}`);return result}async getDiffStats(promptId){if(!this.enabled)return void 0;const targetSnapshot=this.findSnapshot(promptId);if(!targetSnapshot)return void 0;const results=await this.joinOperations(Array.from(this.state.trackedFiles,async trackingPath=>{try{const filePath=this.maybeExpandFilePath(trackingPath);const targetBackup=targetSnapshot.trackedFileBackups[trackingPath];if(targetBackup?.failed){if(this.retainedStorage)throw new Error("Retained backup is unavailable.");return null}const backupFileName=targetBackup?targetBackup.backupFileName:this.getBackupFileNameFirstVersion(trackingPath);if(backupFileName===void 0)return null;const stats=await computeDiffStatsForFile(filePath,backupFileName===null?void 0:backupFileName,this.sessionId,this.retainedStorage);if(stats?.insertions||stats?.deletions){return{filePath,stats}}if(backupFileName===null&&(this.retainedStorage?await this.retainedStorage.withWorkingFile(filePath,async source=>source!==null):await pathExists(filePath))){return{filePath,stats}}return null}catch(error3){if(this.retainedStorage)throw error3;debugLogger13.error(`FileHistory: Error computing diff stats: ${error3}`);return null}}));const filesChanged=[];let insertions=0;let deletions=0;for(const r of results){if(!r)continue;filesChanged.push(r.filePath);insertions+=r.stats?.insertions||0;deletions+=r.stats?.deletions||0}return{filesChanged,insertions,deletions}}async getTurnDiff(promptId){if(!this.enabled)return void 0;const targetIdx=this.findSnapshotIndex(promptId);if(targetIdx<0)return void 0;const target=this.state.snapshots[targetIdx];const nextSnapshot=target.diffAfterBackups?{...target,trackedFileBackups:target.diffAfterBackups}:targetIdx+1<this.state.snapshots.length?this.state.snapshots[targetIdx+1]:void 0;const candidatePaths=Object.keys(target.trackedFileBackups).sort((a,b2)=>a.localeCompare(b2));const filesOmitted=Math.max(0,candidatePaths.length-MAX_TURN_DIFF_FILES);if(filesOmitted>0){debugLogger13.warn(`FileHistory: getTurnDiff truncating ${filesOmitted} files for prompt ${promptId} (cap: ${MAX_TURN_DIFF_FILES})`)}const cappedPaths=candidatePaths.slice(0,MAX_TURN_DIFF_FILES);const results=await this.joinOperations(cappedPaths.map(trackingPath=>this.computeTurnFileDiff(trackingPath,target,nextSnapshot)));const files=[];let totalAdded=0;let totalRemoved=0;for(const r of results){if(!r)continue;files.push(r);totalAdded+=r.linesAdded;totalRemoved+=r.linesRemoved}files.sort((a,b2)=>a.filePath.localeCompare(b2.filePath));return{promptId,timestamp:target.timestamp,files,stats:{filesChanged:files.length,linesAdded:totalAdded,linesRemoved:totalRemoved,filesOmitted}}}async computeTurnFileDiff(trackingPath,before,after){try{return await this.computeTurnFileDiffUnsafe(trackingPath,before,after)}catch(e){if(this.retainedStorage)throw e;debugLogger13.error(`FileHistory: computeTurnFileDiff failed for ${trackingPath}: ${e}`);return null}}async computeTurnFileDiffUnsafe(trackingPath,before,after){const absoluteFilePath=this.maybeExpandFilePath(trackingPath);const beforeBackup=before.trackedFileBackups[trackingPath];if(beforeBackup?.failed){if(this.retainedStorage)throw new Error("Retained backup is unavailable.");return null}let afterBackup;let afterFromWorktree=false;if(after){afterBackup=after.trackedFileBackups[trackingPath];if(afterBackup?.failed){if(this.retainedStorage)throw new Error("Retained backup is unavailable.");return null}}else{afterFromWorktree=true}if(!afterFromWorktree&&beforeBackup!==void 0&&beforeBackup.backupFileName===afterBackup?.backupFileName&&beforeBackup.version===afterBackup?.version){if(this.retainedStorage&&beforeBackup.backupFileName!==null)await this.retainedStorage.withBackupFile(beforeBackup.backupFileName,async()=>{});return null}const beforeRead=await readEndpointContent(beforeBackup,void 0,this.sessionId,this.retainedStorage);if(beforeRead.kind==="unreadable"){debugLogger13.warn(`FileHistory: skipping turn diff for ${trackingPath}: before backup unreadable`);return null}const afterRead=afterFromWorktree?await readEndpointContent(void 0,absoluteFilePath,this.sessionId,this.retainedStorage):await readEndpointContent(afterBackup,void 0,this.sessionId,this.retainedStorage);if(afterRead.kind==="unreadable"){debugLogger13.warn(`FileHistory: skipping turn diff for ${trackingPath}: after ${afterFromWorktree?"worktree":"backup"} unreadable`);return null}if(beforeRead.kind==="oversized"||afterRead.kind==="oversized"){const beforeExists2=beforeRead.exists;const afterExists2=afterRead.exists;return{filePath:trackingPath,hunks:[],isNewFile:!beforeExists2&&afterExists2,isDeleted:beforeExists2&&!afterExists2,linesAdded:0,linesRemoved:0,oversized:true,isBinary:false}}const{content:beforeContent,exists:beforeExists}=beforeRead;const{content:afterContent,exists:afterExists}=afterRead;if(beforeContent===afterContent&&beforeExists===afterExists){return null}const isBinary=looksBinary(beforeContent)||looksBinary(afterContent);if(isBinary){return{filePath:trackingPath,hunks:[],isNewFile:!beforeExists&&afterExists,isDeleted:beforeExists&&!afterExists,linesAdded:0,linesRemoved:0,oversized:false,isBinary:true}}const oversized=Buffer.byteLength(beforeContent,"utf8")>MAX_DIFF_SIZE_BYTES||Buffer.byteLength(afterContent,"utf8")>MAX_DIFF_SIZE_BYTES;if(oversized){const beforeLines=beforeExists?countLines(beforeContent):0;const afterLines=afterExists?countLines(afterContent):0;return{filePath:trackingPath,hunks:[],isNewFile:!beforeExists&&afterExists,isDeleted:beforeExists&&!afterExists,linesAdded:Math.max(0,afterLines-beforeLines),linesRemoved:Math.max(0,beforeLines-afterLines),oversized:true,isBinary:false}}const patch=structuredPatch(trackingPath,trackingPath,beforeContent,afterContent,"","",{context:3});let linesAdded=0;let linesRemoved=0;for(const h of patch.hunks){for(const line2 of h.lines){if(line2.startsWith("+"))linesAdded++;else if(line2.startsWith("-"))linesRemoved++}}if(patch.hunks.length===0&&linesAdded===0&&linesRemoved===0){return null}return{filePath:trackingPath,hunks:patch.hunks,isNewFile:!beforeExists&&afterExists,isDeleted:beforeExists&&!afterExists,linesAdded,linesRemoved,oversized:false,isBinary:false}}findSnapshot(promptId){return this.state.snapshots[this.findSnapshotIndex(promptId)]}findSnapshotIndex(promptId){for(let i=this.state.snapshots.length-1;i>=0;i--){if(this.state.snapshots[i].promptId===promptId){return i}}return-1}async applySnapshot(targetSnapshot){if(this.retainedStorage)throw new Error("Retained history cannot restore.");const filesChanged=[];const filesFailed=[];for(const trackingPath of this.state.trackedFiles){try{const filePath=this.maybeExpandFilePath(trackingPath);const targetBackup=targetSnapshot.trackedFileBackups[trackingPath];if(targetBackup?.failed){filesFailed.push(filePath);continue}const backupFileName=targetBackup?targetBackup.backupFileName:this.getBackupFileNameFirstVersion(trackingPath);if(backupFileName===void 0){debugLogger13.error("FileHistory: Error finding the backup file to apply");filesFailed.push(filePath);continue}if(backupFileName===null){try{await unlink3(filePath);debugLogger13.debug(`FileHistory: Deleted ${filePath}`);filesChanged.push(filePath)}catch(e){if(!isENOENT(e))throw e}continue}if(await checkOriginFileChanged(filePath,backupFileName,this.sessionId)){const restored=await restoreBackup(filePath,backupFileName,this.sessionId);if(restored){debugLogger13.debug(`FileHistory: Restored ${filePath} from ${backupFileName}`);filesChanged.push(filePath)}else{filesFailed.push(filePath)}}}catch(error3){debugLogger13.error(`FileHistory: Error restoring file ${trackingPath}: ${error3}`);filesFailed.push(this.maybeExpandFilePath(trackingPath))}}return{filesChanged,filesFailed}}getBackupFileNameFirstVersion(trackingPath){for(const snapshot of this.state.snapshots){for(const backup of[snapshot.trackedFileBackups[trackingPath],snapshot.diffAfterBackups?.[trackingPath]]){if(backup!==void 0&&backup.version===1)return backup.backupFileName}}return void 0}getMaxVersion(trackingPath){let maxVersion=0;for(const snapshot of this.state.snapshots){for(const existing of[snapshot.trackedFileBackups[trackingPath],snapshot.diffAfterBackups?.[trackingPath]]){if(existing&&existing.version>maxVersion)maxVersion=existing.version}}return maxVersion}async cleanupOrphanedBackups(removedSnapshots){if(this.retainedStorage)throw new Error("Retained history cannot delete backups.");const liveBackups=new Set;for(const s3 of this.state.snapshots){for(const b2 of[...Object.values(s3.trackedFileBackups),...Object.values(s3.diffAfterBackups??{})]){if(b2.backupFileName!==null)liveBackups.add(b2.backupFileName)}}const toDelete=new Set;for(const s3 of removedSnapshots){for(const b2 of[...Object.values(s3.trackedFileBackups),...Object.values(s3.diffAfterBackups??{})]){if(b2.backupFileName!==null&&!liveBackups.has(b2.backupFileName)){toDelete.add(b2.backupFileName)}}}await Promise.all(Array.from(toDelete,async name2=>{try{await unlink3(resolveBackupPath(name2,this.sessionId))}catch(e){if(!isENOENT(e)){debugLogger13.error(`FileHistory: cleanup failed for ${name2}: ${e}`)}}}))}async joinOperations(operations){if(!this.retainedStorage)return Promise.all(operations);const results=await Promise.allSettled(operations);const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw new AggregateError(errors,"Retained history operation failed.");return results.map(result=>{if(result.status!=="fulfilled")throw new Error("Retained operation did not complete.");return result.value})}maybeShortenFilePath(filePath){if(!isAbsolute(filePath))return filePath;if(filePath.startsWith(this.cwd+sep)||filePath===this.cwd){return relative(this.cwd,filePath)}return filePath}maybeExpandFilePath(filePath){if(isAbsolute(filePath))return filePath;return join5(this.cwd,filePath)}};init_esbuild_shims();function readFileHistorySnapshotPayload(record4){if(record4.type!=="system"||record4.subtype!=="file_history_snapshot"||!record4.systemPayload){return void 0}const payload=record4.systemPayload;return Array.isArray(payload.snapshots)?payload:void 0}__name(readFileHistorySnapshotPayload,"readFileHistorySnapshotPayload");var SessionFileHistoryAccumulator=class{static{__name(this,"SessionFileHistoryAccumulator")}seenPromptIds=new Set;retainedPromptIds=[];snapshotsByPromptId=new Map;add(record4){const payload=readFileHistorySnapshotPayload(record4);if(!payload)return;const deserialized=deserializeSnapshots(payload.snapshots);for(const snapshot of deserialized){if(this.seenPromptIds.has(snapshot.promptId)){if(this.snapshotsByPromptId.has(snapshot.promptId)){this.snapshotsByPromptId.set(snapshot.promptId,snapshot)}continue}this.seenPromptIds.add(snapshot.promptId);this.retainedPromptIds.push(snapshot.promptId);this.snapshotsByPromptId.set(snapshot.promptId,snapshot);if(this.retainedPromptIds.length>MAX_SNAPSHOTS){const evictedPromptId=this.retainedPromptIds.shift();this.snapshotsByPromptId.delete(evictedPromptId)}}}finish(){const snapshots=this.retainedPromptIds.map(promptId=>this.snapshotsByPromptId.get(promptId));return snapshots.length>0?snapshots:void 0}};init_esbuild_shims();import{randomUUID}from"node:crypto";import*as fs7 from"node:fs/promises";import*as path8 from"node:path";var GROUP_COLOR_OPTIONS=["red","orange","yellow","green","blue","purple"];var SessionOrganizationError=class extends Error{constructor(message,code,field){super(message);this.code=code;this.field=field;this.name="SessionOrganizationError"}static{__name(this,"SessionOrganizationError")}};var STORE_FILE="session-organization.v1.json";var SCHEMA_VERSION=1;var MAX_GROUP_NAME_LENGTH=64;var MAX_GROUPS=200;var FALLBACK_GROUP_COLOR="blue";var locks=new Map;var warningKeysByStorePath=new Map;function hasControlCharacter(value){return[...value].some(char=>{const codePoint=char.codePointAt(0);return codePoint!==void 0&&(codePoint>=0&&codePoint<=31||codePoint>=127&&codePoint<=159||codePoint>=8203&&codePoint<=8207||codePoint>=8234&&codePoint<=8238||codePoint>=8294&&codePoint<=8297||codePoint===65279)})}__name(hasControlCharacter,"hasControlCharacter");function normalizeGroupName(name2){if(typeof name2!=="string"){throw new SessionOrganizationError("`name` must be a string","invalid_group_name","name")}const trimmed=name2.trim();if(trimmed.length===0||trimmed.length>MAX_GROUP_NAME_LENGTH||hasControlCharacter(trimmed)){throw new SessionOrganizationError("`name` must be 1-64 characters and contain no control characters","invalid_group_name","name")}return trimmed}__name(normalizeGroupName,"normalizeGroupName");function normalizeGroupColor(color){const normalized=typeof color==="string"?color.trim():color;if(typeof normalized==="string"&&isPresetGroupColor(normalized)){return normalized}if(typeof normalized==="string"&&/^#[0-9a-f]{6}$/i.test(normalized)){return normalized.toLowerCase()}throw new SessionOrganizationError("`color` must be a supported preset or a #RRGGBB hex value","invalid_group_color","color")}__name(normalizeGroupColor,"normalizeGroupColor");function assertSessionColor(color){if(typeof color!=="string"||!isPresetGroupColor(color)){throw new SessionOrganizationError("`color` must be one of the supported color options","invalid_group_color","color")}}__name(assertSessionColor,"assertSessionColor");function normalizeOrder(order){if(typeof order!=="number"||!Number.isFinite(order)||!Number.isSafeInteger(order)){throw new SessionOrganizationError("`order` must be a safe integer","invalid_group_order","order")}return order}__name(normalizeOrder,"normalizeOrder");function isPlainRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isPlainRecord,"isPlainRecord");function isPresetGroupColor(color){return GROUP_COLOR_OPTIONS.includes(color)}__name(isPresetGroupColor,"isPresetGroupColor");function emptyStore(){return{schemaVersion:SCHEMA_VERSION,groups:[],sessions:Object.create(null)}}__name(emptyStore,"emptyStore");function groupNameKey(name2){return name2.trim().toLowerCase()}__name(groupNameKey,"groupNameKey");function viewOrganization(organization){const groupId=typeof organization?.groupId==="string"?organization.groupId:null;const color=typeof organization?.color==="string"&&isPresetGroupColor(organization.color)?organization.color:null;const pinnedAt=typeof organization?.pinnedAt==="string"?organization.pinnedAt:void 0;const updatedAt=typeof organization?.updatedAt==="string"?organization.updatedAt:new Date(0).toISOString();return{groupId,color,...pinnedAt!==void 0?{pinnedAt}:{},updatedAt,isPinned:pinnedAt!==void 0}}__name(viewOrganization,"viewOrganization");function serializeOrganization(organization){return{groupId:organization.groupId,...organization.color!=null?{color:organization.color}:{},...organization.pinnedAt!==void 0?{pinnedAt:organization.pinnedAt}:{},updatedAt:organization.updatedAt}}__name(serializeOrganization,"serializeOrganization");var SessionOrganizationService=class{constructor(cwd,onWarning){this.onWarning=onWarning;this.storage=new Storage(cwd)}static{__name(this,"SessionOrganizationService")}storage;readFailed=false;getStorePath(){return path8.join(this.storage.getProjectDir(),STORE_FILE)}async listGroups(){const store=await this.readStore();return{groups:this.sortGroups(store.groups),colorOptions:[...GROUP_COLOR_OPTIONS]}}async readSnapshot(){const store=await this.readStore();const validGroupIds=new Set(store.groups.map(group=>group.id));const sessions=new Map;for(const[sessionId,raw]of Object.entries(store.sessions)){const view=viewOrganization(raw);if(view.groupId!==null&&!validGroupIds.has(view.groupId)){this.warnOrphanedGroupReference(sessionId,view.groupId);view.groupId=null}sessions.set(sessionId,view)}return{groups:this.sortGroups(store.groups),sessions}}async createGroup(input){const name2=normalizeGroupName(input.name);const color=normalizeGroupColor(input.color);return this.withStoreLock(async()=>{const store=await this.readStore();this.assertGroupNameAvailable(store.groups,name2);if(store.groups.length>=MAX_GROUPS){throw new SessionOrganizationError(`Maximum number of groups (${MAX_GROUPS}) reached`,"group_limit_reached")}const now=new Date().toISOString();const group={id:randomUUID(),name:name2,color,order:Math.min(store.groups.reduce((maxOrder,existing)=>Math.max(maxOrder,existing.order),-1)+1,Number.MAX_SAFE_INTEGER),createdAt:now,updatedAt:now};store.groups.push(group);await this.writeStore(store);return group})}async updateGroup(groupId,input){return this.withStoreLock(async()=>{const store=await this.readStore();const group=store.groups.find(candidate=>candidate.id===groupId);if(!group){throw new SessionOrganizationError(`Group not found: ${groupId}`,"group_not_found","groupId")}if(input.name!==void 0){const name2=normalizeGroupName(input.name);this.assertGroupNameAvailable(store.groups,name2,groupId);group.name=name2}if(input.color!==void 0){group.color=normalizeGroupColor(input.color)}if(input.order!==void 0){group.order=normalizeOrder(input.order)}group.updatedAt=new Date().toISOString();await this.writeStore(store);return group})}async deleteGroup(groupId){return this.withStoreLock(async()=>{const store=await this.readStore();const before=store.groups.length;store.groups=store.groups.filter(group=>group.id!==groupId);if(store.groups.length===before){return false}const now=new Date().toISOString();for(const session of Object.values(store.sessions)){if(session.groupId===groupId){session.groupId=null;session.updatedAt=now}}await this.writeStore(store);return true})}async updateSessionOrganization(sessionId,input){const hasUpdate=input.groupId!==void 0||input.isPinned!==void 0||input.color!==void 0;return this.withStoreLock(async()=>{const store=await this.readStore();const current2=viewOrganization(store.sessions[sessionId]);if(!hasUpdate){return current2}const now=new Date().toISOString();if(input.color!==void 0){if(input.color!==null){assertSessionColor(input.color)}current2.color=input.color}if(input.groupId!==void 0){if(input.groupId!==null&&!store.groups.some(group=>group.id===input.groupId)){throw new SessionOrganizationError(`Group not found: ${input.groupId}`,"group_not_found","groupId")}current2.groupId=input.groupId}if(input.isPinned!==void 0){if(input.isPinned){current2.pinnedAt=current2.pinnedAt??now}else{delete current2.pinnedAt}}current2.updatedAt=now;store.sessions[sessionId]=serializeOrganization(current2);await this.writeStore(store);return viewOrganization(store.sessions[sessionId])})}async removeSession(sessionId,options2={}){await this.withStoreLock(async()=>{const store=await this.readStore();if(!Object.prototype.hasOwnProperty.call(store.sessions,sessionId)){return}delete store.sessions[sessionId];await this.writeStore(store,options2)})}async removeSessions(sessionIds,options2={}){const uniqueSessionIds=[...new Set(sessionIds)];if(uniqueSessionIds.length===0)return;await this.withStoreLock(async()=>{const store=await this.readStore();let changed=false;for(const sessionId of uniqueSessionIds){if(Object.prototype.hasOwnProperty.call(store.sessions,sessionId)){delete store.sessions[sessionId];changed=true}}if(changed){await this.writeStore(store,options2)}})}async withStoreLock(work){const storePath=this.getStorePath();const previous=locks.get(storePath)??Promise.resolve();const next=previous.then(work,work);const lock=next.catch(()=>void 0).finally(()=>{if(locks.get(storePath)===lock){locks.delete(storePath)}});locks.set(storePath,lock);return next}async readStore(){try{const raw=JSON.parse(await fs7.readFile(this.getStorePath(),"utf8"));if(!isPlainRecord(raw)){return this.handleUnreadableStore("store root is not an object")}if(raw["schemaVersion"]!==SCHEMA_VERSION){return this.handleUnreadableStore(`store schema is unsupported (found schemaVersion ${String(raw["schemaVersion"])}, expected ${SCHEMA_VERSION})`)}const groups=[];if(Array.isArray(raw["groups"])){for(const rawGroup of raw["groups"]){const group=this.normalizeSessionGroup(rawGroup);if(group!==void 0){groups.push(group)}}}const sessions=isPlainRecord(raw["sessions"])?raw["sessions"]:{};const normalizedSessions=Object.create(null);for(const[sessionId,organization]of Object.entries(sessions)){if(isPlainRecord(organization)){normalizedSessions[sessionId]={groupId:typeof organization["groupId"]==="string"?organization["groupId"]:null,...typeof organization["color"]==="string"&&isPresetGroupColor(organization["color"])?{color:organization["color"]}:{},...typeof organization["pinnedAt"]==="string"?{pinnedAt:organization["pinnedAt"]}:{},updatedAt:typeof organization["updatedAt"]==="string"?organization["updatedAt"]:new Date(0).toISOString()}}else{this.warnMalformedSessionEntry(sessionId)}}this.readFailed=false;return{schemaVersion:SCHEMA_VERSION,groups:this.dedupeGroups(groups),sessions:normalizedSessions}}catch(error3){if(error3.code==="ENOENT"){this.readFailed=false;return emptyStore()}return this.handleUnreadableStore(error3 instanceof Error?error3.message:String(error3))}}handleUnreadableStore(reason){this.readFailed=true;this.warnOnce(`unreadable-store:${reason}`,`Failed to read session organization store at ${this.getStorePath()}: ${reason}`);return emptyStore()}async writeStore(store,options2={}){await fs7.mkdir(path8.dirname(this.getStorePath()),{recursive:true});if(this.readFailed){throw new SessionOrganizationError(`Cannot update session organization store because it could not be read: ${this.getStorePath()}. Delete the file to reset session organization (group/pin data will be lost), or restore it from backup.`,"session_organization_store_unreadable")}await atomicWriteJSON(this.getStorePath(),{schemaVersion:SCHEMA_VERSION,groups:this.sortGroups(store.groups),sessions:store.sessions},{assertCanCommit:options2.assertCanCommit});this.readFailed=false}assertGroupNameAvailable(groups,name2,exceptGroupId){const key=groupNameKey(name2);if(groups.some(group=>group.id!==exceptGroupId&&groupNameKey(group.name)===key)){throw new SessionOrganizationError(`Group name already exists: ${name2}`,"group_name_conflict","name")}}sortGroups(groups){return[...groups].sort((a,b2)=>{const byOrder=a.order-b2.order;if(byOrder!==0)return byOrder;if(a.name!==b2.name)return a.name<b2.name?-1:1;if(a.id!==b2.id)return a.id<b2.id?-1:1;return 0})}normalizeSessionGroup(value){if(!isPlainRecord(value)||typeof value["id"]!=="string"||typeof value["name"]!=="string"||typeof value["color"]!=="string"||typeof value["order"]!=="number"||!Number.isFinite(value["order"])||typeof value["createdAt"]!=="string"||typeof value["updatedAt"]!=="string"){this.warnMalformedGroupEntry(value);return void 0}let color=FALLBACK_GROUP_COLOR;let supported=true;try{color=normalizeGroupColor(value["color"])}catch{supported=false}if(!supported){this.warnOnce(`unknown-group-color:${value["id"]}\0${value["color"]}`,`Session group "${value["name"]}" (id: ${value["id"]}) uses unsupported color "${value["color"]}"; using "${FALLBACK_GROUP_COLOR}"`)}return{id:value["id"],name:value["name"],color,order:value["order"],createdAt:value["createdAt"],updatedAt:value["updatedAt"]}}dedupeGroups(groups){const seen=new Set;const deduped=[];for(const group of groups){const key=groupNameKey(group.name);if(seen.has(key)){this.onWarning?.(`Dropped duplicate session group by name: "${group.name}" (id: ${group.id})`);continue}seen.add(key);deduped.push(group)}return deduped}warnOrphanedGroupReference(sessionId,groupId){this.warnOnce(`orphaned-group:${sessionId}\0${groupId}`,`Dropped orphaned session group reference: session ${sessionId} references missing group ${groupId}`)}warnMalformedSessionEntry(sessionId){this.warnOnce(`malformed-session:${sessionId}`,`Dropped malformed session organization entry: ${sessionId}`)}warnMalformedGroupEntry(value){const id6=isPlainRecord(value)&&typeof value["id"]==="string"?value["id"]:"<unknown>";this.warnOnce(`malformed-group:${id6}`,`Dropped malformed session group entry: ${id6}`)}warnOnce(key,message){const storePath=this.getStorePath();let warningKeys=warningKeysByStorePath.get(storePath);if(warningKeys===void 0){warningKeys=new Set;warningKeysByStorePath.set(storePath,warningKeys)}if(warningKeys.has(key))return;warningKeys.add(key);this.onWarning?.(message)}};init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{existsSync as existsSync2}from"node:fs";import*as fs8 from"node:fs/promises";import*as path10 from"node:path";init_esbuild_shims();import{execFile as execFile2}from"node:child_process";init_esbuild_shims();import{execFile}from"node:child_process";import{existsSync}from"node:fs";import*as path9 from"node:path";import{promisify}from"node:util";var execFileAsync=promisify(execFile);var debugLogger14=createDebugLogger("GITHUB_PRS");var GH_TIMEOUT_MS=1e4;var GH_MAX_BUFFER=16*1024*1024;var GH_ERROR_RAW_MAX=4096;function ghEnv(base2){const source=base2??process.env;const env=gitRemoteEnv(source);if(env["GH_CONFIG_DIR"]===void 0&&source["XDG_CONFIG_HOME"]){env["GH_CONFIG_DIR"]=path9.join(source["XDG_CONFIG_HOME"],"gh")}for(const key of["GIT_SSL_CAINFO","GIT_SSL_CAPATH"]){if(source[key]!==void 0)env[key]=source[key]}return env}__name(ghEnv,"ghEnv");var GH_FALLBACK_BINARIES=["/opt/homebrew/bin/gh","/usr/local/bin/gh","/home/linuxbrew/.linuxbrew/bin/gh"];function resolveGhBinary(env,cwd){const source=env;const pathValue=source["PATH"];if(pathValue&&pathValue.split(path9.delimiter).some(dir=>existsSync(path9.join(path9.resolve(cwd,dir===""?".":dir),"gh")))){return"gh"}const home=source["HOME"];const candidates=[...home&&path9.isAbsolute(home)?[path9.join(home,".local","bin","gh")]:[],...GH_FALLBACK_BINARIES];const fallback=candidates.find(candidate=>existsSync(candidate));if(fallback!==void 0){debugLogger14.debug("gh not on PATH; using fallback binary",{binary:fallback});return fallback}return"gh"}__name(resolveGhBinary,"resolveGhBinary");function fallbackBinaryField(env,gitRoot){const binary=resolveGhBinary(env,gitRoot);return binary==="gh"?{}:{binary}}__name(fallbackBinaryField,"fallbackBinaryField");var GITHUB_PR_ERROR_MESSAGE_MAX=512;var GITHUB_PR_LIST_LIMIT=30;var GH_PR_LIST_FIELDS="number,title,url,author,headRefName,isDraft,reviewDecision,statusCheckRollup,updatedAt,state";var GH_PR_LIST_FIELDS_SLIM="number,url,headRefName,state";var FAILING_CHECK_RUN_CONCLUSIONS=new Set(["FAILURE","CANCELLED","TIMED_OUT","ACTION_REQUIRED","STARTUP_FAILURE","STALE"]);var FAILING_STATUS_CONTEXT_STATES=new Set(["ERROR","FAILURE"]);function aggregateChecks(rollup){if(!Array.isArray(rollup)||rollup.length===0)return"none";let sawPassing=false;let sawPending=false;for(const entry of rollup){if(entry.__typename==="StatusContext"){const state=entry.state?.toUpperCase();if(state&&FAILING_STATUS_CONTEXT_STATES.has(state))return"failing";if(state==="SUCCESS")sawPassing=true;else sawPending=true}else{const conclusion=entry.conclusion?.toUpperCase();if(conclusion){if(FAILING_CHECK_RUN_CONCLUSIONS.has(conclusion))return"failing";sawPassing=true}else{sawPending=true}}}if(sawPending)return"pending";return sawPassing?"passing":"none"}__name(aggregateChecks,"aggregateChecks");function mapReviewDecision(value){switch(value){case"APPROVED":return"approved";case"CHANGES_REQUESTED":return"changes_requested";case"REVIEW_REQUIRED":return"review_required";default:return null}}__name(mapReviewDecision,"mapReviewDecision");function mapEntry(entry){if(typeof entry.number!=="number")return null;const parsed=Date.parse(entry.updatedAt??"");let state;switch(entry.state?.toUpperCase()){case"MERGED":state="merged";break;case"CLOSED":state="closed";break;default:state=entry.isDraft?"draft":"open";break}return{number:entry.number,title:entry.title??"",url:entry.url??"",author:entry.author?.login??"",headRefName:entry.headRefName??"",state,reviewDecision:mapReviewDecision(entry.reviewDecision),checks:aggregateChecks(entry.statusCheckRollup),updatedAt:Number.isNaN(parsed)?0:Math.floor(parsed/1e3)}}__name(mapEntry,"mapEntry");function parseGhPrList(stdout){const parsed=JSON.parse(stdout);if(!Array.isArray(parsed)){throw new Error("unexpected gh output: expected a JSON array")}return parsed.map(entry=>mapEntry(entry)).filter(entry=>entry!==null).sort((a,b2)=>b2.updatedAt-a.updatedAt)}__name(parseGhPrList,"parseGhPrList");function runGhPrList(gitRoot,env,options2={}){const limit=Math.min(Math.max(options2.limit??GITHUB_PR_LIST_LIMIT,1),1e3);const childEnv=ghEnv(env);return new Promise((resolve36,reject)=>{execFile(resolveGhBinary(childEnv,gitRoot),["pr","list","--state",options2.state??"open","--limit",String(limit),"--json",options2.slim?GH_PR_LIST_FIELDS_SLIM:GH_PR_LIST_FIELDS],{cwd:gitRoot,timeout:GH_TIMEOUT_MS,maxBuffer:GH_MAX_BUFFER,windowsHide:true,encoding:"utf8",env:childEnv},(error3,stdout)=>{if(error3)reject(error3);else resolve36(stdout)})})}__name(runGhPrList,"runGhPrList");function ghErrorMessage(error3,commandLabel="gh pr list",timeoutMs=GH_TIMEOUT_MS){if(error3?.killed===true){return`${commandLabel} timed out after ${timeoutMs/1e3}s`}const stderr=error3?.stderr;const raw=typeof stderr==="string"&&stderr.trim()?stderr:error3 instanceof Error?error3.message:String(error3);return raw.replace(/\s+/g," ").trim().slice(0,GH_ERROR_RAW_MAX)}__name(ghErrorMessage,"ghErrorMessage");async function fetchGitHubPullRequests(cwd,env,options2){const gitRoot=findGitRoot(cwd);if(!gitRoot)return{kind:"not_a_repo"};let stdout;try{stdout=await runGhPrList(gitRoot,env,options2)}catch(error3){if(error3.code==="ENOENT"){return{kind:"cli_unavailable"}}return{kind:"failed",message:ghErrorMessage(error3),gitRoot,...fallbackBinaryField(ghEnv(env),gitRoot)}}try{return{kind:"ok",pullRequests:parseGhPrList(stdout)}}catch(error3){return{kind:"failed",message:ghErrorMessage(error3),gitRoot}}}__name(fetchGitHubPullRequests,"fetchGitHubPullRequests");var GH_CREATE_TIMEOUT_MS=3e4;function runGhPrCreate(gitRoot,opts,env){const args=["pr","create","--title",opts.title];args.push("--body",opts.body??"");if(opts.base)args.push("--base",opts.base);if(opts.head)args.push("--head",opts.head);const childEnv=ghEnv(env);return new Promise((resolve36,reject)=>{execFile(resolveGhBinary(childEnv,gitRoot),args,{cwd:gitRoot,timeout:GH_CREATE_TIMEOUT_MS,maxBuffer:GH_MAX_BUFFER,windowsHide:true,encoding:"utf8",env:childEnv},(error3,stdout)=>{if(error3)reject(error3);else resolve36(stdout)})})}__name(runGhPrCreate,"runGhPrCreate");async function createGitHubPullRequest(cwd,opts,env){const gitRoot=findGitRoot(cwd);if(!gitRoot)return{kind:"not_a_repo"};let stdout;try{stdout=await runGhPrCreate(gitRoot,opts,env)}catch(error3){if(error3.code==="ENOENT"){return{kind:"cli_unavailable"}}return{kind:"failed",message:ghErrorMessage(error3,"gh pr create",GH_CREATE_TIMEOUT_MS),gitRoot,...fallbackBinaryField(ghEnv(env),gitRoot)}}const url4=stdout.trim();const numberMatch=/\/pull\/(\d+)/.exec(url4);const number7=numberMatch?parseInt(numberMatch[1],10):null;return{kind:"ok",url:url4,number:number7}}__name(createGitHubPullRequest,"createGitHubPullRequest");async function getDefaultBranch(cwd,env){const gitRoot=findGitRoot(cwd);if(!gitRoot)return null;try{const{stdout}=await execFileAsync("git",["symbolic-ref","refs/remotes/origin/HEAD","--short"],{cwd:gitRoot,timeout:5e3,encoding:"utf8",windowsHide:true,env:gitEnv(env)});const raw=stdout.trim();if(!raw)return null;return raw}catch{return null}}__name(getDefaultBranch,"getDefaultBranch");var GIT_REMOTE_TIMEOUT_MS=5e3;function normalizeRemoteToWebUrl(remote){const trimmed=remote.trim();if(!trimmed)return void 0;let input=trimmed;let sshDerived=false;if(input.startsWith("ssh://")){input=`https://${input.slice("ssh://".length)}`;sshDerived=true}else if(!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(input)){const scp=/^(?:[^@\s/]+@)?([^:\s/]+):(.+)$/.exec(input);if(!scp)return void 0;if(/^[A-Za-z]$/.test(scp[1]))return void 0;input=`https://${scp[1]}/${scp[2]}`;sshDerived=true}let url4;try{url4=new URL(input)}catch{return void 0}if(url4.protocol!=="http:"&&url4.protocol!=="https:")return void 0;const pathname=url4.pathname.replace(/\.git\/?$/,"");if(!pathname||pathname==="/")return void 0;const host=sshDerived?url4.hostname:url4.host;return`${url4.protocol}//${host}${pathname}`.replace(/\/$/,"")}__name(normalizeRemoteToWebUrl,"normalizeRemoteToWebUrl");function repoKeyFromWebUrl(webUrl){let url4;try{url4=new URL(webUrl)}catch{return void 0}if(url4.protocol!=="http:"&&url4.protocol!=="https:")return void 0;const segments=url4.pathname.split("/").filter(Boolean);if(segments.length<2)return void 0;const hostname3=url4.hostname.replace(/^www\./,"");return`${hostname3}/${segments[0]}/${segments[1]}`.toLowerCase()}__name(repoKeyFromWebUrl,"repoKeyFromWebUrl");function fetchRemoteWebUrl(cwd,env){const gitRoot=findGitRoot(cwd);if(!gitRoot)return Promise.resolve(void 0);return new Promise(resolve36=>{execFile("git",["remote","get-url","origin"],{cwd:gitRoot,timeout:GIT_REMOTE_TIMEOUT_MS,encoding:"utf8",windowsHide:true,env:gitEnv(env)},(error3,stdout)=>{resolve36(error3?void 0:normalizeRemoteToWebUrl(stdout))})})}__name(fetchRemoteWebUrl,"fetchRemoteWebUrl");function fetchCurrentBranchPullRequest(cwd,env){const gitRoot=findGitRoot(cwd);if(!gitRoot)return Promise.resolve({status:"error"});const childEnv=ghEnv(env);return new Promise(resolve36=>{execFile(resolveGhBinary(childEnv,gitRoot),["pr","view","--json","number,url,state,headRefName"],{cwd:gitRoot,timeout:GH_TIMEOUT_MS,maxBuffer:GH_MAX_BUFFER,windowsHide:true,encoding:"utf8",env:childEnv},(error3,stdout,stderr)=>{if(error3){resolve36(/no pull requests found/i.test(stderr)?{status:"none"}:{status:"error"});return}try{const parsed=JSON.parse(stdout);const state=parsed.state?.toLowerCase();resolve36(typeof parsed.number==="number"&&typeof parsed.url==="string"&&(state==="open"||state==="merged"||state==="closed")?{status:"pr",number:parsed.number,url:parsed.url,state,...typeof parsed.headRefName==="string"?{headRefName:parsed.headRefName}:{}}:{status:"error"})}catch{resolve36({status:"error"})}})})}__name(fetchCurrentBranchPullRequest,"fetchCurrentBranchPullRequest");function fetchCurrentBranchName(cwd){const gitRoot=findGitRoot(cwd);if(!gitRoot)return Promise.resolve(void 0);return new Promise(resolve36=>{execFile("git",["branch","--show-current"],{cwd:gitRoot,timeout:GIT_REMOTE_TIMEOUT_MS,encoding:"utf8",windowsHide:true,env:gitEnv()},(error3,stdout)=>{const name2=stdout.trim();resolve36(error3||name2===""?void 0:name2)})})}__name(fetchCurrentBranchName,"fetchCurrentBranchName");function fetchAttributionRepoKeys(cwd,env){const gitRoot=findGitRoot(cwd);if(!gitRoot)return Promise.resolve({});const childEnv=ghEnv(env);return new Promise(resolve36=>{execFile(resolveGhBinary(childEnv,gitRoot),["repo","view","--json","url,parent"],{cwd:gitRoot,timeout:GH_TIMEOUT_MS,maxBuffer:GH_MAX_BUFFER,windowsHide:true,encoding:"utf8",env:childEnv},(error3,stdout)=>{if(error3){resolve36({});return}try{const parsed=JSON.parse(stdout);const resolved=typeof parsed.url==="string"?repoKeyFromWebUrl(parsed.url):void 0;const parentUrl=parsed.parent?.url;const parent=typeof parentUrl==="string"?repoKeyFromWebUrl(parentUrl):void 0;resolve36({...resolved?{resolved}:{},...parent?{parent}:{}})}catch{resolve36({})}})})}__name(fetchAttributionRepoKeys,"fetchAttributionRepoKeys");var GH_TIMEOUT_MS2=1e4;var GH_MAX_BUFFER2=16*1024*1024;var GITHUB_PR_ISSUES_BATCH_SIZE=100;var SESSION_PR_ISSUE_LIST_LIMIT=10;var GH_REPO_UNRESOLVED_PATTERN=/no git remotes found|point to a known GitHub host/i;function buildPullRequestIssuesQuery(numbers){const lookups=numbers.map(number7=>`p${number7}: pullRequest(number: ${number7}) { number url closingIssuesReferences(first: ${SESSION_PR_ISSUE_LIST_LIMIT}) { nodes { number url state stateReason } } }`).join(" ");return`query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${lookups} } }`}__name(buildPullRequestIssuesQuery,"buildPullRequestIssuesQuery");function mapIssueState(state,stateReason){if(state!=="CLOSED")return"open";return stateReason==="NOT_PLANNED"||stateReason==="DUPLICATE"?"not_planned":"completed"}__name(mapIssueState,"mapIssueState");function mapIssue(node){if(typeof node.number!=="number"||!Number.isInteger(node.number)||node.number<=0||typeof node.url!=="string"){return null}return{number:node.number,url:node.url,state:mapIssueState(node.state,node.stateReason)}}__name(mapIssue,"mapIssue");var GhRepositoryNotFoundError=class extends Error{static{__name(this,"GhRepositoryNotFoundError")}constructor(){super("gh api graphql: the repository could not be resolved")}};function parsePullRequestIssuesResponse(stdout){const parsed=JSON.parse(stdout);const errors=parsed?.errors;if(Array.isArray(errors)){for(const error3 of errors){const notFoundAt=error3.type==="NOT_FOUND"&&Array.isArray(error3.path)?error3.path:void 0;if(notFoundAt?.length===1&&notFoundAt[0]==="repository"){throw new GhRepositoryNotFoundError}const aliasNotFound=notFoundAt?.length===2&&notFoundAt[0]==="repository";if(!aliasNotFound){throw new Error(`gh api graphql partial error: ${JSON.stringify(error3).slice(0,200)}`)}}}const repository=parsed?.data?.repository;if(repository===null||typeof repository!=="object"){throw new Error("unexpected gh output: expected repository data")}const result=new Map;for(const value of Object.values(repository)){if(value===null||typeof value!=="object")continue;const pr2=value;if(typeof pr2.number!=="number"||typeof pr2.url!=="string")continue;const nodes=pr2.closingIssuesReferences?.nodes;const issues=Array.isArray(nodes)?nodes.map(node=>mapIssue(node)).filter(issue3=>issue3!==null):[];result.set(pr2.number,{url:pr2.url,issues})}return result}__name(parsePullRequestIssuesResponse,"parsePullRequestIssuesResponse");function runGhGraphql(gitRoot,env,query){const childEnv=ghEnv(env);return new Promise((resolve36,reject)=>{execFile2(resolveGhBinary(childEnv,gitRoot),["api","graphql","-F","owner={owner}","-F","name={repo}","-f",`query=${query}`],{cwd:gitRoot,timeout:GH_TIMEOUT_MS2,maxBuffer:GH_MAX_BUFFER2,windowsHide:true,encoding:"utf8",env:childEnv},(error3,stdout,stderr)=>{if(error3&&(error3.killed||!stdout.trim())){reject(Object.assign(error3,{stderr}))}else{resolve36(stdout)}})})}__name(runGhGraphql,"runGhGraphql");async function fetchGitHubPullRequestIssues(cwd,env,numbers){const gitRoot=findGitRoot(cwd);if(!gitRoot)return{kind:"not_a_repo"};const valid=[...new Set(numbers.filter(n=>Number.isSafeInteger(n)&&n>0))];const pullRequests=new Map;for(let i=0;i<valid.length;i+=GITHUB_PR_ISSUES_BATCH_SIZE){const chunk=valid.slice(i,i+GITHUB_PR_ISSUES_BATCH_SIZE);let stdout;try{stdout=await runGhGraphql(gitRoot,env,buildPullRequestIssuesQuery(chunk))}catch(error3){if(error3.code==="ENOENT"){return{kind:"cli_unavailable"}}const stderr=error3.stderr;if(typeof stderr==="string"&&GH_REPO_UNRESOLVED_PATTERN.test(stderr)){return{kind:"repo_unresolved"}}return{kind:"failed",message:ghErrorMessage(error3,"gh api graphql",GH_TIMEOUT_MS2),gitRoot}}try{for(const[number7,entry]of parsePullRequestIssuesResponse(stdout)){pullRequests.set(number7,entry)}}catch(error3){if(error3 instanceof GhRepositoryNotFoundError){return{kind:"repo_unresolved"}}return{kind:"failed",message:ghErrorMessage(error3,"gh api graphql",GH_TIMEOUT_MS2),gitRoot}}}return{kind:"ok",pullRequests}}__name(fetchGitHubPullRequestIssues,"fetchGitHubPullRequestIssues");var SESSION_PR_LIST_LIMIT=10;var SESSION_PR_URL_MAX_LENGTH=2048;function hasControlCharacter2(value){return Array.from(value).some(character=>{const code=character.charCodeAt(0);return code<=31||code===127})}__name(hasControlCharacter2,"hasControlCharacter");function isValidSessionPrUrl(url4){return url4.length<=SESSION_PR_URL_MAX_LENGTH&&/^https?:\/\//i.test(url4)&&!hasControlCharacter2(url4)}__name(isValidSessionPrUrl,"isValidSessionPrUrl");function isValidBindingUrl(value){return typeof value==="string"&&isValidSessionPrUrl(value)}__name(isValidBindingUrl,"isValidBindingUrl");function isValidSessionPrIssue(value){if(value===null||typeof value!=="object")return false;const v2=value;return typeof v2["number"]==="number"&&Number.isInteger(v2["number"])&&v2["number"]>0&&isValidBindingUrl(v2["url"])&&(v2["state"]===void 0||v2["state"]==="open"||v2["state"]==="completed"||v2["state"]==="not_planned")}__name(isValidSessionPrIssue,"isValidSessionPrIssue");function isValidSessionPr(value){if(value===null||typeof value!=="object")return false;const v2=value;return typeof v2["number"]==="number"&&Number.isInteger(v2["number"])&&v2["number"]>0&&isValidBindingUrl(v2["url"])&&typeof v2["createdAt"]==="string"&&(v2["state"]===void 0||v2["state"]==="open"||v2["state"]==="merged"||v2["state"]==="closed")&&(v2["source"]===void 0||v2["source"]==="create"||v2["source"]==="worktree"||v2["source"]==="review")&&(v2["issues"]===void 0||Array.isArray(v2["issues"])&&v2["issues"].length<=SESSION_PR_ISSUE_LIST_LIMIT&&v2["issues"].every(isValidSessionPrIssue))}__name(isValidSessionPr,"isValidSessionPr");function isValidSessionPrList(value){if(value===null||typeof value!=="object")return false;const prs=value["prs"];return Array.isArray(prs)&&prs.length>0&&prs.every(isValidSessionPr)}__name(isValidSessionPrList,"isValidSessionPrList");async function readSessionPrs(filePath,options2={}){let raw;try{options2.signal?.throwIfAborted();raw=options2.signal?await fs8.readFile(filePath,{encoding:"utf-8",signal:options2.signal}):await fs8.readFile(filePath,"utf-8")}catch(error3){options2.signal?.throwIfAborted();if(isNodeError(error3)&&error3.code==="ENOENT")return null;throw error3}options2.signal?.throwIfAborted();let parsed;try{parsed=JSON.parse(raw)}catch{return null}options2.signal?.throwIfAborted();if(!isValidSessionPrList(parsed))return null;return parsed.prs}__name(readSessionPrs,"readSessionPrs");async function writeSessionPrs(filePath,prs,options2={}){await fs8.mkdir(path10.dirname(filePath),{recursive:true});await atomicWriteJSON(filePath,{prs},options2)}__name(writeSessionPrs,"writeSessionPrs");var GH_PR_CREATE_SEGMENT_PATTERN=/^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)*(?:(?:sudo|env|nohup|command)\s+(?:-\S+(?:\s+\S+)?\s+|[A-Za-z_][A-Za-z0-9_]*=\S+\s+){0,3})*(?:\S*[/\\])?gh(?:\.exe|\.cmd|\.bat)?\s+pr\s+(?:create|new)\b/;function commandRunsGhPrCreate(command){return command.split(/&&|\|\||[;|\n]/).some(segment=>GH_PR_CREATE_SEGMENT_PATTERN.test(segment))}__name(commandRunsGhPrCreate,"commandRunsGhPrCreate");var GH_INLINE_ENV_ASSIGNMENT_PATTERN=/^(GH_[A-Za-z0-9_]*|GITHUB_[A-Za-z0-9_]*)=(\S+)$/;var GH_ENV_NAME_PATTERN=/^(?:GH_|GITHUB_)[A-Za-z0-9_]*$/;var GH_CREATE_WRAPPER_NAMES=new Set(["sudo","env","nohup","command"]);var GH_BINARY_PATTERN=/(?:^|[/\\])gh(?:\.exe|\.cmd|\.bat)?$/;function expandInlineEnvValue(raw){if(raw.length>=2&&raw.startsWith("'")&&raw.endsWith("'")){return raw.slice(1,-1)}const unquoted=raw.length>=2&&raw.startsWith('"')&&raw.endsWith('"')?raw.slice(1,-1):raw;if(/\$\{(?![A-Za-z_][A-Za-z0-9_]*\})/.test(unquoted))return unquoted;return unquoted.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,(_match,braced,bare)=>process.env[braced??bare??""]??"")}__name(expandInlineEnvValue,"expandInlineEnvValue");function ghPrCreateInlineEnv(command){const exported={};let record4;const dropAmbient=__name(env=>{for(const name2 of Object.keys(process.env)){if(GH_ENV_NAME_PATTERN.test(name2))env[name2]=void 0}},"dropAmbient");for(const segment of command.split(/&&|\|\||[;|\n]/)){const tokens=segment.trim().split(/\s+/);if(tokens[0]==="export"){for(let i=1;i<tokens.length;i++){const assignment=GH_INLINE_ENV_ASSIGNMENT_PATTERN.exec(tokens[i]);if(assignment!==null){exported[assignment[1]]=expandInlineEnvValue(assignment[2]);continue}if(!tokens[i].includes("="))break}continue}if(tokens[0]==="unset"){for(const token of tokens.slice(1)){if(GH_ENV_NAME_PATTERN.test(token))exported[token]=void 0}continue}if(!GH_PR_CREATE_SEGMENT_PATTERN.test(segment))continue;const env={...exported};let pendingFlag;for(const token of tokens){const assignment=GH_INLINE_ENV_ASSIGNMENT_PATTERN.exec(token);if(assignment!==null){env[assignment[1]]=expandInlineEnvValue(assignment[2]);pendingFlag=void 0;continue}if(/^[A-Za-z_][A-Za-z0-9_]*=\S+$/.test(token)){pendingFlag=void 0;continue}if(GH_BINARY_PATTERN.test(token))break;if(pendingFlag!==void 0){if(pendingFlag==="-u"&&GH_ENV_NAME_PATTERN.test(token)){env[token]=void 0}pendingFlag=void 0;continue}if(token==="-i"){dropAmbient(env);continue}if(GH_CREATE_WRAPPER_NAMES.has(token)||token.startsWith("-")){pendingFlag=token.startsWith("-")?token:void 0;continue}break}record4=env}if(record4===void 0)return void 0;return Object.keys(record4).length>0?record4:void 0}__name(ghPrCreateInlineEnv,"ghPrCreateInlineEnv");function toSessionPrInfo({number:number7,url:url4,state,issues}){return{number:number7,url:url4,...state?{state}:{},...issues?{issues}:{}}}__name(toSessionPrInfo,"toSessionPrInfo");function mergeSessionPrLists(base2,incoming){const byNumber=new Map;for(const entry of[...base2,...incoming]){const known=byNumber.get(entry.number);if(!known){byNumber.set(entry.number,entry);continue}const[newer,older]=entry.createdAt>=known.createdAt?[entry,known]:[known,entry];const source=canonicalSessionPrUrl(newer.url)===canonicalSessionPrUrl(older.url)&&sessionPrSourceAuthority(older.source)>sessionPrSourceAuthority(newer.source)?older.source:newer.source;byNumber.set(entry.number,source===newer.source?newer:{...newer,source})}return capSessionPrListByAuthority([...byNumber.values()].sort((left,right)=>left.createdAt.localeCompare(right.createdAt)))}__name(mergeSessionPrLists,"mergeSessionPrLists");function sessionPrSourceAuthority(source){switch(source){case"worktree":return 3;case"create":return 2;case"review":return 0;default:return 1}}__name(sessionPrSourceAuthority,"sessionPrSourceAuthority");function capSessionPrListByAuthority(list2){const overflow=list2.length-SESSION_PR_LIST_LIMIT;if(overflow<=0)return list2;const evictPositions=new Set(list2.map((_2,index)=>index).sort((a,b2)=>sessionPrSourceAuthority(list2[a].source)-sessionPrSourceAuthority(list2[b2].source)||a-b2).slice(0,overflow));return list2.filter((_2,index)=>!evictPositions.has(index))}__name(capSessionPrListByAuthority,"capSessionPrListByAuthority");var LOCK_OPTIONS={retries:{retries:10,minTimeout:5,maxTimeout:100,factor:2,randomize:true},stale:5e3,onCompromised:__name(()=>{},"onCompromised")};async function withSidecarLock(filePath,run){const dir=path10.dirname(filePath);await fs8.mkdir(dir,{recursive:true});const lockPath=path10.join(await fs8.realpath(dir),path10.basename(filePath));const release=await import_proper_lockfile.default.lock(lockPath,{...LOCK_OPTIONS,realpath:false});try{return await run()}finally{try{await release()}catch{}}}__name(withSidecarLock,"withSidecarLock");var mutationQueue=new Map;function enqueuePrMutation(filePath,run){const previous=mutationQueue.get(filePath)??Promise.resolve();const next=previous.catch(()=>void 0).then(()=>withSidecarLock(filePath,run));mutationQueue.set(filePath,next);const cleanup=__name(()=>{if(mutationQueue.get(filePath)===next)mutationQueue.delete(filePath)},"cleanup");void next.then(cleanup,cleanup);return next}__name(enqueuePrMutation,"enqueuePrMutation");function canonicalSessionPrUrl(url4){try{const parsed=new URL(url4);return`${parsed.origin}${parsed.pathname}`.toLowerCase().replace(/\/+$/,"")}catch{return url4.toLowerCase().replace(/\/+$/,"")}}__name(canonicalSessionPrUrl,"canonicalSessionPrUrl");function upsertSessionPr(filePath,pr2){return enqueuePrMutation(filePath,async()=>{const existing=await readSessionPrs(filePath)??[];const known=existing.find(entry2=>entry2.number===pr2.number&&canonicalSessionPrUrl(entry2.url)===canonicalSessionPrUrl(pr2.url));const source=known===void 0?pr2.source:pr2.source!==void 0&&sessionPrSourceAuthority(pr2.source)>=sessionPrSourceAuthority(known.source)?pr2.source:known.source;const state=pr2.state??known?.state;const entry={number:pr2.number,url:pr2.url,createdAt:new Date().toISOString(),...state?{state}:{},...source?{source}:{},...known?.issues?{issues:known.issues}:{}};if(!isValidSessionPr(entry))return existing;const next=capSessionPrListByAuthority([...existing.filter(e=>e.number!==pr2.number),entry]);await writeSessionPrs(filePath,next);return next})}__name(upsertSessionPr,"upsertSessionPr");function upsertSessionPrs(filePath,candidates){return enqueuePrMutation(filePath,async()=>{const existing=await readSessionPrs(filePath)??[];const next=[...existing];const appended=new Set;const alreadyBound=[];const unresolved=[];let changed=false;for(const candidate of candidates){const knownIndex=next.findIndex(entry2=>entry2.number===candidate.number);const known=knownIndex>=0?next[knownIndex]:void 0;if(candidate.url===void 0){(known?alreadyBound:unresolved).push(candidate.number);continue}if(known&&canonicalSessionPrUrl(known.url)===canonicalSessionPrUrl(candidate.url)){if(candidate.source!==void 0&&sessionPrSourceAuthority(candidate.source)>sessionPrSourceAuthority(known.source)){next[knownIndex]={...known,source:candidate.source};changed=true}alreadyBound.push(candidate.number);continue}const entry={number:candidate.number,url:candidate.url,createdAt:new Date().toISOString(),...candidate.state?{state:candidate.state}:{},...candidate.source?{source:candidate.source}:{}};if(!isValidSessionPr(entry)){unresolved.push(candidate.number);continue}if(knownIndex>=0)next.splice(knownIndex,1);next.push(entry);appended.add(candidate.number)}if(appended.size===0&&!changed){return{prs:existing,added:[],alreadyBound,unresolved}}const prs=capSessionPrListByAuthority(next);const persistedNumbers=new Set(prs.map(entry=>entry.number));const added=[...appended].filter(number7=>persistedNumbers.has(number7));await writeSessionPrs(filePath,prs);return{prs,added,alreadyBound,unresolved}})}__name(upsertSessionPrs,"upsertSessionPrs");function sameIssues(left,right){if(left===void 0||right===void 0)return left===right;return left.length===right.length&&left.every((issue3,index)=>issue3.number===right[index].number&&issue3.url===right[index].url&&issue3.state===right[index].state)}__name(sameIssues,"sameIssues");function updateSessionPrStates(filePath,states,options2={}){return enqueuePrMutation(filePath,async()=>{const existing=await readSessionPrs(filePath);if(!existing)return 0;let changed=0;const next=existing.map(entry=>{const fetched=states.get(entry.number);if(fetched===void 0||canonicalSessionPrUrl(fetched.url)!==canonicalSessionPrUrl(entry.url)){return entry}const state=fetched.state??entry.state;const issues=fetched.issues??entry.issues;if(state===entry.state&&sameIssues(issues,entry.issues)){return entry}changed+=1;return{...entry,...state?{state}:{},...issues?{issues}:{}}});if(changed===0)return 0;await writeSessionPrs(filePath,next,options2);return changed})}__name(updateSessionPrStates,"updateSessionPrStates");function moveSessionPrSidecar(sourcePath,destinationPath,assertCanMutate){if(!existsSync2(sourcePath))return Promise.resolve();const[first,second]=sourcePath<=destinationPath?[sourcePath,destinationPath]:[destinationPath,sourcePath];return enqueuePrMutation(first,()=>withSidecarLock(second,async()=>{if(!existsSync2(sourcePath))return;await fs8.mkdir(path10.dirname(destinationPath),{recursive:true});if(!existsSync2(destinationPath)){assertCanMutate?.();await fs8.rename(sourcePath,destinationPath);return}const merged=mergeSessionPrLists(await readSessionPrs(destinationPath)??[],await readSessionPrs(sourcePath)??[]);if(merged.length>0){if(assertCanMutate){await writeSessionPrs(destinationPath,merged,{assertCanCommit:assertCanMutate})}else{await writeSessionPrs(destinationPath,merged)}}assertCanMutate?.();await fs8.unlink(sourcePath)}))}__name(moveSessionPrSidecar,"moveSessionPrSidecar");function replaceSessionPrs(filePath,plan){return enqueuePrMutation(filePath,async()=>{const existing=await readSessionPrs(filePath)??[];const planned=plan(existing);if(planned===null)return null;const next=planned.filter(isValidSessionPr);if(next.length===0&&planned.length>0)return null;await writeSessionPrs(filePath,next);return next})}__name(replaceSessionPrs,"replaceSessionPrs");init_esbuild_shims();import*as crypto from"node:crypto";import*as fs12 from"node:fs";import*as fsp from"node:fs/promises";import*as path17 from"node:path";import{performance as performance2}from"node:perf_hooks";init_esbuild_shims();init_esbuild_shims();import{randomUUID as randomUUID8}from"node:crypto";init_esbuild_shims();init_esbuild_shims();var MANAGED_EXTENSION_RECORD_LIMITS=Object.freeze({maxIdBytes:MANAGED_SESSION_LIMITS.maxIdBytes,minLeaseDurationMs:1e3,maxLeaseDurationMs:3e5,maxGrantPhases:16,maxPhaseLength:64,maxMonitorEvents:1e4,maxMonitorIdleTimeoutMs:6e5,maxMonitorDebounceMs:6e5});var MANAGED_EXTENSION_RECORD_KINDS=Object.freeze({monitorRun:"managed-monitor_run",monitorOutput:MANAGED_TOOL_RESULT_KINDS.manifest});var RUN_STATES=["reserved","admitted","running","waiting","settled","failed","cancelled","recovery_blocked"];var EXECUTION_STATES=["intent","dispatch_started","running_attached","settled","not_started_proven","outcome_unknown","corrupt"];var DELIVERY_STATES=["planned","sending","partial","delivered","accepting","accepted","consumed","unknown","rejected","cancelled"];var DELIVERY_TARGETS=["channel","session"];var RECOVERY_REASONS=["outcome_unknown","execution_corrupt","runtime_lost","dispatch_unknown","handler_unavailable"];var QUOTA_REASONS=["count_limit","rate_limit","depth_limit","byte_limit","budget_exhausted","duration_limit"];var STOP_REASONS=["exited","max_events","idle_timeout","start_failed","watch_failed","quota_exceeded","stop_requested"];function line(states,transitions){const frozen={};for(const state of states){frozen[state]=Object.freeze([...transitions[state]])}return Object.freeze({states:Object.freeze([...states]),transitions:Object.freeze(frozen)})}__name(line,"line");var MANAGED_EXTENSION_STATE_LINES=Object.freeze({run:line(RUN_STATES,{reserved:["admitted","failed","cancelled"],admitted:["running","waiting","failed","cancelled","recovery_blocked"],running:["waiting","settled","failed","cancelled","recovery_blocked"],waiting:["running","settled","failed","cancelled","recovery_blocked"],settled:[],failed:[],cancelled:[],recovery_blocked:["running","waiting","settled","failed","cancelled"]}),execution:line(EXECUTION_STATES,{intent:["dispatch_started","not_started_proven","outcome_unknown","corrupt"],dispatch_started:["running_attached","settled","not_started_proven","outcome_unknown","corrupt"],running_attached:["settled","outcome_unknown","corrupt"],settled:[],not_started_proven:[],outcome_unknown:["running_attached","settled","not_started_proven","corrupt"],corrupt:[]}),delivery:line(DELIVERY_STATES,{planned:["sending","accepting","cancelled"],sending:["delivered","partial","unknown","rejected"],partial:["sending","unknown"],delivered:[],accepting:["accepted","unknown","rejected"],accepted:["consumed"],consumed:[],unknown:["delivered","partial","accepted","rejected"],rejected:[],cancelled:[]})});var MANAGED_EXTENSION_DELIVERY_TARGETS=Object.freeze({channel:Object.freeze(["planned","sending","partial","delivered","unknown","rejected","cancelled"]),session:Object.freeze(["planned","accepting","accepted","consumed","unknown","rejected","cancelled"])});var MANAGED_EXTENSION_REASONS=Object.freeze({recovery:Object.freeze([...RECOVERY_REASONS]),quota:Object.freeze([...QUOTA_REASONS])});var MANAGED_EXTENSION_MONITOR_STOP_REASONS=Object.freeze({settled:Object.freeze(["exited","max_events","idle_timeout"]),failed:Object.freeze(["start_failed","watch_failed","quota_exceeded"]),cancelled:Object.freeze(["stop_requested"])});var LIMITS=MANAGED_EXTENSION_RECORD_LIMITS;var LINES=MANAGED_EXTENSION_STATE_LINES;var GENERATION_PATTERN=/^[1-9][0-9]{0,18}$/;var MAX_GENERATION=2n**63n-1n;var PHASE_PATTERN=new RegExp(`^[a-z][a-z0-9_]{0,${LIMITS.maxPhaseLength-1}}$`);var TERMINAL_RUN_STATES=["settled","failed","cancelled"];var PROVEN_EXECUTION_STATES=["settled","not_started_proven"];var UNSTARTED_EXECUTION_STATES=[null,"intent","dispatch_started","not_started_proven"];var GRANT_KEYS=["domain","expiresAt","leaseDurationMs","operationId","operationRevision","ownerId","resourceScope","sessionKey","workspaceGeneration"];var SCOPE_KEYS=["phases","recordRef"];var PIN_KEYS=["definitionDigest","definitionId","definitionRevision"];var RUN_KEYS=["definition","delivery","deliveryId","dispatchId","effectId","execution","executionCallId","reason","runtime","state"];var RUNTIME_KEYS=["generation","runtimeBindingId"];var DELIVERY_KEYS=["state","target"];var MONITOR_KEYS=["commandRef","debounceMs","idleTimeoutMs","lastObservationRef","maxEvents","monitorId","notifiedThrough","observationSequence","outputRef","ownerScopeId","run","startReceiptRef","stopReason"];var MONITOR_FIXED_KEYS=["monitorId","ownerScopeId","commandRef","maxEvents","idleTimeoutMs","debounceMs"];function fail(message){throw new ManagedSessionRecordError(message)}__name(fail,"fail");function closed(value,keys2,label){if(typeof value!=="object"||value===null){fail(`${label} must be a JSON object.`)}const prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null){fail(`${label} must be a plain JSON object.`)}const present=Object.keys(value);if(present.length!==keys2.length||present.some(key=>!keys2.includes(key))){fail(`${label} must have exactly the keys ${keys2.join(", ")}.`)}const snapshot={};for(const key of keys2){snapshot[key]=value[key]}return snapshot}__name(closed,"closed");function oneOf(value,allowed,label){if(typeof value!=="string"||!allowed.includes(value)){fail(`${label} must be one of: ${allowed.join(", ")}.`)}return value}__name(oneOf,"oneOf");function id(value,label){return assertManagedSessionStableId(value,label)}__name(id,"id");function count(value,label,min=0,max){const number7=assertManagedSessionSequence(value,label);if(number7<min||max!==void 0&&number7>max){fail(max!==void 0?`${label} must be an integer from ${min} to ${max}.`:`${label} must be an integer from ${min} or more.`)}return number7}__name(count,"count");function generation(value,label){if(typeof value!=="string"||!GENERATION_PATTERN.test(value)||BigInt(value)>MAX_GENERATION){fail(`${label} must be canonical decimal text from 1 to 2^63-1.`)}return value}__name(generation,"generation");function ref(value,label){return Object.freeze(assertManagedSessionDurableRef(value,label))}__name(ref,"ref");function nullable(value,parse15){return value===null?null:parse15(value)}__name(nullable,"nullable");function attempt(parse15){try{return parse15()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return void 0;throw error3}}__name(attempt,"attempt");function sameJson(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(sameJson,"sameJson");function isTerminalRunState(state){return TERMINAL_RUN_STATES.includes(state)}__name(isTerminalRunState,"isTerminalRunState");function isTerminal(state){return isTerminalRunState(state)}__name(isTerminal,"isTerminal");function isRecoveryReason(reason){return RECOVERY_REASONS.includes(reason??"")}__name(isRecoveryReason,"isRecoveryReason");function isQuotaReason(reason){return QUOTA_REASONS.includes(reason??"")}__name(isQuotaReason,"isQuotaReason");function transitionsOf(stateLine){return Object.hasOwn(LINES,stateLine)?LINES[stateLine].transitions:void 0}__name(transitionsOf,"transitionsOf");function isExtensionTransitionAllowed(stateLine,from,to2){const transitions=transitionsOf(stateLine);return transitions!==void 0&&Object.hasOwn(transitions,from)&&transitions[from].includes(to2)}__name(isExtensionTransitionAllowed,"isExtensionTransitionAllowed");function advances(stateLine,from,to2){return from===to2||isExtensionTransitionAllowed(stateLine,from,to2)}__name(advances,"advances");function parseOperationGrant(value){const grant=closed(value,GRANT_KEYS,"grant");const domain=oneOf(grant.domain,MANAGED_SESSION_DOMAINS,"grant.domain");const scope=closed(grant.resourceScope,SCOPE_KEYS,"grant.resourceScope");const recordRef=ref(scope.recordRef,"grant.resourceScope.recordRef");if(recordRef.kind!==`managed-${domain}`||recordRef.schemaVersion!==1){fail(`grant.resourceScope.recordRef must reference managed-${domain} version 1.`)}if(!Array.isArray(scope.phases)||scope.phases.length===0||scope.phases.length>LIMITS.maxGrantPhases){fail(`grant.resourceScope.phases must list 1 to ${LIMITS.maxGrantPhases} phases.`)}const phases=Array.from(scope.phases,(phase,index)=>{if(typeof phase!=="string"||!PHASE_PATTERN.test(phase)){fail(`grant.resourceScope.phases[${index}] must match ${PHASE_PATTERN.source}.`)}return phase});if(new Set(phases).size!==phases.length){fail("grant.resourceScope.phases must not repeat a phase.")}return Object.freeze({sessionKey:Object.freeze(assertManagedSessionKey(grant.sessionKey,"grant.sessionKey")),operationId:id(grant.operationId,"grant.operationId"),domain,operationRevision:count(grant.operationRevision,"grant.operationRevision",1),ownerId:id(grant.ownerId,"grant.ownerId"),workspaceGeneration:generation(grant.workspaceGeneration,"grant.workspaceGeneration"),resourceScope:Object.freeze({recordRef,phases:Object.freeze(phases)}),leaseDurationMs:count(grant.leaseDurationMs,"grant.leaseDurationMs",LIMITS.minLeaseDurationMs,LIMITS.maxLeaseDurationMs),expiresAt:assertManagedSessionTime(grant.expiresAt,"grant.expiresAt")})}__name(parseOperationGrant,"parseOperationGrant");function isOperationGrantSuccessor(previous,next){const before=attempt(()=>parseOperationGrant(previous));const after=attempt(()=>parseOperationGrant(next));if(!before||!after||!managedSessionKeysEqual(before.sessionKey,after.sessionKey)||before.operationId!==after.operationId||before.domain!==after.domain){return false}if(after.operationRevision===before.operationRevision){return after.expiresAt>before.expiresAt&&sameJson({...before,expiresAt:0},{...after,expiresAt:0})}return after.operationRevision>before.operationRevision&&BigInt(after.workspaceGeneration)>=BigInt(before.workspaceGeneration)}__name(isOperationGrantSuccessor,"isOperationGrantSuccessor");function parseDefinitionPin(value,label="definition"){const pin=closed(value,PIN_KEYS,label);return Object.freeze({definitionId:id(pin.definitionId,`${label}.definitionId`),definitionRevision:count(pin.definitionRevision,`${label}.definitionRevision`,1),definitionDigest:assertManagedSessionDigest(pin.definitionDigest,`${label}.definitionDigest`)})}__name(parseDefinitionPin,"parseDefinitionPin");function isDefinitionPinConsistent(first,second){const a=attempt(()=>parseDefinitionPin(first));const b2=attempt(()=>parseDefinitionPin(second));return a!==void 0&&b2!==void 0&&(a.definitionId!==b2.definitionId||a.definitionRevision!==b2.definitionRevision||a.definitionDigest===b2.definitionDigest)}__name(isDefinitionPinConsistent,"isDefinitionPinConsistent");function parseReason(value,label){return nullable(value,reason=>oneOf(reason,[...RECOVERY_REASONS,...QUOTA_REASONS],label))}__name(parseReason,"parseReason");function assertReason(label,run){const{state,reason}=run;const allowed=state==="recovery_blocked"?isRecoveryReason(reason):state==="running"||state==="waiting"?reason===null||isRecoveryReason(reason):state==="failed"?reason===null||isQuotaReason(reason):reason===null;if(!allowed)fail(`${label}.reason does not fit the ${state} state.`);if(reason==="outcome_unknown"&&run.execution!=="outcome_unknown"){fail(`${label}.reason outcome_unknown needs an unknown execution.`)}if(reason==="execution_corrupt"!==(run.execution==="corrupt")){fail(`${label}.reason is execution_corrupt exactly when it is corrupt.`)}if(reason==="runtime_lost"&&run.runtime===null){fail(`${label}.reason runtime_lost needs the Runtime binding it lost.`)}if(reason==="runtime_lost"&&state==="recovery_blocked"&&run.execution==="running_attached"){fail(`${label} cannot be blocked on a lost Runtime while attached.`)}if(reason==="dispatch_unknown"&&run.dispatchId===null){fail(`${label}.reason dispatch_unknown needs a dispatchId.`)}}__name(assertReason,"assertReason");function parseExtensionRun(value,label="run"){const run=closed(value,RUN_KEYS,label);const optionalId=__name(field=>nullable(run[field],each=>id(each,`${label}.${field}`)),"optionalId");const parsed={state:oneOf(run.state,RUN_STATES,`${label}.state`),reason:parseReason(run.reason,`${label}.reason`),definition:nullable(run.definition,pin=>parseDefinitionPin(pin,`${label}.definition`)),executionCallId:optionalId("executionCallId"),effectId:optionalId("effectId"),dispatchId:optionalId("dispatchId"),deliveryId:optionalId("deliveryId"),execution:nullable(run.execution,state2=>oneOf(state2,EXECUTION_STATES,`${label}.execution`)),runtime:nullable(run.runtime,runtime=>{const binding=closed(runtime,RUNTIME_KEYS,`${label}.runtime`);return Object.freeze({runtimeBindingId:id(binding.runtimeBindingId,`${label}.runtime.runtimeBindingId`),generation:generation(binding.generation,`${label}.runtime.generation`)})}),delivery:nullable(run.delivery,delivery2=>{const entry=closed(delivery2,DELIVERY_KEYS,`${label}.delivery`);const target=oneOf(entry.target,DELIVERY_TARGETS,`${label}.delivery.target`);return Object.freeze({target,state:oneOf(entry.state,MANAGED_EXTENSION_DELIVERY_TARGETS[target],`${label}.delivery.state`)})})};const{state,execution,delivery}=parsed;if(parsed.executionCallId!==null&&parsed.effectId!==null){fail(`${label} names one physical identity at most.`)}if(execution!==null&&parsed.executionCallId===null&&parsed.effectId===null){fail(`${label}.execution needs an executionCallId or an effectId.`)}if(parsed.runtime!==null&&execution===null){fail(`${label}.runtime needs an execution.`)}if(parsed.deliveryId!==null!==(delivery?.target==="channel")){fail(`${label}.deliveryId is set exactly for a channel delivery.`)}if(state==="reserved"&&(execution!==null||delivery!==null)){fail(`${label} has nothing dispatched while reserved.`)}if((execution==="outcome_unknown"||execution==="corrupt")&&state!=="recovery_blocked"&&!(execution==="outcome_unknown"&&state==="failed")){fail(`${label}.state must be recovery_blocked while execution is ${execution}.`)}if(isTerminal(state)&&execution!==null&&!PROVEN_EXECUTION_STATES.includes(execution)&&!(state==="failed"&&execution==="outcome_unknown")){fail(`${label}.state ${state} needs an execution proven to have ended.`)}if(state==="settled"&&execution==="not_started_proven"){fail(`${label} cannot settle an execution that never started.`)}if((state==="running"||state==="waiting")&&execution==="not_started_proven"){fail(`${label} cannot run on an execution that never started.`)}if(delivery?.target==="session"&&delivery.state!=="planned"&&delivery.state!=="cancelled"&&!isTerminal(state)){fail(`${label}.delivery cannot hand over a result before the run ends.`)}assertReason(label,parsed);return Object.freeze(parsed)}__name(parseExtensionRun,"parseExtensionRun");function setOnce(before,after){return before===null||sameJson(before,after)}__name(setOnce,"setOnce");function isExtensionRunSuccessor(previous,next){const before=attempt(()=>parseExtensionRun(previous));const after=attempt(()=>parseExtensionRun(next));if(!before||!after||!advances("run",before.state,after.state)){return false}if(isTerminal(before.state)&&!sameJson({...before,delivery:null,deliveryId:null},{...after,delivery:null,deliveryId:null})){return false}if(!setOnce(before.definition,after.definition)||!setOnce(before.executionCallId,after.executionCallId)||!setOnce(before.effectId,after.effectId)||!setOnce(before.dispatchId,after.dispatchId)||!setOnce(before.deliveryId,after.deliveryId)){return false}const dispatched=before.execution!==null&&before.execution!=="intent";if(dispatched&&before.definition===null&&after.definition!==null){return false}if(before.execution===null?after.execution!==null&&after.execution!=="intent":after.execution===null||!advances("execution",before.execution,after.execution)){return false}if(before.delivery===null?after.delivery!==null&&after.delivery.state!=="planned":after.delivery===null||before.delivery.target!==after.delivery.target||!advances("delivery",before.delivery.state,after.delivery.state)){return false}if(before.runtime===null)return after.runtime===null||!dispatched;if(sameJson(before.runtime,after.runtime))return true;return after.runtime!==null&&before.execution==="outcome_unknown"&&after.execution==="running_attached"&&BigInt(after.runtime.generation)>BigInt(before.runtime.generation)}__name(isExtensionRunSuccessor,"isExtensionRunSuccessor");function isExtensionRunStart(value){const run=attempt(()=>parseExtensionRun(value));return run!==void 0&&(run.state==="reserved"||run.state==="admitted")&&(run.execution===null||run.execution==="intent")&&(run.delivery===null||run.delivery.state==="planned")}__name(isExtensionRunStart,"isExtensionRunStart");function parseMonitorRun(value){const monitor=closed(value,MONITOR_KEYS,"monitorRun");const run=parseExtensionRun(monitor.run,"monitorRun.run");if(run.executionCallId===null||run.effectId!==null||run.dispatchId!==null||run.deliveryId!==null||run.delivery!==null||run.definition!==null){fail("monitorRun.run must name its start call and nothing else.")}const maxEvents=count(monitor.maxEvents,"monitorRun.maxEvents",1,LIMITS.maxMonitorEvents);const observationSequence=count(monitor.observationSequence,"monitorRun.observationSequence",0,maxEvents);const parsed={monitorId:id(monitor.monitorId,"monitorRun.monitorId"),ownerScopeId:id(monitor.ownerScopeId,"monitorRun.ownerScopeId"),commandRef:ref(monitor.commandRef,"monitorRun.commandRef"),maxEvents,idleTimeoutMs:count(monitor.idleTimeoutMs,"monitorRun.idleTimeoutMs",1,LIMITS.maxMonitorIdleTimeoutMs),debounceMs:count(monitor.debounceMs,"monitorRun.debounceMs",0,LIMITS.maxMonitorDebounceMs),startReceiptRef:nullable(monitor.startReceiptRef,each=>ref(each,"monitorRun.startReceiptRef")),observationSequence,lastObservationRef:nullable(monitor.lastObservationRef,each=>ref(each,"monitorRun.lastObservationRef")),notifiedThrough:count(monitor.notifiedThrough,"monitorRun.notifiedThrough",0,observationSequence),stopReason:nullable(monitor.stopReason,reason=>oneOf(reason,STOP_REASONS,"monitorRun.stopReason")),outputRef:nullable(monitor.outputRef,each=>{const output=ref(each,"monitorRun.outputRef");if(output.kind!==MANAGED_EXTENSION_RECORD_KINDS.monitorOutput||output.schemaVersion!==1){fail(`monitorRun.outputRef must reference ${MANAGED_EXTENSION_RECORD_KINDS.monitorOutput} version 1.`)}return output}),run};const{execution,state}=run;const{startReceiptRef,stopReason}=parsed;if(parsed.lastObservationRef===null!==(observationSequence===0)){fail("monitorRun.lastObservationRef is set exactly after an observation.")}if(startReceiptRef===null&&(observationSequence>0||execution==="running_attached")){fail("monitorRun.startReceiptRef must be set once the watch started.")}if(startReceiptRef!==null&&UNSTARTED_EXECUTION_STATES.includes(execution)){fail("monitorRun.startReceiptRef must be null before the watch starts.")}if(startReceiptRef!==null&&run.runtime===null){fail("monitorRun.startReceiptRef needs the Runtime binding that started it.")}if(stopReason===null===isTerminal(state)){fail("monitorRun.stopReason is set exactly when the run ends.")}const fitting=Object.hasOwn(MANAGED_EXTENSION_MONITOR_STOP_REASONS,state)?MANAGED_EXTENSION_MONITOR_STOP_REASONS[state]:[];if(stopReason!==null&&!fitting.includes(stopReason)){fail(`monitorRun.stopReason ${stopReason} does not fit the ${state} state.`)}if(state==="settled"&&(execution!=="settled"||startReceiptRef===null)){fail("monitorRun.run settles only with a watch that started and ended.")}if(stopReason==="max_events"&&observationSequence!==maxEvents){fail("monitorRun.stopReason max_events needs maxEvents observations.")}if(stopReason==="start_failed"&&(startReceiptRef!==null||execution===null)){fail("monitorRun.stopReason start_failed needs a watch that never started.")}if(stopReason==="watch_failed"&&startReceiptRef===null){fail("monitorRun.stopReason watch_failed needs a watch that started.")}if(stopReason==="quota_exceeded"!==isQuotaReason(run.reason)){fail("monitorRun.stopReason is quota_exceeded exactly for a quota reason.")}return Object.freeze(parsed)}__name(parseMonitorRun,"parseMonitorRun");function isMonitorRunStart(value){const monitor=attempt(()=>parseMonitorRun(value));return monitor!==void 0&&isExtensionRunStart(monitor.run)&&monitor.outputRef===null}__name(isMonitorRunStart,"isMonitorRunStart");function isMonitorRunSuccessor(previous,next){const before=attempt(()=>parseMonitorRun(previous));const after=attempt(()=>parseMonitorRun(next));if(!before||!after||MONITOR_FIXED_KEYS.some(key=>!sameJson(before[key],after[key]))||!isExtensionRunSuccessor(before.run,after.run)||after.observationSequence<before.observationSequence||after.observationSequence>before.observationSequence&&before.run.execution!=="running_attached"&&after.run.execution!=="running_attached"||after.notifiedThrough<before.notifiedThrough||after.observationSequence===before.observationSequence&&!sameJson(before.lastObservationRef,after.lastObservationRef)||before.outputRef!==null&&after.outputRef===null){return false}if(isTerminal(before.run.state)&&!sameJson({...before,notifiedThrough:0},{...after,notifiedThrough:0})){return false}const rebuilt=before.run.runtime!==null&&!sameJson(before.run.runtime,after.run.runtime);return rebuilt?before.startReceiptRef===null||!sameJson(before.startReceiptRef,after.startReceiptRef):setOnce(before.startReceiptRef,after.startReceiptRef)}__name(isMonitorRunSuccessor,"isMonitorRunSuccessor");import{isDeepStrictEqual}from"node:util";function parseManagedToolStage(value){if(!value||typeof value!=="object"||Array.isArray(value))invalid();const fields=value;if(Object.keys(fields).sort().join(",")!=="expansionId,inputRef,kind,permissionRef,resultRef,run,stepIndex,toolName,toolStageId"||fields["kind"]!=="tool_stage"||!Number.isSafeInteger(fields["stepIndex"])||Number(fields["stepIndex"])<0||!["read_file","shell"].includes(String(fields["toolName"])))invalid();const toolStageId=assertManagedSessionStableId(fields["toolStageId"],"toolStageId");const run=parseExtensionRun(fields["run"]);if(!run.definition||run.definition.definitionId!==fields["toolName"]||run.executionCallId!==toolStageId)invalid();return{kind:"tool_stage",toolStageId,expansionId:assertManagedSessionStableId(fields["expansionId"],"expansionId"),stepIndex:fields["stepIndex"],toolName:fields["toolName"],inputRef:assertManagedSessionDurableRef(fields["inputRef"],"inputRef"),permissionRef:fields["permissionRef"]===null?null:assertManagedSessionDurableRef(fields["permissionRef"],"permissionRef"),resultRef:fields["resultRef"]===null?null:assertManagedSessionDurableRef(fields["resultRef"],"resultRef"),run}}__name(parseManagedToolStage,"parseManagedToolStage");function isManagedToolStageStart(value){try{const record4=parseManagedToolStage(value);return record4.resultRef===null&&isExtensionRunStart(record4.run)}catch(cause){if(cause instanceof ManagedSessionRecordError)return false;throw cause}}__name(isManagedToolStageStart,"isManagedToolStageStart");function isManagedToolStageSuccessor(previous,next){try{const before=parseManagedToolStage(previous);const after=parseManagedToolStage(next);if(isTerminalRunState(before.run.state))return isDeepStrictEqual(before,after);for(const key of["kind","toolStageId","expansionId","stepIndex","toolName","inputRef"])if(!isDeepStrictEqual(before[key],after[key]))return false;for(const key of["permissionRef","resultRef"])if(before[key]&&!isDeepStrictEqual(before[key],after[key]))return false;return isExtensionRunSuccessor(before.run,after.run)}catch(cause){if(cause instanceof ManagedSessionRecordError)return false;throw cause}}__name(isManagedToolStageSuccessor,"isManagedToolStageSuccessor");function invalid(){throw new ManagedSessionRecordError("Invalid Managed command preprocessing stage.")}__name(invalid,"invalid");init_esbuild_shims();import{createHash as createHash5}from"node:crypto";init_esbuild_shims();var MANAGED_EXTENSION_MAX_PACKAGES=32;function parseManagedExtensionEffectiveBundle(value){const bundle=object2(value,"effective extension configuration");keys(bundle,["kind","formatVersion","configRevision","executionMode","mcpRevision","independentMcpSelections","baseMcpServers","baseHookCatalog","packages","mcpServers","hookCatalog"],["mcpChange"],"effective extension configuration");if(bundle["kind"]!=="managed-extension-config-bundle"||bundle["formatVersion"]!==1||!["linux-cgroup","developer-process-group"].includes(String(bundle["executionMode"]))||!revision(bundle["configRevision"],0)||!revision(bundle["mcpRevision"],0)||!Array.isArray(bundle["packages"])||bundle["packages"].length>MANAGED_EXTENSION_MAX_PACKAGES)invalid2("effective extension configuration");const packages=bundle["packages"].map(value2=>{const entry=object2(value2,"package view");keys(entry,["pin","assetRoot","contributionsRef"],[],"package view");const pin=parseManagedExtensionPin(entry["pin"]);if(entry["assetRoot"]!==`extension://${pin.extensionId}/`)invalid2("package asset root");const contributionsRef=assertManagedSessionDurableRef(entry["contributionsRef"],"package contributions");if(contributionsRef.kind!=="managed-extension-contributions"||contributionsRef.schemaVersion!==1)invalid2("package contributions");return{pin,assetRoot:entry["assetRoot"],contributionsRef}});if(new Set(packages.map(entry=>entry.pin.extensionId)).size!==packages.length)invalid2("duplicate package view");return{kind:"managed-extension-config-bundle",formatVersion:1,configRevision:bundle["configRevision"],executionMode:bundle["executionMode"],mcpRevision:bundle["mcpRevision"],independentMcpSelections:mcpSelections(bundle["independentMcpSelections"]),...bundle["mcpChange"]===void 0?{}:{mcpChange:mcpChange(bundle["mcpChange"])},baseMcpServers:mcpPins(bundle["baseMcpServers"]),baseHookCatalog:hookPin(bundle["baseHookCatalog"]),packages,mcpServers:mcpPins(bundle["mcpServers"]),hookCatalog:hookPin(bundle["hookCatalog"])}}__name(parseManagedExtensionEffectiveBundle,"parseManagedExtensionEffectiveBundle");function mcpPins(value){if(!Array.isArray(value)||value.length>32)invalid2("MCP selection");const pins=value.map(value2=>{const pin=object2(value2,"MCP pin");keys(pin,["serverId","serverRevision","definitionDigest"],[],"MCP pin");const identity=parseManagedExtensionPin({extensionId:pin["serverId"],packageRevision:pin["serverRevision"],packageDigest:pin["definitionDigest"]});return{serverId:identity.extensionId,serverRevision:identity.packageRevision,definitionDigest:identity.packageDigest}});if(new Set(pins.map(pin=>pin.serverId)).size!==pins.length)invalid2("duplicate MCP pin");return pins}__name(mcpPins,"mcpPins");function hookPin(value){if(value===null)return null;const pin=object2(value,"Hook catalog pin");keys(pin,["catalogId","catalogRevision","definitionDigest"],[],"Hook catalog pin");const identity=parseManagedExtensionPin({extensionId:pin["catalogId"],packageRevision:pin["catalogRevision"],packageDigest:pin["definitionDigest"]});return{catalogId:identity.extensionId,catalogRevision:identity.packageRevision,definitionDigest:identity.packageDigest}}__name(hookPin,"hookPin");function parseManagedExtensionPin(value){const pin=object2(value,"extension pin");keys(pin,["extensionId","packageRevision","packageDigest"],["settingsRevision"],"extension pin");if(typeof pin["extensionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/u.test(pin["extensionId"])||!revision(pin["packageRevision"],1)||typeof pin["packageDigest"]!=="string"||!/^[a-f0-9]{64}$/u.test(pin["packageDigest"])||pin["settingsRevision"]!==void 0&&!revision(pin["settingsRevision"],1))invalid2("extension pin");return Object.freeze({extensionId:pin["extensionId"],packageRevision:pin["packageRevision"],packageDigest:pin["packageDigest"],...pin["settingsRevision"]===void 0?{}:{settingsRevision:pin["settingsRevision"]}})}__name(parseManagedExtensionPin,"parseManagedExtensionPin");function parseManagedExtensionPins(value){if(!Array.isArray(value)||value.length>MANAGED_EXTENSION_MAX_PACKAGES)invalid2("extension selection");const pins=value.map(parseManagedExtensionPin);if(new Set(pins.map(pin=>pin.extensionId)).size!==pins.length)invalid2("duplicate extension selection");return Object.freeze(pins)}__name(parseManagedExtensionPins,"parseManagedExtensionPins");function parseManagedExtensionApplyCommand(value){const command=object2(value,"extension apply command");keys(command,["operationId","actorKey","expectedRevision","extensions"],["mcpChange"],"extension apply command");if(typeof command["operationId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(command["operationId"])||typeof command["actorKey"]!=="string"||!/^[a-f0-9]{64}$/u.test(command["actorKey"])||!revision(command["expectedRevision"],0)||command["expectedRevision"]===Number.MAX_SAFE_INTEGER)invalid2("extension apply command");return Object.freeze({operationId:command["operationId"],actorKey:command["actorKey"],expectedRevision:command["expectedRevision"],extensions:parseManagedExtensionPins(command["extensions"]),...command["mcpChange"]===void 0?{}:{mcpChange:mcpChange(command["mcpChange"])}})}__name(parseManagedExtensionApplyCommand,"parseManagedExtensionApplyCommand");function mcpSelections(value){if(!Array.isArray(value)||value.length>32)invalid2("MCP selection");const selected=value.map(value2=>{const candidate=object2(value2,"MCP selection");const{state,...pin}=candidate;if(!["enabled","disabled","removed"].includes(String(state)))invalid2("MCP state");return{...mcpPins([pin])[0],state}});if(new Set(selected.map(entry=>entry.serverId)).size!==selected.length||selected.filter(entry=>entry.state==="enabled").length>16)invalid2("MCP selection");return selected}__name(mcpSelections,"mcpSelections");function mcpChange(value){const change=object2(value,"MCP change");keys(change,["action","serverId","expectedRevision","servers"],[],"MCP change");if(!["add","edit","remove","enable","disable","reload","restart"].includes(String(change["action"]))||typeof change["serverId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/u.test(change["serverId"])||!revision(change["expectedRevision"],0))invalid2("MCP change");const servers=mcpSelections(change["servers"]);if(!servers.some(entry=>entry.serverId===change["serverId"]))invalid2("MCP change");return{action:change["action"],serverId:change["serverId"],expectedRevision:change["expectedRevision"],servers}}__name(mcpChange,"mcpChange");function object2(value,label){if(!value||typeof value!=="object"||Array.isArray(value))invalid2(label);return value}__name(object2,"object");function keys(value,required3,optional3,label){if(required3.some(key=>!Object.hasOwn(value,key))||Object.keys(value).some(key=>!required3.includes(key)&&!optional3.includes(key)))invalid2(label)}__name(keys,"keys");function revision(value,minimum){return Number.isSafeInteger(value)&&Number(value)>=minimum}__name(revision,"revision");function invalid2(label){throw new ManagedSessionRecordError(`Invalid Managed ${label}.`)}__name(invalid2,"invalid");var MANAGED_EXTENSION_CONFIG_KIND="hosted-extension-config";var MANAGED_CONFIG_INSTALL_PHASES=["preparing","prepared","committed","active","recovery_required","failed"];var CONTENT_KEYS=["kind","formatVersion","command","mode","phaseOperationId","configRevision","previousConfigRevision","phase","previousBundleRef","restoresBundleRef","bundleRef","rootSnapshotRef","stageAckRefs","enableAckRefs","error"];function isManagedExtensionConfig(value){return value!==null&&typeof value==="object"&&"kind"in value&&value.kind===MANAGED_EXTENSION_CONFIG_KIND}__name(isManagedExtensionConfig,"isManagedExtensionConfig");function parseManagedConfigInstallContent(value){return parse2(value,false)}__name(parseManagedConfigInstallContent,"parseManagedConfigInstallContent");function parseManagedConfigInstallRecord(value){return parse2(value,true)}__name(parseManagedConfigInstallRecord,"parseManagedConfigInstallRecord");function parse2(value,envelope2){const body=object3(value);const expected=envelope2?[...CONTENT_KEYS,"operationId","revision","previousRecordRef"]:CONTENT_KEYS;if(Object.keys(body).length!==expected.length||Object.keys(body).some(key=>!expected.includes(key))||body["kind"]!==MANAGED_EXTENSION_CONFIG_KIND||body["formatVersion"]!==1||!["apply","recoverPrevious"].includes(String(body["mode"]))||!revision2(body["configRevision"],1)||!revision2(body["previousConfigRevision"],0)||body["configRevision"]!==Number(body["previousConfigRevision"])+1||!MANAGED_CONFIG_INSTALL_PHASES.includes(body["phase"]))invalid3();const command=parseManagedExtensionApplyCommand(body["command"]);const phase=body["phase"];const compensating=body["mode"]==="recoverPrevious";if(body["phaseOperationId"]!==(compensating?managedExtensionCompensationOperationId(command.operationId):command.operationId))invalid3();if(Number(body["previousConfigRevision"])!==command.expectedRevision+(compensating?1:0))invalid3();const stageAckRefs=refs(body["stageAckRefs"]);const enableAckRefs=refs(body["enableAckRefs"]);if(["prepared","committed","active"].includes(phase)&&stageAckRefs.length<2||phase==="active"&&enableAckRefs.length<2||["preparing","prepared","failed"].includes(phase)&&enableAckRefs.length!==0)invalid3();const error3=body["error"]===null?null:object3(body["error"]);if(error3&&(Object.keys(error3).length!==1||typeof error3["code"]!=="string"||!/^[a-z][a-z0-9_]{0,127}$/u.test(error3["code"])))invalid3();if((phase==="failed"||phase==="recovery_required")!==(error3!==null))invalid3();const parsed={kind:MANAGED_EXTENSION_CONFIG_KIND,formatVersion:1,command,mode:body["mode"],phaseOperationId:body["phaseOperationId"],configRevision:body["configRevision"],previousConfigRevision:body["previousConfigRevision"],phase,previousBundleRef:body["previousBundleRef"]===null?null:ref2(body["previousBundleRef"]),restoresBundleRef:body["restoresBundleRef"]===null?null:ref2(body["restoresBundleRef"]),bundleRef:body["bundleRef"]===null?null:ref2(body["bundleRef"]),rootSnapshotRef:ref2(body["rootSnapshotRef"]),stageAckRefs,enableAckRefs,error:error3?{code:error3["code"]}:null};if(parsed.restoresBundleRef!==null!==compensating)invalid3();if(parsed.bundleRef===null&&!["preparing","failed"].includes(phase))invalid3();if(!envelope2)return parsed;if(body["operationId"]!==command.operationId||!revision2(body["revision"],1))invalid3();const previousRecordRef=body["previousRecordRef"]===null?null:ref2(body["previousRecordRef"]);if(body["revision"]===1!==(previousRecordRef===null)||previousRecordRef&&(previousRecordRef.kind!=="managed-config_install"||previousRecordRef.schemaVersion!==1))invalid3();return{...parsed,operationId:command.operationId,revision:body["revision"],previousRecordRef}}__name(parse2,"parse");function managedConfigBinding(content){if(!content.bundleRef)invalid3();return{revision:content.configRevision,previousRevision:content.previousConfigRevision||null,bundleRef:content.bundleRef,rootSnapshotRef:content.rootSnapshotRef}}__name(managedConfigBinding,"managedConfigBinding");function assertManagedConfigInstallSuccessor(previous,next){if(!previous){if(next.phase!=="preparing"||next.mode!=="apply"||next.previousConfigRevision!==0)invalid3();return}if(previous.command.operationId!==next.command.operationId){if(!["active","failed"].includes(previous.phase)||previous.phase==="failed"&&previous.mode==="recoverPrevious"||next.phase!=="preparing"||next.mode!=="apply"||next.previousConfigRevision!==(previous.phase==="failed"?previous.previousConfigRevision:previous.configRevision))invalid3();return}const transitions={preparing:["prepared","failed"],prepared:["committed","failed"],committed:["active","recovery_required"],active:[],recovery_required:["active","recovery_required"],failed:[]};const compensation=previous.phase==="recovery_required"&&previous.mode==="apply"&&next.mode==="recoverPrevious"&&next.phase==="preparing";if(!compensation&&!transitions[previous.phase].includes(next.phase)||JSON.stringify(previous.command)!==JSON.stringify(next.command)||!compensation&&(previous.mode!==next.mode||previous.phaseOperationId!==next.phaseOperationId||previous.configRevision!==next.configRevision||!(previous.phase==="preparing"&&previous.bundleRef===null)&&JSON.stringify(previous.bundleRef)!==JSON.stringify(next.bundleRef)||JSON.stringify(previous.rootSnapshotRef)!==JSON.stringify(next.rootSnapshotRef)||JSON.stringify(previous.previousBundleRef)!==JSON.stringify(next.previousBundleRef)||JSON.stringify(previous.restoresBundleRef)!==JSON.stringify(next.restoresBundleRef))||compensation&&(next.configRevision!==previous.configRevision+1||previous.previousBundleRef===null||JSON.stringify(next.previousBundleRef)!==JSON.stringify(previous.bundleRef)||JSON.stringify(next.restoresBundleRef)!==JSON.stringify(previous.previousBundleRef)))invalid3()}__name(assertManagedConfigInstallSuccessor,"assertManagedConfigInstallSuccessor");function managedExtensionCompensationOperationId(operationId){const bytes=createHash5("sha256").update(`managed-extension-recoverPrevious:${operationId.toLowerCase()}`).digest().subarray(0,16);bytes[6]=bytes[6]&15|80;bytes[8]=bytes[8]&63|128;const hex=bytes.toString("hex");return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}__name(managedExtensionCompensationOperationId,"managedExtensionCompensationOperationId");function object3(value){if(!value||typeof value!=="object"||Array.isArray(value))invalid3();return value}__name(object3,"object");function ref2(value){return assertManagedSessionDurableRef(value,"extension config reference")}__name(ref2,"ref");function refs(value){if(!Array.isArray(value)||value.length>8)invalid3();const parsed=value.map(ref2);if(new Set(parsed.map(entry=>entry.resourceId)).size!==parsed.length)invalid3();return parsed}__name(refs,"refs");function revision2(value,minimum){return Number.isSafeInteger(value)&&Number(value)>=minimum}__name(revision2,"revision");function invalid3(){throw new ManagedSessionRecordError("Invalid Managed configuration install.")}__name(invalid3,"invalid");init_esbuild_shims();import{createHash as createHash6}from"node:crypto";var MAX_JSON_BYTES=256*1024;var MAX_JSON_DEPTH=64;var SESSION_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;var DIGEST_PATTERN=/^[a-f0-9]{64}$/;var IDENTITY_KEYS=["sessionId","promptId","callId","capabilityDigest","policyRevision"];var ManagedToolProtocolError=class extends Error{static{__name(this,"ManagedToolProtocolError")}code="managed_tool_invalid_request";constructor(message="Managed Tool invocation data is invalid."){super(message);this.name="ManagedToolProtocolError"}};function canonicalJson(value,maxBytes=MAX_JSON_BYTES){if(!Number.isSafeInteger(maxBytes)||maxBytes<=0){throw new ManagedToolProtocolError("Invalid Managed Tool JSON size limit.")}const ancestors=new Set;const chunks=[];let bytes=0;const append=__name(chunk=>{bytes+=Buffer.byteLength(chunk,"utf8");if(bytes>maxBytes){throw new ManagedToolProtocolError("Managed Tool JSON exceeds size limit.")}chunks.push(chunk)},"append");const appendString=__name(text3=>{if(Buffer.byteLength(text3,"utf8")>maxBytes-bytes){throw new ManagedToolProtocolError("Managed Tool JSON exceeds size limit.")}append(JSON.stringify(text3))},"appendString");const visit3=__name((input,depth)=>{if(depth>MAX_JSON_DEPTH){throw new ManagedToolProtocolError("Managed Tool JSON exceeds depth limit.")}if(input===null){append("null")}else if(typeof input==="string"){appendString(input)}else if(typeof input==="boolean"){append(input?"true":"false")}else if(typeof input==="number"&&Number.isFinite(input)){append(JSON.stringify(input))}else if(typeof input==="object"){if(ancestors.has(input)||!Array.isArray(input)&&Object.getPrototypeOf(input)!==Object.prototype&&Object.getPrototypeOf(input)!==null){throw new ManagedToolProtocolError}ancestors.add(input);const descriptors=Object.getOwnPropertyDescriptors(input);const keys2=Reflect.ownKeys(descriptors);if(keys2.some(key=>{if(typeof key!=="string")return true;if(Array.isArray(input)&&key==="length")return false;const descriptor2=descriptors[key];return!descriptor2.enumerable||!("value"in descriptor2)})){throw new ManagedToolProtocolError}if(Array.isArray(input)){if(keys2.length!==input.length+1||keys2.some(key=>key!=="length"&&(typeof key!=="string"||!/^(0|[1-9][0-9]*)$/.test(key)||Number(key)>=input.length))){throw new ManagedToolProtocolError}append("[");for(let index=0;index<input.length;index++){if(index>0)append(",");visit3(descriptors[String(index)].value,depth+1)}append("]")}else{append("{");Object.keys(descriptors).sort().forEach((key,index)=>{if(index>0)append(",");appendString(key);append(":");visit3(descriptors[key].value,depth+1)});append("}")}ancestors.delete(input)}else{throw new ManagedToolProtocolError}},"visit");visit3(value,0);return chunks.join("")}__name(canonicalJson,"canonicalJson");function managedToolDigest(value,maxBytes=MAX_JSON_BYTES){return createHash6("sha256").update(canonicalJson(value,maxBytes)).digest("hex")}__name(managedToolDigest,"managedToolDigest");function managedToolResponseParts(parts){return parts.map(part=>{const{type,...rest}=part;return type==="text"?rest:part})}__name(managedToolResponseParts,"managedToolResponseParts");function managedToolFailureMessage(payload){if(payload.executionStatus==="not_started"){return`The tool call did not run: ${payload.error?.message??"the Runtime worker did not run it."}`}return payload.error?.message??(payload.executionStatus==="cancelled"?"The tool call was cancelled.":"The tool call failed.")}__name(managedToolFailureMessage,"managedToolFailureMessage");function record(value){if(value===null||typeof value!=="object"||Array.isArray(value)){throw new ManagedToolProtocolError}return value}__name(record,"record");function jsonRecord(value){return record(JSON.parse(canonicalJson(value)))}__name(jsonRecord,"jsonRecord");function assertKeys(input,keys2){if(Object.keys(input).some(key=>!keys2.includes(key))){throw new ManagedToolProtocolError}}__name(assertKeys,"assertKeys");function boundedId(value,maxLength){if(typeof value!=="string"||value.length===0||value.length>maxLength||value.includes("\0")){throw new ManagedToolProtocolError}return value}__name(boundedId,"boundedId");function digest(value){if(typeof value!=="string"||!DIGEST_PATTERN.test(value)){throw new ManagedToolProtocolError}return value}__name(digest,"digest");function identityFields(input){const sessionId=boundedId(input["sessionId"],256);if(!SESSION_ID_PATTERN.test(sessionId))throw new ManagedToolProtocolError;return{sessionId:sessionId.toLowerCase(),promptId:boundedId(input["promptId"],128),callId:boundedId(input["callId"],512),capabilityDigest:digest(input["capabilityDigest"]),policyRevision:boundedId(input["policyRevision"],256)}}__name(identityFields,"identityFields");function parseManagedToolCallIdentity(value){const input=jsonRecord(value);assertKeys(input,IDENTITY_KEYS);return identityFields(input)}__name(parseManagedToolCallIdentity,"parseManagedToolCallIdentity");function parseManagedToolInvocationReference(value){const input=jsonRecord(value);assertKeys(input,[...IDENTITY_KEYS,"invocationId","argsDigest"]);return{...identityFields(input),invocationId:boundedId(input["invocationId"],128),argsDigest:digest(input["argsDigest"])}}__name(parseManagedToolInvocationReference,"parseManagedToolInvocationReference");function parseManagedToolContentModification(value){const input=jsonRecord(value);assertKeys(input,["source","newContent"]);if(typeof input["newContent"]!=="string")throw new ManagedToolProtocolError;return{source:parseManagedToolInvocationReference(input["source"]),newContent:input["newContent"]}}__name(parseManagedToolContentModification,"parseManagedToolContentModification");function parseManagedToolMediaContext(value){const input=jsonRecord(value);assertKeys(input,["inputModalities"]);const modalities=record(input["inputModalities"]);assertKeys(modalities,["image","pdf","audio","video"]);if(Object.values(modalities).some(enabled=>typeof enabled!=="boolean")){throw new ManagedToolProtocolError}return{inputModalities:modalities}}__name(parseManagedToolMediaContext,"parseManagedToolMediaContext");function serializeManagedToolConfirmation(details){if(details.type==="plan"||details.type==="ask_user_question"){throw new ManagedToolProtocolError("Confirmation belongs to the Gateway.")}const base2={title:details.title,...details.hideAlwaysAllow!==void 0?{hideAlwaysAllow:details.hideAlwaysAllow}:{},...details.autoModeFallback!==void 0?{autoModeFallback:{reason:details.autoModeFallback.reason,message:details.autoModeFallback.message}}:{}};let result;switch(details.type){case"edit":result={...base2,type:"edit",fileName:details.fileName,filePath:details.filePath,fileDiff:details.fileDiff,originalContent:details.originalContent,newContent:details.newContent,...details.isModifying!==void 0?{isModifying:details.isModifying}:{},...details.hideModify!==void 0?{hideModify:details.hideModify}:{},...details.skipIdeDiff!==void 0?{skipIdeDiff:details.skipIdeDiff}:{},...details.warnings!==void 0?{warnings:details.warnings}:{}};break;case"exec":result={...base2,type:"exec",command:details.command,rootCommand:details.rootCommand,...details.permissionRules!==void 0?{permissionRules:details.permissionRules}:{},...details.warnings!==void 0?{warnings:details.warnings}:{}};break;case"mcp":result={...base2,type:"mcp",serverName:details.serverName,toolName:details.toolName,toolDisplayName:details.toolDisplayName,...details.permissionRules!==void 0?{permissionRules:details.permissionRules}:{}};break;case"info":result={...base2,type:"info",prompt:details.prompt,...details.renderPromptAsPlainText!==void 0?{renderPromptAsPlainText:details.renderPromptAsPlainText}:{},...details.urls!==void 0?{urls:details.urls}:{},...details.permissionRules!==void 0?{permissionRules:details.permissionRules}:{}};break;default:throw new ManagedToolProtocolError("Confirmation belongs to the Gateway.")}return JSON.parse(canonicalJson(result,8*1024*1024-64*1024))}__name(serializeManagedToolConfirmation,"serializeManagedToolConfirmation");function parseManagedToolConfirmationPayload(value){if(value===void 0)return void 0;const input=jsonRecord(value);assertKeys(input,["newContent","cancelMessage","permissionRules","answers","updatedInput"]);const result={};for(const key of["newContent","cancelMessage"]){if(input[key]!==void 0){if(typeof input[key]!=="string")throw new ManagedToolProtocolError;result[key]=input[key]}}const rules=input["permissionRules"];if(rules!==void 0){if(!Array.isArray(rules)||rules.some(rule=>typeof rule!=="string")){throw new ManagedToolProtocolError}result.permissionRules=rules}if(input["answers"]!==void 0){const answers=record(input["answers"]);if(Object.values(answers).some(answer=>typeof answer!=="string")){throw new ManagedToolProtocolError}result.answers=answers}if(input["updatedInput"]!==void 0){result.updatedInput=record(input["updatedInput"])}return result}__name(parseManagedToolConfirmationPayload,"parseManagedToolConfirmationPayload");init_esbuild_shims();import{readFile as readFile6,rename as rename4,unlink as unlink7,writeFile}from"node:fs/promises";init_esbuild_shims();import{randomUUID as randomUUID4}from"node:crypto";init_esbuild_shims();import{execFile as execFile3}from"node:child_process";import*as nodeConstants from"node:constants";import{createHash as createHash7,randomUUID as randomUUID2}from"node:crypto";import*as nodeFs from"node:fs";import*as fs9 from"node:fs/promises";import*as os from"node:os";import*as path11 from"node:path";var LEGACY_LOCK_SCHEMA_VERSION=1;var LOCK_SCHEMA_VERSION=2;var MANAGED_LOCK_SCHEMA_VERSION=3;var MALFORMED_RETRY_COUNT=3;var MALFORMED_RETRY_DELAY_MS=50;var CLAIMED_PRIMARY_WAIT_ATTEMPTS=20;var RELEASE_PRECHECK_ATTEMPTS=3;var RELEASE_PRECHECK_RETRY_DELAY_MS=50;var ACQUIRE_ATTEMPTS=8;var TRANSCRIPT_SNAPSHOT_ATTEMPTS=3;var TRANSCRIPT_HASH_BUFFER_BYTES=1024*1024;var TRANSCRIPT_NO_FOLLOW_FLAG=nodeConstants.O_NOFOLLOW??0;var TRANSCRIPT_NONBLOCK_FLAG=nodeConstants.O_NONBLOCK??0;var TRANSCRIPT_READ_FLAGS=nodeConstants.O_RDONLY|TRANSCRIPT_NO_FOLLOW_FLAG|TRANSCRIPT_NONBLOCK_FLAG;var TRANSCRIPT_APPEND_FLAGS=nodeConstants.O_APPEND|nodeConstants.O_RDWR|TRANSCRIPT_NO_FOLLOW_FLAG|TRANSCRIPT_NONBLOCK_FLAG;async function openDurableLockDirectory(directory){let handle;try{handle=await fs9.open(directory,nodeConstants.O_RDONLY|(process.platform==="win32"?0:nodeConstants.O_NOFOLLOW??0));const opened=await handle.stat();const current2=await fs9.stat(directory);const openedInodeVerifiable=hasVerifiableInode(opened.ino);const currentInodeVerifiable=hasVerifiableInode(current2.ino);if(!opened.isDirectory()||!current2.isDirectory()||opened.dev!==current2.dev||openedInodeVerifiable!==currentInodeVerifiable||openedInodeVerifiable&&opened.ino!==current2.ino){throw new Error("Session writer lock directory changed.")}return{path:directory,handle,dev:opened.dev,ino:opened.ino,inodeVerifiable:openedInodeVerifiable}}catch(error3){await handle?.close().catch(()=>void 0);if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}__name(openDurableLockDirectory,"openDurableLockDirectory");async function syncDurableLockDirectory(directory){try{const opened=await directory.handle.stat();const openedInodeVerifiable=hasVerifiableInode(opened.ino);if(!opened.isDirectory()||opened.dev!==directory.dev||openedInodeVerifiable!==directory.inodeVerifiable||directory.inodeVerifiable&&opened.ino!==directory.ino){throw new Error("Session writer lock directory changed.")}try{await directory.handle.sync()}catch(error3){if(process.platform!=="win32"||!["EACCES","EINVAL","EPERM"].includes(error3.code??"")){throw error3}}const current2=await fs9.stat(directory.path);const currentInodeVerifiable=hasVerifiableInode(current2.ino);if(!current2.isDirectory()||current2.dev!==directory.dev||currentInodeVerifiable!==directory.inodeVerifiable||directory.inodeVerifiable&&current2.ino!==directory.ino){throw new Error("Session writer lock directory changed.")}}catch(error3){if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}__name(syncDurableLockDirectory,"syncDurableLockDirectory");var debugLogger15=createDebugLogger("SESSION_WRITER_LEASE");function describeError(error3){if(!(error3 instanceof Error))return String(error3);const code=error3.code;return`${error3.name}: ${error3.message}${code?` code=${code}`:""}`}__name(describeError,"describeError");function describeDiagnosticError(error3){const description=describeError(error3);return error3 instanceof Error&&error3.cause!==void 0?`${description} cause=${describeError(error3.cause)}`:description}__name(describeDiagnosticError,"describeDiagnosticError");var SessionWriterError=class extends Error{static{__name(this,"SessionWriterError")}};var SESSION_WRITER_RPC_CODES={session_writer_conflict:-32020,session_writer_lost:-32021,session_transcript_changed:-32022,session_writer_unavailable:-32023};var SessionWriterConflictError=class extends SessionWriterError{static{__name(this,"SessionWriterConflictError")}name="SessionWriterConflictError";rpcCode=SESSION_WRITER_RPC_CODES.session_writer_conflict;errorKind="session_writer_conflict";httpStatus=409;constructor(){super("This session is already open in another Qwen process.")}};var SessionWriterLostError=class extends SessionWriterError{static{__name(this,"SessionWriterLostError")}name="SessionWriterLostError";rpcCode=SESSION_WRITER_RPC_CODES.session_writer_lost;errorKind="session_writer_lost";httpStatus=409;constructor(){super("Write ownership for this session was lost.")}};var SessionTranscriptChangedError=class extends SessionWriterError{static{__name(this,"SessionTranscriptChangedError")}name="SessionTranscriptChangedError";rpcCode=SESSION_WRITER_RPC_CODES.session_transcript_changed;errorKind="session_transcript_changed";httpStatus=409;constructor(){super("The session transcript changed outside its active writer.")}};var SessionWriterUnavailableError=class extends SessionWriterError{static{__name(this,"SessionWriterUnavailableError")}name="SessionWriterUnavailableError";rpcCode=SESSION_WRITER_RPC_CODES.session_writer_unavailable;errorKind="session_writer_unavailable";httpStatus=503;constructor(options2){super(options2?.message??"Session write ownership could not be verified.",options2)}};var SessionTranscriptIdentityUnavailableError=class extends SessionWriterUnavailableError{static{__name(this,"SessionTranscriptIdentityUnavailableError")}name="SessionTranscriptIdentityUnavailableError";constructor(cause){super({message:"Session transcript identity could not be verified on this filesystem.",cause:cause??new Error("The session transcript filesystem does not provide a verifiable inode identity (ino=0).")})}};function isProcessAlive(pid){try{process.kill(pid,0);return true}catch(error3){return error3.code!=="ESRCH"}}__name(isProcessAlive,"isProcessAlive");async function execFileText(file,args,env){return new Promise(resolve36=>{try{execFile3(file,args,{encoding:"utf8",timeout:1e3,windowsHide:true,...env?{env}:{}},(error3,stdout)=>{const value=stdout.trim();resolve36(error3||value.length===0?null:value)})}catch{resolve36(null)}})}__name(execFileText,"execFileText");async function readProcessStartIdentity(pid){if(process.platform==="linux"){try{const[stat15,bootId]=await Promise.all([fs9.readFile(`/proc/${pid}/stat`,"utf8"),fs9.readFile("/proc/sys/kernel/random/boot_id","utf8")]);const fields=stat15.slice(stat15.lastIndexOf(")")+1).trim().split(/\s+/);const startTicks=fields[19];if(!startTicks||!/^\d+$/.test(startTicks)||!/^[0-9a-f-]+$/i.test(bootId.trim())){return null}return`linux:${bootId.trim()}:${startTicks}`}catch{return null}}if(process.platform==="darwin"){const startedAt=await execFileText("/bin/ps",["-o","lstart=","-p",String(pid)],{...process.env,LC_ALL:"C",LANG:"C",TZ:"UTC"});return startedAt?`darwin:${startedAt}`:null}if(process.platform==="win32"){const startedAt=await execFileText("powershell.exe",["-NoProfile","-NonInteractive","-Command",`$targetProcess = Get-Process -Id ${pid} -ErrorAction Stop; $targetProcess.StartTime.ToUniversalTime().Ticks`]);return startedAt&&/^\d+$/.test(startedAt)?`win32:${startedAt}`:null}return null}__name(readProcessStartIdentity,"readProcessStartIdentity");function hasValidOwnerFields(record4){const processKind=record4["process_kind"];return typeof record4["session_id"]==="string"&&record4["session_id"].length>0&&typeof record4["owner_id"]==="string"&&record4["owner_id"].length>0&&Number.isInteger(record4["pid"])&&record4["pid"]>0&&(record4["process_start_identity"]===void 0||typeof record4["process_start_identity"]==="string"&&record4["process_start_identity"].length>0)&&(record4["pid_namespace_id"]===void 0||Number.isSafeInteger(record4["pid_namespace_id"])&&record4["pid_namespace_id"]>0)&&typeof record4["hostname"]==="string"&&record4["hostname"].length>0&&typeof processKind==="string"&&["interactive","acp","daemon","unknown"].includes(processKind)&&typeof record4["acquired_at"]==="string"&&Number.isFinite(Date.parse(record4["acquired_at"]))&&(record4["qwen_version"]===null||typeof record4["qwen_version"]==="string")}__name(hasValidOwnerFields,"hasValidOwnerFields");function isSealedTranscriptProof(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const proof=value;return typeof proof["relative_path"]==="string"&&proof["relative_path"].length>0&&typeof proof["exists"]==="boolean"&&Number.isSafeInteger(proof["byte_length"])&&proof["byte_length"]>=0&&typeof proof["sha256"]==="string"&&/^[0-9a-f]{64}$/.test(proof["sha256"])&&(proof["exists"]||proof["byte_length"]===0)}__name(isSealedTranscriptProof,"isSealedTranscriptProof");function isLockRecord(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const record4=value;if(!hasValidOwnerFields(record4))return false;if(record4["schema_version"]===LEGACY_LOCK_SCHEMA_VERSION){return record4["state"]===void 0}if(record4["schema_version"]===LOCK_SCHEMA_VERSION){if(record4["state"]==="active")return true;return record4["state"]==="sealed"&&typeof record4["sealed_at"]==="string"&&Number.isFinite(Date.parse(record4["sealed_at"]))&&isSealedTranscriptProof(record4["transcript"])}if(record4["schema_version"]===MANAGED_LOCK_SCHEMA_VERSION){if(!isManagedFormatVersion(record4["format_version"]))return false;if(record4["state"]==="active")return true;return record4["state"]==="sealed"&&typeof record4["sealed_at"]==="string"&&Number.isFinite(Date.parse(record4["sealed_at"]))&&isSealedTranscriptProof(record4["transcript"])&&isValidCommitProof(record4)}return false}__name(isLockRecord,"isLockRecord");function parseLockRecord(raw){try{const parsed=JSON.parse(raw);return isLockRecord(parsed)?parsed:null}catch{return null}}__name(parseLockRecord,"parseLockRecord");function isActiveLockRecord(record4){return record4.schema_version===LEGACY_LOCK_SCHEMA_VERSION||record4.state==="active"}__name(isActiveLockRecord,"isActiveLockRecord");function isManagedFormatVersion(value){return Number.isSafeInteger(value)&&value>=1}__name(isManagedFormatVersion,"isManagedFormatVersion");function isManagedLockRecord(record4){return record4.schema_version===MANAGED_LOCK_SCHEMA_VERSION}__name(isManagedLockRecord,"isManagedLockRecord");function isValidCommitProof(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const proof=value;return Number.isSafeInteger(proof["last_commit_sequence"])&&proof["last_commit_sequence"]>=0&&typeof proof["committed_prefix_hash"]==="string"&&/^[0-9a-f]{64}$/.test(proof["committed_prefix_hash"])}__name(isValidCommitProof,"isValidCommitProof");function parseLinuxProcessStartBootId(identity){if(!identity)return null;const match=/^linux:([0-9a-f-]+):\d+$/i.exec(identity);return match?.[1]?.toLowerCase()??null}__name(parseLinuxProcessStartBootId,"parseLinuxProcessStartBootId");async function lockStateForRecord(record4,raw){if(record4.hostname!==os.hostname())return{kind:"live",record:record4,raw};if(process.platform==="linux"){const localBootId=readLocalBootId()?.toLowerCase()??null;const localNamespaceId=readPidNamespaceId();if(localBootId===null||localNamespaceId===null||parseLinuxProcessStartBootId(record4.process_start_identity)!==localBootId||record4.pid_namespace_id===void 0||record4.pid_namespace_id!==localNamespaceId){return{kind:"live",record:record4,raw}}}if(!isProcessAlive(record4.pid))return{kind:"stale",record:record4,raw};if(!record4.process_start_identity)return{kind:"live",record:record4,raw};const currentStartIdentity=await readProcessStartIdentity(record4.pid);return currentStartIdentity!==null&&currentStartIdentity!==record4.process_start_identity?{kind:"stale",record:record4,raw}:{kind:"live",record:record4,raw}}__name(lockStateForRecord,"lockStateForRecord");async function delay2(ms2){await new Promise(resolve36=>setTimeout(resolve36,ms2))}__name(delay2,"delay");function transcriptFingerprint(stat15){return{dev:stat15.dev,ino:stat15.ino,mode:stat15.mode,uid:stat15.uid,gid:stat15.gid,nlink:stat15.nlink,birthtimeMs:stat15.birthtimeMs,ctimeMs:stat15.ctimeMs,mtimeMs:stat15.mtimeMs}}__name(transcriptFingerprint,"transcriptFingerprint");function assertVerifiableTranscriptIdentity(fingerprint2){if(!hasVerifiableInode(fingerprint2.ino)){throw new SessionTranscriptIdentityUnavailableError}}__name(assertVerifiableTranscriptIdentity,"assertVerifiableTranscriptIdentity");async function assertTranscriptFilesystemProvidesIdentity(transcriptPath){let dir=path11.dirname(transcriptPath);for(;;){try{const stat15=await fs9.stat(dir);assertVerifiableTranscriptIdentity({ino:stat15.ino});return}catch(error3){if(error3 instanceof SessionWriterError)throw error3;const code=error3.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return;const parent=path11.dirname(dir);if(parent===dir)return;dir=parent}}}__name(assertTranscriptFilesystemProvidesIdentity,"assertTranscriptFilesystemProvidesIdentity");function sameFileIdentity(left,right){return left.ino!==0&&right.ino!==0&&left.dev===right.dev&&left.ino===right.ino}__name(sameFileIdentity,"sameFileIdentity");function sameFileSecurityMetadata(left,right){return left.mode===right.mode&&left.uid===right.uid&&left.gid===right.gid&&left.nlink===right.nlink}__name(sameFileSecurityMetadata,"sameFileSecurityMetadata");function sameHardTranscriptState(left,right){if(left.exists!==right.exists)return false;if(!left.exists||!right.exists)return true;return left.byteLength===right.byteLength&&sameFileIdentity(left.fingerprint,right.fingerprint)&&sameFileSecurityMetadata(left.fingerprint,right.fingerprint)}__name(sameHardTranscriptState,"sameHardTranscriptState");function sameTranscriptState(left,right){if(left.exists!==right.exists)return false;if(!left.exists||!right.exists)return true;return sameHardTranscriptState(left,right)&&left.fingerprint.birthtimeMs===right.fingerprint.birthtimeMs&&left.fingerprint.ctimeMs===right.fingerprint.ctimeMs&&left.fingerprint.mtimeMs===right.fingerprint.mtimeMs}__name(sameTranscriptState,"sameTranscriptState");function transcriptStateFromStat(stat15){const fingerprint2=transcriptFingerprint(stat15);assertVerifiableTranscriptIdentity(fingerprint2);return{exists:true,byteLength:stat15.size,fingerprint:fingerprint2}}__name(transcriptStateFromStat,"transcriptStateFromStat");function transcriptStateChangedFields(left,right){if(left.exists!==right.exists)return["exists"];if(!left.exists||!right.exists)return[];const fields=[];if(left.byteLength!==right.byteLength)fields.push("byteLength");const fingerprintFields=["dev","ino","mode","uid","gid","nlink","birthtimeMs","ctimeMs","mtimeMs"];for(const field of fingerprintFields){if(left.fingerprint[field]!==right.fingerprint[field]){fields.push(field)}}return fields}__name(transcriptStateChangedFields,"transcriptStateChangedFields");function transcriptHashesEqual(left,right){return left.copy().digest().equals(right.copy().digest())}__name(transcriptHashesEqual,"transcriptHashesEqual");async function assertTranscriptPathMissing(filePath){try{await fs9.lstat(filePath)}catch(error3){if(error3.code==="ENOENT")return;throw error3}throw new SessionWriterUnavailableError({cause:new Error("Session transcript path is not a regular file")})}__name(assertTranscriptPathMissing,"assertTranscriptPathMissing");async function getOpenTranscriptState(filePath,handle,invalidPathIsChange){let handleStat;try{handleStat=await handle.stat()}catch(error3){if(invalidPathIsChange&&error3.code==="ENOENT"){throw new SessionTranscriptChangedError}throw error3}if(!handleStat.isFile()){if(invalidPathIsChange)throw new SessionTranscriptChangedError;throw new SessionWriterUnavailableError}if(handleStat.size>0){const lastByte=Buffer.allocUnsafe(1);const{bytesRead}=await handle.read(lastByte,0,1,handleStat.size-1);if(bytesRead!==1||lastByte[0]!==10){throw new SessionTranscriptChangedError}}let pathStat;try{pathStat=await fs9.lstat(filePath)}catch(error3){if(invalidPathIsChange&&error3.code==="ENOENT"){throw new SessionTranscriptChangedError}throw error3}if(!pathStat.isFile()||pathStat.isSymbolicLink()){if(invalidPathIsChange)throw new SessionTranscriptChangedError;throw new SessionWriterUnavailableError}const handleState=transcriptStateFromStat(handleStat);const pathState=transcriptStateFromStat(pathStat);if(!sameHardTranscriptState(handleState,pathState)){throw new SessionTranscriptChangedError}return pathState}__name(getOpenTranscriptState,"getOpenTranscriptState");async function inspectTranscriptPath(filePath,invalidPathIsChange){let stat15;try{stat15=await fs9.lstat(filePath)}catch(error3){if(error3.code==="ENOENT"){return{exists:false,byteLength:0}}throw error3}if(!stat15.isFile()||stat15.isSymbolicLink()){if(invalidPathIsChange)throw new SessionTranscriptChangedError;throw new SessionWriterUnavailableError}return transcriptStateFromStat(stat15)}__name(inspectTranscriptPath,"inspectTranscriptPath");async function openTranscriptForRead(filePath,expectedState){const pathState=await inspectTranscriptPath(filePath,expectedState!==void 0);if(expectedState&&!sameHardTranscriptState(pathState,expectedState)){throw new SessionTranscriptChangedError}if(!pathState.exists)return void 0;try{return await fs9.open(filePath,TRANSCRIPT_READ_FLAGS)}catch(error3){if(expectedState!==void 0){const code=error3.code;if(code==="ENOENT"||code==="ELOOP"){throw new SessionTranscriptChangedError}const currentState=await inspectTranscriptPath(filePath,true);if(!sameHardTranscriptState(currentState,expectedState)){throw new SessionTranscriptChangedError}}throw error3}}__name(openTranscriptForRead,"openTranscriptForRead");async function openTranscriptForAppend(filePath,expectedState){const pathState=await inspectTranscriptPath(filePath,true);if(!sameHardTranscriptState(pathState,expectedState)){throw new SessionTranscriptChangedError}try{const flags=expectedState.exists?TRANSCRIPT_APPEND_FLAGS:TRANSCRIPT_APPEND_FLAGS|nodeConstants.O_CREAT|nodeConstants.O_EXCL;return await fs9.open(filePath,flags,384)}catch(error3){const code=error3.code;if(code==="EEXIST"||code==="ENOENT"||code==="ELOOP"){throw new SessionTranscriptChangedError}const currentState=await inspectTranscriptPath(filePath,true);if(!sameHardTranscriptState(currentState,expectedState)){throw new SessionTranscriptChangedError}throw error3}}__name(openTranscriptForAppend,"openTranscriptForAppend");async function getTranscriptState(filePath,expectedState){let handle;try{handle=await openTranscriptForRead(filePath,expectedState);if(!handle)return{exists:false,byteLength:0};return await getOpenTranscriptState(filePath,handle,expectedState!==void 0)}catch(error3){if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{await handle?.close().catch(()=>{})}}__name(getTranscriptState,"getTranscriptState");async function captureOpenTranscriptSnapshot(filePath,handle,expectedState,shouldAbort){let buffer;for(let attempt2=1;attempt2<=TRANSCRIPT_SNAPSHOT_ATTEMPTS;attempt2++){if(shouldAbort())throw new SessionWriterLostError;const beforeState=await getOpenTranscriptState(filePath,handle,expectedState!==void 0);if(expectedState&&!sameHardTranscriptState(beforeState,expectedState)){throw new SessionTranscriptChangedError}const bufferBytes=Math.min(TRANSCRIPT_HASH_BUFFER_BYTES,beforeState.byteLength);if(!buffer||buffer.byteLength<bufferBytes){buffer=Buffer.allocUnsafe(bufferBytes)}const hasher=createHash7("sha256");let position=0;while(position<beforeState.byteLength){if(shouldAbort())throw new SessionWriterLostError;const length=Math.min(buffer.byteLength,beforeState.byteLength-position);if(length===0)throw new SessionWriterUnavailableError;let chunkBytesRead=0;while(chunkBytesRead<length){if(shouldAbort())throw new SessionWriterLostError;const{bytesRead}=await handle.read(buffer,chunkBytesRead,length-chunkBytesRead,position+chunkBytesRead);if(bytesRead===0)throw new SessionTranscriptChangedError;chunkBytesRead+=bytesRead}hasher.update(buffer.subarray(0,chunkBytesRead));position+=chunkBytesRead}if(shouldAbort())throw new SessionWriterLostError;const afterState=await getOpenTranscriptState(filePath,handle,expectedState!==void 0);if(!sameHardTranscriptState(beforeState,afterState)){throw new SessionTranscriptChangedError}if(sameTranscriptState(beforeState,afterState)){return{state:afterState,hasher,attempts:attempt2}}debugLogger15.debug(`Session transcript snapshot retry attempt=${attempt2} changedFields=${transcriptStateChangedFields(beforeState,afterState).join(",")}`)}throw new SessionWriterUnavailableError({cause:new Error("Session transcript metadata did not stabilize")})}__name(captureOpenTranscriptSnapshot,"captureOpenTranscriptSnapshot");async function captureTranscriptSnapshot(filePath,expectedState,shouldAbort){let handle;try{handle=await openTranscriptForRead(filePath,expectedState);if(!handle){const missingState={exists:false,byteLength:0};if(expectedState&&!sameHardTranscriptState(missingState,expectedState)){throw new SessionTranscriptChangedError}return{state:missingState,hasher:createHash7("sha256"),attempts:1}}return await captureOpenTranscriptSnapshot(filePath,handle,expectedState,shouldAbort)}catch(error3){if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{await handle?.close().catch(()=>{})}}__name(captureTranscriptSnapshot,"captureTranscriptSnapshot");function getTranscriptRelativePath(runtimeBaseDir,transcriptPath){const relativePath=path11.relative(runtimeBaseDir,transcriptPath);if(relativePath.length===0||path11.isAbsolute(relativePath)||relativePath===".."||relativePath.startsWith(`..${path11.sep}`)){throw new SessionWriterUnavailableError({cause:new Error("Session transcript is outside the runtime base")})}return relativePath.split(path11.sep).join("/")}__name(getTranscriptRelativePath,"getTranscriptRelativePath");async function openTranscriptProof(filePath){let handle;try{try{handle=await fs9.open(filePath,"r")}catch(error3){if(error3.code==="ENOENT"){await assertTranscriptPathMissing(filePath);return{state:{exists:false,byteLength:0},sha256:createHash7("sha256").digest("hex")}}throw error3}const[beforeStat,pathStat]=await Promise.all([handle.stat(),fs9.lstat(filePath)]);if(!beforeStat.isFile()||!pathStat.isFile()||pathStat.isSymbolicLink()){throw new SessionWriterUnavailableError}const beforeState=transcriptStateFromStat(beforeStat);const beforePathFingerprint=transcriptFingerprint(pathStat);assertVerifiableTranscriptIdentity(beforePathFingerprint);if(!sameFileIdentity(beforeState.fingerprint,beforePathFingerprint)){throw new SessionTranscriptChangedError}if(beforeStat.size>0){const lastByte=Buffer.allocUnsafe(1);const{bytesRead}=await handle.read(lastByte,0,1,beforeStat.size-1);if(bytesRead!==1||lastByte[0]!==10){throw new SessionTranscriptChangedError}}const hash2=createHash7("sha256");const buffer=Buffer.allocUnsafe(64*1024);let position=0;while(position<beforeStat.size){const{bytesRead}=await handle.read(buffer,0,Math.min(buffer.byteLength,beforeStat.size-position),position);if(bytesRead===0)throw new SessionTranscriptChangedError;hash2.update(buffer.subarray(0,bytesRead));position+=bytesRead}const[afterStat,afterPathStat]=await Promise.all([handle.stat(),fs9.lstat(filePath)]);const afterState=transcriptStateFromStat(afterStat);const afterPathFingerprint=transcriptFingerprint(afterPathStat);assertVerifiableTranscriptIdentity(afterPathFingerprint);if(!sameTranscriptState(beforeState,afterState)||!afterPathStat.isFile()||afterPathStat.isSymbolicLink()||!sameFileIdentity(afterState.fingerprint,afterPathFingerprint)){throw new SessionTranscriptChangedError}const proof={state:beforeState,sha256:hash2.digest("hex"),handle};handle=void 0;return proof}catch(error3){if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{await handle?.close().catch(()=>{})}}__name(openTranscriptProof,"openTranscriptProof");async function validateOpenTranscriptProof(filePath,proof){if(!proof.state.exists){const current2=await getTranscriptState(filePath,void 0);if(!sameTranscriptState(current2,proof.state)){throw new SessionTranscriptChangedError}return}const handle=proof.handle;if(!handle)throw new SessionWriterUnavailableError;try{const[handleStat,pathStat]=await Promise.all([handle.stat(),fs9.lstat(filePath)]);if(!handleStat.isFile()||!pathStat.isFile()||pathStat.isSymbolicLink()){throw new SessionWriterUnavailableError}const current2=transcriptStateFromStat(handleStat);const pathFingerprint=transcriptFingerprint(pathStat);assertVerifiableTranscriptIdentity(pathFingerprint);if(!sameTranscriptState(current2,proof.state)||!sameFileIdentity(current2.fingerprint,pathFingerprint)){throw new SessionTranscriptChangedError}}catch(error3){if(error3 instanceof SessionWriterError)throw error3;if(error3.code==="ENOENT"){throw new SessionTranscriptChangedError}throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}__name(validateOpenTranscriptProof,"validateOpenTranscriptProof");async function closeTranscriptProof(proof){await proof.handle?.close().catch(()=>{})}__name(closeTranscriptProof,"closeTranscriptProof");function assertSealedProofMatches(sealed,relativePath,proof){const transcript=sealed.transcript;if(transcript.relative_path!==relativePath||transcript.exists!==proof.state.exists||transcript.byte_length!==proof.state.byteLength||transcript.sha256!==proof.sha256){throw new SessionTranscriptChangedError}}__name(assertSealedProofMatches,"assertSealedProofMatches");async function restoreMovedLock(movedPath,lockPath){try{await fs9.link(movedPath,lockPath)}catch(error3){if(error3.code==="EEXIST"){await fs9.unlink(movedPath).catch(()=>{});return}throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}await fs9.unlink(movedPath).catch(()=>{})}__name(restoreMovedLock,"restoreMovedLock");async function syncSnapshotLockDirectory(lockPath,raw){const record4=parseLockRecord(raw);if(!record4||!isManagedLockRecord(record4)||record4.format_version<2)return;const directory=await openDurableLockDirectory(path11.dirname(lockPath));try{await syncDurableLockDirectory(directory)}finally{await directory.handle.close()}}__name(syncSnapshotLockDirectory,"syncSnapshotLockDirectory");async function installLockRecord(lockPath,record4){const temporaryPath=`${lockPath}.${record4.owner_id}.tmp`;let handle;try{const recordRaw=JSON.stringify(record4);handle=await fs9.open(temporaryPath,"wx",384);await handle.writeFile(recordRaw,"utf8");await handle.sync();await handle.close();handle=void 0;try{await fs9.link(temporaryPath,lockPath);await syncSnapshotLockDirectory(lockPath,recordRaw);return true}catch(error3){const{state}=await inspectExactRecord(lockPath,recordRaw);if(state==="exact"){await syncSnapshotLockDirectory(lockPath,recordRaw);return true}if(state==="other"||error3.code==="EEXIST"){return false}throw error3}}catch(error3){if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{await handle?.close().catch(()=>{});await fs9.unlink(temporaryPath).catch(()=>{})}}__name(installLockRecord,"installLockRecord");async function acquireReclaimGuard(lockPath,staleOwnerId,record4,inspect){const basePath=`${lockPath}.reclaim.${encodeURIComponent(staleOwnerId)}`;let guardPath=basePath;for(let attempt2=0;attempt2<ACQUIRE_ATTEMPTS;attempt2++){if(await installLockRecord(guardPath,record4))return guardPath;const state=await inspect(guardPath,record4.session_id);if(state.kind==="missing")continue;if(state.kind==="live"||state.kind==="sealed"||state.kind==="malformed"){throw new SessionWriterUnavailableError}guardPath=`${basePath}.${encodeURIComponent(state.record.owner_id)}`}throw new SessionWriterUnavailableError}__name(acquireReclaimGuard,"acquireReclaimGuard");async function removeOwnedLock(lockPath,ownerId){const record4=parseLockRecord(await fs9.readFile(lockPath,"utf8"));if(!record4||!isActiveLockRecord(record4)||record4.owner_id!==ownerId){throw new SessionWriterLostError}await fs9.unlink(lockPath)}__name(removeOwnedLock,"removeOwnedLock");async function assertPathMissing(candidatePath){try{await fs9.lstat(candidatePath)}catch(error3){if(error3.code==="ENOENT")return;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}throw new SessionWriterUnavailableError({cause:new Error("Session writer transition claim already exists")})}__name(assertPathMissing,"assertPathMissing");async function removeExactRecord(candidatePath,expectedRaw){let raw;try{raw=await fs9.readFile(candidatePath,"utf8")}catch(error3){if(error3.code==="ENOENT")return;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}if(raw!==expectedRaw)throw new SessionWriterLostError;try{await fs9.unlink(candidatePath)}catch(error3){if(error3.code==="ENOENT")return;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}__name(removeExactRecord,"removeExactRecord");async function inspectExactRecord(candidatePath,expectedRaw){try{const stat15=await fs9.lstat(candidatePath);if(!stat15.isFile()||stat15.isSymbolicLink())return{state:"other"};const raw=await fs9.readFile(candidatePath,"utf8");return{state:raw===expectedRaw?"exact":"other"}}catch(error3){if(error3.code==="ENOENT"){return{state:"missing"}}return{state:"unknown",cause:error3 instanceof Error?error3:void 0}}}__name(inspectExactRecord,"inspectExactRecord");async function removeTransitionClaimAfterFailure(lockPath,expectedPrimaryRaw,claimPath,claimRaw){const{state:primaryState}=await inspectExactRecord(lockPath,expectedPrimaryRaw);if(primaryState!=="exact"){throw new SessionWriterUnavailableError({cause:new Error("Session writer primary was not restored; transition claim retained")})}await removeExactRecord(claimPath,claimRaw)}__name(removeTransitionClaimAfterFailure,"removeTransitionClaimAfterFailure");async function releaseTransitionClaim(claimPath,claimRaw){let raw;try{raw=await fs9.readFile(claimPath,"utf8")}catch(error3){if(error3.code==="ENOENT")return;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}if(raw!==claimRaw)return;try{await fs9.unlink(claimPath)}catch(error3){if(error3.code==="ENOENT")return;const{state}=await inspectExactRecord(claimPath,claimRaw);if(state==="missing"||state==="other")return;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}__name(releaseTransitionClaim,"releaseTransitionClaim");async function inspectClaimedPrimary(lockPath,sourceRaw,sessionId){try{const stat15=await fs9.lstat(lockPath);if(!stat15.isFile()||stat15.isSymbolicLink())return{state:"other"};const raw=await fs9.readFile(lockPath,"utf8");if(raw===sourceRaw)return{state:"source"};const record4=parseLockRecord(raw);return{state:record4?.schema_version===LOCK_SCHEMA_VERSION&&record4.state==="active"&&record4.session_id===sessionId?"candidate":"other"}}catch(error3){if(error3.code==="ENOENT"){return{state:"missing"}}return{state:"unknown",cause:error3 instanceof Error?error3:void 0}}}__name(inspectClaimedPrimary,"inspectClaimedPrimary");async function assertExactTransitionClaim(claimPath,claimRaw){const{state:claimState}=await inspectExactRecord(claimPath,claimRaw);if(claimState!=="exact"){throw new SessionWriterUnavailableError({cause:new Error("Session writer transition claim ownership was lost")})}}__name(assertExactTransitionClaim,"assertExactTransitionClaim");async function waitForClaimedPrimaryCandidate(attempt2){if(attempt2>=CLAIMED_PRIMARY_WAIT_ATTEMPTS){throw new SessionWriterUnavailableError({cause:new Error("Session writer primary candidate did not release the claimed path")})}await delay2(MALFORMED_RETRY_DELAY_MS)}__name(waitForClaimedPrimaryCandidate,"waitForClaimedPrimaryCandidate");async function linkClaimedPrimary(lockPath,sourcePath,sourceRaw,sessionId,claimPath,claimRaw){let candidateWaitAttempts=0;for(;;){await assertExactTransitionClaim(claimPath,claimRaw);try{await fs9.link(sourcePath,lockPath);await syncSnapshotLockDirectory(lockPath,sourceRaw);return}catch(error3){const{state}=await inspectClaimedPrimary(lockPath,sourceRaw,sessionId);if(state==="source"){await syncSnapshotLockDirectory(lockPath,sourceRaw);return}if(state==="candidate"){await waitForClaimedPrimaryCandidate(++candidateWaitAttempts);continue}if(state==="other")throw new SessionWriterLostError;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}}__name(linkClaimedPrimary,"linkClaimedPrimary");async function removeClaimedPrimary(lockPath,sourceRaw,sessionId,claimPath,claimRaw){let candidateWaitAttempts=0;for(;;){await assertExactTransitionClaim(claimPath,claimRaw);const{state,cause}=await inspectClaimedPrimary(lockPath,sourceRaw,sessionId);if(state==="missing")return;if(state==="candidate"){await waitForClaimedPrimaryCandidate(++candidateWaitAttempts);continue}if(state==="other")throw new SessionWriterLostError;if(state==="unknown"){throw new SessionWriterUnavailableError({cause})}try{await fs9.unlink(lockPath);return}catch(error3){const{state:afterState}=await inspectClaimedPrimary(lockPath,sourceRaw,sessionId);if(afterState==="missing")return;if(afterState==="candidate"){await waitForClaimedPrimaryCandidate(++candidateWaitAttempts);continue}if(afterState==="other")throw new SessionWriterLostError;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}}__name(removeClaimedPrimary,"removeClaimedPrimary");async function transitionExactPrimary(lockPath,expectedRaw,replacementPath,replacementRaw,retiredPath,sessionId,claimPath,claimRaw){try{await fs9.rename(lockPath,retiredPath)}catch(error3){const[primaryExpected,retired]=await Promise.all([inspectExactRecord(lockPath,expectedRaw),inspectExactRecord(retiredPath,expectedRaw)]);if(primaryExpected.state==="exact"&&retired.state==="missing"){throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}if(retired.state!=="exact"){throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}try{await linkClaimedPrimary(lockPath,replacementPath,replacementRaw,sessionId,claimPath,claimRaw)}catch(error3){try{await linkClaimedPrimary(lockPath,retiredPath,expectedRaw,sessionId,claimPath,claimRaw);await removeExactRecord(retiredPath,expectedRaw)}catch(restoreError){throw new SessionWriterUnavailableError({cause:new AggregateError([error3,restoreError],"Session writer primary transition could not be restored")})}throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}__name(transitionExactPrimary,"transitionExactPrimary");async function rollbackExactTransition(lockPath,replacementRaw,retiredPath,expectedRaw,sessionId,claimPath,claimRaw){await removeClaimedPrimary(lockPath,replacementRaw,sessionId,claimPath,claimRaw);const retired=await inspectExactRecord(retiredPath,expectedRaw);if(retired.state!=="exact"){throw retired.state==="other"?new SessionWriterLostError:new SessionWriterUnavailableError({cause:retired.cause})}try{await linkClaimedPrimary(lockPath,retiredPath,expectedRaw,sessionId,claimPath,claimRaw);await removeExactRecord(retiredPath,expectedRaw)}catch(error3){throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}__name(rollbackExactTransition,"rollbackExactTransition");function getSessionWriterLockPath(runtimeBaseDir,sessionId){return path11.join(runtimeBaseDir,"tmp","session-writer-locks",`${encodeURIComponent(sessionId)}.lock`)}__name(getSessionWriterLockPath,"getSessionWriterLockPath");var SessionWriterLease=class _SessionWriterLease{constructor(lockPath,lockRecord,options2){this.lockPath=lockPath;this.ownerId=lockRecord.owner_id;this.sessionId=options2.sessionId;this.runtimeBaseDir=options2.runtimeBaseDir;this.transcriptPath=options2.transcriptPath;this.managedFormatVersion=isManagedLockRecord(lockRecord)?lockRecord.format_version:void 0;this.lockRecordRaw=JSON.stringify(lockRecord);this.retiredPath=`${lockPath}.released.${encodeURIComponent(this.ownerId)}`;this.claimPath=`${lockPath}.claim`}static{__name(this,"SessionWriterLease")}ownerId;sessionId;runtimeBaseDir;transcriptPath;expectedTranscriptState;expectedTranscriptHasher;released=false;releaseDurabilityPending=false;releaseDirectory;releaseRetryable=true;terminalOperation;terminalPromise;operationTail=Promise.resolve();lockRecordRaw;lockFileIdentity;retiredPath;claimPath;managedFormatVersion;takenOverCommitProof;replacementFailure;get transcriptExistedAtAcquire(){if(!this.expectedTranscriptState){throw new SessionWriterUnavailableError}return this.expectedTranscriptState.exists}get managedJournalFormatVersion(){return this.managedFormatVersion}get takeoverCommitProof(){return this.takenOverCommitProof}static async acquire(options2){try{return await _SessionWriterLease.acquireInternal(options2)}catch(error3){const lockPath=getSessionWriterLockPath(path11.resolve(options2.runtimeBaseDir),options2.sessionId);const errorKind=error3 instanceof SessionWriterError?error3.errorKind:"unknown";debugLogger15.debug(`Session writer lease acquisition failed stage=acquire errorKind=${errorKind} lockPath=${JSON.stringify(lockPath)} transcriptPath=${JSON.stringify(path11.resolve(options2.transcriptPath))} error=${describeDiagnosticError(error3)}`);if(error3 instanceof SessionWriterConflictError||error3 instanceof SessionWriterUnavailableError){debugLogger15.info(`Session writer fence blocks access; it does not prove that a writer is still alive. sessionId=${JSON.stringify(options2.sessionId)} lockPath=${JSON.stringify(lockPath)} Close the owning session normally and retry. For residual locks, fence all writers including ACP children before recovery; see docs/users/conversations-recovery.md.`)}throw error3}}static async acquireSealedManagedMaintenance(options2){const lockPath=getSessionWriterLockPath(options2.runtimeBaseDir,options2.sessionId);const claimPath=`${lockPath}.claim`;await assertPathMissing(claimPath);const observed=await this.inspectExistingLock(lockPath,options2.sessionId);if(observed.kind!=="sealed"||!isManagedLockRecord(observed.record)){throw new SessionWriterUnavailableError}if(observed.record.transcript.relative_path!==getTranscriptRelativePath(options2.runtimeBaseDir,options2.activeTranscriptPath)){throw new SessionWriterUnavailableError}const claimRecord={...observed.record,owner_id:randomUUID2()};const claimRaw=JSON.stringify(claimRecord);if(!await installLockRecord(claimPath,claimRecord)){throw new SessionWriterUnavailableError}try{const primaryIdentity=nodeFs.lstatSync(lockPath,{bigint:true});const claimIdentity=nodeFs.lstatSync(claimPath,{bigint:true});let released=false;let expectedTranscriptState;const assertCleanupOwned=__name(()=>{if(released)throw new SessionWriterLostError;for(const[candidate,identity]of[[lockPath,primaryIdentity],[claimPath,claimIdentity]]){try{const current2=nodeFs.lstatSync(candidate,{bigint:true});if(!current2.isFile()||current2.isSymbolicLink()||current2.dev!==identity.dev||current2.ino!==identity.ino||nodeFs.readFileSync(candidate,"utf8")!==(candidate===lockPath?observed.raw:claimRaw)){throw new SessionWriterLostError}}catch(error3){if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}},"assertCleanupOwned");const assertOwnedAndUnchanged=__name(async()=>{assertCleanupOwned();const proof=await openTranscriptProof(options2.transcriptPath);try{if(proof.state.exists!==observed.record.transcript.exists||proof.state.byteLength!==observed.record.transcript.byte_length||proof.sha256!==observed.record.transcript.sha256||expectedTranscriptState!==void 0&&!sameTranscriptState(proof.state,expectedTranscriptState)){throw new SessionTranscriptChangedError}await validateOpenTranscriptProof(options2.transcriptPath,proof);assertCleanupOwned();expectedTranscriptState??=proof.state}finally{await closeTranscriptProof(proof)}},"assertOwnedAndUnchanged");await assertOwnedAndUnchanged();return{assertOwnedAndUnchanged,assertCleanupOwned,release:__name(async()=>{assertCleanupOwned();await removeExactRecord(claimPath,claimRaw);released=true},"release")}}catch(error3){await removeExactRecord(claimPath,claimRaw);throw error3}}static async acquireInternal(options2){const normalizedOptions={...options2,runtimeBaseDir:path11.resolve(options2.runtimeBaseDir),transcriptPath:path11.resolve(options2.transcriptPath)};const lockPath=getSessionWriterLockPath(normalizedOptions.runtimeBaseDir,normalizedOptions.sessionId);const lockDir=path11.dirname(lockPath);try{await fs9.mkdir(lockDir,{recursive:true,mode:448});const lockDirStat=await fs9.lstat(lockDir);if(!lockDirStat.isDirectory()||lockDirStat.isSymbolicLink()){throw new SessionWriterUnavailableError({cause:new Error("Session writer lock directory is not a regular directory")})}}catch(error3){if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}const processStartIdentity=await readProcessStartIdentity(process.pid);const pidNamespaceId=readPidNamespaceId();const lockSchema=normalizedOptions.lockSchema;if(lockSchema!==void 0&&(!isManagedFormatVersion(lockSchema.formatVersion)||lockSchema.resumeFormatVersion!==void 0&&(!isManagedFormatVersion(lockSchema.resumeFormatVersion)||lockSchema.resumeFormatVersion<lockSchema.formatVersion))){throw new SessionWriterUnavailableError({cause:new Error(`Managed lock schema formatVersion ${lockSchema.formatVersion} is not a supported log format`)})}let lockRecord={...lockSchema===void 0?{schema_version:LOCK_SCHEMA_VERSION}:{schema_version:MANAGED_LOCK_SCHEMA_VERSION,format_version:lockSchema.formatVersion},state:"active",session_id:normalizedOptions.sessionId,owner_id:randomUUID2(),pid:process.pid,...processStartIdentity?{process_start_identity:processStartIdentity}:{},...pidNamespaceId!==null?{pid_namespace_id:pidNamespaceId}:{},hostname:os.hostname(),process_kind:normalizedOptions.processKind??"unknown",acquired_at:new Date().toISOString(),qwen_version:normalizedOptions.qwenVersion??null};const claimPath=`${lockPath}.claim`;for(let attempt2=0;attempt2<ACQUIRE_ATTEMPTS;attempt2++){await assertPathMissing(claimPath);if(await installLockRecord(lockPath,lockRecord)){try{await assertPathMissing(claimPath)}catch(error3){await removeOwnedLock(lockPath,lockRecord.owner_id).catch(()=>{});throw error3}return _SessionWriterLease.finishAcquisition(lockPath,lockRecord,normalizedOptions)}const state=await _SessionWriterLease.inspectExistingLock(lockPath,normalizedOptions.sessionId);if(state.kind==="missing")continue;if(state.kind==="live")throw new SessionWriterConflictError;if(state.kind==="malformed"){throw new SessionWriterUnavailableError({cause:new Error("Existing session writer lock is malformed")})}if(state.kind==="sealed"){if(normalizedOptions.takeoverPolicy!=="certified"){throw new SessionWriterConflictError}const resumeFormat=lockSchema?.resumeFormatVersion;if(resumeFormat!==void 0&&isManagedLockRecord(state.record)&&isManagedLockRecord(lockRecord)){lockRecord={...lockRecord,format_version:resumeFormat}}return _SessionWriterLease.takeOverSealed(lockPath,state,lockRecord,{...normalizedOptions,...resumeFormat===void 0?{}:{lockSchema:{schemaVersion:3,formatVersion:resumeFormat}}})}if(isManagedLockRecord(state.record)&&isManagedLockRecord(lockRecord)&&lockSchema?.resumeFormatVersion!==void 0&&state.record.format_version<=lockSchema.resumeFormatVersion){const formatVersion=Math.max(lockRecord.format_version,state.record.format_version);lockRecord={...lockRecord,format_version:formatVersion};normalizedOptions.lockSchema={schemaVersion:3,formatVersion}}if(isManagedLockRecord(state.record)&&normalizedOptions.lockSchema===void 0){throw new SessionWriterUnavailableError({cause:new Error("Session writer lock uses a schema this acquire cannot continue")})}if(isManagedLockRecord(state.record)&&normalizedOptions.lockSchema!==void 0&&normalizedOptions.lockSchema.formatVersion<state.record.format_version){throw new SessionWriterUnavailableError({cause:new Error(`Stale session writer lock format ${state.record.format_version} is newer than this binary's format ${normalizedOptions.lockSchema.formatVersion}`)})}if(normalizedOptions.reclaimPolicy==="never"){throw new SessionWriterConflictError}const staleOwnerId=state.record.owner_id;const reclaimPath=await acquireReclaimGuard(lockPath,staleOwnerId,lockRecord,(candidatePath,sessionId)=>_SessionWriterLease.inspectExistingLock(candidatePath,sessionId));let primaryInstalled=false;let staleMoved=false;const stalePath=`${lockPath}.stale.${process.pid}.${randomUUID2()}`;if(isManagedLockRecord(lockRecord)&&lockRecord.format_version>=2){const claimRaw=JSON.stringify(lockRecord);if(!await installLockRecord(claimPath,lockRecord)){throw new SessionWriterUnavailableError}const current2=await _SessionWriterLease.inspectExistingLock(lockPath,normalizedOptions.sessionId);if(current2.kind!=="stale"||current2.raw!==state.raw){throw new SessionWriterUnavailableError}await transitionExactPrimary(lockPath,current2.raw,claimPath,claimRaw,stalePath,normalizedOptions.sessionId,claimPath,claimRaw);const lease=await _SessionWriterLease.finishAcquisition(lockPath,lockRecord,normalizedOptions);await releaseTransitionClaim(claimPath,claimRaw);await removeExactRecord(stalePath,current2.raw).catch(()=>void 0);await removeOwnedLock(reclaimPath,lockRecord.owner_id).catch(()=>void 0);return lease}try{await assertPathMissing(claimPath);const currentState=await _SessionWriterLease.inspectExistingLock(lockPath,normalizedOptions.sessionId);if(currentState.kind!=="stale"||currentState.record.owner_id!==staleOwnerId){throw currentState.kind==="live"?new SessionWriterConflictError:new SessionWriterUnavailableError}await fs9.rename(lockPath,stalePath);staleMoved=true;const movedState=await _SessionWriterLease.inspectExistingLock(stalePath,normalizedOptions.sessionId);if(movedState.kind!=="stale"||movedState.record.owner_id!==staleOwnerId){await restoreMovedLock(stalePath,lockPath);staleMoved=false;throw movedState.kind==="live"?new SessionWriterConflictError:new SessionWriterUnavailableError}await fs9.unlink(stalePath);staleMoved=false;if(!await installLockRecord(lockPath,lockRecord)){throw new SessionWriterUnavailableError}primaryInstalled=true;await assertPathMissing(claimPath);const finishingLease=_SessionWriterLease.finishAcquisition(lockPath,lockRecord,normalizedOptions);primaryInstalled=false;const lease=await finishingLease;await removeOwnedLock(reclaimPath,lockRecord.owner_id).catch(()=>{});return lease}catch(error3){if(staleMoved){await restoreMovedLock(stalePath,lockPath).catch(()=>{})}if(primaryInstalled){await removeOwnedLock(lockPath,lockRecord.owner_id).catch(()=>{})}await removeOwnedLock(reclaimPath,lockRecord.owner_id).catch(()=>{});if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}}throw new SessionWriterUnavailableError}static async takeOverSealed(lockPath,observed,lockRecord,options2){if(isManagedLockRecord(observed.record)&&options2.lockSchema===void 0){throw new SessionWriterUnavailableError({cause:new Error("Sealed session writer lock uses a schema this acquire cannot continue")})}if(isManagedLockRecord(observed.record)&&options2.lockSchema!==void 0&&options2.lockSchema.formatVersion<observed.record.format_version){throw new SessionWriterUnavailableError({cause:new Error(`Sealed session writer lock format ${observed.record.format_version} is newer than this binary's format ${options2.lockSchema.formatVersion}`)})}const relativePath=getTranscriptRelativePath(options2.runtimeBaseDir,options2.transcriptPath);const proof=await openTranscriptProof(options2.transcriptPath);const claimPath=`${lockPath}.claim`;const claimRaw=JSON.stringify(lockRecord);const retiredPath=`${lockPath}.sealed.${encodeURIComponent(observed.record.owner_id)}.${encodeURIComponent(lockRecord.owner_id)}`;let claimAcquired=false;let transitionStarted=false;let transitionCommitted=false;try{assertSealedProofMatches(observed.record,relativePath,proof);await assertPathMissing(retiredPath);if(!await installLockRecord(claimPath,lockRecord)){throw new SessionWriterUnavailableError({cause:new Error("Session writer transition claim already exists")})}claimAcquired=true;const current2=await _SessionWriterLease.inspectExistingLock(lockPath,options2.sessionId);if(current2.kind!=="sealed"||current2.raw!==observed.raw){throw current2.kind==="live"?new SessionWriterConflictError:new SessionWriterUnavailableError}await validateOpenTranscriptProof(options2.transcriptPath,proof);assertSealedProofMatches(current2.record,relativePath,proof);transitionStarted=true;await transitionExactPrimary(lockPath,observed.raw,claimPath,claimRaw,retiredPath,options2.sessionId,claimPath,claimRaw);transitionCommitted=true;await validateOpenTranscriptProof(options2.transcriptPath,proof);const lease=await _SessionWriterLease.finishAcquisition(lockPath,lockRecord,options2,proof.state);if(isManagedLockRecord(observed.record)){lease.takenOverCommitProof={last_commit_sequence:observed.record.last_commit_sequence,committed_prefix_hash:observed.record.committed_prefix_hash}}await releaseTransitionClaim(claimPath,claimRaw);claimAcquired=false;await removeExactRecord(retiredPath,observed.raw).catch(error3=>{debugLogger15.debug(`Session writer sealed lock cleanup failed path=${JSON.stringify(retiredPath)} error=${describeDiagnosticError(error3)}`)});debugLogger15.info(`Certified session writer handoff accepted sessionId=${JSON.stringify(options2.sessionId)} previousHostname=${JSON.stringify(observed.record.hostname)} previousPid=${observed.record.pid} sealedAt=${observed.record.sealed_at}`);return lease}catch(error3){const cleanupFailures=[];const claimState=claimAcquired?(await inspectExactRecord(claimPath,claimRaw)).state:"missing";if(claimState==="unknown"){cleanupFailures.push(new SessionWriterUnavailableError({cause:new Error("Session writer transition claim ownership is unreadable")}))}if(transitionCommitted&&claimState==="exact"){try{await rollbackExactTransition(lockPath,claimRaw,retiredPath,observed.raw,options2.sessionId,claimPath,claimRaw)}catch(cleanupError){cleanupFailures.push(cleanupError)}}if(claimState==="exact"){try{if(transitionStarted){await removeTransitionClaimAfterFailure(lockPath,observed.raw,claimPath,claimRaw)}else{await releaseTransitionClaim(claimPath,claimRaw)}}catch(cleanupError){cleanupFailures.push(cleanupError)}}if(cleanupFailures.length>0){throw new SessionWriterUnavailableError({cause:new AggregateError([error3,...cleanupFailures],"Certified session writer takeover cleanup failed")})}if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{await closeTranscriptProof(proof)}}static async finishAcquisition(lockPath,lockRecord,options2,requiredTranscriptState){const lease=new _SessionWriterLease(lockPath,lockRecord,options2);try{lease.lockFileIdentity=lease.readVerifiedLockIdentity();options2.onOwnershipAcquired?.(lease);const snapshot=await captureTranscriptSnapshot(options2.transcriptPath,void 0,()=>lease.released);if(!snapshot.state.exists){await assertTranscriptFilesystemProvidesIdentity(options2.transcriptPath)}await lease.readOwnedLock();lease.expectedTranscriptState=snapshot.state;lease.expectedTranscriptHasher=snapshot.hasher;if(requiredTranscriptState&&!sameTranscriptState(lease.expectedTranscriptState,requiredTranscriptState)){throw new SessionTranscriptChangedError}return lease}catch(error3){if((lease.managedFormatVersion??0)>=2)throw error3;let releaseError;for(let attempt2=0;attempt2<2;attempt2++){if(attempt2===1)lease.releaseRetryable=false;try{await lease.release();releaseError=void 0;break}catch(candidate){releaseError=candidate;if(candidate instanceof SessionWriterLostError)break}}if(releaseError!==void 0){await lease.closeReleaseDirectory();throw new SessionWriterUnavailableError({cause:new AggregateError([error3,releaseError],"Session writer acquisition cleanup failed")})}throw error3}}static async inspectExistingLock(lockPath,expectedSessionId){for(let attempt2=0;attempt2<MALFORMED_RETRY_COUNT;attempt2++){let stat15;try{stat15=await fs9.lstat(lockPath)}catch(error3){if(error3.code==="ENOENT"){return{kind:"missing"}}throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}if(!stat15.isFile()||stat15.isSymbolicLink()){throw new SessionWriterUnavailableError({cause:new Error("Session writer lock is not a regular file")})}let raw;try{raw=await fs9.readFile(lockPath,"utf8")}catch(error3){if(error3.code==="ENOENT"){return{kind:"missing"}}throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}const record4=parseLockRecord(raw);if(record4){if(record4.session_id!==expectedSessionId){throw new SessionWriterUnavailableError({cause:new Error("Session writer lock belongs to another session")})}if(!isActiveLockRecord(record4)){return{kind:"sealed",record:record4,raw}}return lockStateForRecord(record4,raw)}if(attempt2+1<MALFORMED_RETRY_COUNT){await delay2(MALFORMED_RETRY_DELAY_MS)}}return{kind:"malformed"}}async readOwnedLock(){if(this.released)throw new SessionWriterLostError;let stat15;try{stat15=await fs9.lstat(this.lockPath,{bigint:true})}catch(error3){if(error3.code==="ENOENT"){throw new SessionWriterLostError}throw new SessionWriterUnavailableError}if(!stat15.isFile()||stat15.isSymbolicLink()||this.lockFileIdentity!==void 0&&(stat15.dev!==this.lockFileIdentity.dev||stat15.ino!==this.lockFileIdentity.ino)){throw new SessionWriterLostError}let raw;try{raw=await fs9.readFile(this.lockPath,"utf8")}catch(error3){if(error3.code==="ENOENT"){throw new SessionWriterLostError}throw new SessionWriterUnavailableError}const record4=parseLockRecord(raw);if(!record4||!isActiveLockRecord(record4)||record4.owner_id!==this.ownerId||raw!==this.lockRecordRaw){throw new SessionWriterLostError}let current2;try{current2=await fs9.lstat(this.lockPath,{bigint:true})}catch(error3){if(error3.code==="ENOENT"){throw new SessionWriterLostError}throw new SessionWriterUnavailableError}if(!current2.isFile()||current2.isSymbolicLink()||current2.dev!==stat15.dev||current2.ino!==stat15.ino){throw new SessionWriterLostError}return record4}readVerifiedLockIdentity(){let descriptor2;try{descriptor2=nodeFs.openSync(this.lockPath,nodeConstants.O_RDONLY|(nodeConstants.O_NOFOLLOW??0)|(nodeConstants.O_NONBLOCK??0))}catch(error3){const code=error3.code;if(code==="ENOENT"||code==="ELOOP"){throw new SessionWriterLostError}throw new SessionWriterUnavailableError}try{const stat15=nodeFs.fstatSync(descriptor2,{bigint:true});if(!stat15.isFile())throw new SessionWriterLostError;if(!hasVerifiableInode(stat15.ino)){throw new SessionWriterUnavailableError}const assertPathMatchesDescriptor=__name(()=>{let pathStat;try{pathStat=nodeFs.lstatSync(this.lockPath,{bigint:true})}catch(error3){if(error3.code==="ENOENT"){throw new SessionWriterLostError}throw new SessionWriterUnavailableError}if(!pathStat.isFile()||pathStat.isSymbolicLink()||pathStat.dev!==stat15.dev||pathStat.ino!==stat15.ino){throw new SessionWriterLostError}},"assertPathMatchesDescriptor");assertPathMatchesDescriptor();const raw=nodeFs.readFileSync(descriptor2,"utf8");const record4=parseLockRecord(raw);if(!record4||!isActiveLockRecord(record4)||record4.owner_id!==this.ownerId||raw!==this.lockRecordRaw){throw new SessionWriterLostError}assertPathMatchesDescriptor();return{dev:stat15.dev,ino:stat15.ino}}catch(error3){if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError}finally{nodeFs.closeSync(descriptor2)}}assertCleanupOwned(){if(this.released)throw new SessionWriterLostError;const expected=this.lockFileIdentity;if(expected===void 0)throw new SessionWriterUnavailableError;const current2=this.readVerifiedLockIdentity();if(current2.dev!==expected.dev||current2.ino!==expected.ino){throw new SessionWriterLostError}}assertOwnedAndUnchanged(){return this.runExclusive(()=>this.assertOwnedAndUnchangedOnce())}async assertOwnedAndUnchangedOnce(){await this.readOwnedLock();const expectedState=this.expectedTranscriptState;if(!expectedState||!this.expectedTranscriptHasher){throw new SessionWriterUnavailableError}const transcriptState=await getTranscriptState(this.transcriptPath,expectedState);if(sameTranscriptState(transcriptState,expectedState)){debugLogger15.debug("Session transcript verified path=fast");return}if(!sameHardTranscriptState(transcriptState,expectedState)){debugLogger15.debug(`Session transcript hard state changed changedFields=${transcriptStateChangedFields(expectedState,transcriptState).join(",")}`);throw new SessionTranscriptChangedError}await this.reconcileTranscriptMetadata(transcriptState)}appendJsonLine(value){return this.runExclusive(()=>this.appendJsonLineOnce(value))}readTranscript(){return this.runExclusive(async()=>{await this.assertOwnedAndUnchangedOnce();const handle=await openTranscriptForRead(this.transcriptPath,this.expectedTranscriptState);if(!handle)return"";try{const text3=await handle.readFile("utf8");await this.assertOwnedAndUnchangedOnce();if(createHash7("sha256").update(text3).digest("hex")!==this.expectedTranscriptHasher.copy().digest("hex")){throw new SessionTranscriptChangedError}return text3}finally{await handle.close()}})}replaceTranscript(text3,expectedSha256){return this.runExclusive(()=>this.replaceTranscriptOnce(text3,expectedSha256,false))}replaceManagedTranscript(text3,expectedSha256,verify){return this.runExclusive(()=>this.replaceTranscriptOnce(text3,expectedSha256,true,verify))}async replaceTranscriptOnce(text3,expectedSha256,managed,verify){await this.assertOwnedAndUnchangedOnce();if((managed?this.managedFormatVersion!==2:this.managedFormatVersion!==void 0)||this.expectedTranscriptHasher.copy().digest("hex")!==expectedSha256){throw new SessionTranscriptChangedError}const directoryPath=path11.dirname(this.transcriptPath);await fs9.mkdir(directoryPath,{recursive:true,mode:448});const directory=await openDurableLockDirectory(directoryPath);const temporaryPath=path11.join(directoryPath,`.${randomUUID2()}.jsonl.tmp`);let temporary;let replaced=false;let replacementAttempted=false;try{temporary=await fs9.open(temporaryPath,"wx",384);const mode=this.expectedTranscriptState?.exists?this.expectedTranscriptState.fingerprint.mode:void 0;if(mode!==void 0)await temporary.chmod(mode&511);await temporary.writeFile(text3,"utf8");await temporary.sync();const replacementState=transcriptStateFromStat(await temporary.stat());await temporary.close();temporary=void 0;await syncDurableLockDirectory(directory);await this.assertOwnedAndUnchangedOnce();replacementAttempted=true;await fs9.rename(temporaryPath,this.transcriptPath);replaced=true;await syncDurableLockDirectory(directory);const snapshot=await captureTranscriptSnapshot(this.transcriptPath,replacementState,()=>this.released);const expectedHash=createHash7("sha256").update(text3).digest("hex");if(snapshot.hasher.copy().digest("hex")!==expectedHash){throw new SessionTranscriptChangedError}await this.readOwnedLock();this.expectedTranscriptState=snapshot.state;this.expectedTranscriptHasher=snapshot.hasher;verify?.();if(managed)await this.assertOwnedAndUnchangedOnce()}catch(error3){if(managed&&replacementAttempted){this.replacementFailure=error3 instanceof Error?error3:new Error(String(error3))}if(error3 instanceof SessionWriterError)throw error3;if(!replaced){await this.assertOwnedAndUnchangedOnce();throw error3}throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{await temporary?.close().catch(()=>void 0);await fs9.unlink(temporaryPath).catch(()=>void 0);await directory.handle.close().catch(()=>void 0)}}truncateTo(byteLength2){return this.runExclusive(()=>this.truncateToOnce(byteLength2))}async truncateToOnce(byteLength2){if(!Number.isSafeInteger(byteLength2)||byteLength2<0){throw new SessionWriterUnavailableError}await this.assertOwnedAndUnchangedOnce();const expected=this.expectedTranscriptState;if(!expected?.exists||!this.expectedTranscriptHasher){throw new SessionWriterUnavailableError}if(byteLength2>expected.byteLength){throw new SessionWriterUnavailableError}if(byteLength2===expected.byteLength)return;let handle;try{handle=await openTranscriptForAppend(this.transcriptPath,expected);const beforeState=await getOpenTranscriptState(this.transcriptPath,handle,true);if(!sameTranscriptState(beforeState,expected)){throw new SessionTranscriptChangedError}await this.readOwnedLock();assertVerifiableTranscriptIdentity(beforeState.fingerprint);await handle.truncate(byteLength2);await handle.sync();const afterState=transcriptStateFromStat(await handle.stat());if(afterState.byteLength!==byteLength2||!sameFileIdentity(afterState.fingerprint,beforeState.fingerprint)||!sameFileSecurityMetadata(afterState.fingerprint,beforeState.fingerprint)){throw new SessionTranscriptChangedError}await handle.close();handle=void 0;const snapshot=await captureTranscriptSnapshot(this.transcriptPath,afterState,()=>this.released);if(!snapshot.state.exists||snapshot.state.byteLength!==byteLength2||!sameFileIdentity(snapshot.state.fingerprint,afterState.fingerprint)||!sameFileSecurityMetadata(snapshot.state.fingerprint,afterState.fingerprint)){throw new SessionTranscriptChangedError}await this.readOwnedLock();this.expectedTranscriptState=snapshot.state;this.expectedTranscriptHasher=snapshot.hasher}catch(error3){const code=error3.code;if(code==="EEXIST"||code==="ENOENT"){throw new SessionTranscriptChangedError}if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{if(handle){await handle.close().catch(()=>void 0)}}}async appendJsonLineOnce(value){let serialized;try{serialized=JSON.stringify(value)}catch(error3){throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}if(serialized===void 0)throw new SessionWriterUnavailableError;const bytes=Buffer.from(`${serialized}
99
- `,"utf8");await this.assertOwnedAndUnchangedOnce();let expectedBefore=this.expectedTranscriptState;if(!expectedBefore||!this.expectedTranscriptHasher){throw new SessionWriterUnavailableError}let handle;try{await fs9.mkdir(path11.dirname(this.transcriptPath),{recursive:true,mode:448});handle=await openTranscriptForAppend(this.transcriptPath,expectedBefore);let beforeState=await getOpenTranscriptState(this.transcriptPath,handle,true);if(expectedBefore.exists){if(!sameTranscriptState(beforeState,expectedBefore)){if(!sameHardTranscriptState(beforeState,expectedBefore)){throw new SessionTranscriptChangedError}await this.reconcileTranscriptMetadata(beforeState,handle);expectedBefore=this.expectedTranscriptState;if(!expectedBefore?.exists){throw new SessionWriterUnavailableError}beforeState=expectedBefore}}else if(beforeState.byteLength!==0){throw new SessionTranscriptChangedError}const expectedHasher=this.expectedTranscriptHasher;if(!expectedHasher)throw new SessionWriterUnavailableError;const candidateHasher=expectedHasher.copy();candidateHasher.update(bytes);const nextByteLength=expectedBefore.byteLength+bytes.byteLength;await this.readOwnedLock();assertVerifiableTranscriptIdentity(beforeState.fingerprint);await handle.writeFile(bytes);await handle.sync();const afterStat=await handle.stat();const afterState=transcriptStateFromStat(afterStat);if(afterState.byteLength!==nextByteLength||!sameFileIdentity(afterState.fingerprint,beforeState.fingerprint)||!sameFileSecurityMetadata(afterState.fingerprint,beforeState.fingerprint)){throw new SessionTranscriptChangedError}await handle.close();handle=void 0;const transcriptState=await getTranscriptState(this.transcriptPath,afterState);if(!transcriptState.exists||transcriptState.byteLength!==nextByteLength||!sameFileIdentity(transcriptState.fingerprint,afterState.fingerprint)||!sameFileSecurityMetadata(transcriptState.fingerprint,afterState.fingerprint)){throw new SessionTranscriptChangedError}let committedState=transcriptState;let committedHasher=candidateHasher;let appendReconciliation;if(!sameTranscriptState(transcriptState,afterState)){const changedFields=transcriptStateChangedFields(afterState,transcriptState);const startedAt=Date.now();await this.readOwnedLock();const snapshot=await captureTranscriptSnapshot(this.transcriptPath,afterState,()=>this.released);if(!transcriptHashesEqual(snapshot.hasher,candidateHasher)){debugLogger15.debug(`Session transcript content changed after append metadata signal path=slow changedFields=${changedFields.join(",")} attempts=${snapshot.attempts} durationMs=${Date.now()-startedAt}`);throw new SessionTranscriptChangedError}committedState=snapshot.state;committedHasher=snapshot.hasher;appendReconciliation={changedFields,attempts:snapshot.attempts,startedAt}}await this.readOwnedLock();this.expectedTranscriptHasher=committedHasher;this.expectedTranscriptState=committedState;if(appendReconciliation){debugLogger15.debug(`Session transcript append metadata reconciled path=slow changedFields=${appendReconciliation.changedFields.join(",")} attempts=${appendReconciliation.attempts} durationMs=${Date.now()-appendReconciliation.startedAt}`)}}catch(error3){const code=error3.code;if(code==="EEXIST"||code==="ENOENT"){throw new SessionTranscriptChangedError}if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{await handle?.close().catch(()=>{})}}async reconcileTranscriptMetadata(observedState,handle){const expectedState=this.expectedTranscriptState;const expectedHasher=this.expectedTranscriptHasher;if(!expectedState||!expectedHasher||!sameHardTranscriptState(observedState,expectedState)){throw new SessionTranscriptChangedError}const changedFields=transcriptStateChangedFields(expectedState,observedState);const startedAt=Date.now();await this.readOwnedLock();const snapshot=handle?await captureOpenTranscriptSnapshot(this.transcriptPath,handle,expectedState,()=>this.released):await captureTranscriptSnapshot(this.transcriptPath,expectedState,()=>this.released);if(!transcriptHashesEqual(snapshot.hasher,expectedHasher)){debugLogger15.debug(`Session transcript content changed after metadata signal path=slow changedFields=${changedFields.join(",")} attempts=${snapshot.attempts} durationMs=${Date.now()-startedAt}`);throw new SessionTranscriptChangedError}await this.readOwnedLock();this.expectedTranscriptHasher=snapshot.hasher;this.expectedTranscriptState=snapshot.state;debugLogger15.debug(`Session transcript metadata reconciled path=slow changedFields=${changedFields.join(",")} attempts=${snapshot.attempts} durationMs=${Date.now()-startedAt}`)}release(){if(this.terminalOperation==="seal")return this.terminalPromise;if((this.managedFormatVersion??0)>=2&&!this.released){return Promise.reject(new SessionWriterUnavailableError({cause:new Error("A snapshot writer must preserve its seal or active fence.")}))}this.terminalOperation="release";if(this.terminalPromise)return this.terminalPromise;const terminal=this.runExclusive(()=>this.releaseOnce()).catch(error3=>{if(this.releaseRetryable&&(!this.released||this.releaseDurabilityPending)&&!(error3 instanceof SessionWriterLostError)&&this.terminalPromise===terminal){this.terminalPromise=void 0}throw error3});this.terminalPromise=terminal;return this.terminalPromise}sealForHandoff(commitProof){if(this.terminalOperation==="release")return this.release();this.terminalOperation="seal";if(this.terminalPromise)return this.terminalPromise;const terminal=this.runExclusive(()=>this.sealForHandoffOnce(commitProof)).catch(error3=>{if(this.releaseRetryable&&!this.released&&!(error3 instanceof SessionWriterLostError)&&this.terminalPromise===terminal){this.terminalPromise=void 0;this.terminalOperation=void 0}throw error3});this.terminalPromise=terminal;return terminal}get isReleased(){return this.released}get isReleaseDurabilityPending(){return this.releaseDurabilityPending}runExclusive(operation){const checked=__name(()=>{if(this.replacementFailure){throw new SessionWriterUnavailableError({cause:this.replacementFailure})}return operation()},"checked");const pending=this.operationTail.then(checked,checked);this.operationTail=pending.then(()=>void 0,()=>void 0);return pending}async releaseOnce(){if(this.released){if(this.releaseDurabilityPending){if(!this.releaseDirectory)throw new SessionWriterUnavailableError;await syncDurableLockDirectory(this.releaseDirectory);this.releaseDurabilityPending=false;await this.closeReleaseDirectory()}return}try{this.releaseDirectory=await openDurableLockDirectory(path11.dirname(this.lockPath));await this.readOwnedLockForRelease();try{await fs9.rename(this.lockPath,this.retiredPath)}catch(error3){const[primaryState,retiredState]=await Promise.all([this.inspectReleasePath(this.lockPath),this.inspectReleasePath(this.retiredPath)]);if(primaryState==="missing"||primaryState==="other"){this.released=true;if(retiredState==="owned"){this.releaseDurabilityPending=true;await fs9.unlink(this.retiredPath).catch(()=>{});await syncDurableLockDirectory(this.releaseDirectory);this.releaseDurabilityPending=false;await this.closeReleaseDirectory();return}throw new SessionWriterLostError}if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}this.released=true;this.releaseDurabilityPending=true;await fs9.unlink(this.retiredPath).catch(error3=>{debugLogger15.debug(`Session writer retired lock cleanup failed path=${JSON.stringify(this.retiredPath)} error=${describeDiagnosticError(error3)}`)});await syncDurableLockDirectory(this.releaseDirectory);this.releaseDurabilityPending=false;await this.closeReleaseDirectory()}catch(error3){if(!this.releaseDurabilityPending)await this.closeReleaseDirectory();throw error3}}async closeReleaseDirectory(){const directory=this.releaseDirectory;this.releaseDirectory=void 0;await directory?.handle.close().catch(()=>void 0)}async sealForHandoffOnce(commitProof){if(this.released)return;const ownedRecord=await this.readOwnedLockForRelease();if(!this.expectedTranscriptState){throw new SessionWriterUnavailableError}if(this.managedFormatVersion!==void 0&&!isValidCommitProof(commitProof)){throw new SessionWriterUnavailableError({cause:new Error("Managed session writer seal requires the commit proof")})}const relativePath=getTranscriptRelativePath(this.runtimeBaseDir,this.transcriptPath);const proof=await openTranscriptProof(this.transcriptPath);const transcriptProof={relative_path:relativePath,exists:proof.state.exists,byte_length:proof.state.byteLength,sha256:proof.sha256};let sealedRecord;if(this.managedFormatVersion===void 0){sealedRecord={...ownedRecord,schema_version:LOCK_SCHEMA_VERSION,state:"sealed",sealed_at:new Date().toISOString(),transcript:transcriptProof}}else{sealedRecord={...ownedRecord,schema_version:MANAGED_LOCK_SCHEMA_VERSION,state:"sealed",sealed_at:new Date().toISOString(),format_version:this.managedFormatVersion,last_commit_sequence:commitProof.last_commit_sequence,committed_prefix_hash:commitProof.committed_prefix_hash,transcript:transcriptProof}}const sealedRaw=JSON.stringify(sealedRecord);const sealedCandidatePath=`${this.lockPath}.sealed-candidate.${encodeURIComponent(this.ownerId)}`;const handoffRetiredPath=`${this.lockPath}.handoff.${encodeURIComponent(this.ownerId)}`;let claimAcquired=false;let transitionStarted=false;let transitionCommitted=false;try{if(!sameTranscriptState(proof.state,this.expectedTranscriptState)){throw new SessionTranscriptChangedError}if(!await installLockRecord(sealedCandidatePath,sealedRecord)){throw new SessionWriterUnavailableError({cause:new Error("Session writer sealed candidate already exists")})}await assertPathMissing(handoffRetiredPath);if(!await installLockRecord(this.claimPath,ownedRecord)){throw new SessionWriterUnavailableError({cause:new Error("Session writer transition claim already exists")})}claimAcquired=true;await this.readOwnedLock();await validateOpenTranscriptProof(this.transcriptPath,proof);transitionStarted=true;await transitionExactPrimary(this.lockPath,this.lockRecordRaw,sealedCandidatePath,sealedRaw,handoffRetiredPath,this.sessionId,this.claimPath,this.lockRecordRaw);transitionCommitted=true;await validateOpenTranscriptProof(this.transcriptPath,proof);await releaseTransitionClaim(this.claimPath,this.lockRecordRaw);claimAcquired=false;this.released=true;await removeExactRecord(handoffRetiredPath,this.lockRecordRaw).catch(error3=>{debugLogger15.debug(`Session writer handoff retired cleanup failed path=${JSON.stringify(handoffRetiredPath)} error=${describeDiagnosticError(error3)}`)});await removeExactRecord(sealedCandidatePath,sealedRaw).catch(error3=>{debugLogger15.debug(`Session writer handoff candidate cleanup failed path=${JSON.stringify(sealedCandidatePath)} error=${describeDiagnosticError(error3)}`)});debugLogger15.info(`Session writer handoff sealed sessionId=${JSON.stringify(this.sessionId)} hostname=${JSON.stringify(ownedRecord.hostname)} pid=${ownedRecord.pid} sealedAt=${sealedRecord.sealed_at}`)}catch(error3){const cleanupFailures=[];const claimState=claimAcquired?(await inspectExactRecord(this.claimPath,this.lockRecordRaw)).state:"missing";if(claimState==="unknown"){cleanupFailures.push(new SessionWriterUnavailableError({cause:new Error("Session writer transition claim ownership is unreadable")}))}if(transitionCommitted&&claimState==="exact"){try{await rollbackExactTransition(this.lockPath,sealedRaw,handoffRetiredPath,this.lockRecordRaw,this.sessionId,this.claimPath,this.lockRecordRaw)}catch(cleanupError){cleanupFailures.push(cleanupError)}}if(claimState==="exact"){try{if(transitionStarted){await removeTransitionClaimAfterFailure(this.lockPath,this.lockRecordRaw,this.claimPath,this.lockRecordRaw)}else{await releaseTransitionClaim(this.claimPath,this.lockRecordRaw)}}catch(cleanupError){cleanupFailures.push(cleanupError)}}try{await removeExactRecord(sealedCandidatePath,sealedRaw)}catch(cleanupError){cleanupFailures.push(cleanupError)}if((await inspectExactRecord(this.lockPath,this.lockRecordRaw)).state!=="exact"){this.released=true}if(cleanupFailures.length>0){throw new SessionWriterUnavailableError({cause:new AggregateError([error3,...cleanupFailures],"Session writer handoff cleanup failed")})}if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{await closeTranscriptProof(proof)}}async readOwnedLockForRelease(){for(let attempt2=0;attempt2<RELEASE_PRECHECK_ATTEMPTS;attempt2++){try{return await this.readOwnedLock()}catch(error3){if(!(error3 instanceof SessionWriterUnavailableError)||attempt2+1===RELEASE_PRECHECK_ATTEMPTS){throw error3}}await delay2(RELEASE_PRECHECK_RETRY_DELAY_MS)}throw new SessionWriterUnavailableError}async inspectReleasePath(candidatePath){try{const stat15=await fs9.lstat(candidatePath);if(!stat15.isFile()||stat15.isSymbolicLink())return"other";const raw=await fs9.readFile(candidatePath,"utf8");return raw===this.lockRecordRaw?"owned":"other"}catch(error3){return error3.code==="ENOENT"?"missing":"unknown"}}};init_esbuild_shims();import{createHash as createHash8,randomUUID as randomUUID3}from"node:crypto";import{constants}from"node:fs";import{link as link3,lstat as lstat3,mkdir as mkdir6,open as open3,rename as rename3,unlink as unlink6}from"node:fs/promises";import*as path12 from"node:path";var MANAGED_SESSION_RESOURCE_LIMITS=Object.freeze({maxResourceBytes:64*1024*1024});var LocalManagedSessionResourceStore=class _LocalManagedSessionResourceStore{constructor(root,sessionKey){this.root=root;this.sessionKey=sessionKey}static{__name(this,"LocalManagedSessionResourceStore")}static create(options2){return new _LocalManagedSessionResourceStore(managedSessionResourceRoot(options2.runtimeBaseDir,options2.sessionKey.sessionId),options2.sessionKey)}get sessionRoot(){return this.root}async publish(kind,bytes){if(kind==="managed-local-journal-snapshot"||kind==="managed-local-journal-snapshot-page"){throw new ManagedSessionRecordError("Native snapshot resources use their dedicated publisher.")}return this.publishBytes(kind,bytes,randomUUID3(),false)}publishJournalSnapshot(kind,bytes){return this.publishBytes(kind,bytes,createHash8("sha256").update(bytes).digest("hex"),true)}async publishBytes(kind,bytes,resourceId,immutable){const safeKind=assertPathSegment(kind,"kind");if(bytes.byteLength>MANAGED_SESSION_RESOURCE_LIMITS.maxResourceBytes){throw new ManagedSessionRecordError(`${safeKind} is ${bytes.byteLength} bytes where ${MANAGED_SESSION_RESOURCE_LIMITS.maxResourceBytes} is the maximum.`)}const directory=path12.join(this.root,safeKind);const pending=path12.join(directory,immutable?`.${resourceId}.${randomUUID3()}.pending`:`.${resourceId}.pending`);const target=path12.join(directory,resourceId);await ensurePrivateDirectory(path12.dirname(this.root));await ensurePrivateDirectory(this.root);const checkedDirectory=await ensurePrivateDirectory(directory);const resourceRef={resourceId,kind:safeKind,schemaVersion:1,byteLength:bytes.byteLength,digest:immutable?resourceId:createHash8("sha256").update(bytes).digest("hex")};if(immutable&&await lstatOrUndefined(target)){await this.read(resourceRef);await syncDirectory(directory);return resourceRef}const handle=await open3(pending,"wx",384);let written;try{await handle.writeFile(bytes);await handle.sync();written=await handle.stat()}catch(cause){await handle.close();await unlink6(pending).catch(()=>void 0);throw cause}await handle.close();try{if(immutable){try{await link3(pending,target)}catch(cause){if(cause.code!=="EEXIST")throw cause;await this.read(resourceRef);await unlink6(pending);await syncDirectory(directory);return resourceRef}await unlink6(pending)}else{await rename3(pending,target)}const destination=await lstatOrUndefined(directory);const published=await lstatOrUndefined(target);if(destination===void 0||destination.isSymbolicLink()||!destination.isDirectory()||destination.dev!==checkedDirectory.dev||destination.ino!==checkedDirectory.ino||published===void 0||!published.isFile()||published.dev!==written.dev||published.ino!==written.ino){throw new ManagedSessionRecordError(`resource ${resourceId} was not published inside its session directory.`)}await syncDirectory(directory)}catch(cause){await unlink6(pending).catch(()=>void 0);throw cause}return resourceRef}async read(ref11){const target=path12.join(this.root,assertPathSegment(ref11.kind,"kind"),assertPathSegment(ref11.resourceId,"resourceId"));try{for(const directory of[path12.dirname(this.root),this.root,path12.dirname(target)]){const ancestor=await lstat3(directory);if(ancestor.isSymbolicLink()||!ancestor.isDirectory()){throw new ManagedSessionRecordError(`session resource directory is not private: ${directory} is not a real directory.`)}}}catch(cause){if(cause instanceof ManagedSessionRecordError)throw cause;if(cause.code==="ENOENT"){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is not present for session ${this.sessionKey.sessionId}.`)}throw cause}let bytes;let size;try{const stat15=await lstat3(target);if(!stat15.isFile()){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is not a regular file.`)}size=stat15.size}catch(cause){if(cause instanceof ManagedSessionRecordError)throw cause;if(cause.code==="ENOENT"){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is not present for session ${this.sessionKey.sessionId}.`)}throw cause}if(size!==ref11.byteLength){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is ${size} bytes on disk where ${ref11.byteLength} was recorded.`)}let handle;try{handle=await openNoFollow(target)}catch(cause){if(cause.code==="ENOENT"){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is not present for session ${this.sessionKey.sessionId}.`)}if(cause.code==="ELOOP"){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is not a regular file.`)}if(isUnverifiableIdentityError(cause)){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} could not be identity-verified.`)}throw cause}try{const opened=await handle.stat();if(!opened.isFile()||opened.size!==size){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} changed while it was being read.`)}bytes=await handle.readFile()}finally{await handle.close()}if(bytes.byteLength!==ref11.byteLength){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is ${bytes.byteLength} bytes where ${ref11.byteLength} was recorded.`)}const digest2=createHash8("sha256").update(bytes).digest("hex");if(digest2!==ref11.digest){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} does not match its recorded digest.`)}return bytes}};async function readManagedBranchCheckpoint(event,resources,checkpointSequence,committedSequence){if(event.kind!=="checkpoint.committed")return void 0;if(resources===void 0){throw new ManagedSessionRecordError("a resource store is required to classify checkpoints.")}const ref11=assertManagedSessionDurableRef(event.payload["stateRef"],"checkpoint state");const branch=ref11.kind==="managed-branch-checkpoint";if(ref11.schemaVersion!==1||!branch&&ref11.kind!=="managed-checkpoint"){throw new ManagedSessionRecordError("unknown checkpoint state format.")}const id6=event.payload["checkpointId"];const covered=event.payload["coveredSequence"];const previous=event.payload["previousCheckpointId"];const previousSequence=previous===null?void 0:checkpointSequence(previous);if(checkpointSequence(id6)!==void 0||covered>=event.sequence||covered>committedSequence||previous!==null&&(previousSequence===void 0||previousSequence>covered)){throw new ManagedSessionRecordError("invalid checkpoint coverage or predecessor.")}if(branch&&(event.payload["boundary"]!==null||covered!==event.sequence-1)){throw new ManagedSessionRecordError("invalid historical branch checkpoint boundary.")}if(!branch)return void 0;const bytes=await resources.read(ref11);return assertManagedBranchRecord(parseManagedSessionRecordJson(bytes.toString("utf8"),ref11.byteLength),event.sessionKey,id6)}__name(readManagedBranchCheckpoint,"readManagedBranchCheckpoint");function assertPathSegment(value,label){if(value.length===0){throw new ManagedSessionRecordError(`${label} must not be empty.`)}if(value!==path12.basename(value)||value==="."||value===".."){throw new ManagedSessionRecordError(`${label} must be a single path segment.`)}return value}__name(assertPathSegment,"assertPathSegment");async function ensurePrivateDirectory(directory){const created=await mkdir6(directory,{recursive:true,mode:448});const stat15=await lstat3(directory);if(stat15.isSymbolicLink()||!stat15.isDirectory()){throw new ManagedSessionRecordError(`session resource directory is not private: ${directory} is not a real directory.`)}if(process.platform!=="win32"&&(stat15.mode&511)!==448){await tightenDirectory(directory)}if(created!==void 0){await syncDirectory(path12.dirname(directory))}return{dev:stat15.dev,ino:stat15.ino}}__name(ensurePrivateDirectory,"ensurePrivateDirectory");async function lstatOrUndefined(target){try{return await lstat3(target)}catch(cause){if(cause.code==="ENOENT")return void 0;throw cause}}__name(lstatOrUndefined,"lstatOrUndefined");async function tightenDirectory(directory){const flags=constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_DIRECTORY??0);let handle;try{handle=await open3(directory,flags)}catch{return}try{const opened=await handle.stat();if(!opened.isDirectory())return;await handle.chmod(448)}catch{}finally{await handle.close()}}__name(tightenDirectory,"tightenDirectory");async function syncDirectory(directory){const handle=await open3(directory,"r");try{await handle.sync()}catch(error3){if(process.platform!=="win32"||!["EACCES","EINVAL","EPERM"].includes(error3.code??"")){throw error3}}finally{await handle.close()}}__name(syncDirectory,"syncDirectory");init_esbuild_shims();init_esbuild_shims();import{createHash as createHash9}from"node:crypto";init_esbuild_shims();var CHANNEL_ROUTE_SCOPE_KINDS=["user","chat_thread","thread","single"];var CHANNEL_DELIVERY_MAX_SEGMENTS=64;var ROUTE_KEYS=["routeId","channelInstanceId","accountId","accountGeneration","routeRevision","rootSessionId","sessionId","scope","policyRef","run"];var DELIVERY_KEYS2=["deliveryId","routeId","routeRevision","sourceTurnId","contentRef","segments","cancelRequested","run"];var SCOPE_KEYS2=["kind","senderId","chatId","threadId"];var SEGMENT_KEYS=["segmentId","ordinal","contentRef","receipt"];var RECEIPT_KEYS=["providerMessageId","acceptedAt","proofRef"];var REBIND_KEYS=["accountGeneration","routeRevision","rootSessionId","sessionId","policyRef"];var TERMINAL_RUN_STATES2=["settled","failed","cancelled"];function fail2(message){throw new ManagedSessionRecordError(message)}__name(fail2,"fail");function closed2(value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key))){fail2(`Channel record must have exactly the keys ${keys2.join(", ")}.`)}return{...value}}__name(closed2,"closed");function id2(value,label){return assertManagedSessionStableId(value,label)}__name(id2,"id");function revision3(value,label){const parsed=assertManagedSessionSequence(value,label);if(parsed<1)fail2(`${label} must be positive.`);return parsed}__name(revision3,"revision");function ref3(value,label){return Object.freeze(assertManagedSessionDurableRef(value,label))}__name(ref3,"ref");function parseScope(value){const body=closed2(value,SCOPE_KEYS2);const kind=body.kind;if(kind!=="user"&&kind!=="chat_thread"&&kind!=="thread"&&kind!=="single"){fail2("Channel route scope kind must be user, chat_thread, thread or single.")}const nullableId3=__name((field,label)=>field===null?null:id2(field,label),"nullableId");const scope={kind,senderId:nullableId3(body.senderId,"scope.senderId"),chatId:nullableId3(body.chatId,"scope.chatId"),threadId:nullableId3(body.threadId,"scope.threadId")};const{senderId,chatId,threadId}=scope;const carries=scope.kind==="user"?senderId!==null&&chatId!==null&&threadId===null:scope.kind==="thread"?senderId===null&&chatId===null!==(threadId===null):scope.kind==="chat_thread"?senderId===null&&chatId!==null:senderId===null&&chatId===null&&threadId===null;if(!carries){fail2(`Channel route scope ${scope.kind} does not carry its identity.`)}return Object.freeze(scope)}__name(parseScope,"parseScope");function routeRun(value,routeId){const run=parseExtensionRun(value);if(run.definition!==null||run.executionCallId!==null||run.effectId!==routeId||run.dispatchId!==null||run.deliveryId!==null||run.execution!==null||run.runtime!==null||run.delivery!==null){fail2("Channel route run must identify its effect and nothing else.")}return run}__name(routeRun,"routeRun");function parseChannelRoute(value){const body=closed2(value,ROUTE_KEYS);const routeId=id2(body.routeId,"routeId");return Object.freeze({routeId,channelInstanceId:id2(body.channelInstanceId,"channelInstanceId"),accountId:id2(body.accountId,"accountId"),accountGeneration:revision3(body.accountGeneration,"accountGeneration"),routeRevision:revision3(body.routeRevision,"routeRevision"),rootSessionId:id2(body.rootSessionId,"rootSessionId"),sessionId:id2(body.sessionId,"sessionId"),scope:parseScope(body.scope),policyRef:ref3(body.policyRef,"policyRef"),run:routeRun(body.run,routeId)})}__name(parseChannelRoute,"parseChannelRoute");function parseReceipt(value){const body=closed2(value,RECEIPT_KEYS);return Object.freeze({providerMessageId:id2(body.providerMessageId,"receipt.providerMessageId"),acceptedAt:assertManagedSessionTime(body.acceptedAt,"receipt.acceptedAt"),proofRef:body.proofRef===null?null:ref3(body.proofRef,"proofRef")})}__name(parseReceipt,"parseReceipt");function parseSegments(value){if(!Array.isArray(value))fail2("Channel delivery segments must be a list.");if(value.length<1||value.length>CHANNEL_DELIVERY_MAX_SEGMENTS){fail2(`Channel delivery segments must number 1 to ${CHANNEL_DELIVERY_MAX_SEGMENTS}.`)}const seen=new Set;const segments=[];for(let index=0;index<value.length;index+=1){const body=closed2(value[index],SEGMENT_KEYS);const segmentId=id2(body.segmentId,`segments[${index}].segmentId`);if(seen.has(segmentId)){fail2(`Channel delivery segment ${segmentId} is named twice.`)}seen.add(segmentId);const ordinal=assertManagedSessionSequence(body.ordinal,`segments[${index}].ordinal`);if(ordinal!==index){fail2("Channel delivery segment ordinals must be dense from zero.")}segments.push(Object.freeze({segmentId,ordinal,contentRef:ref3(body.contentRef,`segments[${index}].contentRef`),receipt:body.receipt===null?null:parseReceipt(body.receipt)}))}return Object.freeze(segments)}__name(parseSegments,"parseSegments");function deliveryRun(value,deliveryId){const run=parseExtensionRun(value);if(run.definition!==null||run.executionCallId!==null||run.effectId!==deliveryId||run.dispatchId!==null||run.deliveryId!==deliveryId||run.execution!==null||run.runtime!==null||run.delivery===null||run.delivery.target!=="channel"){fail2("Channel delivery run must carry its channel delivery line and nothing else.")}return run}__name(deliveryRun,"deliveryRun");function parseChannelDelivery(value){const body=closed2(value,DELIVERY_KEYS2);if(typeof body.cancelRequested!=="boolean"){fail2("Channel delivery cancelRequested must be boolean.")}const deliveryId=id2(body.deliveryId,"deliveryId");const run=deliveryRun(body.run,deliveryId);const segments=parseSegments(body.segments);const receipts=segments.map(segment=>segment.receipt!==null);const settled=receipts.filter(Boolean).length;const state=run.delivery.state;const pins={planned:run.state==="admitted"&&settled===0,sending:(run.state==="running"||run.state==="waiting"||run.state==="recovery_blocked")&&settled<segments.length,partial:(run.state==="running"||run.state==="waiting"||run.state==="recovery_blocked")&&settled>0&&settled<segments.length,delivered:run.state==="settled"&&settled===segments.length,unknown:run.state==="waiting"&&run.reason===null&&settled<segments.length,rejected:run.state==="failed"&&settled<segments.length,cancelled:run.state==="cancelled"&&settled===0&&body.cancelRequested};if(!pins[state]){fail2(`Channel delivery line ${state} does not match its run and segment receipts.`)}return Object.freeze({deliveryId,routeId:id2(body.routeId,"routeId"),routeRevision:revision3(body.routeRevision,"routeRevision"),sourceTurnId:id2(body.sourceTurnId,"sourceTurnId"),contentRef:ref3(body.contentRef,"contentRef"),segments,cancelRequested:body.cancelRequested,run})}__name(parseChannelDelivery,"parseChannelDelivery");function accepts(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts,"accepts");function same(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same,"same");function isChannelRouteStart(value){return accepts(()=>isExtensionRunStart(parseChannelRoute(value).run))}__name(isChannelRouteStart,"isChannelRouteStart");function isChannelDeliveryStart(value){return accepts(()=>{const record4=parseChannelDelivery(value);return isExtensionRunStart(record4.run)&&!record4.cancelRequested&&record4.segments.every(segment=>segment.receipt===null)})}__name(isChannelDeliveryStart,"isChannelDeliveryStart");function isChannelRouteSuccessor(previous,next){return accepts(()=>{const before=parseChannelRoute(previous);const after=parseChannelRoute(next);if(!same(before.routeId,after.routeId)||!same(before.channelInstanceId,after.channelInstanceId)||!same(before.accountId,after.accountId)||!same(before.scope,after.scope)||!isExtensionRunSuccessor(before.run,after.run)){return false}if(TERMINAL_RUN_STATES2.includes(before.run.state)){return same(before,after)}if(before.routeRevision===after.routeRevision){return REBIND_KEYS.every(key=>same(before[key],after[key]))}return after.routeRevision===before.routeRevision+1&&after.accountGeneration>=before.accountGeneration})}__name(isChannelRouteSuccessor,"isChannelRouteSuccessor");function isChannelDeliverySuccessor(previous,next){return accepts(()=>{const before=parseChannelDelivery(previous);const after=parseChannelDelivery(next);if(before.deliveryId!==after.deliveryId||before.routeId!==after.routeId||before.routeRevision!==after.routeRevision||before.sourceTurnId!==after.sourceTurnId||!same(before.contentRef,after.contentRef)||before.segments.length!==after.segments.length||!before.segments.every((segment,index)=>{const other2=after.segments[index];return segment.segmentId===other2.segmentId&&segment.ordinal===other2.ordinal&&same(segment.contentRef,other2.contentRef)&&(segment.receipt===null||same(segment.receipt,other2.receipt))})||before.cancelRequested&&!after.cancelRequested||!isExtensionRunSuccessor(before.run,after.run)){return false}const settledOf=__name(record4=>record4.segments.filter(segment=>segment.receipt!==null).length,"settledOf");if(before.run.delivery.state==="unknown"&&after.run.delivery.state==="partial"&&settledOf(after)<=settledOf(before)){return false}if(TERMINAL_RUN_STATES2.includes(before.run.state)){return same(before,after)}return true})}__name(isChannelDeliverySuccessor,"isChannelDeliverySuccessor");var MANAGED_CHANNEL_LIMITS=Object.freeze({maxTextChars:32e3,maxEnvelopeBytes:64*1024,maxAttachments:16,maxInlineAttachmentBytes:64*1024,maxReplyContextBytes:8*1024,maxSegmentBytes:48*1024,maxSegments:CHANNEL_DELIVERY_MAX_SEGMENTS,maxSubjectChars:200});var CHANNEL_INPUT_SOURCE="channel";var CHANNEL_RESOURCE_KINDS=Object.freeze({policy:"managed-channel-policy",input:"managed-input",attachment:"managed-channel-attachment",reply:"managed-channel-reply",segment:"managed-channel-segment"});var SEPARATOR="\0";function sha256(parts){return createHash9("sha256").update(parts.map(String).join(SEPARATOR),"utf8").digest("hex")}__name(sha256,"sha256");function fail3(message){throw new ManagedSessionRecordError(message)}__name(fail3,"fail");function assertNoSeparator(value,label){if(value.length===0||value.includes(SEPARATOR)){fail3(`${label} must be non-empty and hold no NUL.`)}return value}__name(assertNoSeparator,"assertNoSeparator");function positive(value,label){if(!Number.isSafeInteger(value)||value<1){fail3(`${label} must be a positive integer.`)}return value}__name(positive,"positive");function channelRouteId(params){return`chrt-${sha256([assertNoSeparator(params.channelInstanceId,"channelInstanceId"),assertNoSeparator(params.accountId,"accountId"),params.scope.kind,params.scope.senderId??"",params.scope.chatId??"",params.scope.threadId??""])}`}__name(channelRouteId,"channelRouteId");function channelDeliveryId(inputId){return`${inputId}:reply`}__name(channelDeliveryId,"channelDeliveryId");function channelResendDeliveryId(deliveryId,attempt2){return`${deliveryId}:r${positive(attempt2,"attempt")}`}__name(channelResendDeliveryId,"channelResendDeliveryId");var CHANNEL_SENDER_POLICIES=["allowlist","open","disabled"];var CHANNEL_DISPATCH_MODES=["followup","steer"];function plainObject(value,label){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype){fail3(`${label} must be a JSON object.`)}return value}__name(plainObject,"plainObject");function exactKeys(record4,keys2,label){const present=Object.keys(record4).sort();if(present.join(",")!==[...keys2].sort().join(",")){fail3(`${label} must have exactly the keys ${keys2.join(", ")}.`)}}__name(exactKeys,"exactKeys");function parseJson(bytes,label){try{return JSON.parse(bytes.toString("utf8"))}catch{fail3(`${label} must be JSON.`)}}__name(parseJson,"parseJson");function text(value,label,max){if(typeof value!=="string"||value.length>max){fail3(`${label} must be text of at most ${max} characters.`)}return value}__name(text,"text");function nullableText(value,label,max){return value===null?null:text(value,label,max)}__name(nullableText,"nullableText");function encodeChannelPolicy(policy){return Buffer.from(JSON.stringify(decodeChannelPolicyValue(policy)),"utf8")}__name(encodeChannelPolicy,"encodeChannelPolicy");function decodeChannelPolicy(bytes){return decodeChannelPolicyValue(parseJson(bytes,"Channel policy"))}__name(decodeChannelPolicy,"decodeChannelPolicy");function assertChannelPolicy(value){return decodeChannelPolicyValue(value)}__name(assertChannelPolicy,"assertChannelPolicy");function decodeChannelPolicyValue(value){const record4=plainObject(value,"Channel policy");exactKeys(record4,["adapter","senderPolicy","allowedSenders","dispatchMode"],"Channel policy");const adapter=text(record4["adapter"],"Channel policy adapter",64);if(!/^[a-z][a-z0-9-]*$/.test(adapter)){fail3("Channel policy adapter must be a lowercase identifier.")}const senderPolicy=record4["senderPolicy"];if(!CHANNEL_SENDER_POLICIES.includes(senderPolicy)){fail3("Channel policy senderPolicy must be allowlist, open or disabled.")}const dispatchMode=record4["dispatchMode"];if(!CHANNEL_DISPATCH_MODES.includes(dispatchMode)){fail3("Channel policy dispatchMode must be followup or steer.")}const senders=record4["allowedSenders"];if(!Array.isArray(senders)||senders.length>1024||!senders.every(sender=>typeof sender==="string"&&sender.length>0)){fail3("Channel policy allowedSenders must list sender identities.")}return Object.freeze({adapter,senderPolicy,allowedSenders:Object.freeze([...senders]),dispatchMode})}__name(decodeChannelPolicyValue,"decodeChannelPolicyValue");var ENVELOPE_KEYS=["channelInstanceId","accountId","accountGeneration","platformEventId","semanticRevision","routeId","routeRevision","senderId","chatId","threadId","subject","text","attachments","replyContext"];var DIGEST=/^[a-f0-9]{64}$/;function parseAttachment(value,index){const label=`attachments[${index}]`;const record4=plainObject(value,label);const common={fileName:text(record4["fileName"],`${label}.fileName`,128),mimeType:text(record4["mimeType"],`${label}.mimeType`,128),byteLength:record4["byteLength"],digest:record4["digest"]};if(!Number.isSafeInteger(common.byteLength)||common.byteLength<0||typeof common.digest!=="string"||!DIGEST.test(common.digest)){fail3(`${label} must carry a byte length and a sha256 digest.`)}if("omitted"in record4){exactKeys(record4,["fileName","mimeType","byteLength","digest","omitted"],label);if(record4["omitted"]!=="too_large"){fail3(`${label}.omitted must be too_large.`)}return Object.freeze({...common,omitted:"too_large"})}exactKeys(record4,["fileName","mimeType","byteLength","digest","ref"],label);const ref11=assertManagedSessionDurableRef(record4["ref"],`${label}.ref`);if(ref11.digest!==common.digest||ref11.byteLength!==common.byteLength){fail3(`${label} must describe the bytes its reference names.`)}return Object.freeze({...common,ref:Object.freeze(ref11)})}__name(parseAttachment,"parseAttachment");function decodeEnvelopeValue(value){const record4=plainObject(value,"Channel input envelope");exactKeys(record4,ENVELOPE_KEYS,"Channel input envelope");const attachments=record4["attachments"];if(!Array.isArray(attachments)||attachments.length>MANAGED_CHANNEL_LIMITS.maxAttachments){fail3(`Channel input attachments must number at most ${MANAGED_CHANNEL_LIMITS.maxAttachments}.`)}const replyContext=record4["replyContext"];if(Buffer.byteLength(JSON.stringify(replyContext??null),"utf8")>MANAGED_CHANNEL_LIMITS.maxReplyContextBytes){fail3(`Channel reply context exceeds ${MANAGED_CHANNEL_LIMITS.maxReplyContextBytes} bytes (byte_limit).`)}const envelope2={channelInstanceId:assertNoSeparator(text(record4["channelInstanceId"],"channelInstanceId",128),"channelInstanceId"),accountId:assertNoSeparator(text(record4["accountId"],"accountId",512),"accountId"),accountGeneration:positive(record4["accountGeneration"],"accountGeneration"),platformEventId:assertNoSeparator(text(record4["platformEventId"],"platformEventId",512),"platformEventId"),semanticRevision:positive(record4["semanticRevision"],"semanticRevision"),routeId:text(record4["routeId"],"routeId",512),routeRevision:positive(record4["routeRevision"],"routeRevision"),senderId:text(record4["senderId"],"senderId",512),chatId:nullableText(record4["chatId"],"chatId",512),threadId:nullableText(record4["threadId"],"threadId",512),subject:nullableText(record4["subject"],"subject",MANAGED_CHANNEL_LIMITS.maxSubjectChars),text:text(record4["text"],"text",MANAGED_CHANNEL_LIMITS.maxTextChars),attachments:Object.freeze(attachments.map((entry,index)=>parseAttachment(entry,index))),replyContext:replyContext===void 0?null:replyContext};return Object.freeze(envelope2)}__name(decodeEnvelopeValue,"decodeEnvelopeValue");function encodeChannelInputEnvelope(envelope2){const bytes=Buffer.from(JSON.stringify(decodeEnvelopeValue(envelope2)),"utf8");if(bytes.byteLength>MANAGED_CHANNEL_LIMITS.maxEnvelopeBytes){fail3(`Channel input envelope exceeds ${MANAGED_CHANNEL_LIMITS.maxEnvelopeBytes} bytes (byte_limit).`)}return bytes}__name(encodeChannelInputEnvelope,"encodeChannelInputEnvelope");function decodeChannelInputEnvelope(bytes){return decodeEnvelopeValue(parseJson(bytes,"Channel input envelope"))}__name(decodeChannelInputEnvelope,"decodeChannelInputEnvelope");function escapeXml2(value){return value.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}__name(escapeXml2,"escapeXml");function channelInputText(envelope2){const lines=["<channel-message>",`<channel>${escapeXml2(envelope2.channelInstanceId)}</channel>`,`<sender>${escapeXml2(envelope2.senderId)}</sender>`,`<platform-event-id>${escapeXml2(envelope2.platformEventId)}</platform-event-id>`];if(envelope2.subject!==null){lines.push(`<subject untrusted="true">${escapeXml2(envelope2.subject)}</subject>`)}if(envelope2.attachments.length>0){lines.push("<attachments>");for(const attachment of envelope2.attachments){const status="omitted"in attachment?' omitted="too_large"':` resource="${escapeXml2(attachment.ref.resourceId)}"`;lines.push(`<attachment name="${escapeXml2(attachment.fileName)}" type="${escapeXml2(attachment.mimeType)}" bytes="${attachment.byteLength}" sha256="${attachment.digest}"${status}/>`)}lines.push("</attachments>")}lines.push(`<text>${escapeXml2(envelope2.text)}</text>`,"</channel-message>");return lines.join("\n")}__name(channelInputText,"channelInputText");function encodeChannelReply(reply){return Buffer.from(JSON.stringify({text:reply.text,replyContext:reply.replyContext}),"utf8")}__name(encodeChannelReply,"encodeChannelReply");function decodeChannelReply(bytes){const record4=plainObject(parseJson(bytes,"Channel reply"),"Channel reply");exactKeys(record4,["text","replyContext"],"Channel reply");if(typeof record4["text"]!=="string")fail3("Channel reply text is missing.");return Object.freeze({text:record4["text"],replyContext:record4["replyContext"]})}__name(decodeChannelReply,"decodeChannelReply");var TRUNCATION_NOTICE="\n\n[Reply truncated because it exceeded the channel segment size limit.]";var CHANNEL_TRUNCATION_NOTICE=TRUNCATION_NOTICE;function truncateChannelTextUtf8(text3,maxBytes){const bytes=Buffer.from(text3,"utf8");if(bytes.byteLength<=maxBytes){return text3}const limit=Math.max(0,maxBytes-Buffer.byteLength(TRUNCATION_NOTICE,"utf8"));let end=limit;while(end>0&&(bytes[end]&192)===128)end-=1;return bytes.subarray(0,end).toString("utf8")+TRUNCATION_NOTICE}__name(truncateChannelTextUtf8,"truncateChannelTextUtf8");function planChannelSegments(text3){return Object.freeze([truncateChannelTextUtf8(text3,MANAGED_CHANNEL_LIMITS.maxSegmentBytes)])}__name(planChannelSegments,"planChannelSegments");function routeRun2(routeId){return Object.freeze({state:"admitted",reason:null,definition:null,executionCallId:null,effectId:routeId,dispatchId:null,deliveryId:null,execution:null,runtime:null,delivery:null})}__name(routeRun2,"routeRun");function assertChannelRouteScope(value){const record4=plainObject(value,"Channel route scope");exactKeys(record4,["kind","senderId","chatId","threadId"],"scope");if(!CHANNEL_ROUTE_SCOPE_KINDS.includes(record4["kind"])){fail3("Channel route scope kind must be user, chat_thread, thread or single.")}return Object.freeze({kind:record4["kind"],senderId:nullableText(record4["senderId"],"scope.senderId",512),chatId:nullableText(record4["chatId"],"scope.chatId",512),threadId:nullableText(record4["threadId"],"scope.threadId",512)})}__name(assertChannelRouteScope,"assertChannelRouteScope");function channelRouteOpenBody(params){return Object.freeze({routeId:params.routeId,channelInstanceId:params.channelInstanceId,accountId:params.accountId,accountGeneration:positive(params.accountGeneration,"accountGeneration"),routeRevision:1,rootSessionId:params.rootSessionId,sessionId:params.sessionId,scope:params.scope,policyRef:params.policyRef,run:routeRun2(params.routeId)})}__name(channelRouteOpenBody,"channelRouteOpenBody");function channelRouteRolloverBody(previous,params){if(positive(params.accountGeneration,"accountGeneration")<=previous.accountGeneration){fail3(`Channel route ${previous.routeId} cannot roll its generation back to ${params.accountGeneration} (channel_generation_stale).`)}return Object.freeze({...previous,accountGeneration:params.accountGeneration,routeRevision:previous.routeRevision+1,policyRef:params.policyRef??previous.policyRef})}__name(channelRouteRolloverBody,"channelRouteRolloverBody");function deliveryRun2(deliveryId,state,line2){return Object.freeze({state,reason:null,definition:null,executionCallId:null,effectId:deliveryId,dispatchId:null,deliveryId,execution:null,runtime:null,delivery:Object.freeze({target:"channel",state:line2})})}__name(deliveryRun2,"deliveryRun");function channelDeliveryPlanBody(params){if(params.segments.length<1||params.segments.length>MANAGED_CHANNEL_LIMITS.maxSegments){fail3(`Channel delivery plans 1 to ${MANAGED_CHANNEL_LIMITS.maxSegments} segments.`)}return Object.freeze({deliveryId:params.deliveryId,routeId:params.routeId,routeRevision:positive(params.routeRevision,"routeRevision"),sourceTurnId:params.sourceTurnId,contentRef:params.contentRef,segments:Object.freeze(params.segments.map((segment,ordinal)=>Object.freeze({segmentId:segment.segmentId,ordinal,contentRef:segment.contentRef,receipt:null}))),cancelRequested:false,run:deliveryRun2(params.deliveryId,"admitted","planned")})}__name(channelDeliveryPlanBody,"channelDeliveryPlanBody");function withRun(previous,state,line2,changes={}){return Object.freeze({...previous,...changes,run:deliveryRun2(previous.deliveryId,state,line2)})}__name(withRun,"withRun");function channelDeliverySendingBody(previous){return withRun(previous,"running","sending")}__name(channelDeliverySendingBody,"channelDeliverySendingBody");function channelDeliveryProvenSegments(delivery){return delivery.segments.filter(segment=>segment.receipt!==null).length}__name(channelDeliveryProvenSegments,"channelDeliveryProvenSegments");function channelDeliveryReceiptBody(previous,ordinal,receipt){const segment=previous.segments[ordinal];if(segment===void 0){fail3(`Channel delivery ${previous.deliveryId} has no segment ${ordinal}.`)}if(segment.receipt!==null){fail3(`Channel delivery segment ${segment.segmentId} already has a receipt.`)}const segments=previous.segments.map((entry,index)=>index===ordinal?Object.freeze({...entry,receipt}):entry);const settled=segments.filter(entry=>entry.receipt!==null).length;const complete=settled===segments.length;return withRun(previous,complete?"settled":previous.run.state==="waiting"?"waiting":"running",complete?"delivered":"partial",{segments:Object.freeze(segments)})}__name(channelDeliveryReceiptBody,"channelDeliveryReceiptBody");function channelDeliveryUnknownBody(previous){return withRun(previous,"waiting","unknown")}__name(channelDeliveryUnknownBody,"channelDeliveryUnknownBody");function channelDeliveryRejectedBody(previous){return withRun(previous,"failed","rejected")}__name(channelDeliveryRejectedBody,"channelDeliveryRejectedBody");function channelDeliveryCancelRequestedBody(previous){return Object.freeze({...previous,cancelRequested:true})}__name(channelDeliveryCancelRequestedBody,"channelDeliveryCancelRequestedBody");function channelDeliveryCancelledBody(previous){if(previous.run.delivery?.state!=="planned"){fail3(`Channel delivery ${previous.deliveryId} is ${previous.run.delivery?.state} and can no longer be cancelled.`)}return withRun(previous,"cancelled","cancelled",{cancelRequested:true})}__name(channelDeliveryCancelledBody,"channelDeliveryCancelledBody");function channelDeliveryResendable(delivery){const state=delivery.run.delivery?.state;return(state==="unknown"||state==="rejected")&&channelDeliveryProvenSegments(delivery)<delivery.segments.length}__name(channelDeliveryResendable,"channelDeliveryResendable");function channelDeliveryResendBody(previous,deliveryId){if(!channelDeliveryResendable(previous)){fail3(`Channel delivery ${previous.deliveryId} is ${previous.run.delivery?.state} and cannot be resent.`)}return channelDeliveryPlanBody({deliveryId,routeId:previous.routeId,routeRevision:previous.routeRevision,sourceTurnId:previous.sourceTurnId,contentRef:previous.contentRef,segments:previous.segments.filter(segment=>segment.receipt===null).map(segment=>({segmentId:segment.segmentId,contentRef:segment.contentRef}))})}__name(channelDeliveryResendBody,"channelDeliveryResendBody");init_esbuild_shims();init_esbuild_shims();var CHILD_RUN_STOP_REASONS=Object.freeze({settled:Object.freeze(["exited"]),failed:Object.freeze(["start_failed","process_failed","quota_exceeded"]),cancelled:Object.freeze(["stop_requested"])});var CHILD_AGENT_STOP_REASONS=Object.freeze({settled:Object.freeze(["completed"]),failed:Object.freeze(["creation_failed","child_failed","quota_exceeded"]),cancelled:Object.freeze(["stop_requested"])});function isChildSessionRun(record4){switch(record4.kind){case"child_agent":case"workflow":return true;case"shell":return false;default:{const unclassified=record4;void unclassified;return false}}}__name(isChildSessionRun,"isChildSessionRun");var SHELL_KEYS=["commandRef","exitCode","exitSignal","kind","outputRef","ownerScopeId","run","shellId","startReceiptRef","stopReason","stopRequested"];var SHELL_FIXED_KEYS=["commandRef","kind","ownerScopeId","shellId"];var CHILD_AGENT_KEYS=["childRunId","childSessionId","completion","depth","inputRef","kind","ownerScopeId","predecessorChildRunId","resultRef","resultVersion","rootSessionId","run","stopReason","stopRequested","terminalReceiptRef","workspaceMode","workingDirectory"];var CHILD_AGENT_FIXED_KEYS=["childRunId","completion","depth","inputRef","kind","ownerScopeId","predecessorChildRunId","rootSessionId","workspaceMode","workingDirectory"];var TERMINAL_RUN_STATES3=["settled","failed","cancelled"];var UNSTARTED_EXECUTION_STATES2=[null,"intent","dispatch_started","not_started_proven"];var EXIT_SIGNAL_PATTERN=/^[A-Z][A-Z0-9]{0,15}$/;var WORKSPACE_MODES=["shared","snapshot","worktree"];var MAX_DEPTH=8;function fail4(message){throw new ManagedSessionRecordError(message)}__name(fail4,"fail");function closed3(value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key)))fail4(`Child run must have exactly the keys ${keys2.join(", ")}.`);return{...value}}__name(closed3,"closed");function id3(value,label){return assertManagedSessionStableId(value,label)}__name(id3,"id");function ref4(value,label){return Object.freeze(assertManagedSessionDurableRef(value,label))}__name(ref4,"ref");function nullable2(value,parse15){return value===null?null:parse15(value)}__name(nullable2,"nullable");function accepts2(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts2,"accepts");function same2(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same2,"same");function setOnce2(before,after){return before===null||same2(before,after)}__name(setOnce2,"setOnce");function stopReasonOf(value,reasons,run){const stopReason=nullable2(value,reason=>{if(typeof reason!=="string"||!Object.values(reasons).some(fitting=>fitting.includes(reason))){fail4("Child run stopReason is not a closed stop reason.")}return reason});if(stopReason===null!==!TERMINAL_RUN_STATES3.includes(run.state)){fail4("Child run stopReason is set exactly when the run ends.")}if(stopReason!==null){const fitting=Object.hasOwn(reasons,run.state)?reasons[run.state]:[];if(!fitting.includes(stopReason)){fail4(`Child run stopReason ${stopReason} does not fit the ${run.state} state.`)}}return stopReason}__name(stopReasonOf,"stopReasonOf");function stopFlags(stopReason,stopRequestedValue,run){if(typeof stopRequestedValue!=="boolean"){fail4("Child run stopRequested must be boolean.")}if(stopReason==="stop_requested"&&!stopRequestedValue){fail4("Child run stop_requested needs its stop request.")}const quota=run.reason!==null&&MANAGED_EXTENSION_REASONS.quota.includes(run.reason);if(stopReason==="quota_exceeded"!==quota){fail4("Child run stopReason is quota_exceeded exactly for a quota reason.")}return stopRequestedValue}__name(stopFlags,"stopFlags");function parseChildRun(value){const kind=typeof value==="object"&&value!==null?value["kind"]:void 0;if(kind==="shell")return parseChildShellRecord(value);if(kind==="child_agent"||kind==="workflow"){return parseChildSessionRun(value,kind)}fail4("Child run kind must be one of shell, child_agent, workflow in schema version 1.")}__name(parseChildRun,"parseChildRun");function parseChildShellRun(value){const record4=parseChildRun(value);if(record4.kind!=="shell"){fail4(`Child run kind must be 'shell' for this consumer, got ${record4.kind}.`)}return record4}__name(parseChildShellRun,"parseChildShellRun");function parseChildShellRecord(value){const body=closed3(value,SHELL_KEYS);const run=parseExtensionRun(body.run);if(run.executionCallId===null||run.effectId!==null||run.dispatchId!==null||run.deliveryId!==null||run.delivery!==null||run.definition!==null){fail4("Child run must name its start call and nothing else.")}const execution=run.execution;const startReceiptRef=nullable2(body.startReceiptRef,each=>ref4(each,"startReceiptRef"));if(startReceiptRef!==null&&UNSTARTED_EXECUTION_STATES2.includes(execution)){fail4("Child run startReceiptRef must be null before the process starts.")}if(startReceiptRef===null&&(execution==="running_attached"||execution==="settled")){fail4("Child run startReceiptRef must be set once the process started.")}if(startReceiptRef!==null&&run.runtime===null){fail4("Child run startReceiptRef needs the Runtime binding that started it.")}const outputRef=nullable2(body.outputRef,each=>{const output=ref4(each,"outputRef");if(output.kind!==MANAGED_TOOL_RESULT_KINDS.manifest||output.schemaVersion!==1){fail4(`Child run outputRef must reference ${MANAGED_TOOL_RESULT_KINDS.manifest} version 1.`)}return output});if(outputRef!==null&&startReceiptRef===null){fail4("Child run outputRef needs a start receipt.")}const stopReason=stopReasonOf(body.stopReason,CHILD_RUN_STOP_REASONS,run);const stopRequested=stopFlags(stopReason,body.stopRequested,run);const exitCode=nullable2(body.exitCode,code=>{if(typeof code!=="number"||!Number.isInteger(code)||code<0||code>255){fail4("Child run exitCode must be an integer from 0 to 255.")}return code});const exitSignal=nullable2(body.exitSignal,signal=>{if(typeof signal!=="string"||!EXIT_SIGNAL_PATTERN.test(signal)){fail4("Child run exitSignal must be an uppercase signal name.")}return signal});if(run.state==="settled"&&execution!=="settled"){fail4("Child run settled needs its settled execution.")}if(run.state==="cancelled"&&execution!=="settled"){fail4("Child run cancelled needs its settled execution.")}if(run.state==="failed"&&execution!=="settled"&&execution!=="not_started_proven"){fail4("Child run failed needs settled or not_started_proven execution.")}if(stopReason==="start_failed"&&(startReceiptRef!==null||execution!=="not_started_proven")){fail4("Child run start_failed needs a process that never started.")}if(stopReason==="process_failed"&&startReceiptRef===null){fail4("Child run process_failed needs a process that started.")}if((stopReason==="process_failed"||stopReason==="quota_exceeded")&&execution!=="settled"){fail4("Child run process failure needs its settled execution.")}if(stopReason==="exited"?exitCode===null&&exitSignal===null:exitCode!==null||exitSignal!==null){fail4("Child run exitCode or exitSignal is proven exactly when it exits.")}return Object.freeze({kind:"shell",shellId:id3(body.shellId,"shellId"),ownerScopeId:id3(body.ownerScopeId,"ownerScopeId"),commandRef:ref4(body.commandRef,"commandRef"),startReceiptRef,outputRef,stopReason,stopRequested,exitCode,exitSignal,run})}__name(parseChildShellRecord,"parseChildShellRecord");function parseChildSessionRun(value,kind){const body=closed3(value,CHILD_AGENT_KEYS);const run=parseExtensionRun(body.run);if(run.executionCallId===null||run.effectId!==null||run.deliveryId!==null){fail4("Child run must name its start call, never an effect or a channel delivery.")}const delivery=run.delivery;if(delivery===null||delivery.target!=="session"){fail4("Child run delivery must target the parent session.")}if(kind==="workflow"&&run.definition===null){fail4("Workflow run must pin its workflow definition from launch.")}if(run.execution!==null&&run.execution!=="intent"&&run.definition===null){fail4("Child run must pin the definition it dispatched.")}const depth=body.depth;if(typeof depth!=="number"||!Number.isInteger(depth)||depth<1||depth>MAX_DEPTH){fail4(`Child run depth must be an integer from 1 to ${MAX_DEPTH}.`)}const completion=body.completion;if(completion!=="tool"&&completion!=="sent"){fail4(`Child run completion must be 'tool' or 'sent'.`)}const inputRef=ref4(body.inputRef,"inputRef");const workspaceMode=body.workspaceMode;if(typeof workspaceMode!=="string"||!WORKSPACE_MODES.includes(workspaceMode)){fail4(`Child run workspaceMode must be one of ${WORKSPACE_MODES.join(", ")}.`)}const workingDirectory=body.workingDirectory;if(typeof workingDirectory!=="string"||!isRelativeDirectory(workingDirectory)){fail4("Child run workingDirectory must be a normalized relative directory.")}const childSessionId=nullable2(body.childSessionId,each=>id3(each,"childSessionId"));if(childSessionId!==null&&run.execution!=="not_started_proven"&&UNSTARTED_EXECUTION_STATES2.includes(run.execution)){fail4("Child run childSessionId needs its admitted creation dispatch.")}if(childSessionId===null&&(run.execution==="running_attached"||run.execution==="settled")){fail4("Child run childSessionId is set once creation is proven.")}if(childSessionId!==null&&run.runtime===null&&run.execution!=="not_started_proven"){fail4("Child run childSessionId needs the Runtime binding that hosts it.")}if((run.execution==="dispatch_started"||run.execution==="outcome_unknown")&&run.runtime===null){fail4("Child run dispatch needs a Runtime binding.")}const predecessorChildRunId=nullable2(body.predecessorChildRunId,each=>id3(each,"predecessorChildRunId"));const resultVersion=body.resultVersion;if(resultVersion!==1){fail4("Child run resultVersion must be 1 in schema version 1.")}const resultRef=nullable2(body.resultRef,each=>ref4(each,"resultRef"));const terminalReceiptRef=nullable2(body.terminalReceiptRef,each=>ref4(each,"terminalReceiptRef"));if(resultRef!==null!==(terminalReceiptRef!==null)){fail4("Child run resultRef and terminalReceiptRef change only together.")}if(resultRef!==null!==(run.state==="settled")){fail4("Child run resultRef and terminalReceiptRef are set exactly when the run settles.")}if((run.state==="failed"||run.state==="cancelled")!==(delivery.state==="cancelled")){fail4("Child run delivery cancelled is set exactly when the run ends without a result.")}const stopReason=stopReasonOf(body.stopReason,CHILD_AGENT_STOP_REASONS,run);const stopRequested=stopFlags(stopReason,body.stopRequested,run);if(run.state==="settled"&&run.execution!=="settled"){fail4("Child run settled needs its settled execution.")}if(run.state==="cancelled"&&run.execution!=="settled"&&run.execution!=="not_started_proven"){fail4("Child run cancelled needs settled or not_started_proven execution.")}if(run.state==="failed"&&run.execution!=="settled"&&run.execution!=="not_started_proven"){fail4("Child run failed needs settled or not_started_proven execution.")}if(stopReason==="creation_failed"&&run.execution!=="not_started_proven"){fail4("Child run creation_failed needs a creation that never started.")}if(stopReason==="child_failed"&&run.execution!=="settled"){fail4("Child run child_failed needs its settled execution.")}return Object.freeze({kind,childRunId:id3(body.childRunId,"childRunId"),ownerScopeId:id3(body.ownerScopeId,"ownerScopeId"),rootSessionId:id3(body.rootSessionId,"rootSessionId"),depth,completion,inputRef,workspaceMode,workingDirectory,childSessionId,predecessorChildRunId,resultVersion,resultRef,terminalReceiptRef,stopReason,stopRequested,run})}__name(parseChildSessionRun,"parseChildSessionRun");function isRelativeDirectory(value){if(value===".")return true;if(value.startsWith("/")||value.endsWith("/")||value.includes("\\")||/^[A-Za-z]:/.test(value)){return false}if(value.split("/").some(segment=>segment===""||segment==="."||segment==="..")){return false}try{assertManagedSessionStableId(value,"workingDirectory")}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}return true}__name(isRelativeDirectory,"isRelativeDirectory");function isChildRunStart(value){return accepts2(()=>{const record4=parseChildRun(value);if(!isExtensionRunStart(record4.run)||record4.stopRequested)return false;if(record4.kind==="shell")return record4.outputRef===null;return isChildSessionRun(record4)&&record4.run.delivery!==null&&record4.run.delivery.state==="planned"&&record4.childSessionId===null&&record4.resultRef===null&&record4.terminalReceiptRef===null})}__name(isChildRunStart,"isChildRunStart");function isChildRunSuccessor(previous,next){return accepts2(()=>{const before=parseChildRun(previous);const after=parseChildRun(next);if(before.kind!==after.kind)return false;if(before.kind==="shell"&&after.kind==="shell"){if(SHELL_FIXED_KEYS.some(key=>!same2(before[key],after[key]))||!isExtensionRunSuccessor(before.run,after.run)||before.outputRef!==null&&after.outputRef===null||before.stopRequested&&!after.stopRequested||!setOnce2(before.startReceiptRef,after.startReceiptRef)){return false}if(TERMINAL_RUN_STATES3.includes(before.run.state)){return same2(before,after)}return true}if(!isChildSessionRun(before)||!isChildSessionRun(after))return false;if(TERMINAL_RUN_STATES3.includes(before.run.state)){const beforeRest={...before,run:null};const afterRest={...after,run:null};return same2(beforeRest,afterRest)&&isExtensionRunSuccessor(before.run,after.run)}return CHILD_AGENT_FIXED_KEYS.every(key=>same2(before[key],after[key]))&&isExtensionRunSuccessor(before.run,after.run)&&(!before.stopRequested||after.stopRequested)&&setOnce2(before.childSessionId,after.childSessionId)})}__name(isChildRunSuccessor,"isChildRunSuccessor");var MANAGED_CHILD_LIMITS=Object.freeze({maxDepth:1,maxActivePerScope:4,maxLaunchesPerScope:64,maxEnvelopeBytes:32*1024,maxDescriptionBytes:512,maxResultBytes:64*1024});var MANAGED_CHILD_ADMITTED_WORKSPACE_MODES=Object.freeze(["shared","worktree","snapshot"]);function parsePublicChildModelRoute(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ManagedSessionRecordError("Invalid public child model route.")}const route=value;if(Object.keys(route).sort().join(",")!==(Object.hasOwn(route,"origin")?"authType,endpointDigest,origin,providerPin":"authType,endpointDigest,providerPin")||typeof route["authType"]!=="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(route["authType"])||typeof route["endpointDigest"]!=="string"||!/^[a-f0-9]{64}$/.test(route["endpointDigest"])||typeof route["providerPin"]!=="string"||!/^[a-f0-9]{64}$/.test(route["providerPin"])){throw new ManagedSessionRecordError("Invalid public child model route.")}let origin;if(Object.hasOwn(route,"origin")){const value2=route["origin"];if(!value2||typeof value2!=="object"||Array.isArray(value2))throw new ManagedSessionRecordError("Invalid public child model origin.");const source=value2;if(Object.keys(source).sort().join(",")!=="authType,endpointDigest,modelId,providerPin"||typeof source["modelId"]!=="string"||!source["modelId"].trim()||Buffer.byteLength(source["modelId"])>512)throw new ManagedSessionRecordError("Invalid public child model origin.");origin=Object.freeze({modelId:source["modelId"],...parsePublicChildModelRoute({authType:source["authType"],endpointDigest:source["endpointDigest"],providerPin:source["providerPin"]})})}return Object.freeze({authType:route["authType"],endpointDigest:route["endpointDigest"],providerPin:route["providerPin"],...origin?{origin}:{}})}__name(parsePublicChildModelRoute,"parsePublicChildModelRoute");function parsePublicChildExtensionAgent(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedSessionRecordError("Invalid extension agent descriptor.");const fields=value;if(Object.keys(fields).sort().join(",")!=="agentName,bundleRef,configRevision,contributionsRef,pin,toolNames"||!Number.isSafeInteger(fields["configRevision"])||Number(fields["configRevision"])<1||typeof fields["agentName"]!=="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/u.test(fields["agentName"])||!Array.isArray(fields["toolNames"])||fields["toolNames"].length>256||fields["toolNames"].some(name2=>typeof name2!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(name2))||new Set(fields["toolNames"]).size!==fields["toolNames"].length)throw new ManagedSessionRecordError("Invalid extension agent descriptor.");const bundleRef=assertManagedSessionDurableRef(fields["bundleRef"],"extension agent bundle");const contributionsRef=assertManagedSessionDurableRef(fields["contributionsRef"],"extension agent contributions");if(bundleRef.kind!=="managed-extension-config-bundle"||bundleRef.schemaVersion!==1||contributionsRef.kind!=="managed-extension-contributions"||contributionsRef.schemaVersion!==1)throw new ManagedSessionRecordError("Invalid extension agent references.");return Object.freeze({configRevision:fields["configRevision"],bundleRef,pin:parseManagedExtensionPin(fields["pin"]),contributionsRef,agentName:fields["agentName"],toolNames:Object.freeze([...fields["toolNames"]])})}__name(parsePublicChildExtensionAgent,"parsePublicChildExtensionAgent");function parsePublicChildLaunch(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ManagedSessionRecordError("Invalid public child launch snapshot.")}const fields=value;if(Object.keys(fields).sort().join(",")!==(fields["version"]===2?"approvalMode,approvalRevision,extensionAgent,modelId,modelRevision,modelRoute,skillsRef,sourcePromptId,version":"approvalMode,approvalRevision,modelId,modelRevision,modelRoute,skillsRef,sourcePromptId,version")||fields["version"]!==1&&fields["version"]!==2||typeof fields["sourcePromptId"]!=="string"||!fields["sourcePromptId"].trim()||fields["sourcePromptId"].length>144||typeof fields["approvalMode"]!=="string"||!["default","auto-edit","yolo"].includes(fields["approvalMode"])||typeof fields["modelId"]!=="string"||!fields["modelId"].trim()||Buffer.byteLength(fields["modelId"],"utf8")>512||!Number.isSafeInteger(fields["approvalRevision"])||fields["approvalRevision"]<0||!Number.isSafeInteger(fields["modelRevision"])||fields["modelRevision"]<0){throw new ManagedSessionRecordError("Invalid public child launch snapshot.")}parsePublicChildModelRoute(fields["modelRoute"]);if(fields["version"]===2)parsePublicChildExtensionAgent(fields["extensionAgent"]);if(fields["skillsRef"]!==null){const ref11=assertManagedSessionDurableRef(fields["skillsRef"],"child Skills");if(ref11.kind!=="managed-agent-skills"||ref11.schemaVersion!==1){throw new ManagedSessionRecordError("Invalid public child Skills snapshot.")}}return Object.freeze({...fields})}__name(parsePublicChildLaunch,"parsePublicChildLaunch");function encodeChildLaunchEnvelope(envelope2){if(Buffer.byteLength(envelope2.description,"utf8")>MANAGED_CHILD_LIMITS.maxDescriptionBytes){throw new ManagedSessionRecordError(`Child launch description exceeds ${MANAGED_CHILD_LIMITS.maxDescriptionBytes} bytes (byte_limit).`)}const bytes=Buffer.from(JSON.stringify({description:envelope2.description,prompt:envelope2.prompt,definition:envelope2.definition,...envelope2.publicLaunch===void 0?{}:{publicLaunch:parsePublicChildLaunch(envelope2.publicLaunch)}}),"utf8");if(bytes.byteLength>MANAGED_CHILD_LIMITS.maxEnvelopeBytes){throw new ManagedSessionRecordError(`Child launch envelope exceeds ${MANAGED_CHILD_LIMITS.maxEnvelopeBytes} bytes (byte_limit).`)}return bytes}__name(encodeChildLaunchEnvelope,"encodeChildLaunchEnvelope");function decodeChildLaunchEnvelope(bytes){let value;try{value=JSON.parse(bytes.toString("utf8"))}catch{throw new ManagedSessionRecordError("Child launch envelope must be JSON.")}if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype){throw new ManagedSessionRecordError("Child launch envelope must be a JSON object.")}const record4=value;const keys2=Object.keys(record4).sort();if(keys2.join(",")!=="definition,description,prompt"&&keys2.join(",")!=="definition,description,prompt,publicLaunch"){throw new ManagedSessionRecordError("Child launch envelope must have exactly description, prompt and definition.")}if(typeof record4["description"]!=="string"||typeof record4["prompt"]!=="string"){throw new ManagedSessionRecordError("Child launch description and prompt must be text.")}const definition=record4["definition"];if(typeof definition!=="object"||definition===null||typeof definition["definitionId"]!=="string"||typeof definition["definitionRevision"]!=="number"||typeof definition["definitionDigest"]!=="string"){throw new ManagedSessionRecordError("Child launch definition must pin an id, a revision and a digest.")}return Object.freeze({description:record4["description"],prompt:record4["prompt"],definition:Object.freeze({...definition}),...record4["publicLaunch"]===void 0?{}:{publicLaunch:parsePublicChildLaunch(record4["publicLaunch"])}})}__name(decodeChildLaunchEnvelope,"decodeChildLaunchEnvelope");function encodeWorkflowLaunchEnvelope(envelope2){let serialized;try{serialized=JSON.stringify({definition:envelope2.definition,script:envelope2.script,args:envelope2.args??null},(_key,value)=>{if(typeof value==="function"||typeof value==="symbol"||typeof value==="number"&&!Number.isFinite(value)){throw new ManagedSessionRecordError("Workflow launch arguments must be JSON values (byte_limit).")}return value})}catch(cause){if(cause instanceof ManagedSessionRecordError){throw cause}throw new ManagedSessionRecordError("Workflow launch arguments must be JSON-serializable (byte_limit).")}const bytes=Buffer.from(serialized,"utf8");if(bytes.byteLength>MANAGED_CHILD_LIMITS.maxEnvelopeBytes){throw new ManagedSessionRecordError(`Workflow launch envelope exceeds ${MANAGED_CHILD_LIMITS.maxEnvelopeBytes} bytes (byte_limit).`)}return bytes}__name(encodeWorkflowLaunchEnvelope,"encodeWorkflowLaunchEnvelope");function admitChildLaunch(params){if(params.closing)return{admitted:false,reason:"closing"};if(!MANAGED_CHILD_ADMITTED_WORKSPACE_MODES.includes(params.workspaceMode)||params.workspaceMode==="worktree"&&!params.childWorkspaces||params.workspaceMode==="snapshot"&&!(params.childWorkspaces&&params.childSnapshots)){return{admitted:false,reason:"workspace_mode"}}if(!params.sameDefinition){return{admitted:false,reason:"definition_scope"}}if(params.depth>MANAGED_CHILD_LIMITS.maxDepth){return{admitted:false,reason:"depth_limit"}}if(params.launchedInScope>=MANAGED_CHILD_LIMITS.maxLaunchesPerScope){return{admitted:false,reason:"budget_exhausted"}}if(params.activeInScope>=MANAGED_CHILD_LIMITS.maxActivePerScope){return{admitted:false,reason:"count_limit"}}if(params.envelopeBytes>MANAGED_CHILD_LIMITS.maxEnvelopeBytes){return{admitted:false,reason:"byte_limit"}}return{admitted:true}}__name(admitChildLaunch,"admitChildLaunch");function childLaunchBody(params){return Object.freeze({kind:"child_agent",childRunId:params.childRunId,ownerScopeId:params.ownerScopeId,rootSessionId:params.rootSessionId,depth:1,completion:params.completion,inputRef:params.inputRef,workspaceMode:params.workspaceMode,workingDirectory:params.workingDirectory,childSessionId:null,predecessorChildRunId:null,resultVersion:1,resultRef:null,terminalReceiptRef:null,stopReason:null,stopRequested:false,run:Object.freeze({state:"admitted",reason:null,definition:Object.freeze({...params.definition}),executionCallId:params.executionCallId,effectId:null,dispatchId:null,deliveryId:null,execution:"intent",runtime:null,delivery:Object.freeze({target:"session",state:"planned"})})})}__name(childLaunchBody,"childLaunchBody");function workflowLaunchBody(params){return Object.freeze({...childLaunchBody({...params,workspaceMode:"shared"}),kind:"workflow"})}__name(workflowLaunchBody,"workflowLaunchBody");function childContinuationBody(predecessor,params){const launch=childLaunchBody({childRunId:params.childRunId,ownerScopeId:predecessor.ownerScopeId,rootSessionId:predecessor.rootSessionId,completion:params.completion,inputRef:params.inputRef,workspaceMode:predecessor.workspaceMode,workingDirectory:predecessor.workingDirectory,executionCallId:params.executionCallId,definition:predecessor.run.definition});return Object.freeze({...launch,kind:predecessor.kind,depth:predecessor.depth,predecessorChildRunId:predecessor.childRunId})}__name(childContinuationBody,"childContinuationBody");function childDispatchBody(previous,params){return Object.freeze({...previous,run:Object.freeze({...previous.run,state:"running",dispatchId:params.dispatchId,execution:"dispatch_started",runtime:Object.freeze({...params.runtime})})})}__name(childDispatchBody,"childDispatchBody");function childAttachBody(previous,params){return Object.freeze({...previous,childSessionId:params.childSessionId,run:Object.freeze({...previous.run,execution:"running_attached"})})}__name(childAttachBody,"childAttachBody");function childSettleCompletedBody(previous,params){return Object.freeze({...previous,stopReason:"completed",resultRef:params.resultRef,terminalReceiptRef:params.terminalReceiptRef,run:Object.freeze({...previous.run,state:"settled",execution:"settled",delivery:Object.freeze({target:"session",state:"accepting"})})})}__name(childSettleCompletedBody,"childSettleCompletedBody");function adoptChildSessionId(previous,childSessionId,verb){if(childSessionId===void 0)return previous.childSessionId;if(previous.childSessionId!==null&&previous.childSessionId!==childSessionId){throw new ManagedSessionRecordError(`Child run ${verb} cannot rename the Session it already named.`)}return childSessionId}__name(adoptChildSessionId,"adoptChildSessionId");function childFailBody(previous,params){return Object.freeze({...previous,stopReason:params.stopReason,childSessionId:adoptChildSessionId(previous,params.childSessionId,"failure"),run:Object.freeze({...previous.run,state:"failed",reason:params.reason,execution:params.started?"settled":"not_started_proven",delivery:Object.freeze({target:"session",state:"cancelled"})})})}__name(childFailBody,"childFailBody");function childStopRequestedBody(previous){return Object.freeze({...previous,stopRequested:true})}__name(childStopRequestedBody,"childStopRequestedBody");function childCancelBody(previous,params){return Object.freeze({...previous,stopReason:"stop_requested",stopRequested:true,childSessionId:adoptChildSessionId(previous,params.childSessionId,"close"),run:Object.freeze({...previous.run,state:"cancelled",execution:params.started?"settled":"not_started_proven",delivery:Object.freeze({target:"session",state:"cancelled"})})})}__name(childCancelBody,"childCancelBody");function childRecoveryBlockedBody(previous,params){return Object.freeze({...previous,childSessionId:adoptChildSessionId(previous,params.childSessionId,"recovery_blocked"),run:Object.freeze({...previous.run,state:"recovery_blocked",reason:params.reason,execution:"outcome_unknown"})})}__name(childRecoveryBlockedBody,"childRecoveryBlockedBody");function childDeliveryBody(previous,state){return Object.freeze({...previous,run:Object.freeze({...previous.run,delivery:Object.freeze({target:"session",state})})})}__name(childDeliveryBody,"childDeliveryBody");function childAcceptanceBody(child,params){return Object.freeze({childRunId:child.childRunId,parentScopeId:child.ownerScopeId,parentExecutionCallId:child.completion==="tool"?child.run.executionCallId:null,resultVersion:child.resultVersion,contentRef:params.contentRef,contentDigest:params.contentRef.digest,terminalReceiptRef:params.terminalReceiptRef,run:Object.freeze({state:"settled",reason:null,definition:null,executionCallId:null,effectId:null,dispatchId:null,deliveryId:null,execution:null,runtime:null,delivery:Object.freeze({target:"session",state:"accepted"})})})}__name(childAcceptanceBody,"childAcceptanceBody");function childAcceptanceConsumedBody(previous){return Object.freeze({...previous,run:Object.freeze({...previous.run,delivery:Object.freeze({target:"session",state:"consumed"})})})}__name(childAcceptanceConsumedBody,"childAcceptanceConsumedBody");init_esbuild_shims();var HARNESS_CHECKPOINT_SCHEMA_VERSION=1;var HARNESS_CHECKPOINT_PHASES=["before_model","model_output_committed","await_action","await_runtime","await_agent","await_command","results_ready","turn_settled"];var HARNESS_MODEL_START_PHASES=new Set(["before_model","model_output_committed","results_ready","turn_settled"]);var HARNESS_TURN_COMPLETE_BOUNDARY="turn_complete";var HARNESS_DURABLE_WAIT_BOUNDARY="durable_wait";var HARNESS_ACTION_SOURCES=["tool_call","automation_run","team_plan","user_operation"];var HARNESS_TOOL_ITEM_STATES=["not_started","in_progress","settled"];var HARNESS_TOOL_OUTCOME_SOURCES=["runtime","orchestration","domain"];var HARNESS_RUNTIME_STATES=["dispatch","settled","committed"];var HARNESS_APPROVAL_STATES=["requested","decided","cancelled","expired"];var HARNESS_ATTEMPT_OUTPUT_STATES=["started","output_committed","abandoned"];var ROOT_KEYS=["identity","resume","continuation","attempt","tools","runtime","approval","agentWait","commandWait","commandLock","output","followUp"];function fail5(message){throw new ManagedSessionRecordError(message)}__name(fail5,"fail");function object4(value,label){if(value===null||typeof value!=="object"||Array.isArray(value)){fail5(`${label} must be a JSON object.`)}return value}__name(object4,"object");function assertNoUnknownKeys(input,allowed,label){for(const key of Object.keys(input)){if(!allowed.includes(key)){fail5(`${label} has the unknown field "${key}".`)}}}__name(assertNoUnknownKeys,"assertNoUnknownKeys");function oneOf2(value,allowed,label){if(typeof value!=="string"||!allowed.includes(value)){fail5(`${label} must be one of ${allowed.join(", ")}.`)}return value}__name(oneOf2,"oneOf");function idOrNull(value,label){if(value===null)return null;return assertManagedSessionStableId(value,label)}__name(idOrNull,"idOrNull");function refOrNull(value,label){if(value===null)return null;return assertManagedSessionDurableRef(value,label)}__name(refOrNull,"refOrNull");function sequenceOrNull(value,label){if(value===null)return null;return assertManagedSessionSequence(value,label)}__name(sequenceOrNull,"sequenceOrNull");function jsonArray(value,label){if(!Array.isArray(value)){fail5(`${label} must be a JSON array.`)}return value}__name(jsonArray,"jsonArray");function idList(value,label){return jsonArray(value,label).map((item,index)=>assertManagedSessionStableId(item,`${label}[${index}]`))}__name(idList,"idList");function uniqueIds(ids,label){const seen=new Set;for(const id6 of ids){if(seen.has(id6)){fail5(`${label} repeats "${id6}".`)}seen.add(id6)}}__name(uniqueIds,"uniqueIds");function parseIdentity(value){const record4=object4(value,"identity");assertNoUnknownKeys(record4,["schemaVersion","sessionKey","engine","checkpointId","coveredSequence","activationId","turnId","promptId","definitionRevision","configRevision","inputDigest","previousCheckpointId"],"identity");if(record4["schemaVersion"]!==HARNESS_CHECKPOINT_SCHEMA_VERSION){fail5("identity.schemaVersion must be 1.")}if(record4["engine"]!=="managed"){fail5("identity.engine must be managed.")}return{schemaVersion:HARNESS_CHECKPOINT_SCHEMA_VERSION,sessionKey:assertManagedSessionKey(record4["sessionKey"],"identity.sessionKey"),engine:"managed",checkpointId:assertManagedSessionStableId(record4["checkpointId"],"identity.checkpointId"),coveredSequence:assertManagedSessionSequence(record4["coveredSequence"],"identity.coveredSequence"),activationId:assertManagedSessionStableId(record4["activationId"],"identity.activationId"),turnId:idOrNull(record4["turnId"],"identity.turnId"),promptId:idOrNull(record4["promptId"],"identity.promptId"),definitionRevision:assertManagedSessionStableId(record4["definitionRevision"],"identity.definitionRevision"),configRevision:assertManagedSessionStableId(record4["configRevision"],"identity.configRevision"),inputDigest:assertManagedSessionDigest(record4["inputDigest"],"identity.inputDigest"),previousCheckpointId:idOrNull(record4["previousCheckpointId"],"identity.previousCheckpointId")}}__name(parseIdentity,"parseIdentity");function parseRecording(value){const record4=object4(value,"resume.recording");assertNoUnknownKeys(record4,["lastCompletedUuid","turnParentUuids","parentSessionId","sourceType","sourceId","lastAssistantModel","executionEngine"],"resume.recording");if(record4["executionEngine"]!=="managed"){fail5("resume.recording.executionEngine must be managed.")}return{lastCompletedUuid:idOrNull(record4["lastCompletedUuid"],"resume.recording.lastCompletedUuid"),turnParentUuids:idList(record4["turnParentUuids"],"resume.recording.turnParentUuids"),parentSessionId:idOrNull(record4["parentSessionId"],"resume.recording.parentSessionId"),sourceType:idOrNull(record4["sourceType"],"resume.recording.sourceType"),sourceId:idOrNull(record4["sourceId"],"resume.recording.sourceId"),lastAssistantModel:idOrNull(record4["lastAssistantModel"],"resume.recording.lastAssistantModel"),executionEngine:"managed"}}__name(parseRecording,"parseRecording");function parseResume(value,coveredSequence){const record4=object4(value,"resume");assertNoUnknownKeys(record4,["source","throughSequence","recording","initialTurn","consumedNotificationIds","apiHistoryRef","fileHistoryRef","artifactRef","goalRecordsRef","goalCheckpointWindowRef","tokenCountsRef","uiTelemetryRef","attributionRef","goalRecoverySourceUuid"],"resume");if(record4["source"]!=="session_log"){fail5("resume.source must be session_log.")}const throughSequence=assertManagedSessionSequence(record4["throughSequence"],"resume.throughSequence");if(throughSequence!==coveredSequence){fail5("resume.throughSequence must equal identity.coveredSequence.")}const consumedNotificationIds=idList(record4["consumedNotificationIds"],"resume.consumedNotificationIds");uniqueIds(consumedNotificationIds,"resume.consumedNotificationIds");return{source:"session_log",throughSequence,recording:parseRecording(record4["recording"]),initialTurn:assertManagedSessionSequence(record4["initialTurn"],"resume.initialTurn"),consumedNotificationIds,apiHistoryRef:refOrNull(record4["apiHistoryRef"],"resume.apiHistoryRef"),fileHistoryRef:refOrNull(record4["fileHistoryRef"],"resume.fileHistoryRef"),artifactRef:refOrNull(record4["artifactRef"],"resume.artifactRef"),goalRecordsRef:refOrNull(record4["goalRecordsRef"],"resume.goalRecordsRef"),goalCheckpointWindowRef:refOrNull(record4["goalCheckpointWindowRef"],"resume.goalCheckpointWindowRef"),tokenCountsRef:refOrNull(record4["tokenCountsRef"],"resume.tokenCountsRef"),uiTelemetryRef:refOrNull(record4["uiTelemetryRef"],"resume.uiTelemetryRef"),attributionRef:refOrNull(record4["attributionRef"],"resume.attributionRef"),goalRecoverySourceUuid:idOrNull(record4["goalRecoverySourceUuid"],"resume.goalRecoverySourceUuid")}}__name(parseResume,"parseResume");function parseContinuation(value){const record4=object4(value,"continuation");assertNoUnknownKeys(record4,["phase","pendingEventIds"],"continuation");const pendingEventIds=idList(record4["pendingEventIds"],"continuation.pendingEventIds");uniqueIds(pendingEventIds,"continuation.pendingEventIds");return{phase:oneOf2(record4["phase"],HARNESS_CHECKPOINT_PHASES,"continuation.phase"),pendingEventIds}}__name(parseContinuation,"parseContinuation");function parseAttempt(value){if(value===null)return null;const record4=object4(value,"attempt");assertNoUnknownKeys(record4,["attemptId","routeRef","capabilityRef","samplingRef","outputState","usageRef","budgetConsumed"],"attempt");const outputState=oneOf2(record4["outputState"],HARNESS_ATTEMPT_OUTPUT_STATES,"attempt.outputState");const usageRef=refOrNull(record4["usageRef"],"attempt.usageRef");if(outputState==="started"&&usageRef!==null){fail5("attempt.usageRef must be null while outputState is started.")}return{attemptId:assertManagedSessionStableId(record4["attemptId"],"attempt.attemptId"),routeRef:assertManagedSessionDurableRef(record4["routeRef"],"attempt.routeRef"),capabilityRef:refOrNull(record4["capabilityRef"],"attempt.capabilityRef"),samplingRef:refOrNull(record4["samplingRef"],"attempt.samplingRef"),outputState,usageRef,budgetConsumed:assertManagedSessionSequence(record4["budgetConsumed"],"attempt.budgetConsumed")}}__name(parseAttempt,"parseAttempt");function parseToolItem(value,label){const record4=object4(value,label);assertNoUnknownKeys(record4,["functionCallId","toolName","executionCallId","modelMessageId","partIndex","ordinal","inputDigest","outcomeSource","state","outcomeRef","consumed"],label);const state=oneOf2(record4["state"],HARNESS_TOOL_ITEM_STATES,`${label}.state`);const outcomeRef=refOrNull(record4["outcomeRef"],`${label}.outcomeRef`);if(state==="settled"&&outcomeRef===null){fail5(`${label}.outcomeRef is required once the item is settled.`)}if(state!=="settled"&&outcomeRef!==null){fail5(`${label}.outcomeRef must be null until the item is settled.`)}if(typeof record4["consumed"]!=="boolean"){fail5(`${label}.consumed must be a boolean.`)}if(record4["consumed"]&&state!=="settled"){fail5(`${label} cannot be consumed before it is settled.`)}return{functionCallId:assertManagedSessionStableId(record4["functionCallId"],`${label}.functionCallId`),toolName:assertManagedSessionStableId(record4["toolName"],`${label}.toolName`),executionCallId:assertManagedSessionStableId(record4["executionCallId"],`${label}.executionCallId`),modelMessageId:assertManagedSessionStableId(record4["modelMessageId"],`${label}.modelMessageId`),partIndex:assertManagedSessionSequence(record4["partIndex"],`${label}.partIndex`),ordinal:assertManagedSessionSequence(record4["ordinal"],`${label}.ordinal`),inputDigest:assertManagedSessionDigest(record4["inputDigest"],`${label}.inputDigest`),outcomeSource:oneOf2(record4["outcomeSource"],HARNESS_TOOL_OUTCOME_SOURCES,`${label}.outcomeSource`),state,outcomeRef,consumed:record4["consumed"]}}__name(parseToolItem,"parseToolItem");function parseTools(value){if(value===null)return null;const record4=object4(value,"tools");assertNoUnknownKeys(record4,["batchId","items"],"tools");const items=jsonArray(record4["items"],"tools.items").map((item,index)=>parseToolItem(item,`tools.items[${index}]`));uniqueIds(items.map(item=>item.executionCallId),"tools.items.executionCallId");uniqueIds(items.map(item=>item.functionCallId),"tools.items.functionCallId");const ordinals=new Set;for(const item of items){if(ordinals.has(item.ordinal)){fail5(`tools.items repeats ordinal ${item.ordinal}.`)}ordinals.add(item.ordinal)}return{batchId:idOrNull(record4["batchId"],"tools.batchId"),items}}__name(parseTools,"parseTools");function parseRuntimeBinding(value,label){const record4=object4(value,label);assertNoUnknownKeys(record4,["executionCallId","invocationBindingId","capabilityVersion","policyVersion","mediaVersion","state","progressCursor"],label);return{executionCallId:assertManagedSessionStableId(record4["executionCallId"],`${label}.executionCallId`),invocationBindingId:assertManagedSessionStableId(record4["invocationBindingId"],`${label}.invocationBindingId`),capabilityVersion:assertManagedSessionStableId(record4["capabilityVersion"],`${label}.capabilityVersion`),policyVersion:assertManagedSessionStableId(record4["policyVersion"],`${label}.policyVersion`),mediaVersion:idOrNull(record4["mediaVersion"],`${label}.mediaVersion`),state:oneOf2(record4["state"],HARNESS_RUNTIME_STATES,`${label}.state`),progressCursor:idOrNull(record4["progressCursor"],`${label}.progressCursor`)}}__name(parseRuntimeBinding,"parseRuntimeBinding");function parseRuntime(value){if(value===null)return null;const record4=object4(value,"runtime");assertNoUnknownKeys(record4,["bindings"],"runtime");const bindings=jsonArray(record4["bindings"],"runtime.bindings").map((item,index)=>parseRuntimeBinding(item,`runtime.bindings[${index}]`));uniqueIds(bindings.map(item=>item.executionCallId),"runtime.bindings.executionCallId");uniqueIds(bindings.map(item=>item.invocationBindingId),"runtime.bindings.invocationBindingId");return{bindings}}__name(parseRuntime,"parseRuntime");function parseApproval(value){if(value===null)return null;const record4=object4(value,"approval");assertNoUnknownKeys(record4,["requestId","kind","source","optionsRef","inputRevision","confirmationVersion","state","decisionRef","invocationRef"],"approval");const state=oneOf2(record4["state"],HARNESS_APPROVAL_STATES,"approval.state");const source=oneOf2(record4["source"],HARNESS_ACTION_SOURCES,"approval.source");const decisionRef=refOrNull(record4["decisionRef"],"approval.decisionRef");if(state==="decided"&&decisionRef===null){fail5("approval.decisionRef is required once the approval is decided.")}if(state!=="decided"&&decisionRef!==null){fail5("approval.decisionRef must be null until the approval is decided.")}const invocationRef=refOrNull(record4["invocationRef"],"approval.invocationRef");if(source==="tool_call"&&invocationRef===null){fail5("approval.invocationRef is required for a tool_call approval.")}if(source==="user_operation"&&invocationRef!==null){fail5("approval.invocationRef must be null for a user_operation approval.")}return{requestId:assertManagedSessionStableId(record4["requestId"],"approval.requestId"),kind:assertManagedSessionStableId(record4["kind"],"approval.kind"),source,optionsRef:assertManagedSessionDurableRef(record4["optionsRef"],"approval.optionsRef"),inputRevision:assertManagedSessionStableId(record4["inputRevision"],"approval.inputRevision"),confirmationVersion:idOrNull(record4["confirmationVersion"],"approval.confirmationVersion"),state,decisionRef,invocationRef}}__name(parseApproval,"parseApproval");function parseAgentWaitRun(value,label){const record4=object4(value,label);assertNoUnknownKeys(record4,["childRunId","functionCallId","toolName","modelMessageId","consumed"],label);if(typeof record4["consumed"]!=="boolean"){fail5(`${label}.consumed must be a boolean.`)}return{childRunId:assertManagedSessionStableId(record4["childRunId"],`${label}.childRunId`),functionCallId:assertManagedSessionStableId(record4["functionCallId"],`${label}.functionCallId`),toolName:assertManagedSessionStableId(record4["toolName"],`${label}.toolName`),modelMessageId:assertManagedSessionStableId(record4["modelMessageId"],`${label}.modelMessageId`),consumed:record4["consumed"]}}__name(parseAgentWaitRun,"parseAgentWaitRun");function parseAgentWait(value){if(value===null)return null;const record4=object4(value,"agentWait");assertNoUnknownKeys(record4,["runs"],"agentWait");const runs=jsonArray(record4["runs"],"agentWait.runs").map((item,index)=>parseAgentWaitRun(item,`agentWait.runs[${index}]`));if(runs.length===0){fail5("agent wait requires at least one run.")}uniqueIds(runs.map(run=>run.childRunId),"agentWait.runs.childRunId");uniqueIds(runs.map(run=>run.functionCallId),"agentWait.runs.functionCallId");return{runs}}__name(parseAgentWait,"parseAgentWait");function parseCommandWaitRun(value,label){const record4=object4(value,label);assertNoUnknownKeys(record4,["commandId","functionCallId","toolName","modelMessageId","folded"],label);if(typeof record4["folded"]!=="boolean"){fail5(`${label}.folded must be a boolean.`)}return{commandId:assertManagedSessionStableId(record4["commandId"],`${label}.commandId`),functionCallId:assertManagedSessionStableId(record4["functionCallId"],`${label}.functionCallId`),toolName:assertManagedSessionStableId(record4["toolName"],`${label}.toolName`),modelMessageId:assertManagedSessionStableId(record4["modelMessageId"],`${label}.modelMessageId`),folded:record4["folded"]}}__name(parseCommandWaitRun,"parseCommandWaitRun");function parseCommandWait(value){if(value===null)return null;const record4=object4(value,"commandWait");assertNoUnknownKeys(record4,["runs","holdsWorkspaceMount"],"commandWait");const runs=jsonArray(record4["runs"],"commandWait.runs").map((item,index)=>parseCommandWaitRun(item,`commandWait.runs[${index}]`));if(runs.length===0){fail5("command wait requires at least one run.")}uniqueIds(runs.map(run=>run.commandId),"commandWait.runs.commandId");uniqueIds(runs.map(run=>run.functionCallId),"commandWait.runs.functionCallId");const mount=record4["holdsWorkspaceMount"];if(typeof mount!=="boolean"){fail5("commandWait.holdsWorkspaceMount must be a boolean.")}return{runs,holdsWorkspaceMount:mount}}__name(parseCommandWait,"parseCommandWait");function parseCommandLock(value){if(value===null)return null;const record4=object4(value,"commandLock");assertNoUnknownKeys(record4,["turnId"],"commandLock");return{turnId:assertManagedSessionStableId(record4["turnId"],"commandLock.turnId")}}__name(parseCommandLock,"parseCommandLock");function carriedCommandLock(previous){const lock=previous.commandLock;return lock!==null&&lock.turnId===previous.identity.turnId?lock:null}__name(carriedCommandLock,"carriedCommandLock");function harnessCommandLockOf(checkpoint){if(checkpoint.identity.turnId===null){throw new ManagedSessionRecordError("a command timeout lock requires the Turn it binds.")}return{turnId:checkpoint.identity.turnId}}__name(harnessCommandLockOf,"harnessCommandLockOf");function harnessCommandLocked(checkpoint,turnId){return checkpoint.commandLock?.turnId===turnId}__name(harnessCommandLocked,"harnessCommandLocked");function parseParentHistory(value){if(value===null)return null;const record4=object4(value,"output.parentHistory");assertNoUnknownKeys(record4,["bindingId","revision"],"output.parentHistory");return{bindingId:assertManagedSessionStableId(record4["bindingId"],"output.parentHistory.bindingId"),revision:assertManagedSessionSequence(record4["revision"],"output.parentHistory.revision")}}__name(parseParentHistory,"parseParentHistory");function parseOutput(value){const record4=object4(value,"output");assertNoUnknownKeys(record4,["llmContentRef","physicalStatus","hookResultRef","mediaRefs","parentHistory"],"output");return{llmContentRef:refOrNull(record4["llmContentRef"],"output.llmContentRef"),physicalStatus:idOrNull(record4["physicalStatus"],"output.physicalStatus"),hookResultRef:refOrNull(record4["hookResultRef"],"output.hookResultRef"),mediaRefs:jsonArray(record4["mediaRefs"],"output.mediaRefs").map((item,index)=>assertManagedSessionDurableRef(item,`output.mediaRefs[${index}]`)),parentHistory:parseParentHistory(record4["parentHistory"])}}__name(parseOutput,"parseOutput");function parseFollowUp(value){const record4=object4(value,"followUp");assertNoUnknownKeys(record4,["pendingInputIds","cancelRequestIds","goalPermitIds","cronIds","notificationIds","childRunIds","stopBudgetRemaining","scopeLineage"],"followUp");const pendingInputIds=idList(record4["pendingInputIds"],"followUp.pendingInputIds");const cancelRequestIds=idList(record4["cancelRequestIds"],"followUp.cancelRequestIds");const goalPermitIds=idList(record4["goalPermitIds"],"followUp.goalPermitIds");const cronIds=idList(record4["cronIds"],"followUp.cronIds");const notificationIds=idList(record4["notificationIds"],"followUp.notificationIds");const childRunIds=idList(record4["childRunIds"],"followUp.childRunIds");uniqueIds(pendingInputIds,"followUp.pendingInputIds");uniqueIds(cancelRequestIds,"followUp.cancelRequestIds");uniqueIds(goalPermitIds,"followUp.goalPermitIds");uniqueIds(cronIds,"followUp.cronIds");uniqueIds(notificationIds,"followUp.notificationIds");uniqueIds(childRunIds,"followUp.childRunIds");return{pendingInputIds,cancelRequestIds,goalPermitIds,cronIds,notificationIds,childRunIds,stopBudgetRemaining:sequenceOrNull(record4["stopBudgetRemaining"],"followUp.stopBudgetRemaining"),scopeLineage:idList(record4["scopeLineage"],"followUp.scopeLineage")}}__name(parseFollowUp,"parseFollowUp");function toolItems(tools){return tools?.items??[]}__name(toolItems,"toolItems");function runtimeBindings(runtime){return runtime?.bindings??[]}__name(runtimeBindings,"runtimeBindings");function assertRuntimeMatchesTools(tools,runtime){const calls=new Set(toolItems(tools).map(item=>item.executionCallId));for(const binding of runtimeBindings(runtime)){if(!calls.has(binding.executionCallId)){fail5(`runtime binding ${binding.executionCallId} has no matching tool item.`)}}}__name(assertRuntimeMatchesTools,"assertRuntimeMatchesTools");function assertPhaseShape(checkpoint){const{phase}=checkpoint.continuation;const items=toolItems(checkpoint.tools);const bindings=runtimeBindings(checkpoint.runtime);const inFlightTools=items.some(item=>item.state==="in_progress");const unsettledTools=items.some(item=>item.state!=="settled");const dispatchRuntime=bindings.some(item=>item.state==="dispatch");if(phase==="before_model"){if(checkpoint.attempt!==null){fail5("before_model cannot carry a model attempt.")}if(items.length>0||bindings.length>0){fail5("before_model cannot carry tools or runtime bindings.")}if(checkpoint.approval!==null){fail5("before_model cannot carry an approval.")}if(checkpoint.agentWait!==null){fail5("before_model cannot carry an agent wait.")}if(checkpoint.commandWait!==null){fail5("before_model cannot carry a command wait.")}return}if(checkpoint.attempt===null){fail5(`${phase} requires a model attempt.`)}if(checkpoint.attempt.outputState==="started"){fail5("an in-flight model stream is not a runnable checkpoint phase.")}if(phase==="model_output_committed"){if(checkpoint.attempt.outputState!=="output_committed"){fail5("model_output_committed requires outputState output_committed.")}if(checkpoint.approval!==null){fail5("model_output_committed cannot carry an approval.")}if(inFlightTools||dispatchRuntime){fail5("model_output_committed cannot carry in-flight tools.")}if(checkpoint.agentWait!==null&&checkpoint.agentWait.runs.some(run=>!run.consumed)){fail5("model_output_committed cannot carry an unconsumed agent wait.")}if(checkpoint.commandWait!==null&&checkpoint.commandWait.runs.some(run=>!run.folded)){fail5("model_output_committed cannot carry an unfolded command wait.")}return}if(phase==="await_action"){if(checkpoint.approval===null||checkpoint.approval.state!=="requested"){fail5("await_action requires a requested approval.")}if(checkpoint.approval.source==="user_operation"&&bindings.length>0){fail5("a user_operation approval cannot carry runtime bindings.")}if(checkpoint.agentWait!==null){fail5("await_action cannot carry an agent wait.")}if(checkpoint.commandWait!==null){fail5("await_action cannot carry a command wait.")}return}if(phase==="await_runtime"){if(!inFlightTools||!dispatchRuntime){fail5("await_runtime requires in-progress tools and dispatch bindings.")}if(checkpoint.approval?.state==="requested"){fail5("await_runtime cannot keep a requested approval.")}if(checkpoint.agentWait!==null){fail5("await_runtime cannot carry an agent wait.")}if(checkpoint.commandWait!==null){fail5("await_runtime cannot carry a command wait.")}return}if(phase==="await_agent"){if(checkpoint.agentWait===null||checkpoint.agentWait.runs.length===0){fail5("await_agent requires the agent wait runs.")}if(checkpoint.agentWait.runs.every(run=>run.consumed)){fail5("await_agent cannot keep an all-consumed agent wait.")}if(checkpoint.approval?.state==="requested"){fail5("await_agent cannot keep a requested approval.")}if(inFlightTools||dispatchRuntime){fail5("await_agent cannot carry in-flight Runtime work.")}if(checkpoint.commandWait!==null){fail5("await_agent cannot carry a command wait.")}return}if(phase==="await_command"){if(checkpoint.commandWait===null||checkpoint.commandWait.runs.length===0){fail5("await_command requires the command wait runs.")}if(checkpoint.commandWait.runs.every(run=>run.folded)){fail5("await_command cannot keep an all-folded command wait.")}if(checkpoint.approval?.state==="requested"){fail5("await_command cannot keep a requested approval.")}if(inFlightTools||dispatchRuntime){fail5("await_command cannot carry in-flight Runtime work.")}if(checkpoint.agentWait!==null){fail5("await_command cannot carry an agent wait.")}return}if(phase==="results_ready"){if(items.length===0||unsettledTools){fail5("results_ready requires every tool item to be settled.")}if(dispatchRuntime||inFlightTools){fail5("results_ready cannot carry in-flight tools.")}if(checkpoint.approval?.state==="requested"){fail5("results_ready cannot keep a requested approval.")}if(checkpoint.agentWait!==null){fail5("results_ready cannot carry an agent wait.")}if(checkpoint.commandWait!==null){fail5("results_ready cannot carry a command wait.")}return}if(inFlightTools||dispatchRuntime||checkpoint.approval?.state==="requested"||checkpoint.agentWait!==null||checkpoint.commandWait!==null){fail5("turn_settled cannot carry in-flight tools, a requested approval, an agent wait, or a command wait.")}}__name(assertPhaseShape,"assertPhaseShape");function parseHarnessCheckpointObject(value){const record4=object4(value,"harness checkpoint");assertNoUnknownKeys(record4,ROOT_KEYS,"harness checkpoint");const identity=parseIdentity(record4["identity"]);const checkpoint={identity,resume:parseResume(record4["resume"],identity.coveredSequence),continuation:parseContinuation(record4["continuation"]),attempt:parseAttempt(record4["attempt"]),tools:parseTools(record4["tools"]),runtime:parseRuntime(record4["runtime"]),approval:parseApproval(record4["approval"]),agentWait:parseAgentWait(record4["agentWait"]),commandWait:parseCommandWait(record4["commandWait"]),commandLock:parseCommandLock(record4["commandLock"]),output:parseOutput(record4["output"]),followUp:parseFollowUp(record4["followUp"])};assertRuntimeMatchesTools(checkpoint.tools,checkpoint.runtime);assertPhaseShape(checkpoint);return checkpoint}__name(parseHarnessCheckpointObject,"parseHarnessCheckpointObject");function harnessCheckpointIsAgentWait(checkpoint){return checkpoint.continuation.phase==="await_agent"||checkpoint.continuation.phase==="model_output_committed"&&checkpoint.agentWait!==null}__name(harnessCheckpointIsAgentWait,"harnessCheckpointIsAgentWait");function harnessCheckpointIsCommandWait(checkpoint){return checkpoint.continuation.phase==="await_command"||checkpoint.continuation.phase==="model_output_committed"&&checkpoint.commandWait!==null}__name(harnessCheckpointIsCommandWait,"harnessCheckpointIsCommandWait");function tryParseHarnessCheckpointV1(bytes){let json2;try{json2=parseManagedSessionRecordJson(bytes.toString("utf8"),MANAGED_SESSION_LIMITS.maxEventBytes)}catch(error3){return{ok:false,reason:"opaque",message:error3 instanceof Error?error3.message:"unreadable checkpoint state"}}if(json2===null||typeof json2!=="object"||Array.isArray(json2)){return{ok:false,reason:"opaque",message:"checkpoint state is not a JSON object."}}const identity=json2["identity"];if(identity===null||typeof identity!=="object"||Array.isArray(identity)||identity["schemaVersion"]===void 0){return{ok:false,reason:"opaque",message:"checkpoint state has no Harness schemaVersion."}}try{return{ok:true,checkpoint:parseHarnessCheckpointObject(json2)}}catch(error3){if(error3 instanceof ManagedSessionRecordError){return{ok:false,reason:"invalid",message:error3.message}}throw error3}}__name(tryParseHarnessCheckpointV1,"tryParseHarnessCheckpointV1");function encodeHarnessCheckpointV1(checkpoint){return Buffer.from(JSON.stringify(checkpoint),"utf8")}__name(encodeHarnessCheckpointV1,"encodeHarnessCheckpointV1");function formatHarnessIdentity(input){return`${input.checkpointId}@${input.coveredSequence} ${input.sessionKey.tenantId}/${input.sessionKey.workspaceId}/${input.sessionKey.sessionId}`}__name(formatHarnessIdentity,"formatHarnessIdentity");function authorizeParsedHarnessCheckpoint(checkpoint,expected){if(!managedSessionKeysEqual(checkpoint.identity.sessionKey,expected.sessionKey)||checkpoint.identity.checkpointId!==expected.checkpointId||checkpoint.identity.coveredSequence!==expected.coveredSequence||checkpoint.identity.engine!=="managed"){return{status:"blocked",reason:"identity_mismatch",message:`checkpoint ${formatHarnessIdentity(checkpoint.identity)} does not match ${formatHarnessIdentity({sessionKey:expected.sessionKey,checkpointId:expected.checkpointId,coveredSequence:expected.coveredSequence})}`}}return{status:"runnable",checkpoint}}__name(authorizeParsedHarnessCheckpoint,"authorizeParsedHarnessCheckpoint");function createInitialHarnessCheckpoint(input){return{identity:{schemaVersion:HARNESS_CHECKPOINT_SCHEMA_VERSION,sessionKey:input.sessionKey,engine:"managed",checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,activationId:input.activationId,turnId:input.turnId,promptId:input.promptId,definitionRevision:input.definitionRevision,configRevision:input.configRevision,inputDigest:input.inputDigest,previousCheckpointId:input.previousCheckpointId},resume:{source:"session_log",throughSequence:input.coveredSequence,recording:{lastCompletedUuid:null,turnParentUuids:[],parentSessionId:null,sourceType:null,sourceId:null,lastAssistantModel:null,executionEngine:"managed"},initialTurn:input.initialTurn??0,consumedNotificationIds:[],apiHistoryRef:null,fileHistoryRef:null,artifactRef:null,goalRecordsRef:null,goalCheckpointWindowRef:null,tokenCountsRef:null,uiTelemetryRef:null,attributionRef:null,goalRecoverySourceUuid:null},continuation:{phase:"before_model",pendingEventIds:[...input.pendingEventIds??[]]},attempt:null,tools:null,runtime:null,approval:null,agentWait:null,commandWait:null,commandLock:null,output:{llmContentRef:null,physicalStatus:null,hookResultRef:null,mediaRefs:[],parentHistory:null},followUp:{pendingInputIds:[],cancelRequestIds:[],goalPermitIds:[],cronIds:[],notificationIds:[],childRunIds:[],stopBudgetRemaining:null,scopeLineage:[]}}}__name(createInitialHarnessCheckpoint,"createInitialHarnessCheckpoint");function createNextTurnReadyHarnessCheckpoint(input){return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,activationId:input.activationId,turnId:input.turnId,promptId:input.promptId,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"before_model",pendingEventIds:[]},attempt:null,tools:null,runtime:null,approval:null,agentWait:null,commandWait:null,commandLock:null,output:{llmContentRef:null,physicalStatus:null,hookResultRef:null,mediaRefs:[],parentHistory:input.previous.output.parentHistory},followUp:input.previous.followUp}}__name(createNextTurnReadyHarnessCheckpoint,"createNextTurnReadyHarnessCheckpoint");function createAwaitActionHarnessCheckpoint(input){return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"await_action",pendingEventIds:[]},attempt:input.attempt,tools:input.previous.tools,runtime:input.previous.runtime,approval:input.approval,agentWait:null,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createAwaitActionHarnessCheckpoint,"createAwaitActionHarnessCheckpoint");function createAwaitAgentHarnessCheckpoint(input){if(input.previous.approval?.state==="requested"){throw new ManagedSessionRecordError("await_agent cannot keep a requested approval.")}if(input.previous.agentWait!==null&&input.previous.agentWait.runs.some(run=>!run.consumed)){throw new ManagedSessionRecordError("await_agent cannot replace an unfinished agent wait.")}if(input.previous.commandWait!==null&&input.previous.commandWait.runs.some(run=>!run.folded)){throw new ManagedSessionRecordError("await_agent cannot replace an unfinished command wait.")}if(input.previous.tools?.items.some(item=>item.state==="in_progress")){throw new ManagedSessionRecordError("await_agent cannot carry in-flight Runtime work.")}const attempt2=input.attempt??input.previous.attempt;if(attempt2===null){throw new ManagedSessionRecordError("await_agent requires the attempt.")}if(input.agentWait.runs.length===0){throw new ManagedSessionRecordError("await_agent requires at least one run.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"await_agent",pendingEventIds:[]},attempt:attempt2,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:input.agentWait,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createAwaitAgentHarnessCheckpoint,"createAwaitAgentHarnessCheckpoint");function createAwaitCommandHarnessCheckpoint(input){if(input.previous.approval?.state==="requested"){throw new ManagedSessionRecordError("await_command cannot keep a requested approval.")}if(input.previous.commandWait!==null&&input.previous.commandWait.runs.some(run=>!run.folded)){throw new ManagedSessionRecordError("await_command cannot replace an unfinished command wait.")}if(input.previous.agentWait!==null&&input.previous.agentWait.runs.some(run=>!run.consumed)){throw new ManagedSessionRecordError("await_command cannot replace an unfinished agent wait.")}if(input.previous.tools?.items.some(item=>item.state==="in_progress")){throw new ManagedSessionRecordError("await_command cannot carry in-flight Runtime work.")}const attempt2=input.attempt??input.previous.attempt;if(attempt2===null){throw new ManagedSessionRecordError("await_command requires the attempt.")}if(input.commandWait.runs.length===0){throw new ManagedSessionRecordError("await_command requires at least one run.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"await_command",pendingEventIds:[]},attempt:attempt2,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:null,commandWait:input.commandWait,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createAwaitCommandHarnessCheckpoint,"createAwaitCommandHarnessCheckpoint");function createConsumedCommandWaitHarnessCheckpoint(input){if(input.previous.continuation.phase!=="await_command"){throw new ManagedSessionRecordError("folded command wait requires an await_command checkpoint.")}if(input.previous.commandWait===null){throw new ManagedSessionRecordError("folded command wait requires the command wait runs.")}const waited=input.previous.commandWait.runs.find(run=>run.commandId===input.commandId);if(waited===void 0){throw new ManagedSessionRecordError(`await_command has no run ${input.commandId}.`)}if(waited.folded){throw new ManagedSessionRecordError(`command wait run ${input.commandId} is already folded.`)}const runs=input.previous.commandWait.runs.map(run=>run.commandId===input.commandId?{...run,folded:true}:run);const allFolded=runs.every(run=>run.folded);return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:allFolded?"model_output_committed":"await_command",pendingEventIds:[]},attempt:input.previous.attempt,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:null,commandWait:{runs,holdsWorkspaceMount:input.previous.commandWait.holdsWorkspaceMount},commandLock:input.timedOut===true?harnessCommandLockOf(input.previous):carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createConsumedCommandWaitHarnessCheckpoint,"createConsumedCommandWaitHarnessCheckpoint");function createConsumedAgentWaitHarnessCheckpoint(input){if(input.previous.continuation.phase!=="await_agent"){throw new ManagedSessionRecordError("consumed agent wait requires an await_agent checkpoint.")}if(input.previous.agentWait===null){throw new ManagedSessionRecordError("consumed agent wait requires the agent wait runs.")}const waited=input.previous.agentWait.runs.find(run=>run.childRunId===input.childRunId);if(waited===void 0){throw new ManagedSessionRecordError(`await_agent has no run ${input.childRunId}.`)}if(waited.consumed){throw new ManagedSessionRecordError(`agent wait run ${input.childRunId} is already consumed.`)}const runs=input.previous.agentWait.runs.map(run=>run.childRunId===input.childRunId?{...run,consumed:true}:run);const allConsumed=runs.every(run=>run.consumed);return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:allConsumed?"model_output_committed":"await_agent",pendingEventIds:[]},attempt:input.previous.attempt,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:{runs},commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createConsumedAgentWaitHarnessCheckpoint,"createConsumedAgentWaitHarnessCheckpoint");function createAwaitRuntimeHarnessCheckpoint(input){if(input.previous.approval?.state==="requested"){throw new ManagedSessionRecordError("await_runtime cannot keep a requested approval.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"await_runtime",pendingEventIds:[]},attempt:input.attempt,tools:input.tools,runtime:input.runtime,approval:null,agentWait:null,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createAwaitRuntimeHarnessCheckpoint,"createAwaitRuntimeHarnessCheckpoint");function createResultsReadyHarnessCheckpoint(input){if(input.previous.continuation.phase!=="await_runtime"){throw new ManagedSessionRecordError("results_ready resume requires an await_runtime checkpoint.")}if(input.previous.attempt===null||input.previous.tools===null){throw new ManagedSessionRecordError("results_ready requires the waited attempt and tools.")}const settledItem=input.previous.tools.items.find(item=>item.executionCallId===input.executionCallId);if(settledItem?.state!=="in_progress"){throw new ManagedSessionRecordError(`await_runtime has no in-progress execution ${input.executionCallId}.`)}const items=input.previous.tools.items.map(item=>item.executionCallId===input.executionCallId?{...item,state:"settled",outcomeRef:input.outcomeRef,consumed:false}:item);const allSettled=items.every(item=>item.state==="settled");return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:allSettled?"results_ready":"await_runtime",pendingEventIds:[]},attempt:input.previous.attempt,tools:{batchId:input.previous.tools.batchId,items},runtime:{bindings:runtimeBindings(input.previous.runtime).map(binding=>binding.executionCallId===input.executionCallId&&binding.state==="dispatch"?{...binding,state:"settled"}:binding)},approval:null,agentWait:null,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createResultsReadyHarnessCheckpoint,"createResultsReadyHarnessCheckpoint");function createTurnSettledHarnessCheckpoint(input){if(input.previous.continuation.phase!=="results_ready"){throw new ManagedSessionRecordError("turn_settled resume requires a results_ready checkpoint.")}const items=input.previous.tools?.items??[];if(items.length===0||items.some(item=>item.state!=="settled"||item.consumed!==true)){throw new ManagedSessionRecordError("turn_settled requires every Runtime receipt to be consumed.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"turn_settled",pendingEventIds:[]},attempt:input.previous.attempt,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:null,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createTurnSettledHarnessCheckpoint,"createTurnSettledHarnessCheckpoint");function createHookStoppedRuntimeHarnessCheckpoint(input){const items=input.previous.tools?.items??[];if(input.previous.continuation.phase!=="results_ready"||items.length===0||items.some(item=>item.state!=="settled")||items.every(item=>item.consumed)){throw new ManagedSessionRecordError("Hook stop requires settled Runtime results not yet consumed by a model.")}return{...input.previous,identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"turn_settled",pendingEventIds:[]}}}__name(createHookStoppedRuntimeHarnessCheckpoint,"createHookStoppedRuntimeHarnessCheckpoint");function createConsumedRuntimeResultsHarnessCheckpoint(input){if(input.previous.continuation.phase!=="results_ready"){throw new ManagedSessionRecordError("consumed Runtime results require a results_ready checkpoint.")}if(input.previous.tools===null){throw new ManagedSessionRecordError("consumed Runtime results require the settled tools.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"results_ready",pendingEventIds:[]},attempt:input.previous.attempt,tools:{batchId:input.previous.tools.batchId,items:input.previous.tools.items.map(item=>item.state==="settled"&&item.consumed===false?{...item,consumed:true}:item)},runtime:input.previous.runtime,approval:null,agentWait:null,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createConsumedRuntimeResultsHarnessCheckpoint,"createConsumedRuntimeResultsHarnessCheckpoint");function createModelOutputCommittedHarnessCheckpoint(input){if(input.previous.attempt===null){throw new ManagedSessionRecordError("model_output_committed requires the waited attempt.")}const carried=input.previous.agentWait;if(carried!==null&&carried.runs.some(run=>!run.consumed)){throw new ManagedSessionRecordError("model_output_committed cannot carry an unconsumed agent wait.")}const carriedCommands=input.previous.commandWait;if(carriedCommands!==null&&carriedCommands.runs.some(run=>!run.folded)){throw new ManagedSessionRecordError("model_output_committed cannot carry an unfolded command wait.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"model_output_committed",pendingEventIds:[]},attempt:input.previous.attempt,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:input.previous.agentWait,commandWait:input.previous.commandWait,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createModelOutputCommittedHarnessCheckpoint,"createModelOutputCommittedHarnessCheckpoint");init_esbuild_shims();import{createHash as createHash10}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual2}from"node:util";var CHECKPOINT_STORAGE_PROFILE="managed-checkpoint-paged/1";var CHECKPOINT_HISTORY_KIND="managed-checkpoint-history";var CHECKPOINT_HISTORY_PAGE_BYTES=48*1024;var CHECKPOINT_HISTORY_PAGE_ITEMS=32;var MAX_HISTORY_PAGES=4096;var MAX_HISTORY_BYTES=64*1024*1024;function requireHistory(condition,message){if(!condition)throw new ManagedSessionRecordError(`Checkpoint history: ${message}`)}__name(requireHistory,"requireHistory");function object5(value){requireHistory(value!==null&&typeof value==="object"&&!Array.isArray(value),"expected an object.");return value}__name(object5,"object");function closed4(record4,keys2){requireHistory(Object.keys(record4).length===keys2.length&&keys2.every(key=>key in record4),"fields conflict.")}__name(closed4,"closed");function json(bytes,limit){return object5(parseManagedSessionRecordJson(bytes.toString("utf8"),limit))}__name(json,"json");function historyRef(value){const ref11=assertManagedSessionDurableRef(value,"checkpoint history");requireHistory(ref11.kind===CHECKPOINT_HISTORY_KIND&&ref11.schemaVersion===1&&ref11.byteLength<=CHECKPOINT_HISTORY_PAGE_BYTES,"page reference conflicts.");return ref11}__name(historyRef,"historyRef");function isPagedHarnessCheckpoint(bytes){try{return json(bytes,MANAGED_SESSION_LIMITS.maxEventBytes)["storageProfile"]===CHECKPOINT_STORAGE_PROFILE}catch{return false}}__name(isPagedHarnessCheckpoint,"isPagedHarnessCheckpoint");function physicalRoot(bytes){const record4=json(bytes,MANAGED_SESSION_LIMITS.maxEventBytes);requireHistory(record4["storageProfile"]===CHECKPOINT_STORAGE_PROFILE,"storage profile is unsupported.");const history=object5(record4["history"]);closed4(history,["ref","toolCount","bindingCount"]);const result={ref:historyRef(history["ref"]),toolCount:assertManagedSessionSequence(history["toolCount"],"history.toolCount"),bindingCount:assertManagedSessionSequence(history["bindingCount"],"history.bindingCount"),pageCount:0,byteLength:0};requireHistory(result.toolCount>0,"empty archive.");const{storageProfile:_profile,history:_history,...state}=record4;return{state,history:result}}__name(physicalRoot,"physicalRoot");function checkpointHistoryPage(bytes){const page=json(bytes,CHECKPOINT_HISTORY_PAGE_BYTES);closed4(page,["storageProfile","sessionKey","turnId","promptId","previous","toolCount","bindingCount","items","bindings"]);requireHistory(page["storageProfile"]===`${CHECKPOINT_HISTORY_KIND}/1`,"page profile is unsupported.");requireHistory(Array.isArray(page["items"])&&Array.isArray(page["bindings"]),"page arrays are missing.");const items=page["items"];const bindings=page["bindings"];requireHistory(items.length<=CHECKPOINT_HISTORY_PAGE_ITEMS&&bindings.length<=CHECKPOINT_HISTORY_PAGE_ITEMS&&items.length+bindings.length>0,"page item count conflicts.");for(const item of items){const tool=object5(item);requireHistory(tool["state"]==="settled"&&tool["consumed"]===true,"unfinished or unconsumed tool was archived.")}for(const item of bindings){const binding=object5(item);requireHistory(binding["state"]==="settled"||binding["state"]==="committed","in-flight binding was archived.")}return{sessionKey:page["sessionKey"],turnId:page["turnId"],promptId:page["promptId"],previous:page["previous"]===null?null:historyRef(page["previous"]),toolCount:assertManagedSessionSequence(page["toolCount"],"page.toolCount"),bindingCount:assertManagedSessionSequence(page["bindingCount"],"page.bindingCount"),items,bindings}}__name(checkpointHistoryPage,"checkpointHistoryPage");function checkpointStorageBody(bytes){return isPagedHarnessCheckpoint(bytes)?json(bytes,MANAGED_SESSION_LIMITS.maxEventBytes):parseHarnessCheckpointObject(json(bytes,MANAGED_SESSION_LIMITS.maxEventBytes))}__name(checkpointStorageBody,"checkpointStorageBody");async function verifiedRead(resources,ref11){const bytes=await resources.read(ref11);requireHistory(bytes.byteLength===ref11.byteLength&&createHash10("sha256").update(bytes).digest("hex")===ref11.digest,"resource length or digest conflicts.");return bytes}__name(verifiedRead,"verifiedRead");async function load(resources,ref11){requireHistory(ref11.kind==="managed-checkpoint"&&ref11.schemaVersion===1,"checkpoint reference conflicts.");const bytes=await verifiedRead(resources,ref11);if(!isPagedHarnessCheckpoint(bytes)){const parsed=tryParseHarnessCheckpointV1(bytes);requireHistory(parsed.ok,parsed.ok?"":parsed.message??"invalid inline checkpoint.");return{bytes,checkpoint:parsed.checkpoint}}const root=physicalRoot(bytes);const identity=object5(root.state["identity"]);const pages=[];const visited=new Set;let next=root.history.ref;let toolCount=root.history.toolCount;let bindingCount=root.history.bindingCount;let totalBytes=0;while(next!==null){requireHistory(!visited.has(next.resourceId)&&visited.size<MAX_HISTORY_PAGES,"page cycle or capacity exceeded.");visited.add(next.resourceId);const part=await verifiedRead(resources,next);totalBytes+=part.byteLength;requireHistory(totalBytes<=MAX_HISTORY_BYTES,"decoded history capacity exceeded.");const page=checkpointHistoryPage(part);requireHistory(isDeepStrictEqual2(page.sessionKey,identity["sessionKey"])&&page.turnId===identity["turnId"]&&page.promptId===identity["promptId"],"page belongs to another Session or Turn.");requireHistory(page.toolCount===toolCount&&page.bindingCount===bindingCount,"page counts conflict.");toolCount-=page.items.length;bindingCount-=page.bindings.length;requireHistory(toolCount>=0&&bindingCount>=0&&(page.previous!==null||toolCount+bindingCount===0),"page coverage conflicts.");pages.push(page);next=page.previous}requireHistory(toolCount===0&&bindingCount===0,"history is incomplete.");const tools=object5(root.state["tools"]);const runtime=root.state["runtime"]===null?null:object5(root.state["runtime"]);requireHistory(Array.isArray(tools["items"])&&(runtime===null||Array.isArray(runtime["bindings"])),"active arrays conflict.");pages.reverse();const items=pages.flatMap(page=>page.items);const bindings=pages.flatMap(page=>page.bindings);const checkpoint=parseHarnessCheckpointObject({...root.state,tools:{...tools,items:[...items,...tools["items"]]},runtime:runtime===null?null:{...runtime,bindings:[...bindings,...runtime["bindings"]]}});requireHistory(root.history.bindingCount===0||runtime!==null,"archived bindings lost their group.");return{bytes,checkpoint,history:{...root.history,pageCount:pages.length,byteLength:totalBytes}}}__name(load,"load");async function readHarnessCheckpoint(resources,ref11){return(await load(resources,ref11)).checkpoint}__name(readHarnessCheckpoint,"readHarnessCheckpoint");var ManagedCheckpointHistory=class{constructor(resources){this.resources=resources}static{__name(this,"ManagedCheckpointHistory")}committed;async read(ref11){if(this.committed&&isDeepStrictEqual2(this.committed.ref,ref11))return this.committed;return load(this.resources,ref11)}async tryRead(ref11){if(this.committed&&isDeepStrictEqual2(this.committed.ref,ref11))return{ok:true,checkpoint:this.committed.checkpoint};const bytes=await verifiedRead(this.resources,ref11);if(!isPagedHarnessCheckpoint(bytes)){const parsed=tryParseHarnessCheckpointV1(bytes);if(parsed.ok)this.remember(ref11,{bytes,checkpoint:parsed.checkpoint});return parsed}try{const prepared=await load(this.resources,ref11);this.remember(ref11,prepared);return{ok:true,checkpoint:prepared.checkpoint}}catch(error3){if(!(error3 instanceof ManagedSessionRecordError))throw error3;return{ok:false,reason:"invalid",message:error3.message}}}remember(ref11,prepared){this.committed={...prepared,ref:ref11}}async prepare(checkpoint,previousRef){const state=parseHarnessCheckpointObject(checkpoint);const items=state.tools?.items??[];const bindings=state.runtime?.bindings??[];let history;if(previousRef&&state.continuation.phase!=="before_model"){const previous=await this.read(previousRef);if(previous.history&&managedSessionKeysEqual(previous.checkpoint.identity.sessionKey,state.identity.sessionKey)&&previous.checkpoint.identity.turnId===state.identity.turnId&&previous.checkpoint.identity.promptId===state.identity.promptId){history=previous.history;requireHistory(isDeepStrictEqual2(items.slice(0,history.toolCount),previous.checkpoint.tools?.items.slice(0,history.toolCount))&&isDeepStrictEqual2(bindings.slice(0,history.bindingCount),previous.checkpoint.runtime?.bindings.slice(0,history.bindingCount)??[]),"committed prefix was changed.")}}let eligible=0;while(eligible<items.length&&items[eligible].state==="settled"&&items[eligible].consumed)eligible++;const toolTarget=Math.max(history?.toolCount??0,Math.floor(Math.max(0,eligible-CHECKPOINT_HISTORY_PAGE_ITEMS)/CHECKPOINT_HISTORY_PAGE_ITEMS)*CHECKPOINT_HISTORY_PAGE_ITEMS);const archivedIds=new Set(items.slice(0,toolTarget).map(item=>item.executionCallId));let bindingTarget=0;while(bindingTarget<bindings.length&&bindings[bindingTarget].state!=="dispatch"&&archivedIds.has(bindings[bindingTarget].executionCallId))bindingTarget++;let toolCount=history?.toolCount??0;let bindingCount=history?.bindingCount??0;requireHistory(eligible>=toolCount&&bindingTarget>=bindingCount,"committed history became unfinished.");while(toolCount<toolTarget||bindingCount<bindingTarget){const pageItems=[];const pageBindings=[];const body=__name(()=>({storageProfile:`${CHECKPOINT_HISTORY_KIND}/1`,sessionKey:state.identity.sessionKey,turnId:state.identity.turnId,promptId:state.identity.promptId,previous:history?.ref??null,toolCount:toolCount+pageItems.length,bindingCount:bindingCount+pageBindings.length,items:pageItems,bindings:pageBindings}),"body");const fits=__name(()=>Buffer.byteLength(JSON.stringify(body()),"utf8")<=CHECKPOINT_HISTORY_PAGE_BYTES,"fits");while(toolCount+pageItems.length<toolTarget&&pageItems.length<CHECKPOINT_HISTORY_PAGE_ITEMS){pageItems.push(items[toolCount+pageItems.length]);if(!fits()){pageItems.pop();break}}while(bindingCount+pageBindings.length<bindingTarget&&pageBindings.length<CHECKPOINT_HISTORY_PAGE_ITEMS){pageBindings.push(bindings[bindingCount+pageBindings.length]);if(!fits()){pageBindings.pop();break}}requireHistory(pageItems.length+pageBindings.length>0,"one history entry exceeds the page budget.");const bytes2=Buffer.from(JSON.stringify(body()),"utf8");const pageCount=(history?.pageCount??0)+1;const byteLength2=(history?.byteLength??0)+bytes2.byteLength;requireHistory(pageCount<=MAX_HISTORY_PAGES&&byteLength2<=MAX_HISTORY_BYTES,"decoded history capacity exceeded.");const ref11=await this.resources.publish(CHECKPOINT_HISTORY_KIND,bytes2);toolCount+=pageItems.length;bindingCount+=pageBindings.length;history={ref:ref11,toolCount,bindingCount,pageCount,byteLength:byteLength2}}if(!history)return{bytes:encodeHarnessCheckpointV1(state),checkpoint:state};const tail={...state,tools:state.tools&&{...state.tools,items:items.slice(toolCount)},runtime:state.runtime&&{...state.runtime,bindings:bindings.slice(bindingCount)}};const bytes=Buffer.from(JSON.stringify({...JSON.parse(encodeHarnessCheckpointV1(tail).toString("utf8")),storageProfile:CHECKPOINT_STORAGE_PROFILE,history:{ref:history.ref,toolCount:history.toolCount,bindingCount:history.bindingCount}}),"utf8");requireHistory(bytes.byteLength<=MANAGED_SESSION_LIMITS.maxEventBytes,"active checkpoint exceeds its physical budget.");return{bytes,checkpoint:state,history}}};init_esbuild_shims();var HOSTED_RECOVERY_RESOURCE_KINDS=new Set(["hosted-approval-continuation","hosted-model-request","hosted-turn-cleanup"]);var HOSTED_MODEL_REQUEST_BYTES=32*1024*1024;function parseHostedRecoveryResource(bytes,expectedKey,kind){const value=parseManagedSessionRecordJson(bytes.toString("utf8"),kind==="hosted-model-request"?HOSTED_MODEL_REQUEST_BYTES:64*1024);if(!value||typeof value!=="object"||Array.isArray(value)||value["v"]!==1)throw new ManagedSessionRecordError("Invalid Hosted recovery resource.");const key=assertManagedSessionKey(value["sessionKey"],"Hosted recovery sessionKey");assertManagedSessionStableId(value["promptId"],"Hosted recovery promptId");if(expectedKey&&(key.tenantId!==expectedKey.tenantId||key.workspaceId!==expectedKey.workspaceId||key.sessionId!==expectedKey.sessionId))throw new ManagedSessionRecordError("Hosted recovery resource names another Session.");return value}__name(parseHostedRecoveryResource,"parseHostedRecoveryResource");function hostedRecoveryReferences(value){const refs2=new Map;if(!value||typeof value!=="object"||Array.isArray(value))return[];const body=value;const pending=["definitionRef","rootSnapshotRef","assistantRef","inputRef","continuationRef"].flatMap(field=>body[field]?[body[field]]:[]);if(Array.isArray(body["calls"]))for(const call of body["calls"]){if(!call||typeof call!=="object")continue;const member=call;pending.push(member["inputRef"],member["definitionRef"])}for(const item of pending){const ref11=assertManagedSessionDurableRef(item,"Hosted recovery reference");const previous=refs2.get(ref11.resourceId);if(previous&&(previous.kind!==ref11.kind||previous.schemaVersion!==ref11.schemaVersion||previous.byteLength!==ref11.byteLength||previous.digest!==ref11.digest))throw new ManagedSessionRecordError("Hosted recovery references conflict.");refs2.set(ref11.resourceId,ref11)}return[...refs2.values()]}__name(hostedRecoveryReferences,"hostedRecoveryReferences");init_esbuild_shims();var MANAGED_MESSAGE_KIND="managed-message";var MANAGED_MESSAGE_PART_KIND="managed-message-part";var MANAGED_MESSAGE_CHUNKS_KIND="managed-message-chunks";var MANAGED_MESSAGE_PART_BYTES=60*1024;var MANAGED_MESSAGE_INLINE_BYTES=64*1024;async function publishManagedMessageBody(resources,body){if(body.byteLength<=MANAGED_MESSAGE_INLINE_BYTES){return resources.publish(MANAGED_MESSAGE_KIND,body)}const parts=[];for(let offset2=0;offset2<body.byteLength;offset2+=MANAGED_MESSAGE_PART_BYTES){parts.push(await resources.publish(MANAGED_MESSAGE_PART_KIND,body.subarray(offset2,offset2+MANAGED_MESSAGE_PART_BYTES)))}return resources.publish(MANAGED_MESSAGE_CHUNKS_KIND,Buffer.from(JSON.stringify({parts}),"utf8"))}__name(publishManagedMessageBody,"publishManagedMessageBody");async function readManagedMessageBody(read2,ref11){if(ref11.kind!==MANAGED_MESSAGE_CHUNKS_KIND){return read2(ref11)}const{parts}=parseManagedMessageChunkManifest(await read2(ref11));const buffers=[];for(const part of parts)buffers.push(await read2(part));return Buffer.concat(buffers)}__name(readManagedMessageBody,"readManagedMessageBody");function managedMessageChunkParts(kind,body){return kind===MANAGED_MESSAGE_CHUNKS_KIND?parseManagedMessageChunkManifest(body).parts:[]}__name(managedMessageChunkParts,"managedMessageChunkParts");function parseManagedMessageChunkManifest(bytes){const manifest=JSON.parse(bytes.toString("utf8"));const parts=manifest["parts"];if(!Array.isArray(parts)||parts.length===0){throw new ManagedSessionRecordError("a Managed message chunk manifest must carry parts.")}return{parts:parts.map(part=>{const ref11=assertManagedSessionDurableRef(part,"message chunk part");if(ref11.kind!==MANAGED_MESSAGE_PART_KIND){throw new ManagedSessionRecordError("a Managed message chunk manifest must reference message parts.")}return ref11})}}__name(parseManagedMessageChunkManifest,"parseManagedMessageChunkManifest");var RESOURCE_REF_PATHS={"managed-tool_stage":["inputRef","permissionRef","resultRef"],"managed-history_maintenance":["requestRef","candidateRef"],"managed-mcp_configuration":["catalogRef"],"managed-mcp_operation":["argsRef","resultRef"],"managed-hook_registration":["catalogRef"],"managed-hook_execution":["planRef","inputRef","resultRef"],"managed-monitor_run":["commandRef","startReceiptRef","outputRef","lastObservationRef"],"managed-child_run":["commandRef","startReceiptRef","outputRef","inputRef","resultRef","terminalReceiptRef"],"managed-child_acceptance":["contentRef","terminalReceiptRef"],"managed-channel_route":["policyRef"],"managed-channel_delivery":["contentRef","segments.*.contentRef","segments.*.receipt.proofRef"],"managed-schedule":["promptRef"],"managed-automation_run":["gateOutputRef"],"managed-session_message":["contentRef"],"managed-session_command":["argsRef","replyRef"],"managed-team_task":["descriptionRef","metadataRef"],"managed-team_message":["contentRef"],"managed-team_plan":["planRef","feedbackRef"],"managed-definition":["sessionSkillsRef","agentDefinition.instructionsRef","agentDefinition.skillsRef","publicChildExtensionAgent.effectiveConfigRef","publicChildExtensionAgent.extensionAgent.bundleRef","publicChildExtensionAgent.extensionAgent.contributionsRef"],"managed-action-options":["definitionRef","rootSnapshotRef","assistantRef","inputRef","continuationRef","calls.*.inputRef","calls.*.definitionRef"],"managed-hook-plan":["messagesRef"],"managed-hook-message-chunks":["parts.*"],"managed-tool-outcome-chunks":["parts.*"],"managed-tool-outcome":["manifestRef","envelope.capture.manifest"],"managed-config_install":["previousBundleRef","restoresBundleRef","bundleRef","rootSnapshotRef","stageAckRefs.*","enableAckRefs.*"],"managed-extension-config-bundle":["packages.*.contributionsRef"],"managed-extension-contributions":["parts.*"]};var CHECKPOINT_REF_PATHS=["resume.apiHistoryRef","resume.fileHistoryRef","resume.artifactRef","resume.goalRecordsRef","resume.goalCheckpointWindowRef","resume.tokenCountsRef","resume.uiTelemetryRef","resume.attributionRef","attempt.routeRef","attempt.capabilityRef","attempt.samplingRef","attempt.usageRef","tools.items.*.outcomeRef","approval.optionsRef","approval.decisionRef","approval.invocationRef","output.llmContentRef","output.hookResultRef","output.mediaRefs.*"];function refsAtPaths(value,paths){const visit3=__name((current2,path89)=>{if(current2===null||current2===void 0)return[];if(path89.length===0)return[assertManagedSessionDurableRef(current2,"resource dependency")];if(typeof current2!=="object")return[];const[field,...rest]=path89;return field==="*"?(Array.isArray(current2)?current2:[]).flatMap(item=>visit3(item,rest)):visit3(current2[field],rest)},"visit");return paths.flatMap(path89=>visit3(value,path89.split(".")))}__name(refsAtPaths,"refsAtPaths");function managedSessionNestedResourceRefs(ref11,bytes){if(ref11.kind===MANAGED_MESSAGE_CHUNKS_KIND)return managedMessageChunkParts(ref11.kind,bytes);if(ref11.kind===CHECKPOINT_HISTORY_KIND)return refsAtPaths(checkpointHistoryPage(bytes),["previous","items.*.outcomeRef"]);if(ref11.kind==="managed-checkpoint"){if(isPagedHarnessCheckpoint(bytes))return refsAtPaths(checkpointStorageBody(bytes),[...CHECKPOINT_REF_PATHS,"history.ref"]);const parsed=tryParseHarnessCheckpointV1(bytes);return parsed.ok?refsAtPaths(parsed.checkpoint,CHECKPOINT_REF_PATHS):[]}if(ref11.kind==="managed-input"){try{return decodeChannelInputEnvelope(bytes).attachments.flatMap(attachment=>"ref"in attachment?[attachment.ref]:[])}catch{try{return refsAtPaths(decodeChildLaunchEnvelope(bytes),["publicLaunch.skillsRef","publicLaunch.extensionAgent.bundleRef","publicLaunch.extensionAgent.contributionsRef"])}catch{return[]}}}if(HOSTED_RECOVERY_RESOURCE_KINDS.has(ref11.kind))return hostedRecoveryReferences(parseHostedRecoveryResource(bytes,void 0,ref11.kind));if(ref11.kind===MANAGED_TOOL_RESULT_KINDS.manifest){try{return refsAtPaths(parseToolResultManifestBytes(bytes),["contents.*.body.ref","contents.*.body.pages.*.ref"])}catch{return[]}}const domain=MANAGED_SESSION_DOMAINS.find(domain2=>ref11.kind===`managed-${domain2}`);const paths=RESOURCE_REF_PATHS[ref11.kind]??[];if(!domain&&paths.length===0)return[];const record4=parseManagedSessionRecordJson(bytes.toString("utf8"),bytes.length);return refsAtPaths(record4,[...paths,...domain?["previousRecordRef"]:[],...ref11.kind==="managed-file_history"&&record4["schemaVersion"]===2&&record4["profile"]==="csi-files-retirement/1"?["preparation.intentRef","preparation.invocations.*.inputRef","preparation.invocations.*.toolDefinitionRef"]:[]])}__name(managedSessionNestedResourceRefs,"managedSessionNestedResourceRefs");init_esbuild_shims();var ManagedSessionCommitRejectedError=class extends ManagedSessionRecordError{static{__name(this,"ManagedSessionCommitRejectedError")}constructor(cause){super(cause.message);this.cause=cause;this.name="ManagedSessionCommitRejectedError"}};function managedSessionCommandKey(operation,commandId){return`${operation}\0${commandId}`}__name(managedSessionCommandKey,"managedSessionCommandKey");function managedSessionActivationStateFrom(event){return{activationId:event.payload["activationId"],epoch:event.payload["epoch"],workerId:event.payload["workerId"],phase:event.payload["phase"],expiresAt:event.payload["expiresAt"],renewalSeq:event.payload["renewalSeq"]??0,installRef:event.payload["installRef"]??null}}__name(managedSessionActivationStateFrom,"managedSessionActivationStateFrom");function scanManagedSessionJournal(bytes,sessionKey,maxBytes){const text3=(maxBytes===void 0||maxBytes>=bytes.byteLength?bytes:bytes.subarray(0,maxBytes)).toString("utf8");const lines=text3.split("\n");const tornTail=lines[lines.length-1]!==""?1:0;lines.pop();let header;const events=[];const transactions=new Map;let committed=0;let lastMarkerDigest=null;let lastRecordUuid=null;let activation;let scanned=0;let committedBytes=0;let headerBytes=0;let foreignRecords=0;let engineRecords=0;let pending=[];for(let index=0;index<lines.length;index++){const line2=lines[index];if(line2===""){throw new ManagedSessionRecordError(`session log line ${index+1} is blank.`)}scanned+=Buffer.byteLength(line2,"utf8")+1;const record4=parseManagedSessionRecordJson(line2,MANAGED_SESSION_LIMITS.maxEventBytes);if(record4===null||typeof record4!=="object"||Array.isArray(record4)){throw new ManagedSessionRecordError(`session log line ${index+1} is not a record object.`)}const envelope2=record4;const subtype=envelope2["subtype"];if(typeof envelope2["uuid"]==="string"){lastRecordUuid=envelope2["uuid"]}if(subtype!==MANAGED_SESSION_HEADER_SUBTYPE&&subtype!==MANAGED_SESSION_EVENT_SUBTYPE&&subtype!==MANAGED_SESSION_COMMIT_SUBTYPE){if(header!==void 0){throw new ManagedSessionRecordError(`session log line ${index+1} has the unknown subtype ${String(subtype)} after the Managed header.`)}foreignRecords++;if(subtype==="session_execution_engine")engineRecords++;continue}const body=envelope2["managedSession"];if(subtype===MANAGED_SESSION_HEADER_SUBTYPE){if(header!==void 0){throw new ManagedSessionRecordError(`session log line ${index+1} repeats the Managed header.`)}if(Buffer.byteLength(line2,"utf8")>MANAGED_SESSION_LIMITS.maxHeaderBytes){throw new ManagedSessionRecordError(`record exceeds ${MANAGED_SESSION_LIMITS.maxHeaderBytes} UTF-8 bytes.`)}header=parseManagedSessionHeader(body);headerBytes=scanned;if(!managedSessionKeysEqual(header.sessionKey,sessionKey)){throw new ManagedSessionRecordError("session log header belongs to a different session.")}continue}if(header===void 0){throw new ManagedSessionRecordError(`session log line ${index+1} precedes the Managed header.`)}if(subtype===MANAGED_SESSION_EVENT_SUBTYPE){const event=parseManagedSessionEvent(body);if(!managedSessionKeysEqual(event.sessionKey,sessionKey)){throw new ManagedSessionRecordError(`session log line ${index+1} belongs to a different session.`)}const expected=committed+pending.length+1;if(event.sequence!==expected){throw new ManagedSessionRecordError(`session log line ${index+1} has sequence ${event.sequence} where ${expected} was expected.`)}pending.push(event);continue}const marker=parseManagedSessionCommitMarker(body);if(marker.previousCommitDigest!==lastMarkerDigest){throw new ManagedSessionRecordError(`session log line ${index+1} does not chain to the previous commit.`)}if(marker.eventCount!==pending.length||marker.firstSequence!==committed+1||marker.lastSequence!==committed+pending.length){throw new ManagedSessionRecordError(`session log line ${index+1} does not cover the preceding events.`)}if(marker.eventsDigest!==managedSessionEventsDigest(pending)){throw new ManagedSessionRecordError(`session log line ${index+1} does not match the preceding event content.`)}for(const event of pending){if(event.kind==="checkpoint.committed"&&event.payload["coveredSequence"]>committed){throw new ManagedSessionRecordError("checkpoint covers events not committed before its transaction.")}events.push(event);if(event.kind==="activation.changed"){activation=managedSessionActivationStateFrom(event)}}committed=marker.lastSequence;committedBytes=scanned;lastMarkerDigest=managedToolDigest(marker,MANAGED_SESSION_LIMITS.maxCommitMarkerBytes);transactions.set(managedSessionCommandKey(marker.operation,marker.commandId),{contentDigest:marker.contentDigest,receipt:{transactionId:marker.transactionId,commandId:marker.commandId,operation:marker.operation,firstSequence:marker.firstSequence,lastSequence:marker.lastSequence,committedSequence:marker.lastSequence,replayed:false}});pending=[]}return{header,events,transactions,committed,lastMarkerDigest,lastRecordUuid,activation,committedBytes,headerBytes,uncommittedBytes:Buffer.byteLength(text3,"utf8")-committedBytes,uncommitted:pending.length+tornTail,foreignRecords,engineRecords}}__name(scanManagedSessionJournal,"scanManagedSessionJournal");init_esbuild_shims();function requireSnapshot2(condition,detail){if(!condition)throw new ManagedSessionRecordError(`Local journal snapshot ${detail}.`)}__name(requireSnapshot2,"requireSnapshot");function readLocalManagedJournal(options2){let bytes;try{bytes=readLocalJournalBytes(options2.transcriptPath,options2.maxBytes)}catch(error3){if(error3.code==="ENOENT")return scanManagedSessionJournal(Buffer.alloc(0),options2.sessionKey);throw error3}const base2=parseLocalJournalBase(bytes,options2.sessionKey);if(!base2)return scanManagedSessionJournal(bytes,options2.sessionKey);const manifest=readLocalJournalManifest(options2.runtimeBaseDir,options2.sessionKey,base2.manifest);const chunks=manifest.pages.map(ref11=>readLocalJournalResource(options2.runtimeBaseDir,options2.sessionKey,ref11));const prefix2=Buffer.concat(chunks);requireSnapshot2(prefix2.length===manifest.byteLength&&localJournalDigest(prefix2)===manifest.digest,"prefix bytes differ");const original=scanManagedSessionJournal(prefix2,options2.sessionKey);requireSnapshot2(original.uncommitted===0&&original.committedBytes===prefix2.length&&original.committed===manifest.committedSequence&&original.lastMarkerDigest===manifest.lastCommitDigest&&original.lastRecordUuid===manifest.lastRecordUuid,"prefix commit proof differs");requireSnapshot2(localJournalPhysicalPrefix(prefix2,original.header).equals(bytes.subarray(0,base2.headerEnd)),"ownership prefix differs from its source");for(const ref11 of manifest.resources)readLocalJournalResource(options2.runtimeBaseDir,options2.sessionKey,ref11);const logical=scanManagedSessionJournal(Buffer.concat([prefix2,bytes.subarray(base2.baseEnd)]),options2.sessionKey);const verified=new Map(manifest.resources.map(ref11=>[ref11.resourceId,ref11]));const pending=logical.events.filter(event=>event.sequence>manifest.committedSequence).flatMap(managedSessionEventRefs);while(pending.length){const ref11=pending.pop();const previous=verified.get(ref11.resourceId);if(previous){requireSnapshot2(previous.kind===ref11.kind&&previous.schemaVersion===ref11.schemaVersion&&previous.byteLength===ref11.byteLength&&previous.digest===ref11.digest,"tail resource references conflict");continue}verified.set(ref11.resourceId,ref11);pending.push(...managedSessionNestedResourceRefs(ref11,readLocalJournalResource(options2.runtimeBaseDir,options2.sessionKey,ref11)))}return{...logical,headerBytes:base2.headerEnd,committedBytes:base2.baseEnd+logical.committedBytes-prefix2.length,uncommittedBytes:bytes.length-(base2.baseEnd+logical.committedBytes-prefix2.length)}}__name(readLocalManagedJournal,"readLocalManagedJournal");function sourceHeader(bytes){for(const line2 of bytes.toString("utf8").split("\n")){if(!line2)continue;const record4=localJournalObject(JSON.parse(line2));if(record4["subtype"]==="managed_session_header_v1"){return parseManagedSessionHeader(record4["managedSession"])}}return void 0}__name(sourceHeader,"sourceHeader");async function acquireLocalManagedSessionWriter(options2){let header;try{header=sourceHeader(readLocalJournalBytes(options2.transcriptPath))}catch(error3){if(error3.code!=="ENOENT")throw error3}const lease=await SessionWriterLease.acquire({...options2,takeoverPolicy:"certified",lockSchema:{schemaVersion:3,formatVersion:header?.minimumReader==="managed-session/2"?LOCAL_MANAGED_JOURNAL_FORMAT:1,resumeFormatVersion:LOCAL_MANAGED_JOURNAL_FORMAT}});return lease}__name(acquireLocalManagedSessionWriter,"acquireLocalManagedSessionWriter");async function prepareLocalManagedSessionWriter(lease,expectedSessionKey){const options2={runtimeBaseDir:lease.runtimeBaseDir,transcriptPath:lease.transcriptPath,sessionId:lease.sessionId};const proof=lease.takeoverCommitProof;if(!proof||lease.managedJournalFormatVersion!==LOCAL_MANAGED_JOURNAL_FORMAT)return false;let header;try{const bytes=Buffer.from(await lease.readTranscript());header=sourceHeader(bytes);if(!header)return false;if(header.sessionKey.sessionId!==options2.sessionId||!managedSessionKeysEqual(header.sessionKey,expectedSessionKey)){throw new ManagedSessionRecordError("Local snapshot source has a different Session.")}if(parseLocalJournalBase(bytes,header.sessionKey))return false;const scan=scanManagedSessionJournal(bytes,header.sessionKey);if(scan.committed!==proof.last_commit_sequence||(scan.lastMarkerDigest??"0".repeat(64))!==proof.committed_prefix_hash){const{ManagedSessionConflictError:ManagedSessionConflictError2}=await import("./managed-session-authority-CFUZ45HT.js");throw new ManagedSessionConflictError2("Local snapshot source does not match the sealed writer proof.")}if(scan.uncommitted>0||scan.committed===0)return false;const resources=LocalManagedSessionResourceStore.create({runtimeBaseDir:options2.runtimeBaseDir,sessionKey:header.sessionKey});const pending=[header.definitionRef,header.rootSnapshotRef,...header.baseTranscriptProof?[header.baseTranscriptProof]:[],...scan.events.flatMap(managedSessionEventRefs)];const refs2=new Map;while(pending.length){const ref11=pending.pop();const previous=refs2.get(ref11.resourceId);if(previous){if(previous.kind!==ref11.kind||previous.schemaVersion!==ref11.schemaVersion||previous.byteLength!==ref11.byteLength||previous.digest!==ref11.digest){throw new ManagedSessionRecordError("Local snapshot resource references conflict.")}continue}refs2.set(ref11.resourceId,ref11);pending.push(...managedSessionNestedResourceRefs(ref11,await resources.read(ref11)))}const pages=[];let pageStart=0;let transactionEnd=0;let offset2=0;while(offset2<bytes.length){const end=bytes.indexOf(10,offset2);if(end<0)throw new ManagedSessionRecordError("Local snapshot source has a torn line.");const record4=localJournalObject(JSON.parse(bytes.subarray(offset2,end).toString("utf8")));if(record4["subtype"]==="managed_session_commit_v1"){if(end+1-pageStart>LOCAL_MANAGED_SNAPSHOT_PAGE_BYTES){if(transactionEnd===pageStart)throw new ManagedSessionRecordError("Local snapshot transaction exceeds its page budget.");pages.push(await resources.publishJournalSnapshot(LOCAL_MANAGED_SNAPSHOT_PAGE_KIND,bytes.subarray(pageStart,transactionEnd)));pageStart=transactionEnd}transactionEnd=end+1;if(transactionEnd-pageStart>LOCAL_MANAGED_SNAPSHOT_PAGE_BYTES)throw new ManagedSessionRecordError("Local snapshot transaction exceeds its page budget.")}offset2=end+1}pages.push(await resources.publishJournalSnapshot(LOCAL_MANAGED_SNAPSHOT_PAGE_KIND,bytes.subarray(pageStart)));const latestRef=__name(domain=>scan.events.findLast(event=>event.kind==="domain.committed"&&event.payload["domain"]===domain)?.payload["recordRef"],"latestRef");const manifest={format:LOCAL_MANAGED_SNAPSHOT_FORMAT,sessionKey:header.sessionKey,pages,byteLength:bytes.length,digest:localJournalDigest(bytes),committedSequence:scan.committed,lastCommitDigest:scan.lastMarkerDigest,lastRecordUuid:scan.lastRecordUuid,resources:[...refs2.values()].sort((a,b2)=>a.resourceId.localeCompare(b2.resourceId)),titleRef:latestRef("session_metadata")??null,sourceRef:latestRef("session_source")??null};const manifestRef=await resources.publishJournalSnapshot(LOCAL_MANAGED_SNAPSHOT_KIND,Buffer.from(JSON.stringify(manifest)));const physicalPrefix=localJournalPhysicalPrefix(bytes,header);const headerRecord=localJournalObject(JSON.parse(physicalPrefix.toString("utf8").trimEnd().split("\n").at(-1)));const base2={uuid:randomUUID4(),parentUuid:headerRecord["uuid"],type:"system",subtype:LOCAL_MANAGED_SNAPSHOT_BASE,sessionId:options2.sessionId,managedSessionSnapshot:{format:LOCAL_MANAGED_SNAPSHOT_FORMAT,sessionKey:header.sessionKey,manifest:manifestRef}};const sessionKey=header.sessionKey;await lease.replaceManagedTranscript(`${physicalPrefix.toString("utf8")}${JSON.stringify(base2)}
100
+ `,"utf8");await this.assertOwnedAndUnchangedOnce();let expectedBefore=this.expectedTranscriptState;if(!expectedBefore||!this.expectedTranscriptHasher){throw new SessionWriterUnavailableError}let handle;try{await fs9.mkdir(path11.dirname(this.transcriptPath),{recursive:true,mode:448});handle=await openTranscriptForAppend(this.transcriptPath,expectedBefore);let beforeState=await getOpenTranscriptState(this.transcriptPath,handle,true);if(expectedBefore.exists){if(!sameTranscriptState(beforeState,expectedBefore)){if(!sameHardTranscriptState(beforeState,expectedBefore)){throw new SessionTranscriptChangedError}await this.reconcileTranscriptMetadata(beforeState,handle);expectedBefore=this.expectedTranscriptState;if(!expectedBefore?.exists){throw new SessionWriterUnavailableError}beforeState=expectedBefore}}else if(beforeState.byteLength!==0){throw new SessionTranscriptChangedError}const expectedHasher=this.expectedTranscriptHasher;if(!expectedHasher)throw new SessionWriterUnavailableError;const candidateHasher=expectedHasher.copy();candidateHasher.update(bytes);const nextByteLength=expectedBefore.byteLength+bytes.byteLength;await this.readOwnedLock();assertVerifiableTranscriptIdentity(beforeState.fingerprint);await handle.writeFile(bytes);await handle.sync();const afterStat=await handle.stat();const afterState=transcriptStateFromStat(afterStat);if(afterState.byteLength!==nextByteLength||!sameFileIdentity(afterState.fingerprint,beforeState.fingerprint)||!sameFileSecurityMetadata(afterState.fingerprint,beforeState.fingerprint)){throw new SessionTranscriptChangedError}await handle.close();handle=void 0;const transcriptState=await getTranscriptState(this.transcriptPath,afterState);if(!transcriptState.exists||transcriptState.byteLength!==nextByteLength||!sameFileIdentity(transcriptState.fingerprint,afterState.fingerprint)||!sameFileSecurityMetadata(transcriptState.fingerprint,afterState.fingerprint)){throw new SessionTranscriptChangedError}let committedState=transcriptState;let committedHasher=candidateHasher;let appendReconciliation;if(!sameTranscriptState(transcriptState,afterState)){const changedFields=transcriptStateChangedFields(afterState,transcriptState);const startedAt=Date.now();await this.readOwnedLock();const snapshot=await captureTranscriptSnapshot(this.transcriptPath,afterState,()=>this.released);if(!transcriptHashesEqual(snapshot.hasher,candidateHasher)){debugLogger15.debug(`Session transcript content changed after append metadata signal path=slow changedFields=${changedFields.join(",")} attempts=${snapshot.attempts} durationMs=${Date.now()-startedAt}`);throw new SessionTranscriptChangedError}committedState=snapshot.state;committedHasher=snapshot.hasher;appendReconciliation={changedFields,attempts:snapshot.attempts,startedAt}}await this.readOwnedLock();this.expectedTranscriptHasher=committedHasher;this.expectedTranscriptState=committedState;if(appendReconciliation){debugLogger15.debug(`Session transcript append metadata reconciled path=slow changedFields=${appendReconciliation.changedFields.join(",")} attempts=${appendReconciliation.attempts} durationMs=${Date.now()-appendReconciliation.startedAt}`)}}catch(error3){const code=error3.code;if(code==="EEXIST"||code==="ENOENT"){throw new SessionTranscriptChangedError}if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{await handle?.close().catch(()=>{})}}async reconcileTranscriptMetadata(observedState,handle){const expectedState=this.expectedTranscriptState;const expectedHasher=this.expectedTranscriptHasher;if(!expectedState||!expectedHasher||!sameHardTranscriptState(observedState,expectedState)){throw new SessionTranscriptChangedError}const changedFields=transcriptStateChangedFields(expectedState,observedState);const startedAt=Date.now();await this.readOwnedLock();const snapshot=handle?await captureOpenTranscriptSnapshot(this.transcriptPath,handle,expectedState,()=>this.released):await captureTranscriptSnapshot(this.transcriptPath,expectedState,()=>this.released);if(!transcriptHashesEqual(snapshot.hasher,expectedHasher)){debugLogger15.debug(`Session transcript content changed after metadata signal path=slow changedFields=${changedFields.join(",")} attempts=${snapshot.attempts} durationMs=${Date.now()-startedAt}`);throw new SessionTranscriptChangedError}await this.readOwnedLock();this.expectedTranscriptHasher=snapshot.hasher;this.expectedTranscriptState=snapshot.state;debugLogger15.debug(`Session transcript metadata reconciled path=slow changedFields=${changedFields.join(",")} attempts=${snapshot.attempts} durationMs=${Date.now()-startedAt}`)}release(){if(this.terminalOperation==="seal")return this.terminalPromise;if((this.managedFormatVersion??0)>=2&&!this.released){return Promise.reject(new SessionWriterUnavailableError({cause:new Error("A snapshot writer must preserve its seal or active fence.")}))}this.terminalOperation="release";if(this.terminalPromise)return this.terminalPromise;const terminal=this.runExclusive(()=>this.releaseOnce()).catch(error3=>{if(this.releaseRetryable&&(!this.released||this.releaseDurabilityPending)&&!(error3 instanceof SessionWriterLostError)&&this.terminalPromise===terminal){this.terminalPromise=void 0}throw error3});this.terminalPromise=terminal;return this.terminalPromise}sealForHandoff(commitProof){if(this.terminalOperation==="release")return this.release();this.terminalOperation="seal";if(this.terminalPromise)return this.terminalPromise;const terminal=this.runExclusive(()=>this.sealForHandoffOnce(commitProof)).catch(error3=>{if(this.releaseRetryable&&!this.released&&!(error3 instanceof SessionWriterLostError)&&this.terminalPromise===terminal){this.terminalPromise=void 0;this.terminalOperation=void 0}throw error3});this.terminalPromise=terminal;return terminal}get isReleased(){return this.released}get isReleaseDurabilityPending(){return this.releaseDurabilityPending}runExclusive(operation){const checked=__name(()=>{if(this.replacementFailure){throw new SessionWriterUnavailableError({cause:this.replacementFailure})}return operation()},"checked");const pending=this.operationTail.then(checked,checked);this.operationTail=pending.then(()=>void 0,()=>void 0);return pending}async releaseOnce(){if(this.released){if(this.releaseDurabilityPending){if(!this.releaseDirectory)throw new SessionWriterUnavailableError;await syncDurableLockDirectory(this.releaseDirectory);this.releaseDurabilityPending=false;await this.closeReleaseDirectory()}return}try{this.releaseDirectory=await openDurableLockDirectory(path11.dirname(this.lockPath));await this.readOwnedLockForRelease();try{await fs9.rename(this.lockPath,this.retiredPath)}catch(error3){const[primaryState,retiredState]=await Promise.all([this.inspectReleasePath(this.lockPath),this.inspectReleasePath(this.retiredPath)]);if(primaryState==="missing"||primaryState==="other"){this.released=true;if(retiredState==="owned"){this.releaseDurabilityPending=true;await fs9.unlink(this.retiredPath).catch(()=>{});await syncDurableLockDirectory(this.releaseDirectory);this.releaseDurabilityPending=false;await this.closeReleaseDirectory();return}throw new SessionWriterLostError}if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}this.released=true;this.releaseDurabilityPending=true;await fs9.unlink(this.retiredPath).catch(error3=>{debugLogger15.debug(`Session writer retired lock cleanup failed path=${JSON.stringify(this.retiredPath)} error=${describeDiagnosticError(error3)}`)});await syncDurableLockDirectory(this.releaseDirectory);this.releaseDurabilityPending=false;await this.closeReleaseDirectory()}catch(error3){if(!this.releaseDurabilityPending)await this.closeReleaseDirectory();throw error3}}async closeReleaseDirectory(){const directory=this.releaseDirectory;this.releaseDirectory=void 0;await directory?.handle.close().catch(()=>void 0)}async sealForHandoffOnce(commitProof){if(this.released)return;const ownedRecord=await this.readOwnedLockForRelease();if(!this.expectedTranscriptState){throw new SessionWriterUnavailableError}if(this.managedFormatVersion!==void 0&&!isValidCommitProof(commitProof)){throw new SessionWriterUnavailableError({cause:new Error("Managed session writer seal requires the commit proof")})}const relativePath=getTranscriptRelativePath(this.runtimeBaseDir,this.transcriptPath);const proof=await openTranscriptProof(this.transcriptPath);const transcriptProof={relative_path:relativePath,exists:proof.state.exists,byte_length:proof.state.byteLength,sha256:proof.sha256};let sealedRecord;if(this.managedFormatVersion===void 0){sealedRecord={...ownedRecord,schema_version:LOCK_SCHEMA_VERSION,state:"sealed",sealed_at:new Date().toISOString(),transcript:transcriptProof}}else{sealedRecord={...ownedRecord,schema_version:MANAGED_LOCK_SCHEMA_VERSION,state:"sealed",sealed_at:new Date().toISOString(),format_version:this.managedFormatVersion,last_commit_sequence:commitProof.last_commit_sequence,committed_prefix_hash:commitProof.committed_prefix_hash,transcript:transcriptProof}}const sealedRaw=JSON.stringify(sealedRecord);const sealedCandidatePath=`${this.lockPath}.sealed-candidate.${encodeURIComponent(this.ownerId)}`;const handoffRetiredPath=`${this.lockPath}.handoff.${encodeURIComponent(this.ownerId)}`;let claimAcquired=false;let transitionStarted=false;let transitionCommitted=false;try{if(!sameTranscriptState(proof.state,this.expectedTranscriptState)){throw new SessionTranscriptChangedError}if(!await installLockRecord(sealedCandidatePath,sealedRecord)){throw new SessionWriterUnavailableError({cause:new Error("Session writer sealed candidate already exists")})}await assertPathMissing(handoffRetiredPath);if(!await installLockRecord(this.claimPath,ownedRecord)){throw new SessionWriterUnavailableError({cause:new Error("Session writer transition claim already exists")})}claimAcquired=true;await this.readOwnedLock();await validateOpenTranscriptProof(this.transcriptPath,proof);transitionStarted=true;await transitionExactPrimary(this.lockPath,this.lockRecordRaw,sealedCandidatePath,sealedRaw,handoffRetiredPath,this.sessionId,this.claimPath,this.lockRecordRaw);transitionCommitted=true;await validateOpenTranscriptProof(this.transcriptPath,proof);await releaseTransitionClaim(this.claimPath,this.lockRecordRaw);claimAcquired=false;this.released=true;await removeExactRecord(handoffRetiredPath,this.lockRecordRaw).catch(error3=>{debugLogger15.debug(`Session writer handoff retired cleanup failed path=${JSON.stringify(handoffRetiredPath)} error=${describeDiagnosticError(error3)}`)});await removeExactRecord(sealedCandidatePath,sealedRaw).catch(error3=>{debugLogger15.debug(`Session writer handoff candidate cleanup failed path=${JSON.stringify(sealedCandidatePath)} error=${describeDiagnosticError(error3)}`)});debugLogger15.info(`Session writer handoff sealed sessionId=${JSON.stringify(this.sessionId)} hostname=${JSON.stringify(ownedRecord.hostname)} pid=${ownedRecord.pid} sealedAt=${sealedRecord.sealed_at}`)}catch(error3){const cleanupFailures=[];const claimState=claimAcquired?(await inspectExactRecord(this.claimPath,this.lockRecordRaw)).state:"missing";if(claimState==="unknown"){cleanupFailures.push(new SessionWriterUnavailableError({cause:new Error("Session writer transition claim ownership is unreadable")}))}if(transitionCommitted&&claimState==="exact"){try{await rollbackExactTransition(this.lockPath,sealedRaw,handoffRetiredPath,this.lockRecordRaw,this.sessionId,this.claimPath,this.lockRecordRaw)}catch(cleanupError){cleanupFailures.push(cleanupError)}}if(claimState==="exact"){try{if(transitionStarted){await removeTransitionClaimAfterFailure(this.lockPath,this.lockRecordRaw,this.claimPath,this.lockRecordRaw)}else{await releaseTransitionClaim(this.claimPath,this.lockRecordRaw)}}catch(cleanupError){cleanupFailures.push(cleanupError)}}try{await removeExactRecord(sealedCandidatePath,sealedRaw)}catch(cleanupError){cleanupFailures.push(cleanupError)}if((await inspectExactRecord(this.lockPath,this.lockRecordRaw)).state!=="exact"){this.released=true}if(cleanupFailures.length>0){throw new SessionWriterUnavailableError({cause:new AggregateError([error3,...cleanupFailures],"Session writer handoff cleanup failed")})}if(error3 instanceof SessionWriterError)throw error3;throw new SessionWriterUnavailableError({cause:error3 instanceof Error?error3:void 0})}finally{await closeTranscriptProof(proof)}}async readOwnedLockForRelease(){for(let attempt2=0;attempt2<RELEASE_PRECHECK_ATTEMPTS;attempt2++){try{return await this.readOwnedLock()}catch(error3){if(!(error3 instanceof SessionWriterUnavailableError)||attempt2+1===RELEASE_PRECHECK_ATTEMPTS){throw error3}}await delay2(RELEASE_PRECHECK_RETRY_DELAY_MS)}throw new SessionWriterUnavailableError}async inspectReleasePath(candidatePath){try{const stat15=await fs9.lstat(candidatePath);if(!stat15.isFile()||stat15.isSymbolicLink())return"other";const raw=await fs9.readFile(candidatePath,"utf8");return raw===this.lockRecordRaw?"owned":"other"}catch(error3){return error3.code==="ENOENT"?"missing":"unknown"}}};init_esbuild_shims();import{createHash as createHash8,randomUUID as randomUUID3}from"node:crypto";import{constants}from"node:fs";import{link as link3,lstat as lstat3,mkdir as mkdir6,open as open3,rename as rename3,unlink as unlink6}from"node:fs/promises";import*as path12 from"node:path";var MANAGED_SESSION_RESOURCE_LIMITS=Object.freeze({maxResourceBytes:64*1024*1024});var LocalManagedSessionResourceStore=class _LocalManagedSessionResourceStore{constructor(root,sessionKey){this.root=root;this.sessionKey=sessionKey}static{__name(this,"LocalManagedSessionResourceStore")}static create(options2){return new _LocalManagedSessionResourceStore(managedSessionResourceRoot(options2.runtimeBaseDir,options2.sessionKey.sessionId),options2.sessionKey)}get sessionRoot(){return this.root}async publish(kind,bytes){if(kind==="managed-local-journal-snapshot"||kind==="managed-local-journal-snapshot-page"){throw new ManagedSessionRecordError("Native snapshot resources use their dedicated publisher.")}return this.publishBytes(kind,bytes,randomUUID3(),false)}publishJournalSnapshot(kind,bytes){return this.publishBytes(kind,bytes,createHash8("sha256").update(bytes).digest("hex"),true)}async publishBytes(kind,bytes,resourceId,immutable){const safeKind=assertPathSegment(kind,"kind");if(bytes.byteLength>MANAGED_SESSION_RESOURCE_LIMITS.maxResourceBytes){throw new ManagedSessionRecordError(`${safeKind} is ${bytes.byteLength} bytes where ${MANAGED_SESSION_RESOURCE_LIMITS.maxResourceBytes} is the maximum.`)}const directory=path12.join(this.root,safeKind);const pending=path12.join(directory,immutable?`.${resourceId}.${randomUUID3()}.pending`:`.${resourceId}.pending`);const target=path12.join(directory,resourceId);await ensurePrivateDirectory(path12.dirname(this.root));await ensurePrivateDirectory(this.root);const checkedDirectory=await ensurePrivateDirectory(directory);const resourceRef={resourceId,kind:safeKind,schemaVersion:1,byteLength:bytes.byteLength,digest:immutable?resourceId:createHash8("sha256").update(bytes).digest("hex")};if(immutable&&await lstatOrUndefined(target)){await this.read(resourceRef);await syncDirectory(directory);return resourceRef}const handle=await open3(pending,"wx",384);let written;try{await handle.writeFile(bytes);await handle.sync();written=await handle.stat()}catch(cause){await handle.close();await unlink6(pending).catch(()=>void 0);throw cause}await handle.close();try{if(immutable){try{await link3(pending,target)}catch(cause){if(cause.code!=="EEXIST")throw cause;await this.read(resourceRef);await unlink6(pending);await syncDirectory(directory);return resourceRef}await unlink6(pending)}else{await rename3(pending,target)}const destination=await lstatOrUndefined(directory);const published=await lstatOrUndefined(target);if(destination===void 0||destination.isSymbolicLink()||!destination.isDirectory()||destination.dev!==checkedDirectory.dev||destination.ino!==checkedDirectory.ino||published===void 0||!published.isFile()||published.dev!==written.dev||published.ino!==written.ino){throw new ManagedSessionRecordError(`resource ${resourceId} was not published inside its session directory.`)}await syncDirectory(directory)}catch(cause){await unlink6(pending).catch(()=>void 0);throw cause}return resourceRef}async read(ref11){const target=path12.join(this.root,assertPathSegment(ref11.kind,"kind"),assertPathSegment(ref11.resourceId,"resourceId"));try{for(const directory of[path12.dirname(this.root),this.root,path12.dirname(target)]){const ancestor=await lstat3(directory);if(ancestor.isSymbolicLink()||!ancestor.isDirectory()){throw new ManagedSessionRecordError(`session resource directory is not private: ${directory} is not a real directory.`)}}}catch(cause){if(cause instanceof ManagedSessionRecordError)throw cause;if(cause.code==="ENOENT"){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is not present for session ${this.sessionKey.sessionId}.`)}throw cause}let bytes;let size;try{const stat15=await lstat3(target);if(!stat15.isFile()){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is not a regular file.`)}size=stat15.size}catch(cause){if(cause instanceof ManagedSessionRecordError)throw cause;if(cause.code==="ENOENT"){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is not present for session ${this.sessionKey.sessionId}.`)}throw cause}if(size!==ref11.byteLength){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is ${size} bytes on disk where ${ref11.byteLength} was recorded.`)}let handle;try{handle=await openNoFollow(target)}catch(cause){if(cause.code==="ENOENT"){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is not present for session ${this.sessionKey.sessionId}.`)}if(cause.code==="ELOOP"){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is not a regular file.`)}if(isUnverifiableIdentityError(cause)){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} could not be identity-verified.`)}throw cause}try{const opened=await handle.stat();if(!opened.isFile()||opened.size!==size){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} changed while it was being read.`)}bytes=await handle.readFile()}finally{await handle.close()}if(bytes.byteLength!==ref11.byteLength){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} is ${bytes.byteLength} bytes where ${ref11.byteLength} was recorded.`)}const digest2=createHash8("sha256").update(bytes).digest("hex");if(digest2!==ref11.digest){throw new ManagedSessionRecordError(`resource ${ref11.resourceId} does not match its recorded digest.`)}return bytes}};async function readManagedBranchCheckpoint(event,resources,checkpointSequence,committedSequence){if(event.kind!=="checkpoint.committed")return void 0;if(resources===void 0){throw new ManagedSessionRecordError("a resource store is required to classify checkpoints.")}const ref11=assertManagedSessionDurableRef(event.payload["stateRef"],"checkpoint state");const branch=ref11.kind==="managed-branch-checkpoint";if(ref11.schemaVersion!==1||!branch&&ref11.kind!=="managed-checkpoint"){throw new ManagedSessionRecordError("unknown checkpoint state format.")}const id6=event.payload["checkpointId"];const covered=event.payload["coveredSequence"];const previous=event.payload["previousCheckpointId"];const previousSequence=previous===null?void 0:checkpointSequence(previous);if(checkpointSequence(id6)!==void 0||covered>=event.sequence||covered>committedSequence||previous!==null&&(previousSequence===void 0||previousSequence>covered)){throw new ManagedSessionRecordError("invalid checkpoint coverage or predecessor.")}if(branch&&(event.payload["boundary"]!==null||covered!==event.sequence-1)){throw new ManagedSessionRecordError("invalid historical branch checkpoint boundary.")}if(!branch)return void 0;const bytes=await resources.read(ref11);return assertManagedBranchRecord(parseManagedSessionRecordJson(bytes.toString("utf8"),ref11.byteLength),event.sessionKey,id6)}__name(readManagedBranchCheckpoint,"readManagedBranchCheckpoint");function assertPathSegment(value,label){if(value.length===0){throw new ManagedSessionRecordError(`${label} must not be empty.`)}if(value!==path12.basename(value)||value==="."||value===".."){throw new ManagedSessionRecordError(`${label} must be a single path segment.`)}return value}__name(assertPathSegment,"assertPathSegment");async function ensurePrivateDirectory(directory){const created=await mkdir6(directory,{recursive:true,mode:448});const stat15=await lstat3(directory);if(stat15.isSymbolicLink()||!stat15.isDirectory()){throw new ManagedSessionRecordError(`session resource directory is not private: ${directory} is not a real directory.`)}if(process.platform!=="win32"&&(stat15.mode&511)!==448){await tightenDirectory(directory)}if(created!==void 0){await syncDirectory(path12.dirname(directory))}return{dev:stat15.dev,ino:stat15.ino}}__name(ensurePrivateDirectory,"ensurePrivateDirectory");async function lstatOrUndefined(target){try{return await lstat3(target)}catch(cause){if(cause.code==="ENOENT")return void 0;throw cause}}__name(lstatOrUndefined,"lstatOrUndefined");async function tightenDirectory(directory){const flags=constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_DIRECTORY??0);let handle;try{handle=await open3(directory,flags)}catch{return}try{const opened=await handle.stat();if(!opened.isDirectory())return;await handle.chmod(448)}catch{}finally{await handle.close()}}__name(tightenDirectory,"tightenDirectory");async function syncDirectory(directory){const handle=await open3(directory,"r");try{await handle.sync()}catch(error3){if(process.platform!=="win32"||!["EACCES","EINVAL","EPERM"].includes(error3.code??"")){throw error3}}finally{await handle.close()}}__name(syncDirectory,"syncDirectory");init_esbuild_shims();init_esbuild_shims();import{createHash as createHash9}from"node:crypto";init_esbuild_shims();var CHANNEL_ROUTE_SCOPE_KINDS=["user","chat_thread","thread","single"];var CHANNEL_DELIVERY_MAX_SEGMENTS=64;var ROUTE_KEYS=["routeId","channelInstanceId","accountId","accountGeneration","routeRevision","rootSessionId","sessionId","scope","policyRef","run"];var DELIVERY_KEYS2=["deliveryId","routeId","routeRevision","sourceTurnId","contentRef","segments","cancelRequested","run"];var SCOPE_KEYS2=["kind","senderId","chatId","threadId"];var SEGMENT_KEYS=["segmentId","ordinal","contentRef","receipt"];var RECEIPT_KEYS=["providerMessageId","acceptedAt","proofRef"];var REBIND_KEYS=["accountGeneration","routeRevision","rootSessionId","sessionId","policyRef"];var TERMINAL_RUN_STATES2=["settled","failed","cancelled"];function fail2(message){throw new ManagedSessionRecordError(message)}__name(fail2,"fail");function closed2(value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key))){fail2(`Channel record must have exactly the keys ${keys2.join(", ")}.`)}return{...value}}__name(closed2,"closed");function id2(value,label){return assertManagedSessionStableId(value,label)}__name(id2,"id");function revision3(value,label){const parsed=assertManagedSessionSequence(value,label);if(parsed<1)fail2(`${label} must be positive.`);return parsed}__name(revision3,"revision");function ref3(value,label){return Object.freeze(assertManagedSessionDurableRef(value,label))}__name(ref3,"ref");function parseScope(value){const body=closed2(value,SCOPE_KEYS2);const kind=body.kind;if(kind!=="user"&&kind!=="chat_thread"&&kind!=="thread"&&kind!=="single"){fail2("Channel route scope kind must be user, chat_thread, thread or single.")}const nullableId3=__name((field,label)=>field===null?null:id2(field,label),"nullableId");const scope={kind,senderId:nullableId3(body.senderId,"scope.senderId"),chatId:nullableId3(body.chatId,"scope.chatId"),threadId:nullableId3(body.threadId,"scope.threadId")};const{senderId,chatId,threadId}=scope;const carries=scope.kind==="user"?senderId!==null&&chatId!==null&&threadId===null:scope.kind==="thread"?senderId===null&&chatId===null!==(threadId===null):scope.kind==="chat_thread"?senderId===null&&chatId!==null:senderId===null&&chatId===null&&threadId===null;if(!carries){fail2(`Channel route scope ${scope.kind} does not carry its identity.`)}return Object.freeze(scope)}__name(parseScope,"parseScope");function routeRun(value,routeId){const run=parseExtensionRun(value);if(run.definition!==null||run.executionCallId!==null||run.effectId!==routeId||run.dispatchId!==null||run.deliveryId!==null||run.execution!==null||run.runtime!==null||run.delivery!==null){fail2("Channel route run must identify its effect and nothing else.")}return run}__name(routeRun,"routeRun");function parseChannelRoute(value){const body=closed2(value,ROUTE_KEYS);const routeId=id2(body.routeId,"routeId");return Object.freeze({routeId,channelInstanceId:id2(body.channelInstanceId,"channelInstanceId"),accountId:id2(body.accountId,"accountId"),accountGeneration:revision3(body.accountGeneration,"accountGeneration"),routeRevision:revision3(body.routeRevision,"routeRevision"),rootSessionId:id2(body.rootSessionId,"rootSessionId"),sessionId:id2(body.sessionId,"sessionId"),scope:parseScope(body.scope),policyRef:ref3(body.policyRef,"policyRef"),run:routeRun(body.run,routeId)})}__name(parseChannelRoute,"parseChannelRoute");function parseReceipt(value){const body=closed2(value,RECEIPT_KEYS);return Object.freeze({providerMessageId:id2(body.providerMessageId,"receipt.providerMessageId"),acceptedAt:assertManagedSessionTime(body.acceptedAt,"receipt.acceptedAt"),proofRef:body.proofRef===null?null:ref3(body.proofRef,"proofRef")})}__name(parseReceipt,"parseReceipt");function parseSegments(value){if(!Array.isArray(value))fail2("Channel delivery segments must be a list.");if(value.length<1||value.length>CHANNEL_DELIVERY_MAX_SEGMENTS){fail2(`Channel delivery segments must number 1 to ${CHANNEL_DELIVERY_MAX_SEGMENTS}.`)}const seen=new Set;const segments=[];for(let index=0;index<value.length;index+=1){const body=closed2(value[index],SEGMENT_KEYS);const segmentId=id2(body.segmentId,`segments[${index}].segmentId`);if(seen.has(segmentId)){fail2(`Channel delivery segment ${segmentId} is named twice.`)}seen.add(segmentId);const ordinal=assertManagedSessionSequence(body.ordinal,`segments[${index}].ordinal`);if(ordinal!==index){fail2("Channel delivery segment ordinals must be dense from zero.")}segments.push(Object.freeze({segmentId,ordinal,contentRef:ref3(body.contentRef,`segments[${index}].contentRef`),receipt:body.receipt===null?null:parseReceipt(body.receipt)}))}return Object.freeze(segments)}__name(parseSegments,"parseSegments");function deliveryRun(value,deliveryId){const run=parseExtensionRun(value);if(run.definition!==null||run.executionCallId!==null||run.effectId!==deliveryId||run.dispatchId!==null||run.deliveryId!==deliveryId||run.execution!==null||run.runtime!==null||run.delivery===null||run.delivery.target!=="channel"){fail2("Channel delivery run must carry its channel delivery line and nothing else.")}return run}__name(deliveryRun,"deliveryRun");function parseChannelDelivery(value){const body=closed2(value,DELIVERY_KEYS2);if(typeof body.cancelRequested!=="boolean"){fail2("Channel delivery cancelRequested must be boolean.")}const deliveryId=id2(body.deliveryId,"deliveryId");const run=deliveryRun(body.run,deliveryId);const segments=parseSegments(body.segments);const receipts=segments.map(segment=>segment.receipt!==null);const settled=receipts.filter(Boolean).length;const state=run.delivery.state;const pins={planned:run.state==="admitted"&&settled===0,sending:(run.state==="running"||run.state==="waiting"||run.state==="recovery_blocked")&&settled<segments.length,partial:(run.state==="running"||run.state==="waiting"||run.state==="recovery_blocked")&&settled>0&&settled<segments.length,delivered:run.state==="settled"&&settled===segments.length,unknown:run.state==="waiting"&&run.reason===null&&settled<segments.length,rejected:run.state==="failed"&&settled<segments.length,cancelled:run.state==="cancelled"&&settled===0&&body.cancelRequested};if(!pins[state]){fail2(`Channel delivery line ${state} does not match its run and segment receipts.`)}return Object.freeze({deliveryId,routeId:id2(body.routeId,"routeId"),routeRevision:revision3(body.routeRevision,"routeRevision"),sourceTurnId:id2(body.sourceTurnId,"sourceTurnId"),contentRef:ref3(body.contentRef,"contentRef"),segments,cancelRequested:body.cancelRequested,run})}__name(parseChannelDelivery,"parseChannelDelivery");function accepts(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts,"accepts");function same(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same,"same");function isChannelRouteStart(value){return accepts(()=>isExtensionRunStart(parseChannelRoute(value).run))}__name(isChannelRouteStart,"isChannelRouteStart");function isChannelDeliveryStart(value){return accepts(()=>{const record4=parseChannelDelivery(value);return isExtensionRunStart(record4.run)&&!record4.cancelRequested&&record4.segments.every(segment=>segment.receipt===null)})}__name(isChannelDeliveryStart,"isChannelDeliveryStart");function isChannelRouteSuccessor(previous,next){return accepts(()=>{const before=parseChannelRoute(previous);const after=parseChannelRoute(next);if(!same(before.routeId,after.routeId)||!same(before.channelInstanceId,after.channelInstanceId)||!same(before.accountId,after.accountId)||!same(before.scope,after.scope)||!isExtensionRunSuccessor(before.run,after.run)){return false}if(TERMINAL_RUN_STATES2.includes(before.run.state)){return same(before,after)}if(before.routeRevision===after.routeRevision){return REBIND_KEYS.every(key=>same(before[key],after[key]))}return after.routeRevision===before.routeRevision+1&&after.accountGeneration>=before.accountGeneration})}__name(isChannelRouteSuccessor,"isChannelRouteSuccessor");function isChannelDeliverySuccessor(previous,next){return accepts(()=>{const before=parseChannelDelivery(previous);const after=parseChannelDelivery(next);if(before.deliveryId!==after.deliveryId||before.routeId!==after.routeId||before.routeRevision!==after.routeRevision||before.sourceTurnId!==after.sourceTurnId||!same(before.contentRef,after.contentRef)||before.segments.length!==after.segments.length||!before.segments.every((segment,index)=>{const other2=after.segments[index];return segment.segmentId===other2.segmentId&&segment.ordinal===other2.ordinal&&same(segment.contentRef,other2.contentRef)&&(segment.receipt===null||same(segment.receipt,other2.receipt))})||before.cancelRequested&&!after.cancelRequested||!isExtensionRunSuccessor(before.run,after.run)){return false}const settledOf=__name(record4=>record4.segments.filter(segment=>segment.receipt!==null).length,"settledOf");if(before.run.delivery.state==="unknown"&&after.run.delivery.state==="partial"&&settledOf(after)<=settledOf(before)){return false}if(TERMINAL_RUN_STATES2.includes(before.run.state)){return same(before,after)}return true})}__name(isChannelDeliverySuccessor,"isChannelDeliverySuccessor");var MANAGED_CHANNEL_LIMITS=Object.freeze({maxTextChars:32e3,maxEnvelopeBytes:64*1024,maxAttachments:16,maxInlineAttachmentBytes:64*1024,maxReplyContextBytes:8*1024,maxSegmentBytes:48*1024,maxSegments:CHANNEL_DELIVERY_MAX_SEGMENTS,maxSubjectChars:200});var CHANNEL_INPUT_SOURCE="channel";var CHANNEL_RESOURCE_KINDS=Object.freeze({policy:"managed-channel-policy",input:"managed-input",attachment:"managed-channel-attachment",reply:"managed-channel-reply",segment:"managed-channel-segment"});var SEPARATOR="\0";function sha256(parts){return createHash9("sha256").update(parts.map(String).join(SEPARATOR),"utf8").digest("hex")}__name(sha256,"sha256");function fail3(message){throw new ManagedSessionRecordError(message)}__name(fail3,"fail");function assertNoSeparator(value,label){if(value.length===0||value.includes(SEPARATOR)){fail3(`${label} must be non-empty and hold no NUL.`)}return value}__name(assertNoSeparator,"assertNoSeparator");function positive(value,label){if(!Number.isSafeInteger(value)||value<1){fail3(`${label} must be a positive integer.`)}return value}__name(positive,"positive");function channelRouteId(params){return`chrt-${sha256([assertNoSeparator(params.channelInstanceId,"channelInstanceId"),assertNoSeparator(params.accountId,"accountId"),params.scope.kind,params.scope.senderId??"",params.scope.chatId??"",params.scope.threadId??""])}`}__name(channelRouteId,"channelRouteId");function channelDeliveryId(inputId){return`${inputId}:reply`}__name(channelDeliveryId,"channelDeliveryId");function channelResendDeliveryId(deliveryId,attempt2){return`${deliveryId}:r${positive(attempt2,"attempt")}`}__name(channelResendDeliveryId,"channelResendDeliveryId");var CHANNEL_SENDER_POLICIES=["allowlist","open","disabled"];var CHANNEL_DISPATCH_MODES=["followup","steer"];function plainObject(value,label){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype){fail3(`${label} must be a JSON object.`)}return value}__name(plainObject,"plainObject");function exactKeys(record4,keys2,label){const present=Object.keys(record4).sort();if(present.join(",")!==[...keys2].sort().join(",")){fail3(`${label} must have exactly the keys ${keys2.join(", ")}.`)}}__name(exactKeys,"exactKeys");function parseJson(bytes,label){try{return JSON.parse(bytes.toString("utf8"))}catch{fail3(`${label} must be JSON.`)}}__name(parseJson,"parseJson");function text(value,label,max){if(typeof value!=="string"||value.length>max){fail3(`${label} must be text of at most ${max} characters.`)}return value}__name(text,"text");function nullableText(value,label,max){return value===null?null:text(value,label,max)}__name(nullableText,"nullableText");function encodeChannelPolicy(policy){return Buffer.from(JSON.stringify(decodeChannelPolicyValue(policy)),"utf8")}__name(encodeChannelPolicy,"encodeChannelPolicy");function decodeChannelPolicy(bytes){return decodeChannelPolicyValue(parseJson(bytes,"Channel policy"))}__name(decodeChannelPolicy,"decodeChannelPolicy");function assertChannelPolicy(value){return decodeChannelPolicyValue(value)}__name(assertChannelPolicy,"assertChannelPolicy");function decodeChannelPolicyValue(value){const record4=plainObject(value,"Channel policy");exactKeys(record4,["adapter","senderPolicy","allowedSenders","dispatchMode"],"Channel policy");const adapter=text(record4["adapter"],"Channel policy adapter",64);if(!/^[a-z][a-z0-9-]*$/.test(adapter)){fail3("Channel policy adapter must be a lowercase identifier.")}const senderPolicy=record4["senderPolicy"];if(!CHANNEL_SENDER_POLICIES.includes(senderPolicy)){fail3("Channel policy senderPolicy must be allowlist, open or disabled.")}const dispatchMode=record4["dispatchMode"];if(!CHANNEL_DISPATCH_MODES.includes(dispatchMode)){fail3("Channel policy dispatchMode must be followup or steer.")}const senders=record4["allowedSenders"];if(!Array.isArray(senders)||senders.length>1024||!senders.every(sender=>typeof sender==="string"&&sender.length>0)){fail3("Channel policy allowedSenders must list sender identities.")}return Object.freeze({adapter,senderPolicy,allowedSenders:Object.freeze([...senders]),dispatchMode})}__name(decodeChannelPolicyValue,"decodeChannelPolicyValue");var ENVELOPE_KEYS=["channelInstanceId","accountId","accountGeneration","platformEventId","semanticRevision","routeId","routeRevision","senderId","chatId","threadId","subject","text","attachments","replyContext"];var DIGEST=/^[a-f0-9]{64}$/;function parseAttachment(value,index){const label=`attachments[${index}]`;const record4=plainObject(value,label);const common={fileName:text(record4["fileName"],`${label}.fileName`,128),mimeType:text(record4["mimeType"],`${label}.mimeType`,128),byteLength:record4["byteLength"],digest:record4["digest"]};if(!Number.isSafeInteger(common.byteLength)||common.byteLength<0||typeof common.digest!=="string"||!DIGEST.test(common.digest)){fail3(`${label} must carry a byte length and a sha256 digest.`)}if("omitted"in record4){exactKeys(record4,["fileName","mimeType","byteLength","digest","omitted"],label);if(record4["omitted"]!=="too_large"){fail3(`${label}.omitted must be too_large.`)}return Object.freeze({...common,omitted:"too_large"})}exactKeys(record4,["fileName","mimeType","byteLength","digest","ref"],label);const ref11=assertManagedSessionDurableRef(record4["ref"],`${label}.ref`);if(ref11.digest!==common.digest||ref11.byteLength!==common.byteLength){fail3(`${label} must describe the bytes its reference names.`)}return Object.freeze({...common,ref:Object.freeze(ref11)})}__name(parseAttachment,"parseAttachment");function decodeEnvelopeValue(value){const record4=plainObject(value,"Channel input envelope");exactKeys(record4,ENVELOPE_KEYS,"Channel input envelope");const attachments=record4["attachments"];if(!Array.isArray(attachments)||attachments.length>MANAGED_CHANNEL_LIMITS.maxAttachments){fail3(`Channel input attachments must number at most ${MANAGED_CHANNEL_LIMITS.maxAttachments}.`)}const replyContext=record4["replyContext"];if(Buffer.byteLength(JSON.stringify(replyContext??null),"utf8")>MANAGED_CHANNEL_LIMITS.maxReplyContextBytes){fail3(`Channel reply context exceeds ${MANAGED_CHANNEL_LIMITS.maxReplyContextBytes} bytes (byte_limit).`)}const envelope2={channelInstanceId:assertNoSeparator(text(record4["channelInstanceId"],"channelInstanceId",128),"channelInstanceId"),accountId:assertNoSeparator(text(record4["accountId"],"accountId",512),"accountId"),accountGeneration:positive(record4["accountGeneration"],"accountGeneration"),platformEventId:assertNoSeparator(text(record4["platformEventId"],"platformEventId",512),"platformEventId"),semanticRevision:positive(record4["semanticRevision"],"semanticRevision"),routeId:text(record4["routeId"],"routeId",512),routeRevision:positive(record4["routeRevision"],"routeRevision"),senderId:text(record4["senderId"],"senderId",512),chatId:nullableText(record4["chatId"],"chatId",512),threadId:nullableText(record4["threadId"],"threadId",512),subject:nullableText(record4["subject"],"subject",MANAGED_CHANNEL_LIMITS.maxSubjectChars),text:text(record4["text"],"text",MANAGED_CHANNEL_LIMITS.maxTextChars),attachments:Object.freeze(attachments.map((entry,index)=>parseAttachment(entry,index))),replyContext:replyContext===void 0?null:replyContext};return Object.freeze(envelope2)}__name(decodeEnvelopeValue,"decodeEnvelopeValue");function encodeChannelInputEnvelope(envelope2){const bytes=Buffer.from(JSON.stringify(decodeEnvelopeValue(envelope2)),"utf8");if(bytes.byteLength>MANAGED_CHANNEL_LIMITS.maxEnvelopeBytes){fail3(`Channel input envelope exceeds ${MANAGED_CHANNEL_LIMITS.maxEnvelopeBytes} bytes (byte_limit).`)}return bytes}__name(encodeChannelInputEnvelope,"encodeChannelInputEnvelope");function decodeChannelInputEnvelope(bytes){return decodeEnvelopeValue(parseJson(bytes,"Channel input envelope"))}__name(decodeChannelInputEnvelope,"decodeChannelInputEnvelope");function escapeXml2(value){return value.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}__name(escapeXml2,"escapeXml");function channelInputText(envelope2){const lines=["<channel-message>",`<channel>${escapeXml2(envelope2.channelInstanceId)}</channel>`,`<sender>${escapeXml2(envelope2.senderId)}</sender>`,`<platform-event-id>${escapeXml2(envelope2.platformEventId)}</platform-event-id>`];if(envelope2.subject!==null){lines.push(`<subject untrusted="true">${escapeXml2(envelope2.subject)}</subject>`)}if(envelope2.attachments.length>0){lines.push("<attachments>");for(const attachment of envelope2.attachments){const status="omitted"in attachment?' omitted="too_large"':` resource="${escapeXml2(attachment.ref.resourceId)}"`;lines.push(`<attachment name="${escapeXml2(attachment.fileName)}" type="${escapeXml2(attachment.mimeType)}" bytes="${attachment.byteLength}" sha256="${attachment.digest}"${status}/>`)}lines.push("</attachments>")}lines.push(`<text>${escapeXml2(envelope2.text)}</text>`,"</channel-message>");return lines.join("\n")}__name(channelInputText,"channelInputText");function encodeChannelReply(reply){return Buffer.from(JSON.stringify({text:reply.text,replyContext:reply.replyContext}),"utf8")}__name(encodeChannelReply,"encodeChannelReply");function decodeChannelReply(bytes){const record4=plainObject(parseJson(bytes,"Channel reply"),"Channel reply");exactKeys(record4,["text","replyContext"],"Channel reply");if(typeof record4["text"]!=="string")fail3("Channel reply text is missing.");return Object.freeze({text:record4["text"],replyContext:record4["replyContext"]})}__name(decodeChannelReply,"decodeChannelReply");var TRUNCATION_NOTICE="\n\n[Reply truncated because it exceeded the channel segment size limit.]";var CHANNEL_TRUNCATION_NOTICE=TRUNCATION_NOTICE;function truncateChannelTextUtf8(text3,maxBytes){const bytes=Buffer.from(text3,"utf8");if(bytes.byteLength<=maxBytes){return text3}const limit=Math.max(0,maxBytes-Buffer.byteLength(TRUNCATION_NOTICE,"utf8"));let end=limit;while(end>0&&(bytes[end]&192)===128)end-=1;return bytes.subarray(0,end).toString("utf8")+TRUNCATION_NOTICE}__name(truncateChannelTextUtf8,"truncateChannelTextUtf8");function planChannelSegments(text3){return Object.freeze([truncateChannelTextUtf8(text3,MANAGED_CHANNEL_LIMITS.maxSegmentBytes)])}__name(planChannelSegments,"planChannelSegments");function routeRun2(routeId){return Object.freeze({state:"admitted",reason:null,definition:null,executionCallId:null,effectId:routeId,dispatchId:null,deliveryId:null,execution:null,runtime:null,delivery:null})}__name(routeRun2,"routeRun");function assertChannelRouteScope(value){const record4=plainObject(value,"Channel route scope");exactKeys(record4,["kind","senderId","chatId","threadId"],"scope");if(!CHANNEL_ROUTE_SCOPE_KINDS.includes(record4["kind"])){fail3("Channel route scope kind must be user, chat_thread, thread or single.")}return Object.freeze({kind:record4["kind"],senderId:nullableText(record4["senderId"],"scope.senderId",512),chatId:nullableText(record4["chatId"],"scope.chatId",512),threadId:nullableText(record4["threadId"],"scope.threadId",512)})}__name(assertChannelRouteScope,"assertChannelRouteScope");function channelRouteOpenBody(params){return Object.freeze({routeId:params.routeId,channelInstanceId:params.channelInstanceId,accountId:params.accountId,accountGeneration:positive(params.accountGeneration,"accountGeneration"),routeRevision:1,rootSessionId:params.rootSessionId,sessionId:params.sessionId,scope:params.scope,policyRef:params.policyRef,run:routeRun2(params.routeId)})}__name(channelRouteOpenBody,"channelRouteOpenBody");function channelRouteRolloverBody(previous,params){if(positive(params.accountGeneration,"accountGeneration")<=previous.accountGeneration){fail3(`Channel route ${previous.routeId} cannot roll its generation back to ${params.accountGeneration} (channel_generation_stale).`)}return Object.freeze({...previous,accountGeneration:params.accountGeneration,routeRevision:previous.routeRevision+1,policyRef:params.policyRef??previous.policyRef})}__name(channelRouteRolloverBody,"channelRouteRolloverBody");function deliveryRun2(deliveryId,state,line2){return Object.freeze({state,reason:null,definition:null,executionCallId:null,effectId:deliveryId,dispatchId:null,deliveryId,execution:null,runtime:null,delivery:Object.freeze({target:"channel",state:line2})})}__name(deliveryRun2,"deliveryRun");function channelDeliveryPlanBody(params){if(params.segments.length<1||params.segments.length>MANAGED_CHANNEL_LIMITS.maxSegments){fail3(`Channel delivery plans 1 to ${MANAGED_CHANNEL_LIMITS.maxSegments} segments.`)}return Object.freeze({deliveryId:params.deliveryId,routeId:params.routeId,routeRevision:positive(params.routeRevision,"routeRevision"),sourceTurnId:params.sourceTurnId,contentRef:params.contentRef,segments:Object.freeze(params.segments.map((segment,ordinal)=>Object.freeze({segmentId:segment.segmentId,ordinal,contentRef:segment.contentRef,receipt:null}))),cancelRequested:false,run:deliveryRun2(params.deliveryId,"admitted","planned")})}__name(channelDeliveryPlanBody,"channelDeliveryPlanBody");function withRun(previous,state,line2,changes={}){return Object.freeze({...previous,...changes,run:deliveryRun2(previous.deliveryId,state,line2)})}__name(withRun,"withRun");function channelDeliverySendingBody(previous){return withRun(previous,"running","sending")}__name(channelDeliverySendingBody,"channelDeliverySendingBody");function channelDeliveryProvenSegments(delivery){return delivery.segments.filter(segment=>segment.receipt!==null).length}__name(channelDeliveryProvenSegments,"channelDeliveryProvenSegments");function channelDeliveryReceiptBody(previous,ordinal,receipt){const segment=previous.segments[ordinal];if(segment===void 0){fail3(`Channel delivery ${previous.deliveryId} has no segment ${ordinal}.`)}if(segment.receipt!==null){fail3(`Channel delivery segment ${segment.segmentId} already has a receipt.`)}const segments=previous.segments.map((entry,index)=>index===ordinal?Object.freeze({...entry,receipt}):entry);const settled=segments.filter(entry=>entry.receipt!==null).length;const complete=settled===segments.length;return withRun(previous,complete?"settled":previous.run.state==="waiting"?"waiting":"running",complete?"delivered":"partial",{segments:Object.freeze(segments)})}__name(channelDeliveryReceiptBody,"channelDeliveryReceiptBody");function channelDeliveryUnknownBody(previous){return withRun(previous,"waiting","unknown")}__name(channelDeliveryUnknownBody,"channelDeliveryUnknownBody");function channelDeliveryRejectedBody(previous){return withRun(previous,"failed","rejected")}__name(channelDeliveryRejectedBody,"channelDeliveryRejectedBody");function channelDeliveryCancelRequestedBody(previous){return Object.freeze({...previous,cancelRequested:true})}__name(channelDeliveryCancelRequestedBody,"channelDeliveryCancelRequestedBody");function channelDeliveryCancelledBody(previous){if(previous.run.delivery?.state!=="planned"){fail3(`Channel delivery ${previous.deliveryId} is ${previous.run.delivery?.state} and can no longer be cancelled.`)}return withRun(previous,"cancelled","cancelled",{cancelRequested:true})}__name(channelDeliveryCancelledBody,"channelDeliveryCancelledBody");function channelDeliveryResendable(delivery){const state=delivery.run.delivery?.state;return(state==="unknown"||state==="rejected")&&channelDeliveryProvenSegments(delivery)<delivery.segments.length}__name(channelDeliveryResendable,"channelDeliveryResendable");function channelDeliveryResendBody(previous,deliveryId){if(!channelDeliveryResendable(previous)){fail3(`Channel delivery ${previous.deliveryId} is ${previous.run.delivery?.state} and cannot be resent.`)}return channelDeliveryPlanBody({deliveryId,routeId:previous.routeId,routeRevision:previous.routeRevision,sourceTurnId:previous.sourceTurnId,contentRef:previous.contentRef,segments:previous.segments.filter(segment=>segment.receipt===null).map(segment=>({segmentId:segment.segmentId,contentRef:segment.contentRef}))})}__name(channelDeliveryResendBody,"channelDeliveryResendBody");init_esbuild_shims();init_esbuild_shims();var CHILD_RUN_STOP_REASONS=Object.freeze({settled:Object.freeze(["exited"]),failed:Object.freeze(["start_failed","process_failed","quota_exceeded"]),cancelled:Object.freeze(["stop_requested"])});var CHILD_AGENT_STOP_REASONS=Object.freeze({settled:Object.freeze(["completed"]),failed:Object.freeze(["creation_failed","child_failed","quota_exceeded"]),cancelled:Object.freeze(["stop_requested"])});function isChildSessionRun(record4){switch(record4.kind){case"child_agent":case"workflow":return true;case"shell":return false;default:{const unclassified=record4;void unclassified;return false}}}__name(isChildSessionRun,"isChildSessionRun");var SHELL_KEYS=["commandRef","exitCode","exitSignal","kind","outputRef","ownerScopeId","run","shellId","startReceiptRef","stopReason","stopRequested"];var SHELL_FIXED_KEYS=["commandRef","kind","ownerScopeId","shellId"];var CHILD_AGENT_KEYS=["childRunId","childSessionId","completion","depth","inputRef","kind","ownerScopeId","predecessorChildRunId","resultRef","resultVersion","rootSessionId","run","stopReason","stopRequested","terminalReceiptRef","workspaceMode","workingDirectory"];var CHILD_AGENT_FIXED_KEYS=["childRunId","completion","depth","inputRef","kind","ownerScopeId","predecessorChildRunId","rootSessionId","workspaceMode","workingDirectory"];var TERMINAL_RUN_STATES3=["settled","failed","cancelled"];var UNSTARTED_EXECUTION_STATES2=[null,"intent","dispatch_started","not_started_proven"];var EXIT_SIGNAL_PATTERN=/^[A-Z][A-Z0-9]{0,15}$/;var WORKSPACE_MODES=["shared","snapshot","worktree"];var MAX_DEPTH=8;function fail4(message){throw new ManagedSessionRecordError(message)}__name(fail4,"fail");function closed3(value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key)))fail4(`Child run must have exactly the keys ${keys2.join(", ")}.`);return{...value}}__name(closed3,"closed");function id3(value,label){return assertManagedSessionStableId(value,label)}__name(id3,"id");function ref4(value,label){return Object.freeze(assertManagedSessionDurableRef(value,label))}__name(ref4,"ref");function nullable2(value,parse15){return value===null?null:parse15(value)}__name(nullable2,"nullable");function accepts2(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts2,"accepts");function same2(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same2,"same");function setOnce2(before,after){return before===null||same2(before,after)}__name(setOnce2,"setOnce");function stopReasonOf(value,reasons,run){const stopReason=nullable2(value,reason=>{if(typeof reason!=="string"||!Object.values(reasons).some(fitting=>fitting.includes(reason))){fail4("Child run stopReason is not a closed stop reason.")}return reason});if(stopReason===null!==!TERMINAL_RUN_STATES3.includes(run.state)){fail4("Child run stopReason is set exactly when the run ends.")}if(stopReason!==null){const fitting=Object.hasOwn(reasons,run.state)?reasons[run.state]:[];if(!fitting.includes(stopReason)){fail4(`Child run stopReason ${stopReason} does not fit the ${run.state} state.`)}}return stopReason}__name(stopReasonOf,"stopReasonOf");function stopFlags(stopReason,stopRequestedValue,run){if(typeof stopRequestedValue!=="boolean"){fail4("Child run stopRequested must be boolean.")}if(stopReason==="stop_requested"&&!stopRequestedValue){fail4("Child run stop_requested needs its stop request.")}const quota=run.reason!==null&&MANAGED_EXTENSION_REASONS.quota.includes(run.reason);if(stopReason==="quota_exceeded"!==quota){fail4("Child run stopReason is quota_exceeded exactly for a quota reason.")}return stopRequestedValue}__name(stopFlags,"stopFlags");function parseChildRun(value){const kind=typeof value==="object"&&value!==null?value["kind"]:void 0;if(kind==="shell")return parseChildShellRecord(value);if(kind==="child_agent"||kind==="workflow"){return parseChildSessionRun(value,kind)}fail4("Child run kind must be one of shell, child_agent, workflow in schema version 1.")}__name(parseChildRun,"parseChildRun");function parseChildShellRun(value){const record4=parseChildRun(value);if(record4.kind!=="shell"){fail4(`Child run kind must be 'shell' for this consumer, got ${record4.kind}.`)}return record4}__name(parseChildShellRun,"parseChildShellRun");function parseChildShellRecord(value){const body=closed3(value,SHELL_KEYS);const run=parseExtensionRun(body.run);if(run.executionCallId===null||run.effectId!==null||run.dispatchId!==null||run.deliveryId!==null||run.delivery!==null||run.definition!==null){fail4("Child run must name its start call and nothing else.")}const execution=run.execution;const startReceiptRef=nullable2(body.startReceiptRef,each=>ref4(each,"startReceiptRef"));if(startReceiptRef!==null&&UNSTARTED_EXECUTION_STATES2.includes(execution)){fail4("Child run startReceiptRef must be null before the process starts.")}if(startReceiptRef===null&&(execution==="running_attached"||execution==="settled")){fail4("Child run startReceiptRef must be set once the process started.")}if(startReceiptRef!==null&&run.runtime===null){fail4("Child run startReceiptRef needs the Runtime binding that started it.")}const outputRef=nullable2(body.outputRef,each=>{const output=ref4(each,"outputRef");if(output.kind!==MANAGED_TOOL_RESULT_KINDS.manifest||output.schemaVersion!==1){fail4(`Child run outputRef must reference ${MANAGED_TOOL_RESULT_KINDS.manifest} version 1.`)}return output});if(outputRef!==null&&startReceiptRef===null){fail4("Child run outputRef needs a start receipt.")}const stopReason=stopReasonOf(body.stopReason,CHILD_RUN_STOP_REASONS,run);const stopRequested=stopFlags(stopReason,body.stopRequested,run);const exitCode=nullable2(body.exitCode,code=>{if(typeof code!=="number"||!Number.isInteger(code)||code<0||code>255){fail4("Child run exitCode must be an integer from 0 to 255.")}return code});const exitSignal=nullable2(body.exitSignal,signal=>{if(typeof signal!=="string"||!EXIT_SIGNAL_PATTERN.test(signal)){fail4("Child run exitSignal must be an uppercase signal name.")}return signal});if(run.state==="settled"&&execution!=="settled"){fail4("Child run settled needs its settled execution.")}if(run.state==="cancelled"&&execution!=="settled"){fail4("Child run cancelled needs its settled execution.")}if(run.state==="failed"&&execution!=="settled"&&execution!=="not_started_proven"){fail4("Child run failed needs settled or not_started_proven execution.")}if(stopReason==="start_failed"&&(startReceiptRef!==null||execution!=="not_started_proven")){fail4("Child run start_failed needs a process that never started.")}if(stopReason==="process_failed"&&startReceiptRef===null){fail4("Child run process_failed needs a process that started.")}if((stopReason==="process_failed"||stopReason==="quota_exceeded")&&execution!=="settled"){fail4("Child run process failure needs its settled execution.")}if(stopReason==="exited"?exitCode===null&&exitSignal===null:exitCode!==null||exitSignal!==null){fail4("Child run exitCode or exitSignal is proven exactly when it exits.")}return Object.freeze({kind:"shell",shellId:id3(body.shellId,"shellId"),ownerScopeId:id3(body.ownerScopeId,"ownerScopeId"),commandRef:ref4(body.commandRef,"commandRef"),startReceiptRef,outputRef,stopReason,stopRequested,exitCode,exitSignal,run})}__name(parseChildShellRecord,"parseChildShellRecord");function parseChildSessionRun(value,kind){const body=closed3(value,CHILD_AGENT_KEYS);const run=parseExtensionRun(body.run);if(run.executionCallId===null||run.effectId!==null||run.deliveryId!==null){fail4("Child run must name its start call, never an effect or a channel delivery.")}const delivery=run.delivery;if(delivery===null||delivery.target!=="session"){fail4("Child run delivery must target the parent session.")}if(kind==="workflow"&&run.definition===null){fail4("Workflow run must pin its workflow definition from launch.")}if(run.execution!==null&&run.execution!=="intent"&&run.definition===null){fail4("Child run must pin the definition it dispatched.")}const depth=body.depth;if(typeof depth!=="number"||!Number.isInteger(depth)||depth<1||depth>MAX_DEPTH){fail4(`Child run depth must be an integer from 1 to ${MAX_DEPTH}.`)}const completion=body.completion;if(completion!=="tool"&&completion!=="sent"){fail4(`Child run completion must be 'tool' or 'sent'.`)}const inputRef=ref4(body.inputRef,"inputRef");const workspaceMode=body.workspaceMode;if(typeof workspaceMode!=="string"||!WORKSPACE_MODES.includes(workspaceMode)){fail4(`Child run workspaceMode must be one of ${WORKSPACE_MODES.join(", ")}.`)}const workingDirectory=body.workingDirectory;if(typeof workingDirectory!=="string"||!isRelativeDirectory(workingDirectory)){fail4("Child run workingDirectory must be a normalized relative directory.")}const childSessionId=nullable2(body.childSessionId,each=>id3(each,"childSessionId"));if(childSessionId!==null&&run.execution!=="not_started_proven"&&UNSTARTED_EXECUTION_STATES2.includes(run.execution)){fail4("Child run childSessionId needs its admitted creation dispatch.")}if(childSessionId===null&&(run.execution==="running_attached"||run.execution==="settled")){fail4("Child run childSessionId is set once creation is proven.")}if(childSessionId!==null&&run.runtime===null&&run.execution!=="not_started_proven"){fail4("Child run childSessionId needs the Runtime binding that hosts it.")}if((run.execution==="dispatch_started"||run.execution==="outcome_unknown")&&run.runtime===null){fail4("Child run dispatch needs a Runtime binding.")}const predecessorChildRunId=nullable2(body.predecessorChildRunId,each=>id3(each,"predecessorChildRunId"));const resultVersion=body.resultVersion;if(resultVersion!==1){fail4("Child run resultVersion must be 1 in schema version 1.")}const resultRef=nullable2(body.resultRef,each=>ref4(each,"resultRef"));const terminalReceiptRef=nullable2(body.terminalReceiptRef,each=>ref4(each,"terminalReceiptRef"));if(resultRef!==null!==(terminalReceiptRef!==null)){fail4("Child run resultRef and terminalReceiptRef change only together.")}if(resultRef!==null!==(run.state==="settled")){fail4("Child run resultRef and terminalReceiptRef are set exactly when the run settles.")}if((run.state==="failed"||run.state==="cancelled")!==(delivery.state==="cancelled")){fail4("Child run delivery cancelled is set exactly when the run ends without a result.")}const stopReason=stopReasonOf(body.stopReason,CHILD_AGENT_STOP_REASONS,run);const stopRequested=stopFlags(stopReason,body.stopRequested,run);if(run.state==="settled"&&run.execution!=="settled"){fail4("Child run settled needs its settled execution.")}if(run.state==="cancelled"&&run.execution!=="settled"&&run.execution!=="not_started_proven"){fail4("Child run cancelled needs settled or not_started_proven execution.")}if(run.state==="failed"&&run.execution!=="settled"&&run.execution!=="not_started_proven"){fail4("Child run failed needs settled or not_started_proven execution.")}if(stopReason==="creation_failed"&&run.execution!=="not_started_proven"){fail4("Child run creation_failed needs a creation that never started.")}if(stopReason==="child_failed"&&run.execution!=="settled"){fail4("Child run child_failed needs its settled execution.")}return Object.freeze({kind,childRunId:id3(body.childRunId,"childRunId"),ownerScopeId:id3(body.ownerScopeId,"ownerScopeId"),rootSessionId:id3(body.rootSessionId,"rootSessionId"),depth,completion,inputRef,workspaceMode,workingDirectory,childSessionId,predecessorChildRunId,resultVersion,resultRef,terminalReceiptRef,stopReason,stopRequested,run})}__name(parseChildSessionRun,"parseChildSessionRun");function isRelativeDirectory(value){if(value===".")return true;if(value.startsWith("/")||value.endsWith("/")||value.includes("\\")||/^[A-Za-z]:/.test(value)){return false}if(value.split("/").some(segment=>segment===""||segment==="."||segment==="..")){return false}try{assertManagedSessionStableId(value,"workingDirectory")}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}return true}__name(isRelativeDirectory,"isRelativeDirectory");function isChildRunStart(value){return accepts2(()=>{const record4=parseChildRun(value);if(!isExtensionRunStart(record4.run)||record4.stopRequested)return false;if(record4.kind==="shell")return record4.outputRef===null;return isChildSessionRun(record4)&&record4.run.delivery!==null&&record4.run.delivery.state==="planned"&&record4.childSessionId===null&&record4.resultRef===null&&record4.terminalReceiptRef===null})}__name(isChildRunStart,"isChildRunStart");function isChildRunSuccessor(previous,next){return accepts2(()=>{const before=parseChildRun(previous);const after=parseChildRun(next);if(before.kind!==after.kind)return false;if(before.kind==="shell"&&after.kind==="shell"){if(SHELL_FIXED_KEYS.some(key=>!same2(before[key],after[key]))||!isExtensionRunSuccessor(before.run,after.run)||before.outputRef!==null&&after.outputRef===null||before.stopRequested&&!after.stopRequested||!setOnce2(before.startReceiptRef,after.startReceiptRef)){return false}if(TERMINAL_RUN_STATES3.includes(before.run.state)){return same2(before,after)}return true}if(!isChildSessionRun(before)||!isChildSessionRun(after))return false;if(TERMINAL_RUN_STATES3.includes(before.run.state)){const beforeRest={...before,run:null};const afterRest={...after,run:null};return same2(beforeRest,afterRest)&&isExtensionRunSuccessor(before.run,after.run)}return CHILD_AGENT_FIXED_KEYS.every(key=>same2(before[key],after[key]))&&isExtensionRunSuccessor(before.run,after.run)&&(!before.stopRequested||after.stopRequested)&&setOnce2(before.childSessionId,after.childSessionId)})}__name(isChildRunSuccessor,"isChildRunSuccessor");var MANAGED_CHILD_LIMITS=Object.freeze({maxDepth:1,maxActivePerScope:4,maxLaunchesPerScope:64,maxEnvelopeBytes:32*1024,maxDescriptionBytes:512,maxResultBytes:64*1024});var MANAGED_CHILD_ADMITTED_WORKSPACE_MODES=Object.freeze(["shared","worktree","snapshot"]);function parsePublicChildModelRoute(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ManagedSessionRecordError("Invalid public child model route.")}const route=value;if(Object.keys(route).sort().join(",")!==(Object.hasOwn(route,"origin")?"authType,endpointDigest,origin,providerPin":"authType,endpointDigest,providerPin")||typeof route["authType"]!=="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(route["authType"])||typeof route["endpointDigest"]!=="string"||!/^[a-f0-9]{64}$/.test(route["endpointDigest"])||typeof route["providerPin"]!=="string"||!/^[a-f0-9]{64}$/.test(route["providerPin"])){throw new ManagedSessionRecordError("Invalid public child model route.")}let origin;if(Object.hasOwn(route,"origin")){const value2=route["origin"];if(!value2||typeof value2!=="object"||Array.isArray(value2))throw new ManagedSessionRecordError("Invalid public child model origin.");const source=value2;if(Object.keys(source).sort().join(",")!=="authType,endpointDigest,modelId,providerPin"||typeof source["modelId"]!=="string"||!source["modelId"].trim()||Buffer.byteLength(source["modelId"])>512)throw new ManagedSessionRecordError("Invalid public child model origin.");origin=Object.freeze({modelId:source["modelId"],...parsePublicChildModelRoute({authType:source["authType"],endpointDigest:source["endpointDigest"],providerPin:source["providerPin"]})})}return Object.freeze({authType:route["authType"],endpointDigest:route["endpointDigest"],providerPin:route["providerPin"],...origin?{origin}:{}})}__name(parsePublicChildModelRoute,"parsePublicChildModelRoute");function parsePublicChildExtensionAgent(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedSessionRecordError("Invalid extension agent descriptor.");const fields=value;if(Object.keys(fields).sort().join(",")!=="agentName,bundleRef,configRevision,contributionsRef,pin,toolNames"||!Number.isSafeInteger(fields["configRevision"])||Number(fields["configRevision"])<1||typeof fields["agentName"]!=="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/u.test(fields["agentName"])||!Array.isArray(fields["toolNames"])||fields["toolNames"].length>256||fields["toolNames"].some(name2=>typeof name2!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(name2))||new Set(fields["toolNames"]).size!==fields["toolNames"].length)throw new ManagedSessionRecordError("Invalid extension agent descriptor.");const bundleRef=assertManagedSessionDurableRef(fields["bundleRef"],"extension agent bundle");const contributionsRef=assertManagedSessionDurableRef(fields["contributionsRef"],"extension agent contributions");if(bundleRef.kind!=="managed-extension-config-bundle"||bundleRef.schemaVersion!==1||contributionsRef.kind!=="managed-extension-contributions"||contributionsRef.schemaVersion!==1)throw new ManagedSessionRecordError("Invalid extension agent references.");return Object.freeze({configRevision:fields["configRevision"],bundleRef,pin:parseManagedExtensionPin(fields["pin"]),contributionsRef,agentName:fields["agentName"],toolNames:Object.freeze([...fields["toolNames"]])})}__name(parsePublicChildExtensionAgent,"parsePublicChildExtensionAgent");function parsePublicChildLaunch(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ManagedSessionRecordError("Invalid public child launch snapshot.")}const fields=value;if(Object.keys(fields).sort().join(",")!==(fields["version"]===2?"approvalMode,approvalRevision,extensionAgent,modelId,modelRevision,modelRoute,skillsRef,sourcePromptId,version":"approvalMode,approvalRevision,modelId,modelRevision,modelRoute,skillsRef,sourcePromptId,version")||fields["version"]!==1&&fields["version"]!==2||typeof fields["sourcePromptId"]!=="string"||!fields["sourcePromptId"].trim()||fields["sourcePromptId"].length>144||typeof fields["approvalMode"]!=="string"||!["default","auto-edit","yolo"].includes(fields["approvalMode"])||typeof fields["modelId"]!=="string"||!fields["modelId"].trim()||Buffer.byteLength(fields["modelId"],"utf8")>512||!Number.isSafeInteger(fields["approvalRevision"])||fields["approvalRevision"]<0||!Number.isSafeInteger(fields["modelRevision"])||fields["modelRevision"]<0){throw new ManagedSessionRecordError("Invalid public child launch snapshot.")}parsePublicChildModelRoute(fields["modelRoute"]);if(fields["version"]===2)parsePublicChildExtensionAgent(fields["extensionAgent"]);if(fields["skillsRef"]!==null){const ref11=assertManagedSessionDurableRef(fields["skillsRef"],"child Skills");if(ref11.kind!=="managed-agent-skills"||ref11.schemaVersion!==1){throw new ManagedSessionRecordError("Invalid public child Skills snapshot.")}}return Object.freeze({...fields})}__name(parsePublicChildLaunch,"parsePublicChildLaunch");function encodeChildLaunchEnvelope(envelope2){if(Buffer.byteLength(envelope2.description,"utf8")>MANAGED_CHILD_LIMITS.maxDescriptionBytes){throw new ManagedSessionRecordError(`Child launch description exceeds ${MANAGED_CHILD_LIMITS.maxDescriptionBytes} bytes (byte_limit).`)}const bytes=Buffer.from(JSON.stringify({description:envelope2.description,prompt:envelope2.prompt,definition:envelope2.definition,...envelope2.publicLaunch===void 0?{}:{publicLaunch:parsePublicChildLaunch(envelope2.publicLaunch)}}),"utf8");if(bytes.byteLength>MANAGED_CHILD_LIMITS.maxEnvelopeBytes){throw new ManagedSessionRecordError(`Child launch envelope exceeds ${MANAGED_CHILD_LIMITS.maxEnvelopeBytes} bytes (byte_limit).`)}return bytes}__name(encodeChildLaunchEnvelope,"encodeChildLaunchEnvelope");function decodeChildLaunchEnvelope(bytes){let value;try{value=JSON.parse(bytes.toString("utf8"))}catch{throw new ManagedSessionRecordError("Child launch envelope must be JSON.")}if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype){throw new ManagedSessionRecordError("Child launch envelope must be a JSON object.")}const record4=value;const keys2=Object.keys(record4).sort();if(keys2.join(",")!=="definition,description,prompt"&&keys2.join(",")!=="definition,description,prompt,publicLaunch"){throw new ManagedSessionRecordError("Child launch envelope must have exactly description, prompt and definition.")}if(typeof record4["description"]!=="string"||typeof record4["prompt"]!=="string"){throw new ManagedSessionRecordError("Child launch description and prompt must be text.")}const definition=record4["definition"];if(typeof definition!=="object"||definition===null||typeof definition["definitionId"]!=="string"||typeof definition["definitionRevision"]!=="number"||typeof definition["definitionDigest"]!=="string"){throw new ManagedSessionRecordError("Child launch definition must pin an id, a revision and a digest.")}return Object.freeze({description:record4["description"],prompt:record4["prompt"],definition:Object.freeze({...definition}),...record4["publicLaunch"]===void 0?{}:{publicLaunch:parsePublicChildLaunch(record4["publicLaunch"])}})}__name(decodeChildLaunchEnvelope,"decodeChildLaunchEnvelope");function encodeWorkflowLaunchEnvelope(envelope2){let serialized;try{serialized=JSON.stringify({definition:envelope2.definition,script:envelope2.script,args:envelope2.args??null},(_key,value)=>{if(typeof value==="function"||typeof value==="symbol"||typeof value==="number"&&!Number.isFinite(value)){throw new ManagedSessionRecordError("Workflow launch arguments must be JSON values (byte_limit).")}return value})}catch(cause){if(cause instanceof ManagedSessionRecordError){throw cause}throw new ManagedSessionRecordError("Workflow launch arguments must be JSON-serializable (byte_limit).")}const bytes=Buffer.from(serialized,"utf8");if(bytes.byteLength>MANAGED_CHILD_LIMITS.maxEnvelopeBytes){throw new ManagedSessionRecordError(`Workflow launch envelope exceeds ${MANAGED_CHILD_LIMITS.maxEnvelopeBytes} bytes (byte_limit).`)}return bytes}__name(encodeWorkflowLaunchEnvelope,"encodeWorkflowLaunchEnvelope");function admitChildLaunch(params){if(params.closing)return{admitted:false,reason:"closing"};if(!MANAGED_CHILD_ADMITTED_WORKSPACE_MODES.includes(params.workspaceMode)||params.workspaceMode==="worktree"&&!params.childWorkspaces||params.workspaceMode==="snapshot"&&!(params.childWorkspaces&&params.childSnapshots)){return{admitted:false,reason:"workspace_mode"}}if(!params.sameDefinition){return{admitted:false,reason:"definition_scope"}}if(params.depth>MANAGED_CHILD_LIMITS.maxDepth){return{admitted:false,reason:"depth_limit"}}if(params.launchedInScope>=MANAGED_CHILD_LIMITS.maxLaunchesPerScope){return{admitted:false,reason:"budget_exhausted"}}if(params.activeInScope>=MANAGED_CHILD_LIMITS.maxActivePerScope){return{admitted:false,reason:"count_limit"}}if(params.envelopeBytes>MANAGED_CHILD_LIMITS.maxEnvelopeBytes){return{admitted:false,reason:"byte_limit"}}return{admitted:true}}__name(admitChildLaunch,"admitChildLaunch");function childLaunchBody(params){return Object.freeze({kind:"child_agent",childRunId:params.childRunId,ownerScopeId:params.ownerScopeId,rootSessionId:params.rootSessionId,depth:1,completion:params.completion,inputRef:params.inputRef,workspaceMode:params.workspaceMode,workingDirectory:params.workingDirectory,childSessionId:null,predecessorChildRunId:null,resultVersion:1,resultRef:null,terminalReceiptRef:null,stopReason:null,stopRequested:false,run:Object.freeze({state:"admitted",reason:null,definition:Object.freeze({...params.definition}),executionCallId:params.executionCallId,effectId:null,dispatchId:null,deliveryId:null,execution:"intent",runtime:null,delivery:Object.freeze({target:"session",state:"planned"})})})}__name(childLaunchBody,"childLaunchBody");function workflowLaunchBody(params){return Object.freeze({...childLaunchBody({...params,workspaceMode:"shared"}),kind:"workflow"})}__name(workflowLaunchBody,"workflowLaunchBody");function childContinuationBody(predecessor,params){const launch=childLaunchBody({childRunId:params.childRunId,ownerScopeId:predecessor.ownerScopeId,rootSessionId:predecessor.rootSessionId,completion:params.completion,inputRef:params.inputRef,workspaceMode:predecessor.workspaceMode,workingDirectory:predecessor.workingDirectory,executionCallId:params.executionCallId,definition:predecessor.run.definition});return Object.freeze({...launch,kind:predecessor.kind,depth:predecessor.depth,predecessorChildRunId:predecessor.childRunId})}__name(childContinuationBody,"childContinuationBody");function childDispatchBody(previous,params){return Object.freeze({...previous,run:Object.freeze({...previous.run,state:"running",dispatchId:params.dispatchId,execution:"dispatch_started",runtime:Object.freeze({...params.runtime})})})}__name(childDispatchBody,"childDispatchBody");function childAttachBody(previous,params){return Object.freeze({...previous,childSessionId:params.childSessionId,run:Object.freeze({...previous.run,execution:"running_attached"})})}__name(childAttachBody,"childAttachBody");function childSettleCompletedBody(previous,params){return Object.freeze({...previous,stopReason:"completed",resultRef:params.resultRef,terminalReceiptRef:params.terminalReceiptRef,run:Object.freeze({...previous.run,state:"settled",execution:"settled",delivery:Object.freeze({target:"session",state:"accepting"})})})}__name(childSettleCompletedBody,"childSettleCompletedBody");function adoptChildSessionId(previous,childSessionId,verb){if(childSessionId===void 0)return previous.childSessionId;if(previous.childSessionId!==null&&previous.childSessionId!==childSessionId){throw new ManagedSessionRecordError(`Child run ${verb} cannot rename the Session it already named.`)}return childSessionId}__name(adoptChildSessionId,"adoptChildSessionId");function childFailBody(previous,params){return Object.freeze({...previous,stopReason:params.stopReason,childSessionId:adoptChildSessionId(previous,params.childSessionId,"failure"),run:Object.freeze({...previous.run,state:"failed",reason:params.reason,execution:params.started?"settled":"not_started_proven",delivery:Object.freeze({target:"session",state:"cancelled"})})})}__name(childFailBody,"childFailBody");function childStopRequestedBody(previous){return Object.freeze({...previous,stopRequested:true})}__name(childStopRequestedBody,"childStopRequestedBody");function childCancelBody(previous,params){return Object.freeze({...previous,stopReason:"stop_requested",stopRequested:true,childSessionId:adoptChildSessionId(previous,params.childSessionId,"close"),run:Object.freeze({...previous.run,state:"cancelled",execution:params.started?"settled":"not_started_proven",delivery:Object.freeze({target:"session",state:"cancelled"})})})}__name(childCancelBody,"childCancelBody");function childRecoveryBlockedBody(previous,params){return Object.freeze({...previous,childSessionId:adoptChildSessionId(previous,params.childSessionId,"recovery_blocked"),run:Object.freeze({...previous.run,state:"recovery_blocked",reason:params.reason,execution:"outcome_unknown"})})}__name(childRecoveryBlockedBody,"childRecoveryBlockedBody");function childDeliveryBody(previous,state){return Object.freeze({...previous,run:Object.freeze({...previous.run,delivery:Object.freeze({target:"session",state})})})}__name(childDeliveryBody,"childDeliveryBody");function childAcceptanceBody(child,params){return Object.freeze({childRunId:child.childRunId,parentScopeId:child.ownerScopeId,parentExecutionCallId:child.completion==="tool"?child.run.executionCallId:null,resultVersion:child.resultVersion,contentRef:params.contentRef,contentDigest:params.contentRef.digest,terminalReceiptRef:params.terminalReceiptRef,run:Object.freeze({state:"settled",reason:null,definition:null,executionCallId:null,effectId:null,dispatchId:null,deliveryId:null,execution:null,runtime:null,delivery:Object.freeze({target:"session",state:"accepted"})})})}__name(childAcceptanceBody,"childAcceptanceBody");function childAcceptanceConsumedBody(previous){return Object.freeze({...previous,run:Object.freeze({...previous.run,delivery:Object.freeze({target:"session",state:"consumed"})})})}__name(childAcceptanceConsumedBody,"childAcceptanceConsumedBody");init_esbuild_shims();var HARNESS_CHECKPOINT_SCHEMA_VERSION=1;var HARNESS_CHECKPOINT_PHASES=["before_model","model_output_committed","await_action","await_runtime","await_agent","await_command","results_ready","turn_settled"];var HARNESS_MODEL_START_PHASES=new Set(["before_model","model_output_committed","results_ready","turn_settled"]);var HARNESS_TURN_COMPLETE_BOUNDARY="turn_complete";var HARNESS_DURABLE_WAIT_BOUNDARY="durable_wait";var HARNESS_ACTION_SOURCES=["tool_call","automation_run","team_plan","user_operation"];var HARNESS_TOOL_ITEM_STATES=["not_started","in_progress","settled"];var HARNESS_TOOL_OUTCOME_SOURCES=["runtime","orchestration","domain"];var HARNESS_RUNTIME_STATES=["dispatch","settled","committed"];var HARNESS_APPROVAL_STATES=["requested","decided","cancelled","expired"];var HARNESS_ATTEMPT_OUTPUT_STATES=["started","output_committed","abandoned"];var ROOT_KEYS=["identity","resume","continuation","attempt","tools","runtime","approval","agentWait","commandWait","commandLock","output","followUp"];function fail5(message){throw new ManagedSessionRecordError(message)}__name(fail5,"fail");function object4(value,label){if(value===null||typeof value!=="object"||Array.isArray(value)){fail5(`${label} must be a JSON object.`)}return value}__name(object4,"object");function assertNoUnknownKeys(input,allowed,label){for(const key of Object.keys(input)){if(!allowed.includes(key)){fail5(`${label} has the unknown field "${key}".`)}}}__name(assertNoUnknownKeys,"assertNoUnknownKeys");function oneOf2(value,allowed,label){if(typeof value!=="string"||!allowed.includes(value)){fail5(`${label} must be one of ${allowed.join(", ")}.`)}return value}__name(oneOf2,"oneOf");function idOrNull(value,label){if(value===null)return null;return assertManagedSessionStableId(value,label)}__name(idOrNull,"idOrNull");function refOrNull(value,label){if(value===null)return null;return assertManagedSessionDurableRef(value,label)}__name(refOrNull,"refOrNull");function sequenceOrNull(value,label){if(value===null)return null;return assertManagedSessionSequence(value,label)}__name(sequenceOrNull,"sequenceOrNull");function jsonArray(value,label){if(!Array.isArray(value)){fail5(`${label} must be a JSON array.`)}return value}__name(jsonArray,"jsonArray");function idList(value,label){return jsonArray(value,label).map((item,index)=>assertManagedSessionStableId(item,`${label}[${index}]`))}__name(idList,"idList");function uniqueIds(ids,label){const seen=new Set;for(const id6 of ids){if(seen.has(id6)){fail5(`${label} repeats "${id6}".`)}seen.add(id6)}}__name(uniqueIds,"uniqueIds");function parseIdentity(value){const record4=object4(value,"identity");assertNoUnknownKeys(record4,["schemaVersion","sessionKey","engine","checkpointId","coveredSequence","activationId","turnId","promptId","definitionRevision","configRevision","inputDigest","previousCheckpointId"],"identity");if(record4["schemaVersion"]!==HARNESS_CHECKPOINT_SCHEMA_VERSION){fail5("identity.schemaVersion must be 1.")}if(record4["engine"]!=="managed"){fail5("identity.engine must be managed.")}return{schemaVersion:HARNESS_CHECKPOINT_SCHEMA_VERSION,sessionKey:assertManagedSessionKey(record4["sessionKey"],"identity.sessionKey"),engine:"managed",checkpointId:assertManagedSessionStableId(record4["checkpointId"],"identity.checkpointId"),coveredSequence:assertManagedSessionSequence(record4["coveredSequence"],"identity.coveredSequence"),activationId:assertManagedSessionStableId(record4["activationId"],"identity.activationId"),turnId:idOrNull(record4["turnId"],"identity.turnId"),promptId:idOrNull(record4["promptId"],"identity.promptId"),definitionRevision:assertManagedSessionStableId(record4["definitionRevision"],"identity.definitionRevision"),configRevision:assertManagedSessionStableId(record4["configRevision"],"identity.configRevision"),inputDigest:assertManagedSessionDigest(record4["inputDigest"],"identity.inputDigest"),previousCheckpointId:idOrNull(record4["previousCheckpointId"],"identity.previousCheckpointId")}}__name(parseIdentity,"parseIdentity");function parseRecording(value){const record4=object4(value,"resume.recording");assertNoUnknownKeys(record4,["lastCompletedUuid","turnParentUuids","parentSessionId","sourceType","sourceId","lastAssistantModel","executionEngine"],"resume.recording");if(record4["executionEngine"]!=="managed"){fail5("resume.recording.executionEngine must be managed.")}return{lastCompletedUuid:idOrNull(record4["lastCompletedUuid"],"resume.recording.lastCompletedUuid"),turnParentUuids:idList(record4["turnParentUuids"],"resume.recording.turnParentUuids"),parentSessionId:idOrNull(record4["parentSessionId"],"resume.recording.parentSessionId"),sourceType:idOrNull(record4["sourceType"],"resume.recording.sourceType"),sourceId:idOrNull(record4["sourceId"],"resume.recording.sourceId"),lastAssistantModel:idOrNull(record4["lastAssistantModel"],"resume.recording.lastAssistantModel"),executionEngine:"managed"}}__name(parseRecording,"parseRecording");function parseResume(value,coveredSequence){const record4=object4(value,"resume");assertNoUnknownKeys(record4,["source","throughSequence","recording","initialTurn","consumedNotificationIds","apiHistoryRef","fileHistoryRef","artifactRef","goalRecordsRef","goalCheckpointWindowRef","tokenCountsRef","uiTelemetryRef","attributionRef","goalRecoverySourceUuid"],"resume");if(record4["source"]!=="session_log"){fail5("resume.source must be session_log.")}const throughSequence=assertManagedSessionSequence(record4["throughSequence"],"resume.throughSequence");if(throughSequence!==coveredSequence){fail5("resume.throughSequence must equal identity.coveredSequence.")}const consumedNotificationIds=idList(record4["consumedNotificationIds"],"resume.consumedNotificationIds");uniqueIds(consumedNotificationIds,"resume.consumedNotificationIds");return{source:"session_log",throughSequence,recording:parseRecording(record4["recording"]),initialTurn:assertManagedSessionSequence(record4["initialTurn"],"resume.initialTurn"),consumedNotificationIds,apiHistoryRef:refOrNull(record4["apiHistoryRef"],"resume.apiHistoryRef"),fileHistoryRef:refOrNull(record4["fileHistoryRef"],"resume.fileHistoryRef"),artifactRef:refOrNull(record4["artifactRef"],"resume.artifactRef"),goalRecordsRef:refOrNull(record4["goalRecordsRef"],"resume.goalRecordsRef"),goalCheckpointWindowRef:refOrNull(record4["goalCheckpointWindowRef"],"resume.goalCheckpointWindowRef"),tokenCountsRef:refOrNull(record4["tokenCountsRef"],"resume.tokenCountsRef"),uiTelemetryRef:refOrNull(record4["uiTelemetryRef"],"resume.uiTelemetryRef"),attributionRef:refOrNull(record4["attributionRef"],"resume.attributionRef"),goalRecoverySourceUuid:idOrNull(record4["goalRecoverySourceUuid"],"resume.goalRecoverySourceUuid")}}__name(parseResume,"parseResume");function parseContinuation(value){const record4=object4(value,"continuation");assertNoUnknownKeys(record4,["phase","pendingEventIds"],"continuation");const pendingEventIds=idList(record4["pendingEventIds"],"continuation.pendingEventIds");uniqueIds(pendingEventIds,"continuation.pendingEventIds");return{phase:oneOf2(record4["phase"],HARNESS_CHECKPOINT_PHASES,"continuation.phase"),pendingEventIds}}__name(parseContinuation,"parseContinuation");function parseAttempt(value){if(value===null)return null;const record4=object4(value,"attempt");assertNoUnknownKeys(record4,["attemptId","routeRef","capabilityRef","samplingRef","outputState","usageRef","budgetConsumed"],"attempt");const outputState=oneOf2(record4["outputState"],HARNESS_ATTEMPT_OUTPUT_STATES,"attempt.outputState");const usageRef=refOrNull(record4["usageRef"],"attempt.usageRef");if(outputState==="started"&&usageRef!==null){fail5("attempt.usageRef must be null while outputState is started.")}return{attemptId:assertManagedSessionStableId(record4["attemptId"],"attempt.attemptId"),routeRef:assertManagedSessionDurableRef(record4["routeRef"],"attempt.routeRef"),capabilityRef:refOrNull(record4["capabilityRef"],"attempt.capabilityRef"),samplingRef:refOrNull(record4["samplingRef"],"attempt.samplingRef"),outputState,usageRef,budgetConsumed:assertManagedSessionSequence(record4["budgetConsumed"],"attempt.budgetConsumed")}}__name(parseAttempt,"parseAttempt");function parseToolItem(value,label){const record4=object4(value,label);assertNoUnknownKeys(record4,["functionCallId","toolName","executionCallId","modelMessageId","partIndex","ordinal","inputDigest","outcomeSource","state","outcomeRef","consumed"],label);const state=oneOf2(record4["state"],HARNESS_TOOL_ITEM_STATES,`${label}.state`);const outcomeRef=refOrNull(record4["outcomeRef"],`${label}.outcomeRef`);if(state==="settled"&&outcomeRef===null){fail5(`${label}.outcomeRef is required once the item is settled.`)}if(state!=="settled"&&outcomeRef!==null){fail5(`${label}.outcomeRef must be null until the item is settled.`)}if(typeof record4["consumed"]!=="boolean"){fail5(`${label}.consumed must be a boolean.`)}if(record4["consumed"]&&state!=="settled"){fail5(`${label} cannot be consumed before it is settled.`)}return{functionCallId:assertManagedSessionStableId(record4["functionCallId"],`${label}.functionCallId`),toolName:assertManagedSessionStableId(record4["toolName"],`${label}.toolName`),executionCallId:assertManagedSessionStableId(record4["executionCallId"],`${label}.executionCallId`),modelMessageId:assertManagedSessionStableId(record4["modelMessageId"],`${label}.modelMessageId`),partIndex:assertManagedSessionSequence(record4["partIndex"],`${label}.partIndex`),ordinal:assertManagedSessionSequence(record4["ordinal"],`${label}.ordinal`),inputDigest:assertManagedSessionDigest(record4["inputDigest"],`${label}.inputDigest`),outcomeSource:oneOf2(record4["outcomeSource"],HARNESS_TOOL_OUTCOME_SOURCES,`${label}.outcomeSource`),state,outcomeRef,consumed:record4["consumed"]}}__name(parseToolItem,"parseToolItem");function parseTools(value){if(value===null)return null;const record4=object4(value,"tools");assertNoUnknownKeys(record4,["batchId","items"],"tools");const items=jsonArray(record4["items"],"tools.items").map((item,index)=>parseToolItem(item,`tools.items[${index}]`));uniqueIds(items.map(item=>item.executionCallId),"tools.items.executionCallId");uniqueIds(items.map(item=>item.functionCallId),"tools.items.functionCallId");const ordinals=new Set;for(const item of items){if(ordinals.has(item.ordinal)){fail5(`tools.items repeats ordinal ${item.ordinal}.`)}ordinals.add(item.ordinal)}return{batchId:idOrNull(record4["batchId"],"tools.batchId"),items}}__name(parseTools,"parseTools");function parseRuntimeBinding(value,label){const record4=object4(value,label);assertNoUnknownKeys(record4,["executionCallId","invocationBindingId","capabilityVersion","policyVersion","mediaVersion","state","progressCursor"],label);return{executionCallId:assertManagedSessionStableId(record4["executionCallId"],`${label}.executionCallId`),invocationBindingId:assertManagedSessionStableId(record4["invocationBindingId"],`${label}.invocationBindingId`),capabilityVersion:assertManagedSessionStableId(record4["capabilityVersion"],`${label}.capabilityVersion`),policyVersion:assertManagedSessionStableId(record4["policyVersion"],`${label}.policyVersion`),mediaVersion:idOrNull(record4["mediaVersion"],`${label}.mediaVersion`),state:oneOf2(record4["state"],HARNESS_RUNTIME_STATES,`${label}.state`),progressCursor:idOrNull(record4["progressCursor"],`${label}.progressCursor`)}}__name(parseRuntimeBinding,"parseRuntimeBinding");function parseRuntime(value){if(value===null)return null;const record4=object4(value,"runtime");assertNoUnknownKeys(record4,["bindings"],"runtime");const bindings=jsonArray(record4["bindings"],"runtime.bindings").map((item,index)=>parseRuntimeBinding(item,`runtime.bindings[${index}]`));uniqueIds(bindings.map(item=>item.executionCallId),"runtime.bindings.executionCallId");uniqueIds(bindings.map(item=>item.invocationBindingId),"runtime.bindings.invocationBindingId");return{bindings}}__name(parseRuntime,"parseRuntime");function parseApproval(value){if(value===null)return null;const record4=object4(value,"approval");assertNoUnknownKeys(record4,["requestId","kind","source","optionsRef","inputRevision","confirmationVersion","state","decisionRef","invocationRef"],"approval");const state=oneOf2(record4["state"],HARNESS_APPROVAL_STATES,"approval.state");const source=oneOf2(record4["source"],HARNESS_ACTION_SOURCES,"approval.source");const decisionRef=refOrNull(record4["decisionRef"],"approval.decisionRef");if(state==="decided"&&decisionRef===null){fail5("approval.decisionRef is required once the approval is decided.")}if(state!=="decided"&&decisionRef!==null){fail5("approval.decisionRef must be null until the approval is decided.")}const invocationRef=refOrNull(record4["invocationRef"],"approval.invocationRef");if(source==="tool_call"&&invocationRef===null){fail5("approval.invocationRef is required for a tool_call approval.")}if(source==="user_operation"&&invocationRef!==null){fail5("approval.invocationRef must be null for a user_operation approval.")}return{requestId:assertManagedSessionStableId(record4["requestId"],"approval.requestId"),kind:assertManagedSessionStableId(record4["kind"],"approval.kind"),source,optionsRef:assertManagedSessionDurableRef(record4["optionsRef"],"approval.optionsRef"),inputRevision:assertManagedSessionStableId(record4["inputRevision"],"approval.inputRevision"),confirmationVersion:idOrNull(record4["confirmationVersion"],"approval.confirmationVersion"),state,decisionRef,invocationRef}}__name(parseApproval,"parseApproval");function parseAgentWaitRun(value,label){const record4=object4(value,label);assertNoUnknownKeys(record4,["childRunId","functionCallId","toolName","modelMessageId","consumed"],label);if(typeof record4["consumed"]!=="boolean"){fail5(`${label}.consumed must be a boolean.`)}return{childRunId:assertManagedSessionStableId(record4["childRunId"],`${label}.childRunId`),functionCallId:assertManagedSessionStableId(record4["functionCallId"],`${label}.functionCallId`),toolName:assertManagedSessionStableId(record4["toolName"],`${label}.toolName`),modelMessageId:assertManagedSessionStableId(record4["modelMessageId"],`${label}.modelMessageId`),consumed:record4["consumed"]}}__name(parseAgentWaitRun,"parseAgentWaitRun");function parseAgentWait(value){if(value===null)return null;const record4=object4(value,"agentWait");assertNoUnknownKeys(record4,["runs"],"agentWait");const runs=jsonArray(record4["runs"],"agentWait.runs").map((item,index)=>parseAgentWaitRun(item,`agentWait.runs[${index}]`));if(runs.length===0){fail5("agent wait requires at least one run.")}uniqueIds(runs.map(run=>run.childRunId),"agentWait.runs.childRunId");uniqueIds(runs.map(run=>run.functionCallId),"agentWait.runs.functionCallId");return{runs}}__name(parseAgentWait,"parseAgentWait");function parseCommandWaitRun(value,label){const record4=object4(value,label);assertNoUnknownKeys(record4,["commandId","functionCallId","toolName","modelMessageId","folded"],label);if(typeof record4["folded"]!=="boolean"){fail5(`${label}.folded must be a boolean.`)}return{commandId:assertManagedSessionStableId(record4["commandId"],`${label}.commandId`),functionCallId:assertManagedSessionStableId(record4["functionCallId"],`${label}.functionCallId`),toolName:assertManagedSessionStableId(record4["toolName"],`${label}.toolName`),modelMessageId:assertManagedSessionStableId(record4["modelMessageId"],`${label}.modelMessageId`),folded:record4["folded"]}}__name(parseCommandWaitRun,"parseCommandWaitRun");function parseCommandWait(value){if(value===null)return null;const record4=object4(value,"commandWait");assertNoUnknownKeys(record4,["runs","holdsWorkspaceMount"],"commandWait");const runs=jsonArray(record4["runs"],"commandWait.runs").map((item,index)=>parseCommandWaitRun(item,`commandWait.runs[${index}]`));if(runs.length===0){fail5("command wait requires at least one run.")}uniqueIds(runs.map(run=>run.commandId),"commandWait.runs.commandId");uniqueIds(runs.map(run=>run.functionCallId),"commandWait.runs.functionCallId");const mount=record4["holdsWorkspaceMount"];if(typeof mount!=="boolean"){fail5("commandWait.holdsWorkspaceMount must be a boolean.")}return{runs,holdsWorkspaceMount:mount}}__name(parseCommandWait,"parseCommandWait");function parseCommandLock(value){if(value===null)return null;const record4=object4(value,"commandLock");assertNoUnknownKeys(record4,["turnId"],"commandLock");return{turnId:assertManagedSessionStableId(record4["turnId"],"commandLock.turnId")}}__name(parseCommandLock,"parseCommandLock");function carriedCommandLock(previous){const lock=previous.commandLock;return lock!==null&&lock.turnId===previous.identity.turnId?lock:null}__name(carriedCommandLock,"carriedCommandLock");function harnessCommandLockOf(checkpoint){if(checkpoint.identity.turnId===null){throw new ManagedSessionRecordError("a command timeout lock requires the Turn it binds.")}return{turnId:checkpoint.identity.turnId}}__name(harnessCommandLockOf,"harnessCommandLockOf");function harnessCommandLocked(checkpoint,turnId){return checkpoint.commandLock?.turnId===turnId}__name(harnessCommandLocked,"harnessCommandLocked");function parseParentHistory(value){if(value===null)return null;const record4=object4(value,"output.parentHistory");assertNoUnknownKeys(record4,["bindingId","revision"],"output.parentHistory");return{bindingId:assertManagedSessionStableId(record4["bindingId"],"output.parentHistory.bindingId"),revision:assertManagedSessionSequence(record4["revision"],"output.parentHistory.revision")}}__name(parseParentHistory,"parseParentHistory");function parseOutput(value){const record4=object4(value,"output");assertNoUnknownKeys(record4,["llmContentRef","physicalStatus","hookResultRef","mediaRefs","parentHistory"],"output");return{llmContentRef:refOrNull(record4["llmContentRef"],"output.llmContentRef"),physicalStatus:idOrNull(record4["physicalStatus"],"output.physicalStatus"),hookResultRef:refOrNull(record4["hookResultRef"],"output.hookResultRef"),mediaRefs:jsonArray(record4["mediaRefs"],"output.mediaRefs").map((item,index)=>assertManagedSessionDurableRef(item,`output.mediaRefs[${index}]`)),parentHistory:parseParentHistory(record4["parentHistory"])}}__name(parseOutput,"parseOutput");function parseFollowUp(value){const record4=object4(value,"followUp");assertNoUnknownKeys(record4,["pendingInputIds","cancelRequestIds","goalPermitIds","cronIds","notificationIds","childRunIds","stopBudgetRemaining","scopeLineage"],"followUp");const pendingInputIds=idList(record4["pendingInputIds"],"followUp.pendingInputIds");const cancelRequestIds=idList(record4["cancelRequestIds"],"followUp.cancelRequestIds");const goalPermitIds=idList(record4["goalPermitIds"],"followUp.goalPermitIds");const cronIds=idList(record4["cronIds"],"followUp.cronIds");const notificationIds=idList(record4["notificationIds"],"followUp.notificationIds");const childRunIds=idList(record4["childRunIds"],"followUp.childRunIds");uniqueIds(pendingInputIds,"followUp.pendingInputIds");uniqueIds(cancelRequestIds,"followUp.cancelRequestIds");uniqueIds(goalPermitIds,"followUp.goalPermitIds");uniqueIds(cronIds,"followUp.cronIds");uniqueIds(notificationIds,"followUp.notificationIds");uniqueIds(childRunIds,"followUp.childRunIds");return{pendingInputIds,cancelRequestIds,goalPermitIds,cronIds,notificationIds,childRunIds,stopBudgetRemaining:sequenceOrNull(record4["stopBudgetRemaining"],"followUp.stopBudgetRemaining"),scopeLineage:idList(record4["scopeLineage"],"followUp.scopeLineage")}}__name(parseFollowUp,"parseFollowUp");function toolItems(tools){return tools?.items??[]}__name(toolItems,"toolItems");function runtimeBindings(runtime){return runtime?.bindings??[]}__name(runtimeBindings,"runtimeBindings");function assertRuntimeMatchesTools(tools,runtime){const calls=new Set(toolItems(tools).map(item=>item.executionCallId));for(const binding of runtimeBindings(runtime)){if(!calls.has(binding.executionCallId)){fail5(`runtime binding ${binding.executionCallId} has no matching tool item.`)}}}__name(assertRuntimeMatchesTools,"assertRuntimeMatchesTools");function assertPhaseShape(checkpoint){const{phase}=checkpoint.continuation;const items=toolItems(checkpoint.tools);const bindings=runtimeBindings(checkpoint.runtime);const inFlightTools=items.some(item=>item.state==="in_progress");const unsettledTools=items.some(item=>item.state!=="settled");const dispatchRuntime=bindings.some(item=>item.state==="dispatch");if(phase==="before_model"){if(checkpoint.attempt!==null){fail5("before_model cannot carry a model attempt.")}if(items.length>0||bindings.length>0){fail5("before_model cannot carry tools or runtime bindings.")}if(checkpoint.approval!==null){fail5("before_model cannot carry an approval.")}if(checkpoint.agentWait!==null){fail5("before_model cannot carry an agent wait.")}if(checkpoint.commandWait!==null){fail5("before_model cannot carry a command wait.")}return}if(checkpoint.attempt===null){fail5(`${phase} requires a model attempt.`)}if(checkpoint.attempt.outputState==="started"){fail5("an in-flight model stream is not a runnable checkpoint phase.")}if(phase==="model_output_committed"){if(checkpoint.attempt.outputState!=="output_committed"){fail5("model_output_committed requires outputState output_committed.")}if(checkpoint.approval!==null){fail5("model_output_committed cannot carry an approval.")}if(inFlightTools||dispatchRuntime){fail5("model_output_committed cannot carry in-flight tools.")}if(checkpoint.agentWait!==null&&checkpoint.agentWait.runs.some(run=>!run.consumed)){fail5("model_output_committed cannot carry an unconsumed agent wait.")}if(checkpoint.commandWait!==null&&checkpoint.commandWait.runs.some(run=>!run.folded)){fail5("model_output_committed cannot carry an unfolded command wait.")}return}if(phase==="await_action"){if(checkpoint.approval===null||checkpoint.approval.state!=="requested"){fail5("await_action requires a requested approval.")}if(checkpoint.approval.source==="user_operation"&&bindings.length>0){fail5("a user_operation approval cannot carry runtime bindings.")}if(checkpoint.agentWait!==null){fail5("await_action cannot carry an agent wait.")}if(checkpoint.commandWait!==null){fail5("await_action cannot carry a command wait.")}return}if(phase==="await_runtime"){if(!inFlightTools||!dispatchRuntime){fail5("await_runtime requires in-progress tools and dispatch bindings.")}if(checkpoint.approval?.state==="requested"){fail5("await_runtime cannot keep a requested approval.")}if(checkpoint.agentWait!==null){fail5("await_runtime cannot carry an agent wait.")}if(checkpoint.commandWait!==null){fail5("await_runtime cannot carry a command wait.")}return}if(phase==="await_agent"){if(checkpoint.agentWait===null||checkpoint.agentWait.runs.length===0){fail5("await_agent requires the agent wait runs.")}if(checkpoint.agentWait.runs.every(run=>run.consumed)){fail5("await_agent cannot keep an all-consumed agent wait.")}if(checkpoint.approval?.state==="requested"){fail5("await_agent cannot keep a requested approval.")}if(inFlightTools||dispatchRuntime){fail5("await_agent cannot carry in-flight Runtime work.")}if(checkpoint.commandWait!==null){fail5("await_agent cannot carry a command wait.")}return}if(phase==="await_command"){if(checkpoint.commandWait===null||checkpoint.commandWait.runs.length===0){fail5("await_command requires the command wait runs.")}if(checkpoint.commandWait.runs.every(run=>run.folded)){fail5("await_command cannot keep an all-folded command wait.")}if(checkpoint.approval?.state==="requested"){fail5("await_command cannot keep a requested approval.")}if(inFlightTools||dispatchRuntime){fail5("await_command cannot carry in-flight Runtime work.")}if(checkpoint.agentWait!==null){fail5("await_command cannot carry an agent wait.")}return}if(phase==="results_ready"){if(items.length===0||unsettledTools){fail5("results_ready requires every tool item to be settled.")}if(dispatchRuntime||inFlightTools){fail5("results_ready cannot carry in-flight tools.")}if(checkpoint.approval?.state==="requested"){fail5("results_ready cannot keep a requested approval.")}if(checkpoint.agentWait!==null){fail5("results_ready cannot carry an agent wait.")}if(checkpoint.commandWait!==null){fail5("results_ready cannot carry a command wait.")}return}if(inFlightTools||dispatchRuntime||checkpoint.approval?.state==="requested"||checkpoint.agentWait!==null||checkpoint.commandWait!==null){fail5("turn_settled cannot carry in-flight tools, a requested approval, an agent wait, or a command wait.")}}__name(assertPhaseShape,"assertPhaseShape");function parseHarnessCheckpointObject(value){const record4=object4(value,"harness checkpoint");assertNoUnknownKeys(record4,ROOT_KEYS,"harness checkpoint");const identity=parseIdentity(record4["identity"]);const checkpoint={identity,resume:parseResume(record4["resume"],identity.coveredSequence),continuation:parseContinuation(record4["continuation"]),attempt:parseAttempt(record4["attempt"]),tools:parseTools(record4["tools"]),runtime:parseRuntime(record4["runtime"]),approval:parseApproval(record4["approval"]),agentWait:parseAgentWait(record4["agentWait"]),commandWait:parseCommandWait(record4["commandWait"]),commandLock:parseCommandLock(record4["commandLock"]),output:parseOutput(record4["output"]),followUp:parseFollowUp(record4["followUp"])};assertRuntimeMatchesTools(checkpoint.tools,checkpoint.runtime);assertPhaseShape(checkpoint);return checkpoint}__name(parseHarnessCheckpointObject,"parseHarnessCheckpointObject");function harnessCheckpointIsAgentWait(checkpoint){return checkpoint.continuation.phase==="await_agent"||checkpoint.continuation.phase==="model_output_committed"&&checkpoint.agentWait!==null}__name(harnessCheckpointIsAgentWait,"harnessCheckpointIsAgentWait");function harnessCheckpointIsCommandWait(checkpoint){return checkpoint.continuation.phase==="await_command"||checkpoint.continuation.phase==="model_output_committed"&&checkpoint.commandWait!==null}__name(harnessCheckpointIsCommandWait,"harnessCheckpointIsCommandWait");function tryParseHarnessCheckpointV1(bytes){let json2;try{json2=parseManagedSessionRecordJson(bytes.toString("utf8"),MANAGED_SESSION_LIMITS.maxEventBytes)}catch(error3){return{ok:false,reason:"opaque",message:error3 instanceof Error?error3.message:"unreadable checkpoint state"}}if(json2===null||typeof json2!=="object"||Array.isArray(json2)){return{ok:false,reason:"opaque",message:"checkpoint state is not a JSON object."}}const identity=json2["identity"];if(identity===null||typeof identity!=="object"||Array.isArray(identity)||identity["schemaVersion"]===void 0){return{ok:false,reason:"opaque",message:"checkpoint state has no Harness schemaVersion."}}try{return{ok:true,checkpoint:parseHarnessCheckpointObject(json2)}}catch(error3){if(error3 instanceof ManagedSessionRecordError){return{ok:false,reason:"invalid",message:error3.message}}throw error3}}__name(tryParseHarnessCheckpointV1,"tryParseHarnessCheckpointV1");function encodeHarnessCheckpointV1(checkpoint){return Buffer.from(JSON.stringify(checkpoint),"utf8")}__name(encodeHarnessCheckpointV1,"encodeHarnessCheckpointV1");function formatHarnessIdentity(input){return`${input.checkpointId}@${input.coveredSequence} ${input.sessionKey.tenantId}/${input.sessionKey.workspaceId}/${input.sessionKey.sessionId}`}__name(formatHarnessIdentity,"formatHarnessIdentity");function authorizeParsedHarnessCheckpoint(checkpoint,expected){if(!managedSessionKeysEqual(checkpoint.identity.sessionKey,expected.sessionKey)||checkpoint.identity.checkpointId!==expected.checkpointId||checkpoint.identity.coveredSequence!==expected.coveredSequence||checkpoint.identity.engine!=="managed"){return{status:"blocked",reason:"identity_mismatch",message:`checkpoint ${formatHarnessIdentity(checkpoint.identity)} does not match ${formatHarnessIdentity({sessionKey:expected.sessionKey,checkpointId:expected.checkpointId,coveredSequence:expected.coveredSequence})}`}}return{status:"runnable",checkpoint}}__name(authorizeParsedHarnessCheckpoint,"authorizeParsedHarnessCheckpoint");function createInitialHarnessCheckpoint(input){return{identity:{schemaVersion:HARNESS_CHECKPOINT_SCHEMA_VERSION,sessionKey:input.sessionKey,engine:"managed",checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,activationId:input.activationId,turnId:input.turnId,promptId:input.promptId,definitionRevision:input.definitionRevision,configRevision:input.configRevision,inputDigest:input.inputDigest,previousCheckpointId:input.previousCheckpointId},resume:{source:"session_log",throughSequence:input.coveredSequence,recording:{lastCompletedUuid:null,turnParentUuids:[],parentSessionId:null,sourceType:null,sourceId:null,lastAssistantModel:null,executionEngine:"managed"},initialTurn:input.initialTurn??0,consumedNotificationIds:[],apiHistoryRef:null,fileHistoryRef:null,artifactRef:null,goalRecordsRef:null,goalCheckpointWindowRef:null,tokenCountsRef:null,uiTelemetryRef:null,attributionRef:null,goalRecoverySourceUuid:null},continuation:{phase:"before_model",pendingEventIds:[...input.pendingEventIds??[]]},attempt:null,tools:null,runtime:null,approval:null,agentWait:null,commandWait:null,commandLock:null,output:{llmContentRef:null,physicalStatus:null,hookResultRef:null,mediaRefs:[],parentHistory:null},followUp:{pendingInputIds:[],cancelRequestIds:[],goalPermitIds:[],cronIds:[],notificationIds:[],childRunIds:[],stopBudgetRemaining:null,scopeLineage:[]}}}__name(createInitialHarnessCheckpoint,"createInitialHarnessCheckpoint");function createNextTurnReadyHarnessCheckpoint(input){return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,activationId:input.activationId,turnId:input.turnId,promptId:input.promptId,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"before_model",pendingEventIds:[]},attempt:null,tools:null,runtime:null,approval:null,agentWait:null,commandWait:null,commandLock:null,output:{llmContentRef:null,physicalStatus:null,hookResultRef:null,mediaRefs:[],parentHistory:input.previous.output.parentHistory},followUp:input.previous.followUp}}__name(createNextTurnReadyHarnessCheckpoint,"createNextTurnReadyHarnessCheckpoint");function createAwaitActionHarnessCheckpoint(input){return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"await_action",pendingEventIds:[]},attempt:input.attempt,tools:input.previous.tools,runtime:input.previous.runtime,approval:input.approval,agentWait:null,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createAwaitActionHarnessCheckpoint,"createAwaitActionHarnessCheckpoint");function createAwaitAgentHarnessCheckpoint(input){if(input.previous.approval?.state==="requested"){throw new ManagedSessionRecordError("await_agent cannot keep a requested approval.")}if(input.previous.agentWait!==null&&input.previous.agentWait.runs.some(run=>!run.consumed)){throw new ManagedSessionRecordError("await_agent cannot replace an unfinished agent wait.")}if(input.previous.commandWait!==null&&input.previous.commandWait.runs.some(run=>!run.folded)){throw new ManagedSessionRecordError("await_agent cannot replace an unfinished command wait.")}if(input.previous.tools?.items.some(item=>item.state==="in_progress")){throw new ManagedSessionRecordError("await_agent cannot carry in-flight Runtime work.")}const attempt2=input.attempt??input.previous.attempt;if(attempt2===null){throw new ManagedSessionRecordError("await_agent requires the attempt.")}if(input.agentWait.runs.length===0){throw new ManagedSessionRecordError("await_agent requires at least one run.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"await_agent",pendingEventIds:[]},attempt:attempt2,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:input.agentWait,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createAwaitAgentHarnessCheckpoint,"createAwaitAgentHarnessCheckpoint");function createAwaitCommandHarnessCheckpoint(input){if(input.previous.approval?.state==="requested"){throw new ManagedSessionRecordError("await_command cannot keep a requested approval.")}if(input.previous.commandWait!==null&&input.previous.commandWait.runs.some(run=>!run.folded)){throw new ManagedSessionRecordError("await_command cannot replace an unfinished command wait.")}if(input.previous.agentWait!==null&&input.previous.agentWait.runs.some(run=>!run.consumed)){throw new ManagedSessionRecordError("await_command cannot replace an unfinished agent wait.")}if(input.previous.tools?.items.some(item=>item.state==="in_progress")){throw new ManagedSessionRecordError("await_command cannot carry in-flight Runtime work.")}const attempt2=input.attempt??input.previous.attempt;if(attempt2===null){throw new ManagedSessionRecordError("await_command requires the attempt.")}if(input.commandWait.runs.length===0){throw new ManagedSessionRecordError("await_command requires at least one run.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"await_command",pendingEventIds:[]},attempt:attempt2,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:null,commandWait:input.commandWait,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createAwaitCommandHarnessCheckpoint,"createAwaitCommandHarnessCheckpoint");function createConsumedCommandWaitHarnessCheckpoint(input){if(input.previous.continuation.phase!=="await_command"){throw new ManagedSessionRecordError("folded command wait requires an await_command checkpoint.")}if(input.previous.commandWait===null){throw new ManagedSessionRecordError("folded command wait requires the command wait runs.")}const waited=input.previous.commandWait.runs.find(run=>run.commandId===input.commandId);if(waited===void 0){throw new ManagedSessionRecordError(`await_command has no run ${input.commandId}.`)}if(waited.folded){throw new ManagedSessionRecordError(`command wait run ${input.commandId} is already folded.`)}const runs=input.previous.commandWait.runs.map(run=>run.commandId===input.commandId?{...run,folded:true}:run);const allFolded=runs.every(run=>run.folded);return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:allFolded?"model_output_committed":"await_command",pendingEventIds:[]},attempt:input.previous.attempt,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:null,commandWait:{runs,holdsWorkspaceMount:input.previous.commandWait.holdsWorkspaceMount},commandLock:input.timedOut===true?harnessCommandLockOf(input.previous):carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createConsumedCommandWaitHarnessCheckpoint,"createConsumedCommandWaitHarnessCheckpoint");function createConsumedAgentWaitHarnessCheckpoint(input){if(input.previous.continuation.phase!=="await_agent"){throw new ManagedSessionRecordError("consumed agent wait requires an await_agent checkpoint.")}if(input.previous.agentWait===null){throw new ManagedSessionRecordError("consumed agent wait requires the agent wait runs.")}const waited=input.previous.agentWait.runs.find(run=>run.childRunId===input.childRunId);if(waited===void 0){throw new ManagedSessionRecordError(`await_agent has no run ${input.childRunId}.`)}if(waited.consumed){throw new ManagedSessionRecordError(`agent wait run ${input.childRunId} is already consumed.`)}const runs=input.previous.agentWait.runs.map(run=>run.childRunId===input.childRunId?{...run,consumed:true}:run);const allConsumed=runs.every(run=>run.consumed);return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:allConsumed?"model_output_committed":"await_agent",pendingEventIds:[]},attempt:input.previous.attempt,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:{runs},commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createConsumedAgentWaitHarnessCheckpoint,"createConsumedAgentWaitHarnessCheckpoint");function createAwaitRuntimeHarnessCheckpoint(input){if(input.previous.approval?.state==="requested"){throw new ManagedSessionRecordError("await_runtime cannot keep a requested approval.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"await_runtime",pendingEventIds:[]},attempt:input.attempt,tools:input.tools,runtime:input.runtime,approval:null,agentWait:null,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createAwaitRuntimeHarnessCheckpoint,"createAwaitRuntimeHarnessCheckpoint");function createResultsReadyHarnessCheckpoint(input){if(input.previous.continuation.phase!=="await_runtime"){throw new ManagedSessionRecordError("results_ready resume requires an await_runtime checkpoint.")}if(input.previous.attempt===null||input.previous.tools===null){throw new ManagedSessionRecordError("results_ready requires the waited attempt and tools.")}const settledItem=input.previous.tools.items.find(item=>item.executionCallId===input.executionCallId);if(settledItem?.state!=="in_progress"){throw new ManagedSessionRecordError(`await_runtime has no in-progress execution ${input.executionCallId}.`)}const items=input.previous.tools.items.map(item=>item.executionCallId===input.executionCallId?{...item,state:"settled",outcomeRef:input.outcomeRef,consumed:false}:item);const allSettled=items.every(item=>item.state==="settled");return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:allSettled?"results_ready":"await_runtime",pendingEventIds:[]},attempt:input.previous.attempt,tools:{batchId:input.previous.tools.batchId,items},runtime:{bindings:runtimeBindings(input.previous.runtime).map(binding=>binding.executionCallId===input.executionCallId&&binding.state==="dispatch"?{...binding,state:"settled"}:binding)},approval:null,agentWait:null,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createResultsReadyHarnessCheckpoint,"createResultsReadyHarnessCheckpoint");function createTurnSettledHarnessCheckpoint(input){if(input.previous.continuation.phase!=="results_ready"){throw new ManagedSessionRecordError("turn_settled resume requires a results_ready checkpoint.")}const items=input.previous.tools?.items??[];if(items.length===0||items.some(item=>item.state!=="settled"||item.consumed!==true)){throw new ManagedSessionRecordError("turn_settled requires every Runtime receipt to be consumed.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"turn_settled",pendingEventIds:[]},attempt:input.previous.attempt,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:null,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createTurnSettledHarnessCheckpoint,"createTurnSettledHarnessCheckpoint");function createHookStoppedRuntimeHarnessCheckpoint(input){const items=input.previous.tools?.items??[];if(input.previous.continuation.phase!=="results_ready"||items.length===0||items.some(item=>item.state!=="settled")||items.every(item=>item.consumed)){throw new ManagedSessionRecordError("Hook stop requires settled Runtime results not yet consumed by a model.")}return{...input.previous,identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"turn_settled",pendingEventIds:[]}}}__name(createHookStoppedRuntimeHarnessCheckpoint,"createHookStoppedRuntimeHarnessCheckpoint");function createConsumedRuntimeResultsHarnessCheckpoint(input){if(input.previous.continuation.phase!=="results_ready"){throw new ManagedSessionRecordError("consumed Runtime results require a results_ready checkpoint.")}if(input.previous.tools===null){throw new ManagedSessionRecordError("consumed Runtime results require the settled tools.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"results_ready",pendingEventIds:[]},attempt:input.previous.attempt,tools:{batchId:input.previous.tools.batchId,items:input.previous.tools.items.map(item=>item.state==="settled"&&item.consumed===false?{...item,consumed:true}:item)},runtime:input.previous.runtime,approval:null,agentWait:null,commandWait:null,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createConsumedRuntimeResultsHarnessCheckpoint,"createConsumedRuntimeResultsHarnessCheckpoint");function createModelOutputCommittedHarnessCheckpoint(input){if(input.previous.attempt===null){throw new ManagedSessionRecordError("model_output_committed requires the waited attempt.")}const carried=input.previous.agentWait;if(carried!==null&&carried.runs.some(run=>!run.consumed)){throw new ManagedSessionRecordError("model_output_committed cannot carry an unconsumed agent wait.")}const carriedCommands=input.previous.commandWait;if(carriedCommands!==null&&carriedCommands.runs.some(run=>!run.folded)){throw new ManagedSessionRecordError("model_output_committed cannot carry an unfolded command wait.")}return{identity:{...input.previous.identity,checkpointId:input.checkpointId,coveredSequence:input.coveredSequence,previousCheckpointId:input.previousCheckpointId},resume:{...input.previous.resume,throughSequence:input.coveredSequence},continuation:{phase:"model_output_committed",pendingEventIds:[]},attempt:input.previous.attempt,tools:input.previous.tools,runtime:input.previous.runtime,approval:null,agentWait:input.previous.agentWait,commandWait:input.previous.commandWait,commandLock:carriedCommandLock(input.previous),output:input.previous.output,followUp:input.previous.followUp}}__name(createModelOutputCommittedHarnessCheckpoint,"createModelOutputCommittedHarnessCheckpoint");init_esbuild_shims();import{createHash as createHash10}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual2}from"node:util";var CHECKPOINT_STORAGE_PROFILE="managed-checkpoint-paged/1";var CHECKPOINT_HISTORY_KIND="managed-checkpoint-history";var CHECKPOINT_HISTORY_PAGE_BYTES=48*1024;var CHECKPOINT_HISTORY_PAGE_ITEMS=32;var MAX_HISTORY_PAGES=4096;var MAX_HISTORY_BYTES=64*1024*1024;function requireHistory(condition,message){if(!condition)throw new ManagedSessionRecordError(`Checkpoint history: ${message}`)}__name(requireHistory,"requireHistory");function object5(value){requireHistory(value!==null&&typeof value==="object"&&!Array.isArray(value),"expected an object.");return value}__name(object5,"object");function closed4(record4,keys2){requireHistory(Object.keys(record4).length===keys2.length&&keys2.every(key=>key in record4),"fields conflict.")}__name(closed4,"closed");function json(bytes,limit){return object5(parseManagedSessionRecordJson(bytes.toString("utf8"),limit))}__name(json,"json");function historyRef(value){const ref11=assertManagedSessionDurableRef(value,"checkpoint history");requireHistory(ref11.kind===CHECKPOINT_HISTORY_KIND&&ref11.schemaVersion===1&&ref11.byteLength<=CHECKPOINT_HISTORY_PAGE_BYTES,"page reference conflicts.");return ref11}__name(historyRef,"historyRef");function isPagedHarnessCheckpoint(bytes){try{return json(bytes,MANAGED_SESSION_LIMITS.maxEventBytes)["storageProfile"]===CHECKPOINT_STORAGE_PROFILE}catch{return false}}__name(isPagedHarnessCheckpoint,"isPagedHarnessCheckpoint");function physicalRoot(bytes){const record4=json(bytes,MANAGED_SESSION_LIMITS.maxEventBytes);requireHistory(record4["storageProfile"]===CHECKPOINT_STORAGE_PROFILE,"storage profile is unsupported.");const history=object5(record4["history"]);closed4(history,["ref","toolCount","bindingCount"]);const result={ref:historyRef(history["ref"]),toolCount:assertManagedSessionSequence(history["toolCount"],"history.toolCount"),bindingCount:assertManagedSessionSequence(history["bindingCount"],"history.bindingCount"),pageCount:0,byteLength:0};requireHistory(result.toolCount>0,"empty archive.");const{storageProfile:_profile,history:_history,...state}=record4;return{state,history:result}}__name(physicalRoot,"physicalRoot");function checkpointHistoryPage(bytes){const page=json(bytes,CHECKPOINT_HISTORY_PAGE_BYTES);closed4(page,["storageProfile","sessionKey","turnId","promptId","previous","toolCount","bindingCount","items","bindings"]);requireHistory(page["storageProfile"]===`${CHECKPOINT_HISTORY_KIND}/1`,"page profile is unsupported.");requireHistory(Array.isArray(page["items"])&&Array.isArray(page["bindings"]),"page arrays are missing.");const items=page["items"];const bindings=page["bindings"];requireHistory(items.length<=CHECKPOINT_HISTORY_PAGE_ITEMS&&bindings.length<=CHECKPOINT_HISTORY_PAGE_ITEMS&&items.length+bindings.length>0,"page item count conflicts.");for(const item of items){const tool=object5(item);requireHistory(tool["state"]==="settled"&&tool["consumed"]===true,"unfinished or unconsumed tool was archived.")}for(const item of bindings){const binding=object5(item);requireHistory(binding["state"]==="settled"||binding["state"]==="committed","in-flight binding was archived.")}return{sessionKey:page["sessionKey"],turnId:page["turnId"],promptId:page["promptId"],previous:page["previous"]===null?null:historyRef(page["previous"]),toolCount:assertManagedSessionSequence(page["toolCount"],"page.toolCount"),bindingCount:assertManagedSessionSequence(page["bindingCount"],"page.bindingCount"),items,bindings}}__name(checkpointHistoryPage,"checkpointHistoryPage");function checkpointStorageBody(bytes){return isPagedHarnessCheckpoint(bytes)?json(bytes,MANAGED_SESSION_LIMITS.maxEventBytes):parseHarnessCheckpointObject(json(bytes,MANAGED_SESSION_LIMITS.maxEventBytes))}__name(checkpointStorageBody,"checkpointStorageBody");async function verifiedRead(resources,ref11){const bytes=await resources.read(ref11);requireHistory(bytes.byteLength===ref11.byteLength&&createHash10("sha256").update(bytes).digest("hex")===ref11.digest,"resource length or digest conflicts.");return bytes}__name(verifiedRead,"verifiedRead");async function load(resources,ref11){requireHistory(ref11.kind==="managed-checkpoint"&&ref11.schemaVersion===1,"checkpoint reference conflicts.");const bytes=await verifiedRead(resources,ref11);if(!isPagedHarnessCheckpoint(bytes)){const parsed=tryParseHarnessCheckpointV1(bytes);requireHistory(parsed.ok,parsed.ok?"":parsed.message??"invalid inline checkpoint.");return{bytes,checkpoint:parsed.checkpoint}}const root=physicalRoot(bytes);const identity=object5(root.state["identity"]);const pages=[];const visited=new Set;let next=root.history.ref;let toolCount=root.history.toolCount;let bindingCount=root.history.bindingCount;let totalBytes=0;while(next!==null){requireHistory(!visited.has(next.resourceId)&&visited.size<MAX_HISTORY_PAGES,"page cycle or capacity exceeded.");visited.add(next.resourceId);const part=await verifiedRead(resources,next);totalBytes+=part.byteLength;requireHistory(totalBytes<=MAX_HISTORY_BYTES,"decoded history capacity exceeded.");const page=checkpointHistoryPage(part);requireHistory(isDeepStrictEqual2(page.sessionKey,identity["sessionKey"])&&page.turnId===identity["turnId"]&&page.promptId===identity["promptId"],"page belongs to another Session or Turn.");requireHistory(page.toolCount===toolCount&&page.bindingCount===bindingCount,"page counts conflict.");toolCount-=page.items.length;bindingCount-=page.bindings.length;requireHistory(toolCount>=0&&bindingCount>=0&&(page.previous!==null||toolCount+bindingCount===0),"page coverage conflicts.");pages.push(page);next=page.previous}requireHistory(toolCount===0&&bindingCount===0,"history is incomplete.");const tools=object5(root.state["tools"]);const runtime=root.state["runtime"]===null?null:object5(root.state["runtime"]);requireHistory(Array.isArray(tools["items"])&&(runtime===null||Array.isArray(runtime["bindings"])),"active arrays conflict.");pages.reverse();const items=pages.flatMap(page=>page.items);const bindings=pages.flatMap(page=>page.bindings);const checkpoint=parseHarnessCheckpointObject({...root.state,tools:{...tools,items:[...items,...tools["items"]]},runtime:runtime===null?null:{...runtime,bindings:[...bindings,...runtime["bindings"]]}});requireHistory(root.history.bindingCount===0||runtime!==null,"archived bindings lost their group.");return{bytes,checkpoint,history:{...root.history,pageCount:pages.length,byteLength:totalBytes}}}__name(load,"load");async function readHarnessCheckpoint(resources,ref11){return(await load(resources,ref11)).checkpoint}__name(readHarnessCheckpoint,"readHarnessCheckpoint");var ManagedCheckpointHistory=class{constructor(resources){this.resources=resources}static{__name(this,"ManagedCheckpointHistory")}committed;async read(ref11){if(this.committed&&isDeepStrictEqual2(this.committed.ref,ref11))return this.committed;return load(this.resources,ref11)}async tryRead(ref11){if(this.committed&&isDeepStrictEqual2(this.committed.ref,ref11))return{ok:true,checkpoint:this.committed.checkpoint};const bytes=await verifiedRead(this.resources,ref11);if(!isPagedHarnessCheckpoint(bytes)){const parsed=tryParseHarnessCheckpointV1(bytes);if(parsed.ok)this.remember(ref11,{bytes,checkpoint:parsed.checkpoint});return parsed}try{const prepared=await load(this.resources,ref11);this.remember(ref11,prepared);return{ok:true,checkpoint:prepared.checkpoint}}catch(error3){if(!(error3 instanceof ManagedSessionRecordError))throw error3;return{ok:false,reason:"invalid",message:error3.message}}}remember(ref11,prepared){this.committed={...prepared,ref:ref11}}async prepare(checkpoint,previousRef){const state=parseHarnessCheckpointObject(checkpoint);const items=state.tools?.items??[];const bindings=state.runtime?.bindings??[];let history;if(previousRef&&state.continuation.phase!=="before_model"){const previous=await this.read(previousRef);if(previous.history&&managedSessionKeysEqual(previous.checkpoint.identity.sessionKey,state.identity.sessionKey)&&previous.checkpoint.identity.turnId===state.identity.turnId&&previous.checkpoint.identity.promptId===state.identity.promptId){history=previous.history;requireHistory(isDeepStrictEqual2(items.slice(0,history.toolCount),previous.checkpoint.tools?.items.slice(0,history.toolCount))&&isDeepStrictEqual2(bindings.slice(0,history.bindingCount),previous.checkpoint.runtime?.bindings.slice(0,history.bindingCount)??[]),"committed prefix was changed.")}}let eligible=0;while(eligible<items.length&&items[eligible].state==="settled"&&items[eligible].consumed)eligible++;const toolTarget=Math.max(history?.toolCount??0,Math.floor(Math.max(0,eligible-CHECKPOINT_HISTORY_PAGE_ITEMS)/CHECKPOINT_HISTORY_PAGE_ITEMS)*CHECKPOINT_HISTORY_PAGE_ITEMS);const archivedIds=new Set(items.slice(0,toolTarget).map(item=>item.executionCallId));let bindingTarget=0;while(bindingTarget<bindings.length&&bindings[bindingTarget].state!=="dispatch"&&archivedIds.has(bindings[bindingTarget].executionCallId))bindingTarget++;let toolCount=history?.toolCount??0;let bindingCount=history?.bindingCount??0;requireHistory(eligible>=toolCount&&bindingTarget>=bindingCount,"committed history became unfinished.");while(toolCount<toolTarget||bindingCount<bindingTarget){const pageItems=[];const pageBindings=[];const body=__name(()=>({storageProfile:`${CHECKPOINT_HISTORY_KIND}/1`,sessionKey:state.identity.sessionKey,turnId:state.identity.turnId,promptId:state.identity.promptId,previous:history?.ref??null,toolCount:toolCount+pageItems.length,bindingCount:bindingCount+pageBindings.length,items:pageItems,bindings:pageBindings}),"body");const fits=__name(()=>Buffer.byteLength(JSON.stringify(body()),"utf8")<=CHECKPOINT_HISTORY_PAGE_BYTES,"fits");while(toolCount+pageItems.length<toolTarget&&pageItems.length<CHECKPOINT_HISTORY_PAGE_ITEMS){pageItems.push(items[toolCount+pageItems.length]);if(!fits()){pageItems.pop();break}}while(bindingCount+pageBindings.length<bindingTarget&&pageBindings.length<CHECKPOINT_HISTORY_PAGE_ITEMS){pageBindings.push(bindings[bindingCount+pageBindings.length]);if(!fits()){pageBindings.pop();break}}requireHistory(pageItems.length+pageBindings.length>0,"one history entry exceeds the page budget.");const bytes2=Buffer.from(JSON.stringify(body()),"utf8");const pageCount=(history?.pageCount??0)+1;const byteLength2=(history?.byteLength??0)+bytes2.byteLength;requireHistory(pageCount<=MAX_HISTORY_PAGES&&byteLength2<=MAX_HISTORY_BYTES,"decoded history capacity exceeded.");const ref11=await this.resources.publish(CHECKPOINT_HISTORY_KIND,bytes2);toolCount+=pageItems.length;bindingCount+=pageBindings.length;history={ref:ref11,toolCount,bindingCount,pageCount,byteLength:byteLength2}}if(!history)return{bytes:encodeHarnessCheckpointV1(state),checkpoint:state};const tail={...state,tools:state.tools&&{...state.tools,items:items.slice(toolCount)},runtime:state.runtime&&{...state.runtime,bindings:bindings.slice(bindingCount)}};const bytes=Buffer.from(JSON.stringify({...JSON.parse(encodeHarnessCheckpointV1(tail).toString("utf8")),storageProfile:CHECKPOINT_STORAGE_PROFILE,history:{ref:history.ref,toolCount:history.toolCount,bindingCount:history.bindingCount}}),"utf8");requireHistory(bytes.byteLength<=MANAGED_SESSION_LIMITS.maxEventBytes,"active checkpoint exceeds its physical budget.");return{bytes,checkpoint:state,history}}};init_esbuild_shims();var HOSTED_RECOVERY_RESOURCE_KINDS=new Set(["hosted-approval-continuation","hosted-model-request","hosted-turn-cleanup"]);var HOSTED_MODEL_REQUEST_BYTES=32*1024*1024;function parseHostedRecoveryResource(bytes,expectedKey,kind){const value=parseManagedSessionRecordJson(bytes.toString("utf8"),kind==="hosted-model-request"?HOSTED_MODEL_REQUEST_BYTES:64*1024);if(!value||typeof value!=="object"||Array.isArray(value)||value["v"]!==1)throw new ManagedSessionRecordError("Invalid Hosted recovery resource.");const key=assertManagedSessionKey(value["sessionKey"],"Hosted recovery sessionKey");assertManagedSessionStableId(value["promptId"],"Hosted recovery promptId");if(expectedKey&&(key.tenantId!==expectedKey.tenantId||key.workspaceId!==expectedKey.workspaceId||key.sessionId!==expectedKey.sessionId))throw new ManagedSessionRecordError("Hosted recovery resource names another Session.");return value}__name(parseHostedRecoveryResource,"parseHostedRecoveryResource");function hostedRecoveryReferences(value){const refs2=new Map;if(!value||typeof value!=="object"||Array.isArray(value))return[];const body=value;const pending=["definitionRef","rootSnapshotRef","assistantRef","inputRef","continuationRef"].flatMap(field=>body[field]?[body[field]]:[]);if(Array.isArray(body["calls"]))for(const call of body["calls"]){if(!call||typeof call!=="object")continue;const member=call;pending.push(member["inputRef"],member["definitionRef"])}for(const item of pending){const ref11=assertManagedSessionDurableRef(item,"Hosted recovery reference");const previous=refs2.get(ref11.resourceId);if(previous&&(previous.kind!==ref11.kind||previous.schemaVersion!==ref11.schemaVersion||previous.byteLength!==ref11.byteLength||previous.digest!==ref11.digest))throw new ManagedSessionRecordError("Hosted recovery references conflict.");refs2.set(ref11.resourceId,ref11)}return[...refs2.values()]}__name(hostedRecoveryReferences,"hostedRecoveryReferences");init_esbuild_shims();var MANAGED_MESSAGE_KIND="managed-message";var MANAGED_MESSAGE_PART_KIND="managed-message-part";var MANAGED_MESSAGE_CHUNKS_KIND="managed-message-chunks";var MANAGED_MESSAGE_PART_BYTES=60*1024;var MANAGED_MESSAGE_INLINE_BYTES=64*1024;async function publishManagedMessageBody(resources,body){if(body.byteLength<=MANAGED_MESSAGE_INLINE_BYTES){return resources.publish(MANAGED_MESSAGE_KIND,body)}const parts=[];for(let offset2=0;offset2<body.byteLength;offset2+=MANAGED_MESSAGE_PART_BYTES){parts.push(await resources.publish(MANAGED_MESSAGE_PART_KIND,body.subarray(offset2,offset2+MANAGED_MESSAGE_PART_BYTES)))}return resources.publish(MANAGED_MESSAGE_CHUNKS_KIND,Buffer.from(JSON.stringify({parts}),"utf8"))}__name(publishManagedMessageBody,"publishManagedMessageBody");async function readManagedMessageBody(read2,ref11){if(ref11.kind!==MANAGED_MESSAGE_CHUNKS_KIND){return read2(ref11)}const{parts}=parseManagedMessageChunkManifest(await read2(ref11));const buffers=[];for(const part of parts)buffers.push(await read2(part));return Buffer.concat(buffers)}__name(readManagedMessageBody,"readManagedMessageBody");function managedMessageChunkParts(kind,body){return kind===MANAGED_MESSAGE_CHUNKS_KIND?parseManagedMessageChunkManifest(body).parts:[]}__name(managedMessageChunkParts,"managedMessageChunkParts");function parseManagedMessageChunkManifest(bytes){const manifest=JSON.parse(bytes.toString("utf8"));const parts=manifest["parts"];if(!Array.isArray(parts)||parts.length===0){throw new ManagedSessionRecordError("a Managed message chunk manifest must carry parts.")}return{parts:parts.map(part=>{const ref11=assertManagedSessionDurableRef(part,"message chunk part");if(ref11.kind!==MANAGED_MESSAGE_PART_KIND){throw new ManagedSessionRecordError("a Managed message chunk manifest must reference message parts.")}return ref11})}}__name(parseManagedMessageChunkManifest,"parseManagedMessageChunkManifest");var RESOURCE_REF_PATHS={"managed-tool_stage":["inputRef","permissionRef","resultRef"],"managed-history_maintenance":["requestRef","candidateRef"],"managed-mcp_configuration":["catalogRef"],"managed-mcp_operation":["argsRef","resultRef"],"managed-hook_registration":["catalogRef"],"managed-hook_execution":["planRef","inputRef","resultRef"],"managed-monitor_run":["commandRef","startReceiptRef","outputRef","lastObservationRef"],"managed-child_run":["commandRef","startReceiptRef","outputRef","inputRef","resultRef","terminalReceiptRef"],"managed-child_acceptance":["contentRef","terminalReceiptRef"],"managed-channel_route":["policyRef"],"managed-channel_delivery":["contentRef","segments.*.contentRef","segments.*.receipt.proofRef"],"managed-schedule":["promptRef"],"managed-automation_run":["gateOutputRef"],"managed-session_message":["contentRef"],"managed-session_command":["argsRef","replyRef"],"managed-team_task":["descriptionRef","metadataRef"],"managed-team_message":["contentRef"],"managed-team_plan":["planRef","feedbackRef"],"managed-definition":["sessionSkillsRef","agentDefinition.instructionsRef","agentDefinition.skillsRef","publicChildExtensionAgent.effectiveConfigRef","publicChildExtensionAgent.extensionAgent.bundleRef","publicChildExtensionAgent.extensionAgent.contributionsRef"],"managed-action-options":["definitionRef","rootSnapshotRef","assistantRef","inputRef","continuationRef","calls.*.inputRef","calls.*.definitionRef"],"managed-hook-plan":["messagesRef"],"managed-hook-message-chunks":["parts.*"],"managed-tool-outcome-chunks":["parts.*"],"managed-tool-outcome":["manifestRef","envelope.capture.manifest"],"managed-config_install":["previousBundleRef","restoresBundleRef","bundleRef","rootSnapshotRef","stageAckRefs.*","enableAckRefs.*"],"managed-extension-config-bundle":["packages.*.contributionsRef"],"managed-extension-contributions":["parts.*"]};var CHECKPOINT_REF_PATHS=["resume.apiHistoryRef","resume.fileHistoryRef","resume.artifactRef","resume.goalRecordsRef","resume.goalCheckpointWindowRef","resume.tokenCountsRef","resume.uiTelemetryRef","resume.attributionRef","attempt.routeRef","attempt.capabilityRef","attempt.samplingRef","attempt.usageRef","tools.items.*.outcomeRef","approval.optionsRef","approval.decisionRef","approval.invocationRef","output.llmContentRef","output.hookResultRef","output.mediaRefs.*"];function refsAtPaths(value,paths){const visit3=__name((current2,path89)=>{if(current2===null||current2===void 0)return[];if(path89.length===0)return[assertManagedSessionDurableRef(current2,"resource dependency")];if(typeof current2!=="object")return[];const[field,...rest]=path89;return field==="*"?(Array.isArray(current2)?current2:[]).flatMap(item=>visit3(item,rest)):visit3(current2[field],rest)},"visit");return paths.flatMap(path89=>visit3(value,path89.split(".")))}__name(refsAtPaths,"refsAtPaths");function managedSessionNestedResourceRefs(ref11,bytes){if(ref11.kind===MANAGED_MESSAGE_CHUNKS_KIND)return managedMessageChunkParts(ref11.kind,bytes);if(ref11.kind===CHECKPOINT_HISTORY_KIND)return refsAtPaths(checkpointHistoryPage(bytes),["previous","items.*.outcomeRef"]);if(ref11.kind==="managed-checkpoint"){if(isPagedHarnessCheckpoint(bytes))return refsAtPaths(checkpointStorageBody(bytes),[...CHECKPOINT_REF_PATHS,"history.ref"]);const parsed=tryParseHarnessCheckpointV1(bytes);return parsed.ok?refsAtPaths(parsed.checkpoint,CHECKPOINT_REF_PATHS):[]}if(ref11.kind==="managed-input"){try{return decodeChannelInputEnvelope(bytes).attachments.flatMap(attachment=>"ref"in attachment?[attachment.ref]:[])}catch{try{return refsAtPaths(decodeChildLaunchEnvelope(bytes),["publicLaunch.skillsRef","publicLaunch.extensionAgent.bundleRef","publicLaunch.extensionAgent.contributionsRef"])}catch{return[]}}}if(HOSTED_RECOVERY_RESOURCE_KINDS.has(ref11.kind))return hostedRecoveryReferences(parseHostedRecoveryResource(bytes,void 0,ref11.kind));if(ref11.kind===MANAGED_TOOL_RESULT_KINDS.manifest){try{return refsAtPaths(parseToolResultManifestBytes(bytes),["contents.*.body.ref","contents.*.body.pages.*.ref"])}catch{return[]}}const domain=MANAGED_SESSION_DOMAINS.find(domain2=>ref11.kind===`managed-${domain2}`);const paths=RESOURCE_REF_PATHS[ref11.kind]??[];if(!domain&&paths.length===0)return[];const record4=parseManagedSessionRecordJson(bytes.toString("utf8"),bytes.length);return refsAtPaths(record4,[...paths,...domain?["previousRecordRef"]:[],...ref11.kind==="managed-file_history"&&record4["schemaVersion"]===2&&record4["profile"]==="csi-files-retirement/1"?["preparation.intentRef","preparation.invocations.*.inputRef","preparation.invocations.*.toolDefinitionRef"]:[]])}__name(managedSessionNestedResourceRefs,"managedSessionNestedResourceRefs");init_esbuild_shims();var ManagedSessionCommitRejectedError=class extends ManagedSessionRecordError{static{__name(this,"ManagedSessionCommitRejectedError")}constructor(cause){super(cause.message);this.cause=cause;this.name="ManagedSessionCommitRejectedError"}};function managedSessionCommandKey(operation,commandId){return`${operation}\0${commandId}`}__name(managedSessionCommandKey,"managedSessionCommandKey");function managedSessionActivationStateFrom(event){return{activationId:event.payload["activationId"],epoch:event.payload["epoch"],workerId:event.payload["workerId"],phase:event.payload["phase"],expiresAt:event.payload["expiresAt"],renewalSeq:event.payload["renewalSeq"]??0,installRef:event.payload["installRef"]??null}}__name(managedSessionActivationStateFrom,"managedSessionActivationStateFrom");function scanManagedSessionJournal(bytes,sessionKey,maxBytes){const text3=(maxBytes===void 0||maxBytes>=bytes.byteLength?bytes:bytes.subarray(0,maxBytes)).toString("utf8");const lines=text3.split("\n");const tornTail=lines[lines.length-1]!==""?1:0;lines.pop();let header;const events=[];const transactions=new Map;let committed=0;let lastMarkerDigest=null;let lastRecordUuid=null;let activation;let scanned=0;let committedBytes=0;let headerBytes=0;let foreignRecords=0;let engineRecords=0;let pending=[];for(let index=0;index<lines.length;index++){const line2=lines[index];if(line2===""){throw new ManagedSessionRecordError(`session log line ${index+1} is blank.`)}scanned+=Buffer.byteLength(line2,"utf8")+1;const record4=parseManagedSessionRecordJson(line2,MANAGED_SESSION_LIMITS.maxEventBytes);if(record4===null||typeof record4!=="object"||Array.isArray(record4)){throw new ManagedSessionRecordError(`session log line ${index+1} is not a record object.`)}const envelope2=record4;const subtype=envelope2["subtype"];if(typeof envelope2["uuid"]==="string"){lastRecordUuid=envelope2["uuid"]}if(subtype!==MANAGED_SESSION_HEADER_SUBTYPE&&subtype!==MANAGED_SESSION_EVENT_SUBTYPE&&subtype!==MANAGED_SESSION_COMMIT_SUBTYPE){if(header!==void 0){throw new ManagedSessionRecordError(`session log line ${index+1} has the unknown subtype ${String(subtype)} after the Managed header.`)}foreignRecords++;if(subtype==="session_execution_engine")engineRecords++;continue}const body=envelope2["managedSession"];if(subtype===MANAGED_SESSION_HEADER_SUBTYPE){if(header!==void 0){throw new ManagedSessionRecordError(`session log line ${index+1} repeats the Managed header.`)}if(Buffer.byteLength(line2,"utf8")>MANAGED_SESSION_LIMITS.maxHeaderBytes){throw new ManagedSessionRecordError(`record exceeds ${MANAGED_SESSION_LIMITS.maxHeaderBytes} UTF-8 bytes.`)}header=parseManagedSessionHeader(body);headerBytes=scanned;if(!managedSessionKeysEqual(header.sessionKey,sessionKey)){throw new ManagedSessionRecordError("session log header belongs to a different session.")}continue}if(header===void 0){throw new ManagedSessionRecordError(`session log line ${index+1} precedes the Managed header.`)}if(subtype===MANAGED_SESSION_EVENT_SUBTYPE){const event=parseManagedSessionEvent(body);if(!managedSessionKeysEqual(event.sessionKey,sessionKey)){throw new ManagedSessionRecordError(`session log line ${index+1} belongs to a different session.`)}const expected=committed+pending.length+1;if(event.sequence!==expected){throw new ManagedSessionRecordError(`session log line ${index+1} has sequence ${event.sequence} where ${expected} was expected.`)}pending.push(event);continue}const marker=parseManagedSessionCommitMarker(body);if(marker.previousCommitDigest!==lastMarkerDigest){throw new ManagedSessionRecordError(`session log line ${index+1} does not chain to the previous commit.`)}if(marker.eventCount!==pending.length||marker.firstSequence!==committed+1||marker.lastSequence!==committed+pending.length){throw new ManagedSessionRecordError(`session log line ${index+1} does not cover the preceding events.`)}if(marker.eventsDigest!==managedSessionEventsDigest(pending)){throw new ManagedSessionRecordError(`session log line ${index+1} does not match the preceding event content.`)}for(const event of pending){if(event.kind==="checkpoint.committed"&&event.payload["coveredSequence"]>committed){throw new ManagedSessionRecordError("checkpoint covers events not committed before its transaction.")}events.push(event);if(event.kind==="activation.changed"){activation=managedSessionActivationStateFrom(event)}}committed=marker.lastSequence;committedBytes=scanned;lastMarkerDigest=managedToolDigest(marker,MANAGED_SESSION_LIMITS.maxCommitMarkerBytes);transactions.set(managedSessionCommandKey(marker.operation,marker.commandId),{contentDigest:marker.contentDigest,receipt:{transactionId:marker.transactionId,commandId:marker.commandId,operation:marker.operation,firstSequence:marker.firstSequence,lastSequence:marker.lastSequence,committedSequence:marker.lastSequence,replayed:false}});pending=[]}return{header,events,transactions,committed,lastMarkerDigest,lastRecordUuid,activation,committedBytes,headerBytes,uncommittedBytes:Buffer.byteLength(text3,"utf8")-committedBytes,uncommitted:pending.length+tornTail,foreignRecords,engineRecords}}__name(scanManagedSessionJournal,"scanManagedSessionJournal");init_esbuild_shims();function requireSnapshot2(condition,detail){if(!condition)throw new ManagedSessionRecordError(`Local journal snapshot ${detail}.`)}__name(requireSnapshot2,"requireSnapshot");function readLocalManagedJournal(options2){let bytes;try{bytes=readLocalJournalBytes(options2.transcriptPath,options2.maxBytes)}catch(error3){if(error3.code==="ENOENT")return scanManagedSessionJournal(Buffer.alloc(0),options2.sessionKey);throw error3}const base2=parseLocalJournalBase(bytes,options2.sessionKey);if(!base2)return scanManagedSessionJournal(bytes,options2.sessionKey);const manifest=readLocalJournalManifest(options2.runtimeBaseDir,options2.sessionKey,base2.manifest);const chunks=manifest.pages.map(ref11=>readLocalJournalResource(options2.runtimeBaseDir,options2.sessionKey,ref11));const prefix2=Buffer.concat(chunks);requireSnapshot2(prefix2.length===manifest.byteLength&&localJournalDigest(prefix2)===manifest.digest,"prefix bytes differ");const original=scanManagedSessionJournal(prefix2,options2.sessionKey);requireSnapshot2(original.uncommitted===0&&original.committedBytes===prefix2.length&&original.committed===manifest.committedSequence&&original.lastMarkerDigest===manifest.lastCommitDigest&&original.lastRecordUuid===manifest.lastRecordUuid,"prefix commit proof differs");requireSnapshot2(localJournalPhysicalPrefix(prefix2,original.header).equals(bytes.subarray(0,base2.headerEnd)),"ownership prefix differs from its source");for(const ref11 of manifest.resources)readLocalJournalResource(options2.runtimeBaseDir,options2.sessionKey,ref11);const logical=scanManagedSessionJournal(Buffer.concat([prefix2,bytes.subarray(base2.baseEnd)]),options2.sessionKey);const verified=new Map(manifest.resources.map(ref11=>[ref11.resourceId,ref11]));const pending=logical.events.filter(event=>event.sequence>manifest.committedSequence).flatMap(managedSessionEventRefs);while(pending.length){const ref11=pending.pop();const previous=verified.get(ref11.resourceId);if(previous){requireSnapshot2(previous.kind===ref11.kind&&previous.schemaVersion===ref11.schemaVersion&&previous.byteLength===ref11.byteLength&&previous.digest===ref11.digest,"tail resource references conflict");continue}verified.set(ref11.resourceId,ref11);pending.push(...managedSessionNestedResourceRefs(ref11,readLocalJournalResource(options2.runtimeBaseDir,options2.sessionKey,ref11)))}return{...logical,headerBytes:base2.headerEnd,committedBytes:base2.baseEnd+logical.committedBytes-prefix2.length,uncommittedBytes:bytes.length-(base2.baseEnd+logical.committedBytes-prefix2.length)}}__name(readLocalManagedJournal,"readLocalManagedJournal");function sourceHeader(bytes){for(const line2 of bytes.toString("utf8").split("\n")){if(!line2)continue;const record4=localJournalObject(JSON.parse(line2));if(record4["subtype"]==="managed_session_header_v1"){return parseManagedSessionHeader(record4["managedSession"])}}return void 0}__name(sourceHeader,"sourceHeader");async function acquireLocalManagedSessionWriter(options2){let header;try{header=sourceHeader(readLocalJournalBytes(options2.transcriptPath))}catch(error3){if(error3.code!=="ENOENT")throw error3}const lease=await SessionWriterLease.acquire({...options2,takeoverPolicy:"certified",lockSchema:{schemaVersion:3,formatVersion:header?.minimumReader==="managed-session/2"?LOCAL_MANAGED_JOURNAL_FORMAT:1,resumeFormatVersion:LOCAL_MANAGED_JOURNAL_FORMAT}});return lease}__name(acquireLocalManagedSessionWriter,"acquireLocalManagedSessionWriter");async function prepareLocalManagedSessionWriter(lease,expectedSessionKey){const options2={runtimeBaseDir:lease.runtimeBaseDir,transcriptPath:lease.transcriptPath,sessionId:lease.sessionId};const proof=lease.takeoverCommitProof;if(!proof||lease.managedJournalFormatVersion!==LOCAL_MANAGED_JOURNAL_FORMAT)return false;let header;try{const bytes=Buffer.from(await lease.readTranscript());header=sourceHeader(bytes);if(!header)return false;if(header.sessionKey.sessionId!==options2.sessionId||!managedSessionKeysEqual(header.sessionKey,expectedSessionKey)){throw new ManagedSessionRecordError("Local snapshot source has a different Session.")}if(parseLocalJournalBase(bytes,header.sessionKey))return false;const scan=scanManagedSessionJournal(bytes,header.sessionKey);if(scan.committed!==proof.last_commit_sequence||(scan.lastMarkerDigest??"0".repeat(64))!==proof.committed_prefix_hash){const{ManagedSessionConflictError:ManagedSessionConflictError2}=await import("./managed-session-authority-MYOYTUM2.js");throw new ManagedSessionConflictError2("Local snapshot source does not match the sealed writer proof.")}if(scan.uncommitted>0||scan.committed===0)return false;const resources=LocalManagedSessionResourceStore.create({runtimeBaseDir:options2.runtimeBaseDir,sessionKey:header.sessionKey});const pending=[header.definitionRef,header.rootSnapshotRef,...header.baseTranscriptProof?[header.baseTranscriptProof]:[],...scan.events.flatMap(managedSessionEventRefs)];const refs2=new Map;while(pending.length){const ref11=pending.pop();const previous=refs2.get(ref11.resourceId);if(previous){if(previous.kind!==ref11.kind||previous.schemaVersion!==ref11.schemaVersion||previous.byteLength!==ref11.byteLength||previous.digest!==ref11.digest){throw new ManagedSessionRecordError("Local snapshot resource references conflict.")}continue}refs2.set(ref11.resourceId,ref11);pending.push(...managedSessionNestedResourceRefs(ref11,await resources.read(ref11)))}const pages=[];let pageStart=0;let transactionEnd=0;let offset2=0;while(offset2<bytes.length){const end=bytes.indexOf(10,offset2);if(end<0)throw new ManagedSessionRecordError("Local snapshot source has a torn line.");const record4=localJournalObject(JSON.parse(bytes.subarray(offset2,end).toString("utf8")));if(record4["subtype"]==="managed_session_commit_v1"){if(end+1-pageStart>LOCAL_MANAGED_SNAPSHOT_PAGE_BYTES){if(transactionEnd===pageStart)throw new ManagedSessionRecordError("Local snapshot transaction exceeds its page budget.");pages.push(await resources.publishJournalSnapshot(LOCAL_MANAGED_SNAPSHOT_PAGE_KIND,bytes.subarray(pageStart,transactionEnd)));pageStart=transactionEnd}transactionEnd=end+1;if(transactionEnd-pageStart>LOCAL_MANAGED_SNAPSHOT_PAGE_BYTES)throw new ManagedSessionRecordError("Local snapshot transaction exceeds its page budget.")}offset2=end+1}pages.push(await resources.publishJournalSnapshot(LOCAL_MANAGED_SNAPSHOT_PAGE_KIND,bytes.subarray(pageStart)));const latestRef=__name(domain=>scan.events.findLast(event=>event.kind==="domain.committed"&&event.payload["domain"]===domain)?.payload["recordRef"],"latestRef");const manifest={format:LOCAL_MANAGED_SNAPSHOT_FORMAT,sessionKey:header.sessionKey,pages,byteLength:bytes.length,digest:localJournalDigest(bytes),committedSequence:scan.committed,lastCommitDigest:scan.lastMarkerDigest,lastRecordUuid:scan.lastRecordUuid,resources:[...refs2.values()].sort((a,b2)=>a.resourceId.localeCompare(b2.resourceId)),titleRef:latestRef("session_metadata")??null,sourceRef:latestRef("session_source")??null};const manifestRef=await resources.publishJournalSnapshot(LOCAL_MANAGED_SNAPSHOT_KIND,Buffer.from(JSON.stringify(manifest)));const physicalPrefix=localJournalPhysicalPrefix(bytes,header);const headerRecord=localJournalObject(JSON.parse(physicalPrefix.toString("utf8").trimEnd().split("\n").at(-1)));const base2={uuid:randomUUID4(),parentUuid:headerRecord["uuid"],type:"system",subtype:LOCAL_MANAGED_SNAPSHOT_BASE,sessionId:options2.sessionId,managedSessionSnapshot:{format:LOCAL_MANAGED_SNAPSHOT_FORMAT,sessionKey:header.sessionKey,manifest:manifestRef}};const sessionKey=header.sessionKey;await lease.replaceManagedTranscript(`${physicalPrefix.toString("utf8")}${JSON.stringify(base2)}
100
101
  `,manifest.digest,()=>{const restored=readLocalManagedJournal({...options2,sessionKey});if(restored.committed!==scan.committed||restored.lastMarkerDigest!==scan.lastMarkerDigest||restored.lastRecordUuid!==scan.lastRecordUuid||JSON.stringify([...restored.transactions])!==JSON.stringify([...scan.transactions])){throw new ManagedSessionRecordError("Local snapshot replacement changed the logical commit proof.")}});return true}catch(error3){await lease.sealForHandoff(proof).catch(()=>void 0);throw error3}}__name(prepareLocalManagedSessionWriter,"prepareLocalManagedSessionWriter");var LocalJsonlManagedSessionJournalStore=class{constructor(options2){this.options=options2}static{__name(this,"LocalJsonlManagedSessionJournalStore")}async open(request){const adopted=this.options.lease!==void 0;const lease=this.options.lease??await acquireLocalManagedSessionWriter({runtimeBaseDir:this.options.runtimeBaseDir,sessionId:this.options.sessionId,transcriptPath:this.options.transcriptPath});return new LocalJsonlManagedSessionJournalHandle(lease,request.sessionKey,!adopted,this.options.requireNew!==true)}static fromLease(lease,sessionKey){return new LocalJsonlManagedSessionJournalHandle(lease,sessionKey,false)}static async read(options2){return readLocalManagedJournal(options2)}};var LocalJsonlManagedSessionJournalHandle=class{constructor(lease,sessionKey,ownsLease,prepareOnRead=true){this.lease=lease;this.sessionKey=sessionKey;this.ownsLease=ownsLease;this.prepareOnRead=prepareOnRead}static{__name(this,"LocalJsonlManagedSessionJournalHandle")}preparation;async read(options2={}){if(this.prepareOnRead){this.preparation??=prepareLocalManagedSessionWriter(this.lease,this.sessionKey);await this.preparation}return LocalJsonlManagedSessionJournalStore.read({transcriptPath:this.lease.transcriptPath,runtimeBaseDir:this.lease.runtimeBaseDir,sessionKey:this.sessionKey,...options2})}async appendTransaction(records){for(const record4 of records){await this.lease.appendJsonLine(record4)}}seal(commit){return this.lease.sealForHandoff({last_commit_sequence:commit.lastCommitSequence,committed_prefix_hash:commit.committedPrefixHash})}get writerSealed(){return this.lease.isReleased}get takeoverCommitProof(){const proof=this.lease.takeoverCommitProof;if(proof===void 0)return void 0;return{lastCommitSequence:proof.last_commit_sequence,committedPrefixHash:proof.committed_prefix_hash}}async abort(){if(!this.ownsLease)return;if((this.lease.managedJournalFormatVersion??0)>=2){const proof=this.lease.takeoverCommitProof;if(proof)await this.lease.sealForHandoff(proof);return}await this.lease.release()}async recoverUncommittedTail(){const scan=await this.read();if(scan.uncommitted===0){throw new ManagedSessionRecordError("session log has no uncommitted tail to discard.")}const retain=Math.max(scan.committedBytes,scan.headerBytes);if(retain===0){throw new ManagedSessionRecordError("session log has no committed prefix to retain.")}const bytes=await readFile6(this.lease.transcriptPath);if(bytes.byteLength<=retain){throw new ManagedSessionRecordError("session log changed while preparing tail recovery.")}const discarded=bytes.subarray(retain);const diagnosticPath=`${this.lease.transcriptPath}.uncommitted-tail`;const pendingPath=`${diagnosticPath}.pending`;await writeFile(pendingPath,discarded,{mode:384});try{await this.lease.truncateTo(retain)}catch(cause){await unlink7(pendingPath).catch(()=>void 0);throw cause}await rename4(pendingPath,diagnosticPath);return{discardedBytes:discarded.byteLength,diagnosticPath}}};init_esbuild_shims();import{createHash as createHash11}from"node:crypto";init_esbuild_shims();var CONFIG_KEYS=["configurationId","runtimeSessionId","serverId","serverRevision","configRevision","catalogRevision","connectionGeneration","catalogRef","releaseState","run"];var OPERATION_KEYS=["operationId","configurationId","serverId","serverRevision","configRevision","catalogRevision","connectionGeneration","operationKind","cancelRequested","argsRef","resultRef","run"];var CONFIG_FIXED=["configurationId","runtimeSessionId","serverId","serverRevision","configRevision"];function fail6(message){throw new ManagedSessionRecordError(message)}__name(fail6,"fail");function closed5(value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key))){fail6(`MCP record must have exactly the keys ${keys2.join(", ")}.`)}return{...value}}__name(closed5,"closed");function revision4(value,label){const parsed=assertManagedSessionSequence(value,label);if(parsed<1)fail6(`${label} must be positive.`);return parsed}__name(revision4,"revision");function ref5(value,label){return Object.freeze(assertManagedSessionDurableRef(value,label))}__name(ref5,"ref");function pinnedRun(value,serverId,serverRevision){const run=parseExtensionRun(value);if(run.definition?.definitionId!==serverId||run.definition.definitionRevision!==serverRevision||run.delivery!==null||run.deliveryId!==null||run.dispatchId!==null){fail6("MCP run must pin its server definition and have no delivery.")}return run}__name(pinnedRun,"pinnedRun");function canRelease(run){return run.execution==="settled"&&(run.state==="settled"||run.state==="failed")||run.execution==="not_started_proven"&&run.state==="cancelled"}__name(canRelease,"canRelease");function parseMcpConfiguration(value){const body=closed5(value,CONFIG_KEYS);const serverId=assertManagedSessionStableId(body.serverId,"serverId");const serverRevision=revision4(body.serverRevision,"serverRevision");const run=pinnedRun(body.run,serverId,serverRevision);if(body.releaseState!=="active"&&body.releaseState!=="releasing"&&body.releaseState!=="drained"&&body.releaseState!=="released"){fail6("MCP releaseState must be active, releasing, drained or released.")}const parsed={configurationId:assertManagedSessionStableId(body.configurationId,"configurationId"),runtimeSessionId:assertManagedSessionStableId(body.runtimeSessionId,"runtimeSessionId"),serverId,serverRevision,configRevision:revision4(body.configRevision,"configRevision"),catalogRevision:body.catalogRevision===null?null:revision4(body.catalogRevision,"catalogRevision"),connectionGeneration:body.connectionGeneration===null?null:revision4(body.connectionGeneration,"connectionGeneration"),catalogRef:body.catalogRef===null?null:ref5(body.catalogRef,"catalogRef"),releaseState:body.releaseState,run};if(run.effectId!==parsed.configurationId||run.executionCallId!==null){fail6("MCP configuration must identify its physical request through effectId.")}if(parsed.releaseState!=="active"&&!canRelease(run)){fail6("Only a conclusively completed MCP configuration can be released.")}const published=parsed.catalogRef!==null;if(published!==(parsed.catalogRevision!==null)||published!==(parsed.connectionGeneration!==null)||published!==(run.state==="settled")||published&&(run.execution!=="settled"||run.runtime===null)){fail6("MCP configuration publishes its catalog and connection exactly on settlement.")}return Object.freeze(parsed)}__name(parseMcpConfiguration,"parseMcpConfiguration");function parseMcpOperation(value){const body=closed5(value,OPERATION_KEYS);const serverId=assertManagedSessionStableId(body.serverId,"serverId");const serverRevision=revision4(body.serverRevision,"serverRevision");const run=pinnedRun(body.run,serverId,serverRevision);const operationId=assertManagedSessionStableId(body.operationId,"operationId");if(body.operationKind!=="resource_read"&&body.operationKind!=="prompt_get"){fail6("MCP operationKind must be resource_read or prompt_get.")}if(run.effectId!==operationId||run.executionCallId!==null){fail6("MCP operation must identify its physical request through effectId.")}if(typeof body.cancelRequested!=="boolean"){fail6("MCP cancelRequested must be boolean.")}const parsed={operationId,configurationId:assertManagedSessionStableId(body.configurationId,"configurationId"),serverId,serverRevision,configRevision:revision4(body.configRevision,"configRevision"),catalogRevision:revision4(body.catalogRevision,"catalogRevision"),connectionGeneration:revision4(body.connectionGeneration,"connectionGeneration"),operationKind:body.operationKind,cancelRequested:body.cancelRequested,argsRef:ref5(body.argsRef,"argsRef"),resultRef:body.resultRef===null?null:ref5(body.resultRef,"resultRef"),run};if(run.state==="settled"&&parsed.resultRef===null||parsed.resultRef!==null&&(run.execution!=="settled"||run.runtime===null)){fail6("MCP result requires a settled physical response; successful operations need a result.")}return Object.freeze(parsed)}__name(parseMcpOperation,"parseMcpOperation");function accepts3(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts3,"accepts");function isMcpConfigurationStart(value){return accepts3(()=>isExtensionRunStart(parseMcpConfiguration(value).run))}__name(isMcpConfigurationStart,"isMcpConfigurationStart");function isMcpOperationStart(value){return accepts3(()=>{const record4=parseMcpOperation(value);return isExtensionRunStart(record4.run)&&record4.resultRef===null&&!record4.cancelRequested})}__name(isMcpOperationStart,"isMcpOperationStart");function same3(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same3,"same");function isMcpConfigurationSuccessor(previous,next){return accepts3(()=>{const before=parseMcpConfiguration(previous);const after=parseMcpConfiguration(next);return CONFIG_FIXED.every(key=>same3(before[key],after[key]))&&isExtensionRunSuccessor(before.run,after.run)&&(before.releaseState===after.releaseState||canRelease(before.run)&&before.releaseState==="active"&&after.releaseState==="releasing"||before.releaseState==="releasing"&&after.releaseState==="drained"||before.releaseState==="drained"&&after.releaseState==="released"||before.releaseState==="releasing"&&after.releaseState==="released")&&(before.catalogRef===null||same3({...before,releaseState:null},{...after,releaseState:null}))})}__name(isMcpConfigurationSuccessor,"isMcpConfigurationSuccessor");function isMcpOperationSuccessor(previous,next){return accepts3(()=>{const before=parseMcpOperation(previous);const after=parseMcpOperation(next);return OPERATION_KEYS.filter(key=>key!=="run"&&key!=="resultRef"&&key!=="cancelRequested").every(key=>same3(before[key],after[key]))&&isExtensionRunSuccessor(before.run,after.run)&&(!before.cancelRequested||after.cancelRequested)&&(before.resultRef===null||same3(before.resultRef,after.resultRef))&&(!["settled","failed","cancelled"].includes(before.run.state)||same3(before,after))})}__name(isMcpOperationSuccessor,"isMcpOperationSuccessor");init_esbuild_shims();var REGISTRATION_KEYS=["registrationId","catalogId","catalogRevision","catalogRef","run"];var EXECUTION_KEYS=["hookExecutionId","occurrenceId","runtimeSessionId","registrationId","eventName","ordinal","hookId","planRef","inputRef","resultRef","onceKey","cancelRequested","run"];function fail7(message){throw new ManagedSessionRecordError(message)}__name(fail7,"fail");function closed6(value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key)))fail7(`Hook record must have exactly the keys ${keys2.join(", ")}.`);return{...value}}__name(closed6,"closed");function ref6(value,label){return Object.freeze(assertManagedSessionDurableRef(value,label))}__name(ref6,"ref");function pinnedRun2(value,effectId){const run=parseExtensionRun(value);if(run.definition===null||run.effectId!==effectId||run.executionCallId!==null||run.dispatchId!==null||run.deliveryId!==null||run.delivery!==null){fail7("Hook run must pin its catalog, identify its effect and have no delivery.")}return run}__name(pinnedRun2,"pinnedRun");function parseHookRegistration(value){const body=closed6(value,REGISTRATION_KEYS);const registrationId=assertManagedSessionStableId(body.registrationId,"registrationId");const catalogId=assertManagedSessionStableId(body.catalogId,"catalogId");const catalogRevision=assertManagedSessionSequence(body.catalogRevision,"catalogRevision");const catalogRef=ref6(body.catalogRef,"catalogRef");const run=pinnedRun2(body.run,registrationId);if(catalogRevision<1||run.definition.definitionId!==catalogId||run.definition.definitionRevision!==catalogRevision||run.execution!==null){fail7("Hook registration must pin its catalog resource and have no execution.")}return Object.freeze({registrationId,catalogId,catalogRevision,catalogRef,run})}__name(parseHookRegistration,"parseHookRegistration");function parseHookExecution(value){const body=closed6(value,EXECUTION_KEYS);const hookExecutionId=assertManagedSessionStableId(body.hookExecutionId,"hookExecutionId");const run=pinnedRun2(body.run,hookExecutionId);if(run.execution===null)fail7("Hook execution must have an execution state.");if(typeof body.cancelRequested!=="boolean")fail7("Hook cancelRequested must be boolean.");const resultRef=body.resultRef===null?null:ref6(body.resultRef,"resultRef");if(run.state==="settled"&&resultRef===null||resultRef!==null&&run.execution!=="settled"){fail7("Hook result requires a settled execution; successful executions need a result.")}return Object.freeze({hookExecutionId,occurrenceId:assertManagedSessionStableId(body.occurrenceId,"occurrenceId"),runtimeSessionId:assertManagedSessionStableId(body.runtimeSessionId,"runtimeSessionId"),registrationId:assertManagedSessionStableId(body.registrationId,"registrationId"),eventName:assertManagedSessionStableId(body.eventName,"eventName"),ordinal:assertManagedSessionSequence(body.ordinal,"ordinal"),hookId:assertManagedSessionStableId(body.hookId,"hookId"),planRef:ref6(body.planRef,"planRef"),inputRef:ref6(body.inputRef,"inputRef"),resultRef,onceKey:body.onceKey===null?null:assertManagedSessionStableId(body.onceKey,"onceKey"),cancelRequested:body.cancelRequested,run})}__name(parseHookExecution,"parseHookExecution");function accepts4(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts4,"accepts");function same4(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same4,"same");function isHookRegistrationStart(value){return accepts4(()=>isExtensionRunStart(parseHookRegistration(value).run))}__name(isHookRegistrationStart,"isHookRegistrationStart");function isHookExecutionStart(value){return accepts4(()=>{const record4=parseHookExecution(value);return isExtensionRunStart(record4.run)&&record4.resultRef===null&&!record4.cancelRequested})}__name(isHookExecutionStart,"isHookExecutionStart");function isHookRegistrationSuccessor(previous,next){return accepts4(()=>{const before=parseHookRegistration(previous);const after=parseHookRegistration(next);return!["settled","failed","cancelled"].includes(before.run.state)&&REGISTRATION_KEYS.filter(key=>key!=="run").every(key=>same4(before[key],after[key]))&&isExtensionRunSuccessor(before.run,after.run)})}__name(isHookRegistrationSuccessor,"isHookRegistrationSuccessor");function isHookExecutionSuccessor(previous,next){return accepts4(()=>{const before=parseHookExecution(previous);const after=parseHookExecution(next);return EXECUTION_KEYS.filter(key=>key!=="run"&&key!=="resultRef"&&key!=="cancelRequested").every(key=>same4(before[key],after[key]))&&isExtensionRunSuccessor(before.run,after.run)&&(!before.cancelRequested||after.cancelRequested)&&(before.resultRef===null||same4(before.resultRef,after.resultRef))&&(!["settled","failed","cancelled"].includes(before.run.state)||same4(before,after))})}__name(isHookExecutionSuccessor,"isHookExecutionSuccessor");init_esbuild_shims();var SCHEDULE_KIND="schedule";var AUTOMATION_RUN_KIND="automation_run";var SCHEDULE_OVERLAP_POLICIES=Object.freeze(["skip","queue_one","allow"]);var SCHEDULE_CATCH_UP_POLICIES=Object.freeze(["none","latest","bounded"]);var SCHEDULE_SESSION_MODES=Object.freeze(["persistent","per_run"]);var SCHEDULE_KEYS=["catchUp","catchUpLimit","cron","definitionDigest","definitionRevision","enabled","gate","goal","kind","overlap","ownerScopeId","promptRef","run","scheduleId","sessionMode","targetSessionId","timezone"];var SCHEDULE_FIXED_KEYS=["kind","ownerScopeId","scheduleId"];var AUTOMATION_RUN_KEYS=["automationRunId","definitionRevision","gateOutputRef","kind","occurrenceKey","run","scheduleId","sessionMode","targetSessionId"];var AUTOMATION_RUN_FIXED_KEYS=["automationRunId","definitionRevision","gateOutputRef","kind","occurrenceKey","scheduleId","sessionMode","targetSessionId"];var SCHEDULE_GATE_MAX_BYTES=2048;var TERMINAL_RUN_STATES4=["settled","failed","cancelled"];var CRON_BOUNDS=[{name:"minute",min:0,max:59},{name:"hour",min:0,max:23},{name:"day-of-month",min:1,max:31},{name:"month",min:1,max:12},{name:"day-of-week",min:0,max:7}];var CRON_PART=/^[0-9*,/-]{1,64}$/;var CRON_DIGITS=/^[0-9]{1,10}$/;var TIMEZONE=/^[A-Za-z][A-Za-z0-9_+-]{0,63}(\/[A-Za-z0-9_+-]{1,64}){0,2}$/;var SLOT=/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$/;var MAX_COUNT=9007199254740990;function fail8(message){throw new ManagedSessionRecordError(message)}__name(fail8,"fail");function closed7(label,value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key)))fail8(`${label} must have exactly the keys ${keys2.join(", ")}.`);return{...value}}__name(closed7,"closed");function id4(value,label){return assertManagedSessionStableId(value,label)}__name(id4,"id");function text2(value,label){return boundedString(value,label,MANAGED_SESSION_LIMITS.maxTextBytes)}__name(text2,"text");function gate(value){return boundedString(value,"gate",SCHEDULE_GATE_MAX_BYTES)}__name(gate,"gate");function count2(value,label,min){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<min||value>MAX_COUNT){fail8(`${label} must be an integer from ${min} to ${MAX_COUNT}.`)}return value}__name(count2,"count");function boolean2(value,label){if(typeof value!=="boolean"){fail8(`${label} must be boolean.`)}return value}__name(boolean2,"boolean");function ref7(value,label){return Object.freeze(assertManagedSessionDurableRef(value,label))}__name(ref7,"ref");function nullable3(value,parse15){return value===null?null:parse15(value)}__name(nullable3,"nullable");function oneOf3(value,allowed,label){if(typeof value!=="string"||!allowed.includes(value)){fail8(`${label} must be one of: ${allowed.join(", ")}.`)}return value}__name(oneOf3,"oneOf");function accepts5(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts5,"accepts");function same5(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same5,"same");function cronField(field,name2,min,max){for(const atom of field.split(",")){const[base2,stepText,...rest]=atom.split("/");if(rest.length>0||base2===void 0||base2===""||!CRON_PART.test(atom)){fail8(`cron ${name2} field must use digit, range, list or step atoms.`)}if(stepText!==void 0){if(!CRON_DIGITS.test(stepText)){fail8(`cron ${name2} field must use digit, range, list or step atoms.`)}const step=Number(stepText);if(step<1||step>max){fail8(`cron ${name2} field steps must stay within 1-${max}.`)}}if(base2==="*"){continue}const range=base2.split("-");if(range.length>2||range.some(end=>!CRON_DIGITS.test(end))){fail8(`cron ${name2} field must use digit, range, list or step atoms.`)}const[from,to2]=range.map(Number);if(from===void 0||from<min||from>max){fail8(`cron ${name2} field values must stay within ${min}-${max}.`)}if(to2!==void 0){if(to2<min||to2>max){fail8(`cron ${name2} field values must stay within ${min}-${max}.`)}if(from>=to2){fail8(`cron ${name2} field ranges must not wrap.`)}}}}__name(cronField,"cronField");function cron(value){const expression=text2(value,"cron");const fields=expression.split(" ");if(expression!==fields.join(" ")||fields.length!==5){fail8("cron must have exactly five fields.")}CRON_BOUNDS.forEach(({name:name2,min,max},index)=>cronField(fields[index],name2,min,max));return expression}__name(cron,"cron");function timezone(value){const name2=text2(value,"timezone");if(!TIMEZONE.test(name2)){fail8("timezone must have the IANA timezone name form.")}return name2}__name(timezone,"timezone");function logicalRun(value,label){const run=parseExtensionRun(value,`${label}.run`);if(run.executionCallId!==null||run.effectId!==null||run.dispatchId!==null||run.deliveryId!==null||run.definition!==null||run.execution!==null||run.runtime!==null||run.delivery!==null){fail8(`${label} run must stay a purely logical lifecycle.`)}return run}__name(logicalRun,"logicalRun");function targetSession(sessionMode,targetSessionId,label){if(sessionMode==="persistent"!==(targetSessionId!==null)){fail8(`${label} targetSessionId is frozen exactly for the persistent target mode.`)}}__name(targetSession,"targetSession");function parseScheduleRecord(value){const body=closed7("Schedule",value,SCHEDULE_KEYS);if(body.kind!==SCHEDULE_KIND){fail8(`Schedule kind must be 'schedule' in schema version 1.`)}const run=logicalRun(body.run,"Schedule");const sessionMode=oneOf3(body.sessionMode,SCHEDULE_SESSION_MODES,"sessionMode");const targetSessionId=nullable3(body.targetSessionId,each=>id4(each,"targetSessionId"));targetSession(sessionMode,targetSessionId,"Schedule");const catchUp=oneOf3(body.catchUp,SCHEDULE_CATCH_UP_POLICIES,"catchUp");const catchUpLimit=nullable3(body.catchUpLimit,each=>count2(each,"catchUpLimit",1));if(catchUp==="bounded"!==(catchUpLimit!==null)){fail8("Schedule catchUpLimit is set exactly for bounded catch-up.")}return Object.freeze({kind:SCHEDULE_KIND,scheduleId:id4(body.scheduleId,"scheduleId"),ownerScopeId:id4(body.ownerScopeId,"ownerScopeId"),goal:text2(body.goal,"goal"),cron:cron(body.cron),timezone:timezone(body.timezone),definitionRevision:count2(body.definitionRevision,"definitionRevision",1),definitionDigest:assertManagedSessionDigest(body.definitionDigest,"definitionDigest"),promptRef:ref7(body.promptRef,"promptRef"),sessionMode,targetSessionId,overlap:oneOf3(body.overlap,SCHEDULE_OVERLAP_POLICIES,"overlap"),catchUp,catchUpLimit,enabled:boolean2(body.enabled,"enabled"),gate:nullable3(body.gate,gate),run})}__name(parseScheduleRecord,"parseScheduleRecord");function isScheduleStart(value){return accepts5(()=>{const record4=parseScheduleRecord(value);return isExtensionRunStart(record4.run)})}__name(isScheduleStart,"isScheduleStart");function isScheduleSuccessor(previous,next){return accepts5(()=>{const before=parseScheduleRecord(previous);const after=parseScheduleRecord(next);if(SCHEDULE_FIXED_KEYS.some(key=>!same5(before[key],after[key]))||!isExtensionRunSuccessor(before.run,after.run)||after.definitionRevision!==before.definitionRevision+1){return false}if(TERMINAL_RUN_STATES4.includes(before.run.state)){return same5({...before,run:null},{...after,run:null})}return true})}__name(isScheduleSuccessor,"isScheduleSuccessor");function occurrenceKey(value){const key=text2(value,"occurrenceKey");const separator=key.indexOf(":");const kind=separator<0?"":key.slice(0,separator);const valuePart=separator<0?"":key.slice(separator+1);if(kind==="schedule"){const parsed=Number.isNaN(Date.parse(valuePart))?null:new Date(valuePart);if(!SLOT.test(valuePart)||parsed===null||parsed.toISOString()!==`${valuePart.slice(0,19)}.000Z`){fail8("AutomationRun occurrenceKey slot must be a canonical UTC instant to the second.")}return key}if(kind==="manual"){id4(valuePart,"occurrenceKey commandId");return key}if(kind==="webhook"){fail8("AutomationRun webhook occurrences are reserved until their slice lands.")}fail8("AutomationRun occurrenceKey must be schedule:<slot> or manual:<commandId>.")}__name(occurrenceKey,"occurrenceKey");function parseAutomationRunRecord(value){const body=closed7("AutomationRun",value,AUTOMATION_RUN_KEYS);if(body.kind!==AUTOMATION_RUN_KIND){fail8(`AutomationRun kind must be 'automation_run' in schema version 1.`)}const run=parseExtensionRun(body.run,"AutomationRun.run");if(run.executionCallId!==null||run.dispatchId===null||run.definition!==null){fail8("AutomationRun run must name its dispatch, no call and no definition.")}if(run.delivery!==null&&run.delivery.state!=="planned"&&!TERMINAL_RUN_STATES4.includes(run.state)){fail8("AutomationRun delivery moves past its plan only once the run ended.")}const sessionMode=oneOf3(body.sessionMode,SCHEDULE_SESSION_MODES,"sessionMode");const targetSessionId=nullable3(body.targetSessionId,each=>id4(each,"targetSessionId"));targetSession(sessionMode,targetSessionId,"AutomationRun");return Object.freeze({kind:AUTOMATION_RUN_KIND,automationRunId:id4(body.automationRunId,"automationRunId"),scheduleId:id4(body.scheduleId,"scheduleId"),definitionRevision:count2(body.definitionRevision,"definitionRevision",1),occurrenceKey:occurrenceKey(body.occurrenceKey),sessionMode,targetSessionId,gateOutputRef:nullable3(body.gateOutputRef,each=>ref7(each,"gateOutputRef")),run})}__name(parseAutomationRunRecord,"parseAutomationRunRecord");function isAutomationRunStart(value){return accepts5(()=>{const record4=parseAutomationRunRecord(value);return isExtensionRunStart(record4.run)})}__name(isAutomationRunStart,"isAutomationRunStart");function isAutomationRunSuccessor(previous,next){return accepts5(()=>{const before=parseAutomationRunRecord(previous);const after=parseAutomationRunRecord(next);return AUTOMATION_RUN_FIXED_KEYS.every(key=>same5(before[key],after[key]))&&isExtensionRunSuccessor(before.run,after.run)})}__name(isAutomationRunSuccessor,"isAutomationRunSuccessor");init_esbuild_shims();var BODY_KEYS=["childRunId","contentDigest","contentRef","parentExecutionCallId","parentScopeId","resultVersion","run","terminalReceiptRef"];var FIXED_KEYS=["childRunId","contentDigest","contentRef","parentExecutionCallId","parentScopeId","resultVersion","terminalReceiptRef"];function fail9(message){throw new ManagedSessionRecordError(message)}__name(fail9,"fail");function closed8(value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key)))fail9(`Child acceptance must have exactly the keys ${keys2.join(", ")}.`);return{...value}}__name(closed8,"closed");function id5(value,label){return assertManagedSessionStableId(value,label)}__name(id5,"id");function ref8(value,label){return Object.freeze(assertManagedSessionDurableRef(value,label))}__name(ref8,"ref");function accepts6(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts6,"accepts");function same6(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same6,"same");function parseChildAcceptance(value){const body=closed8(value,BODY_KEYS);const run=parseExtensionRun(body.run);if(run.executionCallId!==null||run.effectId!==null||run.dispatchId!==null||run.deliveryId!==null||run.runtime!==null||run.execution!==null||run.definition!==null){fail9("Child acceptance run must be purely logical.")}if(run.state!=="settled"){fail9("Child acceptance run must be settled.")}const delivery=run.delivery;if(delivery===null||delivery.target!=="session"||delivery.state!=="accepted"&&delivery.state!=="consumed"){fail9("Child acceptance delivery must be accepted or consumed.")}const contentRef=ref8(body.contentRef,"contentRef");const contentDigest=assertManagedSessionDigest(body.contentDigest,"contentDigest");if(contentDigest!==contentRef.digest){fail9("Child acceptance contentDigest must name the content's digest.")}const terminalReceiptRef=ref8(body.terminalReceiptRef,"terminalReceiptRef");const resultVersion=body.resultVersion;if(resultVersion!==1){fail9("Child acceptance resultVersion must be 1 in schema version 1.")}return Object.freeze({childRunId:id5(body.childRunId,"childRunId"),parentScopeId:id5(body.parentScopeId,"parentScopeId"),parentExecutionCallId:body.parentExecutionCallId===null?null:id5(body.parentExecutionCallId,"parentExecutionCallId"),resultVersion,contentRef,contentDigest,terminalReceiptRef,run})}__name(parseChildAcceptance,"parseChildAcceptance");function isChildAcceptanceStart(value){return accepts6(()=>parseChildAcceptance(value).run.delivery?.state==="accepted")}__name(isChildAcceptanceStart,"isChildAcceptanceStart");function isChildAcceptanceSuccessor(previous,next){return accepts6(()=>{const before=parseChildAcceptance(previous);const after=parseChildAcceptance(next);if(FIXED_KEYS.some(key=>!same6(before[key],after[key])))return false;if(!isExtensionRunSuccessor(before.run,after.run))return false;if(before.run.delivery?.state!=="accepted")return false;return after.run.delivery?.state==="consumed"||same6(before.run,after.run)})}__name(isChildAcceptanceSuccessor,"isChildAcceptanceSuccessor");init_esbuild_shims();var MANAGED_SESSION_MESSAGE_LIMITS=Object.freeze({maxContentBytes:64*1024});var BODY_KEYS2=["childRunId","contentDigest","contentRef","direction","inputId","messageId","route","run","senderSessionId","targetSessionId"];var FIXED_KEYS2=["childRunId","contentDigest","contentRef","direction","messageId","route","senderSessionId"];function fail10(message){throw new ManagedSessionRecordError(message)}__name(fail10,"fail");function closed9(value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key)))fail10(`Session message must have exactly the keys ${keys2.join(", ")}.`);return{...value}}__name(closed9,"closed");function nullableId(value,label){return value===null?null:assertManagedSessionStableId(value,label)}__name(nullableId,"nullableId");function accepts7(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts7,"accepts");function same7(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same7,"same");function parseSessionMessage(value){const body=closed9(value,BODY_KEYS2);const run=parseExtensionRun(body.run);const direction=body.direction;if(direction!=="outbound"&&direction!=="inbound"){fail10("Session message direction must be outbound or inbound.")}const route=body.route;if(route!=="to_child"&&route!=="to_parent"){fail10("Session message route must be to_child or to_parent.")}if(run.definition!==null||run.effectId!==null||run.dispatchId!==null||run.deliveryId!==null||run.execution!==null||run.runtime!==null){fail10("Session message run must be purely logical.")}if(run.state!=="settled"){fail10("Session message run must be settled.")}const delivery=run.delivery;if(delivery===null){fail10("Session message delivery must be a session delivery.")}const messageId=assertManagedSessionStableId(body.messageId,"messageId");const childRunId=assertManagedSessionStableId(body.childRunId,"childRunId");const senderSessionId=assertManagedSessionStableId(body.senderSessionId,"senderSessionId");const targetSessionId=nullableId(body.targetSessionId,"targetSessionId");const inputId=nullableId(body.inputId,"inputId");const contentRef=Object.freeze(assertManagedSessionDurableRef(body.contentRef,"contentRef"));if(contentRef.byteLength>MANAGED_SESSION_MESSAGE_LIMITS.maxContentBytes){fail10(`Session message content exceeds ${MANAGED_SESSION_MESSAGE_LIMITS.maxContentBytes} bytes.`)}const contentDigest=assertManagedSessionDigest(body.contentDigest,"contentDigest");if(contentDigest!==contentRef.digest){fail10("Session message contentDigest must name the content's digest.")}if(targetSessionId===senderSessionId){fail10("Session message cannot address its own sender.")}if(direction==="outbound"){if(run.executionCallId===null){fail10("Outbound session message run must name its sending call.")}if(targetSessionId===null&&delivery.state!=="planned"&&delivery.state!=="cancelled"){fail10("Outbound session message must fix its target once its delivery is claimed.")}if(inputId!==null!==(delivery.state==="accepted"||delivery.state==="consumed")){fail10("Outbound session message names its target's input exactly once accepted.")}}else{if(run.executionCallId!==null){fail10("Inbound session message run must name no call.")}if(delivery.state!=="accepted"&&delivery.state!=="consumed"){fail10("Inbound session message delivery must be accepted or consumed.")}if(targetSessionId===null||inputId===null){fail10("Inbound session message must name its target and its input.")}}return Object.freeze({direction,messageId,route,childRunId,senderSessionId,targetSessionId,contentRef,contentDigest,inputId,run})}__name(parseSessionMessage,"parseSessionMessage");function isSessionMessageStart(value){return accepts7(()=>{const message=parseSessionMessage(value);return message.run.delivery?.state===(message.direction==="outbound"?"planned":"accepted")})}__name(isSessionMessageStart,"isSessionMessageStart");function isSessionMessageSuccessor(previous,next){return accepts7(()=>{const before=parseSessionMessage(previous);const after=parseSessionMessage(next);if(FIXED_KEYS2.some(key=>!same7(before[key],after[key])))return false;if(before.targetSessionId!==null&&before.targetSessionId!==after.targetSessionId||before.inputId!==null&&before.inputId!==after.inputId){return false}if(!isExtensionRunSuccessor(before.run,after.run))return false;if(before.direction==="outbound")return true;if(before.run.delivery?.state!=="accepted")return false;return after.run.delivery?.state==="consumed"||same7(before.run,after.run)})}__name(isSessionMessageSuccessor,"isSessionMessageSuccessor");init_esbuild_shims();var MANAGED_SESSION_COMMAND_LIMITS=Object.freeze({maxArgsBytes:64*1024,maxReplyBytes:64*1024});var BODY_KEYS3=["argsDigest","argsRef","childRunId","commandId","direction","kind","replyDigest","replyRef","route","run","senderSessionId","targetSessionId"];var FIXED_KEYS3=["argsDigest","argsRef","childRunId","commandId","direction","kind","route","senderSessionId"];function fail11(message){throw new ManagedSessionRecordError(message)}__name(fail11,"fail");function closed10(value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key)))fail11(`Session command must have exactly the keys ${keys2.join(", ")}.`);return{...value}}__name(closed10,"closed");function nullableId2(value,label){return value===null?null:assertManagedSessionStableId(value,label)}__name(nullableId2,"nullableId");function accepts8(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts8,"accepts");function same8(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same8,"same");function parseSessionCommand(value){const body=closed10(value,BODY_KEYS3);const run=parseExtensionRun(body.run);const direction=body.direction;if(direction!=="outbound"&&direction!=="inbound"){fail11("Session command direction must be outbound or inbound.")}const route=body.route;if(route!=="to_parent"){fail11("Session command route must be to_parent.")}const kind=body.kind;if(kind!=="board_read"&&kind!=="board_write"&&kind!=="member_message"&&kind!=="plan_submit"){fail11("Session command kind must be one of board_read, board_write, member_message, plan_submit.")}if(run.definition!==null||run.effectId!==null||run.dispatchId!==null||run.deliveryId!==null||run.execution!==null||run.runtime!==null){fail11("Session command run must be purely logical.")}if(run.state!=="settled"){fail11("Session command run must be settled.")}const delivery=run.delivery;if(delivery===null){fail11("Session command delivery must be a session delivery.")}const commandId=assertManagedSessionStableId(body.commandId,"commandId");const childRunId=assertManagedSessionStableId(body.childRunId,"childRunId");const senderSessionId=assertManagedSessionStableId(body.senderSessionId,"senderSessionId");const targetSessionId=nullableId2(body.targetSessionId,"targetSessionId");const argsRef=Object.freeze(assertManagedSessionDurableRef(body.argsRef,"argsRef"));if(argsRef.byteLength>MANAGED_SESSION_COMMAND_LIMITS.maxArgsBytes){fail11(`Session command arguments exceed ${MANAGED_SESSION_COMMAND_LIMITS.maxArgsBytes} bytes.`)}const argsDigest=assertManagedSessionDigest(body.argsDigest,"argsDigest");if(argsDigest!==argsRef.digest){fail11("Session command argsDigest must name the arguments' digest.")}const replyRef=body.replyRef===null?null:Object.freeze(assertManagedSessionDurableRef(body.replyRef,"replyRef"));const replyDigest=body.replyDigest===null?null:assertManagedSessionDigest(body.replyDigest,"replyDigest");if(replyRef===null!==(replyDigest===null)){fail11("Session command names its reply as a pair, or not at all.")}if(replyRef!==null){if(replyRef.byteLength>MANAGED_SESSION_COMMAND_LIMITS.maxReplyBytes){fail11(`Session command reply exceeds ${MANAGED_SESSION_COMMAND_LIMITS.maxReplyBytes} bytes.`)}if(replyDigest!==replyRef.digest){fail11("Session command replyDigest must name the reply's digest.")}}if(targetSessionId!==null&&targetSessionId===senderSessionId){fail11("Session command cannot address its own sender.")}if(direction==="outbound"){if(run.executionCallId===null){fail11("Outbound session command run must name its commanding call.")}if(targetSessionId===null&&delivery.state!=="planned"&&delivery.state!=="cancelled"){fail11("Outbound session command must fix its target once its delivery is claimed.")}if(replyRef!==null!==(delivery.state==="accepted"||delivery.state==="consumed")){fail11("Outbound session command names its reply exactly once accepted.")}}else{if(kind==="board_read"){fail11("Inbound session command is never a board read; reads commit nothing.")}if(run.executionCallId!==null){fail11("Inbound session command run must name no call.")}if(delivery.state!=="consumed"){fail11("Inbound session command opens consumed with its reply.")}if(targetSessionId===null){fail11("Inbound session command must name its target.")}if(replyRef===null){fail11("Inbound session command opens with its reply.")}}return Object.freeze({direction,commandId,route,kind,childRunId,senderSessionId,targetSessionId,argsRef,argsDigest,replyRef,replyDigest,run})}__name(parseSessionCommand,"parseSessionCommand");function isSessionCommandStart(value){return accepts8(()=>{const command=parseSessionCommand(value);return command.run.delivery?.state===(command.direction==="outbound"?"planned":"consumed")})}__name(isSessionCommandStart,"isSessionCommandStart");function isSessionCommandSuccessor(previous,next){return accepts8(()=>{const before=parseSessionCommand(previous);const after=parseSessionCommand(next);if(FIXED_KEYS3.some(key=>!same8(before[key],after[key])))return false;if(before.targetSessionId!==null&&before.targetSessionId!==after.targetSessionId||before.replyRef!==null&&!same8(before.replyRef,after.replyRef)||before.replyDigest!==null&&before.replyDigest!==after.replyDigest){return false}if(!isExtensionRunSuccessor(before.run,after.run))return false;if(before.direction==="outbound")return true;return same8(before.run,after.run)})}__name(isSessionCommandSuccessor,"isSessionCommandSuccessor");init_esbuild_shims();var MANAGED_TEAM_LIMITS=Object.freeze({maxMembers:10,maxNameLength:64,maxBlockers:64,maxContentBytes:64*1024,maxMetadataBytes:32*1024});var MANAGED_TEAM_LEADER="leader";var STATE_KEYS=["lifecycle","leadSessionId","members","membershipRevision","name","run","teamId"];var MEMBER_KEYS=["childRunId","name","planModeRequired"];var TASK_KEYS=["activeForm","blockedBy","descriptionRef","metadataRef","number","owner","run","status","subject","taskId","teamId"];var MESSAGE_KEYS=["contentDigest","contentRef","from","inputId","kind","messageId","run","targetSessionId","teamId","to"];var PLAN_KEYS=["decision","feedbackRef","member","planRef","planRevision","requestId","run","teamId"];var STATE_FIXED_KEYS=["leadSessionId","name","teamId"];var TASK_FIXED_KEYS=["number","taskId","teamId"];var MESSAGE_FIXED_KEYS=["contentDigest","contentRef","from","kind","messageId","teamId","to"];var PLAN_FIXED_KEYS=["member","planRef","planRevision","requestId","teamId"];var LIFECYCLES=["active","closing","deleted"];var TASK_STATUSES=["pending","in_progress","completed","deleted"];var TO_LEADER=["plan_approval_request","shutdown_approved","shutdown_rejected"];var FROM_LEADER=["plan_approval_response","shutdown_request"];var MESSAGE_KINDS=["message","task_assignment",...TO_LEADER,...FROM_LEADER];var NAME=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;var MAX_COUNT2=9007199254740990;function fail12(message){throw new ManagedSessionRecordError(message)}__name(fail12,"fail");function closed11(label,value,keys2){if(typeof value!=="object"||value===null||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Object.keys(value).length!==keys2.length||Object.keys(value).some(key=>!keys2.includes(key)))fail12(`${label} must have exactly the keys ${keys2.join(", ")}.`);return{...value}}__name(closed11,"closed");function oneOf4(value,allowed,message){if(typeof value!=="string"||!allowed.includes(value))fail12(message);return value}__name(oneOf4,"oneOf");function count3(value,label,min,max=MAX_COUNT2){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<min||value>max){fail12(`${label} must be an integer from ${min} to ${max}.`)}return value}__name(count3,"count");function bool(value,label){if(typeof value!=="boolean")fail12(`${label} must be boolean.`);return value}__name(bool,"bool");function name(value,label){if(typeof value!=="string"||value.length>MANAGED_TEAM_LIMITS.maxNameLength||!NAME.test(value)){fail12(`${label} must be dash-separated lowercase letters and digits, at most ${MANAGED_TEAM_LIMITS.maxNameLength} characters.`)}return value}__name(name,"name");function ref9(value,label,maxBytes){const parsed=Object.freeze(assertManagedSessionDurableRef(value,label));if(parsed.byteLength>maxBytes)fail12(`${label} exceeds ${maxBytes} bytes.`);return parsed}__name(ref9,"ref");function nullable4(value,parse15){return value===null?null:parse15(value)}__name(nullable4,"nullable");function logicalRun2(value,label,states){const run=parseExtensionRun(value);if(run.definition!==null||run.executionCallId!==null||run.effectId!==null||run.dispatchId!==null||run.deliveryId!==null||run.execution!==null||run.runtime!==null||run.delivery!==null){fail12(`${label} run must be purely logical.`)}if(!states.includes(run.state)){fail12(`${label} run must be ${states.join(" or ")}.`)}return run}__name(logicalRun2,"logicalRun");function accepts9(check){try{return check()}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(accepts9,"accepts");function same9(left,right){return JSON.stringify(left)===JSON.stringify(right)}__name(same9,"same");function fixed(before,after,keys2){return keys2.every(key=>same9(before[key],after[key]))}__name(fixed,"fixed");function prefix(before,after){return before.every((each,index)=>same9(each,after[index]))}__name(prefix,"prefix");function parseMember(value){const member=closed11("Team member",value,MEMBER_KEYS);const memberName=name(member.name,"Team member name");if(memberName===MANAGED_TEAM_LEADER){fail12("Team member cannot be named leader.")}return Object.freeze({name:memberName,childRunId:assertManagedSessionStableId(member.childRunId,"members.childRunId"),planModeRequired:bool(member.planModeRequired,"members.planModeRequired")})}__name(parseMember,"parseMember");function parseTeamState(value){const body=closed11("Team state",value,STATE_KEYS);const lifecycle=oneOf4(body.lifecycle,LIFECYCLES,"Team lifecycle must be active, closing or deleted.");const run=logicalRun2(body.run,"Team",["admitted","cancelled"]);if(lifecycle==="deleted"!==(run.state==="cancelled")){fail12("Team run must be cancelled exactly once the team is deleted.")}if(!Array.isArray(body.members))fail12("Team members must be an array.");if(body.members.length>MANAGED_TEAM_LIMITS.maxMembers){fail12(`Team members exceed ${MANAGED_TEAM_LIMITS.maxMembers} entries.`)}const members=Object.freeze(body.members.map(parseMember));if(new Set(members.map(member=>member.name)).size!==members.length||new Set(members.map(member=>member.childRunId)).size!==members.length){fail12("Team members must have distinct names and child runs.")}const membershipRevision=count3(body.membershipRevision,"membershipRevision",1);if(membershipRevision!==members.length+1){fail12("Team membershipRevision must be one more than its member count.")}return Object.freeze({teamId:assertManagedSessionStableId(body.teamId,"teamId"),name:name(body.name,"Team name"),leadSessionId:assertManagedSessionStableId(body.leadSessionId,"leadSessionId"),lifecycle,membershipRevision,members,run})}__name(parseTeamState,"parseTeamState");function isTeamStateStart(value){return accepts9(()=>{const team=parseTeamState(value);return team.lifecycle==="active"&&team.members.length===0})}__name(isTeamStateStart,"isTeamStateStart");function isTeamStateSuccessor(previous,next){return accepts9(()=>{const before=parseTeamState(previous);const after=parseTeamState(next);if(!fixed(before,after,STATE_FIXED_KEYS)||!isExtensionRunSuccessor(before.run,after.run)){return false}const step=LIFECYCLES.indexOf(after.lifecycle);const from=LIFECYCLES.indexOf(before.lifecycle);if(step!==from&&step!==from+1)return false;if(!prefix(before.members,after.members))return false;const joined=after.members.length-before.members.length;return joined===0||joined===1&&before.lifecycle==="active"&&after.lifecycle==="active"})}__name(isTeamStateSuccessor,"isTeamStateSuccessor");function parseTeamTask(value){const body=closed11("Team task",value,TASK_KEYS);const status=oneOf4(body.status,TASK_STATUSES,"Team task status must be pending, in_progress, completed or deleted.");const run=logicalRun2(body.run,"Team task",["admitted","cancelled"]);if(status==="deleted"!==(run.state==="cancelled")){fail12("Team task run must be cancelled exactly once the task is deleted.")}const taskId=assertManagedSessionStableId(body.taskId,"taskId");const owner=nullable4(body.owner,each=>name(each,"Team task owner"));if(status==="in_progress"&&owner===null){fail12("Team task in progress must have an owner.")}if(!Array.isArray(body.blockedBy)){fail12("Team task blockedBy must be an array.")}if(body.blockedBy.length>MANAGED_TEAM_LIMITS.maxBlockers){fail12(`Team task blockedBy exceeds ${MANAGED_TEAM_LIMITS.maxBlockers} entries.`)}const blockedBy=Object.freeze(body.blockedBy.map(each=>assertManagedSessionStableId(each,"blockedBy")));if(new Set(blockedBy).size!==blockedBy.length||blockedBy.includes(taskId)){fail12("Team task blockedBy must name distinct other tasks.")}return Object.freeze({teamId:assertManagedSessionStableId(body.teamId,"teamId"),taskId,number:count3(body.number,"number",1),subject:boundedString(body.subject,"subject",MANAGED_SESSION_LIMITS.maxTextBytes),descriptionRef:ref9(body.descriptionRef,"descriptionRef",MANAGED_TEAM_LIMITS.maxContentBytes),activeForm:nullable4(body.activeForm,each=>boundedString(each,"activeForm",MANAGED_SESSION_LIMITS.maxTextBytes)),metadataRef:nullable4(body.metadataRef,each=>ref9(each,"metadataRef",MANAGED_TEAM_LIMITS.maxMetadataBytes)),owner,status,blockedBy,run})}__name(parseTeamTask,"parseTeamTask");function isTeamTaskStart(value){return accepts9(()=>parseTeamTask(value).status!=="deleted")}__name(isTeamTaskStart,"isTeamTaskStart");function isTeamTaskSuccessor(previous,next){return accepts9(()=>{const before=parseTeamTask(previous);const after=parseTeamTask(next);if(!fixed(before,after,TASK_FIXED_KEYS)||!isExtensionRunSuccessor(before.run,after.run)||!prefix(before.blockedBy,after.blockedBy)){return false}return before.status!=="deleted"||same9(before,after)})}__name(isTeamTaskSuccessor,"isTeamTaskSuccessor");function parseTeamMessage(value){const body=closed11("Team message",value,MESSAGE_KEYS);const kind=oneOf4(body.kind,MESSAGE_KINDS,`Team message kind must be one of ${MESSAGE_KINDS.join(", ")}.`);const from=name(body.from,"Team message from");const to2=name(body.to,"Team message to");if(from===to2)fail12("Team message cannot address its own sender.");if(TO_LEADER.includes(kind)&&(from===MANAGED_TEAM_LEADER||to2!==MANAGED_TEAM_LEADER)){fail12(`Team message of kind ${kind} must go from a member to the leader.`)}if(FROM_LEADER.includes(kind)&&(from!==MANAGED_TEAM_LEADER||to2===MANAGED_TEAM_LEADER)){fail12(`Team message of kind ${kind} must go from the leader to a member.`)}if(kind==="task_assignment"&&to2===MANAGED_TEAM_LEADER){fail12("Team message of kind task_assignment must go to a member.")}const run=parseExtensionRun(body.run);if(run.definition!==null||run.effectId!==null||run.dispatchId!==null||run.deliveryId!==null||run.execution!==null||run.runtime!==null){fail12("Team message run must be purely logical.")}if(run.state!=="settled")fail12("Team message run must be settled.");if(run.executionCallId===null){fail12("Team message run must name its sending call.")}const delivery=run.delivery;if(delivery===null){fail12("Team message delivery must be a session delivery.")}const contentRef=ref9(body.contentRef,"contentRef",MANAGED_TEAM_LIMITS.maxContentBytes);const contentDigest=assertManagedSessionDigest(body.contentDigest,"contentDigest");if(contentDigest!==contentRef.digest){fail12("Team message contentDigest must name the content's digest.")}const targetSessionId=nullable4(body.targetSessionId,each=>assertManagedSessionStableId(each,"targetSessionId"));const inputId=nullable4(body.inputId,each=>assertManagedSessionStableId(each,"inputId"));if(targetSessionId===null&&delivery.state!=="planned"&&delivery.state!=="cancelled"){fail12("Team message must fix its target once its delivery is claimed.")}if(inputId!==null!==(delivery.state==="accepted"||delivery.state==="consumed")){fail12("Team message names its target's input exactly once accepted.")}return Object.freeze({teamId:assertManagedSessionStableId(body.teamId,"teamId"),messageId:assertManagedSessionStableId(body.messageId,"messageId"),kind,from,to:to2,contentRef,contentDigest,targetSessionId,inputId,run})}__name(parseTeamMessage,"parseTeamMessage");function isTeamMessageStart(value){return accepts9(()=>parseTeamMessage(value).run.delivery?.state==="planned")}__name(isTeamMessageStart,"isTeamMessageStart");function isTeamMessageSuccessor(previous,next){return accepts9(()=>{const before=parseTeamMessage(previous);const after=parseTeamMessage(next);return fixed(before,after,MESSAGE_FIXED_KEYS)&&(before.targetSessionId===null||before.targetSessionId===after.targetSessionId)&&(before.inputId===null||before.inputId===after.inputId)&&isExtensionRunSuccessor(before.run,after.run)})}__name(isTeamMessageSuccessor,"isTeamMessageSuccessor");function parseTeamPlan(value){const body=closed11("Team plan",value,PLAN_KEYS);const run=logicalRun2(body.run,"Team plan",["waiting","settled","cancelled"]);const member=name(body.member,"Team plan member");if(member===MANAGED_TEAM_LEADER){fail12("Team plan member cannot be the leader.")}const decision=nullable4(body.decision,each=>oneOf4(each,["approved","rejected"],"Team plan decision must be approved or rejected."));if(decision!==null!==(run.state==="settled")){fail12("Team plan has a decision exactly once its run settled.")}const feedbackRef=nullable4(body.feedbackRef,each=>ref9(each,"feedbackRef",MANAGED_TEAM_LIMITS.maxContentBytes));if(feedbackRef!==null&&decision===null){fail12("Team plan feedback comes only with a decision.")}return Object.freeze({teamId:assertManagedSessionStableId(body.teamId,"teamId"),requestId:assertManagedSessionStableId(body.requestId,"requestId"),member,planRevision:count3(body.planRevision,"planRevision",1),planRef:ref9(body.planRef,"planRef",MANAGED_TEAM_LIMITS.maxContentBytes),decision,feedbackRef,run})}__name(parseTeamPlan,"parseTeamPlan");function isTeamPlanStart(value){return accepts9(()=>parseTeamPlan(value).run.state==="waiting")}__name(isTeamPlanStart,"isTeamPlanStart");function isTeamPlanSuccessor(previous,next){return accepts9(()=>{const before=parseTeamPlan(previous);const after=parseTeamPlan(next);return fixed(before,after,PLAN_FIXED_KEYS)&&isExtensionRunSuccessor(before.run,after.run)&&(before.run.state==="waiting"||same9(before,after))})}__name(isTeamPlanSuccessor,"isTeamPlanSuccessor");init_esbuild_shims();var KEYS=["schemaVersion","kind","operationId","expectedCompactionRevision","historyCutSequence","requestRef","phase","attempt","candidateRef","outcome","failureCode","compactionRevision","run"];function fail13(message){throw new ManagedSessionRecordError(`History maintenance ${message}`)}__name(fail13,"fail");function sequence(value,label){if(!Number.isSafeInteger(value)||value<0)fail13(`${label} must be a non-negative safe integer.`);return value}__name(sequence,"sequence");function parseHistoryMaintenance(value){if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length!==KEYS.length||Object.keys(value).some(key=>!KEYS.includes(key)))fail13(`must have exactly the keys ${KEYS.join(", ")}.`);const body=value;if(body["schemaVersion"]!==1||body["kind"]!=="context_compression")fail13("must be a schema version 1 context_compression.");const phase=body["phase"];if(!["admitted","generating","candidate","settled"].includes(String(phase)))fail13("has an invalid phase.");const outcome=body["outcome"];if(outcome!==null&&!["compressed","noop","failed"].includes(String(outcome)))fail13("has an invalid outcome.");const run=parseExtensionRun(body["run"]);if(run.definition!==null||run.executionCallId!==null||run.effectId!==null||run.dispatchId!==null||run.deliveryId!==null||run.execution!==null||run.runtime!==null||run.delivery!==null)fail13("run must be purely logical.");const candidateRef=body["candidateRef"]===null?null:Object.freeze(assertManagedSessionDurableRef(body["candidateRef"],"candidateRef"));const compactionRevision=body["compactionRevision"]===null?null:sequence(body["compactionRevision"],"compactionRevision");const failureCode=body["failureCode"]===null?null:assertManagedSessionStableId(body["failureCode"],"failureCode");const attempt2=sequence(body["attempt"],"attempt");const expectedCompactionRevision=sequence(body["expectedCompactionRevision"],"expectedCompactionRevision");const historyCutSequence=sequence(body["historyCutSequence"],"historyCutSequence");if(historyCutSequence<expectedCompactionRevision)fail13("history cut must not precede its compaction revision.");if(phase==="admitted"&&(attempt2!==0||candidateRef!==null||run.state!=="admitted"))fail13("admission must have no attempt or candidate.");if((phase==="generating"||phase==="candidate")&&(attempt2<1||!["running","recovery_blocked"].includes(run.state)))fail13("an active phase requires a running or blocked attempt.");if(phase==="generating"&&candidateRef!==null)fail13("generation must not already have a candidate.");if(phase==="candidate"&&candidateRef===null)fail13("candidate phase requires its durable candidate.");if(phase!=="settled"&&(outcome!==null||failureCode!==null||compactionRevision!==null))fail13("an active operation must not have an outcome.");if(phase==="settled"){if(outcome===null||run.state!==(outcome==="failed"?"failed":"settled"))fail13("a settled phase requires its terminal outcome.");if(outcome==="failed"!==(failureCode!==null))fail13("only a failed outcome carries a failure code.");if(outcome==="compressed"?candidateRef===null||compactionRevision===null||compactionRevision<=expectedCompactionRevision:compactionRevision!==null)fail13("only a compressed outcome carries its new compaction revision.")}return Object.freeze({schemaVersion:1,kind:"context_compression",operationId:assertManagedSessionStableId(body["operationId"],"operationId"),expectedCompactionRevision,historyCutSequence,requestRef:Object.freeze(assertManagedSessionDurableRef(body["requestRef"],"requestRef")),phase,attempt:attempt2,candidateRef,outcome,failureCode,compactionRevision,run})}__name(parseHistoryMaintenance,"parseHistoryMaintenance");function isHistoryMaintenanceStart(value){try{return parseHistoryMaintenance(value).phase==="admitted"}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(isHistoryMaintenanceStart,"isHistoryMaintenanceStart");function isHistoryMaintenanceSuccessor(previous,next){try{const before=parseHistoryMaintenance(previous);const after=parseHistoryMaintenance(next);if(before.phase==="settled"||!isExtensionRunSuccessor(before.run,after.run))return false;for(const key of["operationId","kind","schemaVersion","expectedCompactionRevision","historyCutSequence","requestRef"])if(JSON.stringify(before[key])!==JSON.stringify(after[key]))return false;if(before.candidateRef!==null&&JSON.stringify(before.candidateRef)!==JSON.stringify(after.candidateRef))return false;if(after.phase==="settled")return after.attempt===before.attempt&&(after.outcome!=="compressed"||before.phase==="candidate");if(before.phase==="admitted")return after.phase==="generating"&&after.attempt===1;if(before.phase==="candidate")return after.phase==="candidate"&&after.attempt===before.attempt;return after.phase==="candidate"?after.attempt===before.attempt:after.phase==="generating"&&(after.attempt===before.attempt||after.attempt===before.attempt+1)}catch(error3){if(error3 instanceof ManagedSessionRecordError)return false;throw error3}}__name(isHistoryMaintenanceSuccessor,"isHistoryMaintenanceSuccessor");function childRunTaskKind(record4){switch(record4.kind){case"shell":return"background_shell";case"child_agent":return"child_agent";case"workflow":return"workflow";default:{const exhaustive=record4;return exhaustive}}}__name(childRunTaskKind,"childRunTaskKind");var MANAGED_EXTENSION_RECORD_BODIES=Object.freeze({tool_stage:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseManagedToolStage(value);return{record:record4,recordId:record4.toolStageId,run:record4.run}},"parse"),isStart:isManagedToolStageStart,isSuccessor:isManagedToolStageSuccessor}),history_maintenance:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseHistoryMaintenance(value);return{record:record4,recordId:record4.operationId,run:record4.run}},"parse"),isStart:isHistoryMaintenanceStart,isSuccessor:isHistoryMaintenanceSuccessor}),mcp_configuration:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseMcpConfiguration(value);return{record:record4,recordId:record4.configurationId,run:record4.run}},"parse"),isStart:isMcpConfigurationStart,isSuccessor:isMcpConfigurationSuccessor}),mcp_operation:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseMcpOperation(value);return{record:record4,recordId:record4.operationId,run:record4.run}},"parse"),isStart:isMcpOperationStart,isSuccessor:isMcpOperationSuccessor}),hook_registration:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseHookRegistration(value);return{record:record4,recordId:record4.registrationId,run:record4.run}},"parse"),isStart:isHookRegistrationStart,isSuccessor:isHookRegistrationSuccessor}),hook_execution:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseHookExecution(value);return{record:record4,recordId:record4.hookExecutionId,run:record4.run}},"parse"),isStart:isHookExecutionStart,isSuccessor:isHookExecutionSuccessor}),monitor_run:Object.freeze({taskKindOf:__name(()=>"monitor","taskKindOf"),parse:__name(value=>{const monitor=parseMonitorRun(value);return{record:monitor,recordId:monitor.monitorId,run:monitor.run}},"parse"),isStart:isMonitorRunStart,isSuccessor:isMonitorRunSuccessor}),child_run:Object.freeze({taskKindOf:__name(record4=>childRunTaskKind(record4),"taskKindOf"),parse:__name(value=>{const record4=parseChildRun(value);return{record:record4,recordId:record4.kind==="shell"?record4.shellId:record4.childRunId,run:record4.run}},"parse"),isStart:isChildRunStart,isSuccessor:isChildRunSuccessor}),channel_route:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseChannelRoute(value);return{record:record4,recordId:record4.routeId,run:record4.run}},"parse"),isStart:isChannelRouteStart,isSuccessor:isChannelRouteSuccessor}),channel_delivery:Object.freeze({taskKindOf:__name(()=>"channel_delivery","taskKindOf"),parse:__name(value=>{const record4=parseChannelDelivery(value);return{record:record4,recordId:record4.deliveryId,run:record4.run}},"parse"),isStart:isChannelDeliveryStart,isSuccessor:isChannelDeliverySuccessor}),child_acceptance:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseChildAcceptance(value);return{record:record4,recordId:record4.childRunId,run:record4.run}},"parse"),isStart:isChildAcceptanceStart,isSuccessor:isChildAcceptanceSuccessor}),schedule:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseScheduleRecord(value);return{record:record4,recordId:record4.scheduleId,run:record4.run}},"parse"),isStart:isScheduleStart,isSuccessor:isScheduleSuccessor}),automation_run:Object.freeze({taskKindOf:__name(()=>"automation_run","taskKindOf"),parse:__name(value=>{const record4=parseAutomationRunRecord(value);return{record:record4,recordId:record4.automationRunId,run:record4.run}},"parse"),isStart:isAutomationRunStart,isSuccessor:isAutomationRunSuccessor}),session_message:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseSessionMessage(value);return{record:record4,recordId:record4.messageId,run:record4.run}},"parse"),isStart:isSessionMessageStart,isSuccessor:isSessionMessageSuccessor}),session_command:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseSessionCommand(value);return{record:record4,recordId:record4.commandId,run:record4.run}},"parse"),isStart:isSessionCommandStart,isSuccessor:isSessionCommandSuccessor}),team_state:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseTeamState(value);return{record:record4,recordId:record4.teamId,run:record4.run}},"parse"),isStart:isTeamStateStart,isSuccessor:isTeamStateSuccessor}),team_task:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseTeamTask(value);return{record:record4,recordId:record4.taskId,run:record4.run}},"parse"),isStart:isTeamTaskStart,isSuccessor:isTeamTaskSuccessor}),team_message:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseTeamMessage(value);return{record:record4,recordId:record4.messageId,run:record4.run}},"parse"),isStart:isTeamMessageStart,isSuccessor:isTeamMessageSuccessor}),team_plan:Object.freeze({taskKindOf:__name(()=>null,"taskKindOf"),parse:__name(value=>{const record4=parseTeamPlan(value);return{record:record4,recordId:record4.requestId,run:record4.run}},"parse"),isStart:isTeamPlanStart,isSuccessor:isTeamPlanSuccessor})});var envelopeBodyCollision=Object.keys(MANAGED_EXTENSION_RECORD_BODIES).filter(domain=>MANAGED_SESSION_ENVELOPE_DOMAINS.includes(domain));if(envelopeBodyCollision.length>0){throw new Error(`record bodies stay out of the envelope domains: ${envelopeBodyCollision.join(", ")}`)}function managedExtensionRecordKey(sessionId,domain,recordId){return createHash11("sha256").update(`${sessionId}\0${domain}\0${recordId}`,"utf8").digest("hex")}__name(managedExtensionRecordKey,"managedExtensionRecordKey");function managedTaskId(recordKey){return`task_${recordKey}`}__name(managedTaskId,"managedTaskId");function managedChildTaskId(sessionId,childRunId){return managedTaskId(managedExtensionRecordKey(sessionId,"child_run",childRunId))}__name(managedChildTaskId,"managedChildTaskId");var STARTED=["running","waiting","settled"];function taskState(run){switch(run.state){case"reserved":case"admitted":return"pending";case"running":case"waiting":return run.reason===null?run.state:"degraded";case"settled":return"completed";default:return run.state}}__name(taskState,"taskState");function runtimeState(run,stopRequested){if(isTerminalRunState(run.state)||run.execution===null)return null;if(run.runtime===null)return"unbound";if(run.execution==="running_attached"){return stopRequested?"draining":"ready"}if(run.reason==="runtime_lost")return"lost";if(run.execution==="intent"||run.execution==="dispatch_started"){return stopRequested?"draining":"provisioning"}return null}__name(runtimeState,"runtimeState");function projectManagedTask(previous,run,occurredAt,stopRequested=false){const createdAt=previous?.createdAt??occurredAt;const startedAt=previous?.startedAt??(STARTED.includes(run.state)?Math.max(occurredAt,createdAt):null);const settledAt=previous?.settledAt??(isTerminalRunState(run.state)?Math.max(occurredAt,startedAt??createdAt):null);return Object.freeze({state:taskState(run),runtimeState:runtimeState(run,stopRequested),definitionRevision:run.definition?.definitionRevision??null,createdAt,startedAt,settledAt})}__name(projectManagedTask,"projectManagedTask");init_esbuild_shims();import{createHash as createHash12}from"node:crypto";init_esbuild_shims();init_esbuild_shims();function executeRuntimeShell(runtime,command,cwd,onOutput,signal,usePty,config3={},options2={}){const policy=runtime.getShellExecutionSandbox?.();if(!policy){return ShellExecutionService.execute(command,cwd,onOutput,signal,usePty,config3,options2)}try{assertShellSandboxCwd(policy,runtime.getTargetDir());assertShellSandboxCwd(policy,cwd);const env=Object.fromEntries(Object.entries({...sanitizeChildEnv(process.env),QWEN_CODE:"1",TERM:"xterm-256color",...getShellPagerEnv(config3.pager,{includeGitPager:usePty,platform:"linux"}),...sessionIdContext.run(runtime.getSessionId(),getShellContextEnvVars),QWEN_CODE_SESSION_ID:runtime.getSessionId(),QWEN_CODE_PROJECT_DIR:runtime.storage.getProjectDir()}).filter(entry=>typeof entry[1]==="string"));return executeSandbox(policy,{executable:"/bin/bash",args:["-c",command],cwd,env},onOutput,signal,usePty,config3,options2)}catch(error3){return Promise.reject(error3)}}__name(executeRuntimeShell,"executeRuntimeShell");init_esbuild_shims();import{spawn}from"node:child_process";import os2 from"node:os";import path16 from"node:path";import{randomUUID as randomUUID7}from"node:crypto";init_esbuild_shims();import*as path14 from"node:path";init_esbuild_shims();init_esbuild_shims();import{randomUUID as randomUUID5}from"node:crypto";var TOOL_LIFECYCLE_DRAIN_MS=3e4;var logger=createDebugLogger("TOOL_LIFECYCLE");function createToolLifecycle(config3,callId,toolName,options2={}){const suppressed=isChatRecordingSuppressed();const subagentId=options2.subagentId??subagentIdentityContext.getStore()?.id;const base2={v:1,kind:"tool",sessionId:config3.getSessionId(),executionId:randomUUID5(),callId,toolName,...subagentId?{subagentId}:{}};const recorder=options2.persist===false?void 0:config3.getChatRecordingService();let startedAt;let monotonicStart;let ended=false;const publish=__name(event=>{if(suppressed)return void 0;if(options2.persist!==false){try{recorder?.recordUiTelemetryEvent({...event,"event.name":"tool_lifecycle"})}catch(error3){logger.warn("Failed to record tool lifecycle:",error3)}}return event},"publish");return{start(epoch=Date.now(),resolvedToolName){if(ended||startedAt!==void 0)return void 0;startedAt=epoch;monotonicStart=performance.now();if(resolvedToolName)base2.toolName=resolvedToolName;return publish({...base2,phase:"started",executionStatus:"running",startedAt})},finish(outcome,executionStatus,executionDurationMs){if(ended)return void 0;ended=true;const terminal={...base2,phase:"ended",outcome,endedAt:Math.max(startedAt??0,Date.now())};if(startedAt===void 0){return publish({...terminal,executionStatus:"not_started"})}return publish({...terminal,executionStatus:executionStatus==="not_started"?"error":executionStatus,startedAt,executionDurationMs:executionDurationMs??Math.max(0,Math.round(performance.now()-monotonicStart))})}}}__name(createToolLifecycle,"createToolLifecycle");import*as fs10 from"node:fs";import*as path13 from"node:path";import{randomUUID as randomUUID6}from"node:crypto";init_esbuild_shims();import{EventEmitter}from"events";var AgentEventEmitter=class{static{__name(this,"AgentEventEmitter")}ee=new EventEmitter;on(event,listener){this.ee.on(event,listener)}off(event,listener){this.ee.off(event,listener)}rawListeners(event){return this.ee.rawListeners(event)}emit(event,payload){this.ee.emit(event,payload)}};var debugLogger16=createDebugLogger("AGENT_TRANSCRIPT");var MAX_PENDING_STREAM_BYTES=64*1024;var MAX_PERSISTED_RECENT_ACTIVITIES=10;function sanitizeFilenameComponent(value){return value.replace(/[^a-zA-Z0-9_-]/g,"_")}__name(sanitizeFilenameComponent,"sanitizeFilenameComponent");function getSubagentsRootDir(projectDir){return path13.join(projectDir,"subagents")}__name(getSubagentsRootDir,"getSubagentsRootDir");function getSubagentSessionDir(projectDir,sessionId){return path13.join(getSubagentsRootDir(projectDir),sanitizeFilenameComponent(sessionId))}__name(getSubagentSessionDir,"getSubagentSessionDir");function getAgentJsonlPath(projectDir,sessionId,agentId){return path13.join(getSubagentSessionDir(projectDir,sessionId),`agent-${sanitizeFilenameComponent(agentId)}.jsonl`)}__name(getAgentJsonlPath,"getAgentJsonlPath");function getAgentMetaPath(projectDir,sessionId,agentId){return path13.join(getSubagentSessionDir(projectDir,sessionId),`agent-${sanitizeFilenameComponent(agentId)}.meta.json`)}__name(getAgentMetaPath,"getAgentMetaPath");var TRACE_WARNING_LIMIT=20;var MAX_AGENT_TRACE_NODES=2e3;var TRACE_READ_CONCURRENCY=8;async function readAgentTrace(projectDir,sessionId,rootAgentId){const dir=getSubagentSessionDir(projectDir,sessionId);const warnings=[];let discovered;try{discovered=(await fs10.promises.readdir(dir)).filter(name2=>name2.endsWith(".meta.json")).sort()}catch(error3){if(error3.code==="ENOENT"){return{nodes:[],rootAgentIds:[],warnings:[]}}throw error3}const fileNames=discovered.slice(0,MAX_AGENT_TRACE_NODES);if(discovered.length>MAX_AGENT_TRACE_NODES){warnings.push(`Trace contains more than ${MAX_AGENT_TRACE_NODES} metadata files; results were truncated`)}const metas=new Map;for(let offset2=0;offset2<fileNames.length;offset2+=TRACE_READ_CONCURRENCY){const batch=fileNames.slice(offset2,offset2+TRACE_READ_CONCURRENCY);await Promise.all(batch.map(async fileName=>{try{const parsed=JSON.parse(await fs10.promises.readFile(path13.join(dir,fileName),"utf8"));if(typeof parsed.agentId!=="string"||parsed.agentId.length===0||typeof parsed.agentType!=="string"||typeof parsed.description!=="string"||typeof parsed.createdAt!=="string"||!Number.isFinite(Date.parse(parsed.createdAt))||parsed.parentAgentId!==null&&typeof parsed.parentAgentId!=="string"||parsed.toolUseId!==void 0&&typeof parsed.toolUseId!=="string"||parsed.depth!==void 0&&!Number.isFinite(parsed.depth)||parsed.status!==void 0&&!["running","paused","completed","failed","cancelled"].includes(parsed.status)||parsed.lastUpdatedAt!==void 0&&(typeof parsed.lastUpdatedAt!=="string"||!Number.isFinite(Date.parse(parsed.lastUpdatedAt)))||parsed.lastError!==void 0&&typeof parsed.lastError!=="string"||parsed.parentSessionId!==sessionId||path13.basename(getAgentMetaPath(projectDir,sessionId,parsed.agentId))!==fileName){throw new Error("invalid agent metadata identity")}metas.set(parsed.agentId,parsed)}catch(error3){if(warnings.length<TRACE_WARNING_LIMIT){warnings.push(`${fileName}: ${error3 instanceof Error?error3.message:String(error3)}`)}}}))}const nodes=[...metas.values()].sort((left,right)=>left.createdAt.localeCompare(right.createdAt)||left.agentId.localeCompare(right.agentId)).map(meta4=>{let cursor=meta4;const lineage=[];const positions=new Map;let lineageState="complete";let cycleRoot;while(cursor.parentAgentId!==null){const previousPosition=positions.get(cursor.agentId);if(previousPosition!==void 0){lineageState="cycle";cycleRoot=[...lineage.slice(previousPosition)].sort()[0];break}positions.set(cursor.agentId,lineage.length);lineage.push(cursor.agentId);const parent=metas.get(cursor.parentAgentId);if(!parent){lineageState="orphaned";break}cursor=parent}const resolvedRoot=lineageState==="cycle"?cycleRoot??cursor.agentId:cursor.agentId;return{agentId:meta4.agentId,agentType:meta4.agentType,description:meta4.description,parentSessionId:meta4.parentSessionId,parentAgentId:meta4.parentAgentId,rootAgentId:resolvedRoot,...meta4.toolUseId?{toolUseId:meta4.toolUseId}:{},...meta4.depth!==void 0?{depth:meta4.depth}:{},...meta4.status?{status:meta4.status}:{},createdAt:meta4.createdAt,...meta4.lastUpdatedAt?{lastUpdatedAt:meta4.lastUpdatedAt}:{},...meta4.lastError?{lastError:meta4.lastError}:{},lineageState}});const filtered=rootAgentId?nodes.filter(node=>node.rootAgentId===rootAgentId):nodes;return{nodes:filtered,rootAgentIds:[...new Set(filtered.map(node=>node.rootAgentId))].sort(),warnings}}__name(readAgentTrace,"readAgentTrace");function normalizeResumedAgentDepth(value){if(value==null)return void 0;return Number.isInteger(value)&&value>=0&&value<=MAX_SUBAGENT_DEPTH_LIMIT?value:MAX_SUBAGENT_DEPTH_LIMIT}__name(normalizeResumedAgentDepth,"normalizeResumedAgentDepth");function writeAgentMeta(metaPath,meta4){const tempPath=`${metaPath}.${process.pid}.${randomUUID6()}.tmp`;try{fs10.mkdirSync(path13.dirname(metaPath),{recursive:true});fs10.writeFileSync(tempPath,JSON.stringify(meta4,null,2),"utf8");fs10.renameSync(tempPath,metaPath)}catch(error3){try{fs10.unlinkSync(tempPath)}catch{}debugLogger16.warn(`Failed to write agent meta sidecar ${metaPath}:`,error3);return}try{const now=new Date;fs10.utimesSync(path13.dirname(metaPath),now,now)}catch(error3){debugLogger16.warn(`Failed to refresh agent session directory for ${metaPath}:`,error3)}}__name(writeAgentMeta,"writeAgentMeta");function readAgentMeta(metaPath){try{return JSON.parse(fs10.readFileSync(metaPath,"utf8"))}catch(error3){if(error3.code!=="ENOENT"){debugLogger16.warn(`Failed to read agent meta sidecar ${metaPath}:`,error3)}return void 0}}__name(readAgentMeta,"readAgentMeta");async function readAgentMetaAsync(metaPath,options2){let contents;try{contents=await fs10.promises.readFile(metaPath,"utf8")}catch(error3){if(error3.code!=="ENOENT"){debugLogger16.warn(`Failed to read agent meta sidecar ${metaPath}:`,error3);if(options2?.throwOnReadError)throw error3}return void 0}try{return JSON.parse(contents)}catch(error3){debugLogger16.warn(`Failed to read agent meta sidecar ${metaPath}:`,error3);return void 0}}__name(readAgentMetaAsync,"readAgentMetaAsync");function patchAgentMeta(metaPath,updates){const current2=readAgentMeta(metaPath);if(!current2)return void 0;const next={...current2,...updates};writeAgentMeta(metaPath,next);return next}__name(patchAgentMeta,"patchAgentMeta");function getAgentMetaTerminalSummary(stats,recentActivities){const candidateStats=stats;const normalizedStats=candidateStats&&Number.isFinite(candidateStats["totalTokens"])&&Number.isFinite(candidateStats["outputTokens"])&&Number.isFinite(candidateStats["toolUses"])&&Number.isFinite(candidateStats["durationMs"])?{totalTokens:candidateStats["totalTokens"],outputTokens:candidateStats["outputTokens"],toolUses:candidateStats["toolUses"],durationMs:candidateStats["durationMs"]}:void 0;const normalizedActivities=Array.isArray(recentActivities)?recentActivities.filter(activity=>activity!==null&&typeof activity==="object"&&typeof activity.name==="string"&&typeof activity.description==="string"&&Number.isFinite(activity.at)):void 0;return{...normalizedStats?{stats:normalizedStats}:{},...normalizedActivities?{recentActivities:normalizedActivities.slice(-MAX_PERSISTED_RECENT_ACTIVITIES).map(({name:name2,description,at:at3})=>({name:name2,description,at:at3}))}:{}}}__name(getAgentMetaTerminalSummary,"getAgentMetaTerminalSummary");function readLastTranscriptRecordUuidSync(jsonlPath){try{const raw=fs10.readFileSync(jsonlPath,"utf8");const lines=raw.split("\n");for(let i=lines.length-1;i>=0;i--){const trimmed=lines[i]?.trim();if(!trimmed)continue;try{const parsed=JSON.parse(trimmed);return parsed.uuid??null}catch{const recovered=_recoverObjectsFromLine(trimmed);const lastRecovered=recovered[recovered.length-1];if(lastRecovered?.uuid){return lastRecovered.uuid}}}}catch(error3){if(error3.code!=="ENOENT"){debugLogger16.warn(`Failed to read last transcript record UUID from ${jsonlPath}:`,error3)}}return null}__name(readLastTranscriptRecordUuidSync,"readLastTranscriptRecordUuidSync");function buildAgentTranscriptAttach(config3,agentId,extras){const projectRoot=config3.getProjectRoot();const options2={agentId,sessionId:config3.getSessionId(),cwd:projectRoot,version:config3.getCliVersion()||"unknown",gitBranch:getCachedGitBranch(projectRoot),...extras};return{jsonlPath:getAgentJsonlPath(config3.storage.getProjectDir(),options2.sessionId,options2.agentId),options:options2}}__name(buildAgentTranscriptAttach,"buildAgentTranscriptAttach");function attachJsonlTranscriptWriter(emitter,jsonlPath,options2){let lastUuid=options2.initialParentUuid!==void 0?options2.initialParentUuid:options2.appendToExisting?readLastTranscriptRecordUuidSync(jsonlPath):null;let fd=null;let streamFd=null;const streamPath=`${jsonlPath}.stream`;const streamRunId=randomUUID6();let pendingStreamText="";let pendingStreamBytes=0;let streamFlushTimer=null;let openFailed=false;try{fs10.rmSync(streamPath,{force:true})}catch(error3){debugLogger16.warn(`Failed to reset streaming transcript ${streamPath}:`,error3)}const ensureOpen=__name(()=>{if(fd!==null)return true;if(openFailed)return false;try{fs10.mkdirSync(path13.dirname(jsonlPath),{recursive:true});fd=fs10.openSync(jsonlPath,"a");return true}catch(error3){debugLogger16.warn(`Failed to open JSONL transcript ${jsonlPath}:`,error3);openFailed=true;return false}},"ensureOpen");const baseFields=__name(type=>({uuid:randomUUID6(),parentUuid:lastUuid,sessionId:options2.sessionId,timestamp:new Date().toISOString(),type,cwd:options2.cwd,version:options2.version,gitBranch:options2.gitBranch,agentId:options2.agentId,agentName:options2.agentName,agentColor:options2.agentColor,isSidechain:true}),"baseFields");const append=__name(record4=>{if(!ensureOpen())return;try{fs10.writeSync(fd,JSON.stringify(record4)+"\n");lastUuid=record4.uuid}catch(error3){debugLogger16.warn(`Failed to append JSONL record to ${jsonlPath}:`,error3)}},"append");const flushStreamText=__name(()=>{streamFlushTimer=null;if(!pendingStreamText)return;const text3=pendingStreamText;pendingStreamText="";pendingStreamBytes=0;try{if(streamFd===null){fs10.mkdirSync(path13.dirname(jsonlPath),{recursive:true});streamFd=fs10.openSync(streamPath,"w")}fs10.writeSync(streamFd,text3)}catch(error3){debugLogger16.warn(`Failed to append streaming transcript ${streamPath}:`,error3)}},"flushStreamText");const appendStreamText=__name(event=>{const record4=`${JSON.stringify({v:1,runId:event.runId??streamRunId,round:event.round,text:event.text,thought:event.thought===true,timestamp:event.timestamp})}
101
102
  `;pendingStreamText+=record4;pendingStreamBytes+=Buffer.byteLength(record4);if(pendingStreamBytes>=MAX_PENDING_STREAM_BYTES){if(streamFlushTimer!==null){clearTimeout(streamFlushTimer);streamFlushTimer=null}flushStreamText();return}if(streamFlushTimer===null){streamFlushTimer=setTimeout(flushStreamText,100);streamFlushTimer.unref()}},"appendStreamText");const onRoundText=__name(event=>{const parts=[...event.thoughtText?[{text:event.thoughtText,thought:true}]:[],...event.text?[{text:event.text}]:[]];if(parts.length===0&&!event.usageMetadata)return;append({...baseFields("assistant"),message:{role:"model",parts},usageMetadata:event.usageMetadata,agentRunId:event.runId??streamRunId,agentRound:event.round})},"onRoundText");const sessionReadiness=new Map;const recordSessionReadiness=__name((callId,ready)=>{if(sessionReadiness.get(callId)===ready)return;sessionReadiness.set(callId,ready);recordSystem("agent_session_ready",{callId,subagentSessionReady:ready})},"recordSessionReadiness");const recordedLifecycle=new Set;const pendingLifecycle=new Set;let cleanedUp=false;let drainTimer;const closeLifecycle=__name(()=>{if(drainTimer)clearTimeout(drainTimer);drainTimer=void 0;emitter.off("tool_result",onToolResult);emitter.off("tool_output_update",onToolOutputUpdate);if(fd!==null){try{fs10.closeSync(fd)}catch{}fd=null}},"closeLifecycle");const recordLifecycle=__name(event=>{if(!event||cleanedUp&&!pendingLifecycle.has(event.executionId))return;const key=`${event.executionId}:${event.phase}`;if(recordedLifecycle.has(key))return;recordedLifecycle.add(key);if(event.phase==="started")pendingLifecycle.add(event.executionId);else pendingLifecycle.delete(event.executionId);if(recordedLifecycle.size>512)recordedLifecycle.delete(recordedLifecycle.values().next().value);append({...baseFields("system"),subtype:"ui_telemetry",systemPayload:{uiEvent:{...event,"event.name":"tool_lifecycle"}}});if(cleanedUp&&pendingLifecycle.size===0)closeLifecycle()},"recordLifecycle");const onToolResult=__name(event=>recordLifecycle(event.lifecycle),"onToolResult");const onToolOutputUpdate=__name(event=>{recordLifecycle(event.lifecycle);if(cleanedUp)return;const output=event.outputChunk;if(typeof output==="object"&&output!==null&&"subagentSessionReady"in output&&typeof output.subagentSessionReady==="boolean"){recordSessionReadiness(event.callId,output.subagentSessionReady)}},"onToolOutputUpdate");const onToolCall=__name(event=>{append({...baseFields("assistant"),message:{role:"model",parts:[{functionCall:{id:event.callId,name:event.modelFacingName??event.name,args:event.modelFacingArgs??event.args}}]}});if(event.name===ToolNames.AGENT){recordSessionReadiness(event.callId,false)}},"onToolCall");const onToolResponsesFinalized=__name(event=>{for(const response of event.responses){append({...baseFields("tool_result"),message:{role:"user",parts:response.responseParts},toolCallResult:{callId:response.callId,...sessionReadiness.has(response.callId)&&response.responseParts.some(part=>part.functionResponse?.response?.["error"])?{status:"error"}:{},...response.durationMs!==void 0?{durationMs:response.durationMs}:{}}})}},"onToolResponsesFinalized");const recordUserMessage=__name((text3,externalInputKind)=>{if(!text3)return;append({...baseFields("user"),message:{role:"user",parts:[{text:text3}]},...externalInputKind?{externalInputKind}:{}})},"recordUserMessage");const recordSystem=__name((subtype,payload)=>{append({...baseFields("system"),subtype,systemPayload:payload})},"recordSystem");const onExternalMessage=__name(event=>{recordUserMessage(event.text,event.kind??"message")},"onExternalMessage");if(options2.bootstrapHistory!==void 0){const payload={kind:"fork",history:structuredClone(options2.bootstrapHistory??[])};recordSystem("agent_bootstrap",payload)}if(options2.initialUserPrompt){recordUserMessage(options2.initialUserPrompt)}if(options2.launchTaskPrompt){recordSystem("agent_launch_prompt",{displayText:options2.launchTaskPrompt})}if(options2.retryAttempt!==void 0){recordSystem("agent_retry",{attempt:options2.retryAttempt})}emitter.on("round_text",onRoundText);emitter.on("stream_text",appendStreamText);emitter.on("tool_call",onToolCall);emitter.on("tool_result",onToolResult);emitter.on("tool_output_update",onToolOutputUpdate);emitter.on("tool_responses_finalized",onToolResponsesFinalized);emitter.on("external_message",onExternalMessage);const cleanup=__name(()=>{if(cleanedUp)return;cleanedUp=true;emitter.off("round_text",onRoundText);emitter.off("stream_text",appendStreamText);emitter.off("tool_call",onToolCall);emitter.off("tool_responses_finalized",onToolResponsesFinalized);emitter.off("external_message",onExternalMessage);if(streamFlushTimer!==null){clearTimeout(streamFlushTimer);streamFlushTimer=null}flushStreamText();if(pendingLifecycle.size===0)closeLifecycle();else{drainTimer=setTimeout(closeLifecycle,TOOL_LIFECYCLE_DRAIN_MS);drainTimer.unref()}if(streamFd!==null){try{fs10.closeSync(streamFd)}catch{}streamFd=null}try{fs10.rmSync(streamPath,{force:true})}catch(error3){debugLogger16.warn(`Failed to remove streaming transcript ${streamPath}:`,error3)}},"cleanup");return{cleanup}}__name(attachJsonlTranscriptWriter,"attachJsonlTranscriptWriter");var debugLogger17=createDebugLogger("MONITOR_REGISTRY");var EVENT_LINE_TRUNCATE=2e3;var MAX_CONCURRENT_MONITORS=16;var MAX_RETAINED_TERMINAL_MONITORS=128;function getMonitorOutputPath(projectDir,sessionId,monitorId){return path14.join(projectDir,"monitors",sanitizeFilenameComponent(sessionId),`monitor-${sanitizeFilenameComponent(monitorId)}.log`)}__name(getMonitorOutputPath,"getMonitorOutputPath");var MonitorRegistry=class{static{__name(this,"MonitorRegistry")}monitors=new Map;agentNotificationCallbacks=new Map;agentLifecycleCallbacks=new Map;notificationCallback;registerCallback;statusChangeCallback;register(registration){if(this.getRunning().length>=MAX_CONCURRENT_MONITORS){throw new Error(`Cannot start monitor: maximum concurrent monitors (${MAX_CONCURRENT_MONITORS}) reached. Stop an existing monitor first.`)}const entry=registration;entry.id=registration.monitorId;entry.kind="monitor";entry.outputOffset=0;entry.notified=false;entry.todoWorkChainId??=todoWorkChainContext.getStore();this.monitors.set(entry.monitorId,entry);debugLogger17.info(`Registered monitor: ${entry.monitorId}`);this.resetIdleTimer(entry);if(!entry.ownerAgentId&&this.registerCallback){try{this.registerCallback(entry)}catch(error3){debugLogger17.error("Failed to emit register callback:",error3)}}this.fireStatusChange(entry);return entry}emitEvent(monitorId,line2){const entry=this.monitors.get(monitorId);if(!entry||entry.status!=="running")return;entry.eventCount++;entry.lastEventTime=Date.now();this.resetIdleTimer(entry);const truncatedLine=line2.length>EVENT_LINE_TRUNCATE?line2.slice(0,EVENT_LINE_TRUNCATE)+"...[truncated]":line2;this.emitNotification(entry,truncatedLine);if(entry.eventCount>=entry.maxEvents){debugLogger17.info(`Monitor ${monitorId} reached max events (${entry.maxEvents}), stopping`);entry.error="Max events reached";this.settle(entry,"completed");entry.abortController.abort();this.emitTerminalNotification(entry,"Max events reached")}}complete(monitorId,exitCode){const entry=this.monitors.get(monitorId);if(!entry||entry.status!=="running")return;if(exitCode!==null)entry.exitCode=exitCode;this.settle(entry,"completed");debugLogger17.info(`Monitor completed: ${monitorId} (exit ${exitCode}, ${entry.eventCount} events)`);this.emitTerminalNotification(entry,exitCode!==null?`Exited with code ${exitCode}`:void 0)}fail(monitorId,error3){const entry=this.monitors.get(monitorId);if(!entry||entry.status!=="running")return;entry.error=error3;this.settle(entry,"failed");debugLogger17.info(`Monitor failed: ${monitorId}: ${error3}`);this.emitTerminalNotification(entry,error3)}cancel(monitorId,options2={}){const entry=this.monitors.get(monitorId);if(!entry||entry.status!=="running")return;if(options2.notify===false){this.settle(entry,"cancelled");entry.notified=true;debugLogger17.info(`Monitor cancelled: ${monitorId}`);entry.abortController.abort();this.dispatchOwnerLifecycleWake(entry);return}entry.abortController.abort();if(entry.status!=="running")return;this.settle(entry,"cancelled");debugLogger17.info(`Monitor cancelled: ${monitorId}`);this.emitTerminalNotification(entry)}get(monitorId){return this.monitors.get(monitorId)}getAll(){return Array.from(this.monitors.values())}getRunning(){return Array.from(this.monitors.values()).filter(e=>e.status==="running")}hasRunningForOwner(ownerAgentId){for(const entry of this.monitors.values()){if(entry.ownerAgentId===ownerAgentId&&entry.status==="running"){return true}}return false}setNotificationCallback(cb){this.notificationCallback=cb}setAgentNotificationCallback(agentId,cb){if(cb){this.agentNotificationCallbacks.set(agentId,cb)}else{this.agentNotificationCallbacks.delete(agentId)}}setAgentLifecycleCallback(agentId,cb){if(cb){this.agentLifecycleCallbacks.set(agentId,cb)}else{this.agentLifecycleCallbacks.delete(agentId)}}setRegisterCallback(cb){this.registerCallback=cb}setStatusChangeCallback(cb){this.statusChangeCallback=cb}clearStatusChangeCallback(cb){if(this.statusChangeCallback===cb)this.statusChangeCallback=void 0}abortAll(options2={}){for(const entry of Array.from(this.monitors.values())){this.cancel(entry.monitorId,options2)}debugLogger17.info("Aborted all monitors")}cancelRunningForOwner(ownerAgentId,options2={}){const monitorIds=[];for(const entry of this.monitors.values()){if(entry.ownerAgentId===ownerAgentId&&entry.status==="running"){monitorIds.push(entry.monitorId)}}for(const monitorId of monitorIds){this.cancel(monitorId,options2)}}reset(){this.agentNotificationCallbacks.clear();this.agentLifecycleCallbacks.clear();if(this.monitors.size===0)return;for(const entry of this.monitors.values()){this.clearIdleTimer(entry);if(entry.status==="running"){entry.abortController.abort()}}this.monitors.clear();this.fireStatusChange()}settle(entry,status){entry.status=status;entry.endTime=Date.now();this.clearIdleTimer(entry);this.pruneTerminalEntries();this.fireStatusChange(entry)}fireStatusChange(entry){if(!this.statusChangeCallback)return;try{this.statusChangeCallback(entry)}catch(error3){debugLogger17.error("statusChange callback failed:",error3)}}dispatchOwnerLifecycleWake(entry){if(!entry.ownerAgentId)return;const callback=this.agentLifecycleCallbacks.get(entry.ownerAgentId);if(!callback)return;try{callback()}catch(error3){debugLogger17.error("owner lifecycle callback failed:",error3)}}pruneTerminalEntries(){const terminalEntries=Array.from(this.monitors.values()).filter(entry=>entry.status!=="running").sort((a,b2)=>(a.endTime??a.startTime)-(b2.endTime??b2.startTime)||a.startTime-b2.startTime);while(terminalEntries.length>MAX_RETAINED_TERMINAL_MONITORS){const oldest=terminalEntries.shift();if(oldest){this.monitors.delete(oldest.monitorId)}}}resetIdleTimer(entry){this.clearIdleTimer(entry);entry.idleTimer=setTimeout(()=>{if(entry.status==="running"){debugLogger17.info(`Monitor ${entry.monitorId} idle timeout (${entry.idleTimeoutMs}ms), stopping`);entry.abortController.abort();if(entry.status!=="running")return;entry.error="Idle timeout";this.settle(entry,"completed");this.emitTerminalNotification(entry,"Idle timeout")}},entry.idleTimeoutMs);entry.idleTimer.unref?.()}clearIdleTimer(entry){if(entry.idleTimer!==void 0){clearTimeout(entry.idleTimer);entry.idleTimer=void 0}}emitNotification(entry,eventLine){const desc=truncateNotificationLabel(entry.description);const safeEventLine=stripDisplayControlChars(eventLine);const displayLine=`Monitor "${desc}" event #${entry.eventCount}: ${safeEventLine}`;const xmlParts=["<task-notification>",`<task-id>${escapeXml(entry.monitorId)}</task-id>`];if(entry.toolUseId){xmlParts.push(`<tool-use-id>${escapeXml(entry.toolUseId)}</tool-use-id>`)}xmlParts.push("<kind>monitor</kind>","<status>running</status>",`<event-count>${entry.eventCount}</event-count>`,`<summary>Monitor "${escapeXml(desc)}" emitted event #${entry.eventCount}.</summary>`,`<result>${escapeXml(safeEventLine)}</result>`,"</task-notification>");const meta4={monitorId:entry.monitorId,status:"running",eventCount:entry.eventCount,toolUseId:entry.toolUseId,ownerAgentId:entry.ownerAgentId,todoWorkChainId:entry.todoWorkChainId};this.dispatchNotification(entry,displayLine,xmlParts.join("\n"),meta4)}emitTerminalNotification(entry,detail){if(entry.notified)return;entry.notified=true;const statusText=entry.status==="completed"?"completed":entry.status==="failed"?"failed":"was cancelled";const desc=truncateNotificationLabel(entry.description);const droppedSuffix=entry.droppedLines>0?`, ${entry.droppedLines} lines dropped due to throttling`:"";const displayLine=`Monitor "${desc}" ${statusText}. (${entry.eventCount} events${droppedSuffix})`;const xmlParts=["<task-notification>",`<task-id>${escapeXml(entry.monitorId)}</task-id>`];if(entry.toolUseId){xmlParts.push(`<tool-use-id>${escapeXml(entry.toolUseId)}</tool-use-id>`)}xmlParts.push("<kind>monitor</kind>",`<status>${escapeXml(entry.status)}</status>`,`<event-count>${entry.eventCount}</event-count>`,`<summary>Monitor "${escapeXml(desc)}" ${statusText}. Total events: ${entry.eventCount}.${entry.droppedLines>0?` ${entry.droppedLines} lines dropped due to throttling.`:""}</summary>`,`<command>${escapeXml(stripDisplayControlChars(entry.command))}</command>`);if(detail){xmlParts.push(`<result>${escapeXml(stripDisplayControlChars(detail))}</result>`)}xmlParts.push("</task-notification>");const meta4={monitorId:entry.monitorId,status:entry.status,eventCount:entry.eventCount,toolUseId:entry.toolUseId,ownerAgentId:entry.ownerAgentId,todoWorkChainId:entry.todoWorkChainId};this.dispatchNotification(entry,displayLine,xmlParts.join("\n"),meta4)}dispatchNotification(entry,displayLine,modelText,meta4){const callback=entry.ownerAgentId?this.agentNotificationCallbacks.get(entry.ownerAgentId):this.notificationCallback;if(!callback){if(entry.ownerAgentId){debugLogger17.warn(`Dropping monitor notification for ${entry.monitorId}: owner agent ${entry.ownerAgentId} has no notification callback`)}return}try{callback(displayLine,modelText,meta4)}catch(error3){debugLogger17.error("Failed to emit monitor notification:",error3)}}};init_esbuild_shims();import fs11 from"node:fs";import{createRequire}from"node:module";import path15 from"node:path";import{fileURLToPath}from"node:url";init_esbuild_shims();import{spawnSync}from"node:child_process";import{statSync}from"node:fs";var NO_RISK={diffExternal:false,fsmonitor:false};var PROBE_FAILED={diffExternal:true,fsmonitor:true};function getLocalGitConfigRisk(cwd){try{if(!statSync(cwd).isDirectory())return NO_RISK}catch{return NO_RISK}const result=spawnSync("git",["-C",cwd,"config","--includes","--show-scope","--null","--get-regexp","^diff\\.external$|^core\\.fsmonitor$"],{encoding:"utf8",maxBuffer:64*1024,timeout:1e3,windowsHide:true});if(result.status===1)return NO_RISK;if(result.status!==0||typeof result.stdout!=="string"){return PROBE_FAILED}const effective=new Map;const fields=result.stdout.split("\0");for(let i=0;i+1<fields.length;i+=2){const entry=fields[i+1];const newline2=entry.indexOf("\n");if(newline2<0)return PROBE_FAILED;effective.set(entry.slice(0,newline2),{scope:fields[i],value:entry.slice(newline2+1)})}const localValue=__name(key=>{const entry=effective.get(key);return entry&&(entry.scope==="local"||entry.scope==="worktree")?entry.value.trim():void 0},"localValue");const diffExternal=localValue("diff.external");const fsmonitor=localValue("core.fsmonitor");return{diffExternal:diffExternal!==void 0&&diffExternal!=="",fsmonitor:fsmonitor!==void 0&&fsmonitor!==""&&!/^(?:true|false|yes|no|on|off|0|1)$/i.test(fsmonitor)}}__name(getLocalGitConfigRisk,"getLocalGitConfigRisk");async function loadWasmBinary(dynamicImport,fallbackSpecifier){const nativeFs=process.getBuiltinModule?.("fs")??fs11;const moduleFilePath=fileURLToPath(import.meta.url);const isBundleMode=!moduleFilePath.includes(path15.join("src",""))&&!moduleFilePath.includes(path15.join("dist","src",""));try{if(isBundleMode){const mod=await dynamicImport();const wasmBinary=mod.default;if(wasmBinary instanceof Uint8Array&&wasmBinary.byteLength>0){return wasmBinary}}}catch{}const require2=createRequire(import.meta.url);const filePath=require2.resolve(fallbackSpecifier);return new Uint8Array(nativeFs.readFileSync(filePath))}__name(loadWasmBinary,"loadWasmBinary");var READ_ONLY_ROOT_COMMANDS=new Set(["awk","basename","cat","cd","column","cut","df","dirname","du","echo","find","git","grep","head","less","ls","more","printenv","printf","ps","pwd","rg","ripgrep","sed","sort","stat","tail","tree","uniq","wc","which","where","whoami"]);var WRITE_ROOT_COMMAND=/^(chgrp|chmod|chown|cp|install|ln|mkdir|mkfifo|mknod|mv|rename|rm|rmdir|shred|touch|truncate|unlink)$/;var READ_ONLY_GIT_SUBCOMMANDS=new Set(["blame","branch","cat-file","diff","grep","log","ls-files","remote","rev-parse","show","status","describe"]);var WRITE_GIT_SUBCOMMAND=/^(add|am|checkout|cherry-pick|clean|clone|commit|fetch|gc|init|merge|mv|pull|push|rebase|reset|restore|revert|rm|stash|switch)$/;var WRITE_GIT_REMOTE_ACTION=/^(add|remove|rm|rename|set-branches|set-head|set-url|update)$/;var GIT_EXTERNAL_HELPER_OPTION=/^--(?:ext-diff|filters|show-signature|textconv|open-files-in-pager)(?:=|$)/;var GIT_COMMIT_VALUE_OPTION=/^(?:-[CcFmt]|--(?:author|cleanup|date|file|fixup|message|pathspec-from-file|reedit-message|reuse-message|squash|template|trailer))$/;var WRITE_GIT_BRANCH_FLAG=/^(?:-[cCdDmMu](?:.|$)|--(?:delete|move|copy|set-upstream(?:-to)?|unset-upstream|create-reflog|edit-description)(?:=|$))/;var GIT_BRANCH_LIST_FLAG=/^(?:-[alr]|--(?:all|list|remotes|show-current|contains|no-contains|merged|no-merged|points-at))(?:=|$)/;var BLOCKED_FIND_PREFIXES=["-fls","-fprint","-fprintf"];var FIND_VALUE_PREDICATE=/^-(?:[ac]?newer|newer[a-z]{2}|[acm](?:min|time)|context|fstype|gid|group|i?(?:lname|name|path|regex)|inum|links|maxdepth|mindepth|path|perm|printf|regextype|samefile|size|type|uid|used|user|wholename|xtype)$/;var UNIQ_VALUE_OPTIONS=new Set("-f --skip-fields -s --skip-chars -w --check-chars".split(" "));var WRITE_REDIRECT_OPERATORS=new Set([">",">>","&>","&>>",">|"]);var KNOWN_SUBCOMMANDS={git:new Set(["add","am","archive","bisect","blame","branch","bundle","cat-file","checkout","cherry-pick","clean","clone","commit","config","describe","diff","fetch","format-patch","gc","grep","init","log","ls-files","ls-remote","merge","mv","notes","pull","push","range-diff","rebase","reflog","remote","reset","restore","revert","rev-parse","rm","shortlog","show","stash","status","submodule","switch","tag","worktree"]),npm:new Set(["access","adduser","audit","bugs","cache","ci","completion","config","create","dedupe","deprecate","diff","dist-tag","docs","doctor","edit","exec","explain","explore","find-dupes","fund","help","hook","init","install","install-ci-test","install-test","link","login","logout","ls","org","outdated","owner","pack","ping","pkg","prefix","profile","prune","publish","query","rebuild","repo","restart","root","run","run-script","search","set-script","shrinkwrap","star","stars","start","stop","team","test","token","uninstall","unpublish","unstar","update","version","view","whoami"]),yarn:new Set(["add","autoclean","bin","cache","check","config","create","generate-lock-entry","global","help","import","info","init","install","licenses","link","list","login","logout","outdated","owner","pack","policies","publish","remove","run","tag","team","test","unlink","unplug","upgrade","upgrade-interactive","version","versions","why","workspace","workspaces"]),pnpm:new Set(["add","audit","create","dedupe","deploy","dlx","env","exec","fetch","import","init","install","install-test","licenses","link","list","ls","outdated","pack","patch","patch-commit","prune","publish","rebuild","remove","root","run","server","setup","store","test","uninstall","unlink","update","why"]),docker:new Set(["attach","build","commit","compose","container","context","cp","create","diff","events","exec","export","history","image","images","import","info","inspect","kill","load","login","logout","logs","manifest","network","node","pause","plugin","port","ps","pull","push","rename","restart","rm","rmi","run","save","search","secret","service","stack","start","stats","stop","swarm","system","tag","top","trust","unpause","update","version","volume","wait"]),pip:new Set(["install","download","uninstall","freeze","inspect","list","show","check","config","search","cache","index","wheel","hash","completion","debug","help"]),pip3:new Set(["install","download","uninstall","freeze","inspect","list","show","check","config","search","cache","index","wheel","hash","completion","debug","help"]),cargo:new Set(["add","bench","build","check","clean","clippy","doc","fetch","fix","fmt","generate-lockfile","init","install","locate-project","login","metadata","new","owner","package","pkgid","publish","read-manifest","remove","report","run","rustc","rustdoc","search","test","tree","uninstall","update","vendor","verify-project","version","yank"]),kubectl:new Set(["annotate","api-resources","api-versions","apply","attach","auth","autoscale","certificate","cluster-info","completion","config","cordon","cp","create","debug","delete","describe","diff","drain","edit","events","exec","explain","expose","get","kustomize","label","logs","patch","plugin","port-forward","proxy","replace","rollout","run","scale","set","taint","top","uncordon","version","wait"]),make:new Set([])};var DOCKER_COMPOSE_SUBCOMMANDS=new Set(["build","config","cp","create","down","events","exec","images","kill","logs","ls","pause","port","ps","pull","push","restart","rm","run","start","stop","top","unpause","up","version","wait","watch"]);var parserInstance=null;var bashLanguage=null;var parserClass;var initPromise=null;var parserInitFailed=false;async function initParser(){if(parserInstance)return;if(parserInitFailed)throw new Error("tree-sitter WASM failed to initialise; using regex-based fallback");if(initPromise)return initPromise;initPromise=(async()=>{const{default:ParserClass}=await import("./tree-sitter-MOEVH2ND.js");const treeSitterWasm=await loadWasmBinary(()=>import("./tree-sitter-RHQPIRIG.js"),"web-tree-sitter/tree-sitter.wasm");await ParserClass.init({wasmBinary:treeSitterWasm});const bashWasm=await loadWasmBinary(()=>import("./tree-sitter-bash-RXTK2HHQ.js"),"tree-sitter-wasms/out/tree-sitter-bash.wasm");bashLanguage=await ParserClass.Language.load(bashWasm);parserClass=ParserClass;parserInstance=new ParserClass;parserInstance.setLanguage(bashLanguage)})().catch(err=>{const failedParser=parserInstance;parserInstance=null;bashLanguage=null;parserInitFailed=true;initPromise=null;try{failedParser?.delete()}catch{}throw err});return initPromise}__name(initParser,"initParser");async function parseShellCommand(command){await initParser();const parser2=parserInstance;try{return parser2.parse(command)}catch(error3){parserInstance=null;let replacement=null;try{replacement=new parserClass;replacement.setLanguage(bashLanguage);parserInstance=replacement}catch{try{replacement?.delete()}catch{}bashLanguage=null;parserInitFailed=true;initPromise=null}finally{parser2.delete()}throw error3}}__name(parseShellCommand,"parseShellCommand");var SHELL_EXPANSION_TYPES=new Set("simple_expansion expansion arithmetic_expansion".split(" "));var CHILD_STATEMENT=/^(?:pipeline|list|subshell|compound_statement|negated_command)$/;function collectDescendants(node,types4,outermostOnly=false){const result=[];const stack=[node];while(stack.length>0){const current2=stack.pop();if(types4.has(current2.type)){result.push(current2);if(outermostOnly)continue}for(let i=current2.childCount-1;i>=0;i--){stack.push(current2.child(i))}}return result}__name(collectDescendants,"collectDescendants");function getCommandName(commandNode){const nameNode=commandNode.childForFieldName("name");if(!nameNode)return null;return nameNode.text.toLowerCase()}__name(getCommandName,"getCommandName");function getArgumentNodes(commandNode){const args=[];for(let i=0;i<commandNode.childCount;i++){const fieldName=commandNode.fieldNameForChild(i);if(fieldName==="argument"){args.push(commandNode.child(i))}}return args}__name(getArgumentNodes,"getArgumentNodes");function stripOuterQuotes(text3){if(text3.length>=2){if(text3.startsWith("'")&&text3.endsWith("'")||text3.startsWith('"')&&text3.endsWith('"')){return text3.slice(1,-1)}}return text3}__name(stripOuterQuotes,"stripOuterQuotes");function hasShellExpansion(node){return collectDescendants(node,SHELL_EXPANSION_TYPES).length>0||["word","concatenation"].includes(node.type)&&hasShellPatternExpansion(node.text)}__name(hasShellExpansion,"hasShellExpansion");function mergeSafety(...results){if(results.includes("write"))return"write";if(results.includes("unknown"))return"unknown";return"read-only"}__name(mergeSafety,"mergeSafety");function beforeTerminator(args){const end=args.indexOf("--");return args.slice(0,end<0?args.length:end)}__name(beforeTerminator,"beforeTerminator");function hasHelp(args,valueOptions=[]){return beforeTerminator(args).some((arg,index,options2)=>/^(?:--help|--version)$/i.test(arg)&&!valueOptions.includes(options2[index-1]))}__name(hasHelp,"hasHelp");function withoutOptionValues(args,valueOption){const result=[];for(let i=0;i<args.length;i++){result.push(args[i]);if(valueOption.test(args[i]))i++}return result}__name(withoutOptionValues,"withoutOptionValues");function evaluateOutputOption(args,long=true,short=true){for(let i=0;i<args.length;i++){const arg=args[i];if(arg==="--")break;if(short&&arg==="-o"||long&&arg==="--output"){return args[i+1]?"write":"unknown"}if(short&&arg.startsWith("-o")&&arg.length>2)return"write";if(long&&arg.startsWith("--output=")){return arg.length>9?"write":"unknown"}}return null}__name(evaluateOutputOption,"evaluateOutputOption");function evaluateGitSafety(args){const first=args[0];if(!first||first==="--version")return"read-only";if(first==="--help")return args.length===1?"read-only":"unknown";if(first.startsWith("-"))return"unknown";const subcommand=first.toLowerCase();const rest=args.slice(1);const options2=beforeTerminator(rest);const invokesHelper=options2.some(arg=>GIT_EXTERNAL_HELPER_OPTION.test(arg))||subcommand==="grep"&&options2.some(arg=>arg.startsWith("-O"))||["log","show"].includes(subcommand)&&options2.some(arg=>/%G[?GKFPST]/.test(arg));if(WRITE_GIT_SUBCOMMAND.test(subcommand)){const effectiveArgs=subcommand==="commit"?withoutOptionValues(rest,GIT_COMMIT_VALUE_OPTION):rest;const effectiveOptions=beforeTerminator(effectiveArgs);const help=hasHelp(effectiveArgs);const dryRun=effectiveOptions.includes("--dry-run")||effectiveOptions.includes("-n")&&["add","clean","mv","push","rm"].includes(subcommand);return help||dryRun?"unknown":"write"}if(!READ_ONLY_GIT_SUBCOMMANDS.has(subcommand))return"unknown";if(["diff","log","show"].includes(subcommand)){const output=evaluateOutputOption(rest,true,false);if(output)return output}if(subcommand==="blame"&&beforeTerminator(rest).some(arg=>/^--output(?:=|$)/.test(arg)))return"unknown";if(subcommand!=="branch"&&hasHelp(rest))return"unknown";if(subcommand==="remote"){const action=rest.find(arg=>!arg.startsWith("-"))?.toLowerCase();if(!action)return invokesHelper?"unknown":"read-only";if(["show","get-url"].includes(action))return rest.some(arg=>/^(?:add|remove|rm|rename|set-branches|set-head|set-url|update|prune)$/i.test(arg))||invokesHelper?"unknown":"read-only";if(WRITE_GIT_REMOTE_ACTION.test(action))return"write";if(action==="prune")return rest.some(arg=>["-n","--dry-run"].includes(arg))?"unknown":"write";return"unknown"}if(subcommand==="branch"){const actions=withoutOptionValues(rest,/^--(?:format|sort)$/);const actionOptions=beforeTerminator(actions);if(hasHelp(actions))return"unknown";if(actions.some(arg=>WRITE_GIT_BRANCH_FLAG.test(arg)))return actionOptions.some(arg=>WRITE_GIT_BRANCH_FLAG.test(arg))?"write":"unknown";if(actions.length!==rest.length)return"unknown";const lists=actionOptions.some(arg=>GIT_BRANCH_LIST_FLAG.test(arg));if(lists)return"read-only";if(rest.some(arg=>!arg.startsWith("-")))return"write";if(rest.includes("--"))return"unknown";if(invokesHelper)return"unknown";return rest.length===0?"read-only":"unknown"}if(invokesHelper)return"unknown";return"read-only"}__name(evaluateGitSafety,"evaluateGitSafety");function evaluateFindSafety(args){let result="read-only";for(let i=0;i<args.length;i++){const lower=args[i].toLowerCase();if(lower==="--")return mergeSafety(result,"unknown");if(/^--(?:help|version)$/.test(lower))return"unknown";if(FIND_VALUE_PREDICATE.test(lower)){if(!args[++i]?.match(/^[^-]/))result=mergeSafety(result,"unknown");continue}if(lower==="-delete"){result="write";continue}if(BLOCKED_FIND_PREFIXES.some(prefix2=>lower.startsWith(prefix2))){result="write";i+=lower.startsWith("-fprintf")?2:1;continue}if(["-exec","-execdir","-ok","-okdir"].includes(lower)){const invoked=args[i+1]?.toLowerCase();let end=-1;for(let index=i+2;index<args.length;index++){if([";","\\;","+"].includes(args[index])){end=index;break}}const invokedArgs=args.slice(i+2,end<0?void 0:end);let nested="unknown";if(invoked&&WRITE_ROOT_COMMAND.test(invoked))nested=hasHelp(invokedArgs)?"unknown":"write";else if(invoked&&/^(kill|killall|pkill)$/.test(invoked))nested=processSafety(invoked,invokedArgs);result=mergeSafety(result,nested);i=end<0?args.length:end}}return result}__name(evaluateFindSafety,"evaluateFindSafety");function evaluateSedSafety(args){return classifySedCommandSafety(args)}__name(evaluateSedSafety,"evaluateSedSafety");function evaluateAwkSafety(args){return classifyAwkCommandSafety(args)}__name(evaluateAwkSafety,"evaluateAwkSafety");function evaluateUniqSafety(args){let positional=0;for(let i=0;i<args.length;i++){const arg=args[i];if(arg==="--"){return args.length-i+positional>2?"write":"read-only"}else if(UNIQ_VALUE_OPTIONS.has(arg)){if(!args[++i])return"unknown"}else if(arg==="-"||!arg.startsWith("-"))positional++}return positional>=2?"write":"read-only"}__name(evaluateUniqSafety,"evaluateUniqSafety");function processSafety(root,args){const options2=beforeTerminator(args);const signalZero=/^(?:SIG)?0+$/i;const signalValueOptions=["--signal",...root==="pkill"?[]:["-s"],...root==="kill"?["-n"]:[]];if(args.length===0||hasHelp(args)||options2.some(arg=>["-h","-V","-help","-version"].includes(arg)))return"unknown";if(options2.some((arg,index)=>/[$`*?()[\]{}]/.test(arg)&&(arg.startsWith("-")||signalValueOptions.includes(options2[index-1]))||/^-(?:[lL0]|-(?:.*list|table)(?:=|$))/.test(arg)||/^--signal=/.test(arg)&&signalZero.test(arg.slice(9))||/^-(?:SIG)?0+$/i.test(arg)||root==="kill"&&/^-[sn](?:SIG)?0+$/i.test(arg)||root==="killall"&&/^-s(?:SIG)?0+$/i.test(arg)||index>0&&signalValueOptions.includes(options2[index-1])&&signalZero.test(arg)))return"unknown";return"write"}__name(processSafety,"processSafety");function evaluateSubstitutions(node){const substitutions=collectDescendants(node,new Set(["command_substitution","process_substitution"]),true);if(substitutions.length===0){for(const expansion of collectDescendants(node,new Set(["expansion"]))){for(let i=0;i<expansion.childCount-1;i++){if(expansion.child(i)?.type==="@"&&expansion.child(i+1)?.type==="P"){return"unknown"}}}return"read-only"}return mergeSafety("unknown",...substitutions.flatMap(substitution=>substitution.namedChildren).map(evaluateStatementSafety))}__name(evaluateSubstitutions,"evaluateSubstitutions");function evaluateCommandSafety(commandNode){const rawRoot=commandNode.childForFieldName("name")?.text;const root=getCommandName(commandNode);const argNodes=getArgumentNodes(commandNode);const args=argNodes.map(node=>stripOuterQuotes(node.text));let result;if(!root)result="read-only";else if(rawRoot!==root)result="unknown";else if(WRITE_ROOT_COMMAND.test(root)){result=hasHelp(args)?"unknown":"write"}else if(/^(kill|killall|pkill)$/.test(root)){result=processSafety(root,args)}else if(root==="git")result=evaluateGitSafety(args);else if(root==="find")result=evaluateFindSafety(args);else if(root==="sed")result=evaluateSedSafety(args);else if(root==="awk")result=evaluateAwkSafety(args);else if(root==="sort"||root==="tree"){result=evaluateOutputOption(args,root==="sort")??"read-only";if(hasHelp(args,["-o","--output"]))result="unknown";if(beforeTerminator(args).some(arg=>/^(?:--o|-[^-]+o)/.test(arg)||root==="sort"&&arg.startsWith("--co"))){result=mergeSafety(result,"unknown")}}else if(root==="uniq"){result=hasHelp(args)?"unknown":evaluateUniqSafety(args)}else if(root==="tee"){const writesFile=args.some((arg,index)=>!arg.startsWith("-")||args[index-1]==="--");result=writesFile?"write":"unknown"}else if(root==="dd"){result=args.some(arg=>arg.startsWith("of="))?"write":"unknown"}else if(root==="printf"&&beforeTerminator(args).some(arg=>/^-[^-]*v/.test(arg))||["less","more"].includes(root)||["rg","ripgrep"].includes(root)&&beforeTerminator(args).some(arg=>/^(?:--(?:hostname-bin|pre)(?:=|$)|--search-zip$|-[^-]*z)/.test(arg))){result="unknown"}else{result=READ_ONLY_ROOT_COMMANDS.has(root)?"read-only":"unknown"}if(result==="read-only"&&root&&/^(awk|find|git|printf|rg|ripgrep|sed|sort|tree|uniq)$/.test(root)&&argNodes.some(node=>hasShellExpansion(node))){result="unknown"}if(result==="write"&&!["find","git","sed","sort","tree"].includes(root??"")&&hasHelp(args))result="unknown";const hasEnvironment=commandNode.namedChildren.some(child=>child.type==="variable_assignment");if(root&&hasEnvironment)result=mergeSafety(result,"unknown");return mergeSafety(result,evaluateRedirectionSafety(commandNode),...commandNode.namedChildren.filter(child=>!child.type.endsWith("_redirect")).map(evaluateSubstitutions))}__name(evaluateCommandSafety,"evaluateCommandSafety");function evaluateRedirectionSafety(node){let result="read-only";for(const redirect of node.namedChildren){if(!redirect.type.endsWith("_redirect"))continue;result=mergeSafety(result,evaluateSubstitutions(redirect));if(redirect.type!=="file_redirect")continue;const operator=redirect.children.find(child=>child.type!=="file_descriptor");if(!operator)return"unknown";if(WRITE_REDIRECT_OPERATORS.has(operator.type))return"write";if(operator.type===">&"){const destination=redirect.childForFieldName("destination");if(!destination)return"unknown";const target=stripOuterQuotes(destination.text);if(/^(?:\d+|-)$/.test(target))continue;result=mergeSafety(result,/[$`*?()[\]{}]/.test(target)?"unknown":"write")}}return result}__name(evaluateRedirectionSafety,"evaluateRedirectionSafety");function childrenSafety(node,floor="read-only"){return mergeSafety(floor,...node.namedChildren.map(evaluateStatementSafety))}__name(childrenSafety,"childrenSafety");function evaluateStatementSafety(node){if(node.type==="command")return evaluateCommandSafety(node);if(CHILD_STATEMENT.test(node.type))return childrenSafety(node);if(node.type==="redirected_statement")return mergeSafety(...node.namedChildren.filter(child=>!child.type.endsWith("_redirect")).map(child=>evaluateStatementSafety(child)),evaluateRedirectionSafety(node));if(/^variable_assignments?$/.test(node.type))return mergeSafety(node.parent?.namedChildCount===1?"read-only":"unknown",evaluateSubstitutions(node));if(node.type==="function_definition")return"unknown";return childrenSafety(node,"unknown")}__name(evaluateStatementSafety,"evaluateStatementSafety");function localGitConfigMakesCommandUnsafe(root,cwd){let changedDirectory=false;let usesDiff=false;let usesStatus=false;for(const command of collectDescendants(root,new Set(["command"]))){const name2=getCommandName(command);if(name2==="cd"||name2==="pushd"){changedDirectory=true;continue}if(name2!=="git")continue;const subcommand=stripOuterQuotes(getArgumentNodes(command)[0]?.text??"").toLowerCase();if(subcommand!=="diff"&&subcommand!=="status")continue;if(changedDirectory)return true;usesDiff||=subcommand==="diff";usesStatus||=subcommand==="status"}if(!usesDiff&&!usesStatus)return false;const risk=getLocalGitConfigRisk(cwd);return usesDiff&&risk.diffExternal||usesStatus&&risk.fsmonitor}__name(localGitConfigMakesCommandUnsafe,"localGitConfigMakesCommandUnsafe");function fallbackGitConfigMakesCommandUnsafe(command,cwd){if(/\b(?:cd|pushd)\b[\s\S]*\bgit\b/i.test(command))return true;if(!/\bgit\b/i.test(command))return false;const risk=getLocalGitConfigRisk(cwd);return risk.diffExternal||risk.fsmonitor}__name(fallbackGitConfigMakesCommandUnsafe,"fallbackGitConfigMakesCommandUnsafe");async function classifyInternal(command,cwd){const tree=await parseShellCommand(command);try{const root=tree.rootNode;if(root.namedChildCount===0||root.hasError)return"unknown";const safety=mergeSafety(...root.namedChildren.map(evaluateStatementSafety));if(safety==="read-only"&&command.includes("\\\n")){const normalizedSafety=await classifyInternal(command.replaceAll("\\\n",""),cwd);if(normalizedSafety!=="read-only")return"unknown"}if(safety!=="read-only"||!cwd)return safety;return localGitConfigMakesCommandUnsafe(root,cwd)?"unknown":"read-only"}finally{tree.delete()}}__name(classifyInternal,"classifyInternal");async function classifyShellCommandSafety(command){if(typeof command!=="string"||!command.trim())return"unknown";return classifyInternal(command).catch(()=>"unknown")}__name(classifyShellCommandSafety,"classifyShellCommandSafety");async function classifyShellCommandSafetyInDirectory(command,cwd){if(typeof command!=="string"||!command.trim())return"unknown";return classifyInternal(command,cwd).catch(()=>"unknown")}__name(classifyShellCommandSafetyInDirectory,"classifyShellCommandSafetyInDirectory");async function isShellCommandReadOnlyAST(command){return isShellCommandReadOnlyInternal(command)}__name(isShellCommandReadOnlyAST,"isShellCommandReadOnlyAST");async function isShellCommandReadOnlyASTInDirectory(command,cwd){return isShellCommandReadOnlyInternal(command,cwd)}__name(isShellCommandReadOnlyASTInDirectory,"isShellCommandReadOnlyASTInDirectory");async function isShellCommandReadOnlyInternal(command,cwd){if(typeof command!=="string"||!command.trim())return false;if(parserInitFailed){return isShellCommandReadOnly(command)&&!(cwd&&fallbackGitConfigMakesCommandUnsafe(command,cwd))}try{return await classifyInternal(command,cwd)==="read-only"}catch{return isShellCommandReadOnly(command)&&!(cwd&&fallbackGitConfigMakesCommandUnsafe(command,cwd))}}__name(isShellCommandReadOnlyInternal,"isShellCommandReadOnlyInternal");function extractRuleFromCommand(commandNode){const rootName=getCommandName(commandNode);if(!rootName)return null;const argNodes=getArgumentNodes(commandNode);const argTexts=argNodes.map(n=>n.text);let idx=0;while(idx<argTexts.length&&argTexts[idx].startsWith("-")){idx++}const knownSubs=KNOWN_SUBCOMMANDS[rootName];let rule=rootName;if(knownSubs&&knownSubs.size>0&&idx<argTexts.length){const potentialSub=argTexts[idx].toLowerCase();if(knownSubs.has(potentialSub)){rule=`${rootName} ${argTexts[idx]}`;if(rootName==="docker"&&potentialSub==="compose"&&idx+1<argTexts.length){const composeSub=argTexts[idx+1].toLowerCase();if(DOCKER_COMPOSE_SUBCOMMANDS.has(composeSub)){rule=`${rootName} compose ${argTexts[idx+1]}`;if(idx+2<argTexts.length){rule+=" *"}return rule}}if(idx+1<argTexts.length){rule+=" *"}return rule}}if(argTexts.length>0){rule+=" *"}return rule}__name(extractRuleFromCommand,"extractRuleFromCommand");function extractRulesFromStatement(node){switch(node.type){case"command":return[extractRuleFromCommand(node)].filter(Boolean);case"pipeline":case"list":case"compound_statement":case"subshell":{const rules=[];for(const child of node.namedChildren){rules.push(...extractRulesFromStatement(child))}return rules}case"redirected_statement":{const body=node.namedChildren[0];return body?extractRulesFromStatement(body):[]}case"negated_command":{const inner=node.namedChildren[0];return inner?extractRulesFromStatement(inner):[]}case"variable_assignment":case"variable_assignments":return[];default:return[]}}__name(extractRulesFromStatement,"extractRulesFromStatement");async function extractCommandRules(command){if(typeof command!=="string"||!command.trim())return[];const tree=await parseShellCommand(command);const root=tree.rootNode;const rules=[];for(const stmt of root.namedChildren){rules.push(...extractRulesFromStatement(stmt))}tree.delete();return[...new Set(rules)]}__name(extractCommandRules,"extractCommandRules");var debugLogger18=createDebugLogger("MONITOR");var DEFAULT_MAX_EVENTS=1e3;var MAX_MAX_EVENTS=1e4;var DEFAULT_IDLE_TIMEOUT_MS=3e5;var MAX_IDLE_TIMEOUT_MS=6e5;var MAX_DISPLAY_DESCRIPTION_LENGTH=80;var PARTIAL_LINE_BUFFER_CAP=4096;var THROTTLE_BURST_SIZE=5;var THROTTLE_REFILL_INTERVAL_MS=1e3;function truncateDisplayDescription(description){return description.length>MAX_DISPLAY_DESCRIPTION_LENGTH?description.slice(0,MAX_DISPLAY_DESCRIPTION_LENGTH-1)+"\u2026":description}__name(truncateDisplayDescription,"truncateDisplayDescription");var STRUCTURAL_ENVELOPE_TAGS=new Set(["task-notification","task-id","tool-use-id","kind","status","event-count","summary","result","gate-output","gate-stderr"]);var STRUCTURAL_TAG_REGEX=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)>/g;function sanitizeMonitorLine(line2){let cleaned="";for(let i=0;i<line2.length;i++){const code=line2.charCodeAt(i);if(code===9){cleaned+=line2[i];continue}if(code<32)continue;if(code>=128&&code<=159)continue;cleaned+=line2[i]}cleaned=cleaned.replace(STRUCTURAL_TAG_REGEX,(match,slash,tagName)=>{if(!STRUCTURAL_ENVELOPE_TAGS.has(String(tagName).toLowerCase())){return match}return slash==="/"?`</\u200B${tagName}>`:`<\u200B${tagName}>`});return cleaned}__name(sanitizeMonitorLine,"sanitizeMonitorLine");var MonitorToolInvocation=class extends BaseToolInvocation{constructor(config3,params){super(params);this.config=config3}static{__name(this,"MonitorToolInvocation")}callId;setCallId(callId){this.callId=callId}getDescription(){const desc=this.params.description||normalizeMonitorCommand(this.params.command).spawnCommand;return`Monitor: ${truncateDisplayDescription(desc)}`}isDirectoryOutsideWorkspace(){return!!this.params.directory&&!this.config.getWorkspaceContext().isPathWithinWorkspace(this.params.directory)}async getDefaultPermission(){if(this.config.getShellExecutionSandbox?.())return"ask";if(this.isDirectoryOutsideWorkspace())return"ask";const normalized=normalizeMonitorCommand(this.params.command);const command=normalized.safetyCommand;const cwd=this.params.directory||this.config.getTargetDir?.()||process.cwd();try{const isReadOnly=await isShellCommandReadOnlyASTInDirectory(command,cwd);if(isReadOnly){return"allow"}}catch(e){debugLogger18.warn("AST read-only check failed, falling back to ask:",e)}return"ask"}async getConfirmationDetails(_abortSignal){const normalized=normalizeMonitorCommand(this.params.command);const cwd=this.params.directory||this.config.getTargetDir?.()||process.cwd();const subCommands=splitCommands(normalized.safetyCommand);const confirmableSubCommands=[];for(const sub of subCommands){let isReadOnly=false;try{if(!this.config.getShellExecutionSandbox?.())isReadOnly=await isShellCommandReadOnlyASTInDirectory(sub,cwd)}catch(e){debugLogger18.warn("AST read-only check failed for monitor sub-command, falling back to ask:",e)}if(isReadOnly){continue}confirmableSubCommands.push(sub)}const effectiveSubCommands=confirmableSubCommands.length>0?confirmableSubCommands:subCommands;const rootCommands=[...new Set(effectiveSubCommands.map(sub=>getCommandRoot(sub)).filter(sub=>!!sub))];let permissionRules=[];try{const allRules=[];for(const sub of effectiveSubCommands){const rules=await extractCommandRules(sub);allRules.push(...rules)}permissionRules=[...new Set(allRules)].map(rule=>`Monitor(${rule})`)}catch(e){debugLogger18.warn("Failed to extract monitor command rules:",e);permissionRules=[`Monitor(${normalized.safetyCommand})`]}const warnings=[...buildShellExecWarnings(normalized.safetyCommand,this.params.command)??[],...this.params.directory&&this.isDirectoryOutsideWorkspace()?[buildOutsideWorkspaceWarning(this.params.directory)]:[]];const confirmationDetails={type:"exec",title:"Monitor",command:normalized.spawnCommand,rootCommand:rootCommands.join(", ")||(getCommandRoot(normalized.safetyCommand)??normalized.spawnCommand),permissionRules,onConfirm:__name(async(_outcome,_payload)=>{},"onConfirm")};if(warnings.length>0){confirmationDetails.warnings=warnings}return confirmationDetails}async execute(_signal){if(_signal.aborted){return{llmContent:"Monitor was cancelled before it could start.",returnDisplay:"Monitor cancelled."}}const normalized=normalizeMonitorCommand(this.params.command);const command=normalized.spawnCommand;if(normalized.strippedTrailingAmp){debugLogger18.warn("Stripped trailing & from monitor command \u2014 monitor lifecycle handles backgrounding")}const description=sanitizeMonitorLine(this.params.description||command);const displayDescription=truncateDisplayDescription(description);const maxEvents=Math.min(this.params.max_events??DEFAULT_MAX_EVENTS,MAX_MAX_EVENTS);const idleTimeoutMs=Math.min(this.params.idle_timeout_ms??DEFAULT_IDLE_TIMEOUT_MS,MAX_IDLE_TIMEOUT_MS);const monitorId=`mon_${randomUUID7().replace(/-/g,"").slice(0,16)}`;const registry3=this.config.getMonitorRegistry();const ownerAgentId=getCurrentAgentId()??void 0;const running=registry3.getRunning();if(running.length>=MAX_CONCURRENT_MONITORS){const message=`Cannot start monitor: maximum concurrent monitors (${MAX_CONCURRENT_MONITORS}) reached. Stop an existing monitor first.`;return{llmContent:message,returnDisplay:`Monitor rejected: too many concurrent monitors.`,error:{message,type:"execution_failed"}}}const entryAc=new AbortController;const registration={monitorId,command,description,status:"running",startTime:Date.now(),abortController:entryAc,toolUseId:this.callId,eventCount:0,lastEventTime:0,maxEvents,idleTimeoutMs,droppedLines:0,outputFile:getMonitorOutputPath(this.config.storage.getProjectDir(),this.config.getSessionId(),monitorId),...ownerAgentId?{ownerAgentId}:{}};const{executable,argsPrefix}=getShellConfiguration();const sandboxed=Boolean(this.config.getShellExecutionSandbox?.());let child;try{if(!sandboxed)child=spawn(executable,[...argsPrefix,command],{cwd:this.params.directory||this.config.getTargetDir(),stdio:["ignore","pipe","pipe"],detached:true,env:{...sanitizeChildEnv(process.env),QWEN_CODE:"1",TERM:"dumb",...getShellPagerEnv(this.config.getShellExecutionConfig().pager,{includeGitPager:false,platform:os2.platform()}),...getShellContextEnvVars()}})}catch(err){const message=`Monitor failed to start: ${getErrorMessage(err)}`;return{llmContent:message,returnDisplay:`Monitor failed: ${getErrorMessage(err)}`,error:{message,type:"execution_failed"}}}registration.pid=child?.pid;let exited=false;let earlySpawnError;const captureEarlySpawnError=__name(err=>{earlySpawnError??=err},"captureEarlySpawnError");child?.on("error",captureEarlySpawnError);const stdoutBuf={value:""};const stderrBuf={value:""};let tokenBucket=THROTTLE_BURST_SIZE;let lastRefill=Date.now();const throttledEmit=__name(line2=>{const sanitized=sanitizeMonitorLine(line2);if(sanitized.length===0||sanitized.trim().length===0)return;const now=Date.now();const elapsed=now-lastRefill;if(elapsed<0){debugLogger18.warn(`Monitor ${monitorId}: clock moved backwards by ${-elapsed}ms, resetting refill timestamp`);lastRefill=now}else{const newTokens=Math.floor(elapsed/THROTTLE_REFILL_INTERVAL_MS);if(newTokens>0){tokenBucket=Math.min(THROTTLE_BURST_SIZE,tokenBucket+newTokens);lastRefill+=newTokens*THROTTLE_REFILL_INTERVAL_MS}}if(tokenBucket>0){tokenBucket--;registry3.emitEvent(monitorId,sanitized)}else{registration.droppedLines++}},"throttledEmit");const flushPartialLineBuffers=__name(()=>{for(const buf of[stdoutBuf,stderrBuf]){const trimmed=buf.value.trim();if(trimmed.length>0){throttledEmit(trimmed)}buf.value=""}},"flushPartialLineBuffers");const killChildProcessGroup=__name(()=>{const pid=child?.pid;if(exited||!pid)return;if(process.platform==="win32"){const tk=spawn("taskkill",["/pid",pid.toString(),"/f","/t"],{stdio:"ignore"});tk.on("error",err=>debugLogger18.warn(`Monitor taskkill failed for pid ${pid}: ${getErrorMessage(err)}`))}else{try{process.kill(-pid,"SIGTERM")}catch(err){debugLogger18.warn(`Monitor ${monitorId} SIGTERM failed (pid=${pid}): ${getErrorMessage(err)}`)}setTimeout(()=>{if(!exited){try{process.kill(-pid,"SIGKILL")}catch(err){debugLogger18.warn(`Monitor ${monitorId} SIGKILL escalation failed (pid=${pid}): ${getErrorMessage(err)}`)}}},200).unref?.()}},"killChildProcessGroup");const abortHandler=__name(()=>{flushPartialLineBuffers();killChildProcessGroup()},"abortHandler");entryAc.signal.addEventListener("abort",abortHandler,{once:true});if(entryAc.signal.aborted){abortHandler()}try{registry3.register(registration)}catch(err){abortHandler();entryAc.signal.removeEventListener("abort",abortHandler);child?.stdout?.destroy?.();child?.stderr?.destroy?.();child?.removeListener("error",captureEarlySpawnError);child?.on("error",()=>{});const message=`Monitor failed to start: ${getErrorMessage(err)}`;return{llmContent:message,returnDisplay:`Monitor failed: ${getErrorMessage(err)}`,error:{message,type:"execution_failed"}}}const processLines=__name((buffer,data2)=>{if(registration.status!=="running")return;const text3=stripAnsi(typeof data2==="string"?data2:data2.toString("utf-8"));buffer.value+=text3;if(!buffer.value.includes("\n")&&buffer.value.length>PARTIAL_LINE_BUFFER_CAP){const trimmed=buffer.value.trim();if(trimmed.length>0){throttledEmit(trimmed.slice(0,PARTIAL_LINE_BUFFER_CAP)+"...")}buffer.value="";return}const lines=buffer.value.split("\n");buffer.value=lines.pop()??"";for(const line2 of lines){const trimmed=line2.trim();if(trimmed.length===0)continue;const truncated=trimmed.length>PARTIAL_LINE_BUFFER_CAP?trimmed.slice(0,PARTIAL_LINE_BUFFER_CAP)+"...":trimmed;throttledEmit(truncated)}},"processLines");child?.stdout?.on("data",data2=>processLines(stdoutBuf,data2));child?.stderr?.on("data",data2=>processLines(stderrBuf,data2));let cleanedUp=false;const cleanup=__name(()=>{if(cleanedUp)return;cleanedUp=true;flushPartialLineBuffers();entryAc.signal.removeEventListener("abort",abortHandler);if(registration.droppedLines>0){debugLogger18.info(`Monitor ${monitorId} dropped ${registration.droppedLines} lines due to throttling`)}},"cleanup");let exitResult=null;const settleFromExit=__name((code,sig)=>{if(registration.status!=="running")return;if(entryAc.signal.aborted){registry3.cancel(monitorId)}else if(code!==null&&code!==0){registry3.fail(monitorId,`Exit code ${code}`)}else if(sig){registry3.fail(monitorId,`Killed by signal ${sig}`)}else{registry3.complete(monitorId,code)}},"settleFromExit");const onExit=__name((code,sig)=>{exited=true;exitResult={code,sig}},"onExit");const onClose=__name((code,sig)=>{exited=true;cleanup();const result=exitResult??{code,sig};settleFromExit(result.code,result.sig)},"onClose");const onError=__name(err=>{exited=true;cleanup();if(registration.status==="running"){registry3.fail(monitorId,getErrorMessage(err))}},"onError");child?.on("exit",onExit);child?.on("close",onClose);child?.on("error",onError);child?.removeListener("error",captureEarlySpawnError);if(sandboxed){try{const shellExecutionConfig=this.config.getShellExecutionConfig();const handle=await executeRuntimeShell(this.config,command,this.params.directory||this.config.getTargetDir(),event=>{if(event.type==="binary_detected"){if(registration.status==="running"){registry3.fail(monitorId,"Binary output detected");entryAc.abort()}}else if(event.type==="data"&&typeof event.chunk==="string"){processLines(event.stream==="stderr"?stderrBuf:stdoutBuf,event.chunk)}},entryAc.signal,false,{...shellExecutionConfig,maxBufferedOutputBytes:Math.min(shellExecutionConfig.maxBufferedOutputBytes??PARTIAL_LINE_BUFFER_CAP,PARTIAL_LINE_BUFFER_CAP)},{streamStdout:true});registration.pid=handle.pid;void handle.result.then(result=>{exited=true;cleanup();if(result.error){if(registration.status==="running")registry3.fail(monitorId,result.error.message)}else{settleFromExit(result.exitCode,result.signal)}},error3=>onError(error3 instanceof Error?error3:new Error(String(error3))))}catch(error3){onError(error3 instanceof Error?error3:new Error(String(error3)));const message=`Monitor failed to start: ${getErrorMessage(error3)}`;return{llmContent:message,returnDisplay:`Monitor failed: ${getErrorMessage(error3)}`,error:{message,type:"execution_failed"}}}}if(earlySpawnError){onError(earlySpawnError);const message=`Monitor failed to start: ${getErrorMessage(earlySpawnError)}`;return{llmContent:message,returnDisplay:`Monitor failed: ${getErrorMessage(earlySpawnError)}`,error:{message,type:"execution_failed"}}}return{llmContent:`Monitor started.
102
103
  id: ${monitorId}
@@ -165,7 +166,7 @@ ${SESSION_START_CONTEXT_SENTINEL_END}`}__name(buildSessionStartContextBlock,"bui
165
166
  ${SESSION_START_CONTEXT_SENTINEL_START}
166
167
  ${SESSION_START_CONTEXT_HEADER}:
167
168
  `);if(startIndex===-1){return systemInstruction}const endIndex=systemInstruction.indexOf(`
168
- ${SESSION_START_CONTEXT_SENTINEL_END}`,startIndex);if(endIndex===-1){return systemInstruction}return systemInstruction.slice(0,startIndex)}__name(stripTrailingSessionStartContextBlock,"stripTrailingSessionStartContextBlock");var LlmChat=class{constructor(config3,generationConfig={},history=[],chatRecordingService,telemetryService){this.config=config3;this.generationConfig=generationConfig;this.history=history;this.chatRecordingService=chatRecordingService;this.telemetryService=telemetryService;validateHistory(history);markCompressedHistory(history);this.redactApprovedPlansFromLoadedHistory();this.markToolResultsInjected(this.history)}static{__name(this,"LlmChat")}historyReplacementRevision=0;getHistoryReplacementRevision(){return this.historyReplacementRevision}sendPromise=Promise.resolve();memorySnapshotsVisible;unaccountedMemorySnapshots=new WeakSet;lastPromptTokenCount=0;lastPromptTokenCountIsEstimated=false;toolBudgetUsageAnchor;toolBudgetFixedInputVersion=0;injectedToolResults=new WeakSet;lastOutputTokenCount=0;lastCachedContentTokenCount=0;tokenCountsRouteKey=void 0;tokenCountsByRouteKey=new Map;consecutiveFailures=0;hardRescueFailureCount=0;pendingPartialAssistantTurnIndex=null;pendingPartialAssistantRecord=null;lastObservedClosedFinishReason;imagePayloadStore=new InMemoryImagePayloadStore;userContentPushCount=0;manualPlanExitNoticesEnabled=false;completedToolCallIds=[];compressionObserver;compressionObserverOptions;setCompressionObserver(observer,options2){this.compressionObserver=observer;this.compressionObserverOptions=options2}async recordCompression(payload){if(this.compressionObserver){const compressedHistory=[...payload.compressedHistory];const promptIds=compressedHistory.map(content=>getApiHistoryPromptId(content)??null);await this.compressionObserver({...payload,compressedHistory,contextPrefixLength:getStartupContextLength(compressedHistory,{includeCompressed:true}),...promptIds.some(Boolean)?{promptIds}:{}})}this.chatRecordingService?.recordChatCompression(payload)}setCompletedToolCallIds(toolCallIds){this.completedToolCallIds=[...new Set(toolCallIds)].filter(id6=>completedToolCallBoundary(this.history,[id6])>0)}getCompletedToolCallIds(){return[...this.completedToolCallIds]}getHistoryForRecovery(count4){const boundary=recoveryHistoryBoundary(this.history,this.completedToolCallIds);const countAnchor=count4===void 0?this.history.length:effectiveHistoryEnd(this.history);const start=count4===void 0?boundary:Math.max(boundary,countAnchor-Math.max(0,count4));return this.history.slice(start).map(copyContentContainer)}isForkedChat=false;clearPendingPartialState(){this.pendingPartialAssistantTurnIndex=null;this.pendingPartialAssistantRecord=null}popPendingPartialAssistantTurn(){const idx=this.pendingPartialAssistantTurnIndex;if(idx===null)return;if(this.history.length>idx&&this.history[idx]?.role==="model"){this.history.splice(idx,1)}else{debugLogger26.warn(`[PARTIAL_POP] Splice skipped: idx=${idx}, historyLength=${this.history.length}, roleAtIdx=${this.history[idx]?.role??"undefined"}`)}this.clearPendingPartialState()}markToolResultsInjected(contents){for(const content of contents)for(const part of content.parts??[]){const provenance=getToolOutputProvenance(part);if(provenance)this.injectedToolResults.add(provenance)}}enableManualPlanExitNotices(){this.manualPlanExitNoticesEnabled=true}currentRouteKey(){return this.config.getModelRouteIdentity?.()??""}adoptTokenCountsForRoute(targetRouteKey){const memorySnapshotsVisible=Boolean(this.config.getAutoMemoryContext?.());if(this.memorySnapshotsVisible!==true&&memorySnapshotsVisible&&this.history.some(entry=>entry.parts?.some(part=>part.partMetadata?.[AUTO_MEMORY_SNAPSHOT_METADATA]===true))){this.lastPromptTokenCount=0;this.lastPromptTokenCountIsEstimated=false;this.lastOutputTokenCount=0;this.lastCachedContentTokenCount=0;this.tokenCountsByRouteKey.clear();this.telemetryService?.setLastPromptTokenCount(0);this.telemetryService?.setLastCachedContentTokenCount(0)}this.memorySnapshotsVisible=memorySnapshotsVisible;if(this.lastPromptTokenCount===0&&this.lastOutputTokenCount===0&&this.tokenCountsByRouteKey.size===0){return}targetRouteKey??=this.currentRouteKey();if(this.tokenCountsRouteKey===targetRouteKey){return}const retained=this.tokenCountsByRouteKey.get(targetRouteKey);if(retained){this.tokenCountsByRouteKey.delete(targetRouteKey);this.retainCurrentTokenCounts();debugLogger26.debug(`[token-counts] restoring retained counts for route ${targetRouteKey}`);this.lastPromptTokenCount=retained.promptTokenCount;this.lastPromptTokenCountIsEstimated=retained.promptTokenCountIsEstimated;this.lastOutputTokenCount=retained.outputTokenCount;this.lastCachedContentTokenCount=retained.cachedContentTokenCount;this.tokenCountsRouteKey=targetRouteKey;this.telemetryService?.setLastPromptTokenCount(retained.promptTokenCount);this.telemetryService?.setLastCachedContentTokenCount(retained.cachedContentTokenCount);return}debugLogger26.debug(`[token-counts] route changed; retaining counts recorded for ${this.tokenCountsRouteKey??"unknown"} (now ${targetRouteKey})`);this.retainCurrentTokenCounts();this.lastPromptTokenCount=0;this.lastPromptTokenCountIsEstimated=false;this.lastOutputTokenCount=0;this.lastCachedContentTokenCount=0;this.tokenCountsRouteKey=targetRouteKey;this.telemetryService?.setLastPromptTokenCount(0);this.telemetryService?.setLastCachedContentTokenCount(0)}retainCurrentTokenCounts(){if(this.tokenCountsRouteKey===void 0||this.lastPromptTokenCount===0&&this.lastOutputTokenCount===0){return}if(this.tokenCountsByRouteKey.size>=MAX_RETAINED_ROUTE_COUNTS){const oldestKey=this.tokenCountsByRouteKey.keys().next().value;if(oldestKey!==void 0){this.tokenCountsByRouteKey.delete(oldestKey)}}this.tokenCountsByRouteKey.set(this.tokenCountsRouteKey,{promptTokenCount:this.lastPromptTokenCount,promptTokenCountIsEstimated:this.lastPromptTokenCountIsEstimated,outputTokenCount:this.lastOutputTokenCount,cachedContentTokenCount:this.lastCachedContentTokenCount})}getLastPromptTokenCount(targetRouteKey){this.adoptTokenCountsForRoute(targetRouteKey);return this.lastPromptTokenCount}getLastOutputTokenCount(){this.adoptTokenCountsForRoute();return this.lastOutputTokenCount}getLastCachedContentTokenCount(targetRouteKey){this.adoptTokenCountsForRoute(targetRouteKey);return this.lastCachedContentTokenCount}getRequestHistory(currentUserContent,history=this.history){const curatedHistory=extractCuratedHistory(this.config.getAutoMemoryContext?.()?history:withoutAutoMemorySnapshots(history));const{maxRecentImages,imagePayloadThreshold}=resolveCompactionTuning(this.config.getChatCompression());let replaced=[];if(countAllInlineImages(curatedHistory)>=imagePayloadThreshold){const skipEntry=currentUserContent?curatedHistory.find(c=>c===currentUserContent||c.role==="user"&&currentUserContent.parts?.some(p2=>c.parts?.includes(p2))):void 0;replaced=replaceImagePayloadsInPlace(curatedHistory,this.imagePayloadStore,skipEntry)}const requestHistory=curatedHistory.map(copyContentContainer);const reattachParts=buildReattachParts(replaced,maxRecentImages,requestHistory,this.imagePayloadStore);if(reattachParts.length>0){const last=requestHistory.at(-1);if(last?.role==="user"){last.parts=[...last.parts??[],...reattachParts]}else{requestHistory.push({role:"user",parts:reattachParts})}}return requestHistory}getRequestHistoryForRoute(currentUserContent,supportedModalities,retainMemorySnapshot=true){const catalog=this.config.getAutoMemoryContext?.()??"";const snapshot=getAutoMemorySnapshot(this.history,catalog);const history=!snapshot?this.history:retainMemorySnapshot?[...this.history]:withoutAutoMemorySnapshots(this.history);if(snapshot&&retainMemorySnapshot){appendAutoMemorySnapshot(history,snapshot)}const request=slimCompactionInput(this.getRequestHistory(currentUserContent,history),supportedModalities).slimmedHistory;if(snapshot&&retainMemorySnapshot){this.history=history;this.chatRecordingService?.recordMemoryCatalogSnapshot(snapshot);this.unaccountedMemorySnapshots.add(snapshot)}return snapshot&&!retainMemorySnapshot?appendAutoMemoryContext(request,catalog):request}setLastPromptTokenCount(count4,isEstimated=false){this.toolBudgetUsageAnchor=void 0;this.unaccountedMemorySnapshots=new WeakSet;this.memorySnapshotsVisible=Boolean(this.config.getAutoMemoryContext?.());this.lastPromptTokenCount=count4;this.lastPromptTokenCountIsEstimated=isEstimated;this.lastOutputTokenCount=0;this.lastCachedContentTokenCount=0;this.telemetryService?.setLastCachedContentTokenCount(0);this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.delete(this.tokenCountsRouteKey)}isLastPromptTokenCountEstimated(){this.adoptTokenCountsForRoute();return this.lastPromptTokenCountIsEstimated}promptCountIsEstimateDerived(){return this.lastPromptTokenCount===0||this.lastPromptTokenCountIsEstimated}seedResumeTokenCounts(promptTokenCount,outputTokenCount,isEstimated=false){this.toolBudgetUsageAnchor=void 0;this.unaccountedMemorySnapshots=new WeakSet;this.memorySnapshotsVisible=Boolean(this.config.getAutoMemoryContext?.());this.lastPromptTokenCount=Number.isFinite(promptTokenCount)?Math.max(0,promptTokenCount):0;this.lastPromptTokenCountIsEstimated=isEstimated;this.lastOutputTokenCount=Number.isFinite(outputTokenCount)?Math.max(0,outputTokenCount):0;this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.delete(this.tokenCountsRouteKey)}async tryCompress(promptId,force=false,signal,options2){this.adoptTokenCountsForRoute(options2?.requestRouteKey);const originalTokenCountOverride=options2?.originalTokenCountOverride;const originalTokenCountIsEstimated=originalTokenCountOverride!==void 0?originalTokenCountOverride.isEstimated:options2?.precomputedEffectiveTokens!==void 0||this.promptCountIsEstimateDerived();const originalTokenCount=originalTokenCountOverride!==void 0?originalTokenCountOverride.count:originalTokenCountIsEstimated?options2?.precomputedEffectiveTokens??estimateContentTokens(options2?.pendingUserMessage?[...this.getHistoryShallow(true),options2.pendingUserMessage]:this.getHistoryShallow(true),resolveSlimmingConfig(this.config.getChatCompression()).imageTokenEstimate):this.lastPromptTokenCount;debugLogger26.debug(`[compaction] token-count provenance: prompt_id=${promptId}, originalTokenCount=${originalTokenCount}, estimated=${originalTokenCountIsEstimated}`);const service=new ChatCompressionService;const{newHistory,info}=await service.compress(this,{promptId,force,config:this.config,consecutiveFailures:this.consecutiveFailures,originalTokenCount,pendingUserMessage:options2?.pendingUserMessage,precomputedEffectiveTokens:options2?.precomputedEffectiveTokens,observedServerCeiling:options2?.observedServerCeiling,observedServerCeilingKind:options2?.observedServerCeilingKind,requestRouteKey:options2?.requestRouteKey,requestGenerationConfig:options2?.requestGenerationConfig,trigger:options2?.trigger,customInstructions:options2?.customInstructions,requestPayloadTooLarge:options2?.requestPayloadTooLarge,signal,restoreRecentFiles:this.compressionObserverOptions?.restoreRecentFiles});info.originalTokenCountIsEstimated=originalTokenCountIsEstimated;this.adoptTokenCountsForRoute(options2?.requestRouteKey);if(info.compressionStatus===1&&newHistory){info.newTokenCountIsEstimated??=true;if(!options2?.deferChatCompressionRecord){await this.recordCompression({info,compressedHistory:options2?.pendingUserMessage?[...newHistory,options2.pendingUserMessage]:newHistory,summaryPrefixLength:newHistory.length,completedToolCallIds:this.completedToolCallIds})}this.setHistory(newHistory,this.completedToolCallIds);debugLogger26.debug("[FILE_READ_CACHE] clear after auto tryCompress");this.config.getFileReadCache().clear();try{await this.config.getExecutionEnvironment?.()?.invalidateReadCache()}catch(error3){debugLogger26.warn("Execution cache invalidation after compression failed",error3)}this.tokenCountsByRouteKey.clear();this.setLastPromptTokenCount(info.newTokenCount,info.newTokenCountIsEstimated);if(options2?.requestRouteKey&&this.tokenCountsRouteKey!==options2.requestRouteKey){this.retainCurrentTokenCounts();this.tokenCountsRouteKey=options2.requestRouteKey;this.tokenCountsByRouteKey.delete(options2.requestRouteKey)}this.telemetryService?.setLastPromptTokenCount(info.newTokenCount);this.consecutiveFailures=0;this.hardRescueFailureCount=0}else if(isCompressionFailureStatus(info.compressionStatus)){if(!force){this.consecutiveFailures+=1;if(this.consecutiveFailures>=MAX_CONSECUTIVE_FAILURES){debugLogger26.warn(`[compaction] circuit breaker tripped after ${this.consecutiveFailures} consecutive failures (cheap-gate path); auto-compaction will NOOP until a successful force compaction resets the counter.`)}}}return info}compressFast(){this.adoptTokenCountsForRoute();const beforeEstimate=estimateContentTokens(this.history);const projectRoot=this.config.getProjectRoot();const targetDir=this.config.getTargetDir?.()??projectRoot;const mcResult=microcompactHistory(this.history,null,this.config.getClearContextOnIdle(),{force:true,preserveReadFileResult:__name(filePath=>isManagedMemoryPath(filePath,projectRoot,targetDir),"preserveReadFileResult")});const mcMeta=mcResult.meta;const newHistory=mcResult.history.map(c=>c.role==="model"?stripThoughtPartsFromContent(c):c).filter(c=>c!==null);const afterEstimate=estimateContentTokens(newHistory);if(afterEstimate>=beforeEstimate){const apiBaseline2=this.lastPromptTokenCount||beforeEstimate;return{info:{originalTokenCount:apiBaseline2,newTokenCount:apiBaseline2,originalTokenCountIsEstimated:this.promptCountIsEstimateDerived(),compressionStatus:5}}}const reduction=beforeEstimate-afterEstimate;const apiBaseline=this.lastPromptTokenCount||beforeEstimate;const baselineIsEstimated=this.promptCountIsEstimateDerived();const adjustedTokenCount=Math.max(0,apiBaseline-reduction);debugLogger26.debug(`[compaction] fast token-count provenance: originalTokenCount=${apiBaseline}, estimated=${baselineIsEstimated}`);const info={originalTokenCount:apiBaseline,newTokenCount:adjustedTokenCount,originalTokenCountIsEstimated:baselineIsEstimated,newTokenCountIsEstimated:true,compressionStatus:1,triggerReason:"manual"};this.chatRecordingService?.recordChatCompression({info,compressedHistory:newHistory,completedToolCallIds:this.completedToolCallIds});logChatCompression(this.config,makeChatCompressionEvent({tokens_before:info.originalTokenCount,tokens_after:info.newTokenCount}));this.setHistory(newHistory,this.completedToolCallIds);this.lastPromptTokenCount=adjustedTokenCount;this.lastPromptTokenCountIsEstimated=true;this.lastCachedContentTokenCount=0;this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.clear();this.telemetryService?.setLastPromptTokenCount(adjustedTokenCount);this.telemetryService?.setLastCachedContentTokenCount(0);this.consecutiveFailures=0;return{info,microcompactMeta:mcMeta}}setSystemInstruction(sysInstr){if(this.generationConfig.systemInstruction!==sysInstr){this.toolBudgetUsageAnchor=void 0;this.toolBudgetFixedInputVersion++}this.generationConfig.systemInstruction=sysInstr}setSessionStartContext(extraInstruction){const trimmed=extraInstruction.trim();if(!trimmed){return}const current2=this.generationConfig.systemInstruction;let baseInstruction="";if(typeof current2==="string"){baseInstruction=stripTrailingSessionStartContextBlock(current2)}else if(current2){baseInstruction=getCustomSystemPrompt(current2);baseInstruction=stripTrailingSessionStartContextBlock(baseInstruction)}const contextBlock=buildSessionStartContextBlock(trimmed);this.setSystemInstruction(`${baseInstruction}${contextBlock}`)}applySessionStartContext(extraInstruction,_source){const trimmed=extraInstruction.trim();if(!trimmed){return}this.setSessionStartContext(trimmed)}async sendPreparedMessageStream(prepared,promptId,signal,onPreparedRequest){signal.throwIfAborted();if(hasImagePayloadReferences(prepared.history))throw new LlmRequestPreparationError("Saved image payloads are unavailable.");return this.sendMessageStream(`${prepared.routeSelector}\0`,{message:[],config:{...prepared.request.config,abortSignal:signal}},promptId,void 0,{preparedRequest:prepared,onPreparedRequest,retractDeliveredOutputOnRetry:true,disableModelFallbacks:true})}async sendMessageStream(model,params,prompt_id,goalContext,options2){const managedSessionBlock=this.config.getManagedSessionBlock?.();if(managedSessionBlock)throw managedSessionBlock;const turnGoalContext=goalContext?{...goalContext}:void 0;const fullTurnRoute=model.endsWith("\0");const exactRoute=fullTurnRoute?await this.config.getBaseLlmClient().resolveForModel(model.slice(0,-1),{failClosed:true}):void 0;if(exactRoute){model=exactRoute.model}const requestRouteKey=this.config.getModelRouteIdentity(model,exactRoute?.contentGeneratorConfig);this.adoptTokenCountsForRoute(requestRouteKey);const requestModalities=exactRoute?.contentGeneratorConfig.modalities??this.config.getEffectiveInputModalities();await this.sendPromise;let streamDoneResolver;const streamDonePromise=new Promise(resolve36=>{streamDoneResolver=resolve36});this.sendPromise=streamDonePromise;this.clearPendingPartialState();let compressionInfo;let requestContents;let userContentAdded=false;let manualPlanExitNoticeVersion;let manualPlanExitNoticeText;const cgConfigForThresholds=exactRoute?.contentGeneratorConfig??this.config.getContentGeneratorConfig();const parsedEnvMaxTokensForClamp=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);const explicitOutputCeiling=params.config?.maxOutputTokens??cgConfigForThresholds?.samplingParams?.max_tokens??parsedEnvMaxTokensForClamp;const outputCeiling=explicitOutputCeiling??defaultOutputCeiling(model);const contextWindowForClamp=cgConfigForThresholds?.contextWindowSize??DEFAULT_TOKEN_LIMIT;let promptTokensForClamp=0;const previousGenerationConfig=options2?.preparedRequest?this.generationConfig:void 0;let currentUserContent;try{if(options2?.preparedRequest){const saved=options2.preparedRequest;if(saved.request.model!==model||saved.providerPin!==llmPreparedProviderPin(exactRoute?.contentGeneratorConfig??this.config.getContentGeneratorConfig()))throw new LlmRequestPreparationError("Saved model route changed.");const history=cloneApiHistory(saved.history);markCompressedHistory(history,saved.contextPrefixLength);this.setHistory(history,saved.completedToolCallIds);this.generationConfig=structuredClone(saved.request.config);requestContents=structuredClone(saved.request.contents);currentUserContent=this.history.at(-1);promptTokensForClamp=saved.promptTokensForClamp;compressionInfo={originalTokenCount:promptTokensForClamp,newTokenCount:promptTokensForClamp,compressionStatus:5}}else{let userContent=createUserContent(params.message);userContent={...userContent,parts:userContent.parts?.map(part=>part.functionResponse&&!getToolOutputProvenance(part)?attachToolOutputProvenance([part],{callId:part.functionResponse.id??"",toolName:part.functionResponse.name??"",promptId:prompt_id,toolType:part.functionResponse.name?.startsWith("mcp__")?"mcp":"native"})[0]:part)};const{auto,hard}=computeThresholds(contextWindowForClamp,this.config.getAutoCompactThreshold());const imageTokenEstimate=resolveSlimmingConfig(this.config.getChatCompression()).imageTokenEstimate;const estimatePendingPrompt=__name((pending,conservative=false)=>{const catalog=this.config.getAutoMemoryContext?.()??"";const snapshot=getAutoMemorySnapshot([...this.history,pending],catalog);const pendingContent=snapshot?{...pending,parts:[...pending.parts??[],snapshot]}:pending;const visiblePendingContent=catalog?pendingContent:withoutAutoMemorySnapshots([pendingContent])[0]??{...pendingContent,parts:[]};const unaccountedSnapshots=catalog&&this.lastPromptTokenCount>0?this.history.flatMap(entry=>(entry.parts??[]).filter(part=>this.unaccountedMemorySnapshots.has(part))):[];return estimatePromptTokens(this.lastPromptTokenCount>0?[]:this.getHistoryShallow(true),visiblePendingContent,this.lastPromptTokenCount+estimateContentTokens([{role:"user",parts:unaccountedSnapshots}]),this.lastOutputTokenCount,imageTokenEstimate,conservative)},"estimatePendingPrompt");const batchBudget=this.config.getToolOutputBatchBudget?.();const pressureBudget=this.pressureToolOutputBudget(userContent,requestRouteKey,contextWindowForClamp);let toolOutputBudget=batchBudget!==void 0&&!Number.isFinite(batchBudget)?batchBudget:Math.min(batchBudget??Number.POSITIVE_INFINITY,pressureBudget??Number.POSITIVE_INFINITY);if(Number.isFinite(toolOutputBudget)&&(batchBudget===void 0||batchBudget>0)&&userContent.parts){const entries=userContent.parts.map(part=>({callId:`send-boundary-${randomUUID11()}`,toolName:"tool-response-batch",responseParts:[part]}));let preview=enforceFunctionResponseBudget(entries,toolOutputBudget,true,false);if(pressureBudget!==void 0&&pressureBudget<(batchBudget??Number.POSITIVE_INFINITY)){if(preview!==entries&&estimatePendingPrompt({...userContent,parts:preview.flatMap(entry=>entry.responseParts)})>=auto){const aggregateBudget=batchBudget??Number.POSITIVE_INFINITY;const aggregatePreview=enforceFunctionResponseBudget(entries,aggregateBudget,false,false);if(estimatePendingPrompt({...userContent,parts:aggregatePreview.flatMap(entry=>entry.responseParts)})<hard){toolOutputBudget=aggregateBudget;preview=aggregatePreview}}}const cutResults=preview.flatMap((entry,index)=>{const before=entries[index].responseParts[0].functionResponse;const after=entry.responseParts[0].functionResponse;return typeof before?.response?.["output"]==="string"&&before.response["output"]!==after?.response?.["output"]?[before]:[]});const paths=[];let unresolvedRead=false;for(const result of cutResults){const calls=result.id?this.history.flatMap(content=>(content.parts??[]).flatMap(part=>part.functionCall&&part.functionCall.id===result.id?[part.functionCall]:[])):[];const responseName=canonicalToolName(result.name??"");if(!calls.length&&(responseName===ToolNames.READ_FILE||responseName===ToolNames.TOOL_CALL))unresolvedRead=true;for(const call of calls){const identity=getFunctionCallIdentity(call);if(!identity){unresolvedRead=true;continue}if(!FILE_PATH_TOOLS.has(identity.name))continue;const filePath=identity.args["file_path"];if(typeof filePath!=="string"||!filePath)unresolvedRead=true;else paths.push(resolvePath2(this.config.getTargetDir(),unescapePath(filePath.trim())))}}const hookRetargetPossible=cutResults.some(result=>{const name2=canonicalToolName(result.name??"");return(name2===ToolNames.TOOL_CALL||FILE_PATH_TOOLS.has(name2))&&!this.config.getDisableAllHooks?.()&&["PreToolUse","PermissionRequest"].some(event=>this.config.getHookSystem?.()?.hasHooksMatchingTool(event,name2,this.config.getSessionId()))});const guarded=unresolvedRead||hookRetargetPossible?entries:await finalizeToolResponses(this.config,entries,void 0,false,false,toolOutputBudget,false,"send_guard",false);if(guarded!==entries){debugLogger26.warn(`Tool response send guard reduced an unfinalized batch to ${toolOutputBudget} characters.`);userContent={...userContent,parts:guarded.flatMap(entry=>entry.responseParts)};if(paths.length||unresolvedRead){const fileReadCache=this.config.getFileReadCache();const stats=await Promise.all(paths.map(p2=>fs15.promises.stat(p2).catch(()=>void 0)));if(this.isForkedChat){for(let i=0;i<paths.length;i++){const stat15=stats[i];if(!stat15||!fileReadCache.markReadEvictedFromHistory(stat15))fileReadCache.invalidateByPath(paths[i])}}else{for(const stat15 of stats){if(!stat15||!fileReadCache.markReadEvictedFromHistory(stat15))unresolvedRead=true}if(unresolvedRead)fileReadCache.markAllReadsEvictedFromHistory()}if(paths.length>0){try{await this.config.getExecutionEnvironment?.()?.invalidateReadCache(paths)}catch(error3){if(!this.isForkedChat)fileReadCache.clear();debugLogger26.warn("Execution cache invalidation after tool-output shrink failed",error3)}}}if(!this.isForkedChat){clearLoadedSkillTracking(this.config.getToolRegistry(),"send-boundary tool-output shrink")}}}const effectiveTokens=estimatePendingPrompt(userContent);const isHardTier=effectiveTokens>=hard;const shouldForceFromHard=!exactRoute&&isHardTier&&this.hardRescueFailureCount<MAX_CONSECUTIVE_FAILURES;const historyBeforeHardRescue=shouldForceFromHard?this.getHistoryShallow():void 0;const completedToolCallIdsBeforeHardRescue=this.completedToolCallIds;const unaccountedMemorySnapshotsBeforeHardRescue=new WeakSet(historyBeforeHardRescue?.flatMap((entry,index)=>(entry.parts??[]).filter((_2,partIndex)=>this.unaccountedMemorySnapshots.has(this.history[index].parts[partIndex])))??[]);const lastPromptTokenCountBeforeHardRescue=this.lastPromptTokenCount;const lastPromptTokenCountWasEstimatedBeforeHardRescue=this.lastPromptTokenCountIsEstimated;const lastOutputTokenCountBeforeHardRescue=this.lastOutputTokenCount;const lastCachedContentTokenCountBeforeHardRescue=this.lastCachedContentTokenCount;const tokenCountsRouteKeyBeforeHardRescue=this.tokenCountsRouteKey;const retainedTokenCountsBeforeHardRescue=new Map(this.tokenCountsByRouteKey);const hardRescueFailureCountBeforeHardRescue=this.hardRescueFailureCount;if(shouldForceFromHard){debugLogger26.warn(`[compaction] hard-tier rescue triggered: prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}, hardRescueAttempt=${this.hardRescueFailureCount+1}, consecutiveFailures=${this.consecutiveFailures}.`)}else if(isHardTier&&!exactRoute){debugLogger26.warn(`[compaction] hard-tier rescue skipped after ${this.hardRescueFailureCount} failed attempts; relying on reactive overflow recovery. prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}.`)}markApiHistoryPrompt(userContent,options2?.promptId);if(exactRoute||isHardTier&&!shouldForceFromHard){compressionInfo={originalTokenCount:effectiveTokens,newTokenCount:effectiveTokens,compressionStatus:5}}else{compressionInfo=await this.tryCompress(prompt_id,shouldForceFromHard,params.config?.abortSignal,{pendingUserMessage:userContent,precomputedEffectiveTokens:effectiveTokens,requestGenerationConfig:params.config,requestRouteKey,deferChatCompressionRecord:shouldForceFromHard,trigger:shouldForceFromHard?"auto":void 0})}if(options2?.suppressedHookContext&&compressionInfo.compressionStatus===1&&!hasUserPromptSubmitContext(userContent,options2.suppressedHookContext)){userContent.parts=[...userContent.parts??[],createUserPromptSubmitContextPart(options2.suppressedHookContext)]}const localPromptTokensAfterCompression=shouldForceFromHard?estimatePendingPrompt(userContent):0;if(shouldStopAfterHardRescue(shouldForceFromHard,hard,localPromptTokensAfterCompression)){const message=getHardRescueFailureMessage(effectiveTokens,hard,compressionInfo,localPromptTokensAfterCompression);if(shouldForceFromHard){this.hardRescueFailureCount=hardRescueFailureCountBeforeHardRescue+1}if(compressionInfo.compressionStatus===1&&historyBeforeHardRescue){this.setHistory(historyBeforeHardRescue,completedToolCallIdsBeforeHardRescue);this.unaccountedMemorySnapshots=unaccountedMemorySnapshotsBeforeHardRescue;this.lastPromptTokenCount=lastPromptTokenCountBeforeHardRescue;this.lastPromptTokenCountIsEstimated=lastPromptTokenCountWasEstimatedBeforeHardRescue;this.lastOutputTokenCount=lastOutputTokenCountBeforeHardRescue;this.lastCachedContentTokenCount=lastCachedContentTokenCountBeforeHardRescue;this.tokenCountsRouteKey=tokenCountsRouteKeyBeforeHardRescue;this.tokenCountsByRouteKey.clear();for(const[retainedRouteKey,retainedCounts]of retainedTokenCountsBeforeHardRescue){this.tokenCountsByRouteKey.set(retainedRouteKey,retainedCounts)}this.telemetryService?.setLastPromptTokenCount(lastPromptTokenCountBeforeHardRescue);this.telemetryService?.setLastCachedContentTokenCount(lastCachedContentTokenCountBeforeHardRescue)}const compressionStatus=CompressionStatus[compressionInfo.compressionStatus]??String(compressionInfo.compressionStatus);debugLogger26.warn(`[compaction] hard-tier rescue stopped oversized prompt: prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}, localPromptTokensAfterCompression=${localPromptTokensAfterCompression}, compressionStatus=${compressionStatus}, newTokenCount=${compressionInfo.newTokenCount}, hardRescueFailureCount=${this.hardRescueFailureCount}, consecutiveFailures=${this.consecutiveFailures}. ${message}`);throw new Error(message)}if(shouldForceFromHard&&compressionInfo.compressionStatus===1){await this.recordCompression({info:compressionInfo,compressedHistory:[...this.getHistoryShallow(),userContent],summaryPrefixLength:this.getHistoryShallow().length,completedToolCallIds:this.completedToolCallIds})}if(this.manualPlanExitNoticesEnabled){const notice=this.config.takePendingManualPlanExitNotice();if(notice){manualPlanExitNoticeVersion=notice.version;manualPlanExitNoticeText=getManualPlanExitSystemReminder(notice.currentMode);userContent={...userContent,parts:[...userContent.parts??[],{text:manualPlanExitNoticeText}]}}}promptTokensForClamp=this.lastPromptTokenCount===0&&manualPlanExitNoticeVersion===void 0?effectiveTokens:estimatePendingPrompt(userContent,true);if(Array.isArray(params.message)){params.message[userContentPushSnapshotKey]=this.userContentPushCount}this.history.push(userContent);for(const part of userContent.parts??[]){if(part.partMetadata?.[AUTO_MEMORY_SNAPSHOT_METADATA]===true){this.unaccountedMemorySnapshots.add(part)}}this.syncReviewedSchemasForContent(userContent);currentUserContent=userContent;userContentAdded=true;this.userContentPushCount++;const inlineRepair=repairOrphanedToolUseTurns(this.history,ORPHAN_TOOL_USE_REPAIR_REASON);if(inlineRepair.injected.length>0){debugLogger26.warn(`[REPAIR] sendMessageStream inline pass synthesized ${inlineRepair.injected.length} functionResponse(s): `+inlineRepair.injected.map(entry=>`${entry.name}(${entry.callId})`).join(", "))}if(inlineRepair.droppedDuplicates.length>0){debugLogger26.warn(`[REPAIR] sendMessageStream inline pass dropped ${inlineRepair.droppedDuplicates.length} duplicate functionResponse(s): `+inlineRepair.droppedDuplicates.map(entry=>`${entry.name}(${entry.callId})`).join(", "))}if(this.promptCountIsEstimateDerived()){promptTokensForClamp+=ESTIMATE_CLAMP_OVERHEAD_PAD;debugLogger26.debug(`[clamp] estimate-derived prompt count; padded by ${ESTIMATE_CLAMP_OVERHEAD_PAD}: promptTokensForClamp=${promptTokensForClamp}, count=${this.lastPromptTokenCount}`)}const clampedMaxOutputTokens=clampOutputTokensToWindow(outputCeiling,contextWindowForClamp,promptTokensForClamp);params={...params,config:{...params.config,maxOutputTokens:clampedMaxOutputTokens}};requestContents=this.getRequestHistoryForRoute(currentUserContent,requestModalities)}}catch(error3){if(userContentAdded){this.history.pop();if(currentUserContent){this.syncReviewedSchemasForContent(currentUserContent)}this.userContentPushCount--}if(manualPlanExitNoticeVersion!==void 0){this.config.restorePendingManualPlanExitNotice(manualPlanExitNoticeVersion)}if(previousGenerationConfig)this.generationConfig=previousGenerationConfig;streamDoneResolver();throw error3}const self2=this;return(async function*(){let successfulRecoveries=0;let activeRecoveryUser;let pendingTransportPrefix=[];const sleepInhibitorHandle=acquireSleepInhibitor(self2.config,"Qwen Code is streaming a model response");try{if(compressionInfo.compressionStatus===1){yield{type:"compressed",info:compressionInfo}}let lastError=new Error("Request failed after all retries.");let rateLimitRetryCount=0;let transientInvalidStreamRetryCount=0;let protocolTagLeakRetryCount=0;const totalInvalidStreamRetryCount=__name(()=>transientInvalidStreamRetryCount+protocolTagLeakRetryCount,"totalInvalidStreamRetryCount");const rearmQuietAcceptanceIfBudgetSpent=__name(()=>{if(transientInvalidStreamRetryCount>=INVALID_STREAM_RETRY_CONFIG.transientMaxRetries){acceptQuietToolResultCompletionOnNextAttempt=true}},"rearmQuietAcceptanceIfBudgetSpent");let streamReplayRetryCount=0;let transportContinuationCount=0;let transportContinuationText="";let transportContinuationParts=[];let transportAttemptParts=[];let transportContinuationPrefix=[];let reactiveCompressionAttempted=false;let omniMediaDegradeAttempts=0;let suppressNextRetryEvent=false;let streamYieldedAnyChunk=false;const cgConfig=exactRoute?.contentGeneratorConfig??self2.config.getContentGeneratorConfig();const requestOverrides=exactRoute?{contentGenerator:exactRoute.contentGenerator,contentGeneratorConfig:exactRoute.contentGeneratorConfig,retryAuthType:exactRoute.retryAuthType,retryErrorCodes:exactRoute.retryErrorCodes,allowPersistentRetry:options2?.preparedRequest?.allowPersistentRetry===true}:void 0;const maxRateLimitRetries=cgConfig?.maxRetries??RATE_LIMIT_RETRY_OPTIONS.maxRetries;const retryInitialDelayMs=cgConfig?.retryInitialDelayMs??RATE_LIMIT_RETRY_OPTIONS.initialDelayMs;const retryMaxDelayMs=cgConfig?.retryMaxDelayMs??RATE_LIMIT_RETRY_OPTIONS.maxDelayMs;const extraRetryErrorCodes=cgConfig?.retryErrorCodes;let maxTokensEscalated=false;const parsedEnvMaxTokens=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);const hasUserMaxTokensOverride=cgConfig?.samplingParams?.max_tokens!==void 0&&cgConfig?.samplingParams?.max_tokens!==null||parsedEnvMaxTokens!==void 0;const effectiveInitialMaxOutputTokens=params.config?.maxOutputTokens??outputCeiling;const escalatedLimit=clampOutputTokensToWindow(OUTPUT_TOKEN_CEILING,contextWindowForClamp,promptTokensForClamp);const shouldEscalateMaxOutputTokens=effectiveInitialMaxOutputTokens<escalatedLimit;let lastFinishReason;const buildAttemptContents=__name(()=>transportContinuationPrefix.length>0?[...requestContents,{role:"model",parts:transportContinuationPrefix},createUserContent([{text:buildRecoveryMessageFromText(TRANSPORT_CONTINUATION_MESSAGE,getPlainTextFromParts(transportContinuationPrefix))}])]:requestContents,"buildAttemptContents");const resetTransportContinuation=__name(()=>{transportContinuationCount=0;transportContinuationText="";transportContinuationParts=[];transportAttemptParts=[];transportContinuationPrefix=[];pendingTransportPrefix=[]},"resetTransportContinuation");const foldTransportAttemptText=__name(()=>{transportContinuationParts=mergeDeliveredParts(transportContinuationParts,consolidateModelResponseParts(transportAttemptParts));transportContinuationText=getPlainTextFromParts(transportContinuationParts);transportAttemptParts=[]},"foldTransportAttemptText");let acceptQuietToolResultCompletionOnNextAttempt=false;for(;;){transportAttemptParts=[];let streamEstablished=false;let streamYieldedChunk=false;let streamYieldedContentChunk=false;let streamYieldedFunctionCall=false;try{if(suppressNextRetryEvent){suppressNextRetryEvent=false}else if(rateLimitRetryCount>0||totalInvalidStreamRetryCount()>0||streamReplayRetryCount>0||transportContinuationCount>0){resetTransportContinuation();yield{type:"retry"}}const acceptQuietToolResultCompletion=acceptQuietToolResultCompletionOnNextAttempt;acceptQuietToolResultCompletionOnNextAttempt=false;const stream=await self2.makeApiCallAndProcessStream(model,buildAttemptContents(),params,prompt_id,requestOverrides,requestRouteKey,turnGoalContext,transportContinuationPrefix.length>0?transportContinuationPrefix:void 0,acceptQuietToolResultCompletion,options2?.onPreparedRequest,promptTokensForClamp,false,options2?.onModelRequestDispatched);streamEstablished=true;pendingTransportPrefix=[];lastFinishReason=void 0;self2.lastObservedClosedFinishReason=void 0;for await(const chunk of stream){if(isFlushedToolCallPark(chunk)&&!streamYieldedContentChunk&&transportContinuationText.trim().length===0){continue}if(hasCandidateOutput(chunk)){streamYieldedChunk=true;streamYieldedAnyChunk=true}if(hasNonThoughtCandidateParts(chunk)){streamYieldedContentChunk=true}const chunkParts=chunk.candidates?.[0]?.content?.parts;transportAttemptParts.push(...(chunkParts??[]).filter(isPlainTextPart).map(part=>({...part})));if(chunkParts?.some(part=>part.functionCall)){streamYieldedFunctionCall=true}const fr2=chunk.candidates?.[0]?.finishReason;if(fr2)lastFinishReason=fr2;yield{type:"chunk",value:chunk}}lastError=null;transportContinuationPrefix=[];break}catch(error3){if(error3 instanceof LlmRequestPreparationError)throw error3;lastError=error3;if(params.config?.abortSignal?.aborted)throw error3;foldTransportAttemptText();const classification=classifyRetryError(error3,{authType:cgConfig?.authType,extraRetryErrorCodes});if(isQuotaExhaustedError(error3)){debugLogger26.warn("Quota exhausted mid-stream, fast-failing",{retryPath:"stream",retryDecision:"fail-fast",errorKind:classification.kind,classificationReason:classification.reason});throw new Error(formatQuotaExhaustedMessage(error3),{cause:error3})}if(error3 instanceof ResponsesHttpError&&error3.headers.get("x-should-retry")==="false"){throw error3}const isRateLimit=isRateLimitError(error3,extraRetryErrorCodes);if(isRateLimit){const details=getRateLimitErrorDetails(error3);const diagnosticFields={classificationDiagnosis:classification.diagnosis,errorKind:classification.kind,classificationReason:classification.reason,...details};if(rateLimitRetryCount<maxRateLimitRetries){self2.popPendingPartialAssistantTurn();rateLimitRetryCount++;const delayMs=getRateLimitRetryDelayMs(rateLimitRetryCount,{...RATE_LIMIT_RETRY_OPTIONS,initialDelayMs:retryInitialDelayMs,maxDelayMs:retryMaxDelayMs,error:error3});const message=parseAndFormatApiError(error3 instanceof Error?error3.message:String(error3));debugLogger26.warn("Rate limit retry scheduled",{retryPath:"stream",retryDecision:"retry",attempt:rateLimitRetryCount,maxRetries:maxRateLimitRetries,retryDelayMs:delayMs,...diagnosticFields});const{promise:delayPromise,skip}=delay3(delayMs,params.config?.abortSignal);resetTransportContinuation();yield{type:"retry",retryInfo:{message,attempt:rateLimitRetryCount,maxRetries:maxRateLimitRetries,delayMs,skipDelay:skip}};await delayPromise;rearmQuietAcceptanceIfBudgetSpent();continue}debugLogger26.warn("Rate limit retry exhausted",{retryPath:"stream",retryDecision:"exhausted",attempts:rateLimitRetryCount,maxRetries:maxRateLimitRetries,...diagnosticFields})}const contextOverflow=getContextLengthExceededInfo(error3);const requestPayloadOverflow=getRequestPayloadTooLargeInfo(error3);const isServerStreamError=streamEstablished&&!isRateLimit&&(classification.kind==="http"||classification.kind==="sse-provider")&&classification.diagnosis==="retryable"&&classification.statusCode!==void 0&&classification.statusCode>=500&&classification.statusCode<600;const isContinuableStreamCut=isRetryableStreamTransportError(classification)||isRetryableStatuslessUpstreamError(classification)&&!contextOverflow.isExceeded&&!requestPayloadOverflow.isTooLarge;const isReplayableStreamError=isContinuableStreamCut||isServerStreamError;const replayAdmitsDeliveredContent=options2?.retractDeliveredOutputOnRetry===true;if(isReplayableStreamError&&(replayAdmitsDeliveredContent||!streamYieldedContentChunk&&transportContinuationText.trim().length===0)&&streamReplayRetryCount<STREAM_RETRY_CONFIG.maxRetries){self2.popPendingPartialAssistantTurn();streamReplayRetryCount++;const delayMs=STREAM_RETRY_CONFIG.initialDelayMs*streamReplayRetryCount;debugLogger26.warn(isServerStreamError?"Server stream retry scheduled":"Transport stream retry scheduled",{retryPath:"stream",retryDecision:"retry",attempt:streamReplayRetryCount,maxRetries:STREAM_RETRY_CONFIG.maxRetries,retryDelayMs:delayMs,yieldedNonContentChunks:streamYieldedChunk,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,...isServerStreamError&&{statusCode:classification.statusCode}});yield{type:"retry",retryDiagnostics:toRetryDiagnostics(classification)};resetTransportContinuation();suppressNextRetryEvent=true;await delay3(delayMs,params.config?.abortSignal).promise;rearmQuietAcceptanceIfBudgetSpent();continue}const attemptFinishReason=lastFinishReason??self2.lastObservedClosedFinishReason;const attemptClosedWithOwnOutput=attemptFinishReason!==void 0&&CLOSED_FINISH_REASONS.has(attemptFinishReason)&&streamYieldedContentChunk;const canContinueAfterTransportCut=isContinuableStreamCut&&!replayAdmitsDeliveredContent&&!attemptClosedWithOwnOutput&&!streamYieldedFunctionCall&&transportContinuationText.trim().length>0&&transportContinuationCount<STREAM_RETRY_CONFIG.maxContinuationRetries;if(canContinueAfterTransportCut){self2.popPendingPartialAssistantTurn();transportContinuationCount++;transportContinuationPrefix=transportContinuationParts;pendingTransportPrefix=transportContinuationPrefix;const delayMs=STREAM_RETRY_CONFIG.initialDelayMs*transportContinuationCount;debugLogger26.warn("Transport stream continuation scheduled",{retryPath:"stream",retryDecision:"continue",attempt:transportContinuationCount,maxRetries:STREAM_RETRY_CONFIG.maxContinuationRetries,retryDelayMs:delayMs,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,deliveredChars:transportContinuationText.length});yield{type:"retry",retryDiagnostics:toRetryDiagnostics(classification),isContinuation:true};suppressNextRetryEvent=true;await delay3(delayMs,params.config?.abortSignal).promise;rearmQuietAcceptanceIfBudgetSpent();continue}if(isReplayableStreamError){debugLogger26.warn(isServerStreamError?"Server stream retry not taken":"Transport stream retry not taken",{retryPath:"stream",retryDecision:attemptClosedWithOwnOutput?"skipped_terminal_finish_reason":streamYieldedContentChunk||transportContinuationText.trim().length>0?"skipped_after_content":"exhausted",attempts:streamReplayRetryCount,maxRetries:STREAM_RETRY_CONFIG.maxRetries,continuationAttempts:transportContinuationCount,maxContinuationRetries:STREAM_RETRY_CONFIG.maxContinuationRetries,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,...isServerStreamError&&{statusCode:classification.statusCode}})}if(contextOverflow.isExceeded||requestPayloadOverflow.isTooLarge){const omniDegradeMaxAttempts=self2.config.getOmniProcessingConfig?.()?.limits.maxTransportPasses??0;if(contextOverflow.isExceeded&&!exactRoute&&omniMediaDegradeAttempts<omniDegradeMaxAttempts){const degradeAttempt=omniMediaDegradeAttempts++;let degradeOutcome;try{const{degradeOmniMediaAfterServerReject}=await import("./reactive-degrade-3OM3HWVA.js");degradeOutcome=await degradeOmniMediaAfterServerReject(self2.config,self2.history,degradeAttempt,{signal:params.config?.abortSignal,observedLimitTokens:contextOverflow.limitTokens})}catch(degradeError){if(params.config?.abortSignal?.aborted||isAbortError(degradeError)){throw degradeError}debugLogger26.warn("Omni media degradation fallback failed.",degradeError)}if(degradeOutcome&&degradeOutcome.replacedParts>0){self2.popPendingPartialAssistantTurn();requestContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities);debugLogger26.warn(`Server input limit exceeded; degraded ${degradeOutcome.degradedResources} omni media resource(s) in place (attempt ${degradeAttempt+1}/${omniDegradeMaxAttempts}); retrying.`);resetTransportContinuation();yield{type:"retry"};suppressNextRetryEvent=true;rearmQuietAcceptanceIfBudgetSpent();continue}}let attemptedPayloadRecovery=false;let payloadRecoveryNoop=false;let payloadRecoveryThrew=false;if(!exactRoute&&!reactiveCompressionAttempted){reactiveCompressionAttempted=true;attemptedPayloadRecovery=requestPayloadOverflow.isTooLarge;const reactiveOriginalTokenCountIsEstimated=contextOverflow.actualTokens===void 0;const reactiveOriginalTokenCount=contextOverflow.actualTokens??contextOverflow.limitTokens??(requestPayloadOverflow.isTooLarge?estimateContentTokens(self2.getHistoryShallow(true),resolveSlimmingConfig(self2.config.getChatCompression()).imageTokenEstimate):cgConfig?.contextWindowSize??DEFAULT_TOKEN_LIMIT);debugLogger26.warn(requestPayloadOverflow.isTooLarge?"Request body rejected with HTTP 413; attempting reactive compression.":"Context length exceeded; attempting reactive compression.");if(!streamYieldedFunctionCall){pendingTransportPrefix=transportContinuationParts}try{const reactiveInfo=await self2.tryCompress(prompt_id,true,params.config?.abortSignal,{originalTokenCountOverride:{count:reactiveOriginalTokenCount,isEstimated:reactiveOriginalTokenCountIsEstimated},precomputedEffectiveTokens:reactiveOriginalTokenCount,observedServerCeiling:contextOverflow.limitTokens,observedServerCeilingKind:contextOverflow.limitKind,requestGenerationConfig:params.config,requestRouteKey,trigger:"auto",requestPayloadTooLarge:requestPayloadOverflow.isTooLarge});if(reactiveInfo.compressionStatus===1){self2.popPendingPartialAssistantTurn();const noticeText=manualPlanExitNoticeText;if(noticeText&&!self2.history.some(content=>content.parts?.some(part=>part.text?.includes(noticeText)))){const lastContent=self2.history.at(-1);if(lastContent?.role==="user"){lastContent.parts=[...lastContent.parts??[],{text:noticeText}]}else{self2.history.push(createUserContent([{text:noticeText}]))}}if(options2?.suppressedHookContext){const lastContent=self2.history.at(-1);const hookContextPart=createUserPromptSubmitContextPart(options2.suppressedHookContext);if(lastContent?.role==="user"){lastContent.parts=[...lastContent.parts??[],hookContextPart]}else{self2.history.push(createUserContent([hookContextPart]))}}requestContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities);debugLogger26.info(`Reactive compression succeeded: ${reactiveInfo.originalTokenCount} -> ${reactiveInfo.newTokenCount} tokens.`);yield{type:"compressed",info:reactiveInfo};resetTransportContinuation();yield{type:"retry"};suppressNextRetryEvent=true;rearmQuietAcceptanceIfBudgetSpent();continue}if(reactiveInfo.compressionStatus===5){payloadRecoveryNoop=true}debugLogger26.warn(requestPayloadOverflow.isTooLarge?`Reactive compression did not recover request payload overflow: status=${reactiveInfo.compressionStatus}.`:`Reactive compression did not recover context overflow: status=${reactiveInfo.compressionStatus}.`);if(isCompressionFailureStatus(reactiveInfo.compressionStatus)){if(requestPayloadOverflow.isTooLarge&&reactiveInfo.compressionStatus===7){payloadRecoveryThrew=true}self2.consecutiveFailures+=1;if(self2.consecutiveFailures>=MAX_CONSECUTIVE_FAILURES){debugLogger26.warn(`[compaction] circuit breaker tripped after ${self2.consecutiveFailures} consecutive failures (reactive overflow path); auto-compaction will NOOP on the cheap-gate until a successful force compaction resets the counter.`)}}}catch(compressionError){if(params.config?.abortSignal?.aborted||isAbortError(compressionError)){throw compressionError}payloadRecoveryThrew=requestPayloadOverflow.isTooLarge;debugLogger26.warn("Reactive compression failed.",compressionError)}}else{attemptedPayloadRecovery=requestPayloadOverflow.isTooLarge&&reactiveCompressionAttempted&&!exactRoute;debugLogger26.warn(requestPayloadOverflow.isTooLarge?"Reactive compression already attempted; propagating the request payload overflow error to caller.":"Reactive compression already attempted; propagating the context overflow error to caller.")}if(attemptedPayloadRecovery){if(payloadRecoveryThrew){debugLogger26.warn("Request payload overflow recovery failed transiently; propagating the original 413 so the next send can retry recovery.")}else{debugLogger26.warn("Request payload overflow recovery exhausted; surfacing actionable 413 error.");const actionableError=new Error(payloadRecoveryNoop?REQUEST_PAYLOAD_TOO_LARGE_NOOP_MESSAGE:REQUEST_PAYLOAD_TOO_LARGE_RECOVERY_MESSAGE,{cause:error3});const payloadStatus=requestPayloadOverflow.status;if(payloadStatus!==void 0){Object.assign(actionableError,{status:payloadStatus})}lastError=actionableError}}break}if(error3 instanceof InvalidStreamError&&(error3.type==="NO_TOOL_RESULT_PROGRESS_MAX_TOKENS"||error3.type==="NO_RESPONSE_TEXT"&&lastFinishReason===FinishReason.MAX_TOKENS)&&!maxTokensEscalated&&!hasUserMaxTokensOverride&&shouldEscalateMaxOutputTokens){lastError=null;lastFinishReason=FinishReason.MAX_TOKENS;break}const isInvalidStreamError=error3 instanceof InvalidStreamError;const maxInvalidStreamRetries=isInvalidStreamError&&error3.type==="PROTOCOL_TAG_LEAK"?INVALID_STREAM_RETRY_CONFIG.protocolTagLeakMaxRetries:INVALID_STREAM_RETRY_CONFIG.transientMaxRetries;const invalidStreamRetryCount=isInvalidStreamError&&error3.type==="PROTOCOL_TAG_LEAK"?protocolTagLeakRetryCount:transientInvalidStreamRetryCount;if(isInvalidStreamError&&invalidStreamRetryCount<maxInvalidStreamRetries){self2.popPendingPartialAssistantTurn();const nextInvalidStreamRetryCount=invalidStreamRetryCount+1;if(error3.type==="PROTOCOL_TAG_LEAK"){protocolTagLeakRetryCount=nextInvalidStreamRetryCount}else{transientInvalidStreamRetryCount=nextInvalidStreamRetryCount}rearmQuietAcceptanceIfBudgetSpent();const delayMs=INVALID_STREAM_RETRY_CONFIG.initialDelayMs*nextInvalidStreamRetryCount;debugLogger26.warn(`Invalid stream [${error3.type}] (retry ${nextInvalidStreamRetryCount}/${maxInvalidStreamRetries}). Waiting ${delayMs/1e3}s before retrying...`);logContentRetry(self2.config,new ContentRetryEvent(nextInvalidStreamRetryCount-1,error3.type,delayMs,model));yield{type:"retry"};await delay3(delayMs,params.config?.abortSignal).promise;continue}break}}const rollbackRecoveryAttempt=__name(()=>{const expectedIdx=self2.pendingPartialAssistantTurnIndex;const lastIdx=self2.history.length-1;if(expectedIdx!==null&&self2.history.length>0&&self2.history[lastIdx]?.role==="model"){if(expectedIdx!==lastIdx){debugLogger26.warn(`[RECOVERY_POP] Marker/last-index mismatch: marker=${expectedIdx}, lastIdx=${lastIdx}, historyLength=${self2.history.length}. Popping last entry as best-effort rollback \u2014 investigate any history mutation between processStreamResponse's partial push and this catch.`)}self2.history.pop();self2.clearPendingPartialState()}if(self2.history.length>0&&self2.history[self2.history.length-1].role==="user"){self2.history.pop()}},"rollbackRecoveryAttempt");const streamWithInvalidStreamRetries=__name(async function*(buildAttempt,retryEvent={type:"retry"}){let transientRetryCount=0;let protocolTagLeakRetryCount2=0;let acceptQuietToolResultCompletionOnNextAttempt2=false;for(;;){const attemptState=buildAttempt();try{const acceptQuietToolResultCompletion=acceptQuietToolResultCompletionOnNextAttempt2;acceptQuietToolResultCompletionOnNextAttempt2=false;const stream=await self2.makeApiCallAndProcessStream(model,attemptState.requestContents,attemptState.params,prompt_id,requestOverrides,requestRouteKey,turnGoalContext,void 0,acceptQuietToolResultCompletion,options2?.onPreparedRequest,promptTokensForClamp,retryEvent.isContinuation===true,options2?.onModelRequestDispatched);for await(const chunk of stream){yield{type:"chunk",value:chunk}}return}catch(error3){if(attemptState.params.config?.abortSignal?.aborted)throw error3;attemptState.rollback();if(!(error3 instanceof InvalidStreamError))throw error3;const maxContinuationRetries=error3.type==="PROTOCOL_TAG_LEAK"?INVALID_STREAM_RETRY_CONFIG.protocolTagLeakMaxRetries:INVALID_STREAM_RETRY_CONFIG.transientMaxRetries;const continuationRetryCount=error3.type==="PROTOCOL_TAG_LEAK"?protocolTagLeakRetryCount2:transientRetryCount;if(continuationRetryCount>=maxContinuationRetries){throw error3}const nextContinuationRetryCount=continuationRetryCount+1;if(error3.type==="PROTOCOL_TAG_LEAK"){protocolTagLeakRetryCount2=nextContinuationRetryCount}else{transientRetryCount=nextContinuationRetryCount}if(transientRetryCount>=INVALID_STREAM_RETRY_CONFIG.transientMaxRetries){acceptQuietToolResultCompletionOnNextAttempt2=true}const delayMs=INVALID_STREAM_RETRY_CONFIG.initialDelayMs*nextContinuationRetryCount;debugLogger26.warn(`Invalid stream [${error3.type}] during output continuation (retry ${nextContinuationRetryCount}/${maxContinuationRetries}). Waiting ${delayMs/1e3}s before retrying...`);logContentRetry(self2.config,new ContentRetryEvent(nextContinuationRetryCount-1,error3.type,delayMs,model));yield retryEvent;await delay3(delayMs,attemptState.params.config?.abortSignal).promise}}},"streamWithInvalidStreamRetries");if(lastError===null&&lastFinishReason===FinishReason.MAX_TOKENS&&!maxTokensEscalated&&!hasUserMaxTokensOverride){maxTokensEscalated=true;let recoveryFinishReason=lastFinishReason;let recoveryParams=params;if(shouldEscalateMaxOutputTokens){debugLogger26.info(`Output truncated at ${effectiveInitialMaxOutputTokens} tokens. Escalating to ${escalatedLimit} tokens.`);if(self2.history.length>0&&self2.history[self2.history.length-1].role==="model"){self2.history.pop()}yield{type:"retry",maxOutputTokensEscalated:escalatedLimit};const escalatedParams={...params,config:{...params.config,maxOutputTokens:escalatedLimit}};recoveryParams=escalatedParams;recoveryFinishReason=void 0;for await(const event of streamWithInvalidStreamRetries(()=>({requestContents,params:escalatedParams,rollback:__name(()=>self2.popPendingPartialAssistantTurn(),"rollback")}))){if(event.type==="retry"){yield event;continue}const fr2=event.value.candidates?.[0]?.finishReason;if(fr2)recoveryFinishReason=fr2;yield event}}else{debugLogger26.info(`Output truncated at ${effectiveInitialMaxOutputTokens} tokens; skipping no-op escalation to ${escalatedLimit} tokens and running recovery.`)}let recoveryCount=0;while(recoveryFinishReason===FinishReason.MAX_TOKENS&&recoveryCount<MAX_OUTPUT_RECOVERY_ATTEMPTS){const lastEntry=self2.history[self2.history.length-1];const hasFunctionCall=lastEntry?.role==="model"&&lastEntry.parts?.some(p2=>p2.functionCall)===true;if(hasFunctionCall){debugLogger26.info("Skipping recovery: truncated turn contains functionCall; deferring to tool scheduler fallback.");break}recoveryCount++;debugLogger26.info(`Output still truncated after max_tokens handling. Recovery attempt ${recoveryCount}/${MAX_OUTPUT_RECOVERY_ATTEMPTS}.`);const recoveryUserContent=createUserContent([{text:buildOutputRecoveryMessage(lastEntry)}]);yield{type:"retry",isContinuation:true};recoveryFinishReason=void 0;const recoveryImageTokenEstimate=resolveSlimmingConfig(self2.config.getChatCompression()).imageTokenEstimate;const countBasedRecoveryEstimate=self2.lastPromptTokenCount>0?estimatePromptTokens([],recoveryUserContent,self2.lastPromptTokenCount,self2.lastOutputTokenCount,recoveryImageTokenEstimate,true):0;self2.history.push(recoveryUserContent);const recoveryContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities,false);self2.history.pop();const walkRecoveryEstimate=estimateContentTokens(recoveryContents,recoveryImageTokenEstimate)+ESTIMATE_CLAMP_OVERHEAD_PAD;const recoveryPromptEstimate=Math.max(countBasedRecoveryEstimate,walkRecoveryEstimate);const recoveryCeiling=recoveryParams.config?.maxOutputTokens??outputCeiling;const iterationParams={...recoveryParams,config:{...recoveryParams.config,maxOutputTokens:clampOutputTokensToWindow(recoveryCeiling,contextWindowForClamp,recoveryPromptEstimate)}};try{for await(const event of streamWithInvalidStreamRetries(()=>{self2.history.push(recoveryUserContent);activeRecoveryUser=recoveryUserContent;return{requestContents:self2.getRequestHistoryForRoute(currentUserContent,requestModalities,false),params:iterationParams,rollback:rollbackRecoveryAttempt}},{type:"retry",isContinuation:true})){if(event.type==="retry"){yield event;continue}const fr2=event.value.candidates?.[0]?.finishReason;if(fr2)recoveryFinishReason=fr2;yield event}successfulRecoveries++;activeRecoveryUser=void 0}catch(recoveryError){if(recoveryError instanceof LlmRequestPreparationError)throw recoveryError;if(params.config?.abortSignal?.aborted)throw recoveryError;rollbackRecoveryAttempt();debugLogger26.warn(`Recovery attempt ${recoveryCount} failed: ${recoveryError}`);yield{type:"chunk",value:{candidates:[{content:{role:"model",parts:[]},finishReason:FinishReason.STOP}]}};break}}}if(lastError){if(lastError instanceof InvalidStreamError){const totalAttempts=totalInvalidStreamRetryCount()+1;logContentRetryFailure(self2.config,new ContentRetryFailureEvent(totalAttempts,lastError.type,model))}const fallbackModels=exactRoute||options2?.disableModelFallbacks?[]:self2.config.getModelFallbacks();if(fallbackModels.length>0&&!isUnattendedMode()&&!streamYieldedAnyChunk){let currentErrorClassification=classifyRetryError(lastError,{authType:cgConfig?.authType,extraRetryErrorCodes});if(isFallbackEligible(currentErrorClassification)){let fallbackSucceeded=false;let fallbackIndex=0;let currentModel=model;let currentResolvedModel=cgConfig?.model??model;let fallbackStreamYieldedAnyChunk=false;for(const fallbackModelId of fallbackModels){if(fallbackModelId===model||fallbackModelId===currentModel){debugLogger26.warn(`[FALLBACK] Skipping fallback model "${fallbackModelId}": same as current model.`);continue}let fallbackGenerator;let fallbackConfig;let fallbackRetryAuthType;let fallbackRetryErrorCodes;let resolvedFallbackModel;let fallbackModalities;try{const resolved=await self2.config.getBaseLlmClient().resolveForModel(fallbackModelId,{failClosed:true});fallbackGenerator=resolved.contentGenerator;fallbackConfig=resolved.contentGeneratorConfig;fallbackRetryAuthType=resolved.retryAuthType;fallbackRetryErrorCodes=resolved.retryErrorCodes;resolvedFallbackModel=resolved.model;fallbackModalities=resolved.contentGeneratorConfig?.modalities}catch(resolveError){if(isAbortError(resolveError))throw resolveError;const resolveErrorMessage=resolveError instanceof Error?resolveError.message:String(resolveError);debugLogger26.warn(`[FALLBACK] Failed to resolve fallback model "${fallbackModelId}": ${resolveErrorMessage}. Trying next fallback.`);continue}if(resolvedFallbackModel===currentResolvedModel){debugLogger26.warn(`[FALLBACK] Skipping fallback model "${fallbackModelId}": resolved model "${resolvedFallbackModel}" matches the current model.`);continue}fallbackIndex++;debugLogger26.warn(`[FALLBACK] Model "${currentModel}" exhausted retries (reason: ${currentErrorClassification.reason}, status: ${currentErrorClassification.statusCode??"unknown"}). Switching to fallback model "${fallbackModelId}" (${fallbackIndex}/${fallbackModels.length}).`);yield{type:"model_fallback",info:{fromModel:currentModel,toModel:resolvedFallbackModel,statusCode:currentErrorClassification.statusCode,fallbackIndex}};self2.popPendingPartialAssistantTurn();let currentFallbackYieldedAnyChunk=false;try{const fallbackRequestContents=self2.getRequestHistoryForRoute(currentUserContent,fallbackModalities??{});for await(const event of self2.makeFallbackStream(resolvedFallbackModel,fallbackRequestContents,params,prompt_id,fallbackGenerator,fallbackRetryAuthType,fallbackRetryErrorCodes,requestRouteKey,turnGoalContext,options2?.onPreparedRequest,promptTokensForClamp,fallbackConfig,options2?.onModelRequestDispatched)){const emittedUserVisibleOutput=event.type!=="chunk"||hasCandidateOutput(event.value);if(emittedUserVisibleOutput){currentFallbackYieldedAnyChunk=true;fallbackStreamYieldedAnyChunk=true}yield event}lastError=null;fallbackSucceeded=true;debugLogger26.info(`[FALLBACK] Successfully completed request with fallback model "${resolvedFallbackModel}".`);return}catch(fallbackError){if(fallbackError instanceof LlmRequestPreparationError)throw fallbackError;if(params.config?.abortSignal?.aborted||isAbortError(fallbackError)){throw fallbackError}lastError=fallbackError;if(currentFallbackYieldedAnyChunk){self2.popPendingPartialAssistantTurn();debugLogger26.warn(`[FALLBACK] Fallback model "${resolvedFallbackModel}" failed after emitting output. Popped the partial assistant turn and stopped the fallback chain to avoid duplicating user-visible output.`);break}const fallbackClassification=classifyRetryError(fallbackError,{authType:fallbackRetryAuthType,extraRetryErrorCodes:fallbackRetryErrorCodes});const canTryNextFallback=isFallbackEligible(fallbackClassification);debugLogger26.warn(`[FALLBACK] Fallback model "${resolvedFallbackModel}" also failed (reason: ${fallbackClassification.reason}, status: ${fallbackClassification.statusCode??"unknown"}). ${canTryNextFallback?"Checking remaining fallbacks.":"Stopping fallback chain."}`);currentModel=resolvedFallbackModel;currentResolvedModel=resolvedFallbackModel;currentErrorClassification=fallbackClassification;if(!canTryNextFallback){debugLogger26.warn(`[FALLBACK] Error from "${resolvedFallbackModel}" is not fallback-eligible (${fallbackClassification.reason}). Stopping fallback chain.`);break}}}if(!fallbackSucceeded){if(!fallbackStreamYieldedAnyChunk){self2.popPendingPartialAssistantTurn()}debugLogger26.warn("[FALLBACK] Fallback chain exhausted without success. Throwing last error.")}}else{debugLogger26.warn(`[FALLBACK] Fallback chain skipped: primary error is not fallback-eligible (reason: ${currentErrorClassification.reason}, diagnosis: ${currentErrorClassification.diagnosis}, status: ${currentErrorClassification.statusCode??"unknown"}, error: ${lastError instanceof Error?lastError.message:String(lastError)}).`)}}else if(fallbackModels.length>0&&!isUnattendedMode()&&streamYieldedAnyChunk){debugLogger26.warn("[FALLBACK] Fallback chain skipped because the primary model already emitted user-visible output.")}if(lastError){throw lastError}}}finally{if(params.config?.abortSignal?.aborted&&pendingTransportPrefix.length>0){const parts=pendingTransportPrefix;self2.history.push({role:"model",parts});self2.pendingPartialAssistantTurnIndex=self2.history.length-1;self2.pendingPartialAssistantRecord={model,message:parts,contextWindowSize:self2.config.getContentGeneratorConfig()?.contextWindowSize,...turnGoalContext?{goalContext:{...turnGoalContext}}:{}}}const recoveryIndex=activeRecoveryUser?self2.history.indexOf(activeRecoveryUser):-1;if(recoveryIndex===self2.history.length-1&&recoveryIndex>=0){self2.history.pop()}else if(recoveryIndex>=0&&recoveryIndex===self2.history.length-2&&self2.history.at(-1)?.role==="model"){successfulRecoveries++}if(successfulRecoveries>0){self2.coalesceRecoveryPairs(successfulRecoveries)}if(previousGenerationConfig){self2.toolBudgetUsageAnchor=void 0;self2.toolBudgetFixedInputVersion++;self2.generationConfig=previousGenerationConfig}sleepInhibitorHandle.release();streamDoneResolver();if(self2.pendingPartialAssistantRecord){try{self2.chatRecordingService?.recordAssistantTurn(self2.pendingPartialAssistantRecord)}catch(recordErr){debugLogger26.error("[PARTIAL_FLUSH] Failed to persist deferred JSONL record: "+(recordErr instanceof Error?recordErr.message:String(recordErr)))}self2.clearPendingPartialState()}}})()}async makeApiCallAndProcessStream(model,requestContents,params,prompt_id,overrides,routeKey=this.currentRouteKey(),goalContext,transportContinuationPrefix,acceptQuietToolResultCompletion=false,onPreparedRequest,promptTokensForClamp=0,continuationInFlight=false,onModelRequestDispatched){const generator=overrides?.contentGenerator??this.config.getContentGenerator();const fixedInputVersion=this.toolBudgetFixedInputVersion;const request={model,contents:requestContents,config:{...this.generationConfig,...params.config},...transportContinuationPrefix!==void 0&&{continuationInFlight:true}};const actualConfig=overrides?.contentGeneratorConfig??this.config.getContentGeneratorConfig();if(onPreparedRequest){const{abortSignal:_signal,httpOptions:_http,...config3}=request.config??{};try{const prepared={request:{model,contents:requestContents,config:config3},history:this.history,contextPrefixLength:getStartupContextLength(this.history,{includeCompressed:true}),completedToolCallIds:[...this.completedToolCallIds],routeSelector:`${actualConfig?.authType??""}:${model}`,providerPin:llmPreparedProviderPin(actualConfig),promptTokensForClamp,allowPersistentRetry:overrides?.allowPersistentRetry??!overrides};const overBudget=onPreparedRequest.maxSnapshotBytes!==void 0&&Buffer.byteLength(JSON.stringify(prepared))>onPreparedRequest.maxSnapshotBytes;await onPreparedRequest(overBudget?prepared:structuredClone(prepared),continuationInFlight||transportContinuationPrefix!==void 0||hasImagePayloadReferences(this.history))}catch(cause){throw new LlmRequestPreparationError(cause)}}params.config?.abortSignal?.throwIfAborted();const apiCall=__name(()=>{this.toolBudgetUsageAnchor=void 0;params.config?.abortSignal?.throwIfAborted();const groups=new Map;for(const content of requestContents)for(const part of content.parts??[]){const provenance=getToolOutputProvenance(part);if(!provenance||this.injectedToolResults.has(provenance))continue;const parts=groups.get(provenance)??[];parts.push(part);groups.set(provenance,parts)}for(const[provenance,parts]of groups){this.injectedToolResults.add(provenance);try{const injected=measureToolOutput(parts,this.config);logToolResultSize(this.config,new ToolResultSizeEvent(provenance.toolName,provenance.toolType,"injection",provenance.rawSize?.chars,injected.chars,provenance.rawSize?.estimatedTokens,injected.estimatedTokens,provenance.truncated,Number.isFinite(provenance.budget)?provenance.budget:void 0,provenance.budgetSource,provenance.callId,provenance.promptId||prompt_id))}catch{}}onModelRequestDispatched?.();return generator.generateContentStream(request,prompt_id)},"apiCall");const cgConfig=this.config.getContentGeneratorConfig();const authType=overrides?.retryAuthType??cgConfig?.authType;const extraRetryErrorCodes=overrides?.retryErrorCodes??cgConfig?.retryErrorCodes;const persistentMode=(overrides?.allowPersistentRetry??!overrides)&&isUnattendedMode();const streamResponse=await retryWithBackoff(apiCall,{shouldRetryOnError:__name(error3=>{if(error3 instanceof ResponsesHttpError){return error3.shouldRetry(extraRetryErrorCodes)}if(error3 instanceof Error){if(isSchemaDepthError(error3.message))return false;if(isInvalidArgumentError(error3.message))return false}const status=getErrorStatus(error3);if(status===400){return classifyRetryError(error3,{authType,extraRetryErrorCodes}).kind==="transport"}if(status===429)return true;if(status&&status>=500&&status<600)return true;return isRetryableUpstreamError(error3,extraRetryErrorCodes)},"shouldRetryOnError"),authType,extraRetryErrorCodes,persistentMode,signal:params.config?.abortSignal,...persistentMode?{heartbeatFn:__name(info=>{process.stderr.write(`[qwen-code] Waiting for API capacity... attempt ${info.attempt}, retry in ${Math.ceil(info.remainingMs/1e3)}s
169
+ ${SESSION_START_CONTEXT_SENTINEL_END}`,startIndex);if(endIndex===-1){return systemInstruction}return systemInstruction.slice(0,startIndex)}__name(stripTrailingSessionStartContextBlock,"stripTrailingSessionStartContextBlock");var LlmChat=class{constructor(config3,generationConfig={},history=[],chatRecordingService,telemetryService){this.config=config3;this.generationConfig=generationConfig;this.history=history;this.chatRecordingService=chatRecordingService;this.telemetryService=telemetryService;validateHistory(history);markCompressedHistory(history);this.redactApprovedPlansFromLoadedHistory();this.markToolResultsInjected(this.history)}static{__name(this,"LlmChat")}historyReplacementRevision=0;getHistoryReplacementRevision(){return this.historyReplacementRevision}sendPromise=Promise.resolve();memorySnapshotsVisible;unaccountedMemorySnapshots=new WeakSet;lastPromptTokenCount=0;lastPromptTokenCountIsEstimated=false;toolBudgetUsageAnchor;toolBudgetFixedInputVersion=0;injectedToolResults=new WeakSet;lastOutputTokenCount=0;lastCachedContentTokenCount=0;tokenCountsRouteKey=void 0;tokenCountsByRouteKey=new Map;consecutiveFailures=0;hardRescueFailureCount=0;pendingPartialAssistantTurnIndex=null;pendingPartialAssistantRecord=null;lastObservedClosedFinishReason;imagePayloadStore=new InMemoryImagePayloadStore;userContentPushCount=0;manualPlanExitNoticesEnabled=false;completedToolCallIds=[];compressionObserver;compressionObserverOptions;setCompressionObserver(observer,options2){this.compressionObserver=observer;this.compressionObserverOptions=options2}async recordCompression(payload){if(this.compressionObserver){const compressedHistory=[...payload.compressedHistory];const promptIds=compressedHistory.map(content=>getApiHistoryPromptId(content)??null);await this.compressionObserver({...payload,compressedHistory,contextPrefixLength:getStartupContextLength(compressedHistory,{includeCompressed:true}),...promptIds.some(Boolean)?{promptIds}:{}})}this.chatRecordingService?.recordChatCompression(payload)}setCompletedToolCallIds(toolCallIds){this.completedToolCallIds=[...new Set(toolCallIds)].filter(id6=>completedToolCallBoundary(this.history,[id6])>0)}getCompletedToolCallIds(){return[...this.completedToolCallIds]}getHistoryForRecovery(count4){const boundary=recoveryHistoryBoundary(this.history,this.completedToolCallIds);const countAnchor=count4===void 0?this.history.length:effectiveHistoryEnd(this.history);const start=count4===void 0?boundary:Math.max(boundary,countAnchor-Math.max(0,count4));return this.history.slice(start).map(copyContentContainer)}isForkedChat=false;clearPendingPartialState(){this.pendingPartialAssistantTurnIndex=null;this.pendingPartialAssistantRecord=null}popPendingPartialAssistantTurn(){const idx=this.pendingPartialAssistantTurnIndex;if(idx===null)return;if(this.history.length>idx&&this.history[idx]?.role==="model"){this.history.splice(idx,1)}else{debugLogger26.warn(`[PARTIAL_POP] Splice skipped: idx=${idx}, historyLength=${this.history.length}, roleAtIdx=${this.history[idx]?.role??"undefined"}`)}this.clearPendingPartialState()}markToolResultsInjected(contents){for(const content of contents)for(const part of content.parts??[]){const provenance=getToolOutputProvenance(part);if(provenance)this.injectedToolResults.add(provenance)}}enableManualPlanExitNotices(){this.manualPlanExitNoticesEnabled=true}currentRouteKey(){return this.config.getModelRouteIdentity?.()??""}adoptTokenCountsForRoute(targetRouteKey){const memorySnapshotsVisible=Boolean(this.config.getAutoMemoryContext?.());if(this.memorySnapshotsVisible!==true&&memorySnapshotsVisible&&this.history.some(entry=>entry.parts?.some(part=>part.partMetadata?.[AUTO_MEMORY_SNAPSHOT_METADATA]===true))){this.lastPromptTokenCount=0;this.lastPromptTokenCountIsEstimated=false;this.lastOutputTokenCount=0;this.lastCachedContentTokenCount=0;this.tokenCountsByRouteKey.clear();this.telemetryService?.setLastPromptTokenCount(0);this.telemetryService?.setLastCachedContentTokenCount(0)}this.memorySnapshotsVisible=memorySnapshotsVisible;if(this.lastPromptTokenCount===0&&this.lastOutputTokenCount===0&&this.tokenCountsByRouteKey.size===0){return}targetRouteKey??=this.currentRouteKey();if(this.tokenCountsRouteKey===targetRouteKey){return}const retained=this.tokenCountsByRouteKey.get(targetRouteKey);if(retained){this.tokenCountsByRouteKey.delete(targetRouteKey);this.retainCurrentTokenCounts();debugLogger26.debug(`[token-counts] restoring retained counts for route ${targetRouteKey}`);this.lastPromptTokenCount=retained.promptTokenCount;this.lastPromptTokenCountIsEstimated=retained.promptTokenCountIsEstimated;this.lastOutputTokenCount=retained.outputTokenCount;this.lastCachedContentTokenCount=retained.cachedContentTokenCount;this.tokenCountsRouteKey=targetRouteKey;this.telemetryService?.setLastPromptTokenCount(retained.promptTokenCount);this.telemetryService?.setLastCachedContentTokenCount(retained.cachedContentTokenCount);return}debugLogger26.debug(`[token-counts] route changed; retaining counts recorded for ${this.tokenCountsRouteKey??"unknown"} (now ${targetRouteKey})`);this.retainCurrentTokenCounts();this.lastPromptTokenCount=0;this.lastPromptTokenCountIsEstimated=false;this.lastOutputTokenCount=0;this.lastCachedContentTokenCount=0;this.tokenCountsRouteKey=targetRouteKey;this.telemetryService?.setLastPromptTokenCount(0);this.telemetryService?.setLastCachedContentTokenCount(0)}retainCurrentTokenCounts(){if(this.tokenCountsRouteKey===void 0||this.lastPromptTokenCount===0&&this.lastOutputTokenCount===0){return}if(this.tokenCountsByRouteKey.size>=MAX_RETAINED_ROUTE_COUNTS){const oldestKey=this.tokenCountsByRouteKey.keys().next().value;if(oldestKey!==void 0){this.tokenCountsByRouteKey.delete(oldestKey)}}this.tokenCountsByRouteKey.set(this.tokenCountsRouteKey,{promptTokenCount:this.lastPromptTokenCount,promptTokenCountIsEstimated:this.lastPromptTokenCountIsEstimated,outputTokenCount:this.lastOutputTokenCount,cachedContentTokenCount:this.lastCachedContentTokenCount})}getLastPromptTokenCount(targetRouteKey){this.adoptTokenCountsForRoute(targetRouteKey);return this.lastPromptTokenCount}getLastOutputTokenCount(){this.adoptTokenCountsForRoute();return this.lastOutputTokenCount}getLastCachedContentTokenCount(targetRouteKey){this.adoptTokenCountsForRoute(targetRouteKey);return this.lastCachedContentTokenCount}getRequestHistory(currentUserContent,history=this.history){const curatedHistory=extractCuratedHistory(this.config.getAutoMemoryContext?.()?history:withoutAutoMemorySnapshots(history));const{maxRecentImages,imagePayloadThreshold}=resolveCompactionTuning(this.config.getChatCompression());let replaced=[];if(countAllInlineImages(curatedHistory)>=imagePayloadThreshold){const skipEntry=currentUserContent?curatedHistory.find(c=>c===currentUserContent||c.role==="user"&&currentUserContent.parts?.some(p2=>c.parts?.includes(p2))):void 0;replaced=replaceImagePayloadsInPlace(curatedHistory,this.imagePayloadStore,skipEntry)}const requestHistory=curatedHistory.map(copyContentContainer);const reattachParts=buildReattachParts(replaced,maxRecentImages,requestHistory,this.imagePayloadStore);if(reattachParts.length>0){const last=requestHistory.at(-1);if(last?.role==="user"){last.parts=[...last.parts??[],...reattachParts]}else{requestHistory.push({role:"user",parts:reattachParts})}}return requestHistory}getRequestHistoryForRoute(currentUserContent,supportedModalities,retainMemorySnapshot=true){const catalog=this.config.getAutoMemoryContext?.()??"";const snapshot=getAutoMemorySnapshot(this.history,catalog);const history=!snapshot?this.history:retainMemorySnapshot?[...this.history]:withoutAutoMemorySnapshots(this.history);if(snapshot&&retainMemorySnapshot){appendAutoMemorySnapshot(history,snapshot)}const request=slimCompactionInput(this.getRequestHistory(currentUserContent,history),supportedModalities).slimmedHistory;if(snapshot&&retainMemorySnapshot){this.history=history;this.chatRecordingService?.recordMemoryCatalogSnapshot(snapshot);this.unaccountedMemorySnapshots.add(snapshot)}return snapshot&&!retainMemorySnapshot?appendAutoMemoryContext(request,catalog):request}setLastPromptTokenCount(count4,isEstimated=false){this.toolBudgetUsageAnchor=void 0;this.unaccountedMemorySnapshots=new WeakSet;this.memorySnapshotsVisible=Boolean(this.config.getAutoMemoryContext?.());this.lastPromptTokenCount=count4;this.lastPromptTokenCountIsEstimated=isEstimated;this.lastOutputTokenCount=0;this.lastCachedContentTokenCount=0;this.telemetryService?.setLastCachedContentTokenCount(0);this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.delete(this.tokenCountsRouteKey)}isLastPromptTokenCountEstimated(){this.adoptTokenCountsForRoute();return this.lastPromptTokenCountIsEstimated}promptCountIsEstimateDerived(){return this.lastPromptTokenCount===0||this.lastPromptTokenCountIsEstimated}seedResumeTokenCounts(promptTokenCount,outputTokenCount,isEstimated=false){this.toolBudgetUsageAnchor=void 0;this.unaccountedMemorySnapshots=new WeakSet;this.memorySnapshotsVisible=Boolean(this.config.getAutoMemoryContext?.());this.lastPromptTokenCount=Number.isFinite(promptTokenCount)?Math.max(0,promptTokenCount):0;this.lastPromptTokenCountIsEstimated=isEstimated;this.lastOutputTokenCount=Number.isFinite(outputTokenCount)?Math.max(0,outputTokenCount):0;this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.delete(this.tokenCountsRouteKey)}async tryCompress(promptId,force=false,signal,options2){this.adoptTokenCountsForRoute(options2?.requestRouteKey);const originalTokenCountOverride=options2?.originalTokenCountOverride;const originalTokenCountIsEstimated=originalTokenCountOverride!==void 0?originalTokenCountOverride.isEstimated:options2?.precomputedEffectiveTokens!==void 0||this.promptCountIsEstimateDerived();const originalTokenCount=originalTokenCountOverride!==void 0?originalTokenCountOverride.count:originalTokenCountIsEstimated?options2?.precomputedEffectiveTokens??estimateContentTokens(options2?.pendingUserMessage?[...this.getHistoryShallow(true),options2.pendingUserMessage]:this.getHistoryShallow(true),resolveSlimmingConfig(this.config.getChatCompression()).imageTokenEstimate):this.lastPromptTokenCount;debugLogger26.debug(`[compaction] token-count provenance: prompt_id=${promptId}, originalTokenCount=${originalTokenCount}, estimated=${originalTokenCountIsEstimated}`);const service=new ChatCompressionService;const{newHistory,info}=await service.compress(this,{promptId,force,config:this.config,consecutiveFailures:this.consecutiveFailures,originalTokenCount,pendingUserMessage:options2?.pendingUserMessage,precomputedEffectiveTokens:options2?.precomputedEffectiveTokens,observedServerCeiling:options2?.observedServerCeiling,observedServerCeilingKind:options2?.observedServerCeilingKind,requestRouteKey:options2?.requestRouteKey,requestGenerationConfig:options2?.requestGenerationConfig,trigger:options2?.trigger,customInstructions:options2?.customInstructions,requestPayloadTooLarge:options2?.requestPayloadTooLarge,signal,restoreRecentFiles:this.compressionObserverOptions?.restoreRecentFiles});info.originalTokenCountIsEstimated=originalTokenCountIsEstimated;this.adoptTokenCountsForRoute(options2?.requestRouteKey);if(info.compressionStatus===1&&newHistory){info.newTokenCountIsEstimated??=true;if(!options2?.deferChatCompressionRecord){await this.recordCompression({info,compressedHistory:options2?.pendingUserMessage?[...newHistory,options2.pendingUserMessage]:newHistory,summaryPrefixLength:newHistory.length,completedToolCallIds:this.completedToolCallIds})}this.setHistory(newHistory,this.completedToolCallIds);debugLogger26.debug("[FILE_READ_CACHE] clear after auto tryCompress");this.config.getFileReadCache().clear();try{await this.config.getExecutionEnvironment?.()?.invalidateReadCache()}catch(error3){debugLogger26.warn("Execution cache invalidation after compression failed",error3)}this.tokenCountsByRouteKey.clear();this.setLastPromptTokenCount(info.newTokenCount,info.newTokenCountIsEstimated);if(options2?.requestRouteKey&&this.tokenCountsRouteKey!==options2.requestRouteKey){this.retainCurrentTokenCounts();this.tokenCountsRouteKey=options2.requestRouteKey;this.tokenCountsByRouteKey.delete(options2.requestRouteKey)}this.telemetryService?.setLastPromptTokenCount(info.newTokenCount);this.consecutiveFailures=0;this.hardRescueFailureCount=0}else if(isCompressionFailureStatus(info.compressionStatus)){if(!force){this.consecutiveFailures+=1;if(this.consecutiveFailures>=MAX_CONSECUTIVE_FAILURES){debugLogger26.warn(`[compaction] circuit breaker tripped after ${this.consecutiveFailures} consecutive failures (cheap-gate path); auto-compaction will NOOP until a successful force compaction resets the counter.`)}}}return info}compressFast(){this.adoptTokenCountsForRoute();const beforeEstimate=estimateContentTokens(this.history);const projectRoot=this.config.getProjectRoot();const targetDir=this.config.getTargetDir?.()??projectRoot;const mcResult=microcompactHistory(this.history,null,this.config.getClearContextOnIdle(),{force:true,preserveReadFileResult:__name(filePath=>isManagedMemoryPath(filePath,projectRoot,targetDir),"preserveReadFileResult")});const mcMeta=mcResult.meta;const newHistory=mcResult.history.map(c=>c.role==="model"?stripThoughtPartsFromContent(c):c).filter(c=>c!==null);const afterEstimate=estimateContentTokens(newHistory);if(afterEstimate>=beforeEstimate){const apiBaseline2=this.lastPromptTokenCount||beforeEstimate;return{info:{originalTokenCount:apiBaseline2,newTokenCount:apiBaseline2,originalTokenCountIsEstimated:this.promptCountIsEstimateDerived(),compressionStatus:5}}}const reduction=beforeEstimate-afterEstimate;const apiBaseline=this.lastPromptTokenCount||beforeEstimate;const baselineIsEstimated=this.promptCountIsEstimateDerived();const adjustedTokenCount=Math.max(0,apiBaseline-reduction);debugLogger26.debug(`[compaction] fast token-count provenance: originalTokenCount=${apiBaseline}, estimated=${baselineIsEstimated}`);const info={originalTokenCount:apiBaseline,newTokenCount:adjustedTokenCount,originalTokenCountIsEstimated:baselineIsEstimated,newTokenCountIsEstimated:true,compressionStatus:1,triggerReason:"manual"};this.chatRecordingService?.recordChatCompression({info,compressedHistory:newHistory,completedToolCallIds:this.completedToolCallIds});logChatCompression(this.config,makeChatCompressionEvent({tokens_before:info.originalTokenCount,tokens_after:info.newTokenCount}));this.setHistory(newHistory,this.completedToolCallIds);this.lastPromptTokenCount=adjustedTokenCount;this.lastPromptTokenCountIsEstimated=true;this.lastCachedContentTokenCount=0;this.tokenCountsRouteKey=this.currentRouteKey();this.tokenCountsByRouteKey.clear();this.telemetryService?.setLastPromptTokenCount(adjustedTokenCount);this.telemetryService?.setLastCachedContentTokenCount(0);this.consecutiveFailures=0;return{info,microcompactMeta:mcMeta}}setSystemInstruction(sysInstr){if(this.generationConfig.systemInstruction!==sysInstr){this.toolBudgetUsageAnchor=void 0;this.toolBudgetFixedInputVersion++}this.generationConfig.systemInstruction=sysInstr}setSessionStartContext(extraInstruction){const trimmed=extraInstruction.trim();if(!trimmed){return}const current2=this.generationConfig.systemInstruction;let baseInstruction="";if(typeof current2==="string"){baseInstruction=stripTrailingSessionStartContextBlock(current2)}else if(current2){baseInstruction=getCustomSystemPrompt(current2);baseInstruction=stripTrailingSessionStartContextBlock(baseInstruction)}const contextBlock=buildSessionStartContextBlock(trimmed);this.setSystemInstruction(`${baseInstruction}${contextBlock}`)}applySessionStartContext(extraInstruction,_source){const trimmed=extraInstruction.trim();if(!trimmed){return}this.setSessionStartContext(trimmed)}async sendPreparedMessageStream(prepared,promptId,signal,onPreparedRequest){signal.throwIfAborted();if(hasImagePayloadReferences(prepared.history))throw new LlmRequestPreparationError("Saved image payloads are unavailable.");return this.sendMessageStream(`${prepared.routeSelector}\0`,{message:[],config:{...prepared.request.config,abortSignal:signal}},promptId,void 0,{preparedRequest:prepared,onPreparedRequest,retractDeliveredOutputOnRetry:true,disableModelFallbacks:true})}async sendMessageStream(model,params,prompt_id,goalContext,options2){const managedSessionBlock=this.config.getManagedSessionBlock?.();if(managedSessionBlock)throw managedSessionBlock;const turnGoalContext=goalContext?{...goalContext}:void 0;const fullTurnRoute=model.endsWith("\0");const exactRoute=fullTurnRoute?await this.config.getBaseLlmClient().resolveForModel(model.slice(0,-1),{failClosed:true}):void 0;if(exactRoute){model=exactRoute.model}const requestRouteKey=this.config.getModelRouteIdentity(model,exactRoute?.contentGeneratorConfig);this.adoptTokenCountsForRoute(requestRouteKey);const requestModalities=exactRoute?.contentGeneratorConfig.modalities??this.config.getEffectiveInputModalities();await this.sendPromise;let streamDoneResolver;const streamDonePromise=new Promise(resolve36=>{streamDoneResolver=resolve36});this.sendPromise=streamDonePromise;this.clearPendingPartialState();let compressionInfo;let requestContents;let userContentAdded=false;let manualPlanExitNoticeVersion;let manualPlanExitNoticeText;const cgConfigForThresholds=exactRoute?.contentGeneratorConfig??this.config.getContentGeneratorConfig();const parsedEnvMaxTokensForClamp=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);const explicitOutputCeiling=params.config?.maxOutputTokens??cgConfigForThresholds?.samplingParams?.max_tokens??parsedEnvMaxTokensForClamp;const outputCeiling=explicitOutputCeiling??defaultOutputCeiling(model);const contextWindowForClamp=cgConfigForThresholds?.contextWindowSize??DEFAULT_TOKEN_LIMIT;let promptTokensForClamp=0;const previousGenerationConfig=options2?.preparedRequest?this.generationConfig:void 0;let currentUserContent;try{if(options2?.preparedRequest){const saved=options2.preparedRequest;if(saved.request.model!==model||saved.providerPin!==llmPreparedProviderPin(exactRoute?.contentGeneratorConfig??this.config.getContentGeneratorConfig()))throw new LlmRequestPreparationError("Saved model route changed.");const history=cloneApiHistory(saved.history);markCompressedHistory(history,saved.contextPrefixLength);this.setHistory(history,saved.completedToolCallIds);this.generationConfig=structuredClone(saved.request.config);requestContents=structuredClone(saved.request.contents);currentUserContent=this.history.at(-1);promptTokensForClamp=saved.promptTokensForClamp;compressionInfo={originalTokenCount:promptTokensForClamp,newTokenCount:promptTokensForClamp,compressionStatus:5}}else{let userContent=createUserContent(params.message);userContent={...userContent,parts:userContent.parts?.map(part=>part.functionResponse&&!getToolOutputProvenance(part)?attachToolOutputProvenance([part],{callId:part.functionResponse.id??"",toolName:part.functionResponse.name??"",promptId:prompt_id,toolType:part.functionResponse.name?.startsWith("mcp__")?"mcp":"native"})[0]:part)};const{auto,hard}=computeThresholds(contextWindowForClamp,this.config.getAutoCompactThreshold());const imageTokenEstimate=resolveSlimmingConfig(this.config.getChatCompression()).imageTokenEstimate;const estimatePendingPrompt=__name((pending,conservative=false)=>{const catalog=this.config.getAutoMemoryContext?.()??"";const snapshot=getAutoMemorySnapshot([...this.history,pending],catalog);const pendingContent=snapshot?{...pending,parts:[...pending.parts??[],snapshot]}:pending;const visiblePendingContent=catalog?pendingContent:withoutAutoMemorySnapshots([pendingContent])[0]??{...pendingContent,parts:[]};const unaccountedSnapshots=catalog&&this.lastPromptTokenCount>0?this.history.flatMap(entry=>(entry.parts??[]).filter(part=>this.unaccountedMemorySnapshots.has(part))):[];return estimatePromptTokens(this.lastPromptTokenCount>0?[]:this.getHistoryShallow(true),visiblePendingContent,this.lastPromptTokenCount+estimateContentTokens([{role:"user",parts:unaccountedSnapshots}]),this.lastOutputTokenCount,imageTokenEstimate,conservative)},"estimatePendingPrompt");const batchBudget=this.config.getToolOutputBatchBudget?.();const pressureBudget=this.pressureToolOutputBudget(userContent,requestRouteKey,contextWindowForClamp);let toolOutputBudget=batchBudget!==void 0&&!Number.isFinite(batchBudget)?batchBudget:Math.min(batchBudget??Number.POSITIVE_INFINITY,pressureBudget??Number.POSITIVE_INFINITY);if(Number.isFinite(toolOutputBudget)&&(batchBudget===void 0||batchBudget>0)&&userContent.parts){const entries=userContent.parts.map(part=>({callId:`send-boundary-${randomUUID11()}`,toolName:"tool-response-batch",responseParts:[part]}));let preview=enforceFunctionResponseBudget(entries,toolOutputBudget,true,false);if(pressureBudget!==void 0&&pressureBudget<(batchBudget??Number.POSITIVE_INFINITY)){if(preview!==entries&&estimatePendingPrompt({...userContent,parts:preview.flatMap(entry=>entry.responseParts)})>=auto){const aggregateBudget=batchBudget??Number.POSITIVE_INFINITY;const aggregatePreview=enforceFunctionResponseBudget(entries,aggregateBudget,false,false);if(estimatePendingPrompt({...userContent,parts:aggregatePreview.flatMap(entry=>entry.responseParts)})<hard){toolOutputBudget=aggregateBudget;preview=aggregatePreview}}}const cutResults=preview.flatMap((entry,index)=>{const before=entries[index].responseParts[0].functionResponse;const after=entry.responseParts[0].functionResponse;return typeof before?.response?.["output"]==="string"&&before.response["output"]!==after?.response?.["output"]?[before]:[]});const paths=[];let unresolvedRead=false;for(const result of cutResults){const calls=result.id?this.history.flatMap(content=>(content.parts??[]).flatMap(part=>part.functionCall&&part.functionCall.id===result.id?[part.functionCall]:[])):[];const responseName=canonicalToolName(result.name??"");if(!calls.length&&(responseName===ToolNames.READ_FILE||responseName===ToolNames.TOOL_CALL))unresolvedRead=true;for(const call of calls){const identity=getFunctionCallIdentity(call);if(!identity){unresolvedRead=true;continue}if(!FILE_PATH_TOOLS.has(identity.name))continue;const filePath=identity.args["file_path"];if(typeof filePath!=="string"||!filePath)unresolvedRead=true;else paths.push(resolvePath2(this.config.getTargetDir(),unescapePath(filePath.trim())))}}const hookRetargetPossible=cutResults.some(result=>{const name2=canonicalToolName(result.name??"");return(name2===ToolNames.TOOL_CALL||FILE_PATH_TOOLS.has(name2))&&!this.config.getDisableAllHooks?.()&&["PreToolUse","PermissionRequest"].some(event=>this.config.getHookSystem?.()?.hasHooksMatchingTool(event,name2,this.config.getSessionId()))});const guarded=unresolvedRead||hookRetargetPossible?entries:await finalizeToolResponses(this.config,entries,void 0,false,false,toolOutputBudget,false,"send_guard",false);if(guarded!==entries){debugLogger26.warn(`Tool response send guard reduced an unfinalized batch to ${toolOutputBudget} characters.`);userContent={...userContent,parts:guarded.flatMap(entry=>entry.responseParts)};if(paths.length||unresolvedRead){const fileReadCache=this.config.getFileReadCache();const stats=await Promise.all(paths.map(p2=>fs15.promises.stat(p2).catch(()=>void 0)));if(this.isForkedChat){for(let i=0;i<paths.length;i++){const stat15=stats[i];if(!stat15||!fileReadCache.markReadEvictedFromHistory(stat15))fileReadCache.invalidateByPath(paths[i])}}else{for(const stat15 of stats){if(!stat15||!fileReadCache.markReadEvictedFromHistory(stat15))unresolvedRead=true}if(unresolvedRead)fileReadCache.markAllReadsEvictedFromHistory()}if(paths.length>0){try{await this.config.getExecutionEnvironment?.()?.invalidateReadCache(paths)}catch(error3){if(!this.isForkedChat)fileReadCache.clear();debugLogger26.warn("Execution cache invalidation after tool-output shrink failed",error3)}}}if(!this.isForkedChat){clearLoadedSkillTracking(this.config.getToolRegistry(),"send-boundary tool-output shrink")}}}const effectiveTokens=estimatePendingPrompt(userContent);const isHardTier=effectiveTokens>=hard;const shouldForceFromHard=!exactRoute&&isHardTier&&this.hardRescueFailureCount<MAX_CONSECUTIVE_FAILURES;const historyBeforeHardRescue=shouldForceFromHard?this.getHistoryShallow():void 0;const completedToolCallIdsBeforeHardRescue=this.completedToolCallIds;const unaccountedMemorySnapshotsBeforeHardRescue=new WeakSet(historyBeforeHardRescue?.flatMap((entry,index)=>(entry.parts??[]).filter((_2,partIndex)=>this.unaccountedMemorySnapshots.has(this.history[index].parts[partIndex])))??[]);const lastPromptTokenCountBeforeHardRescue=this.lastPromptTokenCount;const lastPromptTokenCountWasEstimatedBeforeHardRescue=this.lastPromptTokenCountIsEstimated;const lastOutputTokenCountBeforeHardRescue=this.lastOutputTokenCount;const lastCachedContentTokenCountBeforeHardRescue=this.lastCachedContentTokenCount;const tokenCountsRouteKeyBeforeHardRescue=this.tokenCountsRouteKey;const retainedTokenCountsBeforeHardRescue=new Map(this.tokenCountsByRouteKey);const hardRescueFailureCountBeforeHardRescue=this.hardRescueFailureCount;if(shouldForceFromHard){debugLogger26.warn(`[compaction] hard-tier rescue triggered: prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}, hardRescueAttempt=${this.hardRescueFailureCount+1}, consecutiveFailures=${this.consecutiveFailures}.`)}else if(isHardTier&&!exactRoute){debugLogger26.warn(`[compaction] hard-tier rescue skipped after ${this.hardRescueFailureCount} failed attempts; relying on reactive overflow recovery. prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}.`)}markApiHistoryPrompt(userContent,options2?.promptId);if(exactRoute||isHardTier&&!shouldForceFromHard){compressionInfo={originalTokenCount:effectiveTokens,newTokenCount:effectiveTokens,compressionStatus:5}}else{compressionInfo=await this.tryCompress(prompt_id,shouldForceFromHard,params.config?.abortSignal,{pendingUserMessage:userContent,precomputedEffectiveTokens:effectiveTokens,requestGenerationConfig:params.config,requestRouteKey,deferChatCompressionRecord:shouldForceFromHard,trigger:shouldForceFromHard?"auto":void 0})}if(options2?.suppressedHookContext&&compressionInfo.compressionStatus===1&&!hasUserPromptSubmitContext(userContent,options2.suppressedHookContext)){userContent.parts=[...userContent.parts??[],createUserPromptSubmitContextPart(options2.suppressedHookContext)]}const localPromptTokensAfterCompression=shouldForceFromHard?estimatePendingPrompt(userContent):0;if(shouldStopAfterHardRescue(shouldForceFromHard,hard,localPromptTokensAfterCompression)){const message=getHardRescueFailureMessage(effectiveTokens,hard,compressionInfo,localPromptTokensAfterCompression);if(shouldForceFromHard){this.hardRescueFailureCount=hardRescueFailureCountBeforeHardRescue+1}if(compressionInfo.compressionStatus===1&&historyBeforeHardRescue){this.setHistory(historyBeforeHardRescue,completedToolCallIdsBeforeHardRescue);this.unaccountedMemorySnapshots=unaccountedMemorySnapshotsBeforeHardRescue;this.lastPromptTokenCount=lastPromptTokenCountBeforeHardRescue;this.lastPromptTokenCountIsEstimated=lastPromptTokenCountWasEstimatedBeforeHardRescue;this.lastOutputTokenCount=lastOutputTokenCountBeforeHardRescue;this.lastCachedContentTokenCount=lastCachedContentTokenCountBeforeHardRescue;this.tokenCountsRouteKey=tokenCountsRouteKeyBeforeHardRescue;this.tokenCountsByRouteKey.clear();for(const[retainedRouteKey,retainedCounts]of retainedTokenCountsBeforeHardRescue){this.tokenCountsByRouteKey.set(retainedRouteKey,retainedCounts)}this.telemetryService?.setLastPromptTokenCount(lastPromptTokenCountBeforeHardRescue);this.telemetryService?.setLastCachedContentTokenCount(lastCachedContentTokenCountBeforeHardRescue)}const compressionStatus=CompressionStatus[compressionInfo.compressionStatus]??String(compressionInfo.compressionStatus);debugLogger26.warn(`[compaction] hard-tier rescue stopped oversized prompt: prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}, localPromptTokensAfterCompression=${localPromptTokensAfterCompression}, compressionStatus=${compressionStatus}, newTokenCount=${compressionInfo.newTokenCount}, hardRescueFailureCount=${this.hardRescueFailureCount}, consecutiveFailures=${this.consecutiveFailures}. ${message}`);throw new Error(message)}if(shouldForceFromHard&&compressionInfo.compressionStatus===1){await this.recordCompression({info:compressionInfo,compressedHistory:[...this.getHistoryShallow(),userContent],summaryPrefixLength:this.getHistoryShallow().length,completedToolCallIds:this.completedToolCallIds})}if(this.manualPlanExitNoticesEnabled){const notice=this.config.takePendingManualPlanExitNotice();if(notice){manualPlanExitNoticeVersion=notice.version;manualPlanExitNoticeText=getManualPlanExitSystemReminder(notice.currentMode);userContent={...userContent,parts:[...userContent.parts??[],{text:manualPlanExitNoticeText}]}}}promptTokensForClamp=this.lastPromptTokenCount===0&&manualPlanExitNoticeVersion===void 0?effectiveTokens:estimatePendingPrompt(userContent,true);if(Array.isArray(params.message)){params.message[userContentPushSnapshotKey]=this.userContentPushCount}this.history.push(userContent);for(const part of userContent.parts??[]){if(part.partMetadata?.[AUTO_MEMORY_SNAPSHOT_METADATA]===true){this.unaccountedMemorySnapshots.add(part)}}this.syncReviewedSchemasForContent(userContent);currentUserContent=userContent;userContentAdded=true;this.userContentPushCount++;const inlineRepair=repairOrphanedToolUseTurns(this.history,ORPHAN_TOOL_USE_REPAIR_REASON);if(inlineRepair.injected.length>0){debugLogger26.warn(`[REPAIR] sendMessageStream inline pass synthesized ${inlineRepair.injected.length} functionResponse(s): `+inlineRepair.injected.map(entry=>`${entry.name}(${entry.callId})`).join(", "))}if(inlineRepair.droppedDuplicates.length>0){debugLogger26.warn(`[REPAIR] sendMessageStream inline pass dropped ${inlineRepair.droppedDuplicates.length} duplicate functionResponse(s): `+inlineRepair.droppedDuplicates.map(entry=>`${entry.name}(${entry.callId})`).join(", "))}if(this.promptCountIsEstimateDerived()){promptTokensForClamp+=ESTIMATE_CLAMP_OVERHEAD_PAD;debugLogger26.debug(`[clamp] estimate-derived prompt count; padded by ${ESTIMATE_CLAMP_OVERHEAD_PAD}: promptTokensForClamp=${promptTokensForClamp}, count=${this.lastPromptTokenCount}`)}const clampedMaxOutputTokens=clampOutputTokensToWindow(outputCeiling,contextWindowForClamp,promptTokensForClamp);params={...params,config:{...params.config,maxOutputTokens:clampedMaxOutputTokens}};requestContents=this.getRequestHistoryForRoute(currentUserContent,requestModalities)}}catch(error3){if(userContentAdded){this.history.pop();if(currentUserContent){this.syncReviewedSchemasForContent(currentUserContent)}this.userContentPushCount--}if(manualPlanExitNoticeVersion!==void 0){this.config.restorePendingManualPlanExitNotice(manualPlanExitNoticeVersion)}if(previousGenerationConfig)this.generationConfig=previousGenerationConfig;streamDoneResolver();throw error3}const self2=this;return(async function*(){let successfulRecoveries=0;let activeRecoveryUser;let pendingTransportPrefix=[];const sleepInhibitorHandle=acquireSleepInhibitor(self2.config,"Qwen Code is streaming a model response");try{if(compressionInfo.compressionStatus===1){yield{type:"compressed",info:compressionInfo}}let lastError=new Error("Request failed after all retries.");let rateLimitRetryCount=0;let transientInvalidStreamRetryCount=0;let protocolTagLeakRetryCount=0;const totalInvalidStreamRetryCount=__name(()=>transientInvalidStreamRetryCount+protocolTagLeakRetryCount,"totalInvalidStreamRetryCount");const rearmQuietAcceptanceIfBudgetSpent=__name(()=>{if(transientInvalidStreamRetryCount>=INVALID_STREAM_RETRY_CONFIG.transientMaxRetries){acceptQuietToolResultCompletionOnNextAttempt=true}},"rearmQuietAcceptanceIfBudgetSpent");let streamReplayRetryCount=0;let transportContinuationCount=0;let transportContinuationText="";let transportContinuationParts=[];let transportAttemptParts=[];let transportContinuationPrefix=[];let reactiveCompressionAttempted=false;let omniMediaDegradeAttempts=0;let suppressNextRetryEvent=false;let streamYieldedAnyChunk=false;const cgConfig=exactRoute?.contentGeneratorConfig??self2.config.getContentGeneratorConfig();const requestOverrides=exactRoute?{contentGenerator:exactRoute.contentGenerator,contentGeneratorConfig:exactRoute.contentGeneratorConfig,retryAuthType:exactRoute.retryAuthType,retryErrorCodes:exactRoute.retryErrorCodes,allowPersistentRetry:options2?.preparedRequest?.allowPersistentRetry===true}:void 0;const maxRateLimitRetries=cgConfig?.maxRetries??RATE_LIMIT_RETRY_OPTIONS.maxRetries;const retryInitialDelayMs=cgConfig?.retryInitialDelayMs??RATE_LIMIT_RETRY_OPTIONS.initialDelayMs;const retryMaxDelayMs=cgConfig?.retryMaxDelayMs??RATE_LIMIT_RETRY_OPTIONS.maxDelayMs;const extraRetryErrorCodes=cgConfig?.retryErrorCodes;let maxTokensEscalated=false;const parsedEnvMaxTokens=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);const hasUserMaxTokensOverride=cgConfig?.samplingParams?.max_tokens!==void 0&&cgConfig?.samplingParams?.max_tokens!==null||parsedEnvMaxTokens!==void 0;const effectiveInitialMaxOutputTokens=params.config?.maxOutputTokens??outputCeiling;const escalatedLimit=clampOutputTokensToWindow(OUTPUT_TOKEN_CEILING,contextWindowForClamp,promptTokensForClamp);const shouldEscalateMaxOutputTokens=effectiveInitialMaxOutputTokens<escalatedLimit;let lastFinishReason;const buildAttemptContents=__name(()=>transportContinuationPrefix.length>0?[...requestContents,{role:"model",parts:transportContinuationPrefix},createUserContent([{text:buildRecoveryMessageFromText(TRANSPORT_CONTINUATION_MESSAGE,getPlainTextFromParts(transportContinuationPrefix))}])]:requestContents,"buildAttemptContents");const resetTransportContinuation=__name(()=>{transportContinuationCount=0;transportContinuationText="";transportContinuationParts=[];transportAttemptParts=[];transportContinuationPrefix=[];pendingTransportPrefix=[]},"resetTransportContinuation");const foldTransportAttemptText=__name(()=>{transportContinuationParts=mergeDeliveredParts(transportContinuationParts,consolidateModelResponseParts(transportAttemptParts));transportContinuationText=getPlainTextFromParts(transportContinuationParts);transportAttemptParts=[]},"foldTransportAttemptText");let acceptQuietToolResultCompletionOnNextAttempt=false;for(;;){transportAttemptParts=[];let streamEstablished=false;let streamYieldedChunk=false;let streamYieldedContentChunk=false;let streamYieldedFunctionCall=false;try{if(suppressNextRetryEvent){suppressNextRetryEvent=false}else if(rateLimitRetryCount>0||totalInvalidStreamRetryCount()>0||streamReplayRetryCount>0||transportContinuationCount>0){resetTransportContinuation();yield{type:"retry"}}const acceptQuietToolResultCompletion=acceptQuietToolResultCompletionOnNextAttempt;acceptQuietToolResultCompletionOnNextAttempt=false;const stream=await self2.makeApiCallAndProcessStream(model,buildAttemptContents(),params,prompt_id,requestOverrides,requestRouteKey,turnGoalContext,transportContinuationPrefix.length>0?transportContinuationPrefix:void 0,acceptQuietToolResultCompletion,options2?.onPreparedRequest,promptTokensForClamp,false,options2?.onModelRequestDispatched);streamEstablished=true;pendingTransportPrefix=[];lastFinishReason=void 0;self2.lastObservedClosedFinishReason=void 0;for await(const chunk of stream){if(isFlushedToolCallPark(chunk)&&!streamYieldedContentChunk&&transportContinuationText.trim().length===0){continue}if(hasCandidateOutput(chunk)){streamYieldedChunk=true;streamYieldedAnyChunk=true}if(hasNonThoughtCandidateParts(chunk)){streamYieldedContentChunk=true}const chunkParts=chunk.candidates?.[0]?.content?.parts;transportAttemptParts.push(...(chunkParts??[]).filter(isPlainTextPart).map(part=>({...part})));if(chunkParts?.some(part=>part.functionCall)){streamYieldedFunctionCall=true}const fr2=chunk.candidates?.[0]?.finishReason;if(fr2)lastFinishReason=fr2;yield{type:"chunk",value:chunk}}lastError=null;transportContinuationPrefix=[];break}catch(error3){if(error3 instanceof LlmRequestPreparationError)throw error3;lastError=error3;if(params.config?.abortSignal?.aborted)throw error3;foldTransportAttemptText();const classification=classifyRetryError(error3,{authType:cgConfig?.authType,extraRetryErrorCodes});if(isQuotaExhaustedError(error3)){debugLogger26.warn("Quota exhausted mid-stream, fast-failing",{retryPath:"stream",retryDecision:"fail-fast",errorKind:classification.kind,classificationReason:classification.reason});throw new Error(formatQuotaExhaustedMessage(error3),{cause:error3})}if(error3 instanceof ResponsesHttpError&&error3.headers.get("x-should-retry")==="false"){throw error3}const isRateLimit=isRateLimitError(error3,extraRetryErrorCodes);if(isRateLimit){const details=getRateLimitErrorDetails(error3);const diagnosticFields={classificationDiagnosis:classification.diagnosis,errorKind:classification.kind,classificationReason:classification.reason,...details};if(rateLimitRetryCount<maxRateLimitRetries){self2.popPendingPartialAssistantTurn();rateLimitRetryCount++;const delayMs=getRateLimitRetryDelayMs(rateLimitRetryCount,{...RATE_LIMIT_RETRY_OPTIONS,initialDelayMs:retryInitialDelayMs,maxDelayMs:retryMaxDelayMs,error:error3});const message=parseAndFormatApiError(error3 instanceof Error?error3.message:String(error3));debugLogger26.warn("Rate limit retry scheduled",{retryPath:"stream",retryDecision:"retry",attempt:rateLimitRetryCount,maxRetries:maxRateLimitRetries,retryDelayMs:delayMs,...diagnosticFields});const{promise:delayPromise,skip}=delay3(delayMs,params.config?.abortSignal);resetTransportContinuation();yield{type:"retry",retryInfo:{message,attempt:rateLimitRetryCount,maxRetries:maxRateLimitRetries,delayMs,skipDelay:skip}};await delayPromise;rearmQuietAcceptanceIfBudgetSpent();continue}debugLogger26.warn("Rate limit retry exhausted",{retryPath:"stream",retryDecision:"exhausted",attempts:rateLimitRetryCount,maxRetries:maxRateLimitRetries,...diagnosticFields})}const contextOverflow=getContextLengthExceededInfo(error3);const requestPayloadOverflow=getRequestPayloadTooLargeInfo(error3);const isServerStreamError=streamEstablished&&!isRateLimit&&(classification.kind==="http"||classification.kind==="sse-provider")&&classification.diagnosis==="retryable"&&classification.statusCode!==void 0&&classification.statusCode>=500&&classification.statusCode<600;const isContinuableStreamCut=isRetryableStreamTransportError(classification)||isRetryableStatuslessUpstreamError(classification)&&!contextOverflow.isExceeded&&!requestPayloadOverflow.isTooLarge;const isReplayableStreamError=isContinuableStreamCut||isServerStreamError;const replayAdmitsDeliveredContent=options2?.retractDeliveredOutputOnRetry===true;if(isReplayableStreamError&&(replayAdmitsDeliveredContent||!streamYieldedContentChunk&&transportContinuationText.trim().length===0)&&streamReplayRetryCount<STREAM_RETRY_CONFIG.maxRetries){self2.popPendingPartialAssistantTurn();streamReplayRetryCount++;const delayMs=STREAM_RETRY_CONFIG.initialDelayMs*streamReplayRetryCount;debugLogger26.warn(isServerStreamError?"Server stream retry scheduled":"Transport stream retry scheduled",{retryPath:"stream",retryDecision:"retry",attempt:streamReplayRetryCount,maxRetries:STREAM_RETRY_CONFIG.maxRetries,retryDelayMs:delayMs,yieldedNonContentChunks:streamYieldedChunk,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,...isServerStreamError&&{statusCode:classification.statusCode}});yield{type:"retry",retryDiagnostics:toRetryDiagnostics(classification)};resetTransportContinuation();suppressNextRetryEvent=true;await delay3(delayMs,params.config?.abortSignal).promise;rearmQuietAcceptanceIfBudgetSpent();continue}const attemptFinishReason=lastFinishReason??self2.lastObservedClosedFinishReason;const attemptClosedWithOwnOutput=attemptFinishReason!==void 0&&CLOSED_FINISH_REASONS.has(attemptFinishReason)&&streamYieldedContentChunk;const canContinueAfterTransportCut=isContinuableStreamCut&&!replayAdmitsDeliveredContent&&!attemptClosedWithOwnOutput&&!streamYieldedFunctionCall&&transportContinuationText.trim().length>0&&transportContinuationCount<STREAM_RETRY_CONFIG.maxContinuationRetries;if(canContinueAfterTransportCut){self2.popPendingPartialAssistantTurn();transportContinuationCount++;transportContinuationPrefix=transportContinuationParts;pendingTransportPrefix=transportContinuationPrefix;const delayMs=STREAM_RETRY_CONFIG.initialDelayMs*transportContinuationCount;debugLogger26.warn("Transport stream continuation scheduled",{retryPath:"stream",retryDecision:"continue",attempt:transportContinuationCount,maxRetries:STREAM_RETRY_CONFIG.maxContinuationRetries,retryDelayMs:delayMs,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,deliveredChars:transportContinuationText.length});yield{type:"retry",retryDiagnostics:toRetryDiagnostics(classification),isContinuation:true};suppressNextRetryEvent=true;await delay3(delayMs,params.config?.abortSignal).promise;rearmQuietAcceptanceIfBudgetSpent();continue}if(isReplayableStreamError){debugLogger26.warn(isServerStreamError?"Server stream retry not taken":"Transport stream retry not taken",{retryPath:"stream",retryDecision:attemptClosedWithOwnOutput?"skipped_terminal_finish_reason":streamYieldedContentChunk||transportContinuationText.trim().length>0?"skipped_after_content":"exhausted",attempts:streamReplayRetryCount,maxRetries:STREAM_RETRY_CONFIG.maxRetries,continuationAttempts:transportContinuationCount,maxContinuationRetries:STREAM_RETRY_CONFIG.maxContinuationRetries,errorKind:classification.kind,transportCode:classification.transportCode,classificationReason:classification.reason,providerCode:classification.providerCode,requestId:classification.requestId,...isServerStreamError&&{statusCode:classification.statusCode}})}if(contextOverflow.isExceeded||requestPayloadOverflow.isTooLarge){const omniDegradeMaxAttempts=self2.config.getOmniProcessingConfig?.()?.limits.maxTransportPasses??0;if(contextOverflow.isExceeded&&!exactRoute&&omniMediaDegradeAttempts<omniDegradeMaxAttempts){const degradeAttempt=omniMediaDegradeAttempts++;let degradeOutcome;try{const{degradeOmniMediaAfterServerReject}=await import("./reactive-degrade-FYZBJCF6.js");degradeOutcome=await degradeOmniMediaAfterServerReject(self2.config,self2.history,degradeAttempt,{signal:params.config?.abortSignal,observedLimitTokens:contextOverflow.limitTokens})}catch(degradeError){if(params.config?.abortSignal?.aborted||isAbortError(degradeError)){throw degradeError}debugLogger26.warn("Omni media degradation fallback failed.",degradeError)}if(degradeOutcome&&degradeOutcome.replacedParts>0){self2.popPendingPartialAssistantTurn();requestContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities);debugLogger26.warn(`Server input limit exceeded; degraded ${degradeOutcome.degradedResources} omni media resource(s) in place (attempt ${degradeAttempt+1}/${omniDegradeMaxAttempts}); retrying.`);resetTransportContinuation();yield{type:"retry"};suppressNextRetryEvent=true;rearmQuietAcceptanceIfBudgetSpent();continue}}let attemptedPayloadRecovery=false;let payloadRecoveryNoop=false;let payloadRecoveryThrew=false;if(!exactRoute&&!reactiveCompressionAttempted){reactiveCompressionAttempted=true;attemptedPayloadRecovery=requestPayloadOverflow.isTooLarge;const reactiveOriginalTokenCountIsEstimated=contextOverflow.actualTokens===void 0;const reactiveOriginalTokenCount=contextOverflow.actualTokens??contextOverflow.limitTokens??(requestPayloadOverflow.isTooLarge?estimateContentTokens(self2.getHistoryShallow(true),resolveSlimmingConfig(self2.config.getChatCompression()).imageTokenEstimate):cgConfig?.contextWindowSize??DEFAULT_TOKEN_LIMIT);debugLogger26.warn(requestPayloadOverflow.isTooLarge?"Request body rejected with HTTP 413; attempting reactive compression.":"Context length exceeded; attempting reactive compression.");if(!streamYieldedFunctionCall){pendingTransportPrefix=transportContinuationParts}try{const reactiveInfo=await self2.tryCompress(prompt_id,true,params.config?.abortSignal,{originalTokenCountOverride:{count:reactiveOriginalTokenCount,isEstimated:reactiveOriginalTokenCountIsEstimated},precomputedEffectiveTokens:reactiveOriginalTokenCount,observedServerCeiling:contextOverflow.limitTokens,observedServerCeilingKind:contextOverflow.limitKind,requestGenerationConfig:params.config,requestRouteKey,trigger:"auto",requestPayloadTooLarge:requestPayloadOverflow.isTooLarge});if(reactiveInfo.compressionStatus===1){self2.popPendingPartialAssistantTurn();const noticeText=manualPlanExitNoticeText;if(noticeText&&!self2.history.some(content=>content.parts?.some(part=>part.text?.includes(noticeText)))){const lastContent=self2.history.at(-1);if(lastContent?.role==="user"){lastContent.parts=[...lastContent.parts??[],{text:noticeText}]}else{self2.history.push(createUserContent([{text:noticeText}]))}}if(options2?.suppressedHookContext){const lastContent=self2.history.at(-1);const hookContextPart=createUserPromptSubmitContextPart(options2.suppressedHookContext);if(lastContent?.role==="user"){lastContent.parts=[...lastContent.parts??[],hookContextPart]}else{self2.history.push(createUserContent([hookContextPart]))}}requestContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities);debugLogger26.info(`Reactive compression succeeded: ${reactiveInfo.originalTokenCount} -> ${reactiveInfo.newTokenCount} tokens.`);yield{type:"compressed",info:reactiveInfo};resetTransportContinuation();yield{type:"retry"};suppressNextRetryEvent=true;rearmQuietAcceptanceIfBudgetSpent();continue}if(reactiveInfo.compressionStatus===5){payloadRecoveryNoop=true}debugLogger26.warn(requestPayloadOverflow.isTooLarge?`Reactive compression did not recover request payload overflow: status=${reactiveInfo.compressionStatus}.`:`Reactive compression did not recover context overflow: status=${reactiveInfo.compressionStatus}.`);if(isCompressionFailureStatus(reactiveInfo.compressionStatus)){if(requestPayloadOverflow.isTooLarge&&reactiveInfo.compressionStatus===7){payloadRecoveryThrew=true}self2.consecutiveFailures+=1;if(self2.consecutiveFailures>=MAX_CONSECUTIVE_FAILURES){debugLogger26.warn(`[compaction] circuit breaker tripped after ${self2.consecutiveFailures} consecutive failures (reactive overflow path); auto-compaction will NOOP on the cheap-gate until a successful force compaction resets the counter.`)}}}catch(compressionError){if(params.config?.abortSignal?.aborted||isAbortError(compressionError)){throw compressionError}payloadRecoveryThrew=requestPayloadOverflow.isTooLarge;debugLogger26.warn("Reactive compression failed.",compressionError)}}else{attemptedPayloadRecovery=requestPayloadOverflow.isTooLarge&&reactiveCompressionAttempted&&!exactRoute;debugLogger26.warn(requestPayloadOverflow.isTooLarge?"Reactive compression already attempted; propagating the request payload overflow error to caller.":"Reactive compression already attempted; propagating the context overflow error to caller.")}if(attemptedPayloadRecovery){if(payloadRecoveryThrew){debugLogger26.warn("Request payload overflow recovery failed transiently; propagating the original 413 so the next send can retry recovery.")}else{debugLogger26.warn("Request payload overflow recovery exhausted; surfacing actionable 413 error.");const actionableError=new Error(payloadRecoveryNoop?REQUEST_PAYLOAD_TOO_LARGE_NOOP_MESSAGE:REQUEST_PAYLOAD_TOO_LARGE_RECOVERY_MESSAGE,{cause:error3});const payloadStatus=requestPayloadOverflow.status;if(payloadStatus!==void 0){Object.assign(actionableError,{status:payloadStatus})}lastError=actionableError}}break}if(error3 instanceof InvalidStreamError&&(error3.type==="NO_TOOL_RESULT_PROGRESS_MAX_TOKENS"||error3.type==="NO_RESPONSE_TEXT"&&lastFinishReason===FinishReason.MAX_TOKENS)&&!maxTokensEscalated&&!hasUserMaxTokensOverride&&shouldEscalateMaxOutputTokens){lastError=null;lastFinishReason=FinishReason.MAX_TOKENS;break}const isInvalidStreamError=error3 instanceof InvalidStreamError;const maxInvalidStreamRetries=isInvalidStreamError&&error3.type==="PROTOCOL_TAG_LEAK"?INVALID_STREAM_RETRY_CONFIG.protocolTagLeakMaxRetries:INVALID_STREAM_RETRY_CONFIG.transientMaxRetries;const invalidStreamRetryCount=isInvalidStreamError&&error3.type==="PROTOCOL_TAG_LEAK"?protocolTagLeakRetryCount:transientInvalidStreamRetryCount;if(isInvalidStreamError&&invalidStreamRetryCount<maxInvalidStreamRetries){self2.popPendingPartialAssistantTurn();const nextInvalidStreamRetryCount=invalidStreamRetryCount+1;if(error3.type==="PROTOCOL_TAG_LEAK"){protocolTagLeakRetryCount=nextInvalidStreamRetryCount}else{transientInvalidStreamRetryCount=nextInvalidStreamRetryCount}rearmQuietAcceptanceIfBudgetSpent();const delayMs=INVALID_STREAM_RETRY_CONFIG.initialDelayMs*nextInvalidStreamRetryCount;debugLogger26.warn(`Invalid stream [${error3.type}] (retry ${nextInvalidStreamRetryCount}/${maxInvalidStreamRetries}). Waiting ${delayMs/1e3}s before retrying...`);logContentRetry(self2.config,new ContentRetryEvent(nextInvalidStreamRetryCount-1,error3.type,delayMs,model));yield{type:"retry"};await delay3(delayMs,params.config?.abortSignal).promise;continue}break}}const rollbackRecoveryAttempt=__name(()=>{const expectedIdx=self2.pendingPartialAssistantTurnIndex;const lastIdx=self2.history.length-1;if(expectedIdx!==null&&self2.history.length>0&&self2.history[lastIdx]?.role==="model"){if(expectedIdx!==lastIdx){debugLogger26.warn(`[RECOVERY_POP] Marker/last-index mismatch: marker=${expectedIdx}, lastIdx=${lastIdx}, historyLength=${self2.history.length}. Popping last entry as best-effort rollback \u2014 investigate any history mutation between processStreamResponse's partial push and this catch.`)}self2.history.pop();self2.clearPendingPartialState()}if(self2.history.length>0&&self2.history[self2.history.length-1].role==="user"){self2.history.pop()}},"rollbackRecoveryAttempt");const streamWithInvalidStreamRetries=__name(async function*(buildAttempt,retryEvent={type:"retry"}){let transientRetryCount=0;let protocolTagLeakRetryCount2=0;let acceptQuietToolResultCompletionOnNextAttempt2=false;for(;;){const attemptState=buildAttempt();try{const acceptQuietToolResultCompletion=acceptQuietToolResultCompletionOnNextAttempt2;acceptQuietToolResultCompletionOnNextAttempt2=false;const stream=await self2.makeApiCallAndProcessStream(model,attemptState.requestContents,attemptState.params,prompt_id,requestOverrides,requestRouteKey,turnGoalContext,void 0,acceptQuietToolResultCompletion,options2?.onPreparedRequest,promptTokensForClamp,retryEvent.isContinuation===true,options2?.onModelRequestDispatched);for await(const chunk of stream){yield{type:"chunk",value:chunk}}return}catch(error3){if(attemptState.params.config?.abortSignal?.aborted)throw error3;attemptState.rollback();if(!(error3 instanceof InvalidStreamError))throw error3;const maxContinuationRetries=error3.type==="PROTOCOL_TAG_LEAK"?INVALID_STREAM_RETRY_CONFIG.protocolTagLeakMaxRetries:INVALID_STREAM_RETRY_CONFIG.transientMaxRetries;const continuationRetryCount=error3.type==="PROTOCOL_TAG_LEAK"?protocolTagLeakRetryCount2:transientRetryCount;if(continuationRetryCount>=maxContinuationRetries){throw error3}const nextContinuationRetryCount=continuationRetryCount+1;if(error3.type==="PROTOCOL_TAG_LEAK"){protocolTagLeakRetryCount2=nextContinuationRetryCount}else{transientRetryCount=nextContinuationRetryCount}if(transientRetryCount>=INVALID_STREAM_RETRY_CONFIG.transientMaxRetries){acceptQuietToolResultCompletionOnNextAttempt2=true}const delayMs=INVALID_STREAM_RETRY_CONFIG.initialDelayMs*nextContinuationRetryCount;debugLogger26.warn(`Invalid stream [${error3.type}] during output continuation (retry ${nextContinuationRetryCount}/${maxContinuationRetries}). Waiting ${delayMs/1e3}s before retrying...`);logContentRetry(self2.config,new ContentRetryEvent(nextContinuationRetryCount-1,error3.type,delayMs,model));yield retryEvent;await delay3(delayMs,attemptState.params.config?.abortSignal).promise}}},"streamWithInvalidStreamRetries");if(lastError===null&&lastFinishReason===FinishReason.MAX_TOKENS&&!maxTokensEscalated&&!hasUserMaxTokensOverride){maxTokensEscalated=true;let recoveryFinishReason=lastFinishReason;let recoveryParams=params;if(shouldEscalateMaxOutputTokens){debugLogger26.info(`Output truncated at ${effectiveInitialMaxOutputTokens} tokens. Escalating to ${escalatedLimit} tokens.`);if(self2.history.length>0&&self2.history[self2.history.length-1].role==="model"){self2.history.pop()}yield{type:"retry",maxOutputTokensEscalated:escalatedLimit};const escalatedParams={...params,config:{...params.config,maxOutputTokens:escalatedLimit}};recoveryParams=escalatedParams;recoveryFinishReason=void 0;for await(const event of streamWithInvalidStreamRetries(()=>({requestContents,params:escalatedParams,rollback:__name(()=>self2.popPendingPartialAssistantTurn(),"rollback")}))){if(event.type==="retry"){yield event;continue}const fr2=event.value.candidates?.[0]?.finishReason;if(fr2)recoveryFinishReason=fr2;yield event}}else{debugLogger26.info(`Output truncated at ${effectiveInitialMaxOutputTokens} tokens; skipping no-op escalation to ${escalatedLimit} tokens and running recovery.`)}let recoveryCount=0;while(recoveryFinishReason===FinishReason.MAX_TOKENS&&recoveryCount<MAX_OUTPUT_RECOVERY_ATTEMPTS){const lastEntry=self2.history[self2.history.length-1];const hasFunctionCall=lastEntry?.role==="model"&&lastEntry.parts?.some(p2=>p2.functionCall)===true;if(hasFunctionCall){debugLogger26.info("Skipping recovery: truncated turn contains functionCall; deferring to tool scheduler fallback.");break}recoveryCount++;debugLogger26.info(`Output still truncated after max_tokens handling. Recovery attempt ${recoveryCount}/${MAX_OUTPUT_RECOVERY_ATTEMPTS}.`);const recoveryUserContent=createUserContent([{text:buildOutputRecoveryMessage(lastEntry)}]);yield{type:"retry",isContinuation:true};recoveryFinishReason=void 0;const recoveryImageTokenEstimate=resolveSlimmingConfig(self2.config.getChatCompression()).imageTokenEstimate;const countBasedRecoveryEstimate=self2.lastPromptTokenCount>0?estimatePromptTokens([],recoveryUserContent,self2.lastPromptTokenCount,self2.lastOutputTokenCount,recoveryImageTokenEstimate,true):0;self2.history.push(recoveryUserContent);const recoveryContents=self2.getRequestHistoryForRoute(currentUserContent,requestModalities,false);self2.history.pop();const walkRecoveryEstimate=estimateContentTokens(recoveryContents,recoveryImageTokenEstimate)+ESTIMATE_CLAMP_OVERHEAD_PAD;const recoveryPromptEstimate=Math.max(countBasedRecoveryEstimate,walkRecoveryEstimate);const recoveryCeiling=recoveryParams.config?.maxOutputTokens??outputCeiling;const iterationParams={...recoveryParams,config:{...recoveryParams.config,maxOutputTokens:clampOutputTokensToWindow(recoveryCeiling,contextWindowForClamp,recoveryPromptEstimate)}};try{for await(const event of streamWithInvalidStreamRetries(()=>{self2.history.push(recoveryUserContent);activeRecoveryUser=recoveryUserContent;return{requestContents:self2.getRequestHistoryForRoute(currentUserContent,requestModalities,false),params:iterationParams,rollback:rollbackRecoveryAttempt}},{type:"retry",isContinuation:true})){if(event.type==="retry"){yield event;continue}const fr2=event.value.candidates?.[0]?.finishReason;if(fr2)recoveryFinishReason=fr2;yield event}successfulRecoveries++;activeRecoveryUser=void 0}catch(recoveryError){if(recoveryError instanceof LlmRequestPreparationError)throw recoveryError;if(params.config?.abortSignal?.aborted)throw recoveryError;rollbackRecoveryAttempt();debugLogger26.warn(`Recovery attempt ${recoveryCount} failed: ${recoveryError}`);yield{type:"chunk",value:{candidates:[{content:{role:"model",parts:[]},finishReason:FinishReason.STOP}]}};break}}}if(lastError){if(lastError instanceof InvalidStreamError){const totalAttempts=totalInvalidStreamRetryCount()+1;logContentRetryFailure(self2.config,new ContentRetryFailureEvent(totalAttempts,lastError.type,model))}const fallbackModels=exactRoute||options2?.disableModelFallbacks?[]:self2.config.getModelFallbacks();if(fallbackModels.length>0&&!isUnattendedMode()&&!streamYieldedAnyChunk){let currentErrorClassification=classifyRetryError(lastError,{authType:cgConfig?.authType,extraRetryErrorCodes});if(isFallbackEligible(currentErrorClassification)){let fallbackSucceeded=false;let fallbackIndex=0;let currentModel=model;let currentResolvedModel=cgConfig?.model??model;let fallbackStreamYieldedAnyChunk=false;for(const fallbackModelId of fallbackModels){if(fallbackModelId===model||fallbackModelId===currentModel){debugLogger26.warn(`[FALLBACK] Skipping fallback model "${fallbackModelId}": same as current model.`);continue}let fallbackGenerator;let fallbackConfig;let fallbackRetryAuthType;let fallbackRetryErrorCodes;let resolvedFallbackModel;let fallbackModalities;try{const resolved=await self2.config.getBaseLlmClient().resolveForModel(fallbackModelId,{failClosed:true});fallbackGenerator=resolved.contentGenerator;fallbackConfig=resolved.contentGeneratorConfig;fallbackRetryAuthType=resolved.retryAuthType;fallbackRetryErrorCodes=resolved.retryErrorCodes;resolvedFallbackModel=resolved.model;fallbackModalities=resolved.contentGeneratorConfig?.modalities}catch(resolveError){if(isAbortError(resolveError))throw resolveError;const resolveErrorMessage=resolveError instanceof Error?resolveError.message:String(resolveError);debugLogger26.warn(`[FALLBACK] Failed to resolve fallback model "${fallbackModelId}": ${resolveErrorMessage}. Trying next fallback.`);continue}if(resolvedFallbackModel===currentResolvedModel){debugLogger26.warn(`[FALLBACK] Skipping fallback model "${fallbackModelId}": resolved model "${resolvedFallbackModel}" matches the current model.`);continue}fallbackIndex++;debugLogger26.warn(`[FALLBACK] Model "${currentModel}" exhausted retries (reason: ${currentErrorClassification.reason}, status: ${currentErrorClassification.statusCode??"unknown"}). Switching to fallback model "${fallbackModelId}" (${fallbackIndex}/${fallbackModels.length}).`);yield{type:"model_fallback",info:{fromModel:currentModel,toModel:resolvedFallbackModel,statusCode:currentErrorClassification.statusCode,fallbackIndex}};self2.popPendingPartialAssistantTurn();let currentFallbackYieldedAnyChunk=false;try{const fallbackRequestContents=self2.getRequestHistoryForRoute(currentUserContent,fallbackModalities??{});for await(const event of self2.makeFallbackStream(resolvedFallbackModel,fallbackRequestContents,params,prompt_id,fallbackGenerator,fallbackRetryAuthType,fallbackRetryErrorCodes,requestRouteKey,turnGoalContext,options2?.onPreparedRequest,promptTokensForClamp,fallbackConfig,options2?.onModelRequestDispatched)){const emittedUserVisibleOutput=event.type!=="chunk"||hasCandidateOutput(event.value);if(emittedUserVisibleOutput){currentFallbackYieldedAnyChunk=true;fallbackStreamYieldedAnyChunk=true}yield event}lastError=null;fallbackSucceeded=true;debugLogger26.info(`[FALLBACK] Successfully completed request with fallback model "${resolvedFallbackModel}".`);return}catch(fallbackError){if(fallbackError instanceof LlmRequestPreparationError)throw fallbackError;if(params.config?.abortSignal?.aborted||isAbortError(fallbackError)){throw fallbackError}lastError=fallbackError;if(currentFallbackYieldedAnyChunk){self2.popPendingPartialAssistantTurn();debugLogger26.warn(`[FALLBACK] Fallback model "${resolvedFallbackModel}" failed after emitting output. Popped the partial assistant turn and stopped the fallback chain to avoid duplicating user-visible output.`);break}const fallbackClassification=classifyRetryError(fallbackError,{authType:fallbackRetryAuthType,extraRetryErrorCodes:fallbackRetryErrorCodes});const canTryNextFallback=isFallbackEligible(fallbackClassification);debugLogger26.warn(`[FALLBACK] Fallback model "${resolvedFallbackModel}" also failed (reason: ${fallbackClassification.reason}, status: ${fallbackClassification.statusCode??"unknown"}). ${canTryNextFallback?"Checking remaining fallbacks.":"Stopping fallback chain."}`);currentModel=resolvedFallbackModel;currentResolvedModel=resolvedFallbackModel;currentErrorClassification=fallbackClassification;if(!canTryNextFallback){debugLogger26.warn(`[FALLBACK] Error from "${resolvedFallbackModel}" is not fallback-eligible (${fallbackClassification.reason}). Stopping fallback chain.`);break}}}if(!fallbackSucceeded){if(!fallbackStreamYieldedAnyChunk){self2.popPendingPartialAssistantTurn()}debugLogger26.warn("[FALLBACK] Fallback chain exhausted without success. Throwing last error.")}}else{debugLogger26.warn(`[FALLBACK] Fallback chain skipped: primary error is not fallback-eligible (reason: ${currentErrorClassification.reason}, diagnosis: ${currentErrorClassification.diagnosis}, status: ${currentErrorClassification.statusCode??"unknown"}, error: ${lastError instanceof Error?lastError.message:String(lastError)}).`)}}else if(fallbackModels.length>0&&!isUnattendedMode()&&streamYieldedAnyChunk){debugLogger26.warn("[FALLBACK] Fallback chain skipped because the primary model already emitted user-visible output.")}if(lastError){throw lastError}}}finally{if(params.config?.abortSignal?.aborted&&pendingTransportPrefix.length>0){const parts=pendingTransportPrefix;self2.history.push({role:"model",parts});self2.pendingPartialAssistantTurnIndex=self2.history.length-1;self2.pendingPartialAssistantRecord={model,message:parts,contextWindowSize:self2.config.getContentGeneratorConfig()?.contextWindowSize,...turnGoalContext?{goalContext:{...turnGoalContext}}:{}}}const recoveryIndex=activeRecoveryUser?self2.history.indexOf(activeRecoveryUser):-1;if(recoveryIndex===self2.history.length-1&&recoveryIndex>=0){self2.history.pop()}else if(recoveryIndex>=0&&recoveryIndex===self2.history.length-2&&self2.history.at(-1)?.role==="model"){successfulRecoveries++}if(successfulRecoveries>0){self2.coalesceRecoveryPairs(successfulRecoveries)}if(previousGenerationConfig){self2.toolBudgetUsageAnchor=void 0;self2.toolBudgetFixedInputVersion++;self2.generationConfig=previousGenerationConfig}sleepInhibitorHandle.release();streamDoneResolver();if(self2.pendingPartialAssistantRecord){try{self2.chatRecordingService?.recordAssistantTurn(self2.pendingPartialAssistantRecord)}catch(recordErr){debugLogger26.error("[PARTIAL_FLUSH] Failed to persist deferred JSONL record: "+(recordErr instanceof Error?recordErr.message:String(recordErr)))}self2.clearPendingPartialState()}}})()}async makeApiCallAndProcessStream(model,requestContents,params,prompt_id,overrides,routeKey=this.currentRouteKey(),goalContext,transportContinuationPrefix,acceptQuietToolResultCompletion=false,onPreparedRequest,promptTokensForClamp=0,continuationInFlight=false,onModelRequestDispatched){const generator=overrides?.contentGenerator??this.config.getContentGenerator();const fixedInputVersion=this.toolBudgetFixedInputVersion;const request={model,contents:requestContents,config:{...this.generationConfig,...params.config},...transportContinuationPrefix!==void 0&&{continuationInFlight:true}};const actualConfig=overrides?.contentGeneratorConfig??this.config.getContentGeneratorConfig();if(onPreparedRequest){const{abortSignal:_signal,httpOptions:_http,...config3}=request.config??{};try{const prepared={request:{model,contents:requestContents,config:config3},history:this.history,contextPrefixLength:getStartupContextLength(this.history,{includeCompressed:true}),completedToolCallIds:[...this.completedToolCallIds],routeSelector:`${actualConfig?.authType??""}:${model}`,providerPin:llmPreparedProviderPin(actualConfig),promptTokensForClamp,allowPersistentRetry:overrides?.allowPersistentRetry??!overrides};const overBudget=onPreparedRequest.maxSnapshotBytes!==void 0&&Buffer.byteLength(JSON.stringify(prepared))>onPreparedRequest.maxSnapshotBytes;await onPreparedRequest(overBudget?prepared:structuredClone(prepared),continuationInFlight||transportContinuationPrefix!==void 0||hasImagePayloadReferences(this.history))}catch(cause){throw new LlmRequestPreparationError(cause)}}params.config?.abortSignal?.throwIfAborted();const apiCall=__name(()=>{this.toolBudgetUsageAnchor=void 0;params.config?.abortSignal?.throwIfAborted();const groups=new Map;for(const content of requestContents)for(const part of content.parts??[]){const provenance=getToolOutputProvenance(part);if(!provenance||this.injectedToolResults.has(provenance))continue;const parts=groups.get(provenance)??[];parts.push(part);groups.set(provenance,parts)}for(const[provenance,parts]of groups){this.injectedToolResults.add(provenance);try{const injected=measureToolOutput(parts,this.config);logToolResultSize(this.config,new ToolResultSizeEvent(provenance.toolName,provenance.toolType,"injection",provenance.rawSize?.chars,injected.chars,provenance.rawSize?.estimatedTokens,injected.estimatedTokens,provenance.truncated,Number.isFinite(provenance.budget)?provenance.budget:void 0,provenance.budgetSource,provenance.callId,provenance.promptId||prompt_id))}catch{}}onModelRequestDispatched?.();return generator.generateContentStream(request,prompt_id)},"apiCall");const cgConfig=this.config.getContentGeneratorConfig();const authType=overrides?.retryAuthType??cgConfig?.authType;const extraRetryErrorCodes=overrides?.retryErrorCodes??cgConfig?.retryErrorCodes;const persistentMode=(overrides?.allowPersistentRetry??!overrides)&&isUnattendedMode();const streamResponse=await retryWithBackoff(apiCall,{shouldRetryOnError:__name(error3=>{if(error3 instanceof ResponsesHttpError){return error3.shouldRetry(extraRetryErrorCodes)}if(error3 instanceof Error){if(isSchemaDepthError(error3.message))return false;if(isInvalidArgumentError(error3.message))return false}const status=getErrorStatus(error3);if(status===400){return classifyRetryError(error3,{authType,extraRetryErrorCodes}).kind==="transport"}if(status===429)return true;if(status&&status>=500&&status<600)return true;return isRetryableUpstreamError(error3,extraRetryErrorCodes)},"shouldRetryOnError"),authType,extraRetryErrorCodes,persistentMode,signal:params.config?.abortSignal,...persistentMode?{heartbeatFn:__name(info=>{process.stderr.write(`[qwen-code] Waiting for API capacity... attempt ${info.attempt}, retry in ${Math.ceil(info.remainingMs/1e3)}s
169
170
  `)},"heartbeatFn")}:{},onRetry:__name(info=>{logApiRetry(this.config,new ApiRetryEvent({model,promptId:prompt_id,attemptNumber:info.attempt,error:info.error,statusCode:info.errorStatus,retryDelayMs:info.delayMs,subagentName:subagentNameContext.getStore()}))},"onRetry")});return this.processStreamResponse(model,rejectDegradedPlaceholderResponse(streamResponse),routeKey,fixedInputVersion,goalContext,transportContinuationPrefix,acceptQuietToolResultCompletion,params.config?.abortSignal,{authType,extraRetryErrorCodes})}async*makeFallbackStream(model,requestContents,params,prompt_id,contentGenerator,retryAuthType,retryErrorCodes,routeKey,goalContext,onPreparedRequest,promptTokensForClamp=0,contentGeneratorConfig,onModelRequestDispatched){const stream=await this.makeApiCallAndProcessStream(model,requestContents,params,prompt_id,{contentGenerator,contentGeneratorConfig,retryAuthType,retryErrorCodes},routeKey,goalContext,void 0,false,onPreparedRequest,promptTokensForClamp,false,onModelRequestDispatched);for await(const chunk of stream){yield{type:"chunk",value:chunk}}}curatedBaseHistory(){return this.config.getAutoMemoryContext?.()?this.history:withoutAutoMemorySnapshots(this.history)}getHistory(curated=false){const history=curated?extractCuratedHistory(this.curatedBaseHistory()):this.history;return cloneApiHistory(history)}getHistoryTail(count4,curated=false){if(count4<=0)return[];const history=curated?extractCuratedHistory(this.curatedBaseHistory()):this.history;return cloneApiHistory(history.slice(-count4))}getHistoryShallow(curated=false){const history=curated?extractCuratedHistory(this.curatedBaseHistory()):this.history;return history.map(content=>{const copied=copyContentContainer(content);content.parts?.forEach((part,index)=>{if(this.unaccountedMemorySnapshots.has(part)){this.unaccountedMemorySnapshots.add(copied.parts[index])}});return copied})}getHistoryForForkWindow(){const startup=getStartupContextLength(this.history);const prefix2=getStartupContextLength(this.history,{includeCompressed:true});return[...this.history.slice(startup,prefix2),...extractCuratedHistory(this.history.slice(prefix2))].map(copyContentContainer)}getHistoryTailShallow(count4,curated=false){if(count4<=0)return[];const history=curated?extractCuratedHistory(this.curatedBaseHistory()):this.history;return history.slice(-count4).map(copyContentContainer)}getLastHistoryEntry(){return this.getHistoryTail(1)[0]}peekLastHistoryEntry(){return this.history.at(-1)}findLastHistoryEntry(predicate){for(let i=this.history.length-1;i>=0;i--){const entry=this.history[i];if(predicate(entry)){return entry}}return void 0}getLastModelMessageText(){for(let i=this.history.length-1;i>=0;i--){const message=this.history[i];if(message?.role!=="model")continue;const text3=message.parts?.filter(part=>typeof part.text==="string"&&!part.thought).map(part=>part.text).join("")??"";return text3||void 0}return void 0}getHistoryLength(){return this.history.length}getUserContentPushCount(){return this.userContentPushCount}getHistoryFunctionResponseIds(){const ids=new Set;for(const entry of this.history){if(entry.role!=="user")continue;for(const part of entry.parts??[]){const id6=part.functionResponse?.id;if(id6)ids.add(id6)}}return ids}getSynthesizedRepairCallIds(){const ids=new Set;for(const entry of this.history){if(entry.role!=="user")continue;for(const part of entry.parts??[]){const id6=part.functionResponse?.id;if(id6&&isSynthesizedRepairPart(part))ids.add(id6)}}return ids}replaceSynthesizedToolResponse(callId,realParts){for(const entry of this.history){if(entry.role!=="user")continue;const parts=entry.parts;if(!parts)continue;for(let i=0;i<parts.length;i++){const part=parts[i];if(!part||part.functionResponse?.id!==callId)continue;if(!isSynthesizedRepairPart(part))return false;parts.splice(i,1,...realParts);return true}}return false}getHistoryToolCallFingerprints(){const fingerprintsById=new Map;const respondedIds=new Set;for(const entry of this.history){if(entry.role==="user"){for(const part of entry.parts??[]){const id6=part.functionResponse?.id;if(id6)respondedIds.add(id6)}continue}for(const part of entry.parts??[]){const functionCall=part.functionCall;if(functionCall?.id&&!fingerprintsById.has(functionCall.id)){fingerprintsById.set(functionCall.id,getFunctionCallFingerprint(functionCall))}}}const handled=new Map;for(const id6 of respondedIds){const fingerprint2=fingerprintsById.get(id6);if(fingerprint2!==void 0)handled.set(id6,fingerprint2)}return handled}pressureToolOutputBudget(userContent,routeKey,contextWindow){const anchor=this.toolBudgetUsageAnchor;const baseChars=this.config.getTruncateToolOutputThreshold?.();if(!anchor||anchor.routeKey!==routeKey||!userContent.parts?.some(part=>part.functionResponse)||baseChars===void 0||this.config.isTruncateToolOutputThresholdExplicit?.()||typeof contextWindow!=="number"||!Number.isFinite(contextWindow)||contextWindow<=0||anchor.history.length>this.history.length||!anchor.history.every((content,index)=>content===this.history[index]))return void 0;const shrinkableParts=userContent.parts.filter(isBudgetShrinkablePart);if(shrinkableParts.length===0)return void 0;const minimumContent=minimumFunctionResponseContent(userContent.parts);const newUnshrinkableContent=[...this.history.slice(anchor.history.length),{...userContent,parts:minimumContent.parts}];const{auto}=computeThresholds(contextWindow,this.config.getAutoCompactThreshold());const projectedTokens=estimatePromptTokens([],newUnshrinkableContent,anchor.tokens,0,resolveSlimmingConfig(this.config.getChatCompression()).imageTokenEstimate,true);const remainingTokens=(auto-projectedTokens)/CONSERVATIVE_NEW_CONTENT_SAFETY_FACTOR;if(remainingTokens<=0)return void 0;const chars=Math.floor(remainingTokens*TOKEN_TO_CHAR_RATIO)+minimumContent.budgetedChars;return chars<baseChars*shrinkableParts.length?chars:void 0}clearHistory(){this.toolBudgetUsageAnchor=void 0;this.toolBudgetFixedInputVersion++;this.historyReplacementRevision++;this.history=[];this.completedToolCallIds=[];if(!this.isForkedChat){this.config.getToolRegistry()?.clearReviewedDeclarations?.()}this.clearPendingPartialState()}addHistory(content){this.history.push(content);this.syncReviewedSchemasForContent(content);if(this.pendingPartialAssistantTurnIndex!==null||this.pendingPartialAssistantRecord!==null){debugLogger26.error("[INVARIANT_VIOLATION] addHistory called while a partial-push marker is active \u2014 clearing it.")}this.clearPendingPartialState()}syncReviewedSchemasForContent(content){if(!this.isForkedChat&&content.parts?.some(part=>part.functionResponse?.name===ToolNames.TOOL_SEARCH)){this.config.getToolRegistry()?.syncReviewedDeclarations?.(this.history,this)}}redactApprovedPlanFromHistory(callId,replacement,expectedPlan){for(let i=this.history.length-1;i>=0;i--){const entry=this.history[i];if(entry?.role!=="model"||!entry.parts)continue;const partIdx=entry.parts.findIndex(part2=>part2.functionCall?.id===callId&&canonicalPlanToolName(part2.functionCall.name)===ToolNames.EXIT_PLAN_MODE);if(partIdx===-1)continue;const part=entry.parts[partIdx];const functionCall=part.functionCall;const plan=(functionCall.args??{})["plan"];if(typeof plan!=="string"){return false}if(expectedPlan!==void 0&&plan!==expectedPlan){return false}const newParts=[...entry.parts];newParts[partIdx]={...part,functionCall:{...functionCall,args:{...functionCall.args,plan:replacement}}};this.history[i]={...entry,parts:newParts};return true}return false}redactApprovedPlansFromLoadedHistory(){const hasPlanCall=this.history.some(entry=>entry?.parts?.some(part=>canonicalPlanToolName(part.functionCall?.name)===ToolNames.EXIT_PLAN_MODE));if(!hasPlanCall)return;let planPath;let savedPlan;try{planPath=this.config.getPlanFilePath();savedPlan=fs15.readFileSync(planPath,"utf-8")}catch(err){debugLogger26.debug(`Skipping load-side plan redaction, plan file unavailable: ${err}`);return}const redacted=redactApprovedPlansInHistory(this.history,savedPlan,planPath);if(redacted){this.history=redacted}else{debugLogger26.debug(`Load-side plan redaction left history unchanged: no approved exit_plan_mode call matches the plan file at ${planPath}.`)}}setHistory(history,completedToolCallIds){this.toolBudgetUsageAnchor=void 0;this.toolBudgetFixedInputVersion++;this.historyReplacementRevision++;markCompressedHistory(history);this.history=history;this.markToolResultsInjected(this.history);this.setCompletedToolCallIds(completedToolCallIds);this.clearPendingPartialState();this.redactApprovedPlansFromLoadedHistory();if(!this.isForkedChat){clearLoadedSkillTracking(this.config.getToolRegistry(),"setHistory");this.config.getToolRegistry()?.syncReviewedDeclarations?.(this.history,this)}}truncateHistory(keepCount){this.historyReplacementRevision++;const prevLen=this.history.length;this.history=this.history.slice(0,keepCount);markCompressedHistory(this.history);this.setCompletedToolCallIds(this.completedToolCallIds);if(this.history.length<prevLen&&!this.isForkedChat){clearLoadedSkillTracking(this.config.getToolRegistry(),"truncateHistory");this.config.getToolRegistry()?.syncReviewedDeclarations?.(this.history,this)}this.clearPendingPartialState()}stripThoughtsFromHistory(){this.historyReplacementRevision++;this.history=this.history.map(stripThoughtPartsFromContent).filter(content=>content!==null);this.setCompletedToolCallIds(this.completedToolCallIds);this.clearPendingPartialState()}stripOrphanedUserEntriesFromHistory(){const strippedEntries=[];const boundary=recoveryHistoryBoundary(this.history,this.completedToolCallIds);while(this.history.length>boundary&&this.history[this.history.length-1].role==="user"){const lastEntry=this.history[this.history.length-1];if(lastEntry&&isSystemReminderContent(lastEntry)){break}if(lastEntry&&isAgentEnvelopeContent(lastEntry)){break}strippedEntries.unshift(this.history.pop())}if(strippedEntries.length>0&&!this.isForkedChat){clearLoadedSkillTracking(this.config.getToolRegistry(),"stripOrphanedUserEntries");this.config.getToolRegistry()?.syncReviewedDeclarations?.(this.history,this)}this.clearPendingPartialState();if(strippedEntries.length>0)this.historyReplacementRevision++;return strippedEntries}repairOrphanedToolUseTurns(reason,options2){return repairOrphanedToolUseTurns(this.history,reason,options2)}setTools(tools){if(!isDeepStrictEqual4(this.generationConfig.tools,tools)){this.toolBudgetUsageAnchor=void 0;this.toolBudgetFixedInputVersion++}this.generationConfig.tools=tools}getGenerationConfig(){return{...this.generationConfig}}async maybeIncludeSchemaDepthContext(error3){if(isSchemaDepthError(error3.message)||isInvalidArgumentError(error3.message)){const toolRegistry=this.config.getToolRegistry();await toolRegistry.warmAll();const tools=toolRegistry.getAllTools();const cyclicSchemaTools=[];for(const tool of tools){if(tool.schema.parametersJsonSchema&&hasCycleInSchema(tool.schema.parametersJsonSchema)||tool.schema.parameters&&hasCycleInSchema(tool.schema.parameters)){cyclicSchemaTools.push(tool.displayName)}}if(cyclicSchemaTools.length>0){const extraDetails=`
170
171
 
171
172
  This error was probably caused by cyclic schema references in one of the following tools, try disabling them with excludeTools:
@@ -586,14 +587,14 @@ ${text3}`:text3;return next}__name(appendResponseText,"appendResponseText");func
586
587
  ${details.prompt}`,renderPromptAsPlainText:true};case"mcp":return{type:"info",title:`Hook requested confirmation to run ${details.toolName}`,prompt:`${reason}
587
588
 
588
589
  MCP Server: ${details.serverName}
589
- Tool: ${details.toolName}`,renderPromptAsPlainText:true,hideAlwaysAllow:true,onConfirm:details.onConfirm};default:return details}}__name(withPreToolUseAskReason,"withPreToolUseAskReason");function isConcurrencySafe(call,hookReplacedInput){return isToolCallConcurrencySafe(call.request.name,call.tool.kind,call.request.args,hookReplacedInput?void 0:call.request.source)}__name(isConcurrencySafe,"isConcurrencySafe");function partitionByConcurrencySafety(items,isSafe){return items.reduce((batches,item)=>{const safe=isSafe(item);const lastBatch=batches[batches.length-1];if(safe&&lastBatch?.concurrent){lastBatch.calls.push(item)}else{batches.push({concurrent:safe,calls:[item]})}return batches},[])}__name(partitionByConcurrencySafety,"partitionByConcurrencySafety");function partitionToolCalls(calls,hookReplacedInputCallIds){return partitionByConcurrencySafety(calls,call=>isConcurrencySafe(call,hookReplacedInputCallIds.has(call.request.callId)))}__name(partitionToolCalls,"partitionToolCalls");function producerInputDropsStructuredContent(input){if(input===null||input===void 0||typeof input==="string"){return false}const contentToProcess=Array.isArray(input)&&input.length===1?input[0]:input;if(typeof contentToProcess==="string")return false;const hasOnlyKeys2=__name((part,...keys2)=>Object.entries(part).every(([key,value])=>value===void 0||keys2.includes(key)),"hasOnlyKeys");if(Array.isArray(contentToProcess)){return contentToProcess.some(part=>{if(typeof part==="string")return false;if(part.text!==void 0)return!hasOnlyKeys2(part,"text");if(part.inlineData!==void 0){return!hasOnlyKeys2(part,"inlineData")}if(part.fileData!==void 0)return!hasOnlyKeys2(part,"fileData");return true})}if(contentToProcess.functionResponse!==void 0){return Boolean(contentToProcess.functionResponse.response?.["content"])}if(contentToProcess.inlineData!==void 0||contentToProcess.fileData!==void 0){return!hasOnlyKeys2(contentToProcess,"inlineData","fileData")}if(contentToProcess.text!==void 0){return!hasOnlyKeys2(contentToProcess,"text")}return true}__name(producerInputDropsStructuredContent,"producerInputDropsStructuredContent");function producerContentEqual(toolName,callId,input,output){if(producerInputDropsStructuredContent(input))return false;return isDeepStrictEqual6(convertToFunctionResponseParts(toolName,callId,input??""),Array.isArray(output)?output.map(part=>typeof part==="string"?part:Object.fromEntries(Object.entries(part))):output)}__name(producerContentEqual,"producerContentEqual");var CoreToolScheduler=class _CoreToolScheduler{static{__name(this,"CoreToolScheduler")}schedulerOptions;get toolRegistry(){return this.config.getToolRegistry()}toolCalls=[];outputUpdateHandler;onAllToolCallsComplete;invocationReleases=new Map;onToolCallsUpdate;getPreferredEditor;config;onEditorClose;chatRecordingService;launchRefusedCallIds=new Set;onToolResultFullTurnModel;shouldObserveProducer;hasSkillToolOverride;isToolExecutionAllowed;isFinalizingToolCalls=false;postToolBatchEnabledForBatch=false;postToolBatchSpanCallId;postToolBatchConfigWarned=false;isScheduling=false;validationRetryCounts=new Map;autoModeFallbackCallIds=new Set;toolSpans=new Map;blockedSpans=new Map;callIdToBatch=new Map;callIdToPostToolBatchSignal=new Map;preToolUseIds=new Map;preToolUseAsks=new Map;preToolUseSessionHookIds=new Map;hookReplacedInputCallIds=new Set;preToolUseContexts=new Map;nestedHookContexts=new Map;failureContextsForParent=new Map;hookContextSink;askUserQuestionResponseClaims=new Set;runtimeContentGeneratorViews=new Map;hookOwners=new Map;requestQueue=[];nestedToolScheduler;nestedToolCalls=[];nestedSequence=0;nestedFlushScheduled=false;nestedQueue=[];nestedResolvers=new Map;constructor(options2){this.schedulerOptions=options2;this.config=options2.config;this.outputUpdateHandler=options2.outputUpdateHandler;this.onAllToolCallsComplete=options2.onAllToolCallsComplete;this.onToolCallsUpdate=options2.onToolCallsUpdate;this.getPreferredEditor=options2.getPreferredEditor;this.onEditorClose=options2.onEditorClose;this.chatRecordingService=options2.chatRecordingService;this.onToolResultFullTurnModel=options2.onToolResultFullTurnModel;this.shouldObserveProducer=options2.shouldObserveProducer??(()=>true);this.hasSkillToolOverride=options2.hasSkillTool;this.isToolExecutionAllowed=options2.isToolExecutionAllowed}getOrCreateNestedToolScheduler(){if(this.nestedToolScheduler)return this.nestedToolScheduler;this.nestedToolScheduler=new _CoreToolScheduler({...this.schedulerOptions,modToolCheck:void 0,beforeToolLaunch:void 0,onAllToolCallsComplete:__name(async calls=>{for(const call of calls){const resolver=this.nestedResolvers.get(call.request.callId);if(!resolver)continue;this.nestedResolvers.delete(call.request.callId);try{resolver.onResult?.(call.response)}catch(error3){resolver.reject(error3);continue}if(call.status==="success"){const content=extractCodeModeImageContent(call.response.responseParts);resolver.resolve({callId:call.request.callId,name:call.request.name,status:"success",output:extractCodeModeToolOutput(call.response.responseParts),...content?{content}:{}})}else{resolver.reject(call.response.error??new Error(extractCodeModeToolOutput(call.response.responseParts)||`Tool ${call.request.name} failed.`))}}},"onAllToolCallsComplete"),onToolCallsUpdate:__name(calls=>{this.nestedToolCalls=calls;this.notifyToolCallsUpdate()},"onToolCallsUpdate")});this.nestedToolScheduler.hookContextSink=(request,context2)=>{const parentCallId=request.parentCallId;if(!parentCallId||!this.toolCalls.some(call=>call.request.callId===parentCallId&&call.status==="executing")){return}const contexts=this.nestedHookContexts.get(parentCallId)??[];contexts.push(context2);this.nestedHookContexts.set(parentCallId,contexts)};return this.nestedToolScheduler}dispatchCodeModeTool(name2,args,parent,signal,onResult){const allowedNames=parent.codeModeAllowedToolNames?new Set(parent.codeModeAllowedToolNames):void 0;if(!isCodeModeToolCallAllowed(name2,"code_mode",allowedNames)){return Promise.reject(new Error(`Tool "${name2}" is not callable from exec.`))}const callId=`${parent.callId}:code:${++this.nestedSequence}`;const request={callId,name:name2,args,isClientInitiated:true,prompt_id:parent.prompt_id,response_id:parent.response_id,parentCallId:parent.callId,source:"code_mode",goalContext:parent.goalContext};return new Promise((resolve36,reject)=>{this.nestedQueue.push({request,signal,resolve:resolve36,reject,onResult});if(this.nestedFlushScheduled)return;this.nestedFlushScheduled=true;setTimeout(()=>this.flushNestedQueue(),CODE_MODE_BATCH_WINDOW_MS)})}flushNestedQueue(){this.nestedFlushScheduled=false;const entries=this.nestedQueue.splice(0);if(entries.length===0)return;const active=entries.filter(entry=>!entry.signal.aborted);for(const entry of entries){if(entry.signal.aborted)entry.reject(entry.signal.reason)}if(active.length===0)return;const batchController=new AbortController;const abortBatch=__name(event=>{const aborted3=event.currentTarget;batchController.abort(aborted3.reason)},"abortBatch");for(const entry of active){entry.signal.addEventListener("abort",abortBatch,{once:true});this.nestedResolvers.set(entry.request.callId,{resolve:entry.resolve,reject:entry.reject,onResult:entry.onResult})}void runWithoutToolCallRuntime(()=>this.getOrCreateNestedToolScheduler().schedule(active.map(entry=>entry.request),batchController.signal)).catch(error3=>{for(const entry of active){this.nestedResolvers.delete(entry.request.callId);entry.reject(error3)}}).finally(()=>{for(const entry of active){entry.signal.removeEventListener("abort",abortBatch)}})}get memoryMonitor(){return this.config.getMemoryPressureMonitor?.()}compactResultDisplayForInteractiveHistory(resultDisplay){return typeof this.config.isInteractive==="function"&&this.config.isInteractive()?compactToolResultDisplayForHistory(resultDisplay):resultDisplay}async processToolResultImages(responseParts,signal,executionOrigin){if(executionOrigin?.kind==="fixed_policy"){return{responseParts}}let modelOverride;const notices=[];let omniProcessed=responseParts;if(this.config.isOmniEnabled?.()){const{processToolResultOmniMedia}=await import("./tool-result-media-JLLSLGFL.js");omniProcessed=await processToolResultOmniMedia(responseParts,this.config,signal)}const processedParts=await bridgeToolResultImages({config:this.config,responseParts:omniProcessed,signal,onFullTurnModel:__name(model=>{if(!this.onToolResultFullTurnModel?.(model))return false;modelOverride=model;return true},"onFullTurnModel"),onVisionBridgeNotice:__name(notice=>notices.push(notice),"onVisionBridgeNotice")});return{responseParts:processedParts,...modelOverride!==void 0?{modelOverride}:{},...notices.length>0?{visionBridgeNotice:notices.join("\n")}:{}}}setStatusInternal(targetCallId,newStatus,auxiliaryData,executionStatus){this.toolCalls=this.toolCalls.map(currentCall=>{if(currentCall.request.callId!==targetCallId||currentCall.status==="success"||currentCall.status==="error"||currentCall.status==="cancelled"){return currentCall}const existingStartTime=currentCall.startTime;const toolInstance=currentCall.tool;const invocation=currentCall.invocation;if(invocation?.release&&(newStatus==="success"||newStatus==="error"||newStatus==="cancelled")){this.invocationReleases.set(targetCallId,Promise.resolve().then(()=>invocation.release()).catch(error3=>{debugLogger51.warn("Tool invocation resource cleanup failed:",error3)}))}const outcome=currentCall.outcome;switch(newStatus){case"success":{this.clearRetryCountsForTool(currentCall.request.name);const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;return{request:currentCall.request,tool:toolInstance,invocation,status:"success",response:auxiliaryData,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"error":{const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;return{request:currentCall.request,status:"error",tool:toolInstance,invocation,response:auxiliaryData,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"awaiting_approval":return{request:currentCall.request,tool:toolInstance,status:"awaiting_approval",confirmationDetails:auxiliaryData,startTime:existingStartTime,outcome,invocation};case"scheduled":return{request:currentCall.request,tool:toolInstance,status:"scheduled",startTime:existingStartTime,outcome,invocation};case"cancelled":{const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;let resultDisplay=void 0;if(currentCall.status==="awaiting_approval"){const waitingCall=currentCall;if(waitingCall.confirmationDetails.type==="edit"){resultDisplay={fileDiff:waitingCall.confirmationDetails.fileDiff,fileName:waitingCall.confirmationDetails.fileName,filePath:waitingCall.confirmationDetails.filePath,originalContent:waitingCall.confirmationDetails.originalContent,newContent:waitingCall.confirmationDetails.newContent}}else if(waitingCall.confirmationDetails.type==="plan"){resultDisplay={type:"plan_summary",message:"Plan was rejected. Remaining in plan mode.",plan:waitingCall.confirmationDetails.plan,rejected:true}}}else if(currentCall.status==="executing"){const executingCall=currentCall;if(executingCall.liveOutput!==void 0){resultDisplay=executingCall.liveOutput}}const preservedResultDisplay=this.compactResultDisplayForInteractiveHistory(resultDisplay);const response=isToolCallResponseInfo(auxiliaryData)?{...auxiliaryData,executionStatus:auxiliaryData.executionStatus??executionStatus??"not_started",resultDisplay:auxiliaryData.resultDisplay??preservedResultDisplay}:{...createCancelledResponse(currentCall.request,String(auxiliaryData),executionStatus??"not_started"),resultDisplay:preservedResultDisplay};return{request:currentCall.request,tool:toolInstance,invocation,status:"cancelled",response,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"validating":return{request:currentCall.request,tool:toolInstance,status:"validating",startTime:existingStartTime,outcome,invocation};case"executing":return{request:currentCall.request,tool:toolInstance,status:"executing",startTime:existingStartTime,executionStartTime:Date.now(),outcome,invocation};default:{const exhaustiveCheck=newStatus;return exhaustiveCheck}}});this.notifyToolCallsUpdate();void this.checkAndNotifyCompletion().catch(error3=>{debugLogger51.warn(`setStatusInternal completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}setArgsInternal(targetCallId,args){let invocationError;let argsUpdated=false;this.toolCalls=this.toolCalls.map(call=>{if(call.request.callId!==targetCallId||call.status==="success"||call.status==="error"||call.status==="cancelled"){return call}const invocationOrError=runInRequestGoalContext(call.request,()=>this.buildInvocation(call.tool,args,targetCallId,call.request.prompt_id,call.request.executionOrigin?.kind==="client"));if(invocationOrError instanceof Error){invocationError=invocationOrError;const response=createErrorResponse(call.request,invocationOrError,"invalid_tool_params","not_started");return{request:{...call.request,args},status:"error",tool:call.tool,response}}argsUpdated=true;return{...call,request:{...call.request,args},invocation:invocationOrError}});if(invocationError){this.finalizeBlockedSpan(targetCallId,"error","system");const toolSpan=this.toolSpans.get(targetCallId);if(toolSpan){setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,invocationError.message)}this.finalizeToolSpan(targetCallId);this.notifyToolCallsUpdate();void this.checkAndNotifyCompletion().catch(error3=>{debugLogger51.warn(`setArgsInternal completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)});return false}return argsUpdated}isRunning(){return this.isFinalizingToolCalls||this.toolCalls.some(call=>call.status==="executing"||call.status==="awaiting_approval")}cancelPreExecutionIfAborted(callId,signal,toolSpan=this.toolSpans.get(callId)){if(!signal.aborted)return false;this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started");this.finalizeBlockedSpan(callId,"aborted","system");if(toolSpan){setToolSpanCancelled(toolSpan)}this.finalizeToolSpan(callId);return true}finalizeToolSpan(callId,force=false){this.preToolUseIds.delete(callId);this.preToolUseAsks.delete(callId);this.preToolUseSessionHookIds.delete(callId);this.hookReplacedInputCallIds.delete(callId);this.autoModeFallbackCallIds.delete(callId);this.runtimeContentGeneratorViews.delete(callId);if(callId===this.postToolBatchSpanCallId&&!force)return;const span=this.toolSpans.get(callId);if(!span)return;this.toolSpans.delete(callId);endToolSpan(span);this.releaseBatchListenerIfDrained(callId)}finalizeBlockedSpan(callId,decision,source){const span=this.blockedSpans.get(callId);if(!span)return;this.blockedSpans.delete(callId);endToolBlockedOnUserSpan(span,{decision,source})}releaseBatchListenerIfDrained(callId){const batch=this.callIdToBatch.get(callId);if(!batch)return;this.callIdToBatch.delete(callId);batch.callIds.delete(callId);this.releaseIdleBatchListener(batch)}releaseIdleBatchListener(batch){if(batch.preparing)return;for(const id6 of batch.callIds){if(this.toolSpans.has(id6)||this.blockedSpans.has(id6))return}batch.signal.removeEventListener("abort",batch.onAbort)}getBlockedSource(){return this.config.getIdeMode?.()?"ide":"cli"}drainSpansForBatch(callIds){const ids=Array.from(callIds);setTimeout(()=>{for(const callId of ids){try{const call=this.toolCalls.find(c=>c.request.callId===callId);if(call?.status!=="awaiting_approval"&&call?.status!=="scheduled"){continue}this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started");if(this.blockedSpans.has(callId)){this.finalizeBlockedSpan(callId,"aborted","system")}const span=this.toolSpans.get(callId);if(span){setToolSpanCancelled(span);this.finalizeToolSpan(callId,true)}this.callIdToPostToolBatchSignal.delete(callId);this.autoModeFallbackCallIds.delete(callId)}catch(e){debugLogger51.warn(`drainSpansForBatch: failed to drain ${callId}: ${e instanceof Error?e.message:String(e)}`)}}},0)}postToolUseFailureEndMeta=__name(r=>r.hookError?{success:false,error:r.hookError}:{success:true,hasAdditionalContext:!!r.additionalContext},"postToolUseFailureEndMeta");openToolSpan(reqInfo,tool,batchState){const existing=this.toolSpans.get(reqInfo.callId);if(existing)return existing;const canonicalName=canonicalToolName(reqInfo.name);const toolSpan=startToolSpan(canonicalName,{"tool.call_id":reqInfo.callId,"gen_ai.tool.call.id":reqInfo.providerCallId??reqInfo.callId,call_id:reqInfo.callId,tool_name:canonicalName,...reqInfo.parentCallId?{"tool.parent_call_id":reqInfo.parentCallId}:{},...reqInfo.source?{"tool.source":reqInfo.source}:{}},tool.description,reqInfo.prompt_id);this.toolSpans.set(reqInfo.callId,toolSpan);batchState.callIds.add(reqInfo.callId);this.callIdToBatch.set(reqInfo.callId,batchState);return toolSpan}async withHookSpan(opts,fn,toEndMeta){const hookSpan=startHookSpan(opts);let endMeta={success:false};try{const result=await fn();endMeta=toEndMeta(result);return result}catch(err){endMeta={success:false,error:err instanceof Error?err.message:String(err)};throw err}finally{endHookSpan(hookSpan,endMeta)}}buildInvocation(tool,args,callId,promptId,notifyOnCompletion=false){try{const invocation=tool.build(structuredClone(args));const notificationAware=invocation;notificationAware.setCompletionNotificationEnabled?.(notifyOnCompletion);if(callId){const maybeAware=invocation;if(typeof maybeAware.setCallId==="function"){maybeAware.setCallId(callId)}}if(promptId){const maybeAware=invocation;if(typeof maybeAware.setPromptId==="function"){maybeAware.setPromptId(promptId)}}return invocation}catch(e){if(e instanceof Error){return e}return new Error(String(e))}}async getToolNotFoundMessage(unknownToolName,topN=3){const skillTool=await this.toolRegistry.ensureTool(ToolNames.SKILL);if(skillTool&&"getAvailableSkillNames"in skillTool){const availableSkillNames=skillTool.getAvailableSkillNames();if(availableSkillNames.includes(unknownToolName)){return`"${unknownToolName}" is a skill name, not a tool name. To use this skill, invoke the "${ToolNames.SKILL}" tool with parameter: skill: "${unknownToolName}"`}}const mcpMessage=this.getMcpToolUnavailableMessage(unknownToolName);if(mcpMessage){return mcpMessage}const optInToolMessage=await getOptInToolNotFoundMessage(this.config,unknownToolName,async canonicalName=>Boolean(await this.toolRegistry.ensureTool(canonicalName)));if(optInToolMessage){return optInToolMessage}const suggestion=this.getToolSuggestion(unknownToolName,topN);return`Tool "${unknownToolName}" not found in registry. Tools must use the exact names that are registered.${suggestion}`}getMcpToolUnavailableMessage(unknownToolName){if(!unknownToolName.startsWith("mcp__")){return null}const prefixOf=__name(server=>sanitizeToolNameForProvider(`mcp__${server}__`),"prefixOf");const byPrefixLengthDesc=__name((a,b2)=>prefixOf(b2).length-prefixOf(a).length,"byPrefixLengthDesc");const candidates=Array.from(new Set([...this.config.getMcpServerNames?.()??[],...this.config.getRecentlyRemovedMcpServers?.()??[]])).sort(byPrefixLengthDesc);const serverHit=candidates.find(s3=>unknownToolName.startsWith(prefixOf(s3)));if(!serverHit){return`Tool "${unknownToolName}" not found: no MCP server providing it is currently configured. If you recently removed or renamed an MCP server, its tools are no longer available.`}switch(this.config.getMcpServerUnavailableReason?.(serverHit)){case"removed":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" was removed during this session, so its tools were unloaded. Re-add it to your settings to use this tool again.`;case"not_allowed":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is not in the allow-list (mcp.allowed / --allowed-mcp-server-names), so its tools are not loaded. Add it to mcp.allowed to use this tool.`;case"excluded":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is excluded (mcp.excluded), so its tools are not loaded. Remove it from mcp.excluded to use this tool.`;case"pending_approval":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is awaiting approval, so its tools are not loaded. Approve it (run /mcp) to use this tool.`;default:return`Tool "${unknownToolName}" not found on MCP server "${serverHit}". The server may be disconnected, still starting up, or the tool was renamed.`}}getToolSuggestion(unknownToolName,topN=3){const allToolNames=this.toolRegistry.getAllToolNames().filter(name2=>this.toolRegistry.isToolDeclared?.(name2)??true);const matches2=allToolNames.map(toolName=>({name:toolName,distance:import_fast_levenshtein.default.get(unknownToolName,toolName)}));matches2.sort((a,b2)=>{const aIsPrefix=unknownToolName.startsWith(a.name);const bIsPrefix=unknownToolName.startsWith(b2.name);if(aIsPrefix!==bIsPrefix){return aIsPrefix?-1:1}return a.distance-b2.distance});const topNResults=matches2.slice(0,topN);if(topNResults.length===0){return""}const suggestedNames=topNResults.map(match=>`"${match.name}"`).join(", ");if(topNResults.length>1){return` Did you mean one of: ${suggestedNames}?`}else{return` Did you mean ${suggestedNames}?`}}async resolveToolCallBridgeRequest(request,signal){if(signal.aborted||canonicalToolName(request.name)!==ToolNames.TOOL_CALL){return request}const permissionManager=this.config.getPermissionManager?.();if(permissionManager){let bridgeEnabled;try{bridgeEnabled=await permissionManager.isToolEnabled(ToolNames.TOOL_CALL)}catch(error3){if(signal.aborted){return request}const message=error3 instanceof Error?error3.message:String(error3);return{...request,bridgeResolutionError:{error:new Error(`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${message}`),type:"unhandled_exception"}}}if(signal.aborted||!bridgeEnabled){return request}}else if((this.config.getPermissionsDeny?.()??[]).some(name2=>canonicalToolName(name2).toLowerCase().trim()===ToolNames.TOOL_CALL)){return request}const resolution=await runInRequestGoalContext(request,()=>resolveDeferredToolCall(this.toolRegistry,request.args,{maxSubagentDepth:this.config.getMaxSubagentDepth()}));if("error"in resolution){return{...request,bridgeResolutionError:{error:resolution.error,type:resolution.errorType}}}if(this.isToolExecutionAllowed&&!this.isToolExecutionAllowed(resolution.tool.name)){return{...request,bridgeResolutionError:{error:new Error(`Tool "${resolution.tool.name}" is not permitted by this agent's tool policy (execution allowlist or disallowedTools blocklist).`),type:"execution_denied"}}}return{...request,name:resolution.tool.name,args:resolution.arguments,modelFacingName:request.name,modelFacingArgs:request.args}}schedule(request,signal,runtimeView){const owner=captureHookExecutionOwner(this.config);if(this.isRunning()||this.isScheduling){if(signal.aborted){return Promise.reject(new Error("Tool call cancelled while in queue."))}return new Promise((resolve36,reject)=>{const abortHandler=__name(()=>{const index=this.requestQueue.findIndex(item=>item.request===request);if(index>-1){this.requestQueue.splice(index,1);reject(new Error("Tool call cancelled while in queue."))}},"abortHandler");signal.addEventListener("abort",abortHandler,{once:true});this.requestQueue.push({request,signal,runtimeView,owner,resolve:__name(()=>{signal.removeEventListener("abort",abortHandler);resolve36()},"resolve"),reject:__name(reason=>{signal.removeEventListener("abort",abortHandler);reject(reason)},"reject")})})}return this.scheduleWithOwner(request,signal,runtimeView,owner)}scheduleWithOwner(request,signal,runtimeView,owner){const items=Array.isArray(request)?request:[request];for(const item of items)this.hookOwners.set(item.callId,owner);return runWithHookExecutionOwner(owner,()=>this._schedule(request,signal,runtimeView)).catch(error3=>{for(const item of items){this.hookOwners.delete(item.callId);this.preToolUseContexts.delete(item.callId);this.nestedHookContexts.delete(item.callId);this.failureContextsForParent.delete(item.callId)}throw error3})}drainRequestQueueIfIdle(){if(this.requestQueue.length===0||this.isScheduling||this.isRunning()){return}const next=this.requestQueue.shift();this.scheduleWithOwner(next.request,next.signal,next.runtimeView,next.owner).then(next.resolve).catch(next.reject)}clearRetryCountsForTool(toolName){const prefix2=`${toolName}:`;for(const key of this.validationRetryCounts.keys()){if(key.startsWith(prefix2)){this.validationRetryCounts.delete(key)}}}recordRetryableToolError(toolName,errorMessage){const errorKey=`${toolName}:${errorMessage}`;const count4=(this.validationRetryCounts.get(errorKey)??0)+1;for(const key of this.validationRetryCounts.keys()){if(key.startsWith(`${toolName}:`)&&key!==errorKey){this.validationRetryCounts.delete(key)}}this.validationRetryCounts.set(errorKey,count4);return count4}async _schedule(request,signal,runtimeView){if(runtimeView){const items=Array.isArray(request)?request:[request];for(const item of items){this.runtimeContentGeneratorViews.set(item.callId,runtimeView)}try{return await runWithRuntimeContentGenerator(runtimeView,()=>this._schedule(request,signal))}catch(error3){for(const item of items){this.runtimeContentGeneratorViews.delete(item.callId)}throw error3}}this.isScheduling=true;let preparedBatch;try{if(this.isRunning()){throw new Error("Cannot schedule new tool calls while other tool calls are actively running (executing or awaiting approval).")}const requestsToProcess=await Promise.all(dedupeRequestsByCallId(Array.isArray(request)?request:[request]).map(item=>this.resolveToolCallBridgeRequest({...item,args:structuredClone(item.args)},signal)));const planModeEntryBoundaryIndex=findPlanModeEntryBatchBoundaryIndex(requestsToProcess.map(item=>canonicalToolName(item.name)));if(this.validationRetryCounts.size>0){const currentToolNames=new Set(requestsToProcess.map(r=>r.name));for(const key of[...this.validationRetryCounts.keys()]){const sep21=key.indexOf(":");const toolName=sep21===-1?key:key.slice(0,sep21);if(!currentToolNames.has(toolName)){this.validationRetryCounts.delete(key)}}}const newToolCalls=[];const retryErrorsRecordedInBatch=new Map;const recordBatchRetryableToolError=__name((toolName,errorMessage)=>{const key=`${toolName}:${errorMessage}`;const existingCount=retryErrorsRecordedInBatch.get(key);if(existingCount!==void 0){for(const trackedKey of this.validationRetryCounts.keys()){if(trackedKey.startsWith(`${toolName}:`)){this.validationRetryCounts.delete(trackedKey)}}this.validationRetryCounts.set(key,existingCount);return existingCount}const count4=this.recordRetryableToolError(toolName,errorMessage);retryErrorsRecordedInBatch.set(key,count4);return count4},"recordBatchRetryableToolError");const batchState={signal,onAbort:__name(()=>this.drainSpansForBatch(batchState.callIds),"onAbort"),callIds:new Set,preparing:true};preparedBatch=batchState;signal.addEventListener("abort",batchState.onAbort,{once:true});for(const[requestIndex,reqInfo]of requestsToProcess.entries()){let resolvedTool;let resolvedInvocation;const recordPrevalidationCancellation=__name(()=>{if(!signal.aborted)return false;newToolCalls.push({status:"cancelled",request:reqInfo,response:createCancelledResponse(reqInfo,"Tool call cancelled before execution.","not_started"),...resolvedTool?{tool:resolvedTool}:{},...resolvedInvocation?{invocation:resolvedInvocation}:{},durationMs:0});return true},"recordPrevalidationCancellation");try{if(recordPrevalidationCancellation())continue;if(planModeEntryBoundaryIndex!==void 0&&requestIndex!==planModeEntryBoundaryIndex){newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE),"execution_denied","not_started"),durationMs:0});continue}if(reqInfo.bridgeResolutionError){let bridgeError=reqInfo.bridgeResolutionError.error;if(reqInfo.bridgeResolutionError.type==="invalid_tool_params"){const count4=recordBatchRetryableToolError(reqInfo.name,bridgeError.message);if(count4>=VALIDATION_RETRY_LOOP_THRESHOLD){bridgeError=new Error(`${bridgeError.message}${RETRY_LOOP_STOP_DIRECTIVE}`)}}newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,bridgeError,reqInfo.bridgeResolutionError.type,"not_started"),durationMs:0});continue}const canonicalName=canonicalToolName(reqInfo.name);if(this.config.getToolMode?.()===ToolMode.CodeModeOnly&&reqInfo.executionOrigin?.kind!=="fixed_policy"&&!isCodeModeToolCallAllowed(canonicalName,reqInfo.source??"model")){newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(`Tool "${reqInfo.name}" is unavailable on this CodeModeOnly call surface.`),"execution_denied","not_started"),durationMs:0});continue}const pm=this.config.getPermissionManager?.();const toolAliases2=this.config.getToolRegistry?.()?.getPermissionAliases?.(canonicalName);const mcpIdentity=this.config.getToolRegistry?.()?.getMcpToolIdentity?.(canonicalName);const permissionEnabled=pm?await pm.isToolEnabled(canonicalName,toolAliases2,mcpIdentity):true;if(recordPrevalidationCancellation())continue;if(pm&&!permissionEnabled){const matchingRule=pm.findMatchingDenyRule({toolName:canonicalName,toolAliases:toolAliases2,mcpIdentity});let permissionErrorMessage;if(matchingRule){permissionErrorMessage=`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined. Matching deny rule: "${matchingRule}".`}else if(typeof pm.isToolDisabledByCoreToolsAllowList==="function"&&pm.isToolDisabledByCoreToolsAllowList(canonicalName)){permissionErrorMessage=`"${reqInfo.name}" is not listed in the active core tools allowlist (--core-tools or settings tools.core), so the tool is not available. Add it to the core tools list to re-enable it.`}else{permissionErrorMessage=`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined.`}newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(canonicalName===ToolNames.TOOL_CALL?`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${permissionErrorMessage}`:permissionErrorMessage),"execution_denied","not_started"),durationMs:0});continue}if(!pm){const excludeTools=this.config.getPermissionsDeny?.()??void 0;if(excludeTools&&excludeTools.length>0){const normalizedToolName=canonicalName.toLowerCase().trim();const excludedMatch=excludeTools.find(excludedTool=>excludedTool.toLowerCase().trim()===normalizedToolName);if(excludedMatch){const permissionErrorMessage=`Qwen Code requires permission to use ${excludedMatch}, but that permission was declined.`;newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(canonicalName===ToolNames.TOOL_CALL?`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${permissionErrorMessage}`:permissionErrorMessage),"execution_denied","not_started"),durationMs:0});continue}}}const toolInstance=await runInRequestGoalContext(reqInfo,()=>this.toolRegistry.ensureTool(canonicalName));resolvedTool=toolInstance;if(recordPrevalidationCancellation())continue;if(!toolInstance){const errorMessage=await runInRequestGoalContext(reqInfo,()=>this.getToolNotFoundMessage(reqInfo.name));if(recordPrevalidationCancellation())continue;newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(errorMessage),"tool_not_registered","not_started"),durationMs:0});continue}if((reqInfo.wasOutputTruncated||reqInfo.hadIncompleteArguments)&&toolInstance.kind==="edit"){const truncated=reqInfo.wasOutputTruncated===true;const rejectionMessage=truncated?TRUNCATION_EDIT_REJECTION:INCOMPLETE_ARGS_EDIT_REJECTION;const count4=recordBatchRetryableToolError(reqInfo.name,rejectionMessage);const truncationError=new Error(count4>=VALIDATION_RETRY_LOOP_THRESHOLD?`${rejectionMessage}${truncated?TRUNCATION_RETRY_LOOP_DIRECTIVE:INCOMPLETE_ARGS_RETRY_LOOP_DIRECTIVE}`:rejectionMessage);newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,truncationError,truncated?"output_truncated":"invalid_tool_params","not_started"),durationMs:0});continue}const preToolUseTerminal=await this.runPreToolUse(reqInfo,toolInstance,batchState,signal);if(preToolUseTerminal){newToolCalls.push(preToolUseTerminal);continue}if(recordPrevalidationCancellation())continue;const policyGate=evaluateMediaPolicyToolCall({config:this.config,tool:toolInstance,args:reqInfo.args,executionOrigin:reqInfo.executionOrigin});if(policyGate.outcome==="reject"){newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,new Error(policyGate.message),policyGate.reason==="invalid_params"?"invalid_tool_params":"execution_denied","not_started"),durationMs:0});continue}const refusal=this.schedulerOptions.refuseToolCall?.({...reqInfo,args:policyGate.args});if(refusal!==void 0){newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,new Error(refusal),"execution_denied","not_started"),durationMs:0});continue}const invocationOrError=runInRequestGoalContext(reqInfo,()=>this.buildInvocation(toolInstance,policyGate.args,reqInfo.callId,reqInfo.prompt_id,reqInfo.executionOrigin?.kind==="client"));if(recordPrevalidationCancellation())continue;if(invocationOrError instanceof Error){const targetMessage=reqInfo.modelFacingName!==void 0?describeBridgedArgumentError(reqInfo.name,invocationOrError.message):invocationOrError.message;const paramGuidance=reqInfo.wasOutputTruncated?TRUNCATION_PARAM_GUIDANCE:reqInfo.hadIncompleteArguments?INCOMPLETE_ARGS_PARAM_GUIDANCE:void 0;const displayError=paramGuidance?new Error(`${targetMessage} ${paramGuidance}`):reqInfo.modelFacingName!==void 0?new Error(targetMessage):invocationOrError;const count4=recordBatchRetryableToolError(reqInfo.name,invocationOrError.message);const finalError=count4>=VALIDATION_RETRY_LOOP_THRESHOLD?new Error(`${targetMessage}${RETRY_LOOP_STOP_DIRECTIVE}`):displayError;newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,finalError,"invalid_tool_params","not_started"),durationMs:0});continue}resolvedInvocation=invocationOrError;this.clearRetryCountsForTool(reqInfo.name);newToolCalls.push({status:"validating",request:reqInfo,tool:toolInstance,invocation:invocationOrError,startTime:Date.now()})}catch(error3){if(recordPrevalidationCancellation())continue;const normalizedError=error3 instanceof Error?error3:new Error(String(error3));newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,normalizedError,error3?.errorType??"unhandled_exception","not_started"),...resolvedTool?{tool:resolvedTool}:{},durationMs:0})}}for(const toolCall of newToolCalls){const span=this.toolSpans.get(toolCall.request.callId);if(!span||toolCall.status==="validating")continue;if(toolCall.status==="cancelled"){setToolSpanCancelled(span)}else if(toolCall.status==="error"){setToolSpanFailure(span,TOOL_FAILURE_KIND_TOOL_EXCEPTION,toolCall.response.error?.message??"Tool call failed validation.")}this.finalizeToolSpan(toolCall.request.callId)}this.toolCalls=this.toolCalls.concat(newToolCalls);for(const toolCall of newToolCalls){this.callIdToPostToolBatchSignal.set(toolCall.request.callId,signal)}const postToolBatchParentCallId=newToolCalls.findLast(toolCall=>toolCall.status==="validating")?.request.callId;this.postToolBatchEnabledForBatch=false;this.postToolBatchSpanCallId=void 0;try{this.postToolBatchEnabledForBatch=!this.config.getDisableAllHooks()&&(this.config.hasHooksForEvent?.("PostToolBatch")??false);if(this.postToolBatchEnabledForBatch){this.postToolBatchSpanCallId=postToolBatchParentCallId}}catch(configError){this.postToolBatchEnabledForBatch=true;this.postToolBatchSpanCallId=postToolBatchParentCallId;if(!this.postToolBatchConfigWarned){this.postToolBatchConfigWarned=true;debugLogger51.warn("PostToolBatch hook detection failed; deferring span as a precaution:",configError)}}this.notifyToolCallsUpdate();const permissionRequestGrants=new Set;for(const toolCall of newToolCalls){if(toolCall.status!=="validating"){continue}const{request:reqInfo,invocation}=toolCall;const canonicalName=canonicalToolName(reqInfo.name);const toolSpan=this.openToolSpan(reqInfo,toolCall.tool,batchState);let preToolUseAsk=this.preToolUseAsks.get(reqInfo.callId);let modAsk;try{if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(reqInfo.executionOrigin?.kind==="fixed_policy"){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}let toolParams=invocation.params;const flowResult=await runInRequestGoalContext(reqInfo,()=>evaluatePermissionFlow(this.config,invocation,canonicalName,toolParams,signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const modToolCheck=this.schedulerOptions.modToolCheck;if(modToolCheck){const isReadOnly=canonicalName===ToolNames.SHELL?flowResult.defaultPermission==="allow":CONCURRENCY_SAFE_KINDS.has(toolCall.tool.kind);const approver=!this.canPromptForPreToolUseAsk()?void 0:this.config.isInteractive()||this.config.getExperimentalZedIntegration()?"person":"host";const decision=await runInRequestGoalContext(reqInfo,()=>modToolCheck({tool:canonicalName,input:structuredClone(toolParams),tool_use_id:reqInfo.callId,...approver&&{approver},...isReadOnly&&{isReadOnly:true}},{decision:flowResult.finalPermission==="default"?"ask":flowResult.finalPermission,...flowResult.denyMessage?{reason:flowResult.denyMessage}:{}},signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(!["allow","ask","deny"].includes(decision.decision)){throw new Error("Invalid Mod tool.check decision.")}if(flowResult.finalPermission!=="deny"){if(decision.decision==="deny"){flowResult.finalPermission="deny";flowResult.denyMessage=decision.reason?.trim()||`Tool "${reqInfo.name}" is denied by a Mod.`}else if(decision.decision==="ask"){if(flowResult.finalPermission==="allow")flowResult.finalPermission="ask";if(decision.plugin!==void 0&&!preToolUseAsk){modAsk=preToolUseAsk=decision.reason?.trim()?`Mod ${decision.plugin}: ${decision.reason.trim()}`:`Mod ${decision.plugin} requested confirmation before running ${reqInfo.name}.`;this.preToolUseAsks.set(reqInfo.callId,preToolUseAsk)}}}}const{defaultPermission,finalPermission,pmForcedAsk,pmCtx,denyMessage,requiresUserInteraction}=flowResult;const approvalMode=this.config.getApprovalMode();const isPlanMode=approvalMode==="plan";const isPlanShellCall=isPlanMode&&(canonicalName===ToolNames.SHELL||canonicalName===ToolNames.MONITOR);const isExitPlanModeTool=canonicalName===ToolNames.EXIT_PLAN_MODE;const isEnterPlanModeTool=canonicalName===ToolNames.ENTER_PLAN_MODE;const forceAutoReviewForAllow=approvalMode==="auto"&&(shouldForceAutoModeReviewForAllow(pmCtx,this.config.getCwd())||shouldClassifyAllShellForAutoMode(canonicalName,this.config));const confirmationPermission=getEffectivePermissionForConfirmation(finalPermission,forceAutoReviewForAllow);if(finalPermission==="allow"&&forceAutoReviewForAllow){debugLogger51.info(`Auto mode: L4 allow overridden by protected-write guard for ${canonicalName}`)}if(isPlanRequiredTeammateAwaitingApproval(this.config)&&finalPermission!=="deny"){const isExplicitPreApprovalTool=isPlanRequiredTeammatePreApprovalAllowedTool(canonicalName,toolParams);const canRunBeforeLeaderApproval=!preToolUseAsk&&isExplicitPreApprovalTool&&(canonicalName===ToolNames.EXIT_PLAN_MODE||canonicalName===ToolNames.TASK_UPDATE||defaultPermission==="allow"&&finalPermission==="allow"&&!forceAutoReviewForAllow);if(canRunBeforeLeaderApproval){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}const message=getPlanRequiredTeammatePreApprovalMessage(canonicalName);this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(message),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId);continue}if(finalPermission==="deny"){this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(denyMessage??`Tool "${reqInfo.name}" is denied.`),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_DENIED,TOOL_SPAN_STATUS_PERMISSION_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}let planShellAmbientWorkingDirectory;if(isPlanShellCall){const directory=toolParams["directory"];planShellAmbientWorkingDirectory=typeof directory==="string"&&directory.length>0?void 0:this.config.getTargetDir();invocation.params={...structuredClone(invocation.params),directory:typeof directory==="string"&&directory.length>0?directory:planShellAmbientWorkingDirectory};toolParams=invocation.params}const planShellDecision=isPlanShellCall?await runInRequestGoalContext(reqInfo,()=>evaluatePlanModeShellPolicy({config:this.config,toolName:canonicalName,requestArgs:reqInfo.args,invocationParams:toolParams,permissionContext:pmCtx,ambientWorkingDirectory:planShellAmbientWorkingDirectory,signal})):{classification:"not-applicable"};if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const rejectPlanShell=__name(message=>{this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,new Error(message),"execution_denied","not_started"),resultDisplay:message});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId)},"rejectPlanShell");if(planShellDecision.classification!=="not-applicable"){const initialPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(initialPlanShellError){rejectPlanShell(initialPlanShellError);continue}}if(planShellDecision.classification==="write"){rejectPlanShell(planShellDecision.writeBlockMessage);continue}const planShellRequiresConfirmation=planShellDecision.classification==="unknown";if(finalPermission==="allow"&&!forceAutoReviewForAllow&&!planShellRequiresConfirmation&&!preToolUseAsk){if(approvalMode==="auto"){const actionFingerprint=getAutoModeActionFingerprint(canonicalName,toolParams,this.config.getCwd());this.config.setAutoModeDenialState(recordAllow(this.config.getAutoModeDenialState(),actionFingerprint))}this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}let autoModeFallback;let autoModeFallbackRequiresHuman=false;if(!requiresUserInteraction&&!preToolUseAsk&&shouldRunAutoModeForCall(approvalMode,canonicalName)){const actionFingerprint=getAutoModeActionFingerprint(canonicalName,toolParams,this.config.getCwd());const{denialState,fallback}=prepareAutoModeFallback(this.config,actionFingerprint);const llmClient=this.config.getLlmClient?.();const messages=llmClient?.getHistoryTail(MAX_TRANSCRIPT_MESSAGES,false)??[];const trustedUserAnswers=llmClient?.getTrustedUserAnswers?.()??[];const decision=await runInRequestGoalContext(reqInfo,()=>evaluateAutoMode({ctx:pmCtx,pmForcedAsk,toolParams,messages,trustedUserAnswers,config:this.config,signal,skipClassifierReason:fallback.fallback?fallback.reason:void 0}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const outcome=applyAutoModeDecision(decision,this.config,denialState,actionFingerprint);if(!this.config.getDisableAllHooks()&&shouldFirePermissionDeniedForAutoMode(decision,outcome)){try{await runInRequestGoalContext(reqInfo,()=>this.config.getHookSystem?.()?.firePermissionDeniedEvent(canonicalName,toolParams,reqInfo.callId,getAutoModePermissionDeniedReason(decision),signal,reqInfo.callId))}catch(hookError){debugLogger51.warn(`PermissionDenied hook failed for tool ${reqInfo.callId}: ${hookError instanceof Error?hookError.message:String(hookError)}`)}}if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}switch(outcome.kind){case"approved":this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue;case"blocked":debugLogger51.warn(`Auto mode blocked (${outcome.reason}): tool=${canonicalName}, `+formatDenialStateLog(denialState));this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(outcome.errorMessage),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_DENIED,outcome.errorMessage);this.finalizeToolSpan(reqInfo.callId);continue;case"fallback":autoModeFallbackRequiresHuman=outcome.requiresHumanDecision===true;if(outcome.message&&(isDenialFallbackReason(outcome.reason)||outcome.reason==="classifier_unavailable")){this.autoModeFallbackCallIds.add(reqInfo.callId);autoModeFallback={reason:outcome.reason,message:outcome.message};debugLogger51.warn(`Auto mode fallback to manual approval (${outcome.reason}): `+formatDenialStateLog(denialState))}else if((outcome.reason==="external_write"||outcome.reason==="external_directory")&&outcome.message){this.autoModeFallbackCallIds.add(reqInfo.callId);autoModeFallback={reason:outcome.reason,message:outcome.message};debugLogger51.warn(`Auto mode fallback to manual approval (${outcome.reason}): target outside workspace.`)}break;default:{const _exhaustive=outcome;void _exhaustive}}}const isAskUserQuestionTool=canonicalName===ToolNames.ASK_USER_QUESTION;let confirmationDetails;if(!preToolUseAsk&&!needsConfirmation(planShellRequiresConfirmation?"ask":confirmationPermission,approvalMode,canonicalName,requiresUserInteraction)){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled")}else{confirmationDetails=await runInRequestGoalContext(reqInfo,()=>invocation.getConfirmationDetails(signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(autoModeFallback){confirmationDetails=decorateAutoModeFallbackConfirmation(confirmationDetails,autoModeFallback.reason,autoModeFallback.message)}if(planShellDecision.classification!=="not-applicable"){const preDisplayPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(preDisplayPlanShellError){rejectPlanShell(preDisplayPlanShellError);continue}}try{confirmationDetails=decoratePlanModeShellConfirmation(planShellDecision,confirmationDetails)}catch{if(planShellDecision.classification==="unknown"){rejectPlanShell(planShellDecision.noApprovalMessage);continue}throw new Error("Unable to prepare shell confirmation.")}const planModeDetails=confirmationDetails;if(preToolUseAsk){confirmationDetails=withPreToolUseAskReason(confirmationDetails,preToolUseAsk)}injectPermissionRulesIfMissing(confirmationDetails,pmCtx);if(planShellDecision.classification==="not-applicable"&&isPlanModeBlocked(isPlanMode,isExitPlanModeTool,isAskUserQuestionTool,planModeDetails,isEnterPlanModeTool)){const isPlanRequiredTeammate=!shouldUsePlanOnlyReminderInSubagentContext()&&!this.config.getSdkMode();const planModeError=new Error(`Tool blocked by plan mode: "${reqInfo.name}" is not a read-only tool. Only read-only tools (read_file, grep_search, glob, web_fetch, etc.) are allowed in plan mode. Do NOT retry this tool. `+(isPlanRequiredTeammate?`Pivot to read-only alternatives to gather the information you need, then call exit_plan_mode with a plan that covers this tool's purpose.`:`Pivot to read-only alternatives to gather equivalent information, then present your plan directly to the caller.`));this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,planModeError,"execution_denied","not_started"),resultDisplay:"Plan mode blocked a non-read-only tool call."});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId);continue}if(!requiresUserInteraction&&!preToolUseAsk&&isAutoEditApproved(approvalMode,confirmationDetails)){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}const isNonInteractiveDeny=!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&(this.config.getInputFormat()!=="stream-json"||autoModeFallbackRequiresHuman);if(isNonInteractiveDeny){const errorMessage=planShellDecision.classification==="unknown"?planShellDecision.noApprovalMessage:modAsk?`Qwen Code could not ask the user to confirm "${reqInfo.name}" in non-interactive mode, so it was not run. ${modAsk}`:`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined (non-interactive mode cannot prompt for confirmation).`;if(planShellDecision.classification==="unknown"){rejectPlanShell(errorMessage);continue}this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,new Error(errorMessage),"execution_denied","not_started"),...!preToolUseAsk&&{approvalRequired:true}});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_NON_INTERACTIVE_DENIED,TOOL_SPAN_STATUS_NON_INTERACTIVE_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}const preparedConfirmationDetails=confirmationDetails;const messageBus=this.config.getMessageBus();const hooksEnabled=!this.config.getDisableAllHooks();const permissionRequestGrant=permissionRequestGrants.has(reqInfo.callId);if(hooksEnabled&&messageBus||permissionRequestGrant){const permissionMode=String(this.config.getApprovalMode());const hookResult=permissionRequestGrant?{hasDecision:true,shouldAllow:true}:await runInRequestGoalContext(reqInfo,()=>firePermissionRequestHook(messageBus,canonicalName,reqInfo.args||{},permissionMode,void 0,signal,this.hookOwners.get(reqInfo.callId)));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const allowApplies=hookResult.shouldAllow===true&&!requiresUserInteraction&&!autoModeFallbackRequiresHuman&&(!preToolUseAsk||hookResult.updatedInput!==void 0&&planShellDecision.classification==="not-applicable");if(hookResult.hasDecision&&(!hookResult.shouldAllow||allowApplies)){if(hookResult.shouldAllow){if(planShellDecision.classification!=="not-applicable"){const approval=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellApproval({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal,outcome:"proceed_once",payload:hookResult.updatedInput?{updatedInput:hookResult.updatedInput}:void 0}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(approval.outcome==="cancel"){await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm(approval.outcome,approval.payload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}rejectPlanShell(approval.payload?.cancelMessage??planShellDecision.noApprovalMessage);continue}await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm(approval.outcome,approval.payload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,approval.outcome);this.setToolCallOutcome(reqInfo.callId,approval.outcome);this.setStatusInternal(reqInfo.callId,"scheduled");continue}if(hookResult.updatedInput){const rebuilt=this.rebuildWithPermissionRequestInput(reqInfo,toolCall.tool,hookResult.updatedInput,toolSpan);if(rebuilt){permissionRequestGrants.add(reqInfo.callId);newToolCalls.push(rebuilt)}continue}await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm("proceed_once"));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,"proceed_once");this.setToolCallOutcome(reqInfo.callId,"proceed_once");this.setStatusInternal(reqInfo.callId,"scheduled")}else{const cancelPayload=hookResult.denyMessage?{cancelMessage:hookResult.denyMessage}:void 0;await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm("cancel",cancelPayload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,"cancel");this.setToolCallOutcome(reqInfo.callId,"cancel");this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(hookResult.denyMessage||`Permission denied by hook for "${reqInfo.name}"`),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_HOOK_DENIED,TOOL_SPAN_STATUS_PERMISSION_HOOK_DENIED);this.finalizeToolSpan(reqInfo.callId)}continue}}if(this.config.getShouldAvoidPermissionPrompts?.()){const errorMessage=planShellDecision.classification==="unknown"?planShellDecision.noApprovalMessage:`Tool "${reqInfo.name}" requires permission, but background agents cannot prompt for confirmation. The tool call was denied.`;if(planShellDecision.classification==="unknown"){rejectPlanShell(errorMessage);continue}this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(errorMessage),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_BACKGROUND_AGENT_DENIED,TOOL_SPAN_STATUS_BACKGROUND_AGENT_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(planShellDecision.classification!=="not-applicable"){const finalPreDisplayPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(finalPreDisplayPlanShellError){rejectPlanShell(finalPreDisplayPlanShellError);continue}}if(confirmationDetails.type!=="edit"||!confirmationDetails.skipIdeDiff){this.openIdeDiffIfEnabled(confirmationDetails,reqInfo.callId,signal)}const originalOnConfirm=confirmationDetails.onConfirm;const invocationContext=getInvocationContext();let planShellResponseClaimed=false;const wrappedConfirmationDetails={...confirmationDetails,...pmForcedAsk||requiresUserInteraction||preToolUseAsk?{hideAlwaysAllow:true}:{},onConfirm:__name(async(outcome,payload)=>runWithInvocationContext(invocationContext,async()=>{await runInRequestGoalContext(reqInfo,async()=>{if(planShellDecision.classification!=="not-applicable"){if(planShellResponseClaimed)return;planShellResponseClaimed=true;const currentCall=this.toolCalls.find(call=>call.request.callId===reqInfo.callId&&call.status==="awaiting_approval");if(!currentCall)return;const approval=await validatePlanModeShellApproval({config:this.config,decision:planShellDecision,requestArgs:currentCall.request.args,invocationParams:currentCall.invocation.params,signal,outcome,payload});await this.handleConfirmationResponse(reqInfo.callId,originalOnConfirm,approval.outcome,signal,approval.payload);return}await this.handleConfirmationResponse(reqInfo.callId,originalOnConfirm,outcome,signal,payload)})}),"onConfirm")};this.setStatusInternal(reqInfo.callId,"awaiting_approval",wrappedConfirmationDetails);const blockedSpan=startToolBlockedOnUserSpan(toolSpan,{tool_name:canonicalName,call_id:reqInfo.callId});this.blockedSpans.set(reqInfo.callId,blockedSpan);if(hooksEnabled&&messageBus){fireNotificationHook(messageBus,`Qwen Code needs your permission to use ${reqInfo.name}`,"permission_prompt","Permission needed",void 0,this.hookOwners.get(reqInfo.callId)).then(({terminalSequence})=>{if(terminalSequence){this.schedulerOptions.onPermissionPromptTerminalSequence?.(terminalSequence)}}).catch(error3=>{debugLogger51.warn(`Permission prompt notification hook failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}}}catch(error3){if(signal.aborted){this.setStatusInternal(reqInfo.callId,"cancelled","Tool call cancelled by user.","not_started");this.finalizeBlockedSpan(reqInfo.callId,"aborted","system");setToolSpanCancelled(toolSpan);this.finalizeToolSpan(reqInfo.callId);continue}const explicitErrorType=error3?.errorType;this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,error3 instanceof Error?error3:new Error(String(error3)),explicitErrorType??"unhandled_exception","not_started"));this.finalizeBlockedSpan(reqInfo.callId,"error","system");setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,error3 instanceof Error?error3.message:String(error3));this.finalizeToolSpan(reqInfo.callId)}}batchState.preparing=false;await this.attemptExecutionOfScheduledCalls(signal);void this.checkAndNotifyCompletion().catch(error3=>{debugLogger51.warn(`_schedule completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}finally{if(preparedBatch){preparedBatch.preparing=false;this.releaseIdleBatchListener(preparedBatch)}this.isScheduling=false;this.drainRequestQueueIfIdle()}}async handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload){const owner=this.hookOwners.get(callId);if(getHookExecutionOwner()!==owner){return runWithHookExecutionOwner(owner,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const runtimeView=this.runtimeContentGeneratorViews.get(callId);if(runtimeView&&getRuntimeContentGenerator()!==runtimeView){return runWithRuntimeContentGenerator(runtimeView,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const toolCall=this.toolCalls.find(c=>c.request.callId===callId&&c.status==="awaiting_approval");if(!toolCall){if(this.nestedToolScheduler?.toolCalls.some(call=>call.request.callId===callId)){return this.nestedToolScheduler.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload)}return}if(goalTurnContext.getStore()!==toolCall.request.goalContext){return runInRequestGoalContext(toolCall.request,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const claimsAskUserQuestionResponse=toolCall.tool instanceof AskUserQuestionTool&&toolCall.confirmationDetails.type==="ask_user_question";if(claimsAskUserQuestionResponse&&this.askUserQuestionResponseClaims.has(callId)){return}if(claimsAskUserQuestionResponse){this.askUserQuestionResponseClaims.add(callId)}try{await this._handleConfirmationResponseInner(callId,toolCall,originalOnConfirm,outcome,signal,payload)}catch(error3){const aborted3=signal.aborted;if(aborted3){this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started")}else{this.setStatusInternal(callId,"error",createErrorResponse(toolCall.request,error3 instanceof Error?error3:new Error(String(error3)),"unhandled_exception","not_started"))}this.finalizeBlockedSpan(callId,aborted3?"aborted":"error","system");const toolSpan=this.toolSpans.get(callId);if(toolSpan){if(aborted3){setToolSpanCancelled(toolSpan)}else{setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,error3 instanceof Error?error3.message:String(error3))}}this.finalizeToolSpan(callId);debugLogger51.warn(`handleConfirmationResponse failed for ${callId}: ${error3 instanceof Error?error3.message:String(error3)}`);throw error3}finally{if(claimsAskUserQuestionResponse){this.askUserQuestionResponseClaims.delete(callId)}}await this.attemptExecutionOfScheduledCalls(signal)}async _handleConfirmationResponseInner(callId,toolCall,originalOnConfirm,outcome,signal,payload){const shouldSwitchToDefault=outcome==="proceed_once_and_switch_to_default";const normalizedOutcome=shouldSwitchToDefault?"proceed_once":outcome;const isCurrentApproval=__name(()=>!signal.aborted&&this.toolCalls.includes(toolCall)&&toolCall.status==="awaiting_approval","isCurrentApproval");const isCurrentCancellation=__name(()=>outcome==="cancel"&&this.toolCalls.includes(toolCall)&&toolCall.status==="awaiting_approval","isCurrentCancellation");if(!isCurrentApproval()&&!isCurrentCancellation())return;if(!signal.aborted)await originalOnConfirm(normalizedOutcome,payload);if(!isCurrentApproval()&&!isCurrentCancellation())return;if(shouldSwitchToDefault){this.config.setApprovalMode("default")}outcome=normalizedOutcome;if(outcome==="proceed_always"||outcome==="proceed_always_project"||outcome==="proceed_always_user"){await persistPermissionOutcome(outcome,toolCall.confirmationDetails,this.config.getOnPersistPermissionRule?.(),this.config.getPermissionManager?.(),payload,isCurrentApproval);if(!isCurrentApproval())return;await this.autoApproveCompatiblePendingTools(signal,callId,isCurrentApproval);if(!isCurrentApproval())return}this.setToolCallOutcome(callId,outcome);this.recordAutoModeFallbackResolution(callId,outcome);if(outcome==="cancel"||signal.aborted){const cancelMessage=payload?.cancelMessage||"User did not allow tool call";this.setStatusInternal(callId,"cancelled",cancelMessage,"not_started");const toolSpan=this.toolSpans.get(callId);if(toolSpan){setToolSpanCancelled(toolSpan)}const explicitCancel=outcome==="cancel";this.finalizeBlockedSpan(callId,explicitCancel?"cancel":"aborted",explicitCancel?this.getBlockedSource():"system");this.finalizeToolSpan(callId)}else if(outcome==="modify_with_editor"){const waitingToolCall=toolCall;if(waitingToolCall.confirmationDetails.type==="edit"&&isModifiableDeclarativeTool(waitingToolCall.tool)){const modifyContext=waitingToolCall.tool.getModifyContext(signal,callId);const editorType=this.getPreferredEditor();if(!editorType){debugLogger51.warn(`ModifyWithEditor requested for ${callId} but no editor available \u2014 tool stays in awaiting_approval; user can recover via Cancel/Proceed`);const toolSpan=this.toolSpans.get(callId);if(toolSpan){try{toolSpan.setAttributes({"qwen-code.tool.modify_with_editor_unavailable":true})}catch{}}return}this.setStatusInternal(callId,"awaiting_approval",{...waitingToolCall.confirmationDetails,isModifying:true});const normalizedArgs={...waitingToolCall.request.args};for(const key of PATH_ARG_KEYS){if(typeof normalizedArgs[key]==="string"){normalizedArgs[key]=unescapePath(String(normalizedArgs[key]).trim())}}const{updatedParams,updatedDiff}=await modifyWithEditor(normalizedArgs,modifyContext,editorType,signal,this.onEditorClose);if(!this.setArgsInternal(callId,updatedParams))return;this.setStatusInternal(callId,"awaiting_approval",{...waitingToolCall.confirmationDetails,fileDiff:updatedDiff,isModifying:false})}}else{const waitingToolCall=toolCall;if(isApproveOutcome(outcome)&&waitingToolCall.tool instanceof AskUserQuestionTool&&waitingToolCall.confirmationDetails.type==="ask_user_question"){this.config.getLlmClient?.()?.recordTrustedUserAnswers(callId,waitingToolCall.confirmationDetails.questions,payload?.answers)}if(payload?.newContent&&toolCall){if(!await this._applyInlineModify(toolCall,payload,signal)){return}}this.setStatusInternal(callId,"scheduled");const decision=outcome==="proceed_once"?"proceed_once":"proceed_always";this.finalizeBlockedSpan(callId,decision,this.getBlockedSource())}}recordAutoModeFallbackResolution(callId,outcome){const wasAutoModeFallback=this.autoModeFallbackCallIds.delete(callId);if(this.config.getApprovalMode()==="auto"&&wasAutoModeFallback&&isApproveOutcome(outcome)){const before=this.config.getAutoModeDenialState();const after=recordFallbackApprove(before);if(after===before){debugLogger51.warn(`Auto mode denial counters already clear after fallback approval: `+formatDenialStateLog(before));return}debugLogger51.warn(`Auto mode denial counters reset after fallback approval: ${formatDenialStateLog(before)} -> ${formatDenialStateLog(after)}`);this.config.setAutoModeDenialState(after)}}async openIdeDiffIfEnabled(confirmationDetails,callId,signal){if(confirmationDetails.type!=="edit"||!this.config.getIdeMode()||this.config.getExecutionEnvironment?.()){return}let resolution;try{const ideClient=await IdeClient.getInstance();if(!ideClient.isDiffingEnabled())return;resolution=await ideClient.openDiff(confirmationDetails.filePath,confirmationDetails.newContent)}catch(error3){if(!signal.aborted){debugLogger51.warn(`IDE diff open failed for ${callId}: ${error3 instanceof Error?error3.message:String(error3)}`)}return}const still=this.toolCalls.find(c=>c.request.callId===callId&&c.status==="awaiting_approval");if(!still)return;if(resolution.status==="accepted"){const userEdited=resolution.content!=null&&resolution.content!==confirmationDetails.newContent;await this.handleConfirmationResponse(callId,confirmationDetails.onConfirm,"proceed_once",signal,userEdited?{newContent:resolution.content}:void 0)}else{await this.handleConfirmationResponse(callId,confirmationDetails.onConfirm,"cancel",signal)}}async _applyInlineModify(toolCall,payload,signal){const confirmDetails=toolCall.confirmationDetails;if(confirmDetails.type!=="edit"||!isModifiableDeclarativeTool(toolCall.tool)||!payload.newContent){return true}const currentContent=confirmDetails.originalContent??"";const modifyContext=toolCall.tool.getModifyContext(signal,toolCall.request.callId);const updatedParams=modifyContext.createUpdatedParams(currentContent,payload.newContent,toolCall.request.args);const updatedDiff=createPatch(confirmDetails.filePath,currentContent,payload.newContent,"Current","Proposed");if(!this.setArgsInternal(toolCall.request.callId,updatedParams)){return false}this.setStatusInternal(toolCall.request.callId,"awaiting_approval",{...confirmDetails,fileDiff:updatedDiff});return true}async attemptExecutionOfScheduledCalls(signal){while(true){const allCallsFinalOrScheduled=this.toolCalls.every(call=>call.status==="scheduled"||call.status==="cancelled"||call.status==="success"||call.status==="error");if(!allCallsFinalOrScheduled){return}const callsToExecute=this.toolCalls.filter(call=>call.status==="scheduled");if(callsToExecute.length===0){return}const batches=partitionToolCalls(callsToExecute,this.hookReplacedInputCallIds);for(const batch of batches){if(batch.concurrent&&batch.calls.length>1){await this.runConcurrently(batch.calls,signal);if(this.hasExecutingOrAwaitingApprovalCall()){return}}else{for(const call of batch.calls){if(this.schedulerOptions.beforeToolLaunch&&await this.launchRefused(call)){continue}await this.executeSingleToolCall(call,signal);if(this.hasExecutingOrAwaitingApprovalCall()){return}}}}}}async launchRefused(call){const beforeToolLaunch=this.schedulerOptions.beforeToolLaunch;if(!beforeToolLaunch||await beforeToolLaunch(call))return false;const{callId}=call.request;this.launchRefusedCallIds.add(callId);this.setStatusInternal(callId,"cancelled","Tool call was not started.","not_started");this.finalizeBlockedSpan(callId,"aborted","system");const toolSpan=this.toolSpans.get(callId);if(toolSpan){setToolSpanCancelled(toolSpan)}this.finalizeToolSpan(callId);return true}hasExecutingOrAwaitingApprovalCall(){return this.toolCalls.some(call=>call.status==="executing"||call.status==="awaiting_approval")}async runConcurrently(calls,signal){const maxConcurrency=parsePositiveIntegerEnv(process.env["QWEN_CODE_MAX_TOOL_CONCURRENCY"],10);const executing=new Set;const admitted=[];const launchAdmitted=__name(()=>{for(const call of admitted.splice(0)){const p2=this.executeSingleToolCall(call,signal).finally(()=>{executing.delete(p2)});executing.add(p2)}},"launchAdmitted");for(const call of calls){if(this.schedulerOptions.beforeToolLaunch&&await this.launchRefused(call)){continue}admitted.push(call);if(executing.size+admitted.length>=maxConcurrency){launchAdmitted();await Promise.race(executing)}}launchAdmitted();await Promise.all(executing)}async executeSingleToolCall(toolCall,signal){if(toolCall.status!=="scheduled")return;if(goalTurnContext.getStore()!==toolCall.request.goalContext){return runInRequestGoalContext(toolCall.request,()=>this.executeSingleToolCall(toolCall,signal))}const scheduledCall=toolCall;const{callId,name:toolName}=scheduledCall.request;const owner=this.hookOwners.get(callId);if(getHookExecutionOwner()!==owner){return runWithHookExecutionOwner(owner,()=>this.executeSingleToolCall(toolCall,signal))}const runtimeView=this.runtimeContentGeneratorViews.get(callId);if(runtimeView&&getRuntimeContentGenerator()!==runtimeView){return runWithRuntimeContentGenerator(runtimeView,()=>this.executeSingleToolCall(toolCall,signal))}let toolSpan=this.toolSpans.get(callId);if(!toolSpan){const canonical=canonicalToolName(toolName);toolSpan=startToolSpan(canonical,{"tool.call_id":callId,"gen_ai.tool.call.id":scheduledCall.request.providerCallId??callId,call_id:callId,tool_name:canonical,...scheduledCall.request.parentCallId?{"tool.parent_call_id":scheduledCall.request.parentCallId}:{},...scheduledCall.request.source?{"tool.source":scheduledCall.request.source}:{}},scheduledCall.tool.description,scheduledCall.request.prompt_id);this.toolSpans.set(callId,toolSpan)}try{await runInToolSpanContext(toolSpan,()=>this._executeToolCallBody(scheduledCall,signal,toolSpan))}catch(error3){const errorMessage=error3 instanceof Error?error3.message:String(error3);setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,errorMessage);this.setStatusInternal(callId,"error",createErrorResponse(scheduledCall.request,error3 instanceof Error?error3:new Error(errorMessage),"unhandled_exception",this.toolCalls.find(call=>call.request.callId===callId)?.status==="executing"?"error":"not_started"))}finally{this.finalizeToolSpan(callId);this.memoryMonitor?.scheduleCheck()}}async runPreToolUse(reqInfo,tool,batchState,signal){const messageBus=this.config.getMessageBus();if(this.config.getDisableAllHooks()||!messageBus)return void 0;const{callId}=reqInfo;const canonicalName=canonicalToolName(reqInfo.name);const toolInput=structuredClone(reqInfo.args);for(const key of PATH_ARG_KEYS){if(typeof toolInput[key]==="string"){toolInput[key]=unescapePath(String(toolInput[key]).trim())}}const toolUseId=generateToolUseId();this.preToolUseIds.set(callId,toolUseId);this.preToolUseSessionHookIds.set(callId,this.sessionPreToolUseHookIds(callId,canonicalName));const toolSpan=this.openToolSpan(reqInfo,tool,batchState);const result=await runInToolSpanContext(toolSpan,()=>runInRequestGoalContext(reqInfo,()=>this.withHookSpan({hookEvent:"PreToolUse",toolName:canonicalName,toolUseId},()=>firePreToolUseHook(messageBus,canonicalName,toolInput,toolUseId,this.config.getApprovalMode(),signal,callId,this.hookOwners.get(callId)),r=>r.hookError?{success:false,error:r.hookError,shouldProceed:true}:{success:true,shouldProceed:r.shouldProceed,blockType:r.shouldProceed?void 0:r.blockType,hasAdditionalContext:!!r.additionalContext})));if(result.additionalContext){this.preToolUseContexts.set(callId,result.additionalContext)}if(signal.aborted)return void 0;const fixedPolicy=reqInfo.executionOrigin?.kind==="fixed_policy";let blockReason;if(!result.shouldProceed&&(result.blockType!=="ask"||fixedPolicy||!this.canPromptForPreToolUseAsk())){blockReason=result.blockReason||"Tool execution blocked by hook"}else if(fixedPolicy&&result.updatedInput){blockReason="PreToolUse updatedInput is not supported for policy-owned tool calls, which skip the permission flow; the tool was not run."}if(blockReason){setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_SPAN_STATUS_PRE_HOOK_BLOCKED);this.finalizeToolSpan(callId);return{status:"error",request:reqInfo,tool,response:createErrorResponse(reqInfo,new Error(blockReason),"execution_denied","not_started"),durationMs:0}}if(!result.shouldProceed){this.preToolUseAsks.set(callId,result.blockReason||`A PreToolUse hook requested confirmation before running ${reqInfo.name}.`)}if(result.updatedInput){reqInfo.args=result.updatedInput;this.hookReplacedInputCallIds.add(callId)}return void 0}rebuildWithPermissionRequestInput(reqInfo,tool,args,toolSpan){const{callId}=reqInfo;const policyGate=evaluateMediaPolicyToolCall({config:this.config,tool,args,executionOrigin:reqInfo.executionOrigin});if(policyGate.outcome==="reject"){this.setStatusInternal(callId,"error",createErrorResponse(reqInfo,new Error(policyGate.message),policyGate.reason==="invalid_params"?"invalid_tool_params":"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,policyGate.message);this.finalizeToolSpan(callId);return void 0}if(!this.setArgsInternal(callId,policyGate.args))return void 0;this.hookReplacedInputCallIds.add(callId);return this.toolCalls.find(call=>call.request.callId===callId&&call.status==="validating")}sessionPreToolUseHookIds(callId,toolName){const sessionId=this.hookOwners.get(callId)?.sessionId??this.config.getSessionId();return new Set(this.config.getHookSystem?.()?.getSessionHooksManager?.().getMatchingHooks(sessionId,"PreToolUse",toolName).map(entry=>entry.hookId)??[])}canPromptForPreToolUseAsk(){const isNonInteractive=!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&this.config.getInputFormat()!=="stream-json";if(isNonInteractive){return false}if(this.config.getShouldAvoidPermissionPrompts?.()){return false}return true}safelyAddToolArgumentsAttributes(span,argumentsValue){try{addToolArgumentsAttributes(this.config,span,argumentsValue)}catch(error3){debugLogger51.warn("Failed to add tool arguments span attribute:",error3)}}safelyAddToolCallResultAttributes(span,result){try{addToolCallResultAttributes(this.config,span,result)}catch(error3){debugLogger51.warn("Failed to add tool result span attribute:",error3)}}async _executeToolCallBody(scheduledCall,signal,span){const{callId,name:toolName}=scheduledCall.request;const canonicalName=canonicalToolName(toolName);const invocation=scheduledCall.invocation;const toolInput=scheduledCall.request.args;for(const key of PATH_ARG_KEYS){if(typeof toolInput[key]==="string"){toolInput[key]=unescapePath(String(toolInput[key]).trim())}}const toolUseId=this.preToolUseIds.get(callId)??generateToolUseId();const messageBus=this.config.getMessageBus();const hooksEnabled=!this.config.getDisableAllHooks();let producerObserved=false;const observeSyntheticProducer=__name(response=>{try{if(producerObserved||!this.shouldObserveProducer(callId))return;producerObserved=true;observeToolResultBoundary({stage:"producer",sessionId:this.config.getSessionId(),promptId:scheduledCall.request.prompt_id,toolCallId:callId,toolName:canonicalName,artifacts:[toolResultBoundaryArtifact(response.persistedOutputFiles??[],response.artifacts??[])],values:__name(()=>[...toolResultPartDiagnosticValues(response.responseParts),...shellResultText(response.resultDisplay)!==void 0?[{representation:"display",value:shellResultText(response.resultDisplay)}]:[]],"values")})}catch{}},"observeSyntheticProducer");const checkedHookIds=this.preToolUseSessionHookIds.get(callId);if(checkedHookIds&&[...this.sessionPreToolUseHookIds(callId,canonicalName)].some(hookId=>!checkedHookIds.has(hookId))){const errorResponse=createErrorResponse(scheduledCall.request,new Error(`A PreToolUse hook was registered after "${toolName}" was checked, so the call was not run. Call the tool again.`),"execution_denied","not_started");observeSyntheticProducer(errorResponse);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_SPAN_STATUS_PRE_HOOK_BLOCKED);return}const toolInvocationGuard=this.config.getToolInvocationGuard?.();if(toolInvocationGuard){const invocationContext=getInvocationContext();const guardDecision=await evaluateToolInvocationGuard(toolInvocationGuard,{callId,toolName:canonicalName,args:invocation.params,signal,permissionChecked:scheduledCall.request.executionOrigin?.kind!=="fixed_policy",sessionId:this.config.getSessionId(),cwd:this.config.getTargetDir(),...invocationContext?{invocationContext}:{}});if(signal.aborted){const cancelledResponse=createCancelledResponse(scheduledCall.request,"Tool call cancelled before execution.","not_started");observeSyntheticProducer(cancelledResponse);this.setStatusInternal(callId,"cancelled",cancelledResponse);if(this.toolSpans.has(callId)){setToolSpanCancelled(span)}return}if(!guardDecision.allowed){const errorResponse=createErrorResponse(scheduledCall.request,new Error(guardDecision.reason),"execution_denied","not_started");observeSyntheticProducer(errorResponse);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_INVOCATION_GUARD_DENIED,TOOL_SPAN_STATUS_INVOCATION_GUARD_DENIED);return}}if(signal.aborted){const currentCall=this.toolCalls.find(call=>call.request.callId===callId);if(currentCall&&currentCall.status!=="success"&&currentCall.status!=="error"&&currentCall.status!=="cancelled"){const cancelledResponse=createCancelledResponse(scheduledCall.request,"Tool call cancelled before execution.","not_started");observeSyntheticProducer(cancelledResponse);this.setStatusInternal(callId,"cancelled",cancelledResponse);if(this.toolSpans.has(callId)){setToolSpanCancelled(span)}}return}const liveOutputCallback=scheduledCall.tool.canUpdateOutput?outputChunk=>{if(isShellProgressData(outputChunk)){if(this.outputUpdateHandler){this.outputUpdateHandler(callId,outputChunk)}return}const compactOutput=this.compactResultDisplayForInteractiveHistory(outputChunk);if(this.outputUpdateHandler){this.outputUpdateHandler(callId,outputChunk)}this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,liveOutput:compactOutput}:tc);this.notifyToolCallsUpdate()}:void 0;const shellExecutionConfig=this.config.getShellExecutionConfig();const sleepInhibitorHandle=acquireSleepInhibitor(this.config,`Qwen Code is executing tool ${canonicalName}`);let removeParentAbortForward;let executionStatus="not_started";let executionSettled=false;let execSpan;let executionStartedAt;const elapsedExecutionMs=__name(()=>executionStartedAt===void 0?void 0:Math.round(performance.now()-executionStartedAt),"elapsedExecutionMs");let producerToolResult;let appliedOutputBudget;const recordBudgetReduction=__name((before,after,value,source)=>{if(before!==after&&measureToolOutput(after,this.config).chars<measureToolOutput(before,this.config).chars)appliedOutputBudget={value,source}},"recordBudgetReduction");const globalBudgetSource=this.config.isTruncateToolOutputThresholdExplicit?.()?"explicit":"global";let observeProducerOutput=observeSyntheticProducer;try{let promise;const toolExecutionTimeoutMs=Math.min(parsePositiveIntegerEnv(process.env["QWEN_CODE_TOOL_EXECUTION_TIMEOUT_MS"],0),2147483647);let execSignal=signal;let timeoutController;if(toolExecutionTimeoutMs>0){timeoutController=new AbortController;execSignal=timeoutController.signal;if(signal.aborted){timeoutController.abort(signal.reason)}else{const controller=timeoutController;const forwardAbort=__name(()=>controller.abort(signal.reason),"forwardAbort");signal.addEventListener("abort",forwardAbort,{once:true});removeParentAbortForward=__name(()=>signal.removeEventListener("abort",forwardAbort),"removeParentAbortForward")}}const inheritedTodoWorkChainId=todoWorkChainContext.getStore();const todoWorkChainId=this.config.getActiveTodoWorkChainOwner?.(scheduledCall.request.prompt_id,inheritedTodoWorkChainId)??inheritedTodoWorkChainId??scheduledCall.request.prompt_id;if(invocation instanceof ShellToolInvocation){const setPidCallback=__name(pid=>{this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,pid}:tc);this.notifyToolCallsUpdate()},"setPidCallback");const setPromoteAbortControllerCallback=__name(ac=>{this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,promoteAbortController:ac}:tc);this.notifyToolCallsUpdate()},"setPromoteAbortControllerCallback");const canPromoteForegroundShell=__name(()=>{const promotableShells=this.toolCalls.filter(tc=>tc.status==="executing"&&tc.request.name===ToolNames.SHELL&&tc.promoteAbortController!==void 0);return promotableShells.length===1&&promotableShells[0]?.request.callId===callId},"canPromoteForegroundShell");this.safelyAddToolArgumentsAttributes(span,invocation.params);promise=todoWorkChainContext.run(todoWorkChainId,()=>promptIdContext.run(scheduledCall.request.prompt_id,()=>{executionStartedAt=performance.now();this.setStatusInternal(callId,"executing");execSpan=startToolExecutionSpan({toolName:canonicalName,callId});executionStatus="error";const execute=__name(()=>{executionStartedAt=performance.now();try{this.schedulerOptions.onToolExecutionStarted?.(callId,Date.now())}catch(error3){debugLogger51.warn("Tool lifecycle start observer failed:",error3)}return invocation.execute(execSignal,liveOutputCallback,shellExecutionConfig,setPidCallback,setPromoteAbortControllerCallback,canPromoteForegroundShell)},"execute");return scheduledCall.request.name===ToolNames.EXEC||scheduledCall.request.name===ToolNames.TOOL_SEARCH?runWithToolCallRuntime({parentCallId:callId,allowedToolNames:scheduledCall.request.codeModeAllowedToolNames,dispatch:__name((name2,args,nestedSignal,onResult)=>this.dispatchCodeModeTool(name2,args,scheduledCall.request,nestedSignal,onResult),"dispatch")},execute):scheduledCall.request.source==="code_mode"?runWithToolCallSource({kind:"code_mode"},execute):execute()}))}else{this.safelyAddToolArgumentsAttributes(span,invocation.params);promise=todoWorkChainContext.run(todoWorkChainId,()=>promptIdContext.run(scheduledCall.request.prompt_id,()=>{executionStartedAt=performance.now();this.setStatusInternal(callId,"executing");execSpan=startToolExecutionSpan({toolName:canonicalName,callId});executionStatus="error";const execute=__name(()=>{executionStartedAt=performance.now();try{this.schedulerOptions.onToolExecutionStarted?.(callId,Date.now())}catch(error3){debugLogger51.warn("Tool lifecycle start observer failed:",error3)}return invocation.execute(execSignal,liveOutputCallback,shellExecutionConfig)},"execute");return scheduledCall.request.name===ToolNames.EXEC||scheduledCall.request.name===ToolNames.TOOL_SEARCH?runWithToolCallRuntime({parentCallId:callId,allowedToolNames:scheduledCall.request.codeModeAllowedToolNames,dispatch:__name((name2,args,nestedSignal,onResult)=>this.dispatchCodeModeTool(name2,args,scheduledCall.request,nestedSignal,onResult),"dispatch")},execute):scheduledCall.request.source==="code_mode"?runWithToolCallSource({kind:"code_mode"},execute):execute()}))}let toolResult;let schedulerTimeoutResultSelected=false;let schedulerTimeoutWon=false;if(timeoutController){let timeoutTimer;try{toolResult=await new Promise((resolve36,reject)=>{timeoutTimer=setTimeout(()=>{schedulerTimeoutResultSelected=true;schedulerTimeoutWon=!signal.aborted;debugLogger51.warn(`Tool ${canonicalName} (${callId}) timed out after ${toolExecutionTimeoutMs}ms \u2014 aborting`);timeoutController?.abort(new DOMException(`Tool execution timed out after ${toolExecutionTimeoutMs}ms`,"TimeoutError"));resolve36(createToolTimeoutResult(toolExecutionTimeoutMs))},toolExecutionTimeoutMs);timeoutTimer.unref?.();promise.then(resolve36,reject)})}finally{if(timeoutTimer)clearTimeout(timeoutTimer);removeParentAbortForward?.()}}else{toolResult=await promise}producerToolResult=toolResult;observeProducerOutput=__name((response,replacement=false)=>{const rawSize=replacement||producerToolResult?.rawOutputSize===null||producerToolResult?.error!==void 0?void 0:producerToolResult?.rawOutputSize??measureToolOutput(producerToolResult?.llmContent??"",this.config);const processedChars=measureToolOutput(response.responseParts,this.config).chars;const budgetReduced=!replacement&&appliedOutputBudget!==void 0;response.responseParts=attachToolOutputRecovery(attachToolOutputProvenance(response.responseParts,{callId,toolName:getModelFacingToolName(scheduledCall.request),promptId:scheduledCall.request.prompt_id,toolType:scheduledCall.tool instanceof DiscoveredMCPTool?"mcp":"native",rawSize,truncated:!replacement&&producerToolResult?.truncatedByProducer===true?true:budgetReduced?true:rawSize===void 0?void 0:processedChars<rawSize.chars,budget:budgetReduced?appliedOutputBudget?.value:void 0,budgetSource:budgetReduced?appliedOutputBudget?.source:void 0}),{text:replacement?void 0:producerToolResult?.recoveryText,persistedOutputFiles:response.persistedOutputFiles});try{if(producerObserved||!this.shouldObserveProducer(callId))return;producerObserved=true;let producerInputValues;const getProducerInputValues=__name(()=>producerInputValues??=[...toolResultPartDiagnosticValues(producerToolResult?.llmContent),...shellResultText(producerToolResult?.returnDisplay)!==void 0?[{representation:"display",value:shellResultText(producerToolResult?.returnDisplay)}]:[]],"getProducerInputValues");let producerOutputValues;const getProducerOutputValues=__name(()=>producerOutputValues??=[...toolResultPartDiagnosticValues(response.responseParts),...shellResultText(response.resultDisplay)!==void 0?[{representation:"display",value:shellResultText(response.resultDisplay)}]:[],...typeof response.visionBridgeNotice==="string"?[{representation:"display",value:response.visionBridgeNotice}]:[]],"getProducerOutputValues");const inputArtifact=toolResultBoundaryArtifact(producerToolResult?.persistedOutputFiles,producerToolResult?.artifacts);const outputArtifact=toolResultBoundaryArtifact(response.persistedOutputFiles,response.artifacts);let mutated;const isMutated=__name(()=>mutated??=producerToolResult==null||!producerContentEqual(getModelFacingToolName(scheduledCall.request),callId,producerToolResult.llmContent,response.responseParts)||!isDeepStrictEqual6(producerToolResult.returnDisplay,response.resultDisplay)||!isDeepStrictEqual6(inputArtifact,outputArtifact)||typeof response.visionBridgeNotice==="string","isMutated");const observation={sessionId:this.config.getSessionId(),promptId:scheduledCall.request.prompt_id,toolCallId:callId,toolName:canonicalName,mutated:isMutated};observeToolResultBoundary({...observation,stage:"producer_input",artifacts:[inputArtifact],values:getProducerInputValues});observeToolResultBoundary({...observation,stage:"producer_output",artifacts:[outputArtifact],values:getProducerOutputValues})}catch{}},"observeProducerOutput");const isTimeout=toolResult.error?.type==="execution_timeout"&&(!schedulerTimeoutResultSelected||schedulerTimeoutWon);const parentAbortedAtExecutionSettle=signal.aborted;const aborted3=parentAbortedAtExecutionSettle&&!isTimeout;const executionErrorType=toolResult.error?toolResult.error.type??(scheduledCall.tool instanceof DiscoveredMCPTool?"mcp_tool_error":"unknown"):void 0;executionStatus=aborted3?"cancelled":toolResult.error?"error":"success";executionSettled=true;try{this.schedulerOptions.onToolExecutionSettled?.(callId,executionStatus,elapsedExecutionMs()??0)}catch(error3){debugLogger51.warn("Tool lifecycle end observer failed:",error3)}if(execSpan){const completedExecSpan=execSpan;execSpan=void 0;endToolExecutionSpan(completedExecSpan,{success:executionStatus==="success",error:aborted3?TOOL_SPAN_STATUS_TOOL_CANCELLED:isTimeout?TOOL_SPAN_STATUS_TOOL_TIMEOUT:toolResult.error?TOOL_SPAN_STATUS_TOOL_ERROR:void 0,cancelled:aborted3,executionStatus,errorType:executionErrorType})}if(aborted3){let cancelMessage=TOOL_CANCELLED_AFTER_COMPLETION_MESSAGE;let failureHookArtifacts;if(hooksEnabled&&messageBus){const failureHookResult=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:canonicalName,toolUseId,isInterrupt:true},()=>safelyFirePostToolUseFailureHook(messageBus,toolUseId,canonicalName,toolInput,cancelMessage,true,this.config.getApprovalMode(),callId,elapsedExecutionMs(),this.hookOwners.get(callId)),this.postToolUseFailureEndMeta);if(failureHookResult.additionalContext&&!this.keepFailureContextForParent(callId,failureHookResult.additionalContext)){cancelMessage+=`
590
+ Tool: ${details.toolName}`,renderPromptAsPlainText:true,hideAlwaysAllow:true,onConfirm:details.onConfirm};default:return details}}__name(withPreToolUseAskReason,"withPreToolUseAskReason");function isConcurrencySafe(call,hookReplacedInput){return isToolCallConcurrencySafe(call.request.name,call.tool.kind,call.request.args,hookReplacedInput?void 0:call.request.source)}__name(isConcurrencySafe,"isConcurrencySafe");function partitionByConcurrencySafety(items,isSafe){return items.reduce((batches,item)=>{const safe=isSafe(item);const lastBatch=batches[batches.length-1];if(safe&&lastBatch?.concurrent){lastBatch.calls.push(item)}else{batches.push({concurrent:safe,calls:[item]})}return batches},[])}__name(partitionByConcurrencySafety,"partitionByConcurrencySafety");function partitionToolCalls(calls,hookReplacedInputCallIds){return partitionByConcurrencySafety(calls,call=>isConcurrencySafe(call,hookReplacedInputCallIds.has(call.request.callId)))}__name(partitionToolCalls,"partitionToolCalls");function producerInputDropsStructuredContent(input){if(input===null||input===void 0||typeof input==="string"){return false}const contentToProcess=Array.isArray(input)&&input.length===1?input[0]:input;if(typeof contentToProcess==="string")return false;const hasOnlyKeys2=__name((part,...keys2)=>Object.entries(part).every(([key,value])=>value===void 0||keys2.includes(key)),"hasOnlyKeys");if(Array.isArray(contentToProcess)){return contentToProcess.some(part=>{if(typeof part==="string")return false;if(part.text!==void 0)return!hasOnlyKeys2(part,"text");if(part.inlineData!==void 0){return!hasOnlyKeys2(part,"inlineData")}if(part.fileData!==void 0)return!hasOnlyKeys2(part,"fileData");return true})}if(contentToProcess.functionResponse!==void 0){return Boolean(contentToProcess.functionResponse.response?.["content"])}if(contentToProcess.inlineData!==void 0||contentToProcess.fileData!==void 0){return!hasOnlyKeys2(contentToProcess,"inlineData","fileData")}if(contentToProcess.text!==void 0){return!hasOnlyKeys2(contentToProcess,"text")}return true}__name(producerInputDropsStructuredContent,"producerInputDropsStructuredContent");function producerContentEqual(toolName,callId,input,output){if(producerInputDropsStructuredContent(input))return false;return isDeepStrictEqual6(convertToFunctionResponseParts(toolName,callId,input??""),Array.isArray(output)?output.map(part=>typeof part==="string"?part:Object.fromEntries(Object.entries(part))):output)}__name(producerContentEqual,"producerContentEqual");var CoreToolScheduler=class _CoreToolScheduler{static{__name(this,"CoreToolScheduler")}schedulerOptions;get toolRegistry(){return this.config.getToolRegistry()}toolCalls=[];outputUpdateHandler;onAllToolCallsComplete;invocationReleases=new Map;onToolCallsUpdate;getPreferredEditor;config;onEditorClose;chatRecordingService;launchRefusedCallIds=new Set;onToolResultFullTurnModel;shouldObserveProducer;hasSkillToolOverride;isToolExecutionAllowed;isFinalizingToolCalls=false;postToolBatchEnabledForBatch=false;postToolBatchSpanCallId;postToolBatchConfigWarned=false;isScheduling=false;validationRetryCounts=new Map;autoModeFallbackCallIds=new Set;toolSpans=new Map;blockedSpans=new Map;callIdToBatch=new Map;callIdToPostToolBatchSignal=new Map;preToolUseIds=new Map;preToolUseAsks=new Map;preToolUseSessionHookIds=new Map;hookReplacedInputCallIds=new Set;preToolUseContexts=new Map;nestedHookContexts=new Map;failureContextsForParent=new Map;hookContextSink;askUserQuestionResponseClaims=new Set;runtimeContentGeneratorViews=new Map;hookOwners=new Map;requestQueue=[];nestedToolScheduler;nestedToolCalls=[];nestedSequence=0;nestedFlushScheduled=false;nestedQueue=[];nestedResolvers=new Map;constructor(options2){this.schedulerOptions=options2;this.config=options2.config;this.outputUpdateHandler=options2.outputUpdateHandler;this.onAllToolCallsComplete=options2.onAllToolCallsComplete;this.onToolCallsUpdate=options2.onToolCallsUpdate;this.getPreferredEditor=options2.getPreferredEditor;this.onEditorClose=options2.onEditorClose;this.chatRecordingService=options2.chatRecordingService;this.onToolResultFullTurnModel=options2.onToolResultFullTurnModel;this.shouldObserveProducer=options2.shouldObserveProducer??(()=>true);this.hasSkillToolOverride=options2.hasSkillTool;this.isToolExecutionAllowed=options2.isToolExecutionAllowed}getOrCreateNestedToolScheduler(){if(this.nestedToolScheduler)return this.nestedToolScheduler;this.nestedToolScheduler=new _CoreToolScheduler({...this.schedulerOptions,modToolCheck:void 0,beforeToolLaunch:void 0,onAllToolCallsComplete:__name(async calls=>{for(const call of calls){const resolver=this.nestedResolvers.get(call.request.callId);if(!resolver)continue;this.nestedResolvers.delete(call.request.callId);try{resolver.onResult?.(call.response)}catch(error3){resolver.reject(error3);continue}if(call.status==="success"){const content=extractCodeModeImageContent(call.response.responseParts);resolver.resolve({callId:call.request.callId,name:call.request.name,status:"success",output:extractCodeModeToolOutput(call.response.responseParts),...content?{content}:{}})}else{resolver.reject(call.response.error??new Error(extractCodeModeToolOutput(call.response.responseParts)||`Tool ${call.request.name} failed.`))}}},"onAllToolCallsComplete"),onToolCallsUpdate:__name(calls=>{this.nestedToolCalls=calls;this.notifyToolCallsUpdate()},"onToolCallsUpdate")});this.nestedToolScheduler.hookContextSink=(request,context2)=>{const parentCallId=request.parentCallId;if(!parentCallId||!this.toolCalls.some(call=>call.request.callId===parentCallId&&call.status==="executing")){return}const contexts=this.nestedHookContexts.get(parentCallId)??[];contexts.push(context2);this.nestedHookContexts.set(parentCallId,contexts)};return this.nestedToolScheduler}dispatchCodeModeTool(name2,args,parent,signal,onResult){const allowedNames=parent.codeModeAllowedToolNames?new Set(parent.codeModeAllowedToolNames):void 0;if(!isCodeModeToolCallAllowed(name2,"code_mode",allowedNames)){return Promise.reject(new Error(`Tool "${name2}" is not callable from exec.`))}const callId=`${parent.callId}:code:${++this.nestedSequence}`;const request={callId,name:name2,args,isClientInitiated:true,prompt_id:parent.prompt_id,response_id:parent.response_id,parentCallId:parent.callId,source:"code_mode",goalContext:parent.goalContext};return new Promise((resolve36,reject)=>{this.nestedQueue.push({request,signal,resolve:resolve36,reject,onResult});if(this.nestedFlushScheduled)return;this.nestedFlushScheduled=true;setTimeout(()=>this.flushNestedQueue(),CODE_MODE_BATCH_WINDOW_MS)})}flushNestedQueue(){this.nestedFlushScheduled=false;const entries=this.nestedQueue.splice(0);if(entries.length===0)return;const active=entries.filter(entry=>!entry.signal.aborted);for(const entry of entries){if(entry.signal.aborted)entry.reject(entry.signal.reason)}if(active.length===0)return;const batchController=new AbortController;const abortBatch=__name(event=>{const aborted3=event.currentTarget;batchController.abort(aborted3.reason)},"abortBatch");for(const entry of active){entry.signal.addEventListener("abort",abortBatch,{once:true});this.nestedResolvers.set(entry.request.callId,{resolve:entry.resolve,reject:entry.reject,onResult:entry.onResult})}void runWithoutToolCallRuntime(()=>this.getOrCreateNestedToolScheduler().schedule(active.map(entry=>entry.request),batchController.signal)).catch(error3=>{for(const entry of active){this.nestedResolvers.delete(entry.request.callId);entry.reject(error3)}}).finally(()=>{for(const entry of active){entry.signal.removeEventListener("abort",abortBatch)}})}get memoryMonitor(){return this.config.getMemoryPressureMonitor?.()}compactResultDisplayForInteractiveHistory(resultDisplay){return typeof this.config.isInteractive==="function"&&this.config.isInteractive()?compactToolResultDisplayForHistory(resultDisplay):resultDisplay}async processToolResultImages(responseParts,signal,executionOrigin){if(executionOrigin?.kind==="fixed_policy"){return{responseParts}}let modelOverride;const notices=[];let omniProcessed=responseParts;if(this.config.isOmniEnabled?.()){const{processToolResultOmniMedia}=await import("./tool-result-media-LRBB2KS6.js");omniProcessed=await processToolResultOmniMedia(responseParts,this.config,signal)}const processedParts=await bridgeToolResultImages({config:this.config,responseParts:omniProcessed,signal,onFullTurnModel:__name(model=>{if(!this.onToolResultFullTurnModel?.(model))return false;modelOverride=model;return true},"onFullTurnModel"),onVisionBridgeNotice:__name(notice=>notices.push(notice),"onVisionBridgeNotice")});return{responseParts:processedParts,...modelOverride!==void 0?{modelOverride}:{},...notices.length>0?{visionBridgeNotice:notices.join("\n")}:{}}}setStatusInternal(targetCallId,newStatus,auxiliaryData,executionStatus){this.toolCalls=this.toolCalls.map(currentCall=>{if(currentCall.request.callId!==targetCallId||currentCall.status==="success"||currentCall.status==="error"||currentCall.status==="cancelled"){return currentCall}const existingStartTime=currentCall.startTime;const toolInstance=currentCall.tool;const invocation=currentCall.invocation;if(invocation?.release&&(newStatus==="success"||newStatus==="error"||newStatus==="cancelled")){this.invocationReleases.set(targetCallId,Promise.resolve().then(()=>invocation.release()).catch(error3=>{debugLogger51.warn("Tool invocation resource cleanup failed:",error3)}))}const outcome=currentCall.outcome;switch(newStatus){case"success":{this.clearRetryCountsForTool(currentCall.request.name);const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;return{request:currentCall.request,tool:toolInstance,invocation,status:"success",response:auxiliaryData,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"error":{const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;return{request:currentCall.request,status:"error",tool:toolInstance,invocation,response:auxiliaryData,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"awaiting_approval":return{request:currentCall.request,tool:toolInstance,status:"awaiting_approval",confirmationDetails:auxiliaryData,startTime:existingStartTime,outcome,invocation};case"scheduled":return{request:currentCall.request,tool:toolInstance,status:"scheduled",startTime:existingStartTime,outcome,invocation};case"cancelled":{const durationMs=existingStartTime?Date.now()-existingStartTime:void 0;let resultDisplay=void 0;if(currentCall.status==="awaiting_approval"){const waitingCall=currentCall;if(waitingCall.confirmationDetails.type==="edit"){resultDisplay={fileDiff:waitingCall.confirmationDetails.fileDiff,fileName:waitingCall.confirmationDetails.fileName,filePath:waitingCall.confirmationDetails.filePath,originalContent:waitingCall.confirmationDetails.originalContent,newContent:waitingCall.confirmationDetails.newContent}}else if(waitingCall.confirmationDetails.type==="plan"){resultDisplay={type:"plan_summary",message:"Plan was rejected. Remaining in plan mode.",plan:waitingCall.confirmationDetails.plan,rejected:true}}}else if(currentCall.status==="executing"){const executingCall=currentCall;if(executingCall.liveOutput!==void 0){resultDisplay=executingCall.liveOutput}}const preservedResultDisplay=this.compactResultDisplayForInteractiveHistory(resultDisplay);const response=isToolCallResponseInfo(auxiliaryData)?{...auxiliaryData,executionStatus:auxiliaryData.executionStatus??executionStatus??"not_started",resultDisplay:auxiliaryData.resultDisplay??preservedResultDisplay}:{...createCancelledResponse(currentCall.request,String(auxiliaryData),executionStatus??"not_started"),resultDisplay:preservedResultDisplay};return{request:currentCall.request,tool:toolInstance,invocation,status:"cancelled",response,durationMs,...durationMs!==void 0?{startTime:existingStartTime}:{},outcome}}case"validating":return{request:currentCall.request,tool:toolInstance,status:"validating",startTime:existingStartTime,outcome,invocation};case"executing":return{request:currentCall.request,tool:toolInstance,status:"executing",startTime:existingStartTime,executionStartTime:Date.now(),outcome,invocation};default:{const exhaustiveCheck=newStatus;return exhaustiveCheck}}});this.notifyToolCallsUpdate();void this.checkAndNotifyCompletion().catch(error3=>{debugLogger51.warn(`setStatusInternal completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}setArgsInternal(targetCallId,args){let invocationError;let argsUpdated=false;this.toolCalls=this.toolCalls.map(call=>{if(call.request.callId!==targetCallId||call.status==="success"||call.status==="error"||call.status==="cancelled"){return call}const invocationOrError=runInRequestGoalContext(call.request,()=>this.buildInvocation(call.tool,args,targetCallId,call.request.prompt_id,call.request.executionOrigin?.kind==="client"));if(invocationOrError instanceof Error){invocationError=invocationOrError;const response=createErrorResponse(call.request,invocationOrError,"invalid_tool_params","not_started");return{request:{...call.request,args},status:"error",tool:call.tool,response}}argsUpdated=true;return{...call,request:{...call.request,args},invocation:invocationOrError}});if(invocationError){this.finalizeBlockedSpan(targetCallId,"error","system");const toolSpan=this.toolSpans.get(targetCallId);if(toolSpan){setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,invocationError.message)}this.finalizeToolSpan(targetCallId);this.notifyToolCallsUpdate();void this.checkAndNotifyCompletion().catch(error3=>{debugLogger51.warn(`setArgsInternal completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)});return false}return argsUpdated}isRunning(){return this.isFinalizingToolCalls||this.toolCalls.some(call=>call.status==="executing"||call.status==="awaiting_approval")}cancelPreExecutionIfAborted(callId,signal,toolSpan=this.toolSpans.get(callId)){if(!signal.aborted)return false;this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started");this.finalizeBlockedSpan(callId,"aborted","system");if(toolSpan){setToolSpanCancelled(toolSpan)}this.finalizeToolSpan(callId);return true}finalizeToolSpan(callId,force=false){this.preToolUseIds.delete(callId);this.preToolUseAsks.delete(callId);this.preToolUseSessionHookIds.delete(callId);this.hookReplacedInputCallIds.delete(callId);this.autoModeFallbackCallIds.delete(callId);this.runtimeContentGeneratorViews.delete(callId);if(callId===this.postToolBatchSpanCallId&&!force)return;const span=this.toolSpans.get(callId);if(!span)return;this.toolSpans.delete(callId);endToolSpan(span);this.releaseBatchListenerIfDrained(callId)}finalizeBlockedSpan(callId,decision,source){const span=this.blockedSpans.get(callId);if(!span)return;this.blockedSpans.delete(callId);endToolBlockedOnUserSpan(span,{decision,source})}releaseBatchListenerIfDrained(callId){const batch=this.callIdToBatch.get(callId);if(!batch)return;this.callIdToBatch.delete(callId);batch.callIds.delete(callId);this.releaseIdleBatchListener(batch)}releaseIdleBatchListener(batch){if(batch.preparing)return;for(const id6 of batch.callIds){if(this.toolSpans.has(id6)||this.blockedSpans.has(id6))return}batch.signal.removeEventListener("abort",batch.onAbort)}getBlockedSource(){return this.config.getIdeMode?.()?"ide":"cli"}drainSpansForBatch(callIds){const ids=Array.from(callIds);setTimeout(()=>{for(const callId of ids){try{const call=this.toolCalls.find(c=>c.request.callId===callId);if(call?.status!=="awaiting_approval"&&call?.status!=="scheduled"){continue}this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started");if(this.blockedSpans.has(callId)){this.finalizeBlockedSpan(callId,"aborted","system")}const span=this.toolSpans.get(callId);if(span){setToolSpanCancelled(span);this.finalizeToolSpan(callId,true)}this.callIdToPostToolBatchSignal.delete(callId);this.autoModeFallbackCallIds.delete(callId)}catch(e){debugLogger51.warn(`drainSpansForBatch: failed to drain ${callId}: ${e instanceof Error?e.message:String(e)}`)}}},0)}postToolUseFailureEndMeta=__name(r=>r.hookError?{success:false,error:r.hookError}:{success:true,hasAdditionalContext:!!r.additionalContext},"postToolUseFailureEndMeta");openToolSpan(reqInfo,tool,batchState){const existing=this.toolSpans.get(reqInfo.callId);if(existing)return existing;const canonicalName=canonicalToolName(reqInfo.name);const toolSpan=startToolSpan(canonicalName,{"tool.call_id":reqInfo.callId,"gen_ai.tool.call.id":reqInfo.providerCallId??reqInfo.callId,call_id:reqInfo.callId,tool_name:canonicalName,...reqInfo.parentCallId?{"tool.parent_call_id":reqInfo.parentCallId}:{},...reqInfo.source?{"tool.source":reqInfo.source}:{}},tool.description,reqInfo.prompt_id);this.toolSpans.set(reqInfo.callId,toolSpan);batchState.callIds.add(reqInfo.callId);this.callIdToBatch.set(reqInfo.callId,batchState);return toolSpan}async withHookSpan(opts,fn,toEndMeta){const hookSpan=startHookSpan(opts);let endMeta={success:false};try{const result=await fn();endMeta=toEndMeta(result);return result}catch(err){endMeta={success:false,error:err instanceof Error?err.message:String(err)};throw err}finally{endHookSpan(hookSpan,endMeta)}}buildInvocation(tool,args,callId,promptId,notifyOnCompletion=false){try{const invocation=tool.build(structuredClone(args));const notificationAware=invocation;notificationAware.setCompletionNotificationEnabled?.(notifyOnCompletion);if(callId){const maybeAware=invocation;if(typeof maybeAware.setCallId==="function"){maybeAware.setCallId(callId)}}if(promptId){const maybeAware=invocation;if(typeof maybeAware.setPromptId==="function"){maybeAware.setPromptId(promptId)}}return invocation}catch(e){if(e instanceof Error){return e}return new Error(String(e))}}async getToolNotFoundMessage(unknownToolName,topN=3){const skillTool=await this.toolRegistry.ensureTool(ToolNames.SKILL);if(skillTool&&"getAvailableSkillNames"in skillTool){const availableSkillNames=skillTool.getAvailableSkillNames();if(availableSkillNames.includes(unknownToolName)){return`"${unknownToolName}" is a skill name, not a tool name. To use this skill, invoke the "${ToolNames.SKILL}" tool with parameter: skill: "${unknownToolName}"`}}const mcpMessage=this.getMcpToolUnavailableMessage(unknownToolName);if(mcpMessage){return mcpMessage}const optInToolMessage=await getOptInToolNotFoundMessage(this.config,unknownToolName,async canonicalName=>Boolean(await this.toolRegistry.ensureTool(canonicalName)));if(optInToolMessage){return optInToolMessage}const suggestion=this.getToolSuggestion(unknownToolName,topN);return`Tool "${unknownToolName}" not found in registry. Tools must use the exact names that are registered.${suggestion}`}getMcpToolUnavailableMessage(unknownToolName){if(!unknownToolName.startsWith("mcp__")){return null}const prefixOf=__name(server=>sanitizeToolNameForProvider(`mcp__${server}__`),"prefixOf");const byPrefixLengthDesc=__name((a,b2)=>prefixOf(b2).length-prefixOf(a).length,"byPrefixLengthDesc");const candidates=Array.from(new Set([...this.config.getMcpServerNames?.()??[],...this.config.getRecentlyRemovedMcpServers?.()??[]])).sort(byPrefixLengthDesc);const serverHit=candidates.find(s3=>unknownToolName.startsWith(prefixOf(s3)));if(!serverHit){return`Tool "${unknownToolName}" not found: no MCP server providing it is currently configured. If you recently removed or renamed an MCP server, its tools are no longer available.`}switch(this.config.getMcpServerUnavailableReason?.(serverHit)){case"removed":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" was removed during this session, so its tools were unloaded. Re-add it to your settings to use this tool again.`;case"not_allowed":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is not in the allow-list (mcp.allowed / --allowed-mcp-server-names), so its tools are not loaded. Add it to mcp.allowed to use this tool.`;case"excluded":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is excluded (mcp.excluded), so its tools are not loaded. Remove it from mcp.excluded to use this tool.`;case"pending_approval":return`Tool "${unknownToolName}" is unavailable: the MCP server "${serverHit}" is awaiting approval, so its tools are not loaded. Approve it (run /mcp) to use this tool.`;default:return`Tool "${unknownToolName}" not found on MCP server "${serverHit}". The server may be disconnected, still starting up, or the tool was renamed.`}}getToolSuggestion(unknownToolName,topN=3){const allToolNames=this.toolRegistry.getAllToolNames().filter(name2=>this.toolRegistry.isToolDeclared?.(name2)??true);const matches2=allToolNames.map(toolName=>({name:toolName,distance:import_fast_levenshtein.default.get(unknownToolName,toolName)}));matches2.sort((a,b2)=>{const aIsPrefix=unknownToolName.startsWith(a.name);const bIsPrefix=unknownToolName.startsWith(b2.name);if(aIsPrefix!==bIsPrefix){return aIsPrefix?-1:1}return a.distance-b2.distance});const topNResults=matches2.slice(0,topN);if(topNResults.length===0){return""}const suggestedNames=topNResults.map(match=>`"${match.name}"`).join(", ");if(topNResults.length>1){return` Did you mean one of: ${suggestedNames}?`}else{return` Did you mean ${suggestedNames}?`}}async resolveToolCallBridgeRequest(request,signal){if(signal.aborted||canonicalToolName(request.name)!==ToolNames.TOOL_CALL){return request}const permissionManager=this.config.getPermissionManager?.();if(permissionManager){let bridgeEnabled;try{bridgeEnabled=await permissionManager.isToolEnabled(ToolNames.TOOL_CALL)}catch(error3){if(signal.aborted){return request}const message=error3 instanceof Error?error3.message:String(error3);return{...request,bridgeResolutionError:{error:new Error(`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${message}`),type:"unhandled_exception"}}}if(signal.aborted||!bridgeEnabled){return request}}else if((this.config.getPermissionsDeny?.()??[]).some(name2=>canonicalToolName(name2).toLowerCase().trim()===ToolNames.TOOL_CALL)){return request}const resolution=await runInRequestGoalContext(request,()=>resolveDeferredToolCall(this.toolRegistry,request.args,{maxSubagentDepth:this.config.getMaxSubagentDepth()}));if("error"in resolution){return{...request,bridgeResolutionError:{error:resolution.error,type:resolution.errorType}}}if(this.isToolExecutionAllowed&&!this.isToolExecutionAllowed(resolution.tool.name)){return{...request,bridgeResolutionError:{error:new Error(`Tool "${resolution.tool.name}" is not permitted by this agent's tool policy (execution allowlist or disallowedTools blocklist).`),type:"execution_denied"}}}return{...request,name:resolution.tool.name,args:resolution.arguments,modelFacingName:request.name,modelFacingArgs:request.args}}schedule(request,signal,runtimeView){const owner=captureHookExecutionOwner(this.config);if(this.isRunning()||this.isScheduling){if(signal.aborted){return Promise.reject(new Error("Tool call cancelled while in queue."))}return new Promise((resolve36,reject)=>{const abortHandler=__name(()=>{const index=this.requestQueue.findIndex(item=>item.request===request);if(index>-1){this.requestQueue.splice(index,1);reject(new Error("Tool call cancelled while in queue."))}},"abortHandler");signal.addEventListener("abort",abortHandler,{once:true});this.requestQueue.push({request,signal,runtimeView,owner,resolve:__name(()=>{signal.removeEventListener("abort",abortHandler);resolve36()},"resolve"),reject:__name(reason=>{signal.removeEventListener("abort",abortHandler);reject(reason)},"reject")})})}return this.scheduleWithOwner(request,signal,runtimeView,owner)}scheduleWithOwner(request,signal,runtimeView,owner){const items=Array.isArray(request)?request:[request];for(const item of items)this.hookOwners.set(item.callId,owner);return runWithHookExecutionOwner(owner,()=>this._schedule(request,signal,runtimeView)).catch(error3=>{for(const item of items){this.hookOwners.delete(item.callId);this.preToolUseContexts.delete(item.callId);this.nestedHookContexts.delete(item.callId);this.failureContextsForParent.delete(item.callId)}throw error3})}drainRequestQueueIfIdle(){if(this.requestQueue.length===0||this.isScheduling||this.isRunning()){return}const next=this.requestQueue.shift();this.scheduleWithOwner(next.request,next.signal,next.runtimeView,next.owner).then(next.resolve).catch(next.reject)}clearRetryCountsForTool(toolName){const prefix2=`${toolName}:`;for(const key of this.validationRetryCounts.keys()){if(key.startsWith(prefix2)){this.validationRetryCounts.delete(key)}}}recordRetryableToolError(toolName,errorMessage){const errorKey=`${toolName}:${errorMessage}`;const count4=(this.validationRetryCounts.get(errorKey)??0)+1;for(const key of this.validationRetryCounts.keys()){if(key.startsWith(`${toolName}:`)&&key!==errorKey){this.validationRetryCounts.delete(key)}}this.validationRetryCounts.set(errorKey,count4);return count4}async _schedule(request,signal,runtimeView){if(runtimeView){const items=Array.isArray(request)?request:[request];for(const item of items){this.runtimeContentGeneratorViews.set(item.callId,runtimeView)}try{return await runWithRuntimeContentGenerator(runtimeView,()=>this._schedule(request,signal))}catch(error3){for(const item of items){this.runtimeContentGeneratorViews.delete(item.callId)}throw error3}}this.isScheduling=true;let preparedBatch;try{if(this.isRunning()){throw new Error("Cannot schedule new tool calls while other tool calls are actively running (executing or awaiting approval).")}const requestsToProcess=await Promise.all(dedupeRequestsByCallId(Array.isArray(request)?request:[request]).map(item=>this.resolveToolCallBridgeRequest({...item,args:structuredClone(item.args)},signal)));const planModeEntryBoundaryIndex=findPlanModeEntryBatchBoundaryIndex(requestsToProcess.map(item=>canonicalToolName(item.name)));if(this.validationRetryCounts.size>0){const currentToolNames=new Set(requestsToProcess.map(r=>r.name));for(const key of[...this.validationRetryCounts.keys()]){const sep21=key.indexOf(":");const toolName=sep21===-1?key:key.slice(0,sep21);if(!currentToolNames.has(toolName)){this.validationRetryCounts.delete(key)}}}const newToolCalls=[];const retryErrorsRecordedInBatch=new Map;const recordBatchRetryableToolError=__name((toolName,errorMessage)=>{const key=`${toolName}:${errorMessage}`;const existingCount=retryErrorsRecordedInBatch.get(key);if(existingCount!==void 0){for(const trackedKey of this.validationRetryCounts.keys()){if(trackedKey.startsWith(`${toolName}:`)){this.validationRetryCounts.delete(trackedKey)}}this.validationRetryCounts.set(key,existingCount);return existingCount}const count4=this.recordRetryableToolError(toolName,errorMessage);retryErrorsRecordedInBatch.set(key,count4);return count4},"recordBatchRetryableToolError");const batchState={signal,onAbort:__name(()=>this.drainSpansForBatch(batchState.callIds),"onAbort"),callIds:new Set,preparing:true};preparedBatch=batchState;signal.addEventListener("abort",batchState.onAbort,{once:true});for(const[requestIndex,reqInfo]of requestsToProcess.entries()){let resolvedTool;let resolvedInvocation;const recordPrevalidationCancellation=__name(()=>{if(!signal.aborted)return false;newToolCalls.push({status:"cancelled",request:reqInfo,response:createCancelledResponse(reqInfo,"Tool call cancelled before execution.","not_started"),...resolvedTool?{tool:resolvedTool}:{},...resolvedInvocation?{invocation:resolvedInvocation}:{},durationMs:0});return true},"recordPrevalidationCancellation");try{if(recordPrevalidationCancellation())continue;if(planModeEntryBoundaryIndex!==void 0&&requestIndex!==planModeEntryBoundaryIndex){newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE),"execution_denied","not_started"),durationMs:0});continue}if(reqInfo.bridgeResolutionError){let bridgeError=reqInfo.bridgeResolutionError.error;if(reqInfo.bridgeResolutionError.type==="invalid_tool_params"){const count4=recordBatchRetryableToolError(reqInfo.name,bridgeError.message);if(count4>=VALIDATION_RETRY_LOOP_THRESHOLD){bridgeError=new Error(`${bridgeError.message}${RETRY_LOOP_STOP_DIRECTIVE}`)}}newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,bridgeError,reqInfo.bridgeResolutionError.type,"not_started"),durationMs:0});continue}const canonicalName=canonicalToolName(reqInfo.name);if(this.config.getToolMode?.()===ToolMode.CodeModeOnly&&reqInfo.executionOrigin?.kind!=="fixed_policy"&&!isCodeModeToolCallAllowed(canonicalName,reqInfo.source??"model")){newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(`Tool "${reqInfo.name}" is unavailable on this CodeModeOnly call surface.`),"execution_denied","not_started"),durationMs:0});continue}const pm=this.config.getPermissionManager?.();const toolAliases2=this.config.getToolRegistry?.()?.getPermissionAliases?.(canonicalName);const mcpIdentity=this.config.getToolRegistry?.()?.getMcpToolIdentity?.(canonicalName);const permissionEnabled=pm?await pm.isToolEnabled(canonicalName,toolAliases2,mcpIdentity):true;if(recordPrevalidationCancellation())continue;if(pm&&!permissionEnabled){const matchingRule=pm.findMatchingDenyRule({toolName:canonicalName,toolAliases:toolAliases2,mcpIdentity});let permissionErrorMessage;if(matchingRule){permissionErrorMessage=`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined. Matching deny rule: "${matchingRule}".`}else if(typeof pm.isToolDisabledByCoreToolsAllowList==="function"&&pm.isToolDisabledByCoreToolsAllowList(canonicalName)){permissionErrorMessage=`"${reqInfo.name}" is not listed in the active core tools allowlist (--core-tools or settings tools.core), so the tool is not available. Add it to the core tools list to re-enable it.`}else{permissionErrorMessage=`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined.`}newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(canonicalName===ToolNames.TOOL_CALL?`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${permissionErrorMessage}`:permissionErrorMessage),"execution_denied","not_started"),durationMs:0});continue}if(!pm){const excludeTools=this.config.getPermissionsDeny?.()??void 0;if(excludeTools&&excludeTools.length>0){const normalizedToolName=canonicalName.toLowerCase().trim();const excludedMatch=excludeTools.find(excludedTool=>excludedTool.toLowerCase().trim()===normalizedToolName);if(excludedMatch){const permissionErrorMessage=`Qwen Code requires permission to use ${excludedMatch}, but that permission was declined.`;newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(canonicalName===ToolNames.TOOL_CALL?`${DEFERRED_TOOL_CALL_REFUSAL_PREFIX}${permissionErrorMessage}`:permissionErrorMessage),"execution_denied","not_started"),durationMs:0});continue}}}const toolInstance=await runInRequestGoalContext(reqInfo,()=>this.toolRegistry.ensureTool(canonicalName));resolvedTool=toolInstance;if(recordPrevalidationCancellation())continue;if(!toolInstance){const errorMessage=await runInRequestGoalContext(reqInfo,()=>this.getToolNotFoundMessage(reqInfo.name));if(recordPrevalidationCancellation())continue;newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,new Error(errorMessage),"tool_not_registered","not_started"),durationMs:0});continue}if((reqInfo.wasOutputTruncated||reqInfo.hadIncompleteArguments)&&toolInstance.kind==="edit"){const truncated=reqInfo.wasOutputTruncated===true;const rejectionMessage=truncated?TRUNCATION_EDIT_REJECTION:INCOMPLETE_ARGS_EDIT_REJECTION;const count4=recordBatchRetryableToolError(reqInfo.name,rejectionMessage);const truncationError=new Error(count4>=VALIDATION_RETRY_LOOP_THRESHOLD?`${rejectionMessage}${truncated?TRUNCATION_RETRY_LOOP_DIRECTIVE:INCOMPLETE_ARGS_RETRY_LOOP_DIRECTIVE}`:rejectionMessage);newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,truncationError,truncated?"output_truncated":"invalid_tool_params","not_started"),durationMs:0});continue}const preToolUseTerminal=await this.runPreToolUse(reqInfo,toolInstance,batchState,signal);if(preToolUseTerminal){newToolCalls.push(preToolUseTerminal);continue}if(recordPrevalidationCancellation())continue;const policyGate=evaluateMediaPolicyToolCall({config:this.config,tool:toolInstance,args:reqInfo.args,executionOrigin:reqInfo.executionOrigin});if(policyGate.outcome==="reject"){newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,new Error(policyGate.message),policyGate.reason==="invalid_params"?"invalid_tool_params":"execution_denied","not_started"),durationMs:0});continue}const refusal=this.schedulerOptions.refuseToolCall?.({...reqInfo,args:policyGate.args});if(refusal!==void 0){newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,new Error(refusal),"execution_denied","not_started"),durationMs:0});continue}const invocationOrError=runInRequestGoalContext(reqInfo,()=>this.buildInvocation(toolInstance,policyGate.args,reqInfo.callId,reqInfo.prompt_id,reqInfo.executionOrigin?.kind==="client"));if(recordPrevalidationCancellation())continue;if(invocationOrError instanceof Error){const targetMessage=reqInfo.modelFacingName!==void 0?describeBridgedArgumentError(reqInfo.name,invocationOrError.message):invocationOrError.message;const paramGuidance=reqInfo.wasOutputTruncated?TRUNCATION_PARAM_GUIDANCE:reqInfo.hadIncompleteArguments?INCOMPLETE_ARGS_PARAM_GUIDANCE:void 0;const displayError=paramGuidance?new Error(`${targetMessage} ${paramGuidance}`):reqInfo.modelFacingName!==void 0?new Error(targetMessage):invocationOrError;const count4=recordBatchRetryableToolError(reqInfo.name,invocationOrError.message);const finalError=count4>=VALIDATION_RETRY_LOOP_THRESHOLD?new Error(`${targetMessage}${RETRY_LOOP_STOP_DIRECTIVE}`):displayError;newToolCalls.push({status:"error",request:reqInfo,tool:toolInstance,response:createErrorResponse(reqInfo,finalError,"invalid_tool_params","not_started"),durationMs:0});continue}resolvedInvocation=invocationOrError;this.clearRetryCountsForTool(reqInfo.name);newToolCalls.push({status:"validating",request:reqInfo,tool:toolInstance,invocation:invocationOrError,startTime:Date.now()})}catch(error3){if(recordPrevalidationCancellation())continue;const normalizedError=error3 instanceof Error?error3:new Error(String(error3));newToolCalls.push({status:"error",request:reqInfo,response:createErrorResponse(reqInfo,normalizedError,error3?.errorType??"unhandled_exception","not_started"),...resolvedTool?{tool:resolvedTool}:{},durationMs:0})}}for(const toolCall of newToolCalls){const span=this.toolSpans.get(toolCall.request.callId);if(!span||toolCall.status==="validating")continue;if(toolCall.status==="cancelled"){setToolSpanCancelled(span)}else if(toolCall.status==="error"){setToolSpanFailure(span,TOOL_FAILURE_KIND_TOOL_EXCEPTION,toolCall.response.error?.message??"Tool call failed validation.")}this.finalizeToolSpan(toolCall.request.callId)}this.toolCalls=this.toolCalls.concat(newToolCalls);for(const toolCall of newToolCalls){this.callIdToPostToolBatchSignal.set(toolCall.request.callId,signal)}const postToolBatchParentCallId=newToolCalls.findLast(toolCall=>toolCall.status==="validating")?.request.callId;this.postToolBatchEnabledForBatch=false;this.postToolBatchSpanCallId=void 0;try{this.postToolBatchEnabledForBatch=!this.config.getDisableAllHooks()&&(this.config.hasHooksForEvent?.("PostToolBatch")??false);if(this.postToolBatchEnabledForBatch){this.postToolBatchSpanCallId=postToolBatchParentCallId}}catch(configError){this.postToolBatchEnabledForBatch=true;this.postToolBatchSpanCallId=postToolBatchParentCallId;if(!this.postToolBatchConfigWarned){this.postToolBatchConfigWarned=true;debugLogger51.warn("PostToolBatch hook detection failed; deferring span as a precaution:",configError)}}this.notifyToolCallsUpdate();const permissionRequestGrants=new Set;for(const toolCall of newToolCalls){if(toolCall.status!=="validating"){continue}const{request:reqInfo,invocation}=toolCall;const canonicalName=canonicalToolName(reqInfo.name);const toolSpan=this.openToolSpan(reqInfo,toolCall.tool,batchState);let preToolUseAsk=this.preToolUseAsks.get(reqInfo.callId);let modAsk;try{if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(reqInfo.executionOrigin?.kind==="fixed_policy"){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}let toolParams=invocation.params;const flowResult=await runInRequestGoalContext(reqInfo,()=>evaluatePermissionFlow(this.config,invocation,canonicalName,toolParams,signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const modToolCheck=this.schedulerOptions.modToolCheck;if(modToolCheck){const isReadOnly=canonicalName===ToolNames.SHELL?flowResult.defaultPermission==="allow":CONCURRENCY_SAFE_KINDS.has(toolCall.tool.kind);const approver=!this.canPromptForPreToolUseAsk()?void 0:this.config.isInteractive()||this.config.getExperimentalZedIntegration()?"person":"host";const decision=await runInRequestGoalContext(reqInfo,()=>modToolCheck({tool:canonicalName,input:structuredClone(toolParams),tool_use_id:reqInfo.callId,...approver&&{approver},...isReadOnly&&{isReadOnly:true}},{decision:flowResult.finalPermission==="default"?"ask":flowResult.finalPermission,...flowResult.denyMessage?{reason:flowResult.denyMessage}:{}},signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(!["allow","ask","deny"].includes(decision.decision)){throw new Error("Invalid Mod tool.check decision.")}if(flowResult.finalPermission!=="deny"){if(decision.decision==="deny"){flowResult.finalPermission="deny";flowResult.denyMessage=decision.reason?.trim()||`Tool "${reqInfo.name}" is denied by a Mod.`}else if(decision.decision==="ask"){if(flowResult.finalPermission==="allow")flowResult.finalPermission="ask";if(decision.plugin!==void 0&&!preToolUseAsk){modAsk=preToolUseAsk=decision.reason?.trim()?`Mod ${decision.plugin}: ${decision.reason.trim()}`:`Mod ${decision.plugin} requested confirmation before running ${reqInfo.name}.`;this.preToolUseAsks.set(reqInfo.callId,preToolUseAsk)}}}}const{defaultPermission,finalPermission,pmForcedAsk,pmCtx,denyMessage,requiresUserInteraction}=flowResult;const approvalMode=this.config.getApprovalMode();const isPlanMode=approvalMode==="plan";const isPlanShellCall=isPlanMode&&(canonicalName===ToolNames.SHELL||canonicalName===ToolNames.MONITOR);const isExitPlanModeTool=canonicalName===ToolNames.EXIT_PLAN_MODE;const isEnterPlanModeTool=canonicalName===ToolNames.ENTER_PLAN_MODE;const forceAutoReviewForAllow=approvalMode==="auto"&&(shouldForceAutoModeReviewForAllow(pmCtx,this.config.getCwd())||shouldClassifyAllShellForAutoMode(canonicalName,this.config));const confirmationPermission=getEffectivePermissionForConfirmation(finalPermission,forceAutoReviewForAllow);if(finalPermission==="allow"&&forceAutoReviewForAllow){debugLogger51.info(`Auto mode: L4 allow overridden by protected-write guard for ${canonicalName}`)}if(isPlanRequiredTeammateAwaitingApproval(this.config)&&finalPermission!=="deny"){const isExplicitPreApprovalTool=isPlanRequiredTeammatePreApprovalAllowedTool(canonicalName,toolParams);const canRunBeforeLeaderApproval=!preToolUseAsk&&isExplicitPreApprovalTool&&(canonicalName===ToolNames.EXIT_PLAN_MODE||canonicalName===ToolNames.TASK_UPDATE||defaultPermission==="allow"&&finalPermission==="allow"&&!forceAutoReviewForAllow);if(canRunBeforeLeaderApproval){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}const message=getPlanRequiredTeammatePreApprovalMessage(canonicalName);this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(message),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId);continue}if(finalPermission==="deny"){this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(denyMessage??`Tool "${reqInfo.name}" is denied.`),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_DENIED,TOOL_SPAN_STATUS_PERMISSION_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}let planShellAmbientWorkingDirectory;if(isPlanShellCall){const directory=toolParams["directory"];planShellAmbientWorkingDirectory=typeof directory==="string"&&directory.length>0?void 0:this.config.getTargetDir();invocation.params={...structuredClone(invocation.params),directory:typeof directory==="string"&&directory.length>0?directory:planShellAmbientWorkingDirectory};toolParams=invocation.params}const planShellDecision=isPlanShellCall?await runInRequestGoalContext(reqInfo,()=>evaluatePlanModeShellPolicy({config:this.config,toolName:canonicalName,requestArgs:reqInfo.args,invocationParams:toolParams,permissionContext:pmCtx,ambientWorkingDirectory:planShellAmbientWorkingDirectory,signal})):{classification:"not-applicable"};if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const rejectPlanShell=__name(message=>{this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,new Error(message),"execution_denied","not_started"),resultDisplay:message});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId)},"rejectPlanShell");if(planShellDecision.classification!=="not-applicable"){const initialPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(initialPlanShellError){rejectPlanShell(initialPlanShellError);continue}}if(planShellDecision.classification==="write"){rejectPlanShell(planShellDecision.writeBlockMessage);continue}const planShellRequiresConfirmation=planShellDecision.classification==="unknown";if(finalPermission==="allow"&&!forceAutoReviewForAllow&&!planShellRequiresConfirmation&&!preToolUseAsk){if(approvalMode==="auto"){const actionFingerprint=getAutoModeActionFingerprint(canonicalName,toolParams,this.config.getCwd());this.config.setAutoModeDenialState(recordAllow(this.config.getAutoModeDenialState(),actionFingerprint))}this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}let autoModeFallback;let autoModeFallbackRequiresHuman=false;if(!requiresUserInteraction&&!preToolUseAsk&&shouldRunAutoModeForCall(approvalMode,canonicalName)){const actionFingerprint=getAutoModeActionFingerprint(canonicalName,toolParams,this.config.getCwd());const{denialState,fallback}=prepareAutoModeFallback(this.config,actionFingerprint);const llmClient=this.config.getLlmClient?.();const messages=llmClient?.getHistoryTail(MAX_TRANSCRIPT_MESSAGES,false)??[];const trustedUserAnswers=llmClient?.getTrustedUserAnswers?.()??[];const decision=await runInRequestGoalContext(reqInfo,()=>evaluateAutoMode({ctx:pmCtx,pmForcedAsk,toolParams,messages,trustedUserAnswers,config:this.config,signal,skipClassifierReason:fallback.fallback?fallback.reason:void 0}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const outcome=applyAutoModeDecision(decision,this.config,denialState,actionFingerprint);if(!this.config.getDisableAllHooks()&&shouldFirePermissionDeniedForAutoMode(decision,outcome)){try{await runInRequestGoalContext(reqInfo,()=>this.config.getHookSystem?.()?.firePermissionDeniedEvent(canonicalName,toolParams,reqInfo.callId,getAutoModePermissionDeniedReason(decision),signal,reqInfo.callId))}catch(hookError){debugLogger51.warn(`PermissionDenied hook failed for tool ${reqInfo.callId}: ${hookError instanceof Error?hookError.message:String(hookError)}`)}}if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}switch(outcome.kind){case"approved":this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue;case"blocked":debugLogger51.warn(`Auto mode blocked (${outcome.reason}): tool=${canonicalName}, `+formatDenialStateLog(denialState));this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(outcome.errorMessage),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_DENIED,outcome.errorMessage);this.finalizeToolSpan(reqInfo.callId);continue;case"fallback":autoModeFallbackRequiresHuman=outcome.requiresHumanDecision===true;if(outcome.message&&(isDenialFallbackReason(outcome.reason)||outcome.reason==="classifier_unavailable")){this.autoModeFallbackCallIds.add(reqInfo.callId);autoModeFallback={reason:outcome.reason,message:outcome.message};debugLogger51.warn(`Auto mode fallback to manual approval (${outcome.reason}): `+formatDenialStateLog(denialState))}else if((outcome.reason==="external_write"||outcome.reason==="external_directory")&&outcome.message){this.autoModeFallbackCallIds.add(reqInfo.callId);autoModeFallback={reason:outcome.reason,message:outcome.message};debugLogger51.warn(`Auto mode fallback to manual approval (${outcome.reason}): target outside workspace.`)}break;default:{const _exhaustive=outcome;void _exhaustive}}}const isAskUserQuestionTool=canonicalName===ToolNames.ASK_USER_QUESTION;let confirmationDetails;if(!preToolUseAsk&&!needsConfirmation(planShellRequiresConfirmation?"ask":confirmationPermission,approvalMode,canonicalName,requiresUserInteraction)){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled")}else{confirmationDetails=await runInRequestGoalContext(reqInfo,()=>invocation.getConfirmationDetails(signal));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(autoModeFallback){confirmationDetails=decorateAutoModeFallbackConfirmation(confirmationDetails,autoModeFallback.reason,autoModeFallback.message)}if(planShellDecision.classification!=="not-applicable"){const preDisplayPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(preDisplayPlanShellError){rejectPlanShell(preDisplayPlanShellError);continue}}try{confirmationDetails=decoratePlanModeShellConfirmation(planShellDecision,confirmationDetails)}catch{if(planShellDecision.classification==="unknown"){rejectPlanShell(planShellDecision.noApprovalMessage);continue}throw new Error("Unable to prepare shell confirmation.")}const planModeDetails=confirmationDetails;if(preToolUseAsk){confirmationDetails=withPreToolUseAskReason(confirmationDetails,preToolUseAsk)}injectPermissionRulesIfMissing(confirmationDetails,pmCtx);if(planShellDecision.classification==="not-applicable"&&isPlanModeBlocked(isPlanMode,isExitPlanModeTool,isAskUserQuestionTool,planModeDetails,isEnterPlanModeTool)){const isPlanRequiredTeammate=!shouldUsePlanOnlyReminderInSubagentContext()&&!this.config.getSdkMode();const planModeError=new Error(`Tool blocked by plan mode: "${reqInfo.name}" is not a read-only tool. Only read-only tools (read_file, grep_search, glob, web_fetch, etc.) are allowed in plan mode. Do NOT retry this tool. `+(isPlanRequiredTeammate?`Pivot to read-only alternatives to gather the information you need, then call exit_plan_mode with a plan that covers this tool's purpose.`:`Pivot to read-only alternatives to gather equivalent information, then present your plan directly to the caller.`));this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,planModeError,"execution_denied","not_started"),resultDisplay:"Plan mode blocked a non-read-only tool call."});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PLAN_MODE_BLOCKED,TOOL_SPAN_STATUS_PLAN_MODE_BLOCKED);this.finalizeToolSpan(reqInfo.callId);continue}if(!requiresUserInteraction&&!preToolUseAsk&&isAutoEditApproved(approvalMode,confirmationDetails)){this.setToolCallOutcome(reqInfo.callId,"proceed_always");this.setStatusInternal(reqInfo.callId,"scheduled");continue}const isNonInteractiveDeny=!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&(this.config.getInputFormat()!=="stream-json"||autoModeFallbackRequiresHuman);if(isNonInteractiveDeny){const errorMessage=planShellDecision.classification==="unknown"?planShellDecision.noApprovalMessage:modAsk?`Qwen Code could not ask the user to confirm "${reqInfo.name}" in non-interactive mode, so it was not run. ${modAsk}`:`Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined (non-interactive mode cannot prompt for confirmation).`;if(planShellDecision.classification==="unknown"){rejectPlanShell(errorMessage);continue}this.setStatusInternal(reqInfo.callId,"error",{...createErrorResponse(reqInfo,new Error(errorMessage),"execution_denied","not_started"),...!preToolUseAsk&&{approvalRequired:true}});setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_NON_INTERACTIVE_DENIED,TOOL_SPAN_STATUS_NON_INTERACTIVE_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}const preparedConfirmationDetails=confirmationDetails;const messageBus=this.config.getMessageBus();const hooksEnabled=!this.config.getDisableAllHooks();const permissionRequestGrant=permissionRequestGrants.has(reqInfo.callId);if(hooksEnabled&&messageBus||permissionRequestGrant){const permissionMode=String(this.config.getApprovalMode());const hookResult=permissionRequestGrant?{hasDecision:true,shouldAllow:true}:await runInRequestGoalContext(reqInfo,()=>firePermissionRequestHook(messageBus,canonicalName,reqInfo.args||{},permissionMode,void 0,signal,this.hookOwners.get(reqInfo.callId)));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}const allowApplies=hookResult.shouldAllow===true&&!requiresUserInteraction&&!autoModeFallbackRequiresHuman&&(!preToolUseAsk||hookResult.updatedInput!==void 0&&planShellDecision.classification==="not-applicable");if(hookResult.hasDecision&&(!hookResult.shouldAllow||allowApplies)){if(hookResult.shouldAllow){if(planShellDecision.classification!=="not-applicable"){const approval=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellApproval({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal,outcome:"proceed_once",payload:hookResult.updatedInput?{updatedInput:hookResult.updatedInput}:void 0}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(approval.outcome==="cancel"){await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm(approval.outcome,approval.payload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}rejectPlanShell(approval.payload?.cancelMessage??planShellDecision.noApprovalMessage);continue}await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm(approval.outcome,approval.payload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,approval.outcome);this.setToolCallOutcome(reqInfo.callId,approval.outcome);this.setStatusInternal(reqInfo.callId,"scheduled");continue}if(hookResult.updatedInput){const rebuilt=this.rebuildWithPermissionRequestInput(reqInfo,toolCall.tool,hookResult.updatedInput,toolSpan);if(rebuilt){permissionRequestGrants.add(reqInfo.callId);newToolCalls.push(rebuilt)}continue}await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm("proceed_once"));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,"proceed_once");this.setToolCallOutcome(reqInfo.callId,"proceed_once");this.setStatusInternal(reqInfo.callId,"scheduled")}else{const cancelPayload=hookResult.denyMessage?{cancelMessage:hookResult.denyMessage}:void 0;await runInRequestGoalContext(reqInfo,()=>preparedConfirmationDetails.onConfirm("cancel",cancelPayload));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}this.recordAutoModeFallbackResolution(reqInfo.callId,"cancel");this.setToolCallOutcome(reqInfo.callId,"cancel");this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(hookResult.denyMessage||`Permission denied by hook for "${reqInfo.name}"`),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PERMISSION_HOOK_DENIED,TOOL_SPAN_STATUS_PERMISSION_HOOK_DENIED);this.finalizeToolSpan(reqInfo.callId)}continue}}if(this.config.getShouldAvoidPermissionPrompts?.()){const errorMessage=planShellDecision.classification==="unknown"?planShellDecision.noApprovalMessage:`Tool "${reqInfo.name}" requires permission, but background agents cannot prompt for confirmation. The tool call was denied.`;if(planShellDecision.classification==="unknown"){rejectPlanShell(errorMessage);continue}this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,new Error(errorMessage),"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_BACKGROUND_AGENT_DENIED,TOOL_SPAN_STATUS_BACKGROUND_AGENT_DENIED);this.finalizeToolSpan(reqInfo.callId);continue}if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(planShellDecision.classification!=="not-applicable"){const finalPreDisplayPlanShellError=await runInRequestGoalContext(reqInfo,()=>validatePlanModeShellContext({config:this.config,decision:planShellDecision,requestArgs:reqInfo.args,invocationParams:invocation.params,signal}));if(this.cancelPreExecutionIfAborted(reqInfo.callId,signal,toolSpan)){continue}if(finalPreDisplayPlanShellError){rejectPlanShell(finalPreDisplayPlanShellError);continue}}if(confirmationDetails.type!=="edit"||!confirmationDetails.skipIdeDiff){this.openIdeDiffIfEnabled(confirmationDetails,reqInfo.callId,signal)}const originalOnConfirm=confirmationDetails.onConfirm;const invocationContext=getInvocationContext();let planShellResponseClaimed=false;const wrappedConfirmationDetails={...confirmationDetails,...pmForcedAsk||requiresUserInteraction||preToolUseAsk?{hideAlwaysAllow:true}:{},onConfirm:__name(async(outcome,payload)=>runWithInvocationContext(invocationContext,async()=>{await runInRequestGoalContext(reqInfo,async()=>{if(planShellDecision.classification!=="not-applicable"){if(planShellResponseClaimed)return;planShellResponseClaimed=true;const currentCall=this.toolCalls.find(call=>call.request.callId===reqInfo.callId&&call.status==="awaiting_approval");if(!currentCall)return;const approval=await validatePlanModeShellApproval({config:this.config,decision:planShellDecision,requestArgs:currentCall.request.args,invocationParams:currentCall.invocation.params,signal,outcome,payload});await this.handleConfirmationResponse(reqInfo.callId,originalOnConfirm,approval.outcome,signal,approval.payload);return}await this.handleConfirmationResponse(reqInfo.callId,originalOnConfirm,outcome,signal,payload)})}),"onConfirm")};this.setStatusInternal(reqInfo.callId,"awaiting_approval",wrappedConfirmationDetails);const blockedSpan=startToolBlockedOnUserSpan(toolSpan,{tool_name:canonicalName,call_id:reqInfo.callId});this.blockedSpans.set(reqInfo.callId,blockedSpan);if(hooksEnabled&&messageBus){fireNotificationHook(messageBus,`Qwen Code needs your permission to use ${reqInfo.name}`,"permission_prompt","Permission needed",void 0,this.hookOwners.get(reqInfo.callId)).then(({terminalSequence})=>{if(terminalSequence){this.schedulerOptions.onPermissionPromptTerminalSequence?.(terminalSequence)}}).catch(error3=>{debugLogger51.warn(`Permission prompt notification hook failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}}}catch(error3){if(signal.aborted){this.setStatusInternal(reqInfo.callId,"cancelled","Tool call cancelled by user.","not_started");this.finalizeBlockedSpan(reqInfo.callId,"aborted","system");setToolSpanCancelled(toolSpan);this.finalizeToolSpan(reqInfo.callId);continue}const explicitErrorType=error3?.errorType;this.setStatusInternal(reqInfo.callId,"error",createErrorResponse(reqInfo,error3 instanceof Error?error3:new Error(String(error3)),explicitErrorType??"unhandled_exception","not_started"));this.finalizeBlockedSpan(reqInfo.callId,"error","system");setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,error3 instanceof Error?error3.message:String(error3));this.finalizeToolSpan(reqInfo.callId)}}batchState.preparing=false;await this.attemptExecutionOfScheduledCalls(signal);void this.checkAndNotifyCompletion().catch(error3=>{debugLogger51.warn(`_schedule completion notification failed: ${error3 instanceof Error?error3.message:String(error3)}`)})}finally{if(preparedBatch){preparedBatch.preparing=false;this.releaseIdleBatchListener(preparedBatch)}this.isScheduling=false;this.drainRequestQueueIfIdle()}}async handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload){const owner=this.hookOwners.get(callId);if(getHookExecutionOwner()!==owner){return runWithHookExecutionOwner(owner,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const runtimeView=this.runtimeContentGeneratorViews.get(callId);if(runtimeView&&getRuntimeContentGenerator()!==runtimeView){return runWithRuntimeContentGenerator(runtimeView,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const toolCall=this.toolCalls.find(c=>c.request.callId===callId&&c.status==="awaiting_approval");if(!toolCall){if(this.nestedToolScheduler?.toolCalls.some(call=>call.request.callId===callId)){return this.nestedToolScheduler.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload)}return}if(goalTurnContext.getStore()!==toolCall.request.goalContext){return runInRequestGoalContext(toolCall.request,()=>this.handleConfirmationResponse(callId,originalOnConfirm,outcome,signal,payload))}const claimsAskUserQuestionResponse=toolCall.tool instanceof AskUserQuestionTool&&toolCall.confirmationDetails.type==="ask_user_question";if(claimsAskUserQuestionResponse&&this.askUserQuestionResponseClaims.has(callId)){return}if(claimsAskUserQuestionResponse){this.askUserQuestionResponseClaims.add(callId)}try{await this._handleConfirmationResponseInner(callId,toolCall,originalOnConfirm,outcome,signal,payload)}catch(error3){const aborted3=signal.aborted;if(aborted3){this.setStatusInternal(callId,"cancelled","Tool call cancelled by user.","not_started")}else{this.setStatusInternal(callId,"error",createErrorResponse(toolCall.request,error3 instanceof Error?error3:new Error(String(error3)),"unhandled_exception","not_started"))}this.finalizeBlockedSpan(callId,aborted3?"aborted":"error","system");const toolSpan=this.toolSpans.get(callId);if(toolSpan){if(aborted3){setToolSpanCancelled(toolSpan)}else{setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,error3 instanceof Error?error3.message:String(error3))}}this.finalizeToolSpan(callId);debugLogger51.warn(`handleConfirmationResponse failed for ${callId}: ${error3 instanceof Error?error3.message:String(error3)}`);throw error3}finally{if(claimsAskUserQuestionResponse){this.askUserQuestionResponseClaims.delete(callId)}}await this.attemptExecutionOfScheduledCalls(signal)}async _handleConfirmationResponseInner(callId,toolCall,originalOnConfirm,outcome,signal,payload){const shouldSwitchToDefault=outcome==="proceed_once_and_switch_to_default";const normalizedOutcome=shouldSwitchToDefault?"proceed_once":outcome;const isCurrentApproval=__name(()=>!signal.aborted&&this.toolCalls.includes(toolCall)&&toolCall.status==="awaiting_approval","isCurrentApproval");const isCurrentCancellation=__name(()=>outcome==="cancel"&&this.toolCalls.includes(toolCall)&&toolCall.status==="awaiting_approval","isCurrentCancellation");if(!isCurrentApproval()&&!isCurrentCancellation())return;if(!signal.aborted)await originalOnConfirm(normalizedOutcome,payload);if(!isCurrentApproval()&&!isCurrentCancellation())return;if(shouldSwitchToDefault){this.config.setApprovalMode("default")}outcome=normalizedOutcome;if(outcome==="proceed_always"||outcome==="proceed_always_project"||outcome==="proceed_always_user"){await persistPermissionOutcome(outcome,toolCall.confirmationDetails,this.config.getOnPersistPermissionRule?.(),this.config.getPermissionManager?.(),payload,isCurrentApproval);if(!isCurrentApproval())return;await this.autoApproveCompatiblePendingTools(signal,callId,isCurrentApproval);if(!isCurrentApproval())return}this.setToolCallOutcome(callId,outcome);this.recordAutoModeFallbackResolution(callId,outcome);if(outcome==="cancel"||signal.aborted){const cancelMessage=payload?.cancelMessage||"User did not allow tool call";this.setStatusInternal(callId,"cancelled",cancelMessage,"not_started");const toolSpan=this.toolSpans.get(callId);if(toolSpan){setToolSpanCancelled(toolSpan)}const explicitCancel=outcome==="cancel";this.finalizeBlockedSpan(callId,explicitCancel?"cancel":"aborted",explicitCancel?this.getBlockedSource():"system");this.finalizeToolSpan(callId)}else if(outcome==="modify_with_editor"){const waitingToolCall=toolCall;if(waitingToolCall.confirmationDetails.type==="edit"&&isModifiableDeclarativeTool(waitingToolCall.tool)){const modifyContext=waitingToolCall.tool.getModifyContext(signal,callId);const editorType=this.getPreferredEditor();if(!editorType){debugLogger51.warn(`ModifyWithEditor requested for ${callId} but no editor available \u2014 tool stays in awaiting_approval; user can recover via Cancel/Proceed`);const toolSpan=this.toolSpans.get(callId);if(toolSpan){try{toolSpan.setAttributes({"qwen-code.tool.modify_with_editor_unavailable":true})}catch{}}return}this.setStatusInternal(callId,"awaiting_approval",{...waitingToolCall.confirmationDetails,isModifying:true});const normalizedArgs={...waitingToolCall.request.args};for(const key of PATH_ARG_KEYS){if(typeof normalizedArgs[key]==="string"){normalizedArgs[key]=unescapePath(String(normalizedArgs[key]).trim())}}const{updatedParams,updatedDiff}=await modifyWithEditor(normalizedArgs,modifyContext,editorType,signal,this.onEditorClose);if(!this.setArgsInternal(callId,updatedParams))return;this.setStatusInternal(callId,"awaiting_approval",{...waitingToolCall.confirmationDetails,fileDiff:updatedDiff,isModifying:false})}}else{const waitingToolCall=toolCall;if(isApproveOutcome(outcome)&&waitingToolCall.tool instanceof AskUserQuestionTool&&waitingToolCall.confirmationDetails.type==="ask_user_question"){this.config.getLlmClient?.()?.recordTrustedUserAnswers(callId,waitingToolCall.confirmationDetails.questions,payload?.answers)}if(payload?.newContent&&toolCall){if(!await this._applyInlineModify(toolCall,payload,signal)){return}}this.setStatusInternal(callId,"scheduled");const decision=outcome==="proceed_once"?"proceed_once":"proceed_always";this.finalizeBlockedSpan(callId,decision,this.getBlockedSource())}}recordAutoModeFallbackResolution(callId,outcome){const wasAutoModeFallback=this.autoModeFallbackCallIds.delete(callId);if(this.config.getApprovalMode()==="auto"&&wasAutoModeFallback&&isApproveOutcome(outcome)){const before=this.config.getAutoModeDenialState();const after=recordFallbackApprove(before);if(after===before){debugLogger51.warn(`Auto mode denial counters already clear after fallback approval: `+formatDenialStateLog(before));return}debugLogger51.warn(`Auto mode denial counters reset after fallback approval: ${formatDenialStateLog(before)} -> ${formatDenialStateLog(after)}`);this.config.setAutoModeDenialState(after)}}async openIdeDiffIfEnabled(confirmationDetails,callId,signal){if(confirmationDetails.type!=="edit"||!this.config.getIdeMode()||this.config.getExecutionEnvironment?.()){return}let resolution;try{const ideClient=await IdeClient.getInstance();if(!ideClient.isDiffingEnabled())return;resolution=await ideClient.openDiff(confirmationDetails.filePath,confirmationDetails.newContent)}catch(error3){if(!signal.aborted){debugLogger51.warn(`IDE diff open failed for ${callId}: ${error3 instanceof Error?error3.message:String(error3)}`)}return}const still=this.toolCalls.find(c=>c.request.callId===callId&&c.status==="awaiting_approval");if(!still)return;if(resolution.status==="accepted"){const userEdited=resolution.content!=null&&resolution.content!==confirmationDetails.newContent;await this.handleConfirmationResponse(callId,confirmationDetails.onConfirm,"proceed_once",signal,userEdited?{newContent:resolution.content}:void 0)}else{await this.handleConfirmationResponse(callId,confirmationDetails.onConfirm,"cancel",signal)}}async _applyInlineModify(toolCall,payload,signal){const confirmDetails=toolCall.confirmationDetails;if(confirmDetails.type!=="edit"||!isModifiableDeclarativeTool(toolCall.tool)||!payload.newContent){return true}const currentContent=confirmDetails.originalContent??"";const modifyContext=toolCall.tool.getModifyContext(signal,toolCall.request.callId);const updatedParams=modifyContext.createUpdatedParams(currentContent,payload.newContent,toolCall.request.args);const updatedDiff=createPatch(confirmDetails.filePath,currentContent,payload.newContent,"Current","Proposed");if(!this.setArgsInternal(toolCall.request.callId,updatedParams)){return false}this.setStatusInternal(toolCall.request.callId,"awaiting_approval",{...confirmDetails,fileDiff:updatedDiff});return true}async attemptExecutionOfScheduledCalls(signal){while(true){const allCallsFinalOrScheduled=this.toolCalls.every(call=>call.status==="scheduled"||call.status==="cancelled"||call.status==="success"||call.status==="error");if(!allCallsFinalOrScheduled){return}const callsToExecute=this.toolCalls.filter(call=>call.status==="scheduled");if(callsToExecute.length===0){return}const batches=partitionToolCalls(callsToExecute,this.hookReplacedInputCallIds);for(const batch of batches){if(batch.concurrent&&batch.calls.length>1){await this.runConcurrently(batch.calls,signal);if(this.hasExecutingOrAwaitingApprovalCall()){return}}else{for(const call of batch.calls){if(this.schedulerOptions.beforeToolLaunch&&await this.launchRefused(call)){continue}await this.executeSingleToolCall(call,signal);if(this.hasExecutingOrAwaitingApprovalCall()){return}}}}}}async launchRefused(call){const beforeToolLaunch=this.schedulerOptions.beforeToolLaunch;if(!beforeToolLaunch||await beforeToolLaunch(call))return false;const{callId}=call.request;this.launchRefusedCallIds.add(callId);this.setStatusInternal(callId,"cancelled","Tool call was not started.","not_started");this.finalizeBlockedSpan(callId,"aborted","system");const toolSpan=this.toolSpans.get(callId);if(toolSpan){setToolSpanCancelled(toolSpan)}this.finalizeToolSpan(callId);return true}hasExecutingOrAwaitingApprovalCall(){return this.toolCalls.some(call=>call.status==="executing"||call.status==="awaiting_approval")}async runConcurrently(calls,signal){const maxConcurrency=parsePositiveIntegerEnv(process.env["QWEN_CODE_MAX_TOOL_CONCURRENCY"],10);const executing=new Set;const admitted=[];const launchAdmitted=__name(()=>{for(const call of admitted.splice(0)){const p2=this.executeSingleToolCall(call,signal).finally(()=>{executing.delete(p2)});executing.add(p2)}},"launchAdmitted");for(const call of calls){if(this.schedulerOptions.beforeToolLaunch&&await this.launchRefused(call)){continue}admitted.push(call);if(executing.size+admitted.length>=maxConcurrency){launchAdmitted();await Promise.race(executing)}}launchAdmitted();await Promise.all(executing)}async executeSingleToolCall(toolCall,signal){if(toolCall.status!=="scheduled")return;if(goalTurnContext.getStore()!==toolCall.request.goalContext){return runInRequestGoalContext(toolCall.request,()=>this.executeSingleToolCall(toolCall,signal))}const scheduledCall=toolCall;const{callId,name:toolName}=scheduledCall.request;const owner=this.hookOwners.get(callId);if(getHookExecutionOwner()!==owner){return runWithHookExecutionOwner(owner,()=>this.executeSingleToolCall(toolCall,signal))}const runtimeView=this.runtimeContentGeneratorViews.get(callId);if(runtimeView&&getRuntimeContentGenerator()!==runtimeView){return runWithRuntimeContentGenerator(runtimeView,()=>this.executeSingleToolCall(toolCall,signal))}let toolSpan=this.toolSpans.get(callId);if(!toolSpan){const canonical=canonicalToolName(toolName);toolSpan=startToolSpan(canonical,{"tool.call_id":callId,"gen_ai.tool.call.id":scheduledCall.request.providerCallId??callId,call_id:callId,tool_name:canonical,...scheduledCall.request.parentCallId?{"tool.parent_call_id":scheduledCall.request.parentCallId}:{},...scheduledCall.request.source?{"tool.source":scheduledCall.request.source}:{}},scheduledCall.tool.description,scheduledCall.request.prompt_id);this.toolSpans.set(callId,toolSpan)}try{await runInToolSpanContext(toolSpan,()=>this._executeToolCallBody(scheduledCall,signal,toolSpan))}catch(error3){const errorMessage=error3 instanceof Error?error3.message:String(error3);setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,errorMessage);this.setStatusInternal(callId,"error",createErrorResponse(scheduledCall.request,error3 instanceof Error?error3:new Error(errorMessage),"unhandled_exception",this.toolCalls.find(call=>call.request.callId===callId)?.status==="executing"?"error":"not_started"))}finally{this.finalizeToolSpan(callId);this.memoryMonitor?.scheduleCheck()}}async runPreToolUse(reqInfo,tool,batchState,signal){const messageBus=this.config.getMessageBus();if(this.config.getDisableAllHooks()||!messageBus)return void 0;const{callId}=reqInfo;const canonicalName=canonicalToolName(reqInfo.name);const toolInput=structuredClone(reqInfo.args);for(const key of PATH_ARG_KEYS){if(typeof toolInput[key]==="string"){toolInput[key]=unescapePath(String(toolInput[key]).trim())}}const toolUseId=generateToolUseId();this.preToolUseIds.set(callId,toolUseId);this.preToolUseSessionHookIds.set(callId,this.sessionPreToolUseHookIds(callId,canonicalName));const toolSpan=this.openToolSpan(reqInfo,tool,batchState);const result=await runInToolSpanContext(toolSpan,()=>runInRequestGoalContext(reqInfo,()=>this.withHookSpan({hookEvent:"PreToolUse",toolName:canonicalName,toolUseId},()=>firePreToolUseHook(messageBus,canonicalName,toolInput,toolUseId,this.config.getApprovalMode(),signal,callId,this.hookOwners.get(callId)),r=>r.hookError?{success:false,error:r.hookError,shouldProceed:true}:{success:true,shouldProceed:r.shouldProceed,blockType:r.shouldProceed?void 0:r.blockType,hasAdditionalContext:!!r.additionalContext})));if(result.additionalContext){this.preToolUseContexts.set(callId,result.additionalContext)}if(signal.aborted)return void 0;const fixedPolicy=reqInfo.executionOrigin?.kind==="fixed_policy";let blockReason;if(!result.shouldProceed&&(result.blockType!=="ask"||fixedPolicy||!this.canPromptForPreToolUseAsk())){blockReason=result.blockReason||"Tool execution blocked by hook"}else if(fixedPolicy&&result.updatedInput){blockReason="PreToolUse updatedInput is not supported for policy-owned tool calls, which skip the permission flow; the tool was not run."}if(blockReason){setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_SPAN_STATUS_PRE_HOOK_BLOCKED);this.finalizeToolSpan(callId);return{status:"error",request:reqInfo,tool,response:createErrorResponse(reqInfo,new Error(blockReason),"execution_denied","not_started"),durationMs:0}}if(!result.shouldProceed){this.preToolUseAsks.set(callId,result.blockReason||`A PreToolUse hook requested confirmation before running ${reqInfo.name}.`)}if(result.updatedInput){reqInfo.args=result.updatedInput;this.hookReplacedInputCallIds.add(callId)}return void 0}rebuildWithPermissionRequestInput(reqInfo,tool,args,toolSpan){const{callId}=reqInfo;const policyGate=evaluateMediaPolicyToolCall({config:this.config,tool,args,executionOrigin:reqInfo.executionOrigin});if(policyGate.outcome==="reject"){this.setStatusInternal(callId,"error",createErrorResponse(reqInfo,new Error(policyGate.message),policyGate.reason==="invalid_params"?"invalid_tool_params":"execution_denied","not_started"));setToolSpanFailure(toolSpan,TOOL_FAILURE_KIND_TOOL_EXCEPTION,policyGate.message);this.finalizeToolSpan(callId);return void 0}if(!this.setArgsInternal(callId,policyGate.args))return void 0;this.hookReplacedInputCallIds.add(callId);return this.toolCalls.find(call=>call.request.callId===callId&&call.status==="validating")}sessionPreToolUseHookIds(callId,toolName){const sessionId=this.hookOwners.get(callId)?.sessionId??this.config.getSessionId();return new Set(this.config.getHookSystem?.()?.getSessionHooksManager?.().getMatchingHooks(sessionId,"PreToolUse",toolName).map(entry=>entry.hookId)??[])}canPromptForPreToolUseAsk(){const isNonInteractive=!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&this.config.getInputFormat()!=="stream-json";if(isNonInteractive){return false}if(this.config.getShouldAvoidPermissionPrompts?.()){return false}return true}safelyAddToolArgumentsAttributes(span,argumentsValue){try{addToolArgumentsAttributes(this.config,span,argumentsValue)}catch(error3){debugLogger51.warn("Failed to add tool arguments span attribute:",error3)}}safelyAddToolCallResultAttributes(span,result){try{addToolCallResultAttributes(this.config,span,result)}catch(error3){debugLogger51.warn("Failed to add tool result span attribute:",error3)}}async _executeToolCallBody(scheduledCall,signal,span){const{callId,name:toolName}=scheduledCall.request;const canonicalName=canonicalToolName(toolName);const invocation=scheduledCall.invocation;const toolInput=scheduledCall.request.args;for(const key of PATH_ARG_KEYS){if(typeof toolInput[key]==="string"){toolInput[key]=unescapePath(String(toolInput[key]).trim())}}const toolUseId=this.preToolUseIds.get(callId)??generateToolUseId();const messageBus=this.config.getMessageBus();const hooksEnabled=!this.config.getDisableAllHooks();let producerObserved=false;const observeSyntheticProducer=__name(response=>{try{if(producerObserved||!this.shouldObserveProducer(callId))return;producerObserved=true;observeToolResultBoundary({stage:"producer",sessionId:this.config.getSessionId(),promptId:scheduledCall.request.prompt_id,toolCallId:callId,toolName:canonicalName,artifacts:[toolResultBoundaryArtifact(response.persistedOutputFiles??[],response.artifacts??[])],values:__name(()=>[...toolResultPartDiagnosticValues(response.responseParts),...shellResultText(response.resultDisplay)!==void 0?[{representation:"display",value:shellResultText(response.resultDisplay)}]:[]],"values")})}catch{}},"observeSyntheticProducer");const checkedHookIds=this.preToolUseSessionHookIds.get(callId);if(checkedHookIds&&[...this.sessionPreToolUseHookIds(callId,canonicalName)].some(hookId=>!checkedHookIds.has(hookId))){const errorResponse=createErrorResponse(scheduledCall.request,new Error(`A PreToolUse hook was registered after "${toolName}" was checked, so the call was not run. Call the tool again.`),"execution_denied","not_started");observeSyntheticProducer(errorResponse);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_PRE_HOOK_BLOCKED,TOOL_SPAN_STATUS_PRE_HOOK_BLOCKED);return}const toolInvocationGuard=this.config.getToolInvocationGuard?.();if(toolInvocationGuard){const invocationContext=getInvocationContext();const guardDecision=await evaluateToolInvocationGuard(toolInvocationGuard,{callId,toolName:canonicalName,args:invocation.params,signal,permissionChecked:scheduledCall.request.executionOrigin?.kind!=="fixed_policy",sessionId:this.config.getSessionId(),cwd:this.config.getTargetDir(),...invocationContext?{invocationContext}:{}});if(signal.aborted){const cancelledResponse=createCancelledResponse(scheduledCall.request,"Tool call cancelled before execution.","not_started");observeSyntheticProducer(cancelledResponse);this.setStatusInternal(callId,"cancelled",cancelledResponse);if(this.toolSpans.has(callId)){setToolSpanCancelled(span)}return}if(!guardDecision.allowed){const errorResponse=createErrorResponse(scheduledCall.request,new Error(guardDecision.reason),"execution_denied","not_started");observeSyntheticProducer(errorResponse);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_INVOCATION_GUARD_DENIED,TOOL_SPAN_STATUS_INVOCATION_GUARD_DENIED);return}}if(signal.aborted){const currentCall=this.toolCalls.find(call=>call.request.callId===callId);if(currentCall&&currentCall.status!=="success"&&currentCall.status!=="error"&&currentCall.status!=="cancelled"){const cancelledResponse=createCancelledResponse(scheduledCall.request,"Tool call cancelled before execution.","not_started");observeSyntheticProducer(cancelledResponse);this.setStatusInternal(callId,"cancelled",cancelledResponse);if(this.toolSpans.has(callId)){setToolSpanCancelled(span)}}return}const liveOutputCallback=scheduledCall.tool.canUpdateOutput?outputChunk=>{if(isShellProgressData(outputChunk)){if(this.outputUpdateHandler){this.outputUpdateHandler(callId,outputChunk)}return}const compactOutput=this.compactResultDisplayForInteractiveHistory(outputChunk);if(this.outputUpdateHandler){this.outputUpdateHandler(callId,outputChunk)}this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,liveOutput:compactOutput}:tc);this.notifyToolCallsUpdate()}:void 0;const shellExecutionConfig=this.config.getShellExecutionConfig();const sleepInhibitorHandle=acquireSleepInhibitor(this.config,`Qwen Code is executing tool ${canonicalName}`);let removeParentAbortForward;let executionStatus="not_started";let executionSettled=false;let execSpan;let executionStartedAt;const elapsedExecutionMs=__name(()=>executionStartedAt===void 0?void 0:Math.round(performance.now()-executionStartedAt),"elapsedExecutionMs");let producerToolResult;let appliedOutputBudget;const recordBudgetReduction=__name((before,after,value,source)=>{if(before!==after&&measureToolOutput(after,this.config).chars<measureToolOutput(before,this.config).chars)appliedOutputBudget={value,source}},"recordBudgetReduction");const globalBudgetSource=this.config.isTruncateToolOutputThresholdExplicit?.()?"explicit":"global";let observeProducerOutput=observeSyntheticProducer;try{let promise;const toolExecutionTimeoutMs=Math.min(parsePositiveIntegerEnv(process.env["QWEN_CODE_TOOL_EXECUTION_TIMEOUT_MS"],0),2147483647);let execSignal=signal;let timeoutController;if(toolExecutionTimeoutMs>0){timeoutController=new AbortController;execSignal=timeoutController.signal;if(signal.aborted){timeoutController.abort(signal.reason)}else{const controller=timeoutController;const forwardAbort=__name(()=>controller.abort(signal.reason),"forwardAbort");signal.addEventListener("abort",forwardAbort,{once:true});removeParentAbortForward=__name(()=>signal.removeEventListener("abort",forwardAbort),"removeParentAbortForward")}}const inheritedTodoWorkChainId=todoWorkChainContext.getStore();const todoWorkChainId=this.config.getActiveTodoWorkChainOwner?.(scheduledCall.request.prompt_id,inheritedTodoWorkChainId)??inheritedTodoWorkChainId??scheduledCall.request.prompt_id;if(invocation instanceof ShellToolInvocation){const setPidCallback=__name(pid=>{this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,pid}:tc);this.notifyToolCallsUpdate()},"setPidCallback");const setPromoteAbortControllerCallback=__name(ac=>{this.toolCalls=this.toolCalls.map(tc=>tc.request.callId===callId&&tc.status==="executing"?{...tc,promoteAbortController:ac}:tc);this.notifyToolCallsUpdate()},"setPromoteAbortControllerCallback");const canPromoteForegroundShell=__name(()=>{const promotableShells=this.toolCalls.filter(tc=>tc.status==="executing"&&tc.request.name===ToolNames.SHELL&&tc.promoteAbortController!==void 0);return promotableShells.length===1&&promotableShells[0]?.request.callId===callId},"canPromoteForegroundShell");this.safelyAddToolArgumentsAttributes(span,invocation.params);promise=todoWorkChainContext.run(todoWorkChainId,()=>promptIdContext.run(scheduledCall.request.prompt_id,()=>{executionStartedAt=performance.now();this.setStatusInternal(callId,"executing");execSpan=startToolExecutionSpan({toolName:canonicalName,callId});executionStatus="error";const execute=__name(()=>{executionStartedAt=performance.now();try{this.schedulerOptions.onToolExecutionStarted?.(callId,Date.now())}catch(error3){debugLogger51.warn("Tool lifecycle start observer failed:",error3)}return invocation.execute(execSignal,liveOutputCallback,shellExecutionConfig,setPidCallback,setPromoteAbortControllerCallback,canPromoteForegroundShell)},"execute");return scheduledCall.request.name===ToolNames.EXEC||scheduledCall.request.name===ToolNames.TOOL_SEARCH?runWithToolCallRuntime({parentCallId:callId,allowedToolNames:scheduledCall.request.codeModeAllowedToolNames,dispatch:__name((name2,args,nestedSignal,onResult)=>this.dispatchCodeModeTool(name2,args,scheduledCall.request,nestedSignal,onResult),"dispatch")},execute):scheduledCall.request.source==="code_mode"?runWithToolCallSource({kind:"code_mode"},execute):execute()}))}else{this.safelyAddToolArgumentsAttributes(span,invocation.params);promise=todoWorkChainContext.run(todoWorkChainId,()=>promptIdContext.run(scheduledCall.request.prompt_id,()=>{executionStartedAt=performance.now();this.setStatusInternal(callId,"executing");execSpan=startToolExecutionSpan({toolName:canonicalName,callId});executionStatus="error";const execute=__name(()=>{executionStartedAt=performance.now();try{this.schedulerOptions.onToolExecutionStarted?.(callId,Date.now())}catch(error3){debugLogger51.warn("Tool lifecycle start observer failed:",error3)}return invocation.execute(execSignal,liveOutputCallback,shellExecutionConfig)},"execute");return scheduledCall.request.name===ToolNames.EXEC||scheduledCall.request.name===ToolNames.TOOL_SEARCH?runWithToolCallRuntime({parentCallId:callId,allowedToolNames:scheduledCall.request.codeModeAllowedToolNames,dispatch:__name((name2,args,nestedSignal,onResult)=>this.dispatchCodeModeTool(name2,args,scheduledCall.request,nestedSignal,onResult),"dispatch")},execute):scheduledCall.request.source==="code_mode"?runWithToolCallSource({kind:"code_mode"},execute):execute()}))}let toolResult;let schedulerTimeoutResultSelected=false;let schedulerTimeoutWon=false;if(timeoutController){let timeoutTimer;try{toolResult=await new Promise((resolve36,reject)=>{timeoutTimer=setTimeout(()=>{schedulerTimeoutResultSelected=true;schedulerTimeoutWon=!signal.aborted;debugLogger51.warn(`Tool ${canonicalName} (${callId}) timed out after ${toolExecutionTimeoutMs}ms \u2014 aborting`);timeoutController?.abort(new DOMException(`Tool execution timed out after ${toolExecutionTimeoutMs}ms`,"TimeoutError"));resolve36(createToolTimeoutResult(toolExecutionTimeoutMs))},toolExecutionTimeoutMs);timeoutTimer.unref?.();promise.then(resolve36,reject)})}finally{if(timeoutTimer)clearTimeout(timeoutTimer);removeParentAbortForward?.()}}else{toolResult=await promise}producerToolResult=toolResult;observeProducerOutput=__name((response,replacement=false)=>{const rawSize=replacement||producerToolResult?.rawOutputSize===null||producerToolResult?.error!==void 0?void 0:producerToolResult?.rawOutputSize??measureToolOutput(producerToolResult?.llmContent??"",this.config);const processedChars=measureToolOutput(response.responseParts,this.config).chars;const budgetReduced=!replacement&&appliedOutputBudget!==void 0;response.responseParts=attachToolOutputRecovery(attachToolOutputProvenance(response.responseParts,{callId,toolName:getModelFacingToolName(scheduledCall.request),promptId:scheduledCall.request.prompt_id,toolType:scheduledCall.tool instanceof DiscoveredMCPTool?"mcp":"native",rawSize,truncated:!replacement&&producerToolResult?.truncatedByProducer===true?true:budgetReduced?true:rawSize===void 0?void 0:processedChars<rawSize.chars,budget:budgetReduced?appliedOutputBudget?.value:void 0,budgetSource:budgetReduced?appliedOutputBudget?.source:void 0}),{text:replacement?void 0:producerToolResult?.recoveryText,persistedOutputFiles:response.persistedOutputFiles});try{if(producerObserved||!this.shouldObserveProducer(callId))return;producerObserved=true;let producerInputValues;const getProducerInputValues=__name(()=>producerInputValues??=[...toolResultPartDiagnosticValues(producerToolResult?.llmContent),...shellResultText(producerToolResult?.returnDisplay)!==void 0?[{representation:"display",value:shellResultText(producerToolResult?.returnDisplay)}]:[]],"getProducerInputValues");let producerOutputValues;const getProducerOutputValues=__name(()=>producerOutputValues??=[...toolResultPartDiagnosticValues(response.responseParts),...shellResultText(response.resultDisplay)!==void 0?[{representation:"display",value:shellResultText(response.resultDisplay)}]:[],...typeof response.visionBridgeNotice==="string"?[{representation:"display",value:response.visionBridgeNotice}]:[]],"getProducerOutputValues");const inputArtifact=toolResultBoundaryArtifact(producerToolResult?.persistedOutputFiles,producerToolResult?.artifacts);const outputArtifact=toolResultBoundaryArtifact(response.persistedOutputFiles,response.artifacts);let mutated;const isMutated=__name(()=>mutated??=producerToolResult==null||!producerContentEqual(getModelFacingToolName(scheduledCall.request),callId,producerToolResult.llmContent,response.responseParts)||!isDeepStrictEqual6(producerToolResult.returnDisplay,response.resultDisplay)||!isDeepStrictEqual6(inputArtifact,outputArtifact)||typeof response.visionBridgeNotice==="string","isMutated");const observation={sessionId:this.config.getSessionId(),promptId:scheduledCall.request.prompt_id,toolCallId:callId,toolName:canonicalName,mutated:isMutated};observeToolResultBoundary({...observation,stage:"producer_input",artifacts:[inputArtifact],values:getProducerInputValues});observeToolResultBoundary({...observation,stage:"producer_output",artifacts:[outputArtifact],values:getProducerOutputValues})}catch{}},"observeProducerOutput");const isTimeout=toolResult.error?.type==="execution_timeout"&&(!schedulerTimeoutResultSelected||schedulerTimeoutWon);const parentAbortedAtExecutionSettle=signal.aborted;const aborted3=parentAbortedAtExecutionSettle&&!isTimeout;const executionErrorType=toolResult.error?toolResult.error.type??(scheduledCall.tool instanceof DiscoveredMCPTool?"mcp_tool_error":"unknown"):void 0;executionStatus=aborted3?"cancelled":toolResult.error?"error":"success";executionSettled=true;try{this.schedulerOptions.onToolExecutionSettled?.(callId,executionStatus,elapsedExecutionMs()??0)}catch(error3){debugLogger51.warn("Tool lifecycle end observer failed:",error3)}if(execSpan){const completedExecSpan=execSpan;execSpan=void 0;endToolExecutionSpan(completedExecSpan,{success:executionStatus==="success",error:aborted3?TOOL_SPAN_STATUS_TOOL_CANCELLED:isTimeout?TOOL_SPAN_STATUS_TOOL_TIMEOUT:toolResult.error?TOOL_SPAN_STATUS_TOOL_ERROR:void 0,cancelled:aborted3,executionStatus,errorType:executionErrorType})}if(aborted3){let cancelMessage=TOOL_CANCELLED_AFTER_COMPLETION_MESSAGE;let failureHookArtifacts;if(hooksEnabled&&messageBus){const failureHookResult=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:canonicalName,toolUseId,isInterrupt:true},()=>safelyFirePostToolUseFailureHook(messageBus,toolUseId,canonicalName,toolInput,cancelMessage,true,this.config.getApprovalMode(),callId,elapsedExecutionMs(),this.hookOwners.get(callId)),this.postToolUseFailureEndMeta);if(failureHookResult.additionalContext&&!this.keepFailureContextForParent(callId,failureHookResult.additionalContext)){cancelMessage+=`
590
591
 
591
592
  ${failureHookResult.additionalContext}`}failureHookArtifacts=failureHookResult.artifacts}const cancelledResponse=createCancelledResponse(scheduledCall.request,cancelMessage,executionStatus,failureHookArtifacts,toolResult.persistedOutputFiles);observeProducerOutput(cancelledResponse,true);this.setStatusInternal(callId,"cancelled",cancelledResponse);setToolSpanCancelled(span);return}const cancelAfterPostProcessing=__name((artifacts,preserved)=>{if(!signal.aborted||isTimeout&&parentAbortedAtExecutionSettle){return false}const cancelledResponse=createCancelledResponse(scheduledCall.request,TOOL_CANCELLED_AFTER_COMPLETION_MESSAGE,executionStatus,artifacts,preserved?.persistedOutputFiles,preserved?.visionBridgeNotice);observeProducerOutput(cancelledResponse,true);this.setStatusInternal(callId,"cancelled",cancelledResponse);setToolSpanCancelled(span);return true},"cancelAfterPostProcessing");if(toolResult.error===void 0){let content=toolResult.llmContent??"";let persistedOutputFiles=toolResult.persistedOutputFiles?[...toolResult.persistedOutputFiles]:toolResult.persistedOutputFiles;const mergePersistedOutputFiles=__name(outputFiles=>{if(outputFiles===void 0)return;persistedOutputFiles=Array.from(new Set([...persistedOutputFiles??[],...outputFiles]))},"mergePersistedOutputFiles");let contentLength=typeof content==="string"?content.length:void 0;let postToolUseAdditionalContext;let postToolUseArtifacts;let reminderEnvelope;if(hooksEnabled&&messageBus){const toolResponse={llmContent:content,returnDisplay:toolResult.returnDisplay};const permissionMode=this.config.getApprovalMode();const postHookResult=await this.withHookSpan({hookEvent:"PostToolUse",toolName:canonicalName,toolUseId},()=>firePostToolUseHook(messageBus,canonicalName,toolInput,toolResponse,toolUseId,permissionMode,void 0,callId,elapsedExecutionMs(),this.hookOwners.get(callId)),r=>r.hookError?{success:false,error:r.hookError,shouldStop:false}:{success:true,shouldStop:r.shouldStop,hasAdditionalContext:!!r.additionalContext,blockType:r.shouldStop?"stop":void 0});if(postHookResult.additionalContext){postToolUseAdditionalContext=postHookResult.additionalContext}if(postHookResult.artifacts&&postHookResult.artifacts.length>0){postToolUseArtifacts=postHookResult.artifacts}if(postHookResult.shouldStop){if(cancelAfterPostProcessing(postHookResult.artifacts,{persistedOutputFiles})){return}const stopMessage=postHookResult.stopReason||"Execution stopped by hook";const errorResponse=createErrorResponse(scheduledCall.request,new Error(stopMessage),"execution_denied",executionStatus);if(persistedOutputFiles!==void 0){errorResponse.persistedOutputFiles=persistedOutputFiles}observeProducerOutput(errorResponse,true);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_POST_HOOK_STOPPED,TOOL_SPAN_STATUS_POST_HOOK_STOPPED);return}}const persisted=await this.maybePersistLargeToolResult(callId,toolName,content,toolResult.outputBudgetApplied===true,scheduledCall.request.prompt_id);recordBudgetReduction(content,persisted.content,this.config.getTruncateToolOutputThreshold()+GATE_HEADROOM,globalBudgetSource);content=persisted.content;mergePersistedOutputFiles(persisted.persistedOutputFiles);const inputPaths=extractToolFilePaths(toolName,toolInput);const resultPaths=isFilesystemPathTool(toolName)&&Array.isArray(toolResult.resultFilePaths)?toolResult.resultFilePaths:[];const candidatePaths=Array.from(new Set([...inputPaths.map(p2=>unescapePath(p2)),...resultPaths]));if(candidatePaths.length>0&&!this.config.getExecutionEnvironment?.()){const rulesRegistry=this.config.getConditionalRulesRegistry();const skillManager=sessionSkillManager(this.config);const reminderBlocks=[];for(const candidatePath of candidatePaths){const rulesCtx=await rulesRegistry?.matchAndConsume(candidatePath);if(rulesCtx)reminderBlocks.push(rulesCtx)}const activatedSkills=await skillManager?.matchAndActivateByPaths(candidatePaths);if(activatedSkills&&activatedSkills.length>0&&skillManager){const hasSkillTool=this.hasSkillToolOverride?this.hasSkillToolOverride():!!this.toolRegistry.getTool(ToolNames.SKILL);if(hasSkillTool){let activatedEntries=[];try{const collected=await collectAvailableSkillEntries(skillManager,this.config);const activatedSet=new Set(activatedSkills);activatedEntries=collected.entries.filter(e=>e.level!==void 0&&activatedSet.has(e.name))}catch(error3){debugLogger51.warn("coreToolScheduler: collectAvailableSkillEntries failed in activation path",error3);activatedEntries=activatedSkills.map(name2=>({name:name2,description:"",level:"project"}))}if(activatedEntries.length>0){reminderBlocks.push(`${SKILLS_ACTIVATED_OPENER}; invoke a skill by passing its name to the Skill tool:
592
593
  <available_skills>
593
594
  ${renderAvailableSkillsBlock(activatedEntries)}
594
595
  </available_skills>`);this.config.addInlineAnnouncedSkillKeys(activatedEntries.map(e=>`skill:${e.name}`))}}}if(reminderBlocks.length>0){const body=escapeSystemReminderTags(reminderBlocks.join("\n\n"));reminderEnvelope=`<system-reminder>
595
596
  ${body}
596
- </system-reminder>`}}const limitsTool=scheduledCall.tool;const perToolMax=limitsTool.maxOutputChars;const perToolKeep=limitsTool.truncateKeep;const staticBudgetSource=perToolMax!==void 0?"per_tool":globalBudgetSource;const perToolLines=perToolMax!==void 0?Number.POSITIVE_INFINITY:void 0;const promptIdForTruncation=scheduledCall.request.prompt_id;try{const contentBeforeTruncation=content;const truncated=await truncateLlmContent(this.config,toolName,content,{threshold:perToolMax,lines:perToolLines,keep:perToolKeep},promptIdForTruncation,scheduledCall.request.callId);recordBudgetReduction(contentBeforeTruncation,truncated.content,perToolMax??this.config.getTruncateToolOutputThreshold(),staticBudgetSource);content=truncated.content;mergePersistedOutputFiles(persistedOutputFilesForTruncation(contentBeforeTruncation,truncated))}catch(truncErr){debugLogger51.warn(`TRUNCATION failed for ${toolName}: ${truncErr instanceof Error?truncErr.message:String(truncErr)}`)}if(postToolUseAdditionalContext){content=appendAdditionalContext(content,postToolUseAdditionalContext)}if(reminderEnvelope){content=appendAdditionalContext(content,reminderEnvelope)}if((postToolUseAdditionalContext||reminderEnvelope)&&typeof content==="string"&&!content.startsWith(TOOL_OUTPUT_TRUNCATED_PREFIX)){const baseThreshold=perToolMax??this.config.getTruncateToolOutputThreshold();const combinedLines=perToolMax!==void 0?Number.POSITIVE_INFINITY:this.config.getTruncateToolOutputLines()*2;if(content.length>baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR){try{const contentBeforeRecombination=content;const recombined=await truncateToolOutput(this.config,toolName,content,{layer:"combined",source:scheduledCall.tool.maxOutputChars!==void 0?"per_tool":this.config.isTruncateToolOutputThresholdExplicit?.()?"explicit":"global",threshold:baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR,lines:combinedLines,keep:perToolKeep},promptIdForTruncation,scheduledCall.request.callId);recordBudgetReduction(contentBeforeRecombination,recombined.content,baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR,staticBudgetSource);content=recombined.content;mergePersistedOutputFiles(persistedOutputFilesForTruncation(contentBeforeRecombination,recombined))}catch(truncErr){debugLogger51.warn(`TRUNCATION (combined) failed for ${toolName}: ${truncErr instanceof Error?truncErr.message:String(truncErr)}`)}}}contentLength=typeof content==="string"?content.length:void 0;const convertedResponse=convertToFunctionResponse(getModelFacingToolName(scheduledCall.request),callId,content,{recoveryText:toolResult.recoveryText,persistedOutputFiles});const processedImages=await this.processToolResultImages(convertedResponse,signal,scheduledCall.request.executionOrigin);const response=processedImages.responseParts;if(response!==convertedResponse){contentLength=response.reduce((total,part)=>total+extractTextFromPartListUnion(part).length,0)}const artifacts=[...toolResult.artifacts??[],...postToolUseArtifacts??[]];const policyArtifacts=scheduledCall.tool.mediaPolicyDescriptor&&toolResult.artifacts&&toolResult.artifacts.length>0?{toolName:canonicalName,invocationId:callId,executionOrigin:scheduledCall.request.executionOrigin??{kind:"model"},artifacts:toolResult.artifacts}:void 0;if(policyArtifacts&&policyArtifacts.executionOrigin.kind!=="fixed_policy"&&scheduledCall.tool.mediaPolicyDescriptor){const{collectModelPolicyCall}=await import("./model-call-collection-WBWTO3EG.js");await collectModelPolicyCall({config:this.config,batch:policyArtifacts,descriptor:scheduledCall.tool.mediaPolicyDescriptor,args:scheduledCall.invocation.params,..."executionStartTime"in scheduledCall&&typeof scheduledCall.executionStartTime==="number"?{startedAt:scheduledCall.executionStartTime}:{},signal})}const successResponse={callId,responseParts:response,resultDisplay:this.compactResultDisplayForInteractiveHistory(toolResult.returnDisplay),error:void 0,errorType:void 0,executionStatus,contentLength,...persistedOutputFiles!==void 0?{persistedOutputFiles}:{},...processedImages.modelOverride!==void 0?{modelOverride:processedImages.modelOverride}:"modelOverride"in toolResult?{modelOverride:toolResult.modelOverride}:{},...toolResult.terminateTurn?{terminateTurn:true}:{},...processedImages.visionBridgeNotice!==void 0?{visionBridgeNotice:processedImages.visionBridgeNotice}:{},...artifacts.length>0?{artifacts}:{},...policyArtifacts?{policyArtifacts}:{}};if(canonicalName===ToolNames.EXIT_PLAN_MODE&&typeof toolResult.llmContent==="string"&&PLAN_EXIT_APPROVED_LLM_CONTENT_PREFIXES.some(prefix2=>toolResult.llmContent.startsWith(prefix2))){try{const planPath=this.config.getPlanFilePath();const savedPlan=fsSync.readFileSync(planPath,"utf-8");const redacted=this.config.getLlmClient?.()?.getChat().redactApprovedPlanFromHistory(callId,approvedPlanRedactionText(planPath),savedPlan);if(redacted===false){debugLogger51.debug(`Approved-plan redaction left history unchanged for ${callId}: no matching exit_plan_mode call, or its plan text does not match ${planPath}.`)}}catch(redactErr){debugLogger51.warn(`Skipping approved-plan redaction for ${callId} (plan file unavailable?): ${redactErr instanceof Error?redactErr.message:String(redactErr)}`)}}if(cancelAfterPostProcessing(artifacts,{persistedOutputFiles:successResponse.persistedOutputFiles,visionBridgeNotice:successResponse.visionBridgeNotice})){return}observeProducerOutput(successResponse);this.setStatusInternal(callId,"success",successResponse);try{span.setAttribute("success",true)}catch{}const result=response.find(part=>part.functionResponse!==void 0)?.functionResponse?.response;if(result!==void 0){this.safelyAddToolCallResultAttributes(span,result)}}else{const operationalErrorMessage=toolResult.error.message;let errorMessage=operationalErrorMessage;let errorPersistedOutputFiles=toolResult.persistedOutputFiles?[...toolResult.persistedOutputFiles]:toolResult.persistedOutputFiles;let failureHookAdditionalContext;let failureHookArtifacts;if(hooksEnabled&&messageBus){const failureHookResult=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:canonicalName,toolUseId,isInterrupt:false},()=>safelyFirePostToolUseFailureHook(messageBus,toolUseId,canonicalName,toolInput,toolResult.error.message,false,this.config.getApprovalMode(),callId,elapsedExecutionMs(),this.hookOwners.get(callId)),this.postToolUseFailureEndMeta);if(failureHookResult.additionalContext&&!this.keepFailureContextForParent(callId,failureHookResult.additionalContext)){if(isTimeout){failureHookAdditionalContext=failureHookResult.additionalContext}else{errorMessage+=`
597
+ </system-reminder>`}}const limitsTool=scheduledCall.tool;const perToolMax=limitsTool.maxOutputChars;const perToolKeep=limitsTool.truncateKeep;const staticBudgetSource=perToolMax!==void 0?"per_tool":globalBudgetSource;const perToolLines=perToolMax!==void 0?Number.POSITIVE_INFINITY:void 0;const promptIdForTruncation=scheduledCall.request.prompt_id;try{const contentBeforeTruncation=content;const truncated=await truncateLlmContent(this.config,toolName,content,{threshold:perToolMax,lines:perToolLines,keep:perToolKeep},promptIdForTruncation,scheduledCall.request.callId);recordBudgetReduction(contentBeforeTruncation,truncated.content,perToolMax??this.config.getTruncateToolOutputThreshold(),staticBudgetSource);content=truncated.content;mergePersistedOutputFiles(persistedOutputFilesForTruncation(contentBeforeTruncation,truncated))}catch(truncErr){debugLogger51.warn(`TRUNCATION failed for ${toolName}: ${truncErr instanceof Error?truncErr.message:String(truncErr)}`)}if(postToolUseAdditionalContext){content=appendAdditionalContext(content,postToolUseAdditionalContext)}if(reminderEnvelope){content=appendAdditionalContext(content,reminderEnvelope)}if((postToolUseAdditionalContext||reminderEnvelope)&&typeof content==="string"&&!content.startsWith(TOOL_OUTPUT_TRUNCATED_PREFIX)){const baseThreshold=perToolMax??this.config.getTruncateToolOutputThreshold();const combinedLines=perToolMax!==void 0?Number.POSITIVE_INFINITY:this.config.getTruncateToolOutputLines()*2;if(content.length>baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR){try{const contentBeforeRecombination=content;const recombined=await truncateToolOutput(this.config,toolName,content,{layer:"combined",source:scheduledCall.tool.maxOutputChars!==void 0?"per_tool":this.config.isTruncateToolOutputThresholdExplicit?.()?"explicit":"global",threshold:baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR,lines:combinedLines,keep:perToolKeep},promptIdForTruncation,scheduledCall.request.callId);recordBudgetReduction(contentBeforeRecombination,recombined.content,baseThreshold*COMBINED_PASS_TOLERANCE_FACTOR,staticBudgetSource);content=recombined.content;mergePersistedOutputFiles(persistedOutputFilesForTruncation(contentBeforeRecombination,recombined))}catch(truncErr){debugLogger51.warn(`TRUNCATION (combined) failed for ${toolName}: ${truncErr instanceof Error?truncErr.message:String(truncErr)}`)}}}contentLength=typeof content==="string"?content.length:void 0;const convertedResponse=convertToFunctionResponse(getModelFacingToolName(scheduledCall.request),callId,content,{recoveryText:toolResult.recoveryText,persistedOutputFiles});const processedImages=await this.processToolResultImages(convertedResponse,signal,scheduledCall.request.executionOrigin);const response=processedImages.responseParts;if(response!==convertedResponse){contentLength=response.reduce((total,part)=>total+extractTextFromPartListUnion(part).length,0)}const artifacts=[...toolResult.artifacts??[],...postToolUseArtifacts??[]];const policyArtifacts=scheduledCall.tool.mediaPolicyDescriptor&&toolResult.artifacts&&toolResult.artifacts.length>0?{toolName:canonicalName,invocationId:callId,executionOrigin:scheduledCall.request.executionOrigin??{kind:"model"},artifacts:toolResult.artifacts}:void 0;if(policyArtifacts&&policyArtifacts.executionOrigin.kind!=="fixed_policy"&&scheduledCall.tool.mediaPolicyDescriptor){const{collectModelPolicyCall}=await import("./model-call-collection-KNTWFZQS.js");await collectModelPolicyCall({config:this.config,batch:policyArtifacts,descriptor:scheduledCall.tool.mediaPolicyDescriptor,args:scheduledCall.invocation.params,..."executionStartTime"in scheduledCall&&typeof scheduledCall.executionStartTime==="number"?{startedAt:scheduledCall.executionStartTime}:{},signal})}const successResponse={callId,responseParts:response,resultDisplay:this.compactResultDisplayForInteractiveHistory(toolResult.returnDisplay),error:void 0,errorType:void 0,executionStatus,contentLength,...persistedOutputFiles!==void 0?{persistedOutputFiles}:{},...processedImages.modelOverride!==void 0?{modelOverride:processedImages.modelOverride}:"modelOverride"in toolResult?{modelOverride:toolResult.modelOverride}:{},...toolResult.terminateTurn?{terminateTurn:true}:{},...processedImages.visionBridgeNotice!==void 0?{visionBridgeNotice:processedImages.visionBridgeNotice}:{},...artifacts.length>0?{artifacts}:{},...policyArtifacts?{policyArtifacts}:{}};if(canonicalName===ToolNames.EXIT_PLAN_MODE&&typeof toolResult.llmContent==="string"&&PLAN_EXIT_APPROVED_LLM_CONTENT_PREFIXES.some(prefix2=>toolResult.llmContent.startsWith(prefix2))){try{const planPath=this.config.getPlanFilePath();const savedPlan=fsSync.readFileSync(planPath,"utf-8");const redacted=this.config.getLlmClient?.()?.getChat().redactApprovedPlanFromHistory(callId,approvedPlanRedactionText(planPath),savedPlan);if(redacted===false){debugLogger51.debug(`Approved-plan redaction left history unchanged for ${callId}: no matching exit_plan_mode call, or its plan text does not match ${planPath}.`)}}catch(redactErr){debugLogger51.warn(`Skipping approved-plan redaction for ${callId} (plan file unavailable?): ${redactErr instanceof Error?redactErr.message:String(redactErr)}`)}}if(cancelAfterPostProcessing(artifacts,{persistedOutputFiles:successResponse.persistedOutputFiles,visionBridgeNotice:successResponse.visionBridgeNotice})){return}observeProducerOutput(successResponse);this.setStatusInternal(callId,"success",successResponse);try{span.setAttribute("success",true)}catch{}const result=response.find(part=>part.functionResponse!==void 0)?.functionResponse?.response;if(result!==void 0){this.safelyAddToolCallResultAttributes(span,result)}}else{const operationalErrorMessage=toolResult.error.message;let errorMessage=operationalErrorMessage;let errorPersistedOutputFiles=toolResult.persistedOutputFiles?[...toolResult.persistedOutputFiles]:toolResult.persistedOutputFiles;let failureHookAdditionalContext;let failureHookArtifacts;if(hooksEnabled&&messageBus){const failureHookResult=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:canonicalName,toolUseId,isInterrupt:false},()=>safelyFirePostToolUseFailureHook(messageBus,toolUseId,canonicalName,toolInput,toolResult.error.message,false,this.config.getApprovalMode(),callId,elapsedExecutionMs(),this.hookOwners.get(callId)),this.postToolUseFailureEndMeta);if(failureHookResult.additionalContext&&!this.keepFailureContextForParent(callId,failureHookResult.additionalContext)){if(isTimeout){failureHookAdditionalContext=failureHookResult.additionalContext}else{errorMessage+=`
597
598
 
598
599
  ${failureHookResult.additionalContext}`}}failureHookArtifacts=failureHookResult.artifacts}if(isTimeout){const markedProducerBudget=toolResult.outputBudgetApplied===true?scheduledCall.tool.maxOutputChars:void 0;let timeoutContent;if(markedProducerBudget!==void 0){try{const truncated=await truncateLlmContent(this.config,toolName,toolResult.llmContent,{threshold:markedProducerBudget,lines:Number.POSITIVE_INFINITY,keep:scheduledCall.tool.truncateKeep},scheduledCall.request.prompt_id,scheduledCall.request.callId);recordBudgetReduction(toolResult.llmContent,truncated.content,markedProducerBudget,"per_tool");timeoutContent={content:truncated.content,persistedOutputFiles:persistedOutputFilesForTruncation(toolResult.llmContent,truncated)}}catch(truncErr){debugLogger51.warn(`TRUNCATION (timeout detail) failed for ${toolName}: ${truncErr instanceof Error?truncErr.message:String(truncErr)}`);timeoutContent={content:toolResult.llmContent}}}else{timeoutContent=await this.maybePersistLargeToolResult(callId,toolName,toolResult.llmContent,toolResult.outputBudgetApplied===true,scheduledCall.request.prompt_id)}if(markedProducerBudget===void 0)recordBudgetReduction(toolResult.llmContent,timeoutContent.content,this.config.getTruncateToolOutputThreshold()+GATE_HEADROOM,globalBudgetSource);let responseParts=convertToFunctionErrorResponse(getModelFacingToolName(scheduledCall.request),callId,timeoutContent.content,operationalErrorMessage);if(failureHookAdditionalContext&&responseParts.length>0){const lastIndex=responseParts.length-1;responseParts=[...responseParts];responseParts[lastIndex]=appendContextToResponsePart(responseParts[lastIndex],failureHookAdditionalContext)}const processedImages=await this.processToolResultImages(responseParts,signal,scheduledCall.request.executionOrigin);responseParts=processedImages.responseParts;const contentLength=responseParts.reduce((total,part)=>{const error4=part.functionResponse?.response?.["error"];return total+(typeof error4==="string"?error4.length:0)},0);const artifacts=[...toolResult.artifacts??[],...failureHookArtifacts??[]];const timeoutPersistedOutputFiles=errorPersistedOutputFiles===void 0&&timeoutContent.persistedOutputFiles===void 0?void 0:Array.from(new Set([...errorPersistedOutputFiles??[],...timeoutContent.persistedOutputFiles??[]]));if(cancelAfterPostProcessing(artifacts,{persistedOutputFiles:timeoutPersistedOutputFiles,visionBridgeNotice:processedImages.visionBridgeNotice})){return}const timeoutResponse={callId,responseParts,resultDisplay:this.compactResultDisplayForInteractiveHistory(toolResult.returnDisplay),error:new Error(operationalErrorMessage),errorType:"execution_timeout",executionStatus,contentLength,...timeoutPersistedOutputFiles!==void 0?{persistedOutputFiles:timeoutPersistedOutputFiles}:{},...processedImages.modelOverride!==void 0?{modelOverride:processedImages.modelOverride}:{},...processedImages.visionBridgeNotice!==void 0?{visionBridgeNotice:processedImages.visionBridgeNotice}:{},...artifacts.length>0?{artifacts}:{}};observeProducerOutput(timeoutResponse);this.setStatusInternal(callId,"error",timeoutResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_TIMEOUT,TOOL_SPAN_STATUS_TOOL_TIMEOUT);return}const errorGateThreshold=this.config.getTruncateToolOutputThreshold()+GATE_HEADROOM;const errorBodyAlreadyBounded=toolResult.outputBudgetApplied===true&&errorMessage===toolResult.llmContent;if(canonicalName!==ToolNames.EXEC&&errorMessage.length>errorGateThreshold&&!errorBodyAlreadyBounded&&!isAlreadyTruncated(errorMessage)){const persistResult=await persistAndTruncateToolResult(callId,toolName,errorMessage,this.config,scheduledCall.request.prompt_id);recordBudgetReduction(errorMessage,persistResult.content,errorGateThreshold,globalBudgetSource);errorMessage=persistResult.content;errorPersistedOutputFiles=Array.from(new Set([...errorPersistedOutputFiles??[],...persistResult.outputFile?[persistResult.outputFile]:[]]))}const error3=new Error(errorMessage);let errorResponse=createErrorResponse(scheduledCall.request,error3,executionErrorType??"unknown",executionStatus,failureHookArtifacts,typeof toolResult.returnDisplay==="string"?void 0:this.compactResultDisplayForInteractiveHistory(isShellResultDisplay(toolResult.returnDisplay)?{...toolResult.returnDisplay,text:errorMessage}:toolResult.returnDisplay));if(errorPersistedOutputFiles!==void 0){errorResponse.persistedOutputFiles=Array.from(new Set(errorPersistedOutputFiles))}const imageParts=normalizeParts(toolResult.llmContent).flatMap(part=>{const nestedImages=(part.functionResponse?.parts??[]).filter(nested=>isImagePart(nested)).map(nested=>nested);return isImagePart(part)?[part,...nestedImages]:nestedImages});if(imageParts.length>0){const basePart=errorResponse.responseParts[0];const functionResponse=basePart?.functionResponse;const imageErrorParts=functionResponse?[{...basePart,functionResponse:{...functionResponse,parts:imageParts}}]:errorResponse.responseParts;const processedImages=await this.processToolResultImages(imageErrorParts,signal,scheduledCall.request.executionOrigin);const bridgedErrorParts=processedImages.responseParts;if(bridgedErrorParts!==imageErrorParts||this.config.getEffectiveInputModalities?.()?.image===true){errorResponse={...errorResponse,responseParts:bridgedErrorParts,contentLength:bridgedErrorParts.reduce((total,part)=>{const response=part.functionResponse?.response;const text3=response?.["error"]??response?.["output"];return total+(typeof text3==="string"?text3.length:0)},0),...processedImages.modelOverride!==void 0?{modelOverride:processedImages.modelOverride}:{},...processedImages.visionBridgeNotice!==void 0?{visionBridgeNotice:processedImages.visionBridgeNotice}:{}}}}if(canonicalName===ToolNames.EXEC){const audioParts=normalizeParts(toolResult.llmContent).filter(part=>part.inlineData?.mimeType?.startsWith("audio/"));const response=errorResponse.responseParts[0]?.functionResponse;if(response&&audioParts.length>0){response.parts=[...response.parts??[],...audioParts]}}if(cancelAfterPostProcessing([...toolResult.artifacts??[],...failureHookArtifacts??[]],{persistedOutputFiles:errorResponse.persistedOutputFiles,visionBridgeNotice:errorResponse.visionBridgeNotice})){return}observeProducerOutput(errorResponse);this.setStatusInternal(callId,"error",errorResponse);setToolSpanFailure(span,TOOL_FAILURE_KIND_TOOL_ERROR,TOOL_SPAN_STATUS_TOOL_ERROR)}}catch(executionError){const errorMessage=executionError instanceof Error?executionError.message:String(executionError);const executionThrew=!executionSettled&&executionStatus!=="not_started";const explicitErrorType=executionError?.errorType;const executionTimedOut=executionThrew&&explicitErrorType==="execution_timeout";const aborted3=signal.aborted&&!executionTimedOut;if(executionThrew){executionStatus=aborted3?"cancelled":"error";executionSettled=true;try{this.schedulerOptions.onToolExecutionSettled?.(callId,executionStatus,elapsedExecutionMs()??0)}catch(error3){debugLogger51.warn("Tool lifecycle end observer failed:",error3)}}const exceptionErrorType=explicitErrorType??(executionThrew&&scheduledCall.tool instanceof DiscoveredMCPTool?"mcp_tool_error":"unhandled_exception");if(execSpan){const failedExecSpan=execSpan;execSpan=void 0;endToolExecutionSpan(failedExecSpan,{success:false,error:aborted3?TOOL_SPAN_STATUS_TOOL_CANCELLED:executionTimedOut?TOOL_SPAN_STATUS_TOOL_TIMEOUT:TOOL_SPAN_STATUS_TOOL_EXCEPTION,cancelled:aborted3,executionStatus,errorType:executionStatus==="error"?exceptionErrorType:void 0})}if(aborted3){let cancelMessage=executionThrew?TOOL_CANCELLED_BEFORE_COMPLETION_MESSAGE:TOOL_CANCELLED_AFTER_COMPLETION_MESSAGE;let failureHookArtifacts;if(hooksEnabled&&messageBus){const failureHookResult=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:canonicalName,toolUseId,isInterrupt:true},()=>safelyFirePostToolUseFailureHook(messageBus,toolUseId,canonicalName,toolInput,cancelMessage,true,this.config.getApprovalMode(),callId,elapsedExecutionMs(),this.hookOwners.get(callId)),this.postToolUseFailureEndMeta);if(failureHookResult.additionalContext&&!this.keepFailureContextForParent(callId,failureHookResult.additionalContext)){cancelMessage+=`
599
600
 
@@ -2148,7 +2149,7 @@ ${trimmedContent}
2148
2149
  --- End of Context from: ${displayPath} ---`}).join("\n\n")}__name(concatenateInstructions,"concatenateInstructions");function createMemoryTypeClassifier(userHomePath,foundRoot,extensionContextFilePaths){const resolvedHome=path85.resolve(userHomePath);const globalQwenDir=path85.resolve(Storage.getGlobalQwenDir());const resolvedRoot=foundRoot?path85.resolve(foundRoot):void 0;const extensionPaths=new Set(extensionContextFilePaths.map(filePath=>path85.resolve(filePath)));const extensionRoots=extensionContextFilePaths.map(filePath=>path85.dirname(path85.resolve(filePath)));return filePath=>{const resolvedPath=path85.resolve(filePath);if(extensionPaths.has(resolvedPath)||extensionRoots.some(root=>isSubpath(root,resolvedPath))){return"extension"}if(resolvedPath.startsWith(`${globalQwenDir}${path85.sep}`)){return"user"}if(resolvedRoot&&resolvedPath===path85.join(resolvedRoot,QWEN_DIR,LOCAL_CONTEXT_FILENAME)){return"local"}if(resolvedRoot&&isSubpath(resolvedRoot,resolvedPath)){return"project"}if(path85.dirname(resolvedPath)===resolvedHome){return"user"}return"project"}}__name(createMemoryTypeClassifier,"createMemoryTypeClassifier");async function loadServerHierarchicalMemory(currentWorkingDirectory,includeDirectoriesToReadMemory,fileService,extensionContextFilePaths=[],folderTrust,importFormat="tree",contextRuleExcludes=[],options2={}){logger5.debug(`Loading server hierarchical memory for CWD: ${currentWorkingDirectory} (importFormat: ${importFormat})`);const implicitDiscoveryEnabled=!options2.explicitOnly;const userHomePath=homedir6();const filePaths=await getMemoryFilePathsInternal(currentWorkingDirectory,includeDirectoriesToReadMemory,userHomePath,fileService,extensionContextFilePaths,folderTrust,implicitDiscoveryEnabled);const resolvedCwd=path85.resolve(currentWorkingDirectory);const foundRoot=await findProjectRoot(resolvedCwd);const effectiveRoot=foundRoot??resolvedCwd;if(implicitDiscoveryEnabled&&folderTrust&&foundRoot){const localContextPath=path85.join(foundRoot,QWEN_DIR,LOCAL_CONTEXT_FILENAME);try{await fs79.access(localContextPath,fsSync6.constants.R_OK);if(!filePaths.includes(localContextPath)){filePaths.push(localContextPath);logger5.debug(`Found readable local ${LOCAL_CONTEXT_FILENAME}: ${localContextPath}`)}}catch{}}const{filePaths:dedupedFilePaths,topLevelFiles}=await dedupeByCanonicalIdentity(filePaths);let combinedInstructions="";let fileCount=0;let contextFilePaths=[];if(dedupedFilePaths.length>0){const loadReason=options2.loadReason??"session_start";const contentsWithPaths=await readMemoryFiles(dedupedFilePaths,topLevelFiles,importFormat,createMemoryTypeClassifier(userHomePath,foundRoot,extensionContextFilePaths),options2.onInstructionsLoaded,loadReason);combinedInstructions=concatenateInstructions(contentsWithPaths,currentWorkingDirectory);const memoryFilenames=new Set([...getAllMemoryFilenames(),LOCAL_CONTEXT_FILENAME]);const memoryItems=contentsWithPaths.filter(item=>memoryFilenames.has(path85.basename(item.filePath)));fileCount=memoryItems.length;contextFilePaths=contentsWithPaths.filter(hasAttachedContent).map(item=>formatContextFileDisplayPath(item.filePath,currentWorkingDirectory,userHomePath))}const{content:rulesContent,ruleCount,conditionalRules,ignoredExtensionRules}=options2.explicitOnly?{content:"",ruleCount:0,conditionalRules:[],ignoredExtensionRules:[]}:await loadRules(effectiveRoot,folderTrust,contextRuleExcludes,options2.extensionRuleSources??[]);let memoryContent=combinedInstructions;if(rulesContent){memoryContent=memoryContent?`${memoryContent}
2149
2150
 
2150
2151
  ${rulesContent}`:rulesContent}if(!memoryContent&&dedupedFilePaths.length===0&&ruleCount===0){logger5.debug("No QWEN.md files or rules found.")}return{memoryContent,fileCount,contextFilePaths,ruleCount,conditionalRules,...ignoredExtensionRules.length>0?{ignoredExtensionRules}:{},projectRoot:effectiveRoot}}__name(loadServerHierarchicalMemory,"loadServerHierarchicalMemory");init_esbuild_shims();import{execFile as execFile9}from"node:child_process";import*as path86 from"node:path";import{promisify as promisify5}from"node:util";var execFileAsync5=promisify5(execFile9);var debugLogger122=createDebugLogger("TEAM_MEMORY_SYNC");var GIT_TIMEOUT_MS=15e3;async function tryGit(cwd,args,killSignal="SIGTERM"){try{const{stdout}=await execFileAsync5("git",[...NO_EXEC_CONFIG,...args],{cwd,encoding:"utf8",timeout:GIT_TIMEOUT_MS,killSignal,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:process.env["GIT_SSH_COMMAND"]?`${process.env["GIT_SSH_COMMAND"]} -oBatchMode=yes -oConnectTimeout=5`:"ssh -oBatchMode=yes -oConnectTimeout=5"}});return stdout}catch(error3){debugLogger122.debug(`git ${args[0]} failed`,error3);return null}}__name(tryGit,"tryGit");async function resolvePushTarget(gitRoot,branch){const remote=(await tryGit(gitRoot,["config","--get",`branch.${branch}.remote`]))?.trim();const mergeRef=(await tryGit(gitRoot,["config","--get",`branch.${branch}.merge`]))?.trim();if(!remote||!mergeRef){return null}return{remote,mergeRef}}__name(resolvePushTarget,"resolvePushTarget");async function syncTeamMemory(projectRoot,opts){const result={committed:false,pulled:false,pushed:false};let ourSha=null;const teamRoot=getTeamAutoMemoryRoot(projectRoot);const gitRoot=findGitRoot(teamRoot);if(!gitRoot||!isGitRepository(gitRoot)){result.skippedReason="not-a-git-repo";return result}const relPath=path86.relative(gitRoot,teamRoot)||".";const branch=(await tryGit(gitRoot,["symbolic-ref","--quiet","--short","HEAD"],"SIGKILL"))?.trim();if(!branch){result.skippedReason="detached-head";return result}const upstream=await tryGit(gitRoot,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],"SIGKILL");let wasAheadBeforeSync=false;if(upstream!==null){const ahead=await tryGit(gitRoot,["rev-list","@{u}..HEAD"]);wasAheadBeforeSync=!!ahead&&ahead.trim().length>0;result.pulled=await tryGit(gitRoot,["pull","--ff-only"],"SIGKILL")!==null;if(!result.pulled){result.skippedReason="pull-failed";return result}}const status=await tryGit(gitRoot,["--no-optional-locks","status","--porcelain","--",relPath]);if(status&&status.trim().length>0){const staged=await tryGit(gitRoot,["add","--",relPath])!==null;const commitArgs=["commit","--no-gpg-sign","-m",opts.message];if(opts.author){const email4=opts.author.email??`${opts.author.name}@users.noreply`;commitArgs.push("--author",`${opts.author.name} <${email4}>`)}commitArgs.push("--",relPath);result.committed=await tryGit(gitRoot,commitArgs)!==null;if(result.committed){ourSha=(await tryGit(gitRoot,["rev-parse","HEAD"],"SIGKILL"))?.trim()??null}if(!result.committed&&staged){await tryGit(gitRoot,["reset","--quiet","--",relPath])}}if(upstream===null){result.skippedReason="no-upstream";return result}if(!result.committed){return result}if(wasAheadBeforeSync){result.skippedReason="local-ahead";return result}const pushTarget=await resolvePushTarget(gitRoot,branch);if(!pushTarget){result.skippedReason="push-failed";return result}result.pushed=await tryGit(gitRoot,["push",pushTarget.remote,`HEAD:${pushTarget.mergeRef}`],"SIGKILL")!==null;if(!result.pushed){const headNow=(await tryGit(gitRoot,["rev-parse","HEAD"],"SIGKILL"))?.trim()??null;const remoteTip=await tryGit(gitRoot,["ls-remote",pushTarget.remote,pushTarget.mergeRef],"SIGKILL");const remoteHasIt=ourSha!==null&&(remoteTip??"").includes(ourSha);if(headNow===ourSha&&!remoteHasIt){const rewound=await tryGit(gitRoot,["reset","--soft",`${ourSha}^`],"SIGTERM")!==null;const unstaged=await tryGit(gitRoot,["reset","--quiet","--",relPath])!==null;if(!rewound||!unstaged){debugLogger122.warn(`team memory push-failed rollback incomplete (reset=${rewound}, unstage=${unstaged})`)}}result.skippedReason="push-failed"}return result}__name(syncTeamMemory,"syncTeamMemory");init_esbuild_shims();import*as path87 from"node:path";init_esbuild_shims();import{execFileSync as execFileSync3}from"node:child_process";var GIT_TIMEOUT_MS2=5e3;function isGitIgnored(worktree,path89,timeoutMs=GIT_TIMEOUT_MS2){const probe=path89.startsWith(":")?`./${path89}`:path89;const env={};for(const[key,value]of Object.entries(process.env)){if(!key.startsWith("GIT_"))env[key]=value}env["GIT_CONFIG_NOSYSTEM"]="1";try{execFileSync3("git",[...NO_EXEC_CONFIG,"-C",worktree,"check-ignore","-q","--",probe],{stdio:"ignore",timeout:timeoutMs,env});return true}catch{return false}}__name(isGitIgnored,"isGitIgnored");var debugLogger123=createDebugLogger("TEAM_MEMORY_GIT_STATUS");function isTeamFileGitIgnored(gitRoot,filePath){const rel=path87.relative(gitRoot,filePath)||".";return isGitIgnored(gitRoot,rel)}__name(isTeamFileGitIgnored,"isTeamFileGitIgnored");function getTeamMemoryShareabilityWarning(projectRoot){const teamRoot=getTeamAutoMemoryRoot(projectRoot);const gitRoot=findGitRoot(teamRoot);if(!gitRoot){debugLogger123.debug(`No git root for team memory at ${teamRoot}.`);return`Team memory is enabled, but ${teamRoot} is not inside a git repository, so saved memories stay local and are not shared with collaborators.`}const indexIgnored=isTeamFileGitIgnored(gitRoot,getTeamAutoMemoryIndexPath(projectRoot));const topicIgnored=isTeamFileGitIgnored(gitRoot,path87.join(teamRoot,"feedback.md"));if(indexIgnored||topicIgnored){debugLogger123.debug(`Team memory at ${teamRoot} is git-ignored (index=${indexIgnored}, topic=${topicIgnored}).`);return`Team memory is enabled, but ${teamRoot} is git-ignored, so saved memories are not shared. If your .gitignore excludes '.qwen/' (directory form), change it to '.qwen/*' and re-include '.qwen/team-memory/' (and its contents, e.g. '!.qwen/team-memory/**').`}return null}__name(getTeamMemoryShareabilityWarning,"getTeamMemoryShareabilityWarning");init_esbuild_shims();var SAFE_MODE_ENV_VAR="QWEN_CODE_SAFE_MODE";function isSafeModeEnv(){return isTruthy(process.env[SAFE_MODE_ENV_VAR])}__name(isSafeModeEnv,"isSafeModeEnv");init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();function resolveField(layers,defaultValue,defaultSource2={kind:"default"}){for(const layer2 of layers){if(isValuePresent(layer2.value)){return{value:layer2.value,source:layer2.source}}}return{value:defaultValue,source:defaultSource2}}__name(resolveField,"resolveField");function resolveOptionalField(layers){for(const layer2 of layers){if(isValuePresent(layer2.value)){return{value:layer2.value,source:layer2.source}}}return void 0}__name(resolveOptionalField,"resolveOptionalField");function isValuePresent(value){if(value===void 0||value===null){return false}if(typeof value==="string"&&value.trim()===""){return false}return true}__name(isValuePresent,"isValuePresent");function cliSource(detail){return{kind:"cli",detail}}__name(cliSource,"cliSource");function envSource(envKey){return{kind:"env",envKey}}__name(envSource,"envSource");function settingsSource(settingsPath){return{kind:"settings",settingsPath}}__name(settingsSource,"settingsSource");function modelProvidersSource(authType,modelId,detail){return{kind:"modelProviders",authType,modelId,detail}}__name(modelProvidersSource,"modelProvidersSource");function defaultSource(detail){return{kind:"default",detail}}__name(defaultSource,"defaultSource");function computedSource(detail){return{kind:"computed",detail}}__name(computedSource,"computedSource");function envLayer(env,key,transform3){const rawValue=env[key];const value=rawValue!==void 0?transform3?transform3(rawValue):rawValue:void 0;return{value,source:envSource(key)}}__name(envLayer,"envLayer");function layer(value,source){return{value,source}}__name(layer,"layer");function applyTimeoutEnvOverride(env,generationConfig,sources,modelProvider){if(modelProvider?.generationConfig?.timeout!==void 0)return;const raw=env["QWEN_CODE_API_TIMEOUT_MS"];if(raw===void 0)return;const trimmed=raw.trim();if(!/^\d+$/.test(trimmed))return;const parsed=Number(trimmed);if(!Number.isSafeInteger(parsed))return;generationConfig.timeout=parsed;sources["timeout"]={kind:"env",envKey:"QWEN_CODE_API_TIMEOUT_MS"}}__name(applyTimeoutEnvOverride,"applyTimeoutEnvOverride");function resolveModelConfig(input){const{authType,cli,settings,env,modelProvider,proxy}=input;const warnings=[];const sources={};if(authType==="qwen-oauth"){return resolveQwenOAuthConfig(input,warnings)}const envMapping=authType?AUTH_ENV_MAPPINGS[authType]:{model:[],apiKey:[],baseUrl:[]};const modelLayers=[];if(authType&&modelProvider){modelLayers.push(layer(modelProvider.id,modelProvidersSource(authType,modelProvider.id,"model.id")))}if(cli?.model){modelLayers.push(layer(cli.model,cliSource("--model")))}for(const envKey of envMapping.model){modelLayers.push(envLayer(env,envKey))}if(settings?.model){modelLayers.push(layer(settings.model,settingsSource("model.name")))}const defaultModel=authType?DEFAULT_MODELS[authType]:"";const modelResult=resolveField(modelLayers,defaultModel,defaultSource(defaultModel));sources["model"]=modelResult.source;const apiKeyLayers=[];if(authType&&modelProvider?.envKey){const apiKeyFromEnv=env[modelProvider.envKey];if(apiKeyFromEnv){apiKeyLayers.push(layer(apiKeyFromEnv,{kind:"env",envKey:modelProvider.envKey,via:modelProvidersSource(authType,modelProvider.id,"envKey")}))}}if(cli?.apiKey){apiKeyLayers.push(layer(cli.apiKey,cliSource("--openaiApiKey")))}for(const envKey of envMapping.apiKey){apiKeyLayers.push(envLayer(env,envKey))}if(settings?.apiKey){apiKeyLayers.push(layer(settings.apiKey,settingsSource("security.auth.apiKey")))}const apiKeyResult=resolveOptionalField(apiKeyLayers);if(apiKeyResult){sources["apiKey"]=apiKeyResult.source}const baseUrlLayers=[];if(authType&&modelProvider?.baseUrl){baseUrlLayers.push(layer(modelProvider.baseUrl,modelProvidersSource(authType,modelProvider.id,"baseUrl")))}if(cli?.baseUrl){baseUrlLayers.push(layer(cli.baseUrl,cliSource("--openaiBaseUrl")))}for(const envKey of envMapping.baseUrl){baseUrlLayers.push(envLayer(env,envKey))}if(settings?.baseUrl){baseUrlLayers.push(layer(settings.baseUrl,settingsSource("security.auth.baseUrl")))}const baseUrlResult=resolveOptionalField(baseUrlLayers);if(baseUrlResult){sources["baseUrl"]=baseUrlResult.source}let apiKeyEnvKey;if(authType&&modelProvider?.envKey){apiKeyEnvKey=modelProvider.envKey;sources["apiKeyEnvKey"]={...modelProvidersSource(authType,modelProvider.id,"envKey"),envKey:modelProvider.envKey}}const generationConfig=resolveGenerationConfig(settings?.generationConfig,modelProvider?.generationConfig,authType,modelProvider?.id??modelResult.value,sources);applyTimeoutEnvOverride(env,generationConfig,sources,modelProvider);const config3={authType,model:modelResult.value||"",apiKey:apiKeyResult?.value,apiKeyEnvKey,baseUrl:baseUrlResult?.value,proxy,...generationConfig};if(proxy){sources["proxy"]=computedSource("Config.getProxy()")}sources["authType"]=computedSource("provided by caller");return{config:config3,sources,warnings}}__name(resolveModelConfig,"resolveModelConfig");function resolveQwenOAuthConfig(input,warnings){const{cli,settings,proxy,modelProvider}=input;const sources={};const allowedModels=new Set(QWEN_OAUTH_ALLOWED_MODELS);const requestedModel=cli?.model||settings?.model;let resolvedModel;let modelSource;if(requestedModel&&allowedModels.has(requestedModel)){resolvedModel=requestedModel;modelSource=cli?.model?cliSource("--model"):settingsSource("model.name")}else{if(requestedModel){const isVisionModel=requestedModel.includes("vl")||requestedModel.includes("vision");const extraMessage=isVisionModel?` Note: vision-model has been removed since coder-model now supports vision capabilities.`:"";warnings.push(`Warning: Unsupported Qwen OAuth model '${requestedModel}', falling back to '${DEFAULT_QWEN_MODEL}'.${extraMessage}`)}resolvedModel=DEFAULT_QWEN_MODEL;modelSource=defaultSource(`fallback to '${DEFAULT_QWEN_MODEL}'`)}sources["model"]=modelSource;sources["apiKey"]=computedSource("Qwen OAuth dynamic token");sources["authType"]=computedSource("provided by caller");if(proxy){sources["proxy"]=computedSource("Config.getProxy()")}const generationConfig=resolveGenerationConfig(settings?.generationConfig,modelProvider?.generationConfig,"qwen-oauth",resolvedModel,sources);applyTimeoutEnvOverride(input.env,generationConfig,sources,modelProvider);const config3={authType:"qwen-oauth",model:resolvedModel,apiKey:"QWEN_OAUTH_DYNAMIC_TOKEN",proxy,...generationConfig};return{config:config3,sources,warnings}}__name(resolveQwenOAuthConfig,"resolveQwenOAuthConfig");function resolveGenerationConfig(settingsConfig,modelProviderConfig,authType,modelId,sources){const result={};for(const field of MODEL_GENERATION_CONFIG_FIELDS){if(authType&&modelProviderConfig&&field in modelProviderConfig){result[field]=modelProviderConfig[field];sources[field]=modelProvidersSource(authType,modelId||"",`generationConfig.${field}`)}else if(settingsConfig&&field in settingsConfig){result[field]=settingsConfig[field];sources[field]=settingsSource(`model.generationConfig.${field}`)}}if(result.contextWindowSize===void 0&&modelId){const knownLimit=knownTokenLimit(modelId,"input");if(knownLimit!==void 0){result.contextWindowSize=knownLimit;sources["contextWindowSize"]=computedSource("auto-detected from model")}}if(result.modalities===void 0&&modelId){result.modalities=defaultModalities(modelId);sources["modalities"]=computedSource("auto-detected from model")}return result}__name(resolveGenerationConfig,"resolveGenerationConfig");var gitCoAuthorLogger=createDebugLogger("GIT_CO_AUTHOR");var memoryPressureConfigLogger=createDebugLogger("MEMORY_PRESSURE");var MEMORY_CONTEXT_WARNING_RATIO=.15;var MEMORY_CONTEXT_WARNING_MAX_TOKENS=1e4;var ACTIVE_TODO_REMINDER_REFRESH_TURNS=3;var DEFAULT_TOOL_SEARCH_THRESHOLD=0;var MANAGED_ACTIVATION_LEASE_MS=5*60*1e3;function managedRecordWriter(managed,log){return{canCarry:__name(record4=>managed.sink.canCarry(record4),"canCarry"),write:__name(record4=>managed.sink.write(record4),"write"),project:__name(()=>readManagedSessionRecords({transcriptPath:log.transcriptPath,runtimeBaseDir:log.runtimeBaseDir,sessionKey:managed.authority.sessionHeader.sessionKey}),"project"),stopAdvancing:__name(()=>stopAdvancing(managed),"stopAdvancing"),commitProof:__name(()=>managedCommitProof(managed),"commitProof"),logSize:__name(()=>{try{return fs80.statSync(log.transcriptPath).size}catch{return void 0}},"logSize")}}__name(managedRecordWriter,"managedRecordWriter");async function stopAdvancing(managed){await managed.close();await managed.releaseActivation()}__name(stopAdvancing,"stopAdvancing");function managedCommitProof(managed){const proof=managed.authority.commitProof;return{last_commit_sequence:proof.lastCommitSequence,committed_prefix_hash:proof.committedPrefixHash}}__name(managedCommitProof,"managedCommitProof");function parseVisionModelSetting(setting){if(!setting)return void 0;const nullIdx=setting.indexOf("\0");if(nullIdx<0)return{selector:setting};const selector=setting.slice(0,nullIdx);if(!selector)return void 0;return{selector,baseUrl:setting.slice(nullIdx+1)||void 0}}__name(parseVisionModelSetting,"parseVisionModelSetting");function formatVisionModelSettingForLog(setting){return setting.replace(/\0/g,"\\0")}__name(formatVisionModelSettingForLog,"formatVisionModelSettingForLog");function isValidAdvisorMaxUses(value){return Number.isSafeInteger(value)&&value>=0}__name(isValidAdvisorMaxUses,"isValidAdvisorMaxUses");function normalizeAdvisorModel(model){const trimmed=model?.trim();if(!trimmed||trimmed.toLowerCase()==="off")return void 0;return trimmed}__name(normalizeAdvisorModel,"normalizeAdvisorModel");var TrustGateError=class extends Error{static{__name(this,"TrustGateError")}constructor(message){super(message);this.name="TrustGateError"}};var SESSION_AGENT_APPROVAL_MODE_ERROR='A session agent always asks before writing or running commands; its approval mode stays "default".';var APPROVAL_MODE_INFO={["plan"]:{id:"plan",name:"Plan",description:"Analyze only, do not modify files or execute commands"},["default"]:{id:"default",name:"Default",description:"Require approval for file edits or shell commands"},["auto-edit"]:{id:"auto-edit",name:"Auto Edit",description:"Automatically approve file edits"},["auto"]:{id:"auto",name:"Auto",description:"LLM classifier auto-approves safe actions, blocks risky ones"},["yolo"]:{id:"yolo",name:"YOLO",description:"Automatically approve all tools"}};function normalizeGitCoAuthor(value){if(typeof value==="boolean"){return{commit:value,pr:value}}const pickBool=__name((v2,fieldName)=>{if(v2===void 0)return true;if(typeof v2==="boolean")return v2;if(typeof v2==="string"){const lowered=v2.trim().toLowerCase();if(lowered==="true"||lowered==="yes"||lowered==="on"||lowered==="1"){return true}const knownDisable=["false","no","off","0","disabled",""];if(!knownDisable.includes(lowered)){gitCoAuthorLogger.warn(`Unrecognized string value for general.gitCoAuthor.${fieldName}: ${JSON.stringify(v2)}; treating as false. Accepted forms: true/yes/on/1, false/no/off/0/empty.`)}return false}if(typeof v2==="number")return v2===1;return false},"pickBool");return{commit:pickBool(value?.commit,"commit"),pr:pickBool(value?.pr,"pr")}}__name(normalizeGitCoAuthor,"normalizeGitCoAuthor");var DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD=25e3;var DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES=1e3;var DEFAULT_TOOL_OUTPUT_BATCH_BUDGET=2e5;function normalizeConfigOutputFormat(format){if(!format){return void 0}switch(format){case"stream-json":return"stream-json";case"json":case"json":return"json";case"text":case"text":default:return"text"}}__name(normalizeConfigOutputFormat,"normalizeConfigOutputFormat");function loadMemoryPressureConfig(){const config3={...DEFAULT_PRESSURE_CONFIG};try{config3.softPressureRatio=readMemoryPressureRatioEnv("QWEN_MEMORY_PRESSURE_SOFT",config3.softPressureRatio);config3.hardPressureRatio=readMemoryPressureRatioEnv("QWEN_MEMORY_PRESSURE_HARD",config3.hardPressureRatio);config3.criticalRatio=readMemoryPressureRatioEnv("QWEN_MEMORY_PRESSURE_CRITICAL",config3.criticalRatio);const enableGC=process8.env["QWEN_MEMORY_ENABLE_GC"];if(enableGC&&["0","false","off","no"].includes(enableGC.trim().toLowerCase())){config3.enableExplicitGC=false}validateMemoryPressureConfig(config3)}catch(err){const fallbackMsg=`[QWEN] WARNING: Invalid memory pressure config; using defaults. Error: ${getErrorMessage(err)}`;process8.stderr.write(`${fallbackMsg}
2151
- `);memoryPressureConfigLogger.warn(fallbackMsg);return{...DEFAULT_PRESSURE_CONFIG}}return config3}__name(loadMemoryPressureConfig,"loadMemoryPressureConfig");var DEFAULT_MAX_SUBAGENT_DEPTH=5;var MAX_SUBAGENT_DEPTH_LIMIT=100;function normalizeMaxSubagentDepth(value){return value==null||!Number.isFinite(value)?DEFAULT_MAX_SUBAGENT_DEPTH:Math.min(MAX_SUBAGENT_DEPTH_LIMIT,Math.max(1,Math.floor(value)))}__name(normalizeMaxSubagentDepth,"normalizeMaxSubagentDepth");function validateMaxSessionTurns(value){const resolved=value??-1;if(!Number.isInteger(resolved)){throw new FatalConfigError(`Invalid maxSessionTurns: must be an integer, got ${String(resolved)}`)}return resolved}__name(validateMaxSessionTurns,"validateMaxSessionTurns");function normalizeGoalTokenBudget(value){if(value===0||value===-1)return Number.POSITIVE_INFINITY;return isValidGoalTokenBudget(value)?value:GOAL_DEFAULT_TOKEN_BUDGET}__name(normalizeGoalTokenBudget,"normalizeGoalTokenBudget");var GOAL_TOKEN_BUDGET_CAP=10*GOAL_DEFAULT_TOKEN_BUDGET;function isValidGoalTokenBudget(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_TOKEN_BUDGET_CAP)}__name(isValidGoalTokenBudget,"isValidGoalTokenBudget");var GOAL_MAX_TURNS_CAP=1e4;var GOAL_MAX_ACTIVE_MINUTES_CAP=7*24*60;function isValidGoalMaxTurns(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_MAX_TURNS_CAP)}__name(isValidGoalMaxTurns,"isValidGoalMaxTurns");function normalizeGoalMaxTurns(value){if(!isValidGoalMaxTurns(value)||value===-1||value===0){return Number.POSITIVE_INFINITY}return value}__name(normalizeGoalMaxTurns,"normalizeGoalMaxTurns");function isValidGoalMaxActiveMinutes(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_MAX_ACTIVE_MINUTES_CAP)}__name(isValidGoalMaxActiveMinutes,"isValidGoalMaxActiveMinutes");function normalizeGoalMaxActiveMinutes(value){if(!isValidGoalMaxActiveMinutes(value)||value===-1||value===0){return Number.POSITIVE_INFINITY}return value*6e4}__name(normalizeGoalMaxActiveMinutes,"normalizeGoalMaxActiveMinutes");function validateMaxToolCallsPerTurn(value){const resolved=value??DEFAULT_MAX_TOOL_CALLS_PER_TURN;if(!Number.isInteger(resolved)){throw new FatalConfigError(`Invalid maxToolCallsPerTurn: must be an integer, got ${String(resolved)}`)}return resolved}__name(validateMaxToolCallsPerTurn,"validateMaxToolCallsPerTurn");var MAX_MODEL_FALLBACKS=3;function normalizeModelFallbacks(raw){if(!raw||raw.length===0)return[];const seen=new Set;const result=[];for(const entry of raw){const trimmed=entry.trim();if(!trimmed||seen.has(trimmed))continue;seen.add(trimmed);result.push(trimmed);if(result.length>=MAX_MODEL_FALLBACKS)break}return result}__name(normalizeModelFallbacks,"normalizeModelFallbacks");function bareEnabledGrantWarnings(lists,skills,defaultOffNames=new Set){if(lists.enabled.size===0)return[];const registry3=new Set(skills.map(skill=>skill.name.trim().toLowerCase()));const registryNamesByAuthored=new Map;for(const skill of skills){const authored=authoredSkillName(skill).trim().toLowerCase();const registryName=skill.name.trim().toLowerCase();if(authored===registryName)continue;const group=registryNamesByAuthored.get(authored)??[];group.push(registryName);registryNamesByAuthored.set(authored,group)}const warnings=[];for(const[authored,registryNames]of registryNamesByAuthored){if(registry3.has(authored))continue;if(!lists.enabled.has(authored))continue;const plural=registryNames.length>1;const names=registryNames.map(name2=>`'${name2}'`).join(", ");const skillWord=plural?"skills":"skill";const hardNote=lists.hardDisabled.has(authored)?` A bare '${authored}' in skills.disabled also blocks ${plural?"them":"it"} under either spelling, so replacing the grant alone will not enable anything: remove that entry too.`:"";if(lists.defaultDisabled.has(authored)){const offNames=registryNames.filter(name2=>defaultOffNames.has(name2));const onNames=offNames.filter(name2=>lists.enabled.has(name2)&&!lists.hardDisabled.has(name2)&&!lists.hardDisabled.has(authored));const stillOff=offNames.filter(name2=>!onNames.includes(name2));if(stillOff.length){const offPlural=stillOff.length>1;const offList=stillOff.map(name2=>`'${name2}'`).join(", ");const hardQualified=stillOff.filter(name2=>lists.hardDisabled.has(name2));const qualifiedNote=hardQualified.length?` ${hardQualified.map(name2=>`'${name2}'`).join(", ")} in skills.disabled also blocks ${hardQualified.length>1?"them":"it"} under either spelling, so replacing the grant alone will not enable anything: remove ${hardQualified.length>1?"those entries":"that entry"} too.`:"";warnings.push(`Warning: skills.enabled and skills.defaultDisabled both list '${authored}' by bare name. The pair cancels the disablement but no longer enables the extension ${offPlural?"skills":"skill"} ${offList}, which ${offPlural?"default":"defaults"} off. Replace the bare '${authored}' with ${offList} in both skills.enabled and skills.defaultDisabled to enable ${offPlural?"them":"it"}.`+hardNote+qualifiedNote)}if(onNames.length){const onPlural=onNames.length>1;const onList=onNames.map(name2=>`'${name2}'`).join(", ");warnings.push(`Warning: skills.enabled and skills.defaultDisabled both list '${authored}' by bare name, but the qualified ${onPlural?"grants":"grant"} ${onList} in skills.enabled already ${onPlural?"enable":"enables"} ${onPlural?"them":"it"}, so the bare pair changes nothing. Replace the bare '${authored}' with ${onList} in both skills.enabled and skills.defaultDisabled to drop the dead entries.`)}continue}warnings.push(`Warning: skills.enabled lists '${authored}' by bare name, which no longer enables the extension ${skillWord} ${names}. Replace it with ${names}.`+hardNote)}return warnings}__name(bareEnabledGrantWarnings,"bareEnabledGrantWarnings");function bareDisablementBlocksQualifiedGrantWarnings(lists,disabledNames,skills){if(lists.enabled.size===0||disabledNames.size===0)return[];const warnings=[];for(const skill of skills){const authored=authoredSkillName(skill).trim().toLowerCase();const registryName=skill.name.trim().toLowerCase();if(authored===registryName)continue;if(!lists.enabled.has(registryName))continue;if(!disabledNames.has(authored))continue;if(lists.hardDisabled.has(authored)){const unlocked=[...new Set(skills.filter(other2=>{const name2=other2.name.trim().toLowerCase();return name2!==registryName&&(name2===authored||authoredSkillName(other2).trim().toLowerCase()===authored)}).map(other2=>other2.name.trim().toLowerCase()))];const names=__name(list2=>list2.map(name2=>`'${name2}'`).join(", "),"names");const reBlockable=unlocked.filter(name2=>name2!==authored);const notAlone=unlocked.filter(name2=>name2===authored);let sideEffect="";if(unlocked.length){sideEffect=` The removal also re-enables ${names(unlocked)}.`;if(reBlockable.length){sideEffect+=` Add ${names(reBlockable)} to skills.disabled to keep ${reBlockable.length>1?"them":"it"} blocked.`}if(notAlone.length){sideEffect+=` ${names(notAlone)} cannot be blocked on ${notAlone.length>1?"their":"its"} own while '${registryName}' stays enabled, because any entry matching ${names(notAlone)} also matches '${registryName}'.`}}warnings.push(`Warning: skills.enabled opts in '${registryName}' but '${authored}' in skills.disabled still blocks it \u2014 hard entries are never cancelled by skills.enabled. Remove '${authored}' from skills.disabled to enable the skill.`+sideEffect);continue}warnings.push(`Warning: skills.enabled opts in '${registryName}' but a bare '${authored}' entry still blocks it \u2014 disable entries match under either spelling; a skills.defaultDisabled entry is cancelled only by the identical spelling. Write '${registryName}' in both lists, or remove '${authored}'.`)}return warnings}__name(bareDisablementBlocksQualifiedGrantWarnings,"bareDisablementBlocksQualifiedGrantWarnings");function readMemoryPressureRatioEnv(envName,fallback){const raw=process8.env[envName];if(!raw){return fallback}const parsed=Number(raw);if(!Number.isFinite(parsed)){throw new Error(`${envName} must be a finite number`)}return parsed}__name(readMemoryPressureRatioEnv,"readMemoryPressureRatioEnv");var DEFAULT_BARE_CORE_TOOLS=[ToolNames.READ_FILE,ToolNames.EDIT,ToolNames.NOTEBOOK_EDIT,ToolNames.SHELL];var EMPTY_DISABLED_SKILL_NAMES=Object.freeze(new Set);var sessionEnvClaimed=false;var projectDirEnvClaimed=false;var modelEnvClaimed=false;function resolveSensitiveSpanAttributeMaxLength(value){if(value===void 0){return DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH}if(!isValidSensitiveSpanAttributeMaxLength(value)){throw new FatalConfigError(`Invalid telemetry.sensitiveSpanAttributeMaxLength: must be a positive integer no greater than ${SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT}, got ${String(value)}`)}return value}__name(resolveSensitiveSpanAttributeMaxLength,"resolveSensitiveSpanAttributeMaxLength");function resolveCronRecurringMaxAgeDays(setting){const env=process8.env["QWEN_CODE_CRON_MAX_AGE_DAYS"];const fromEnv=env!==void 0&&env.trim()!=="";const raw=fromEnv?Number(env):setting;if(raw===void 0||!Number.isFinite(raw)||raw<0){if(raw!==void 0){console.warn((fromEnv?`QWEN_CODE_CRON_MAX_AGE_DAYS="${env}" is invalid`:`cronRecurringMaxAgeDays=${setting} is invalid`)+`; recurring cron jobs will expire after the ${DEFAULT_RECURRING_MAX_AGE_DAYS}-day default.`)}return DEFAULT_RECURRING_MAX_AGE_DAYS}return normalizeRecurringMaxAge(raw,DEFAULT_RECURRING_MAX_AGE_DAYS)}__name(resolveCronRecurringMaxAgeDays,"resolveCronRecurringMaxAgeDays");var SessionWriterShutdownError=class extends SessionWriterUnavailableError{static{__name(this,"SessionWriterShutdownError")}};function containsErrorByIdentity(error3,candidate){return error3===candidate||error3 instanceof Error&&error3.cause instanceof AggregateError&&error3.cause.errors.includes(candidate)}__name(containsErrorByIdentity,"containsErrorByIdentity");var DERIVED_CONFIG=Symbol("derivedConfig");function isDerivedConfig(config3){return config3[DERIVED_CONFIG]===true}__name(isDerivedConfig,"isDerivedConfig");function deriveApprovalModeConfig(base2,mode,options2={}){const baseApprovalMode=base2.getApprovalMode();const initialMode=getTrustedDerivedApprovalMode(base2,mode);let autoOverrideAcquired=false;const acquireAutoOverride=__name(()=>{if(autoOverrideAcquired||base2.getApprovalMode()==="auto"){return}if(options2.hooks){autoOverrideAcquired=options2.hooks.acquireAutoApprovalOverride();return}base2.getPermissionManager?.()?.stripDangerousRulesForAutoMode();autoOverrideAcquired=true},"acquireAutoOverride");const releaseAutoOverride=__name(()=>{if(!autoOverrideAcquired)return;if(options2.hooks){options2.hooks.releaseAutoApprovalOverride()}else if(base2.getApprovalMode()!=="auto"){base2.getPermissionManager?.()?.restoreDangerousRules()}autoOverrideAcquired=false},"releaseAutoOverride");const derived=deriveConfig(base2,{getApprovalMode:Config.prototype.getApprovalMode});const state=derived;state.approvalMode=initialMode;state.prePlanMode=initialMode==="plan"?baseApprovalMode==="plan"?base2.getPrePlanMode():baseApprovalMode:void 0;state.approvalModeRevision=0;state.manualPlanExitNoticeEventState={...base2.manualPlanExitNoticeEventState??{version:0,kind:"clear"}};state.autoModeDenialState=createDenialState();Object.defineProperty(derived,"setApprovalMode",{value:__name((nextMode,setOptions2)=>{const beforeMode=derived.getApprovalMode();const hadOwnPermissionManager=Object.hasOwn(derived,"permissionManager");const ownPermissionManager=state.permissionManager;state.permissionManager=null;try{Config.prototype.setApprovalMode.call(derived,nextMode,setOptions2)}finally{if(hadOwnPermissionManager){state.permissionManager=ownPermissionManager}else{delete state.permissionManager}}const afterMode=derived.getApprovalMode();if(beforeMode!=="auto"&&afterMode==="auto"){acquireAutoOverride()}else if(beforeMode==="auto"&&afterMode!=="auto"){releaseAutoOverride()}},"value"),writable:true,configurable:true,enumerable:true});if(initialMode==="auto"&&base2.getApprovalMode()!=="auto"){acquireAutoOverride()}return{config:derived,cleanup:releaseAutoOverride}}__name(deriveApprovalModeConfig,"deriveApprovalModeConfig");function deriveAgentConfig(base2,workingDirectory,options2={}){const fileService=new FileDiscoveryService(workingDirectory,options2.customIgnoreFiles);const workspaceContext=new WorkspaceContext(workingDirectory);const derived=deriveConfig(base2,{getTargetDir:__name(()=>workingDirectory,"getTargetDir"),getCwd:__name(()=>workingDirectory,"getCwd"),getWorkingDir:__name(()=>workingDirectory,"getWorkingDir"),getProjectRoot:__name(()=>workingDirectory,"getProjectRoot"),getPlanFilePath:options2.getPlanFilePath,getFileService:__name(()=>fileService,"getFileService"),getWorkspaceContext:__name(()=>workspaceContext,"getWorkspaceContext")});const workspaceState=derived;workspaceState.targetDir=workingDirectory;workspaceState.cwd=workingDirectory;workspaceState.fileDiscoveryService=fileService;workspaceState.workspaceContext=workspaceContext;return{config:derived,fileService,workspaceContext}}__name(deriveAgentConfig,"deriveAgentConfig");function getTrustedDerivedApprovalMode(base2,requestedMode){if((!base2.isTrustedFolder()||base2.isSessionAgentSession?.()===true)&&requestedMode!=="default"&&requestedMode!=="plan"){return"default"}return requestedMode}__name(getTrustedDerivedApprovalMode,"getTrustedDerivedApprovalMode");function deriveWorktreeConfig(base2,worktreePath,options2={}){const fileService=new FileDiscoveryService(worktreePath,options2.customIgnoreFiles);const workspaceContext=new WorkspaceContext(worktreePath);const derived=deriveConfig(base2,{getTargetDir:__name(()=>worktreePath,"getTargetDir"),getCwd:__name(()=>worktreePath,"getCwd"),getWorkingDir:__name(()=>worktreePath,"getWorkingDir"),getProjectRoot:__name(()=>worktreePath,"getProjectRoot"),getFileService:__name(()=>fileService,"getFileService"),getWorkspaceContext:__name(()=>workspaceContext,"getWorkspaceContext")});const workspaceState=derived;workspaceState.targetDir=worktreePath;workspaceState.cwd=worktreePath;workspaceState.fileDiscoveryService=fileService;workspaceState.workspaceContext=workspaceContext;return derived}__name(deriveWorktreeConfig,"deriveWorktreeConfig");function deriveConfig(base2,overrides={}){const shellSandbox=base2.getShellExecutionSandbox?.();if(shellSandbox){for(const key of["getTargetDir","getCwd","getWorkingDir","getProjectRoot"]){assertShellSandboxCwd(shellSandbox,overrides[key]?.()??base2[key]())}}const derived=Object.create(base2);for(const key in overrides){if(!Object.hasOwn(overrides,key))continue;const override=overrides[key];if(override!==void 0){Object.defineProperty(derived,key,{value:override,writable:true,configurable:true,enumerable:true})}}Object.defineProperty(derived,DERIVED_CONFIG,{value:true});return derived}__name(deriveConfig,"deriveConfig");var Config=class _Config{static{__name(this,"Config")}shellExecutionSandbox;sessionId;sessionSourceType;sessionSourceId;sessionData;workflowModeContext=new WorkflowModeContext;initialWorkflowMode;workflowModeReady=false;workflowModeEpoch=0;workflowModeWriteTail=Promise.resolve();workflowModePublishedState;workflowModeListeners=new Set;pendingSessionRestoreProjection;sessionRestoreRuntime;sessionRestoreProjectionSource;sessionExecutionEngine;managedRuntimeEnvironmentFactory;managedRuntimeEnvironment;onManagedEngineQuarantine;managedRuntimeClosing;managedSessionBlock;restoredFileHistory=false;goalRestoreActivation;rejectGoalRestoreActivation;sessionRuntimeBaseDir;provisionalWorkspace;provisionalWorkspaceActivated=false;provisionalWorkspaceActivation;sessionProjectDirRegistered=false;pendingSessionWriterLease;managedSession;managedRuntimeOutcomes;pendingSessionWriterRelease;sessionWriterReclaimPolicy="local";sessionWriterTakeoverPolicy="never";sessionWriterShutdownRequested=false;sessionWriterHandoffRequested=false;sessionWriterActivationPromise;sessionWriterClosePromise;pendingStartupWorktreeNotice=null;pendingRecoveredAgentsNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;resourceRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry;monitorRegistry=new MonitorRegistry;backgroundAgentResumeService;backgroundShellRegistry=new BackgroundShellRegistry;workflowRunRegistry=new WorkflowRunRegistry;turnBudget=new TurnBudget;fileReadCache=new FileReadCache;extensionManager;skillManager=null;bundledGeneratedUi;bundledGeneratedUiActive=false;mcpAppHostSupported=false;bundledGeneratedUiStatus={version:1,enabled:false,reason:"setting-disabled"};permissionManager=null;toolInvocationGuard;workflowAncestorTrustProvider;modelInvocableCommandsProvider=null;modelInvocableCommandsExecutor=null;pendingInlineAnnouncedSkillKeys=new Set;fileSystemService;contentGeneratorConfig;contentGeneratorConfigSources={};contentGenerator;initialAuthType;initialResolvedAuthType;embeddingModel;modelsConfig;modelProvidersConfig;providerProtocolConfig;sandbox;targetDir;workspaceContext;debugMode;inputFormat;outputFormat;includePartialMessages;question;systemPrompt;workspaceAgentName;workspaceAgentExecutionAllowedTools;workspaceAgentDisallowedTools;sessionAgentSession=false;appendSystemPrompt;liveAppendSystemPrompt;outputStyle;coreTools;allowedTools;excludeTools;disabledSlashCommands;disabledSkillNamesProvider;enabledSkillNamesProvider;skillSettingsListsProvider;terminalImageRenderSupportProvider;disabledSkillLevels;customSkillDirs;disabledTools;visibleTools;eagerTools;toolSearchThreshold;toolMode;freeform;permissionsAllow;permissionsAsk;permissionsDeny;permissionsAutoMode;toolDiscoveryCommand;toolCallCommand;mcpServerCommand;mcpServers;recentlyRemovedMcpServers=new Set;topTierMcpServers;runtimeMcpServers=new Map;lspEnabled;lspClient;lspInitializationError;allowedMcpServers;cliAllowedMcpServerNames;excludedMcpServers;pendingMcpServers;mcpToolIdleTimeoutMs;mcpReconcileInProgress=false;mcpReconcilePending=false;mcpReconcilePromise;sessionSubagents;userMemory;staticSystemPrefix;promptToolSnapshot;promptAgentReachable=false;autoMemoryPrompt="";autoMemoryContext="";memoryRecallMode="legacy";memoryCorpusRevision="";memoryRecallModeInitialized=false;sdkMode;memoryFileCount;loadedContextFilePaths=[];conditionalRulesRegistry;contextRuleExcludes;approvalMode;prePlanMode;planExecutionMode;approvalModeRevision=0;manualPlanExitNoticeEventState={version:0,kind:"clear"};manualPlanExitNoticeCursorState={seenVersion:0};autoModeDenialState=createDenialState();accessibility;showResponseTokensPerSecond;telemetrySettings;telemetryInitializationDeferred;outboundCorrelationSettings;gitCoAuthor;usageStatisticsEnabled;fileReadCacheDisabled;activeTodoReminders=new Map;activeTodoWorkChainOwners=new Map;activeTodoReminderTurns=new Map;activeTodoPlanWriterOwner;llmClient;baseLlmClient;cronScheduler=null;fileFiltering;fileDiscoveryService=null;sessionService=void 0;chatRecordingService=void 0;goalRuntime;goalRuntimeReady;pendingGoalProposal;goalProposalApprovalController;pendingGoalRestore;goalTurnHost;goalTurnHostUnbind;goalTurnHostGeneration=0;chatRecordingFailureListeners=new Set;requestLifecycleListeners=new Set;fileCheckpointingEnabled;toolResultBudget={bytesWritten:0};fileHistoryService;proxy;cwd;explicitIncludeDirectories;bugCommand;outputLanguageFilePath;noBrowser;folderTrustFeature;folderTrust;ideMode;maxSessionTurns;goalTokenBudgetGrant;goalTurnBudgetGrant;goalActiveTimeBudgetGrantMs;maxSubagentDepth;maxWallTimeSeconds;maxToolCalls;clearContextOnIdle;sessionTokenLimit;listExtensions;overrideExtensions;cliVersion;runtimeStatusEnabled=false;sessionRegistryActive=false;sessionRegistered=false;sessionRegistrySlot=SHARED_RECORD_SLOT;experimentalZedIntegration=false;restoreAskUserQuestion=false;preserveRestorableAskUserQuestion=false;sessionWriterLeaseEnabled=false;cronEnabled=true;cronRecurringMaxAgeDays;lsToolEnabled=false;todoWriteEnabled=false;agentTeamEnabled=false;unifiedAgentLoopEnabled=false;agentCollaborationEnabled=false;artifactEnabled=true;artifactSnapshotsEnabled=false;artifactAutoOpen=true;artifactPublisher="local";artifactHost;artifactOss;omniEnabled=false;omniMaxUploadFileBytes;omniMaxEstimatedTokens;omniMaxDurationSeconds;omniUrlDownloadMaxFileBytes;omniUploadUrlTtlHours;omniUploadBaseUrl;omniUploadApiKeyEnv;omniUploadModel;omniUploadConfig;omniPolicyTools;omniFixedPolicies;omniTransportGuardPolicies;omniProcessingLimits;omniQuarantineRetentionDays;omniStorageRetentionDays;omniStorageMaxTotalBytes;omniQuarantineMaxBytes;omniMemory;omniProcessingConfig;omniMemoryConfig;omniMediaResourceRegistry;workflowsEnabled;workflowKeywordTriggerEnabled;sessionWorkflowEnabled;sessionWorkflowEnabledProvider;sessionWorkflowPlanRevision;externalAgentExecutor;agentExecutionBackend;executionEnvironmentFactory;executionEnvironment;executionEnvironments;executionShutdown=new AbortController;executionCleanupPromise;modelProposedGoals;goalProposalHostSupported=false;goalProposalTurnKey;skipWorkflowUsageWarning=false;workflowSizeGuideline;workflowNameOnly;emitToolUseSummaries=true;chatRecordingEnabled;loadMemoryFromIncludeDirectories=false;importFormat;chatCompression;autoCompactThreshold;interactive;trustedFolder;useRipgrep;useBuiltinRipgrep;shouldUseNodePtyShell;preventSystemSleep;skipNextSpeakerCheck;shellExecutionConfig;arenaManager=null;arenaManagerChangeCallback=null;arenaAgentClient;teamManager=null;teamManagerChangeCallbacks=new Set;teamContext=null;agentsSettings;worktreeSettings;skipLoopDetection;loopProtection;maxToolCallsPerTurn;maxToolCallsPerTurnExplicit;skipStartupContext;bareMode;safeMode;warnings;ignoredExtensionRules=[];allowedHttpHookUrls;allowPrivateNetworkHooks;onPersistPermissionRuleCallback;initialized=false;initializationPromise;initializationSucceeded=false;initializationSettled=false;shutdownRequested=false;resourceShutdownAfterInitializationScheduled=false;resourceShutdownPromise;proxyDispatcherReady;storage;runtimeStatusWrite=Promise.resolve();sessionRegistryWrite=Promise.resolve();fileExclusions;truncateToolOutputThreshold;truncateToolOutputThresholdExplicit;truncateToolOutputLines;toolOutputBatchBudget;shellDefaultTimeoutMs;shellHeartbeatIntervalMs;eventEmitter;channel;jsonFd;jsonFile;jsonSchema;inputFile;plansDir;plansDirectoryConfigured;defaultFileEncoding;enableManagedAutoMemory;enableManagedAutoDream;enableTeamMemory;enableTeamMemorySync;enableStructuredMemoryRecall;teamMemoryShareabilityChecked=new Set;enableAutoSkill;autoSkillConfirm;memoryAgentTimeoutMinutes;memoryAgentMaxTurns;fastModel;advisorModel;advisorMaxUses;advisorUsage={calls:0};webSearchSettings;webSearchNoticeEmitted=false;webSearchSessionUsage={calls:0};visionModel;compactionModel;reasoningSnapshot;latestReasoningSnapshot;imageModel;visionBridgeTimeoutMs;modelFallbacks;disableAllHooks;stopHookBlockingCap;systemHooks;userHooks;projectHooks;hooks;hookSystem;messageBus;messageBusListeners=new Set;memoryManager;modelChangeListeners=new Set;approvalModeChangeListeners=new Set;ownsModelEnvSlot=false;settingsWatcher;constructor(params){this.executionEnvironment=params.executionEnvironment;if(params.executionEnvironment){this.executionEnvironments=new Set([Promise.resolve(params.executionEnvironment)])}this.agentExecutionBackend=params.agentExecutionBackend;const executionFactory=params.executionEnvironmentFactory;this.executionEnvironmentFactory=executionFactory?(config3,signal)=>executionFactory(config3,AbortSignal.any([signal,this.executionShutdown.signal])):void 0;this.sessionRuntimeBaseDir=Storage.getRuntimeBaseDir();this.shellExecutionSandbox=admitShellSandbox(params,this.sessionRuntimeBaseDir,Storage.getGlobalQwenDir());this.provisionalWorkspace=params.provisionalWorkspace===true;this.sessionId=params.sessionId??randomUUID29();if(!sessionEnvClaimed&&process8.env){process8.env["QWEN_CODE_SESSION_ID"]=this.sessionId;sessionEnvClaimed=true}this.sessionData=params.sessionData;this.sessionRestoreProjectionSource=params.sessionRestoreProjectionSource;this.sessionExecutionEngine=params.sessionExecutionEngine;this.managedRuntimeEnvironmentFactory=params.sessionExecutionEngine==="managed"?params.managedRuntimeEnvironment:void 0;this.onManagedEngineQuarantine=params.sessionExecutionEngine==="managed"?params.onManagedEngineQuarantine:void 0;this.setSessionRestoreProjection(params.sessionRestoreProjection);if(sessionIdContext.getStore()===void 0){setDebugLogSession(this)}this.debugLogger=createDebugLogger();this.embeddingModel=params.embeddingModel??DEFAULT_QWEN_EMBEDDING_MODEL;this.fileSystemService=new StandardFileSystemService;this.sandbox=params.sandbox;this.targetDir=path88.resolve(params.targetDir);this.plansDirectoryConfigured=Boolean(params.plansDirectory?.trim());this.plansDir=Storage.getPlansDir(this.targetDir,params.plansDirectory);this.explicitIncludeDirectories=Array.from(new Set(params.includeDirectories??[]));this.workspaceContext=new WorkspaceContext(this.targetDir,this.explicitIncludeDirectories);this.debugMode=params.debugMode;this.inputFormat=params.inputFormat??"text";const normalizedOutputFormat=normalizeConfigOutputFormat(params.outputFormat??params.output?.format);this.outputFormat=normalizedOutputFormat??"text";this.includePartialMessages=params.includePartialMessages??false;this.question=params.question;this.systemPrompt=params.systemPrompt;this.appendSystemPrompt=params.appendSystemPrompt;this.outputStyle=params.outputStyle;this.coreTools=params.coreTools;this.allowedTools=params.allowedTools;this.excludeTools=params.excludeTools;this.disabledSlashCommands=Object.freeze([...params.disabledSlashCommands??[]]);this.disabledSkillNamesProvider=params.disabledSkillNamesProvider??null;this.enabledSkillNamesProvider=params.enabledSkillNamesProvider??null;this.skillSettingsListsProvider=params.skillSettingsListsProvider??null;this.terminalImageRenderSupportProvider=params.terminalImageRenderSupportProvider??null;this.disabledSkillLevels=new Set(params.disabledSkillLevels??[]);this.customSkillDirs=Object.freeze([...params.customSkillDirs??[]]);this.disabledTools=new Set(params.disabledTools??[]);this.visibleTools=new Set((params.visibleTools??[]).filter(name2=>typeof name2==="string"));this.eagerTools=params.eagerTools===void 0?void 0:Object.freeze(params.eagerTools.filter(name2=>typeof name2==="string"));this.toolSearchThreshold=params.toolSearchThreshold??DEFAULT_TOOL_SEARCH_THRESHOLD;this.permissionsAllow=params.permissions?.allow||[];this.permissionsAsk=params.permissions?.ask||[];this.permissionsDeny=params.permissions?.deny||[];this.permissionsAutoMode=params.permissions?.autoMode??{};this.toolInvocationGuard=params.toolInvocationGuard;this.workflowAncestorTrustProvider=params.workflowAncestorTrustProvider;this.toolDiscoveryCommand=params.toolDiscoveryCommand;this.toolCallCommand=params.toolCallCommand;this.mcpServerCommand=params.mcpServerCommand;this.mcpServers=params.mcpServers;this.topTierMcpServers=params.topTierMcpServers;this.bundledGeneratedUi=Object.freeze({...params.bundledGeneratedUi,enabled:params.bundledGeneratedUi?.enabled===true});this.lspEnabled=params.lsp?.enabled??false;this.lspClient=params.lspClient;this.allowedMcpServers=params.allowedMcpServers;this.cliAllowedMcpServerNames=params.cliAllowedMcpServerNames;this.excludedMcpServers=params.excludedMcpServers;this.pendingMcpServers=params.pendingMcpServers;const envTimeout=process8.env["QWEN_CODE_MCP_TOOL_IDLE_TIMEOUT_MS"];const parsedEnv=envTimeout!==void 0?Number(envTimeout):NaN;this.mcpToolIdleTimeoutMs=params.mcpToolIdleTimeoutMs??(Number.isFinite(parsedEnv)&&parsedEnv>=0?parsedEnv:3e5);this.sessionSubagents=params.sessionSubagents??[];this.sdkMode=params.sdkMode??false;this.userMemory=params.userMemory??"";this.memoryFileCount=params.memoryFileCount??params.geminiMdFileCount??0;this.contextRuleExcludes=params.contextRuleExcludes??[];this.approvalMode=params.approvalMode??"auto";this.accessibility=params.accessibility??{};this.showResponseTokensPerSecond=params.showResponseTokensPerSecond??false;this.telemetrySettings={enabled:params.telemetry?.enabled??false,target:params.telemetry?.target??DEFAULT_TELEMETRY_TARGET,otlpEndpoint:params.telemetry?.otlpEndpoint,otlpProtocol:params.telemetry?.otlpProtocol,otlpTracesEndpoint:params.telemetry?.otlpTracesEndpoint,otlpLogsEndpoint:params.telemetry?.otlpLogsEndpoint,otlpMetricsEndpoint:params.telemetry?.otlpMetricsEndpoint,logPrompts:params.telemetry?.logPrompts??true,userId:params.telemetry?.userId?.trim()||void 0,includeSensitiveSpanAttributes:params.telemetry?.includeSensitiveSpanAttributes??false,sensitiveSpanAttributeMaxLength:resolveSensitiveSpanAttributeMaxLength(params.telemetry?.sensitiveSpanAttributeMaxLength),outfile:params.telemetry?.outfile,resourceAttributes:params.telemetry?.resourceAttributes,metrics:params.telemetry?.metrics,resourceAttributeWarnings:params.telemetry?.resourceAttributeWarnings};this.telemetryInitializationDeferred=params.deferTelemetryInitialization??false;this.outboundCorrelationSettings={propagateTraceContext:params.outboundCorrelation?.propagateTraceContext??false,allowDynamicHeaderValues:params.outboundCorrelation?.allowDynamicHeaderValues===true};this.gitCoAuthor={...normalizeGitCoAuthor(params.gitCoAuthor),name:"Qwen-Coder",email:"qwen-coder@alibabacloud.com"};this.usageStatisticsEnabled=params.usageStatisticsEnabled??true;this.fileReadCacheDisabled=params.sessionExecutionEngine==="managed"||(params.fileReadCacheDisabled??false);this.outputLanguageFilePath=params.outputLanguageFilePath;this.fileFiltering={respectGitIgnore:params.fileFiltering?.respectGitIgnore??true,respectQwenIgnore:params.fileFiltering?.respectQwenIgnore??true,customIgnoreFiles:params.fileFiltering?.customIgnoreFiles??[...DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES],enableRecursiveFileSearch:params.fileFiltering?.enableRecursiveFileSearch??true,enableFuzzySearch:params.fileFiltering?.enableFuzzySearch??true};this.fileCheckpointingEnabled=params.fileCheckpointingEnabled??(!params.sdkMode&&(params.interactive??false));this.proxy=params.proxy;this.cwd=params.cwd??process8.cwd();this.fileDiscoveryService=params.fileDiscoveryService??null;this.bugCommand=params.bugCommand;this.maxSessionTurns=validateMaxSessionTurns(params.maxSessionTurns);this.goalTokenBudgetGrant=normalizeGoalTokenBudget(params.goalTokenBudget);if(params.goalTokenBudget!==void 0&&!isValidGoalTokenBudget(params.goalTokenBudget)){this.debugLogger.warn(`Ignoring invalid goalTokenBudget ${String(params.goalTokenBudget)}: expected a non-negative integer or -1 (no budget); using the default of ${GOAL_DEFAULT_TOKEN_BUDGET}.`)}this.goalTurnBudgetGrant=normalizeGoalMaxTurns(params.goalMaxTurns);if(params.goalMaxTurns!==void 0&&!isValidGoalMaxTurns(params.goalMaxTurns)){this.debugLogger.warn(`Ignoring invalid goalMaxTurns ${String(params.goalMaxTurns)}: expected an integer between 1 and ${GOAL_MAX_TURNS_CAP}, or -1 for no turn ceiling; Goals will run with no turn ceiling.`)}this.goalActiveTimeBudgetGrantMs=normalizeGoalMaxActiveMinutes(params.goalMaxActiveMinutes);if(params.goalMaxActiveMinutes!==void 0&&!isValidGoalMaxActiveMinutes(params.goalMaxActiveMinutes)){this.debugLogger.warn(`Ignoring invalid goalMaxActiveMinutes ${String(params.goalMaxActiveMinutes)}: expected an integer between 1 and ${GOAL_MAX_ACTIVE_MINUTES_CAP}, or -1 for no time ceiling; Goals will run with no time ceiling.`)}this.maxSubagentDepth=normalizeMaxSubagentDepth(params.maxSubagentDepth);this.maxWallTimeSeconds=params.maxWallTimeSeconds??-1;this.maxToolCalls=params.maxToolCalls??-1;const clearContextOnIdle=params.clearContextOnIdle;const toolResultsThresholdMinutes=clearContextOnIdle?.toolResultsThresholdMinutes??60;this.clearContextOnIdle={toolResultsThresholdMinutes,toolResultsNumToKeep:clearContextOnIdle?.toolResultsNumToKeep??5,toolResultsTotalCharsThreshold:clearContextOnIdle?.toolResultsTotalCharsThreshold??((clearContextOnIdle?.toolResultsThresholdMinutes??0)<0?-1:DEFAULT_TOOL_RESULTS_TOTAL_CHARS_THRESHOLD)};this.sessionTokenLimit=params.sessionTokenLimit??-1;this.experimentalZedIntegration=params.experimentalZedIntegration??false;this.restoreAskUserQuestion=params.restoreAskUserQuestion===true;this.preserveRestorableAskUserQuestion=this.restoreAskUserQuestion;this.sessionWriterLeaseEnabled=this.experimentalZedIntegration===true&&params.sessionWriterLeaseEnabled===true;this.cronEnabled=params.cronEnabled??true;this.cronRecurringMaxAgeDays=resolveCronRecurringMaxAgeDays(params.cronRecurringMaxAgeDays);this.lsToolEnabled=params.lsToolEnabled??false;this.todoWriteEnabled=params.todoWriteEnabled??false;this.agentTeamEnabled=params.agentTeamEnabled??false;this.unifiedAgentLoopEnabled=params.unifiedAgentLoopEnabled??false;this.agentCollaborationEnabled=params.agentCollaborationEnabled??false;this.artifactEnabled=params.artifactEnabled??true;this.artifactAutoOpen=params.artifactAutoOpen??true;this.artifactPublisher=params.artifactPublisher??"local";this.artifactHost=params.artifactHost;this.artifactOss=params.artifactOss;this.omniEnabled=params.omniEnabled??false;this.omniMaxUploadFileBytes=params.omniMaxUploadFileBytes;this.omniMaxEstimatedTokens=params.omniMaxEstimatedTokens;this.omniMaxDurationSeconds=params.omniMaxDurationSeconds;this.omniUrlDownloadMaxFileBytes=params.omniUrlDownloadMaxFileBytes;this.omniUploadUrlTtlHours=params.omniUploadUrlTtlHours;this.omniUploadBaseUrl=params.omniUploadBaseUrl;this.omniUploadApiKeyEnv=params.omniUploadApiKeyEnv;this.omniUploadModel=params.omniUploadModel;this.omniPolicyTools=params.omniPolicyTools;this.omniFixedPolicies=params.omniFixedPolicies;this.omniTransportGuardPolicies=params.omniTransportGuardPolicies;this.omniProcessingLimits=params.omniProcessingLimits;this.omniQuarantineRetentionDays=params.omniQuarantineRetentionDays;this.omniQuarantineMaxBytes=params.omniQuarantineMaxBytes;this.omniStorageRetentionDays=params.omniStorageRetentionDays;this.omniStorageMaxTotalBytes=params.omniStorageMaxTotalBytes;this.omniMemory=params.omniMemory;this.workflowsEnabled=params.workflowsEnabled;this.workflowKeywordTriggerEnabled=params.workflowKeywordTriggerEnabled??true;this.sessionWorkflowEnabled=params.sessionWorkflowEnabled??false;this.modelProposedGoals=params.modelProposedGoals??"alwaysAsk";this.skipWorkflowUsageWarning=params.skipWorkflowUsageWarning??false;this.workflowSizeGuideline=isWorkflowSizeGuideline(params.workflowSizeGuideline)?params.workflowSizeGuideline:void 0;this.workflowNameOnly=params.workflowNameOnly===true||process8.env["QWEN_CODE_WORKFLOW_NAME_ONLY"]==="1";this.workflowRunRegistry.setNameOnly(this.workflowNameOnly);this.emitToolUseSummaries=params.emitToolUseSummaries??true;this.listExtensions=params.listExtensions??false;this.overrideExtensions=params.overrideExtensions;this.noBrowser=params.noBrowser??false;this.folderTrustFeature=params.folderTrustFeature??false;this.folderTrust=params.folderTrust??false;this.ideMode=params.ideMode??false;this.modelProvidersConfig=params.modelProvidersConfig;this.providerProtocolConfig=params.providerProtocolConfig;this.cliVersion=params.cliVersion;this.chatRecordingEnabled=params.chatRecording??true;this.loadMemoryFromIncludeDirectories=params.loadMemoryFromIncludeDirectories??false;this.importFormat=params.importFormat??"tree";this.chatCompression=params.chatCompression;this.autoCompactThreshold=params.autoCompactThreshold;this.interactive=params.interactive??false;this.trustedFolder=params.trustedFolder;this.skipLoopDetection=params.skipLoopDetection??false;this.loopProtection=isLoopProtectionMode(params.loopProtection)?params.loopProtection:DEFAULT_LOOP_PROTECTION;this.maxToolCallsPerTurn=validateMaxToolCallsPerTurn(params.maxToolCallsPerTurn);this.maxToolCallsPerTurnExplicit=params.maxToolCallsPerTurn!==void 0;this.skipStartupContext=params.skipStartupContext??false;this.bareMode=params.bareMode??false;this.safeMode=params.safeMode??isSafeModeEnv();this.toolMode=params.codeModeOnly&&!this.bareMode&&!this.safeMode?ToolMode.CodeModeOnly:ToolMode.Direct;this.freeform=this.toolMode===ToolMode.CodeModeOnly&&params.freeform===true;if(this.safeMode){this.debugLogger.info("Safe mode active: hooks, extensions, skills, MCP servers, context files, rules disabled")}this.warnings=params.warnings??[];this.addLegacyPlanLocationWarning();this.allowedHttpHookUrls=params.allowedHttpHookUrls??[];this.allowPrivateNetworkHooks=params.allowPrivateNetworkHooks??false;this.onPersistPermissionRuleCallback=params.onPersistPermissionRule;this.useRipgrep=params.useRipgrep??true;this.useBuiltinRipgrep=params.useBuiltinRipgrep??true;this.shouldUseNodePtyShell=params.shouldUseNodePtyShell??shouldDefaultToNodePty();this.preventSystemSleep=params.preventSystemSleep??true;this.skipNextSpeakerCheck=params.skipNextSpeakerCheck??true;this.shellExecutionConfig={terminalWidth:params.shellExecutionConfig?.terminalWidth??80,terminalHeight:params.shellExecutionConfig?.terminalHeight??24,showColor:params.shellExecutionConfig?.showColor??false,pager:params.shellExecutionConfig?.pager,maxBufferedOutputBytes:params.shellExecutionConfig?.maxBufferedOutputBytes};this.truncateToolOutputThreshold=params.truncateToolOutputThreshold??DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD;this.truncateToolOutputThresholdExplicit=params.truncateToolOutputThreshold!=null;this.truncateToolOutputLines=params.truncateToolOutputLines??DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES;this.toolOutputBatchBudget=params.toolOutputBatchBudget??DEFAULT_TOOL_OUTPUT_BATCH_BUDGET;this.shellDefaultTimeoutMs=params.shellDefaultTimeoutMs!==void 0&&Number.isInteger(params.shellDefaultTimeoutMs)&&params.shellDefaultTimeoutMs>=0&&params.shellDefaultTimeoutMs<=2147483647?params.shellDefaultTimeoutMs:void 0;this.shellHeartbeatIntervalMs=params.shellHeartbeatIntervalMs!==void 0&&Number.isInteger(params.shellHeartbeatIntervalMs)&&params.shellHeartbeatIntervalMs>=0&&params.shellHeartbeatIntervalMs<=2147483647?params.shellHeartbeatIntervalMs:void 0;this.channel=params.channel;this.jsonFd=params.jsonFd;this.jsonFile=params.jsonFile;this.jsonSchema=params.jsonSchema;this.inputFile=params.inputFile;this.defaultFileEncoding=params.defaultFileEncoding;this.storage=new Storage(this.targetDir,this.sessionRuntimeBaseDir);if(!projectDirEnvClaimed&&process8.env){process8.env["QWEN_CODE_PROJECT_DIR"]=this.storage.getProjectDir();projectDirEnvClaimed=true}this.inputFormat=params.inputFormat??"text";this.fileExclusions=new FileExclusions(this);this.eventEmitter=params.eventEmitter;this.arenaAgentClient=ArenaAgentClient.create();this.agentsSettings=params.agents??{};this.backgroundTaskRegistry=new BackgroundTaskRegistry({...this.agentsSettings.maxParallelAgents!==void 0?{maxConcurrentBackgroundAgents:this.agentsSettings.maxParallelAgents}:{},...this.agentsSettings.maxParallelAgentsByModel!==void 0?{maxConcurrentBackgroundAgentsByModel:this.agentsSettings.maxParallelAgentsByModel}:{}});this.worktreeSettings=params.worktree??{};if(params.contextFileName){setMemoryFilename(params.contextFileName)}this.initialAuthType=params.authType??params.generationConfig?.authType;this.modelsConfig=new ModelsConfig({initialAuthType:this.initialAuthType,modelProvidersConfig:this.modelProvidersConfig,providerProtocolConfig:this.providerProtocolConfig,generationConfig:{model:params.model,...params.generationConfig||{},baseUrl:params.generationConfig?.baseUrl},generationConfigSources:params.generationConfigSources,initialRegistryBaseUrl:params.initialModelRegistryBaseUrl,onModelChange:this.handleModelChange.bind(this)});this.initialResolvedAuthType=this.modelsConfig.getCurrentAuthType();if(!modelEnvClaimed&&process8.env){modelEnvClaimed=true;this.ownsModelEnvSlot=true}this.publishModelEnv();if(this.telemetrySettings.enabled&&!this.telemetryInitializationDeferred){void Promise.resolve(initializeTelemetry(this)).catch(error3=>{this.debugLogger.error("Failed to initialize telemetry:",error3)})}const proxyUrl=this.getProxy();if(proxyUrl&&(params.installProxyDispatcher??true)){this.proxyDispatcherReady=loadUndici().then(({EnvHttpProxyAgent,setGlobalDispatcher})=>{setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}));setResolvedProxyUrlForRuntimeFetch(proxyUrl)}).catch(error3=>{this.debugLogger.error("Failed to install proxy dispatcher:",redactProxyError(error3));throw error3});this.proxyDispatcherReady.catch(()=>{})}this.llmClient=new LlmClient(this);this.chatRecordingService=this.chatRecordingEnabled?this.createChatRecordingService():void 0;if(!this.sessionRestoreProjectionSource||this.sessionRestoreRuntime||!this.sessionWriterLeaseEnabled){this.initializeGoalRuntime(this.sessionRestoreRuntime?.goalRecords??this.sessionData?.conversation.messages,this.sessionRestoreRuntime)}this.extensionManager=new ExtensionManager({workspaceDir:this.targetDir,enabledExtensionOverrides:this.overrideExtensions,isWorkspaceTrusted:this.isTrustedFolder(),locale:params.locale,usageStatisticsEnabled:this.usageStatisticsEnabled,proxy:this.proxy});this.enableManagedAutoMemory=params.enableManagedAutoMemory??true;this.enableManagedAutoDream=params.enableManagedAutoDream??true;this.enableTeamMemory=params.enableTeamMemory??false;this.enableTeamMemorySync=params.enableTeamMemorySync??false;this.enableStructuredMemoryRecall=params.enableStructuredMemoryRecall??false;this.enableAutoSkill=params.enableAutoSkill??false;this.autoSkillConfirm=params.autoSkillConfirm??true;this.memoryAgentTimeoutMinutes=params.memoryAgentTimeoutMinutes!==void 0&&params.memoryAgentTimeoutMinutes>=0?params.memoryAgentTimeoutMinutes:void 0;this.memoryAgentMaxTurns=params.memoryAgentMaxTurns!==void 0&&Number.isInteger(params.memoryAgentMaxTurns)&&params.memoryAgentMaxTurns>=0?params.memoryAgentMaxTurns:void 0;this.fastModel=params.fastModel||void 0;this.advisorModel=normalizeAdvisorModel(params.advisorModel);this.advisorMaxUses=isValidAdvisorMaxUses(params.advisorMaxUses)?params.advisorMaxUses:0;this.webSearchSettings=params.webSearch;this.visionModel=params.visionModel||void 0;this.compactionModel=params.compactionModel||void 0;this.imageModel=params.imageModel||void 0;this.visionBridgeTimeoutMs=params.visionBridgeTimeoutMs!==void 0&&Number.isInteger(params.visionBridgeTimeoutMs)&&params.visionBridgeTimeoutMs>0&&params.visionBridgeTimeoutMs<=2147483647?params.visionBridgeTimeoutMs:void 0;this.modelFallbacks=normalizeModelFallbacks(params.modelFallbacks);this.disableAllHooks=params.disableAllHooks??false;this.stopHookBlockingCap=resolveStopHookBlockingCap(params.stopHookBlockingCap);this.systemHooks=params.systemHooks;this.userHooks=params.userHooks;this.projectHooks=params.projectHooks;this.hooks=params.hooks;this.settingsWatcher=params.settingsWatcher;this.memoryManager=new MemoryManager;if(params.workflowMode!==void 0){this.stageInitialWorkflowMode(params.workflowMode)}}async initialize(options2){if(this.executionEnvironment){options2={...options2,skipHooks:true,skipMcpDiscovery:true,skipSkillManager:true,skipFileCheckpointing:true}}if(this.sessionExecutionEngine==="managed"){options2={...options2,skipMcpDiscovery:true}}if(isDerivedConfig(this)){throw new Error("Derived Configs cannot be initialized")}if(this.initialized){if(!this.initializationSettled){options2?.signal?.throwIfAborted();this.debugLogger.debug("Config.initialize() called while initialization is in flight; joining the existing run");await this.initializationPromise;return}await this.initializationPromise;throw Error("Config was already initialized")}if(this.shutdownRequested){throw Error("Config is shutting down")}options2?.signal?.throwIfAborted();this.initialized=true;const initialization=this.initializeOnce(options2);this.initializationPromise=initialization;try{await initialization;this.initializationSucceeded=true}finally{this.initializationSettled=true}}async activateProvisionalWorkspace(){if(!this.provisionalWorkspace||this.provisionalWorkspaceActivated){return}if(this.provisionalWorkspaceActivation){return this.provisionalWorkspaceActivation}const activation=(async()=>{this.getFileService();await this.llmClient.initialize();await this.toolRegistry.warmAll({strict:true});await this.initializeOmniPolicies();logStartSession(this,new StartSessionEvent(this));this.provisionalWorkspaceActivated=true})();this.provisionalWorkspaceActivation=activation;return activation}async initializeOmniPolicies(){if(this.isOmniEnabled()){const{normalizeOmniProcessingConfig}=await import("./config-QVHNAELH.js");this.omniProcessingConfig=normalizeOmniProcessingConfig({fixedPolicies:this.omniFixedPolicies,transportGuardPolicies:this.omniTransportGuardPolicies,limits:this.omniProcessingLimits,policyTools:this.omniPolicyTools,maxUploadFileBytes:this.omniMaxUploadFileBytes,maxEstimatedTokens:this.omniMaxEstimatedTokens,urlTtlHours:this.omniUploadUrlTtlHours},this.toolRegistry);await this.ensureOmniMemoryConfig()}}isProvisionalWorkspace(){return this.provisionalWorkspace}async initializeOnce(options2){try{if(this.shellExecutionSandbox)this.shellExecutionSandbox=await probeShellSandbox(this.shellExecutionSandbox,options2?.signal);const activation=this.activateChatRecording();this.sessionWriterActivationPromise=activation;try{await activation}finally{if(this.sessionWriterActivationPromise===activation){this.sessionWriterActivationPromise=void 0}}options2?.signal?.throwIfAborted();this.workflowModeContext.restore(this.isWorkflowModeSupported()?this.chatRecordingService?.getSessionWorkflowMode():void 0);await this.bindSessionExecutionEngine();registerSessionProjectDir(this.sessionId,this.storage.getProjectDir());this.sessionProjectDirRegistered=true;await this.initializeInternal(options2);this.workflowModeReady=true;if(this.initialWorkflowMode!==void 0){const enabled=this.initialWorkflowMode;this.initialWorkflowMode=void 0;await this.setWorkflowMode(enabled)}this.refreshWorkflowMode()}catch(error3){this.clearSessionRestoreProjection();if(this.sessionProjectDirRegistered){unregisterSessionProjectDir(this.sessionId);this.sessionProjectDirRegistered=false}try{await this.closeSessionWriter()}catch(closeError){if(options2?.signal?.aborted&&containsErrorByIdentity(error3,options2.signal.reason)){this.debugLogger.warn("Chat recording close failed after initialization was aborted:",closeError);options2.signal.throwIfAborted()}if(containsErrorByIdentity(error3,closeError)){throw error3}throw new SessionWriterUnavailableError({cause:new AggregateError([error3,closeError],"Chat recording close failed during failed initialization")})}throw error3}}async bindSessionExecutionEngine(){const engine=this.sessionExecutionEngine;if(engine===void 0)return;if(this.sessionRestoreProjectionSource||this.sessionData){assertSessionExecutionEngine(this.pendingSessionRestoreProjection?.executionEngine,this.sessionId,engine);return}if(this.managedSession)return;await this.chatRecordingService?.recordExecutionEngine(engine)}async initializeInternal(options2){this.debugLogger.info("Config initialization started");await this.proxyDispatcherReady;void refreshModelCatalog();options2?.signal?.throwIfAborted();if(this.isOmniEnabled()){const{normalizeDedicatedOmniUploadConfig}=await import("./upload-config-OWLL4SRQ.js");this.omniUploadConfig=normalizeDedicatedOmniUploadConfig({baseUrl:this.omniUploadBaseUrl,apiKeyEnv:this.omniUploadApiKeyEnv,model:this.omniUploadModel});const{assertOmniRuntimeDependencies}=await import("./ffmpeg-3AJSGZKK.js");await assertOmniRuntimeDependencies()}if(options2?.skipFileCheckpointing===true||this.shellExecutionSandbox){this.fileCheckpointingEnabled=false;this.fileHistoryService=void 0}if(!this.provisionalWorkspace){this.getFileService()}this.promptRegistry=new PromptRegistry;this.resourceRegistry=new ResourceRegistry;this.extensionManager.setConfig(this);const explicitExtensionNames=this.isSafeMode()?[]:(this.overrideExtensions??[]).filter(n=>n.trim()!==""&&n.toLowerCase()!=="none");recordStartupEvent("config_initialize_extensions_initial_start");if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.isSafeMode()&&!this.getBareMode()){await this.extensionManager.refreshCache()}else if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.isSafeMode()&&explicitExtensionNames.length>0){await this.extensionManager.refreshCache({names:explicitExtensionNames})}recordStartupEvent("config_initialize_extensions_initial_end");options2?.signal?.throwIfAborted();this.debugLogger.debug("Extension manager initialized");recordStartupEvent("config_initialize_hooks_start");if(!this.shellExecutionSandbox&&(options2?.managedHookDispatcher||!options2?.skipHooks&&!this.getDisableAllHooks())){this.hookSystem=new HookSystem(this,options2?.managedHookDispatcher);await this.hookSystem.initialize();this.debugLogger.debug("Hook system initialized");this.messageBus=new MessageBus;this.messageBus.subscribe("hook-execution-request",async request=>{try{const hookSystem=this.hookSystem;if(!hookSystem){this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:new Error("Hook system not initialized")});return}if(request.signal?.aborted){this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:new Error("Hook execution cancelled (aborted)")});return}assertHookExecutionOwner(request.owner,hookSystem.runtimeId,this.getSessionId());await runWithHookExecutionOwner(request.owner,async()=>{let result;let stopHookCount;const input=request.input||{};const signal=request.signal;switch(request.eventName){case"UserPromptSubmit":result=await hookSystem.fireUserPromptSubmitEvent(input["prompt"]||"",signal,typeof input["submitted_prompt"]==="string"&&input["submitted_prompt"].trim().length>0?input["submitted_prompt"]:void 0);break;case"UserPromptExpansion":result=await hookSystem.fireUserPromptExpansionEvent(input["command_name"]||"",input["command_args"]||"",input["prompt"]||"",signal);break;case"Stop":{const contextUsageData=buildContextUsage(input["context_limit"],input["input_tokens"]??0);const stopResult=await hookSystem.fireStopEvent(input["stop_hook_active"]||false,input["last_assistant_message"]||"",contextUsageData,signal);result=stopResult.finalOutput?createHookOutput("Stop",stopResult.finalOutput):void 0;stopHookCount=stopResult.allOutputs.length;break}case"MessageDisplay":{const messageDisplayResult=await hookSystem.fireMessageDisplayEvent(input["message_id"]||"",input["displayed_text"]||"",input["is_final"]||false,signal);result=messageDisplayResult.finalOutput?createHookOutput("MessageDisplay",messageDisplayResult.finalOutput):void 0;break}case"PreToolUse":{result=await hookSystem.firePreToolUseEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_use_id"]||"",input["permission_mode"]??"default",signal,input["tool_call_id"]||void 0);break}case"PostToolUse":result=await hookSystem.firePostToolUseEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_response"]||{},input["tool_use_id"]||"",input["permission_mode"]||"default",signal,input["tool_call_id"]||void 0,typeof input["duration_ms"]==="number"?input["duration_ms"]:void 0);break;case"PostToolUseFailure":result=await hookSystem.firePostToolUseFailureEvent(input["tool_use_id"]||"",input["tool_name"]||"",input["tool_input"]||{},input["error"]||"",input["is_interrupt"],input["permission_mode"]||"default",signal,input["tool_call_id"]||void 0,typeof input["duration_ms"]==="number"?input["duration_ms"]:void 0);break;case"PostToolBatch":result=await hookSystem.firePostToolBatchEvent(input["tool_calls"]||[],input["permission_mode"]||"default",signal);break;case"Notification":result=await hookSystem.fireNotificationEvent(input["message"]||"",input["notification_type"]||"permission_prompt",input["title"]||void 0,signal);break;case"PermissionRequest":result=await hookSystem.firePermissionRequestEvent(input["tool_name"]||"",input["tool_input"]||{},input["permission_mode"]||"default",input["permission_suggestions"]||void 0,signal);break;case"PermissionDenied":result=await hookSystem.firePermissionDeniedEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_use_id"]||"",input["reason"]||"classifier_blocked",signal,input["tool_call_id"]||void 0);break;case"SubagentStart":result=await hookSystem.fireSubagentStartEvent(input["agent_id"]||"",input["agent_type"]||"",input["permission_mode"]||"default",signal);break;case"SubagentStop":result=await hookSystem.fireSubagentStopEvent(input["agent_id"]||"",input["agent_type"]||"",input["agent_transcript_path"]||"",input["last_assistant_message"]||"",input["stop_hook_active"]||false,input["permission_mode"]||"default",signal);break;case"SessionStart":result=await hookSystem.fireSessionStartEvent(input["source"],input["model"]||"",input["permission_mode"]||void 0,input["agent_type"],signal);break;case"SessionEnd":result=await hookSystem.fireSessionEndEvent(input["reason"],signal);break;case"SessionDelete":result=await hookSystem.fireSessionDeleteEvent(input["deleted_session_id"]||"",signal);break;case"PreCompact":result=await hookSystem.firePreCompactEvent(input["trigger"],input["custom_instructions"]||"",signal);break;case"PostCompact":result=await hookSystem.firePostCompactEvent(input["trigger"],input["compact_summary"]||"",signal);break;case"InstructionsLoaded":result=await hookSystem.fireInstructionsLoadedEvent(input["file_path"]||"",input["memory_type"],input["load_reason"],{triggerFilePath:input["trigger_file_path"],parentFilePath:input["parent_file_path"]},signal);break;case"StopFailure":result=(await hookSystem.fireStopFailureEvent(input["error"],input["error_details"],input["last_assistant_message"],signal)).finalOutput;break;case"TodoCreated":result=(await hookSystem.fireTodoCreatedEvent(input["todo_id"]||"",input["todo_content"]||"",input["todo_status"],input["all_todos"]||[],input["phase"],signal)).finalOutput;break;case"TodoCompleted":result=(await hookSystem.fireTodoCompletedEvent(input["todo_id"]||"",input["todo_content"]||"",input["previous_status"],input["all_todos"]||[],input["phase"],signal)).finalOutput;break;default:this.debugLogger.warn(`Unknown hook event: ${request.eventName}`);result=void 0}this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:true,output:result,stopHookCount})})}catch(error3){this.debugLogger.warn(`Hook execution failed: ${error3}`);this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:error3 instanceof Error?error3:new Error(String(error3))})}});this.announceMessageBus(this.messageBus);this.debugLogger.debug("MessageBus initialized with hook subscription")}else{this.debugLogger.debug("Hook system disabled, skipping initialization")}recordStartupEvent("config_initialize_hooks_end");options2?.signal?.throwIfAborted();this.subagentManager=new SubagentManager(this);this.initializeBundledGeneratedUi(options2);recordStartupEvent("config_initialize_skills_start");if(!options2?.skipSkillManager){if(!this.provisionalWorkspace&&this.getAutoSkillEnabled()&&this.isTrustedFolder()){try{const curatorResult=await maybeRunAutoSkillCurator(this.getProjectRoot());if(curatorResult.status==="ran"){this.debugLogger.debug(`Auto-skill curator checked ${curatorResult.result.checked} skill(s) and archived ${curatorResult.result.archived.length}.`)}}catch(error3){this.debugLogger.warn(`Auto-skill curator skipped: ${error3 instanceof Error?error3.message:String(error3)}`)}}this.skillManager=new SkillManager(this);if(this.shellExecutionSandbox||this.getBareMode()||this.isSafeMode()){await this.skillManager.refreshCache()}else{await this.skillManager.startWatching()}this.debugLogger.debug("Skill manager initialized");if(this.skillSettingsListsProvider){try{const lists=this.skillSettingsListsProvider();const skills=await this.skillManager.listSkills();const extensionIdByName=new Map(this.getExtensions().map(extension=>[extension.name,extension.id]));const defaultOffNames=new Set;for(const skill of skills){const extensionId=skill.extensionName?extensionIdByName.get(skill.extensionName):void 0;if(skill.level!=="extension"||!extensionId)continue;const state=this.extensionManager.getExtensionSkillState(extensionId,authoredSkillName(skill));if(state.defaultEnabled===false&&!state.workspaceEnabled){defaultOffNames.add(skill.name.trim().toLowerCase())}}this.warnings.push(...bareEnabledGrantWarnings(lists,skills,defaultOffNames),...bareDisablementBlocksQualifiedGrantWarnings(lists,this.getDisabledSkillNames(),skills))}catch(error3){this.debugLogger.warn(`Skill settings migration warning skipped: ${getErrorMessage(error3)}`)}}}else{this.skillManager=null;this.debugLogger.debug("Skill manager skipped")}recordStartupEvent("config_initialize_skills_end");options2?.signal?.throwIfAborted();this.memoryPressureConfig=loadMemoryPressureConfig();this.memoryPressureMonitor=new MemoryPressureMonitor(this,this.memoryPressureConfig);this.permissionManager=new PermissionManager(this);this.permissionManager.initialize();this.debugLogger.debug("Permission manager initialized");if(this.sessionSubagents.length>0){this.subagentManager.loadSessionSubagents(this.sessionSubagents)}recordStartupEvent("config_initialize_extensions_final_start");if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.getBareMode()&&!this.isSafeMode()){await this.extensionManager.refreshCache()}recordStartupEvent("config_initialize_extensions_final_end");options2?.signal?.throwIfAborted();if(!this.provisionalWorkspace){recordStartupEvent("config_initialize_hierarchical_memory_start");await this.refreshHierarchicalMemory("session_start",options2?.signal);recordStartupEvent("config_initialize_hierarchical_memory_end");this.debugLogger.debug("Hierarchical memory loaded")}options2?.signal?.throwIfAborted();const legacyBlockingMcp=process8.env["QWEN_CODE_LEGACY_MCP_BLOCKING"]==="1";const skipInlineMcpDiscovery=this.getBareMode()||this.isSafeMode()||this.provisionalWorkspace||!legacyBlockingMcp||options2?.skipMcpDiscovery===true;recordStartupEvent("config_initialize_tool_registry_start");this.toolRegistry=await this.createToolRegistry(options2?.sendSdkMcpMessage,skipInlineMcpDiscovery?{skipDiscovery:true}:void 0);options2?.signal?.throwIfAborted();recordStartupEvent("config_initialize_tool_registry_end");recordStartupEvent("tool_registry_created",{toolCount:this.toolRegistry.getAllToolNames().length,mcpInline:!skipInlineMcpDiscovery});this.debugLogger.info(`Tool registry initialized with ${this.toolRegistry.getAllToolNames().length} tools`);if(!(options2?.skipLlmInitialization??options2?.skipGeminiInitialization)&&!this.provisionalWorkspace){await this.llmClient.initialize(void 0,options2?.signal);this.debugLogger.info("LLM client initialized")}else{this.debugLogger.info("LLM client initialization skipped")}this.modelsConfig.detectAndCaptureRuntimeModel();if(!this.provisionalWorkspace){recordStartupEvent("config_initialize_tool_warmup_start");await this.toolRegistry.warmAll({strict:options2?.lenientToolWarmup!==true});options2?.signal?.throwIfAborted();recordStartupEvent("config_initialize_tool_warmup_end")}if(!this.provisionalWorkspace){await this.initializeOmniPolicies();options2?.signal?.throwIfAborted()}const hasMcpServers=Object.keys(this.getMcpServers()??{}).length>0;if(!this.shellExecutionSandbox&&skipInlineMcpDiscovery&&(!(this.getBareMode()||this.isSafeMode())||hasMcpServers)&&!this.provisionalWorkspace&&!options2?.skipMcpDiscovery){this.startMcpDiscoveryInBackground()}if(!this.provisionalWorkspace){options2?.signal?.throwIfAborted();logStartSession(this,new StartSessionEvent(this))}this.debugLogger.info("Config initialization completed");if(!this.shellExecutionSandbox&&!this.getBareMode()&&this.sessionSourceType!=="agent-host"&&!this.provisionalWorkspace){void(async()=>{try{const root=findGitRoot(this.targetDir)??this.targetDir;const worktreesDir=path88.join(root,".qwen","worktrees");try{await fsPromises4.access(worktreesDir)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${worktreesDir} does not exist`);return}const removed=await cleanupStaleAgentWorktrees(root);if(removed>0){this.debugLogger.info(`Stale worktree sweep removed ${removed} ephemeral worktree(s) under ${root}`)}else{this.debugLogger.debug(`Stale worktree sweep ran under ${root}: nothing to remove`)}}catch(error3){this.debugLogger.warn(`Stale worktree sweep failed (non-fatal): ${error3}`)}})()}}async openManagedSessionLog(lease){const transcriptPath=this.getTranscriptPath();const sessionKey=localManagedSessionKey(this.storage.getProjectRoot(),this.sessionId);const resources=LocalManagedSessionResourceStore.create({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionKey});const create=isManagedSessionTranscriptSync(transcriptPath)?void 0:await this.publishManagedSessionRoot(resources);const open8=__name(()=>openManagedSession({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionId:this.sessionId,transcriptPath,sessionKey,cwd:this.getProjectRoot(),version:this.getCliVersion()||"unknown",workerId:this.sessionId,activationLeaseDurationMs:MANAGED_ACTIVATION_LEASE_MS,lease,resourceStore:resources,...create===void 0?{}:{create}}),"open");try{return await open8()}catch(error3){if(!(error3 instanceof ManagedSessionUncommittedTailError))throw error3;await LocalManagedSessionAuthority.recoverUncommittedTail({lease,sessionKey});return await open8()}}isLegacyTranscript(){const transcriptPath=this.getTranscriptPath();try{if(fs80.statSync(transcriptPath).size===0)return false}catch{return false}return readManagedExecutionEvidenceSync(transcriptPath)===false}async finishManagedWriter(lease,opened){if(opened){try{await stopAdvancing(opened)}catch{}await lease.sealForHandoff(managedCommitProof(opened));return}const takenOver=lease.takeoverCommitProof;if(takenOver!==void 0){await lease.sealForHandoff(takenOver);return}const transcriptPath=this.getTranscriptPath();const evidence=readManagedExecutionEvidenceSync(transcriptPath);if(evidence===false){await lease.release();return}if(evidence===void 0)return;let scan;try{scan=await LocalJsonlManagedSessionJournalStore.read({transcriptPath,runtimeBaseDir:this.sessionRuntimeBaseDir,sessionKey:localManagedSessionKey(this.storage.getProjectRoot(),this.sessionId)})}catch{return}await lease.sealForHandoff({last_commit_sequence:scan.committed,committed_prefix_hash:scan.lastMarkerDigest??EMPTY_COMMIT_PREFIX_HASH})}async publishManagedSessionRoot(resources){const[definitionRef,rootSnapshotRef]=await Promise.all([resources.publish("managed-session-definition",Buffer.from(JSON.stringify({version:1,engine:"managed",model:this.getModel(),approvalMode:this.getApprovalMode()}),"utf8")),resources.publish("managed-session-root-snapshot",Buffer.from(JSON.stringify({version:1,messages:[]}),"utf8"))]);return{definitionRef,rootSnapshotRef,createdBy:`qwen-code/${this.getCliVersion()||"unknown"}`}}async activateChatRecording(){const managed=this.sessionExecutionEngine==="managed";if(managed&&(!this.chatRecordingEnabled||!this.sessionWriterLeaseEnabled)){throw new SessionExecutionEngineError(this.sessionId,"managed execution requires chat recording and a writer lease")}if(!this.chatRecordingEnabled||!this.sessionWriterLeaseEnabled){return}if(managed&&this.isLegacyTranscript()){throw new SessionExecutionEngineError(this.sessionId,"belongs to legacy, cannot execute with managed")}if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const recorder=this.chatRecordingService;if(!recorder)throw new SessionWriterUnavailableError;let lease;try{const acquire=managed?acquireLocalManagedSessionWriter:SessionWriterLease.acquire;lease=await acquire({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionId:this.sessionId,transcriptPath:this.getTranscriptPath(),processKind:"acp",qwenVersion:this.cliVersion??null,reclaimPolicy:this.sessionWriterReclaimPolicy,takeoverPolicy:managed?"certified":this.sessionWriterTakeoverPolicy,...managed?{lockSchema:{schemaVersion:3,formatVersion:MANAGED_SESSION_FORMAT_VERSION}}:{},onOwnershipAcquired:__name(acquiredLease=>{lease=acquiredLease;this.pendingSessionWriterLease=acquiredLease;if(this.sessionWriterShutdownRequested){this.startPendingSessionWriterRelease(acquiredLease)}},"onOwnershipAcquired")});if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const location=await this.getSessionService().getSessionLocation(this.sessionId);if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}if(location==="archived"){throw new SessionTranscriptChangedError}let authoritative;let projection;if(this.sessionRestoreProjectionSource){addDaemonRequestAttribute("qwen-code.daemon.session_restore.projection_acquisition","after_writer_lease");projection=await this.sessionRestoreProjectionSource();if(managed){assertSessionExecutionEngine(projection?.executionEngine,this.sessionId,"managed")}if(managed&&await prepareLocalManagedSessionWriter(lease,localManagedSessionKey(this.storage.getProjectRoot(),this.sessionId))){projection=await this.sessionRestoreProjectionSource();assertSessionExecutionEngine(projection?.executionEngine,this.sessionId,"managed")}this.setSessionRestoreProjection(projection)}else if(managed&&(this.sessionData||lease.transcriptExistedAtAcquire)){throw new SessionExecutionEngineError(this.sessionId,"managed restore requires a restore projection")}else if(this.sessionData||lease.transcriptExistedAtAcquire){authoritative=await this.getSessionService().loadSession(this.sessionId);if(!authoritative)throw new SessionWriterUnavailableError}else if(location!==void 0){throw new SessionTranscriptChangedError}const persistedTitleInfo=authoritative?this.getSessionService().getSessionTitleInfo(this.sessionId):void 0;await lease.assertOwnedAndUnchanged();if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}this.sessionData=authoritative;if(managed){this.managedSession=await this.openManagedSessionLog(lease);if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const sequenceBeforeRepair=this.managedSession.authority.committedSequence;await this.getManagedRuntimeOutcomes()?.recoverCommittedReceipts();if(this.sessionRestoreProjectionSource&&this.managedSession.authority.committedSequence!==sequenceBeforeRepair){projection=await this.sessionRestoreProjectionSource();this.setSessionRestoreProjection(projection)}const unresolved=await unresolvedRuntimeWorkReason(this.managedSession.authority);if(unresolved!==void 0){this.blockManagedSession(new ManagedRuntimeOutcomeUnknownError(`The Managed session's log shows Runtime work with an unknown outcome: ${unresolved}.`))}recorder.bindManagedSink(managedRecordWriter(this.managedSession,{transcriptPath:this.getTranscriptPath(),runtimeBaseDir:this.sessionRuntimeBaseDir}))}recorder.activate(lease,authoritative,persistedTitleInfo,projection?.runtime.recording);if(this.sessionRestoreProjectionSource){this.initializeGoalRuntime(projection?.runtime.goalRecords,projection?.runtime)}this.pendingSessionWriterLease=void 0;lease=void 0;this.startPendingGoalRestore()}catch(error3){let failure=error3;const ownedLease=lease??this.pendingSessionWriterLease;let releaseFailureAlreadyReported=false;const abandonedManagedSession=this.managedSession;this.managedSession=void 0;if(managed&&ownedLease){const finishing=this.finishManagedWriter(ownedLease,abandonedManagedSession);void finishing.catch(()=>void 0);this.pendingSessionWriterRelease={lease:ownedLease,promise:finishing}}if(!(failure instanceof SessionWriterError)&&!(failure instanceof ManagedSessionRecordError)&&failure&&typeof failure==="object"&&typeof failure.code==="string"){failure=new SessionWriterUnavailableError({cause:failure})}try{await this.startPendingSessionWriterRelease(ownedLease);if(this.pendingSessionWriterLease===ownedLease&&(ownedLease?.isReleased??true)&&!ownedLease?.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}if(this.sessionWriterShutdownRequested&&failure instanceof SessionWriterLostError&&ownedLease?.isReleased){failure=new SessionWriterShutdownError}}catch(releaseError){if(releaseError instanceof SessionWriterLostError||ownedLease?.isReleased&&!ownedLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}else{releaseFailureAlreadyReported=containsErrorByIdentity(failure,releaseError);if(!releaseFailureAlreadyReported){failure=new SessionWriterUnavailableError({cause:new AggregateError([failure,releaseError],"Session writer lease release failed during activation cleanup")})}}}finally{if(!releaseFailureAlreadyReported&&this.pendingSessionWriterRelease?.lease===ownedLease){this.pendingSessionWriterRelease=void 0}}this.settlePendingGoalRestore(failure);throw failure}}mcpDiscoveryPromise;startMcpDiscoveryInBackground(){const manager=this.toolRegistry.getMcpClientManager?.();if(!manager){this.debugLogger.debug("Skipping background MCP discovery: ToolRegistry has no MCP client manager");return}this.mcpDiscoveryPromise=manager.discoverAllMcpToolsIncremental(this).then(async()=>{try{await this.llmClient?.setTools()}catch(err){this.debugLogger.error(`setTools() after background MCP discovery failed: ${err instanceof Error?err.message:String(err)}`)}}).catch(err=>{this.debugLogger.error(`Background MCP discovery failed: ${err instanceof Error?err.message:String(err)}`)})}async waitForMcpReady(){if(this.mcpDiscoveryPromise){await this.mcpDiscoveryPromise}}getFailedMcpServerNames(){const servers=this.getMcpServers();if(!servers){return[]}const failed=[];for(const name2 of Object.keys(servers)){if(this.isMcpServerDisabled(name2)){continue}if(this.isMcpServerPendingApproval(name2)){continue}if(getMCPServerStatus(name2)!=="connected"){failed.push(name2)}}return failed}async refreshHierarchicalMemory(loadReason="refresh",signal){if(this.executionEnvironment)return;if(this.isSafeMode()){this.setUserMemory("");this.autoMemoryPrompt="";this.autoMemoryContext="";this.setMemoryFileCount(0);this.setContextFilePaths([]);this.conditionalRulesRegistry=new ConditionalRulesRegistry([],this.getWorkingDir());return}const{memoryContent,fileCount,contextFilePaths,conditionalRules,ignoredExtensionRules,projectRoot}=await loadServerHierarchicalMemory(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason,onInstructionsLoaded:createInstructionsLoadedCallback(()=>this.hookSystem,signal),extensionRuleSources:this.getExtensionRuleSources()});this.ignoredExtensionRules=ignoredExtensionRules??[];if(this.isManagedMemoryAvailable()){const teamMemoryEnabled=this.getTeamMemoryEnabled()&&this.isTrustedFolder();if(this.getTeamMemoryEnabled()&&!this.isTrustedFolder()){this.debugLogger.debug("Team memory enabled but inactive: workspace is not trusted.")}const teamProjectRoot=this.getProjectRoot();if(teamMemoryEnabled&&!this.teamMemoryShareabilityChecked.has(teamProjectRoot)){this.teamMemoryShareabilityChecked.add(teamProjectRoot);const shareabilityWarning=getTeamMemoryShareabilityWarning(teamProjectRoot);if(shareabilityWarning){this.warnings.push(shareabilityWarning);this.debugLogger.warn(shareabilityWarning)}}let teamAutoMemoryIndex=null;if(teamMemoryEnabled){let teamRootSecurityBlocked=false;try{teamAutoMemoryIndex=await rebuildTeamAutoMemoryIndex(teamProjectRoot)}catch(err){if(err instanceof TeamMemoryRootSecurityError){teamRootSecurityBlocked=true;this.debugLogger.warn("team memory root failed the symlink/escape safety check; skipping sync",err)}else{this.debugLogger.warn("team memory index rebuild failed (operational); not security-gating sync",err)}}if(!teamRootSecurityBlocked&&this.getTeamMemorySyncEnabled()){const syncResult=await syncTeamMemory(teamProjectRoot,{message:"chore(memory): sync team memory"}).catch(err=>{this.debugLogger.warn("team memory sync failed",err);return void 0});if(syncResult?.skippedReason){this.debugLogger.warn(`team memory sync skipped: ${syncResult.skippedReason}`)}if(syncResult?.pulled){teamAutoMemoryIndex=await rebuildTeamAutoMemoryIndex(teamProjectRoot).catch(()=>teamAutoMemoryIndex)}}}if(!this.memoryRecallModeInitialized){const corpusStatus=this.getStructuredMemoryRecallEnabled()?await this.scanMemoryRecallCorpusStatus().catch(error3=>{this.debugLogger.warn("memory metadata readiness scan failed; preserving the active recall protocol",error3);return void 0}):void 0;this.memoryRecallMode=corpusStatus?.ready?"structured":"legacy";this.memoryCorpusRevision=corpusStatus?.revision??"";this.memoryRecallModeInitialized=true}const[managedAutoMemoryIndexRead,userAutoMemoryIndexRead]=await Promise.all([readAutoMemoryIndexWithStats(this.getProjectRoot()),readUserAutoMemoryIndexWithStats().catch(()=>null)]);this.recordAutoMemoryIndexRead(getAutoMemoryIndexPath(this.getProjectRoot()),managedAutoMemoryIndexRead);this.recordAutoMemoryIndexRead(getUserAutoMemoryIndexPath(),userAutoMemoryIndexRead);const managedAutoMemoryIndex=managedAutoMemoryIndexRead?.content??null;const userAutoMemoryIndex=userAutoMemoryIndexRead?.content??null;this.setUserMemory(memoryContent);const memoryDir=getAutoMemoryRoot(this.getProjectRoot());const userSection={memoryDir:getUserAutoMemoryRoot(),indexContent:userAutoMemoryIndex};const teamSection=teamMemoryEnabled?{memoryDir:getTeamAutoMemoryRoot(this.getProjectRoot()),indexContent:teamAutoMemoryIndex}:void 0;if(this.memoryRecallMode==="structured"){this.autoMemoryPrompt=buildStructuredAutoMemoryPrompt(memoryDir,userSection.memoryDir,teamSection?.memoryDir)}else{const policy=this.memoryManager.buildAutoMemoryPrompt(memoryDir,managedAutoMemoryIndex,userSection,teamSection,{includeIndexes:false});const catalog=buildAutoMemoryIndexContext(memoryDir,managedAutoMemoryIndex,userSection,teamSection);this.autoMemoryPrompt=policy;this.autoMemoryContext=catalog}}else{this.setUserMemory(memoryContent);this.autoMemoryPrompt="";this.autoMemoryContext=""}this.setMemoryFileCount(fileCount);this.setContextFilePaths(contextFilePaths);this.conditionalRulesRegistry=new ConditionalRulesRegistry(conditionalRules,projectRoot)}recordAutoMemoryIndexRead(indexPath,indexRead){if(indexRead===null||this.getFileReadCacheDisabled()){return}this.getFileReadCache().recordRead(indexPath,indexRead.stats,{full:true,cacheable:true})}buildMemoryContextWarning(memoryContent){const contextWindowSize=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??tokenLimit(this.getModel(),"input");if(!contextWindowSize||contextWindowSize<=0||!memoryContent){return void 0}const estimatedTokens=Math.ceil(memoryContent.length/CHARS_PER_TOKEN);const ratioTokens=Math.floor(contextWindowSize*MEMORY_CONTEXT_WARNING_RATIO);const thresholdTokens=Math.min(ratioTokens,MEMORY_CONTEXT_WARNING_MAX_TOKENS);if(estimatedTokens<=thresholdTokens){return void 0}const windowClause=`${Math.round(MEMORY_CONTEXT_WARNING_RATIO*100)}% of this model's ${contextWindowSize.toLocaleString()} token context window`;const bound=thresholdTokens===ratioTokens?windowClause:`${MEMORY_CONTEXT_WARNING_MAX_TOKENS.toLocaleString()} tokens \u2014 the smaller of that and ${windowClause}`;return`Warning: Loaded always-on context (QWEN.md context files + auto-memory) uses about ${estimatedTokens.toLocaleString()} tokens, more than ${bound}. Consider trimming long always-loaded context or moving details into on-demand files.`}getMemoryDiscoveryDirectories(){if(!this.shouldLoadMemoryFromIncludeDirectories()){return[]}if(this.getBareMode()){return this.explicitIncludeDirectories}return[...this.getWorkspaceContext().getDirectories()]}getConditionalRulesRegistry(){return this.conditionalRulesRegistry}setConditionalRulesRegistry(registry3){this.conditionalRulesRegistry=registry3}getContextRuleExcludes(){return this.contextRuleExcludes}getContentGenerator(){return getRuntimeContentGenerator()?.contentGenerator??this.contentGenerator}getModelsConfig(){return this.modelsConfig}updateCredentials(credentials,settingsGenerationConfig){this.modelsConfig.updateCredentials(credentials,settingsGenerationConfig)}reloadModelProvidersConfig(modelProvidersConfig,providerProtocolConfig){this.modelsConfig.reloadModelProvidersConfig(modelProvidersConfig,providerProtocolConfig);this.captureLatestReasoning();this.baseLlmClient?.clearPerModelGeneratorCache()}getReasoningSnapshot(){return this.reasoningSnapshot??=captureReasoningSnapshot(this.getAllConfiguredModels())}stageReasoningOverrides(providers,protocols={}){const previous=this.latestReasoningSnapshot??this.getReasoningSnapshot();const models=this.getAllConfiguredModels().map(model=>{const prior=previous.find(row=>row.id===model.id&&row.authType===model.authType&&row.registryBaseUrl===model.registryBaseUrl);const configured=Object.entries(providers??{}).flatMap(([provider,entries])=>model.authType!=="qwen-oauth"&&resolveProviderProtocol(provider,protocols)===model.authType&&Array.isArray(entries)?entries:[]).find(entry=>entry?.id===model.id&&entry.baseUrl===model.registryBaseUrl);return{...model,capabilities:{...model.capabilities,reasoning:configured?configured.capabilities?.reasoning:prior?prior.reasoning:model.capabilities?.reasoning}}});return this.captureLatestReasoning(models)}captureLatestReasoning(models=this.getAllConfiguredModels()){try{const next=captureReasoningSnapshot(models);for(const row of next){if(row.authType!=="qwen-oauth"||row.reasoning?.profile){validateReasoningCapabilities({model:row.id,authType:row.authType,baseUrl:row.baseUrl},row.reasoning)}}const generation2=this.getContentGeneratorConfig();if(generation2)resolveReasoningForModel(this,{...generation2,reasoningSnapshot:next},generation2.model,true);this.latestReasoningSnapshot=next;return void 0}catch(error3){const message=`Reasoning settings not applied; keeping the previous configuration. ${getErrorMessage(error3)}`;console.warn(message);return message}}applyReasoningOverrides(){if(!this.latestReasoningSnapshot)this.captureLatestReasoning();const next=this.latestReasoningSnapshot;if(!next||JSON.stringify(next)===JSON.stringify(this.reasoningSnapshot))return false;this.reasoningSnapshot=next;const generation2=this.getContentGeneratorConfig();if(generation2)generation2.reasoningSnapshot=next;this.baseLlmClient?.clearPerModelGeneratorCache();this.notifyModelChangeListeners();return true}getModelProvidersConfig(){return this.modelsConfig.getModelProvidersConfig()}getProviderProtocolConfig(){return this.modelsConfig.getProviderProtocolConfig()}syncModelSelection(authType,modelId,baseUrl){this.modelsConfig.syncAfterAuthRefresh(authType,modelId,baseUrl);this.initialResolvedAuthType=void 0}async refreshAuth(authMethod,isInitialAuth){const hookOwner=captureHookExecutionOwner(this,null);if(!this.contentGenerator&&authMethod===this.initialAuthType){authMethod=this.initialResolvedAuthType??authMethod}const priorGeneration={...this.modelsConfig.getGenerationConfig(),authType:this.modelsConfig.getCurrentAuthType()};const priorReasoning=priorGeneration.reasoning;const priorReasoningSource=this.modelsConfig.getGenerationConfigSources()["reasoning"];const priorReasoningEffort=priorReasoning?priorReasoning.effort:void 0;const modelId=this.modelsConfig.getModel();this.modelsConfig.syncAfterAuthRefresh(authMethod,modelId);const requireCached=this.modelsConfig.consumeRequireCachedCredentialsFlag();const{config:config3,sources}=resolveContentGeneratorConfigWithSources(this,authMethod,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()});const newContentGeneratorConfig=config3;const requestModel=getRequestModel(newContentGeneratorConfig);const deepSeekRoute=getBuiltinDeepSeekReasoning({...priorGeneration,model:getRequestModel(priorGeneration)})||getBuiltinDeepSeekReasoning({...newContentGeneratorConfig,model:requestModel});const explicitOff=priorReasoningSource?.kind==="settings"&&priorReasoningSource.settingsPath==="model.reasoningEffort"||priorReasoningSource?.kind==="programmatic"&&priorReasoningSource.detail==="reasoning selection";const preserveReasoningOff=priorReasoning===false&&(requestModel!==newContentGeneratorConfig.model||newContentGeneratorConfig.thinkingMandatory!==true)&&(!deepSeekRoute||explicitOff&&priorGeneration.authType===newContentGeneratorConfig.authType&&priorGeneration.model===newContentGeneratorConfig.model&&priorGeneration.baseUrl===newContentGeneratorConfig.baseUrl&&resolveReasoningForModel(this,newContentGeneratorConfig)?.canDisable!==false);if(preserveReasoningOff){newContentGeneratorConfig.reasoning=false;if(deepSeekRoute&&priorReasoningSource)sources["reasoning"]=priorReasoningSource}this.contentGenerator=await createContentGenerator(newContentGeneratorConfig,this,requireCached?true:isInitialAuth);this.contentGeneratorConfig=newContentGeneratorConfig;this.contentGeneratorConfigSources=sources;this.publishModelEnv();if(priorReasoning===false&&newContentGeneratorConfig.reasoning===false){this.modelsConfig.getGenerationConfig().reasoning=false;if(preserveReasoningOff&&deepSeekRoute&&priorReasoningSource){this.modelsConfig.getGenerationConfigSources()["reasoning"]=priorReasoningSource}}if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}this.baseLlmClient=new BaseLlmClient(this.contentGenerator,this);const messageBus=this.getMessageBus();const hooksEnabled=!this.getDisableAllHooks();if(hooksEnabled&&messageBus){fireNotificationHook(messageBus,`Successfully authenticated with ${authMethod}`,"auth_success","Authentication successful",void 0,hookOwner).catch(()=>{})}}getBaseLlmClient(){if(!this.baseLlmClient){if(this.contentGenerator){this.baseLlmClient=new BaseLlmClient(this.getContentGenerator(),this)}else{throw new Error("BaseLlmClient not initialized. Ensure authentication has occurred and ContentGenerator is ready.")}}return this.baseLlmClient}getSessionId(){return this.sessionId}getSessionExecutionEngine(){return this.sessionExecutionEngine}getManagedRuntimeEnvironment(){if(isDerivedConfig(this))return void 0;if(!this.managedRuntimeEnvironment&&!this.shutdownRequested&&!this.managedRuntimeClosing){this.managedRuntimeEnvironment=this.managedRuntimeEnvironmentFactory?.(this)}return this.managedRuntimeEnvironment}closeManagedRuntime(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).closeManagedRuntime()}if(!this.managedRuntimeClosing){const environment=this.managedRuntimeEnvironment;this.managedRuntimeEnvironment=void 0;this.managedRuntimeClosing=Promise.resolve(environment?.dispose())}return this.managedRuntimeClosing}blockManagedSession(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).blockManagedSession(reason);return}this.managedSessionBlock??=reason}getManagedSessionBlock(){return this.managedSessionBlock}reportManagedEngineQuarantine(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).reportManagedEngineQuarantine(reason);return}this.onManagedEngineQuarantine?.(true,reason)}clearManagedEngineQuarantine(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).clearManagedEngineQuarantine(reason);return}this.onManagedEngineQuarantine?.(false,reason)}getManagedRuntimeOutcomes(){if(isDerivedConfig(this)||!this.managedSession)return void 0;return this.managedRuntimeOutcomes??=new LocalManagedRuntimeOutcomes(this.managedSession)}getSessionRestoreRuntime(){return this.sessionRestoreRuntime}consumeSessionRestoreProjection(){const projection=this.pendingSessionRestoreProjection;this.pendingSessionRestoreProjection=void 0;return projection}hydrateSessionRestoreFileHistory(){if(this.restoredFileHistory)return;const snapshots=this.sessionRestoreRuntime?.fileHistorySnapshots;if(!snapshots?.length)return;const service=this.getFileHistoryService();if(!service.isEnabled())return;service.restoreFromSnapshots(snapshots);this.restoredFileHistory=true}finalizeSessionRestore(){const runtime=this.sessionRestoreRuntime;if(!runtime)return;this.sessionRestoreRuntime=void 0;if(runtime.attributionSnapshot){try{CommitAttributionService.getInstance().restoreFromSnapshot(runtime.attributionSnapshot)}catch(error3){this.debugLogger.error(`Session restore attribution activation failed: ${error3}`)}}const activateGoal=this.goalRestoreActivation;this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;if(activateGoal){try{void activateGoal().catch(error3=>{this.debugLogger.error(`Session restore goal activation failed: ${error3}`)})}catch(error3){this.debugLogger.error(`Session restore goal activation failed: ${error3}`)}}if(this.restoredFileHistory&&this.fileHistoryService){try{void this.fileHistoryService.validateRestoredSnapshots().catch(error3=>{this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${error3}`)})}catch(error3){this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${error3}`)}}}applyWorkspaceAgentPersona(systemPrompt,agentName,executionAllowedTools,disallowedTools){if(this.sessionSourceType!=="agent"){throw new Error("A workspace-agent persona may only be applied to an agent session.")}if(this.systemPrompt!==void 0){throw new Error("This session already has a persona; it cannot be changed in place.")}this.systemPrompt=systemPrompt;this.workspaceAgentName=agentName;this.workspaceAgentExecutionAllowedTools=executionAllowedTools?new Set(executionAllowedTools):void 0;this.workspaceAgentDisallowedTools=disallowedTools?[...disallowedTools]:void 0}getWorkspaceAgentName(){return this.workspaceAgentName}markSessionAgentSession(){if(this.sessionSourceType!=="agent"){throw new Error("Only an agent session can be marked as a session-agents session.")}this.sessionAgentSession=true;this.approvalMode="default";this.prePlanMode=void 0;this.planExecutionMode=void 0}isSessionAgentSession(){return this.sessionAgentSession&&this.sessionSourceType==="agent"}setSessionSource(sourceType,sourceId){this.sessionSourceType=sourceType;this.sessionSourceId=sourceId}getSessionSourceType(){return this.sessionSourceType}getSessionSourceId(){return this.sessionSourceId}getWarnings(){const memoryContextWarning=this.buildMemoryContextWarning([this.getUserMemory(),this.getAutoMemoryPrompt(),this.getAutoMemoryContext()].filter(Boolean).join("\n\n"));const ruleWarnings=this.ignoredExtensionRules.map(displayPath=>`Extension rule ${displayPath} has no \`paths:\` and was skipped. An extension's rules must be conditional: a baseline one would be sent with every request, which is the cost a rule exists to avoid. Add \`paths:\` to it, or move the content into the extension's context file.`);const extra=memoryContextWarning?[...ruleWarnings,memoryContextWarning]:ruleWarnings;return extra.length>0?[...this.warnings,...extra]:this.warnings}getDebugLogger(){return this.debugLogger}startNewSession(sessionId,sessionData){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot start new sessions")}if(this.chatRecordingService?.hasWriteOwnership()){throw new SessionWriterUnavailableError}if(Object.hasOwn(this,"goalRuntime")){this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.goalRuntime?.dispose()}const outgoingChatRecordingService=this.chatRecordingService;try{outgoingChatRecordingService?.finalize()}catch{}void outgoingChatRecordingService?.flush().catch(()=>{});const previousSessionId=this.sessionId;const nextSessionId=sessionId??randomUUID29();this.memoryManager.discardExtractCadence(previousSessionId,nextSessionId);const isSessionTransition=nextSessionId!==previousSessionId;if(isSessionTransition){logSessionEnd(this)}this.sessionId=nextSessionId;if(process8.env){process8.env["QWEN_CODE_SESSION_ID"]=this.sessionId}unregisterSessionModel(previousSessionId);this.publishModelEnv();this.sessionData=sessionData;this.workflowModeEpoch++;this.workflowModeContext.retire();if(isSessionTransition){const skillTool=this.toolRegistry?.getTool?.(ToolNames.SKILL);if(skillTool&&"clearLoadedSkills"in skillTool){skillTool.clearLoadedSkills()}this.toolRegistry?.clearReviewedDeclarations?.();this.permissionManager?.clearSessionAllowRules();forgetAutofixPrSession(previousSessionId);forgetAutofixPrSession(nextSessionId);this.webSearchSessionUsage.calls=0;this.advisorUsage.calls=0}this.clearSessionRestoreProjection();this.pendingRecoveredAgentsNotice=null;this.clearActiveTodoReminders();if(sessionIdContext.getStore()===void 0){setDebugLogSession(this)}this.debugLogger=createDebugLogger();outgoingChatRecordingService?.pinSessionIdentity(previousSessionId);this.chatRecordingService=this.chatRecordingEnabled?this.createChatRecordingService():void 0;this.workflowModeContext.restore(this.isWorkflowModeSupported()?this.chatRecordingService?.getSessionWorkflowMode():void 0);this.workflowModePublishedState=void 0;this.refreshWorkflowMode();this.sessionSourceService=this.sessionSourceServiceFactory?.();this.initializeGoalRuntime(this.sessionData?.conversation.messages);this.getFileReadCache().clear();this.toolResultBudget.bytesWritten=0;this.getMemoryPressureMonitor()?.resetForNewSession();this.fileHistoryService=void 0;refreshSessionContext(this.sessionId);CommitAttributionService.resetInstance();if(this.initialized){logStartSession(this,new StartSessionEvent(this),sessionData&&isSessionTransition?previousSessionId:void 0)}if(isSessionTransition){if(this.runtimeStatusEnabled){const oldPath=this.storage.getRuntimeStatusPath(previousSessionId);const newPath=this.storage.getRuntimeStatusPath(this.sessionId);const cliVersion=this.cliVersion??null;const workDir=this.targetDir;const newSessionId=this.sessionId;this.queueRuntimeStatusWrite(async()=>{await clearRuntimeStatus(oldPath);await writeRuntimeStatus(newPath,{sessionId:newSessionId,workDir,qwenVersion:cliVersion})})}if(this.sessionRegistryActive){const workDir=this.targetDir;const newSessionId=this.sessionId;this.queueRetriedSessionRegistryPatch({sessionId:newSessionId,cwd:workDir},"session registry record still names the previous session id; peers addressing this session by its new id will be refused until it is re-asserted")}}return this.sessionId}async reassertSessionRegistryRecord(){if(!this.sessionRegistryActive)return;this.queueRetriedSessionRegistryPatch({sessionId:this.sessionId,cwd:this.targetDir},"session registry record could not be re-asserted; peers may keep addressing a stale session id");await this.sessionRegistryWrite}queueRetriedSessionRegistryPatch(patch,failureWarning){this.queueSessionRegistryWrite(async()=>{const slot=this.sessionRegistrySlot;let applied=await patchSessionRecord(patch,slot);for(let attempt2=0;attempt2<2&&!applied;attempt2+=1){await delay(250);applied=await patchSessionRecord(patch,slot)}if(!applied){this.debugLogger.warn(failureWarning)}})}markRuntimeStatusEnabled(){this.runtimeStatusEnabled=true}trackSessionRegistration(registration){this.sessionRegistryActive=true;this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(async()=>{const outcome=await registration;this.sessionRegistrySlot=outcome.slot;this.sessionRegistered=outcome.registered;if(!this.sessionRegistered)this.sessionRegistryActive=false}).catch(()=>{this.sessionRegistered=false;this.sessionRegistryActive=false})}getSessionRegistrySlot(){return this.sessionRegistrySlot}async whenSessionRegistered(){await this.sessionRegistryWrite.catch(()=>{});return this.sessionRegistered}async updateSessionRegistryIpcPath(ipcPath,ipcToken){if(!this.sessionRegistryActive)return;let applied=false;this.queueSessionRegistryWrite(async()=>{const slot=this.sessionRegistrySlot;applied=await patchSessionRecord({ipcPath,ipcToken},slot);if(ipcPath===void 0||applied)return;for(let attempt2=0;attempt2<2&&!applied;attempt2+=1){await delay(250);applied=await patchSessionRecord({ipcPath,ipcToken},slot)}if(!applied){this.debugLogger.warn("peer inbox address was not published to the session registry; peers cannot discover this session until it restarts")}});await this.sessionRegistryWrite}async unregisterSessionRegistry(){this.sessionRegistryActive=false;this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(async()=>{if(!this.sessionRegistered)return;this.sessionRegistered=false;await unregisterSession(this.sessionRegistrySlot)}).catch(()=>{});await this.sessionRegistryWrite}queueRuntimeStatusWrite(write){this.runtimeStatusWrite=this.runtimeStatusWrite.catch(()=>{}).then(write).catch(()=>{})}queueSessionRegistryWrite(write){this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(write).catch(()=>{})}async flushRuntimeStatusWrites(){await this.runtimeStatusWrite.catch(()=>{})}async refreshCurrentRuntimeStatus(workDir){const sessionId=this.sessionId;if(this.runtimeStatusEnabled){const sidecarPath=this.storage.getRuntimeStatusPath(sessionId);this.queueRuntimeStatusWrite(async()=>{await writeRuntimeStatus(sidecarPath,{sessionId,workDir,qwenVersion:this.cliVersion??null})})}if(this.sessionRegistryActive){this.queueSessionRegistryWrite(async()=>{await patchSessionRecord({cwd:workDir,name:deriveSessionName(workDir,sessionId)},this.sessionRegistrySlot)})}await this.flushRuntimeStatusWrites()}getResumedSessionData(){return this.sessionData}shouldLoadMemoryFromIncludeDirectories(){return this.loadMemoryFromIncludeDirectories}getImportFormat(){return this.importFormat}getContentGeneratorConfig(){return getRuntimeContentGenerator()?.contentGeneratorConfig??this.contentGeneratorConfig}getContentGeneratorConfigSources(){if(Object.keys(this.contentGeneratorConfigSources).length===0&&this.modelsConfig){return this.modelsConfig.getGenerationConfigSources()}return this.contentGeneratorConfigSources}getModel(){return this.getContentGeneratorConfig()?.model||this.modelsConfig.getModel()}getCurrentModelRegistryBaseUrl(){return this.modelsConfig.getCurrentRegistryBaseUrl()}getCurrentAuthType(){return this.modelsConfig.getCurrentAuthType()}getEffectiveInputModalities(){return this.getContentGeneratorConfig()?.modalities??{}}getModelDisplayName(){return this.modelsConfig.getModelDisplayName(this.getModel())}onModelChange(listener){this.modelChangeListeners.add(listener);return()=>{this.modelChangeListeners.delete(listener)}}notifyModelChangeListeners(){this.publishModelEnv();const model=this.getModel();for(const listener of this.modelChangeListeners){listener(model)}}onApprovalModeChange(listener){this.approvalModeChangeListeners.add(listener);return()=>{this.approvalModeChangeListeners.delete(listener)}}notifyApprovalModeChangeListeners(){if(isDerivedConfig(this))return;for(const listener of this.approvalModeChangeListeners){listener(this.approvalMode,this.prePlanMode)}}publishModelEnv(){if(!process8.env){return}const model=this.getModel();registerSessionModel(this.sessionId,model,this.resolvedModelIdentity());if(this.ownsModelEnvSlot){process8.env["QWEN_CODE_MODEL"]=model;process8.env["QWEN_CODE_MODEL_IDENTITY"]=this.resolvedModelIdentity()}}resolvedModelIdentity(model=this.getModel(),generatorConfig=this.getContentGeneratorConfig()){const authType=generatorConfig?.authType??"";const baseUrl=generatorConfig?.baseUrl??(model===this.getModel()?this.getCurrentModelRegistryBaseUrl():void 0)??"";if(authType===""&&baseUrl==="")return model;const digest2=createHash29("sha256").update(`${authType}\0${baseUrl}`).digest("hex").slice(0,8);return`${model}@${digest2}`}getModelRouteIdentity(model,generatorConfig){return this.resolvedModelIdentity(model,generatorConfig)}getFastModel(){const selector=this.resolveFastModelSelector();if(!selector)return void 0;const available=selector.authType?this.getAllConfiguredModels([selector.authType]):this.getAllConfiguredModels();if(!available.some(model=>model.id===selector.modelId&&!model.voiceOnly&&!model.imageOnly&&!model.visionOnly)){return void 0}const rawSelector=resolveModelId(this.fastModel);if(!rawSelector?.authType)return selector.modelId;const qualified=`${rawSelector.authType}:${selector.modelId}`;const endpoint=this.pinnedAuxEndpoint(this.fastModel,selector.modelId,available);return endpoint?`${qualified}\0${endpoint}`:qualified}pinnedAuxEndpoint(persisted,modelId,available){const endpoint=persisted?.trim().split("\0")[1];if(!endpoint)return void 0;const hits=available.filter(model=>model.id===modelId&&model.baseUrl===endpoint);const matched=hits.find(model=>model.registryBaseUrl!==void 0)??hits[0];if(!matched){this.debugLogger.warn(`Aux endpoint pin dropped for "${modelId}": no configured entry at ${formatVisionModelSettingForLog(endpoint)}; falling back to the first same-id match.`);return void 0}return matched.registryBaseUrl}getWebSearchSettings(){return this.webSearchSettings}getWebSearchSessionUsage(){return this.webSearchSessionUsage}resolveFastModelSelector(){if(!this.fastModel)return void 0;try{const rawSelector=resolveModelId(this.fastModel);if(!rawSelector)return void 0;if(rawSelector.authType)return rawSelector;const currentAuthType=this.getContentGeneratorConfig()?.authType;if(!currentAuthType){this.debugLogger.debug("No active auth type; skipping bare fast model resolution");return void 0}return resolveModelId(this.fastModel,{currentAuthType,getAvailableModels:__name(()=>this.getAllConfiguredModels([currentAuthType]),"getAvailableModels")})}catch{return void 0}}setFastModel(model){this.fastModel=model||void 0}getAdvisorMaxUses(){return this.advisorMaxUses}getAdvisorUseCount(){return this.advisorUsage.calls}tryConsumeAdvisorUse(){if(this.advisorMaxUses>0&&this.advisorUsage.calls>=this.advisorMaxUses)return false;this.advisorUsage.calls+=1;return true}getAdvisorModel(){return this.advisorModel}async setAdvisorModel(model){const normalizedModel=normalizeAdvisorModel(model);if(normalizedModel&&this.getDisabledTools().has(ToolNames.ADVISOR)){return false}this.advisorModel=normalizedModel;if(!this.initialized||!this.toolRegistry){return true}await this.syncAdvisorToolRegistration(this.toolRegistry);await this.llmClient?.setTools();return true}setVisionModel(model){this.visionModel=model||void 0}getCompactionModel(){const selector=this.resolveCompactionModelSelector();if(selector){const available=selector.authType?this.getAllConfiguredModels([selector.authType]):this.getAllConfiguredModels();if(!available.some(m2=>m2.id===selector.modelId&&!m2.fastOnly&&!m2.voiceOnly&&!m2.imageOnly&&!m2.visionOnly)){return void 0}const rawSelector=resolveModelId(this.compactionModel);if(!rawSelector?.authType)return selector.modelId;const qualified=`${rawSelector.authType}:${selector.modelId}`;const endpoint=this.pinnedAuxEndpoint(this.compactionModel,selector.modelId,available);return endpoint?`${qualified}\0${endpoint}`:qualified}return this.getModel()}resolveCompactionModelSelector(){if(!this.compactionModel)return void 0;try{const rawSelector=resolveModelId(this.compactionModel);if(!rawSelector)return void 0;if(rawSelector.authType)return rawSelector;const currentAuthType=this.getContentGeneratorConfig()?.authType;if(!currentAuthType){this.debugLogger.debug("No active auth type; skipping bare compaction model resolution");return void 0}return resolveModelId(this.compactionModel,{currentAuthType,getAvailableModels:__name(()=>this.getAllConfiguredModels([currentAuthType]),"getAvailableModels")})}catch{return void 0}}setCompactionModel(model){this.compactionModel=model||void 0}async setImageModel(model){this.imageModel=model||void 0;if(!this.initialized||!this.toolRegistry){return}if(this.isImageGenerationEnabled()){await this.registerImageGenerationTool(this.toolRegistry);await this.toolRegistry.ensureTool(ToolNames.IMAGE_GEN)}await this.llmClient.setTools()}getModelFallbacks(){return this.modelFallbacks}getReasoningEffort(){const reasoning=this.getContentGeneratorConfig()?.reasoning;if(!reasoning){return void 0}return reasoning.effort}getReasoningEffortOverride(){const cfg=this.getContentGeneratorConfig();if(!cfg||!DashScopeOpenAICompatibleProvider.isDashScopeProvider(cfg)){return void 0}const configuredReasoning=resolveReasoningForModel(this,cfg);const model=getRequestModel(cfg);const tieredModel=isTieredEffortWireModel(model,configuredReasoning);if(!tieredModel)return void 0;const currentEffort=this.getReasoningEffort();const selected=selectDashScopeThinkingKnob(model,cfg.extra_body,cfg.samplingParams,currentEffort,tieredModel);if(!selected||selected.source==="reasoning"||selected.field==="reasoning_effort"&&selected.value===currentEffort){return void 0}if(selected.field==="enable_thinking"&&selected.value===true){if(selected.source!=="extra_body"){return void 0}const below=selectDashScopeThinkingKnob(model,void 0,cfg.samplingParams,currentEffort,tieredModel);if(below?.source==="samplingParams"&&below.field==="reasoning_effort"&&below.value!==currentEffort){return{source:below.source,field:below.field}}return void 0}return{source:selected.source,field:selected.field}}setReasoningEffort(effort){const applyEffort=__name(cfg=>{setGeneratorReasoningEffort(cfg,effort)},"applyEffort");applyEffort(this.contentGeneratorConfig);const runtimeCfg=getRuntimeContentGenerator()?.contentGeneratorConfig;if(runtimeCfg&&runtimeCfg!==this.contentGeneratorConfig){applyEffort(runtimeCfg)}applyEffort(this.modelsConfig?.getGenerationConfig())}isCurrentPrimaryModel(model){if(model.id!==this.getModel())return false;const cfg=this.getContentGeneratorConfig();const primaryAuthType=cfg?.authType;if(primaryAuthType===void 0)return true;if(model.authType!==primaryAuthType)return false;const primaryBaseUrl=cfg?.baseUrl;if(primaryBaseUrl!==void 0&&model.baseUrl!==void 0){return model.baseUrl===primaryBaseUrl}return true}resolveVisionModelSelection(){if(!this.visionModel)return void 0;const visionModelForLog=formatVisionModelSettingForLog(this.visionModel);const parsedSetting=parseVisionModelSetting(this.visionModel);if(!parsedSetting){this.debugLogger.warn(`vision model pin '${visionModelForLog}' could not be parsed; falling back to auto-select`);return void 0}let selector;try{selector=resolveModelId(parsedSetting.selector)}catch{this.debugLogger.warn(`vision model pin '${visionModelForLog}' could not be parsed; falling back to auto-select`);return void 0}if(!selector){this.debugLogger.warn(`vision model pin '${visionModelForLog}' resolved to no selector; falling back to auto-select`);return void 0}const routeMatches=this.getAllConfiguredModels().filter(m2=>m2.id===selector.modelId&&(!selector.authType||m2.authType===selector.authType)&&(!parsedSetting.baseUrl||m2.baseUrl===parsedSetting.baseUrl)&&!m2.fastOnly&&!m2.voiceOnly&&!m2.imageOnly&&!this.isCurrentPrimaryModel(m2));if(routeMatches.length>1){this.debugLogger.warn(`vision model pin '${visionModelForLog}' matched multiple configured routes; falling back to auto-select`);return void 0}const match=routeMatches[0];if(!match){this.debugLogger.warn(`vision model pin '${visionModelForLog}' did not match a usable configured model (removed, mistyped, selector-only, or the primary itself); falling back to auto-select`);return void 0}const agentCapable=isFullTurnVisionCapable(match);return{id:getQualifiedVisionModelId(match),...(parsedSetting.baseUrl??match.baseUrl)&&{baseUrl:parsedSetting.baseUrl??match.baseUrl},...agentCapable&&{agentCapable:true}}}getDefaultVisionBridgeModel(){const explicit=this.resolveVisionModelSelection();if(explicit)return explicit;const contentGeneratorConfig=this.getContentGeneratorConfig();return selectVisionBridgeModel(this.getModel(),this.getAllConfiguredModels(),{authType:contentGeneratorConfig?.authType,baseUrl:contentGeneratorConfig?.baseUrl})}getVisionBridgeTimeoutMs(){return this.visionBridgeTimeoutMs}async setModel(newModel,metadata){await this.modelsConfig.setModel(newModel,metadata);if(this.contentGeneratorConfig){this.contentGeneratorConfig.model=newModel}this.notifyModelChangeListeners()}async handleModelChange(authType,requiresRefresh){this.initialResolvedAuthType=void 0;if(!this.contentGeneratorConfig){return}const priorReasoningEffort=this.getReasoningEffort();if(authType==="qwen-oauth"&&!requiresRefresh){const{config:config3,sources}=resolveContentGeneratorConfigWithSources(this,authType,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()});this.contentGeneratorConfig.reasoningRouteBaseUrl=config3.reasoningRouteBaseUrl;this.contentGeneratorConfig.model=config3.model;this.contentGeneratorConfig.samplingParams=config3.samplingParams;this.contentGeneratorConfig.contextWindowSize=config3.contextWindowSize;this.contentGeneratorConfig.enableCacheControl=config3.enableCacheControl;this.contentGeneratorConfig.enableRequestMetadata=config3.enableRequestMetadata;this.contentGeneratorConfig.forceGlobalCacheScope=config3.forceGlobalCacheScope;this.contentGeneratorConfig.cacheRetention=config3.cacheRetention;this.contentGeneratorConfig.cacheRetentionByBlock=config3.cacheRetentionByBlock;this.contentGeneratorConfig.splitToolMedia=config3.splitToolMedia;this.contentGeneratorConfig.toolResultContentFormat=config3.toolResultContentFormat;this.contentGeneratorConfig.modalities=config3.modalities;if("model"in sources){this.contentGeneratorConfigSources["model"]=sources["model"]}if("modalities"in sources){this.contentGeneratorConfigSources["modalities"]=sources["modalities"]}if("samplingParams"in sources){this.contentGeneratorConfigSources["samplingParams"]=sources["samplingParams"]}if("enableCacheControl"in sources){this.contentGeneratorConfigSources["enableCacheControl"]=sources["enableCacheControl"]}if("enableRequestMetadata"in sources){this.contentGeneratorConfigSources["enableRequestMetadata"]=sources["enableRequestMetadata"]}if("forceGlobalCacheScope"in sources){this.contentGeneratorConfigSources["forceGlobalCacheScope"]=sources["forceGlobalCacheScope"]}if("cacheRetention"in sources){this.contentGeneratorConfigSources["cacheRetention"]=sources["cacheRetention"]}if("cacheRetentionByBlock"in sources){this.contentGeneratorConfigSources["cacheRetentionByBlock"]=sources["cacheRetentionByBlock"]}if("contextWindowSize"in sources){this.contentGeneratorConfigSources["contextWindowSize"]=sources["contextWindowSize"]}if("splitToolMedia"in sources){this.contentGeneratorConfigSources["splitToolMedia"]=sources["splitToolMedia"]}if("toolResultContentFormat"in sources){this.contentGeneratorConfigSources["toolResultContentFormat"]=sources["toolResultContentFormat"]}if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}resetPreloadedContentGenerator(this.contentGenerator);return}await this.refreshAuth(authType);if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}}getAvailableModels(){return this.modelsConfig.getAvailableModels()}getAvailableModelsForAuthType(authType){return this.modelsConfig.getAvailableModelsForAuthType(authType)}getAllConfiguredModels(authTypes){return this.modelsConfig.getAllConfiguredModels(authTypes)}getResolvedModelConfig(authType,modelId,baseUrl){return this.modelsConfig.getResolvedModel(authType,modelId,baseUrl)}getActiveRuntimeModelSnapshot(){return this.modelsConfig.getActiveRuntimeModelSnapshot()}async switchModel(authType,modelId,options2){await this.modelsConfig.switchModel(authType,modelId,options2);this.notifyModelChangeListeners()}getMaxSessionTurns(){return this.maxSessionTurns}getGoalTokenBudgetGrant(){return this.goalTokenBudgetGrant}getGoalTurnBudgetGrant(){return this.goalTurnBudgetGrant}getGoalActiveTimeBudgetGrantMs(){return this.goalActiveTimeBudgetGrantMs}getMaxSubagentDepth(){return this.maxSubagentDepth}getMaxWallTimeSeconds(){return this.maxWallTimeSeconds}getMaxToolCalls(){return this.maxToolCalls}getClearContextOnIdle(){return this.clearContextOnIdle}getSessionTokenLimit(){return this.sessionTokenLimit}getEmbeddingModel(){return this.embeddingModel}getSandbox(){return this.sandbox}isRestrictiveSandbox(){const sandboxConfig=this.getSandbox();const seatbeltProfile=process8.env["SEATBELT_PROFILE"];return!!sandboxConfig&&sandboxConfig.command==="sandbox-exec"&&!!seatbeltProfile&&seatbeltProfile.startsWith("restrictive-")}getTargetDir(){return this.targetDir}getCurrentSessionArtifactMoves(oldStorage,newStorage){const oldChatsDir=path88.join(oldStorage.getProjectDir(),"chats");const newChatsDir=path88.join(newStorage.getProjectDir(),"chats");return[`${this.sessionId}.jsonl`,`${this.sessionId}.runtime.json`,`${this.sessionId}.worktree.json`,`${this.sessionId}.pr.json`].map(fileName=>({from:path88.join(oldChatsDir,fileName),to:path88.join(newChatsDir,fileName)}))}moveFile(from,to2){try{fs80.renameSync(from,to2)}catch(error3){if(error3.code!=="EXDEV"){throw error3}let copied=false;try{fs80.copyFileSync(from,to2);copied=true;fs80.unlinkSync(from)}catch(fallbackError){if(copied){try{fs80.unlinkSync(to2)}catch{}}throw fallbackError}}}moveCurrentSessionArtifacts(oldStorage,newStorage){const moved=[];for(const{from,to:to2}of this.getCurrentSessionArtifactMoves(oldStorage,newStorage)){if(!fs80.existsSync(from)){continue}fs80.mkdirSync(path88.dirname(to2),{recursive:true});try{this.moveFile(from,to2);moved.push({from,to:to2})}catch(error3){for(const movedArtifact of moved.reverse()){try{fs80.mkdirSync(path88.dirname(movedArtifact.from),{recursive:true});this.moveFile(movedArtifact.to,movedArtifact.from)}catch(rollbackError){this.debugLogger.warn("Failed to roll back moved session artifact",rollbackError)}}throw error3}}}async prepareSessionArtifactMigration(oldStorage,newStorage,oldDir,opts){try{this.chatRecordingService?.finalize();await this.chatRecordingService?.flush()}catch(error3){this.debugLogger.debug("Continuing session artifact migration after chat recording settle failed:",error3)}await this.flushRuntimeStatusWrites();try{this.moveCurrentSessionArtifacts(oldStorage,newStorage)}catch(error3){if(!opts?.skipProcessChdir){try{process8.chdir(oldDir)}catch(rollbackError){this.debugLogger.warn("Failed to roll back working directory after session artifact migration failed",rollbackError)}}throw error3}}async relocateWorkingDirectory(newDir,expectedCanonicalDir,opts){if(this.shellExecutionSandbox){assertShellSandboxCwd(this.shellExecutionSandbox,path88.resolve(newDir))}if(isDerivedConfig(this)){throw new Error("Derived Configs cannot relocate working directories")}if(this.sessionExecutionEngine==="managed"){throw new Error("A Managed session cannot change its directory.")}if(!opts?.skipArtifactMigration&&this.chatRecordingService?.hasWriteOwnership()){throw new SessionWriterUnavailableError}const oldDir=opts?.skipProcessChdir?this.cwd:fs80.realpathSync(process8.cwd());const targetPath=path88.resolve(newDir);const expected=expectedCanonicalDir??fs80.realpathSync(targetPath);if(!fs80.statSync(targetPath).isDirectory()){throw new Error(`Path is not a directory: ${targetPath}`)}const workspaceDirectories=WorkspaceContext.resolveRootDirectories(expected,this.explicitIncludeDirectories);if(!opts?.skipProcessChdir){process8.chdir(targetPath);const actualCwd=fs80.realpathSync(process8.cwd());if(actualCwd!==expected){process8.chdir(oldDir);throw new Error(`Changed directory to ${actualCwd}, expected ${expected}.`)}}else{const actualCanonical=fs80.realpathSync(targetPath);if(actualCanonical!==expected){throw new Error(`Realpath mismatch: resolved ${actualCanonical}, expected ${expected}.`)}}const oldStorage=this.storage;if(!opts?.skipArtifactMigration){const newStorage=new Storage(expected,this.sessionRuntimeBaseDir);await this.prepareSessionArtifactMigration(oldStorage,newStorage,oldDir,opts);this.storage=newStorage;this.chatRecordingService?.resetStoragePaths()}this.backgroundTaskRegistry.disposeResidentAgents();this.targetDir=expected;this.cwd=expected;resetPreloadedContentGenerator(this.contentGenerator);await this.refreshCurrentRuntimeStatus(expected);this.workspaceContext.applyRootDirectories(workspaceDirectories);this.fileDiscoveryService=null;const sessionPrBoundCallback=this.sessionService?.getSessionPrBoundCallback();this.sessionService=void 0;if(sessionPrBoundCallback){this.getSessionService().setSessionPrBoundCallback(sessionPrBoundCallback)}this.fileHistoryService=void 0;this.getFileReadCache().clear();this.memoryRecallMode="legacy";this.memoryCorpusRevision="";this.memoryRecallModeInitialized=false;this.autoMemoryPrompt="";this.autoMemoryContext="";let memoryRefreshError;try{await this.refreshHierarchicalMemory()}catch(error3){memoryRefreshError=error3}let mcpRefreshError;try{await this.waitForMcpReady();await this.refreshMcpServers()}catch(error3){mcpRefreshError=error3}return{...memoryRefreshError!==void 0&&{memoryRefreshError},...mcpRefreshError!==void 0&&{mcpRefreshError}}}setPendingStartupWorktreeNotice(notice){this.pendingStartupWorktreeNotice=notice}consumePendingStartupWorktreeNotice(){const v2=this.pendingStartupWorktreeNotice;this.pendingStartupWorktreeNotice=null;return v2}getProjectRoot(){return this.targetDir}getCwd(){return this.targetDir}getWorkspaceContext(){return this.workspaceContext}getToolRegistry(){return this.toolRegistry}async shutdown(options2){if(isDerivedConfig(this))return;this.shutdownRequested=true;this.workflowModeEpoch++;this.workflowModeContext.retire();this.workflowModeListeners.clear();forgetAutofixPrSession(this.sessionId);void this.shutdownExecutionEnvironments().catch(()=>void 0);this.settingsWatcher?.stopWatching();if(this.managedRuntimeEnvironment||this.managedRuntimeClosing){try{await this.closeManagedRuntime()}catch(error3){this.debugLogger.error("Failed to stop the Managed Runtime worker:",error3)}}const closeWriter=__name(()=>this.closeSessionWriter().catch(error3=>{this.debugLogger.error("Failed to release session writer lease:",error3)}),"closeWriter");const earlyWriterClose=!options2?.skipSessionWriter&&this.initializationPromise!==void 0&&!this.initializationSucceeded?closeWriter():void 0;try{if(!options2?.skipSessionWriter&&!earlyWriterClose){try{this.chatRecordingService?.finalize();await this.chatRecordingService?.flush()}catch{}}try{await this.shutdownResources(options2?.strictResourceCleanup===true)}catch(error3){if(options2?.strictResourceCleanup)throw error3}}finally{if(!options2?.skipSessionWriter){await(earlyWriterClose??closeWriter())}this.chatRecordingFailureListeners.clear();this.requestLifecycleListeners.clear();if(options2?.shutdownTelemetry!==false&&isTelemetrySdkInitialized()){await shutdownTelemetry()}}}async shutdownResources(waitForInitialization){if(waitForInitialization){try{await this.initializationPromise}catch{}}else if(this.initializationPromise&&!this.initializationSettled){this.scheduleResourceShutdownAfterInitialization();return}return this.runResourceShutdown()}scheduleResourceShutdownAfterInitialization(){if(this.resourceShutdownAfterInitializationScheduled||!this.initializationPromise){return}this.resourceShutdownAfterInitializationScheduled=true;void this.initializationPromise.then(()=>this.runResourceShutdown(),()=>this.runResourceShutdown()).catch(error3=>{this.debugLogger.error("Deferred Config resource cleanup failed:",error3)})}runResourceShutdown(){if(this.resourceShutdownPromise){return this.resourceShutdownPromise}const shutdown=this.shutdownResourcesOnce();this.resourceShutdownPromise=shutdown;const clear=__name(()=>{if(this.resourceShutdownPromise===shutdown){this.resourceShutdownPromise=void 0}},"clear");void shutdown.then(clear,clear);return shutdown}async shutdownResourcesOnce(){let resourceError;try{this.memoryManager.cancelMigrations();this.clearSessionRestoreProjection();if(this.sessionProjectDirRegistered){unregisterSessionProjectDir(this.sessionId);this.sessionProjectDirRegistered=false}unregisterSessionModel(this.sessionId);if(Object.hasOwn(this,"goalRuntime")){this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Goal runtime disposed"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.settlePendingGoalRestore(new GoalPersistenceUnavailableError("Config shut down before the session writer became available"));this.goalRuntime?.dispose()}try{await this.lspClient?.stop?.()}catch(lspStopError){this.debugLogger.error("Error stopping LSP client:",lspStopError)}if(this.initialized){this.skillManager?.stopWatching();if(this.toolRegistry){await this.toolRegistry.stop()}this.backgroundTaskRegistry.abortAll();this.monitorRegistry.abortAll({notify:false});this.backgroundShellRegistry.abortAll();this.workflowRunRegistry.abortAll()}}catch(error3){resourceError=error3;this.debugLogger.error("Error during Config shutdown:",error3)}try{await this.shutdownExecutionEnvironments()}catch(cleanupError){const errors=cleanupError instanceof AggregateError?[...cleanupError.errors]:[cleanupError];if(resourceError!==void 0)errors.unshift(resourceError);throw new AggregateError(errors,"Container execution cleanup failed during session shutdown.")}if(resourceError!==void 0)throw resourceError;if(!this.initialized)return;try{await this.cleanupArenaRuntime();await this.cleanupTeamRuntime()}catch(error3){this.debugLogger.error("Error during session runtime cleanup:",error3);throw error3}}getPromptRegistry(){return this.promptRegistry}getResourceRegistry(){return this.resourceRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){const parts=[this.appendSystemPrompt,this.liveAppendSystemPrompt].filter(part=>Boolean(part?.trim()));return parts.length>0?parts.join("\n\n"):void 0}setLiveAppendSystemPrompt(prompt){this.liveAppendSystemPrompt=prompt}getOutputStyle(){return this.outputStyle}setOutputStyle(style){this.outputStyle=style}getCoreTools(){if(this.shellExecutionSandbox)return[ToolNames.SHELL,ToolNames.TASK_STOP,ToolNames.READ_FILE,ToolNames.WRITE_FILE,ToolNames.EDIT,ToolNames.MONITOR,ToolNames.AGENT,ToolNames.EXEC,ToolNames.GLOB,ToolNames.LS,ToolNames.ASK_USER_QUESTION,ToolNames.STRUCTURED_OUTPUT];if(this.getBareMode()){return DEFAULT_BARE_CORE_TOOLS}return this.coreTools}getPermissionsAllow(){const base2=this.permissionsAllow??[];const sdkAllow=[...this.allowedTools??[]];if(sdkAllow.length===0)return base2.length>0?base2:[];const merged=[...base2];for(const t of sdkAllow){if(t&&!merged.includes(t))merged.push(t)}return merged}getPermissionsAsk(){return this.permissionsAsk}getEagerTools(){return this.eagerTools}getPermissionsDeny(){const base2=this.permissionsDeny??[];const sdkDeny=this.excludeTools??[];if(sdkDeny.length===0)return base2.length>0?base2:[];const merged=[...base2];for(const t of sdkDeny){if(t&&!merged.includes(t))merged.push(t)}return merged}getToolDiscoveryCommand(){return this.toolDiscoveryCommand}getDisabledSlashCommands(){return this.disabledSlashCommands}getDisabledSkillNames(){return this.disabledSkillNamesProvider?.()??EMPTY_DISABLED_SKILL_NAMES}hasSkillSettingsListsProvider(){return this.skillSettingsListsProvider!==null}isSkillEnabled(skill){if(skill.level==="bundled"&&skill.name==="generated-ui"&&!this.getBundledGeneratedUiStatus().enabled){return false}const registryName=skill.name.trim().toLowerCase();const authoredName=authoredSkillName(skill).trim().toLowerCase();const extension=skill.level==="extension"?this.getExtensions().find(candidate=>candidate.name===skill.extensionName&&candidate.skills?.some(owned=>owned.name.trim().toLowerCase()===authoredName&&owned.filePath===skill.filePath)):void 0;if(skill.level==="extension"&&!extension?.isActive)return false;const disabledNames=this.getDisabledSkillNames();if(skillRestrictionNames(skill).some(entry=>disabledNames.has(entry))){return false}if(!extension||this.enabledSkillNamesProvider?.().has(registryName)){return true}const state=this.extensionManager.getExtensionSkillState(extension.id,authoredSkillName(skill));return state.workspaceEnabled??state.defaultEnabled}getDisabledSkillLevels(){return this.disabledSkillLevels}getCustomSkillDirs(){return this.customSkillDirs}getDisabledTools(){return this.disabledTools}getVisibleTools(){return this.visibleTools}getToolSearchThreshold(){return this.toolSearchThreshold}getCodeModeOnly(){return this.toolMode===ToolMode.CodeModeOnly}getFreeform(){return this.freeform}getToolMode(){return this.toolMode}setDisabledTools(disabled){this.disabledTools=new Set(disabled)}getToolCallCommand(){return this.toolCallCommand}getMcpServerCommand(){return this.mcpServerCommand}mcpTransportPool;setMcpTransportPool(pool){this.mcpTransportPool=pool}getMcpTransportPool(){return this.mcpTransportPool}getSettingsMcpServers(){return this.mcpServers}getTopTierMcpServers(){return this.topTierMcpServers}getMergedMcpServers(includeBundledGeneratedUi=true){const mcpServers={...this.mcpServers||{}};const extensions=this.getActiveExtensions();for(const extension of extensions){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key])return;mcpServers[key]={...server,extensionName:extension.config.name}})}for(const[name2,cfg]of this.runtimeMcpServers){mcpServers[name2]=cfg}if(includeBundledGeneratedUi&&this.bundledGeneratedUiActive&&this.bundledGeneratedUi.server){mcpServers[BUNDLED_GENERATED_UI_SERVER]=this.bundledGeneratedUi.server}return mcpServers}rendersMcpApps(){return this.mcpAppHostSupported&&this.sessionSourceType!=="channel"}generatedUiUnavailableReason(){if(!this.bundledGeneratedUi.enabled)return"setting-disabled";if(!this.rendersMcpApps())return"unsupported-client";if(this.getBareMode()||this.isSafeMode()||this.sandbox||this.shellExecutionSandbox||this.executionEnvironment||this.sessionExecutionEngine==="managed"||this.provisionalWorkspace||this.getSessionSourceType()==="agent-host"){return"unsupported-runtime"}if(!this.isTrustedFolder())return"workspace-untrusted";if(this.bundledGeneratedUi.unavailableReason){return this.bundledGeneratedUi.unavailableReason}if(!this.bundledGeneratedUi.server||!this.bundledGeneratedUi.skillsDir){return"assets-missing"}if(this.topTierMcpServers?.[BUNDLED_GENERATED_UI_SERVER]||this.getMergedMcpServers(false)[BUNDLED_GENERATED_UI_SERVER]){return"provider-conflict"}const qualified=`mcp__${BUNDLED_GENERATED_UI_SERVER}__${BUNDLED_GENERATED_UI_TOOL}`;if(this.allowedMcpServers&&!matchesAnyServerPattern(BUNDLED_GENERATED_UI_SERVER,this.allowedMcpServers)||this.isMcpServerDisabled(BUNDLED_GENERATED_UI_SERVER)||this.isMcpServerPendingApproval(BUNDLED_GENERATED_UI_SERVER)||[...this.disabledTools].some(name2=>name2===BUNDLED_GENERATED_UI_TOOL||name2===qualified||normalizeMcpToolName(name2)===qualified)){return"policy-disabled"}return void 0}initializeBundledGeneratedUi(options2){const reason=this.bundledGeneratedUi.enabled&&this.rendersMcpApps()&&(options2?.disableBundledGeneratedUi||options2?.skipSkillManager)?"unsupported-runtime":this.generatedUiUnavailableReason();this.bundledGeneratedUiActive=reason===void 0;this.bundledGeneratedUiStatus={version:1,enabled:this.bundledGeneratedUiActive,...reason?{reason}:{}};if(reason&&reason!=="setting-disabled"&&reason!=="unsupported-client"&&this.bundledGeneratedUi.explicit){const warning=`Bundled Generated UI is unavailable (${reason}). Restart the owning session after resolving it.`;this.warnings.push(warning);this.debugLogger.warn(warning)}}getBundledGeneratedUiStatus(){if(!this.bundledGeneratedUiActive){return{...this.bundledGeneratedUiStatus}}const reason=this.generatedUiUnavailableReason();return reason?{version:1,enabled:false,reason}:{version:1,enabled:true}}getBundledGeneratedUiSkillsDir(){return this.getBundledGeneratedUiStatus().enabled?this.bundledGeneratedUi.skillsDir:void 0}isBundledGeneratedUiServer(serverName){return serverName===BUNDLED_GENERATED_UI_SERVER&&this.bundledGeneratedUiActive&&this.getMergedMcpServers()[serverName]===this.bundledGeneratedUi.server}assertGeneratedUiServerNotReplaced(servers){if(this.bundledGeneratedUiActive&&servers?.[BUNDLED_GENERATED_UI_SERVER]){throw new Error("Generated UI is already active as a bundled provider. Restart the owning session to configure a manual generated-ui server.")}}getMcpServers(){if(this.executionEnvironment||this.shellExecutionSandbox||this.sessionExecutionEngine==="managed"){return{}}let mcpServers=this.isSafeMode()?{...this.topTierMcpServers}:this.getMergedMcpServers();if(this.bundledGeneratedUiActive&&!this.getBundledGeneratedUiStatus().enabled){delete mcpServers[BUNDLED_GENERATED_UI_SERVER]}if(this.allowedMcpServers){mcpServers=Object.fromEntries(Object.entries(mcpServers).filter(([key])=>matchesAnyServerPattern(key,this.allowedMcpServers)))}return mcpServers}getExcludedMcpServers(){return this.excludedMcpServers}setExcludedMcpServers(excluded){this.excludedMcpServers=excluded}getMcpToolIdleTimeoutMs(){return this.mcpToolIdleTimeoutMs}isMcpServerDisabled(serverName){if(matchesAnyServerPattern(serverName,this.excludedMcpServers))return true;if(this.mcpServers?.[serverName])return false;for(const extension of this.getActiveExtensions()){if(extension.config.mcpServers?.[serverName]){return this.extensionManager?.getDisabledMcpServers(extension.config.name).includes(serverName)??false}}return false}isMcpServerPendingApproval(serverName){return this.pendingMcpServers?.includes(serverName)??false}approveMcpServerForSession(serverName){if(!this.pendingMcpServers){return}this.pendingMcpServers=this.pendingMcpServers.filter(name2=>name2!==serverName)}addMcpServers(servers){this.assertGeneratedUiServerNotReplaced(servers);if(this.shellExecutionSandbox&&Object.keys(servers).length)throw new Error("Tool execution sandbox does not support MCP servers.");if(this.initialized){throw new Error("Cannot modify mcpServers after initialization")}this.mcpServers={...this.mcpServers,...servers}}setMcpServers(servers){this.assertGeneratedUiServerNotReplaced(servers);if(this.shellExecutionSandbox&&Object.keys(servers??{}).length)throw new Error("Tool execution sandbox does not support MCP servers.");this.mcpServers=servers}setAllowedMcpServers(allowed){this.allowedMcpServers=allowed}getAllowedMcpServers(){return this.allowedMcpServers}getCliAllowedMcpServerNames(){return this.cliAllowedMcpServerNames}setPendingMcpServers(pending){this.pendingMcpServers=pending}getMcpGating(){return{excluded:this.excludedMcpServers,allowed:this.allowedMcpServers,pending:this.pendingMcpServers}}getRecentlyRemovedMcpServers(){return[...this.recentlyRemovedMcpServers]}getMcpServerNames(){return Object.keys(this.getMergedMcpServers())}getMcpServerUnavailableReason(serverName){if(this.recentlyRemovedMcpServers.has(serverName))return"removed";if(!(serverName in this.getMergedMcpServers()))return void 0;if(this.allowedMcpServers&&!matchesAnyServerPattern(serverName,this.allowedMcpServers)){return"not_allowed"}if(matchesAnyServerPattern(serverName,this.excludedMcpServers))return"excluded";if(this.isMcpServerPendingApproval(serverName))return"pending_approval";return void 0}async reinitializeMcpServers(servers){this.debugLogger.debug(`[mcp-hot-reload] reinitializeMcpServers: servers=[${Object.keys(servers??{}).join(", ")}] initialized=${this.initialized} inProgress=${this.mcpReconcileInProgress}`);const prevConfigured=new Set(Object.keys(this.getMergedMcpServers()));this.setMcpServers(servers);const nextConfigured=new Set(Object.keys(this.getMergedMcpServers()));for(const name2 of nextConfigured){this.recentlyRemovedMcpServers.delete(name2)}for(const name2 of prevConfigured){if(!nextConfigured.has(name2)){this.recentlyRemovedMcpServers.add(name2)}}await this.refreshMcpServers()}async refreshMcpServers(){if(this.shellExecutionSandbox||this.sessionExecutionEngine==="managed"){return}if(!this.initialized){this.debugLogger.debug("[mcp-hot-reload] not initialized yet \u2014 deferring to boot-time discovery (no-op)");return}if(this.mcpReconcileInProgress){this.mcpReconcilePending=true;this.debugLogger.debug("[mcp-hot-reload] reconcile already in flight \u2014 coalescing into a follow-up pass");return this.mcpReconcilePromise??Promise.resolve()}this.mcpReconcileInProgress=true;const registry3=this.getToolRegistry();const runReconcile=(async()=>{try{this.debugLogger.debug("[mcp-hot-reload] running incremental reconcile (pass 1)");await registry3.getMcpClientManager().discoverAllMcpToolsIncremental(this);let pass=1;while(this.mcpReconcilePending){this.mcpReconcilePending=false;pass+=1;this.debugLogger.debug(`[mcp-hot-reload] running coalesced incremental reconcile (pass ${pass})`);await registry3.getMcpClientManager().discoverAllMcpToolsIncremental(this)}this.debugLogger.debug(`[mcp-hot-reload] reconcile complete after ${pass} pass(es); live servers=[${Object.keys(this.getMcpServers()??{}).join(", ")}]`)}catch(err){this.debugLogger.error(`[mcp-hot-reload] reconcile failed: ${err instanceof Error?err.stack??err.message:String(err)}`);throw err}finally{this.mcpReconcileInProgress=false;this.mcpReconcilePending=false;this.mcpReconcilePromise=void 0}})();this.mcpReconcilePromise=runReconcile;await runReconcile}addRuntimeMcpServer(name2,config3){this.assertGeneratedUiServerNotReplaced({[name2]:config3});if(this.shellExecutionSandbox)throw new Error("Tool execution sandbox does not support MCP servers.");this.runtimeMcpServers.set(name2,config3)}getRuntimeMcpServers(){return Object.fromEntries(this.runtimeMcpServers)}removeRuntimeMcpServer(name2){return this.runtimeMcpServers.delete(name2)}isLspEnabled(){return this.lspEnabled&&!this.shellExecutionSandbox&&!this.getBareMode()&&!this.provisionalWorkspace}getLspClient(){return this.lspClient}getLspStatusSnapshot(){if(!this.isLspEnabled()){return this.createLspStatusSnapshot(false)}const clientSnapshot=this.lspClient?.getStatusSnapshot?.();if(clientSnapshot){return{...clientSnapshot,enabled:true,initializationError:this.lspInitializationError??clientSnapshot.initializationError}}if(this.lspClient){return{...this.createLspStatusSnapshot(true,this.lspInitializationError),statusUnavailable:true}}return this.createLspStatusSnapshot(true,this.lspInitializationError??"LSP client is not initialized")}createLspStatusSnapshot(enabled,initializationError){return{enabled,configuredServers:0,readyServers:0,failedServers:0,inProgressServers:0,notStartedServers:0,servers:[],...initializationError?{initializationError}:{}}}setLspClient(client){if(this.shellExecutionSandbox&&client)throw new Error("Tool execution sandbox does not support LSP.");if(this.initialized){throw new Error("Cannot set LSP client after initialization")}this.lspClient=client}setLspInitializationError(error3){if(this.initialized){throw new Error("Cannot set LSP status after initialization")}this.setRuntimeLspInitializationError(error3)}setRuntimeLspInitializationError(error3){this.lspInitializationError=error3 instanceof Error?error3.message:error3}async reinitializeLsp(){if(!this.isLspEnabled()||!this.lspClient?.reinitialize){return void 0}try{const result=await this.lspClient.reinitialize();if(result.reconcile.failed.length>0){this.setRuntimeLspInitializationError(`LSP reload partially failed: ${result.reconcile.failed.join(", ")}`)}else{this.setRuntimeLspInitializationError(void 0)}return result}catch(error3){this.setRuntimeLspInitializationError(error3 instanceof Error?error3:String(error3));throw error3}}getSessionSubagents(){return this.sessionSubagents}setSessionSubagents(subagents){if(this.initialized){throw new Error("Cannot modify sessionSubagents after initialization")}this.sessionSubagents=subagents}getSdkMode(){return this.sdkMode}setSdkMode(value){this.sdkMode=value}getUserMemory(){return this.userMemory}getStaticSystemPrefix(){return this.staticSystemPrefix}setStaticSystemPrefix(prefix2){this.staticSystemPrefix=prefix2}getPromptToolSnapshot(){return this.promptToolSnapshot}setPromptToolSnapshot(names){this.promptToolSnapshot=names}getPromptAgentReachable(){return this.promptAgentReachable}setPromptAgentReachable(reachable){this.promptAgentReachable=reachable}getAutoMemoryPrompt(){return this.autoMemoryPrompt}getAutoMemoryContext(){return this.memoryRecallMode==="legacy"&&this.getAutoMemoryPrompt()?this.autoMemoryContext:""}getMemoryRecallMode(){return this.memoryRecallMode}async prepareMemoryRecallTransition(){if(!this.getManagedAutoMemoryEnabled())return void 0;if(!this.getStructuredMemoryRecallEnabled())return void 0;if(this.memoryRecallMode==="structured")return void 0;const status=await this.scanMemoryRecallCorpusStatus();if(!status.ready){this.memoryCorpusRevision=status.revision;return void 0}const projectRoot=this.getProjectRoot();const teamEnabled=this.getTeamMemoryEnabled()&&this.isTrustedFolder();const configuredProjectRoot=getAutoMemoryRoot(projectRoot);await Promise.all([...getProjectMetadataMigrationRoots(projectRoot,this.isTrustedFolder()).map(root=>root===configuredProjectRoot?rebuildManagedAutoMemoryIndex(projectRoot):rebuildAutoMemoryIndexAtRoot(root,"project")),rebuildUserAutoMemoryIndex(),...teamEnabled?[rebuildTeamAutoMemoryIndex(projectRoot)]:[]].map(pending=>pending.catch(error3=>{this.debugLogger.debug(`Memory index rebuild failed during recall transition: ${error3 instanceof Error?error3.message:String(error3)}`)})));const autoMemoryPrompt=await buildStructuredAutoMemoryPrompt(getAutoMemoryRoot(projectRoot),getUserAutoMemoryRoot(),teamEnabled?getTeamAutoMemoryRoot(projectRoot):void 0);const confirmed=await this.scanMemoryRecallCorpusStatus();if(confirmed.revision!==status.revision)return void 0;return{from:"legacy",to:"structured",revision:confirmed.revision,autoMemoryPrompt,previousRevision:this.memoryCorpusRevision,previousAutoMemoryPrompt:this.autoMemoryPrompt}}async confirmMemoryRecallTransition(transition){if(transition.from!==this.memoryRecallMode)return false;const status=await this.scanMemoryRecallCorpusStatus();return status.revision===transition.revision&&(status.ready?"structured":"legacy")===transition.to}commitMemoryRecallTransition(transition){if(transition.from!==this.memoryRecallMode)return;this.memoryRecallMode=transition.to;this.memoryCorpusRevision=transition.revision;this.autoMemoryPrompt=transition.autoMemoryPrompt;this.memoryRecallModeInitialized=true}rollbackMemoryRecallTransition(transition){if(this.memoryRecallMode!==transition.to)return;this.memoryRecallMode=transition.from;this.memoryCorpusRevision=transition.previousRevision;this.autoMemoryPrompt=transition.previousAutoMemoryPrompt}scanMemoryRecallCorpusStatus(){return scanMemoryMetadataCorpusStatus({projectRoot:this.getProjectRoot(),teamMemoryEnabled:this.getTeamMemoryEnabled(),trustedProject:this.isTrustedFolder()})}getOutputLanguageFilePath(){return this.outputLanguageFilePath}setOutputLanguageFilePath(filePath){this.outputLanguageFilePath=filePath}setUserMemory(newUserMemory){this.userMemory=newUserMemory}getMemoryFileCount(){return this.memoryFileCount}setMemoryFileCount(count4){this.memoryFileCount=count4}getGeminiMdFileCount(){return this.getMemoryFileCount()}setGeminiMdFileCount(count4){this.setMemoryFileCount(count4)}getContextFilePaths(){return this.loadedContextFilePaths}setContextFilePaths(paths){this.loadedContextFilePaths=paths}getArenaManager(){return this.arenaManager}setArenaManager(manager){if(this.shellExecutionSandbox&&manager)throw new Error("Tool execution sandbox does not support agent arenas.");this.arenaManager=manager;this.arenaManagerChangeCallback?.(manager)}onArenaManagerChange(cb){this.arenaManagerChangeCallback=cb}getArenaAgentClient(){return this.arenaAgentClient}getAgentsSettings(){return this.agentsSettings}getTeamManager(){return this.teamManager}setTeamManager(manager){if(this.shellExecutionSandbox&&manager)throw new Error("Tool execution sandbox does not support agent teams.");this.teamManager=manager;for(const cb of this.teamManagerChangeCallbacks){cb(manager)}}onTeamManagerChange(cb,previous){if(previous){this.teamManagerChangeCallbacks.delete(previous)}if(cb){this.teamManagerChangeCallbacks.add(cb)}}getTeamContext(){return this.teamContext}setTeamContext(ctx){this.teamContext=ctx}async cleanupTeamRuntime(){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot clean up Team runtime")}const manager=this.teamManager;if(!manager){return}await manager.cleanup();this.setTeamManager(null);this.setTeamContext(null)}getWorktreeSymlinkDirectories(){return this.worktreeSettings.symlinkDirectories??[]}async cleanupArenaRuntime(force){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot clean up Arena runtime")}const manager=this.arenaManager;if(!manager){return}if(!force&&this.agentsSettings.arena?.preserveArtifacts){await manager.cleanupRuntime()}else{await manager.cleanup()}this.setArenaManager(null)}getApprovalMode(){return this.approvalMode}getSessionApprovalMode(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).getSessionApprovalMode()}return this.getApprovalMode()}getAutoModeSettings(){return this.permissionsAutoMode}getAutoModeDenialState(){return this.autoModeDenialState}setAutoModeDenialState(state){this.autoModeDenialState=state}getPrePlanMode(){return this.prePlanMode??"default"}getPlanExecutionMode(){return Object.hasOwn(this,"planExecutionMode")?this.planExecutionMode:void 0}setPlanMode(enabled,executionMode){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot change plan workflow mode")}if(executionMode==="plan"){throw new Error("Plan is not an execution approval mode")}if(this.isSessionAgentSession?.()===true&&executionMode!=="default"){throw new Error(SESSION_AGENT_APPROVAL_MODE_ERROR)}if(!this.isTrustedFolder()&&executionMode!=="default"){throw new TrustGateError("Cannot enable privileged approval modes in an untrusted folder.")}const previousMode=this.approvalMode;const previousExecutionMode=this.planExecutionMode;if(enabled)this.planExecutionMode=executionMode;try{this.setApprovalMode(enabled?"plan":executionMode)}catch(error3){this.planExecutionMode=previousExecutionMode;throw error3}if(enabled&&previousMode==="plan"&&previousExecutionMode!==executionMode){this.notifyApprovalModeChangeListeners()}}getApprovalModeRevision(){return this.approvalModeRevision}getManualPlanExitNoticeEventState(){if(!Object.prototype.hasOwnProperty.call(this,"manualPlanExitNoticeEventState")&&Object.prototype.hasOwnProperty.call(this,"approvalMode")){const inheritedEvent=this.manualPlanExitNoticeEventState;this.manualPlanExitNoticeEventState=inheritedEvent?{...inheritedEvent}:{version:0,kind:"clear"}}return this.manualPlanExitNoticeEventState}getOwnManualPlanExitNoticeCursorState(){if(!Object.prototype.hasOwnProperty.call(this,"manualPlanExitNoticeCursorState")){this.manualPlanExitNoticeCursorState={seenVersion:0}}return this.manualPlanExitNoticeCursorState}setApprovalMode(mode,options2){if(isDerivedConfig(this)&&!Object.prototype.hasOwnProperty.call(this,"setApprovalMode")){throw new Error("Derived Configs cannot change approval mode")}if(this.isSessionAgentSession?.()===true&&mode!=="default"&&mode!=="plan"){throw new Error(SESSION_AGENT_APPROVAL_MODE_ERROR)}if(!this.isTrustedFolder()&&mode!=="default"&&mode!=="plan"){throw new TrustGateError("Cannot enable privileged approval modes in an untrusted folder.")}const fromMode=this.approvalMode;if(this.permissionManager){if(mode==="auto"&&fromMode!=="auto"){this.permissionManager.stripDangerousRulesForAutoMode()}else if(fromMode==="auto"&&mode!=="auto"){this.permissionManager.restoreDangerousRules()}}let noticeEvent=_Config.prototype.getManualPlanExitNoticeEventState.call(this);if(!Object.prototype.hasOwnProperty.call(this,"approvalMode")){noticeEvent={...noticeEvent};this.manualPlanExitNoticeEventState=noticeEvent}if(mode==="plan"&&fromMode!=="plan"){if(!isDerivedConfig(this)){this.goalProposalApprovalController?.abort()}this.prePlanMode=fromMode;noticeEvent.version++;noticeEvent.kind="clear"}else if(mode!=="plan"&&fromMode==="plan"){this.prePlanMode=void 0;noticeEvent.version++;noticeEvent.kind=options2?.fromApprovedPlanExit||options2?.fromSessionRestore?"clear":"manual-exit";if(options2?.fromApprovedPlanExit&&Object.getPrototypeOf(this)===_Config.prototype){this.approveSessionWorkflowPlanRevision()}}if(fromMode!==mode){this.autoModeDenialState=resetDenialState();if(!isDerivedConfig(this)&&mode!=="plan"&&fromMode!=="plan"){clearSessionCommits()}}this.approvalMode=mode;if(mode!=="plan")this.planExecutionMode=void 0;if(fromMode!==mode){this.approvalModeRevision++;if(!isDerivedConfig(this)){this.notifyApprovalModeChangeListeners()}}}takePendingManualPlanExitNotice(){const event=_Config.prototype.getManualPlanExitNoticeEventState.call(this);const cursor=_Config.prototype.getOwnManualPlanExitNoticeCursorState.call(this);if(event.version<=cursor.seenVersion){return void 0}cursor.seenVersion=event.version;if(event.kind!=="manual-exit"||this.approvalMode==="plan"){return void 0}return{version:event.version,currentMode:this.approvalMode}}restorePendingManualPlanExitNotice(version4){const event=_Config.prototype.getManualPlanExitNoticeEventState.call(this);const cursor=_Config.prototype.getOwnManualPlanExitNoticeCursorState.call(this);if(event.version===version4&&event.kind==="manual-exit"&&this.approvalMode!=="plan"&&cursor.seenVersion===version4){cursor.seenVersion=Math.max(0,version4-1)}}consumePendingManualPlanExitNotice(){return _Config.prototype.takePendingManualPlanExitNotice.call(this)!==void 0}getPlansDir(){return this.plansDir}getPlansAnchorTargetDir(){if(Object.prototype.hasOwnProperty.call(this,"plansDirectoryConfigured")){return this.targetDir}let current2=Object.getPrototypeOf(this);while(current2!==null&&current2!==_Config.prototype){if(Object.prototype.hasOwnProperty.call(current2,"plansDirectoryConfigured")){return current2.targetDir}current2=Object.getPrototypeOf(current2)}return this.targetDir}assertPlansDirWithinTargetDir(){if(!this.plansDirectoryConfigured){return}Storage.assertPathWithinDirectory(this.plansDir,this.getPlansAnchorTargetDir(),`plansDirectory must resolve within the project root.`)}assertPlanFilePathWithinTargetDir(filePath){if(!this.plansDirectoryConfigured){return}Storage.assertPathWithinDirectory(filePath,this.getPlansAnchorTargetDir(),`plansDirectory must resolve within the project root.`)}addLegacyPlanLocationWarning(){try{if(!this.plansDirectoryConfigured){return}const legacyPlansDir=Storage.getPlansDir();const legacyPlanFiles=this.getPlanFileNames(legacyPlansDir);if(legacyPlanFiles.length===0){return}const configuredPlanFiles=new Set(this.getPlanFileNames(this.plansDir));const hiddenLegacyPlanFiles=legacyPlanFiles.filter(fileName=>!configuredPlanFiles.has(fileName));if(hiddenLegacyPlanFiles.length===0){return}this.warnings.push(`Warning: Saved plan files exist at ${legacyPlansDir}, but plansDirectory is configured to use ${this.plansDir}. Move existing plan files to ${this.plansDir} if you want to keep using them.`)}catch(err){const message=`Failed to check legacy plan directory migration warning: ${err instanceof Error?err.message:String(err)}`;this.warnings.push(message);this.debugLogger.warn(message,err)}}getPlanFileNames(plansDir){try{return fs80.readdirSync(plansDir).filter(entry=>entry.endsWith(".md"))}catch(err){const code=err.code;if(code==="ENOENT"){return[]}if(code==="EACCES"||code==="EPERM"){const message=`Failed to read plan directory ${plansDir}: ${err instanceof Error?err.message:String(err)}`;this.warnings.push(message);this.debugLogger.warn(message,err);return[]}throw err}}getPlanFilePath(){return path88.join(this.plansDir,`${Storage.sanitizePlanSessionId(this.sessionId)}.md`)}savePlan(plan){this.assertPlansDirWithinTargetDir();const filePath=this.getPlanFilePath();const dir=path88.dirname(filePath);fs80.mkdirSync(dir,{recursive:true});const tmpPath=filePath+".tmp";fs80.writeFileSync(tmpPath,plan,"utf-8");try{fs80.renameSync(tmpPath,filePath)}catch(err){if(err.code!=="EXDEV"){throw err}fs80.copyFileSync(tmpPath,filePath);fs80.unlinkSync(tmpPath)}try{this.assertPlanFilePathWithinTargetDir(filePath)}catch(err){try{fs80.unlinkSync(filePath)}catch{}throw err}}loadPlan(){this.assertPlansDirWithinTargetDir();const filePath=this.getPlanFilePath();this.assertPlanFilePathWithinTargetDir(filePath);try{return fs80.readFileSync(filePath,"utf-8")}catch(error3){if(typeof error3==="object"&&error3!==null&&"code"in error3&&error3.code==="ENOENT"){return void 0}throw error3}}getInputFormat(){return this.inputFormat}getIncludePartialMessages(){return this.includePartialMessages}getAccessibility(){return this.accessibility}getShowResponseTokensPerSecond(){return this.showResponseTokensPerSecond}getTelemetryEnabled(){return this.telemetrySettings.enabled??false}isTelemetryInitializationDeferred(){return this.telemetryInitializationDeferred}getTelemetryLogPromptsEnabled(){return this.telemetrySettings.logPrompts??true}getTelemetryUserId(){return this.telemetrySettings.userId}getTelemetryIncludeSensitiveSpanAttributes(){return this.telemetrySettings.includeSensitiveSpanAttributes??false}getTelemetrySensitiveSpanAttributeMaxLength(){return this.telemetrySettings.sensitiveSpanAttributeMaxLength}getTelemetryOtlpEndpoint(){return this.telemetrySettings.otlpEndpoint??DEFAULT_OTLP_ENDPOINT}getTelemetryOtlpProtocol(){return this.telemetrySettings.otlpProtocol??"grpc"}getTelemetryOtlpTracesEndpoint(){return this.telemetrySettings.otlpTracesEndpoint}getTelemetryOtlpLogsEndpoint(){return this.telemetrySettings.otlpLogsEndpoint}getTelemetryOtlpMetricsEndpoint(){return this.telemetrySettings.otlpMetricsEndpoint}getTelemetryTarget(){return this.telemetrySettings.target??DEFAULT_TELEMETRY_TARGET}getTelemetryResourceAttributes(){return this.telemetrySettings.resourceAttributes??{}}getTelemetryMetricsIncludeSessionId(){return this.telemetrySettings.metrics?.includeSessionId??false}getTelemetryResourceAttributeWarnings(){return this.telemetrySettings.resourceAttributeWarnings??[]}getOutboundCorrelationPropagateTraceContext(){return this.outboundCorrelationSettings.propagateTraceContext??false}getOutboundAllowDynamicHeaderValues(){return this.outboundCorrelationSettings.allowDynamicHeaderValues??false}getTelemetryOutfile(){return this.telemetrySettings.outfile}getGitCoAuthor(){return this.gitCoAuthor}getLlmClient(){return this.llmClient}getGeminiClient(){return this.getLlmClient()}getOwnActiveTodoReminders(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoReminders")){this.activeTodoReminders=new Map}return this.activeTodoReminders}getOwnActiveTodoWorkChainOwners(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoWorkChainOwners")){this.activeTodoWorkChainOwners=new Map}return this.activeTodoWorkChainOwners}getOwnActiveTodoReminderTurns(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoReminderTurns")){this.activeTodoReminderTurns=new Map}return this.activeTodoReminderTurns}getActiveTodoWorkChainOwner(promptId,fallbackOwner=promptId){return this.getOwnActiveTodoWorkChainOwners().get(promptId)??fallbackOwner}getActiveTodoReminder(promptId){return this.getOwnActiveTodoReminders().get(this.getActiveTodoWorkChainOwner(promptId))}getActiveTodoPlanWriterOwner(){return this.activeTodoPlanWriterOwner}recordActiveTodoPlanWriter(promptId){this.activeTodoPlanWriterOwner=this.getActiveTodoWorkChainOwner(promptId)}takeActiveTodoReminder(promptId,force=false){const owner=this.getActiveTodoWorkChainOwner(promptId);const reminder=this.getOwnActiveTodoReminders().get(owner);if(!reminder)return void 0;const turns=this.getOwnActiveTodoReminderTurns();const elapsed=(turns.get(owner)??0)+1;if(!force&&elapsed<ACTIVE_TODO_REMINDER_REFRESH_TURNS){turns.set(owner,elapsed);return void 0}turns.set(owner,0);return reminder}setActiveTodoReminder(promptId,reminder){const reminders=this.getOwnActiveTodoReminders();const owner=this.getActiveTodoWorkChainOwner(promptId);if(reminder){reminders.set(owner,reminder);this.getOwnActiveTodoReminderTurns().set(owner,0)}else{reminders.clear();this.getOwnActiveTodoReminderTurns().clear();this.activeTodoPlanWriterOwner=void 0}}startActiveTodoWorkChain(promptId,continuedFrom){const reminders=this.getOwnActiveTodoReminders();const owners=this.getOwnActiveTodoWorkChainOwners();if(!continuedFrom){reminders.clear();owners.clear();this.getOwnActiveTodoReminderTurns().clear();owners.set(promptId,promptId);return}const owner=this.getActiveTodoWorkChainOwner(continuedFrom);for(const reminderOwner of reminders.keys()){if(reminderOwner!==owner)reminders.delete(reminderOwner)}for(const[mappedPromptId,mappedOwner]of owners){if(mappedOwner!==owner)owners.delete(mappedPromptId)}owners.delete(continuedFrom);owners.set(promptId,owner)}startAutomaticActiveTodoWorkChain(promptId,continuedFrom){const reminders=this.getOwnActiveTodoReminders();const owners=this.getOwnActiveTodoWorkChainOwners();const owner=continuedFrom?this.getActiveTodoWorkChainOwner(continuedFrom):promptId;owners.set(promptId,owner);if(owner===promptId)reminders.delete(owner)}endAutomaticActiveTodoWorkChain(promptId){const owners=this.getOwnActiveTodoWorkChainOwners();const owner=this.getActiveTodoWorkChainOwner(promptId);owners.delete(promptId);if(![...owners.values()].includes(owner)){this.getOwnActiveTodoReminders().delete(owner)}}clearActiveTodoReminders(){this.getOwnActiveTodoReminders().clear();this.getOwnActiveTodoWorkChainOwners().clear();this.getOwnActiveTodoReminderTurns().clear();this.activeTodoPlanWriterOwner=void 0}getMemoryPressureMonitor(){if(!Object.prototype.hasOwnProperty.call(this,"memoryPressureMonitor")){const inheritedMonitor=this.memoryPressureMonitor;if(inheritedMonitor){const inheritedConfig=this.memoryPressureConfig;if(!inheritedConfig){throw new Error("Inherited memory pressure monitor is missing config")}this.memoryPressureConfig={...inheritedConfig};this.memoryPressureMonitor=new MemoryPressureMonitor(this,this.memoryPressureConfig)}}return this.memoryPressureMonitor}getCronScheduler(){if(!this.cronScheduler){this.cronScheduler=new CronScheduler(this.getProjectRoot(),this.getCronRecurringMaxAgeDays()*24*60*60*1e3,{runGate:createCronGateRunner(this)})}return this.cronScheduler}getCronRecurringMaxAgeDays(){return this.cronRecurringMaxAgeDays}isCronEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_DISABLE_CRON"]==="1")return false;return this.cronEnabled}isLsToolEnabled(){if(this.lsToolEnabled)return true;return this.getCoreTools()?.some(name2=>parseRule(name2).toolName===ToolNames.LS)??false}isTodoWriteEnabled(){return this.todoWriteEnabled}isAgentTeamEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_ENABLE_AGENT_TEAM"]==="1")return true;return this.agentTeamEnabled}isUnifiedAgentLoopEnabled(){if(process8.env["QWEN_CODE_ENABLE_UNIFIED_AGENT_LOOP"]==="1")return true;return this.unifiedAgentLoopEnabled}isAgentCollaborationEnabled(){if(process8.env["QWEN_CODE_ENABLE_AGENT_COLLABORATION"]==="1"){return true}return this.agentCollaborationEnabled}isArtifactEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_DISABLE_ARTIFACT"]==="1")return false;if(this.sdkMode)return false;if(!this.interactive&&!this.isArtifactSnapshotsEnabled())return false;if(process8.env["QWEN_CODE_ENABLE_ARTIFACT"]==="1")return true;return this.artifactEnabled}sessionSourceService;sessionSourceServiceFactory;setSessionSourceServiceFactory(factory){this.sessionSourceServiceFactory=factory;this.sessionSourceService=factory()}getSessionSourceService(){return Object.hasOwn(this,"sessionSourceService")?this.sessionSourceService:void 0}isRecordArtifactEnabled(){if(process8.env["QWEN_CODE_DISABLE_ARTIFACT"]==="1")return false;if(this.sdkMode)return false;if(process8.env["QWEN_CODE_ENABLE_ARTIFACT"]==="1")return true;return this.artifactEnabled}getArtifactPublisherKind(){return this.artifactPublisher}isArtifactSnapshotsEnabled(){return this.artifactSnapshotsEnabled&&this.chatRecordingEnabled}setArtifactSnapshotsEnabled(enabled){this.artifactSnapshotsEnabled=enabled}getArtifactHostConfig(){return this.artifactHost}getArtifactOssConfig(){return this.artifactOss}isOmniEnabled(){if(this.bareMode)return false;if(process8.env["QWEN_CODE_ENABLE_OMNI"]==="1")return true;return this.omniEnabled}getOmniMaxUploadFileBytes(){return this.omniMaxUploadFileBytes}getOmniMaxEstimatedTokens(){return this.omniMaxEstimatedTokens}getOmniMaxDurationSeconds(){return this.omniMaxDurationSeconds}getOmniUrlDownloadMaxFileBytes(){return this.omniUrlDownloadMaxFileBytes}getOmniUploadUrlTtlHours(){return this.omniUploadUrlTtlHours}getOmniUploadConfig(){return this.omniUploadConfig}getOmniPolicyToolsSettings(){return this.omniPolicyTools}async loadOmniMediaReader(){return import("./omni-I5YECZBW.js")}getOmniProcessingConfig(){return this.omniProcessingConfig}getOmniMemoryConfig(){return this.omniMemoryConfig}async ensureOmniMemoryConfig(){if(!this.omniMemoryConfig){const{normalizeOmniMemoryConfig}=await import("./config-NOIFIDXC.js");this.omniMemoryConfig=normalizeOmniMemoryConfig(this.omniMemory)}return this.omniMemoryConfig}getOmniMediaResourceRegistry(){this.omniMediaResourceRegistry??=new MediaResourceRegistry;return this.omniMediaResourceRegistry}getOmniQuarantineRetentionDays(){const days=this.omniQuarantineRetentionDays;return typeof days==="number"&&Number.isFinite(days)&&days>0?days:7}getOmniQuarantineMaxBytes(){const bytes=this.omniQuarantineMaxBytes;return typeof bytes==="number"&&Number.isFinite(bytes)&&bytes>0?bytes:5*1024*1024*1024}getOmniStorageRetentionDays(){const days=this.omniStorageRetentionDays;return typeof days==="number"&&Number.isFinite(days)&&days>=1?days:14}getOmniStorageMaxTotalBytes(){const bytes=this.omniStorageMaxTotalBytes;return typeof bytes==="number"&&Number.isFinite(bytes)&&bytes>0?bytes:20*1024*1024*1024}resolveImageGenerationModel(setting){const parsedSetting=parseVisionModelSetting(setting);if(!parsedSetting)return void 0;let selector;try{selector=resolveModelId(parsedSetting.selector)}catch{return void 0}if(!selector)return void 0;const routeMatches=this.getAllConfiguredModels().filter(model=>isImageGenerationCapable(model)&&!model.fastOnly&&!model.voiceOnly&&model.id===selector.modelId&&(!selector.authType||model.authType===selector.authType)&&(!parsedSetting.baseUrl||model.baseUrl===parsedSetting.baseUrl));if(routeMatches.length!==1)return void 0;const match=routeMatches[0];const apiKeyEnv=match.envKey?.trim();const configuredBaseUrl=match.registryBaseUrl?.trim();if(!apiKeyEnv||!configuredBaseUrl)return void 0;const baseUrl=normalizeImageGenerationBaseUrl(parsedSetting.baseUrl??configuredBaseUrl);if(!baseUrl)return void 0;return{model:match.id,baseUrl,apiKeyEnv}}getImageGenerationConfig(){if(this.bareMode||this.safeMode)return void 0;return this.resolveImageGenerationModel(this.imageModel)}isImageGenerationEnabled(){if(this.shellExecutionSandbox)return false;return this.getImageGenerationConfig()!==void 0}shouldAutoOpenArtifact(){if(this.isArtifactSnapshotsEnabled())return false;if(process8.env["QWEN_ARTIFACT_NO_AUTO_OPEN"]==="1")return false;return this.artifactAutoOpen&&!this.isBrowserLaunchSuppressed()}isWorkflowsEnabled(){if(this.shellExecutionSandbox)return false;if(this.provisionalWorkspace)return false;if(process8.env["QWEN_CODE_DISABLE_WORKFLOWS"]==="1")return false;if(process8.env["QWEN_CODE_ENABLE_WORKFLOWS"]==="1")return true;return this.workflowsEnabled??false}setWorkflowsEnabled(enabled){this.workflowsEnabled=enabled;this.refreshWorkflowMode()}isWorkflowModeSupported(){return!isDerivedConfig(this)&&this.chatRecordingEnabled&&this.sessionExecutionEngine!=="managed"&&!this.executionEnvironment&&this.sessionSourceType!=="agent"&&this.sessionSourceType!=="agent-host"&&!this.shutdownRequested&&!this.sessionWriterShutdownRequested}getWorkflowMode(){if(!this.isWorkflowModeSupported()){return{requested:false,available:false,effective:false,reason:"unsupported"}}const requested=this.workflowModeContext.getRequested();if(!this.workflowModeReady){return{requested,available:false,effective:false,reason:"initializing"}}let available=false;try{available=resolveWorkflowContext(this)!==null}catch{}return{requested,available,effective:requested&&available,...!available?{reason:"workflow_unavailable"}:{}}}stageInitialWorkflowMode(enabled){if(typeof enabled!=="boolean"){throw new Error("Workflow mode must be a boolean")}if(!this.isWorkflowModeSupported()){throw new Error("Workflow mode is unsupported for this session")}if(this.initialized){throw new Error("Initial workflow mode must be staged before initialization")}if(this.initialWorkflowMode!==void 0&&this.initialWorkflowMode!==enabled){throw new Error("Conflicting initial workflow mode values")}this.initialWorkflowMode=enabled}async setWorkflowMode(enabled){if(typeof enabled!=="boolean"){throw new Error("Workflow mode must be a boolean")}if(!this.isWorkflowModeSupported()){throw new Error("Workflow mode is unsupported for this session")}if(getInvocationContext()?.workflowModeWriteAllowed===false){throw new Error("Workspace is not trusted.")}if(!this.workflowModeReady){throw new Error("Workflow mode is not initialized")}if(this.getLlmClient().isTelemetrySwapInProgress()){throw new Error("A session switch is in progress. Try again in a moment.")}const epoch=this.workflowModeEpoch;const recorder=this.chatRecordingService;const write=this.workflowModeWriteTail.then(async()=>{if(epoch!==this.workflowModeEpoch||recorder!==this.chatRecordingService||!this.isWorkflowModeSupported()){throw new Error("Workflow mode session changed")}const state=this.getWorkflowMode();if(enabled&&!state.available){throw new Error("Workflow mode is unavailable in this session")}if(!recorder)throw new SessionWriterUnavailableError;await recorder.recordSessionWorkflowMode(enabled);if(epoch!==this.workflowModeEpoch||recorder!==this.chatRecordingService||!this.isWorkflowModeSupported()){throw new Error("Workflow mode session changed")}const changed=!this.workflowModeContext.hasRecord()||this.workflowModeContext.getRequested()!==enabled;this.workflowModeContext.setRequested(enabled);if(changed)this.workflowModePublishedState=void 0;this.refreshWorkflowMode();return this.getWorkflowMode()});this.workflowModeWriteTail=write.then(()=>void 0,()=>void 0);return write}onWorkflowModeChange(listener){if(!this.isWorkflowModeSupported())return()=>{};this.workflowModeListeners.add(listener);return()=>this.workflowModeListeners.delete(listener)}refreshWorkflowMode(){if(isDerivedConfig(this))return;const state=Object.freeze(this.getWorkflowMode());this.workflowModeContext.observeAvailability(state.available);const previous=this.workflowModePublishedState;this.workflowModePublishedState=state;if(previous?.requested===state.requested&&previous.available===state.available&&previous.reason===state.reason){return}for(const listener of this.workflowModeListeners){try{listener(state)}catch(error3){this.debugLogger.warn("Workflow mode listener failed:",error3)}}}resetWorkflowModeContext(){if(this.isWorkflowModeSupported()){this.workflowModeContext.resetContext()}}hasWorkflowModeContext(){return this.isWorkflowModeSupported()&&this.workflowModeContext.hasContext()}async captureWorkflowModeState(){await this.workflowModeWriteTail;return this.isWorkflowModeSupported()?this.workflowModeContext.snapshot():new WorkflowModeContext().snapshot()}restoreWorkflowModeState(snapshot){if(!this.isWorkflowModeSupported())return;this.workflowModeEpoch++;this.workflowModeContext.restoreSnapshot(snapshot);this.chatRecordingService?.restoreSessionWorkflowMode(snapshot.recorded?snapshot.requested:void 0);this.workflowModeContext.resetContext();this.refreshWorkflowMode()}prepareWorkflowMode(keyword){if(!this.isWorkflowModeSupported()||!this.workflowModeReady){return{reminder:keyword?.reminder}}this.refreshWorkflowMode();let context2=null;try{context2=resolveWorkflowContext(this)}catch{}return this.workflowModeContext.prepare(context2,keyword)}getWorkflowKeywordTriggerEnabled(){return this.workflowKeywordTriggerEnabled}setWorkflowKeywordTriggerEnabled(enabled){this.workflowKeywordTriggerEnabled=enabled}async enableReviewWorkflow(){if(this.shellExecutionSandbox||this.workflowsEnabled===false||!isTopLevelSession()||this.getBareMode()||this.provisionalWorkspace||process8.env["QWEN_CODE_DISABLE_WORKFLOWS"]==="1"){return}if(await this.registerWorkflowTool(this.getToolRegistry())){this.setWorkflowsEnabled(true);await this.getLlmClient().setTools()}}isSessionWorkflowEnabled(){if(this.shellExecutionSandbox)return false;return this.sessionWorkflowEnabledProvider?.()??this.sessionWorkflowEnabled}setSessionWorkflowEnabledProvider(provider){this.sessionWorkflowEnabledProvider=provider;if(!this.isSessionWorkflowEnabled()){this.sessionWorkflowPlanRevision=void 0}}setExternalAgentExecutor(executor){this.externalAgentExecutor=executor}getExternalAgentExecutor(){return this.externalAgentExecutor}getAgentExecutionBackend(){return this.agentExecutionBackend}getExecutionEnvironmentFactory(){return this.shutdownRequested||this.executionShutdown.signal.aborted?void 0:this.executionEnvironmentFactory}getExecutionEnvironment(){return this.executionEnvironment}shutdownExecutionEnvironments(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).shutdownExecutionEnvironments()}this.executionShutdown.abort();if(this.executionCleanupPromise)return this.executionCleanupPromise;const cleanup=Promise.allSettled([...this.executionEnvironments??[]].map(async pending=>{let environment;try{environment=await pending}catch(error3){if(error3 instanceof ExecutionCleanupError){if(!error3.retryCleanup)throw error3;await error3.retryCleanup()}this.executionEnvironments?.delete(pending);return}await environment.dispose();this.executionEnvironments?.delete(pending)})).then(results=>{const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw new AggregateError(errors,errors.map(String).join("; "))});let timer;this.executionCleanupPromise=new Promise((resolve36,reject)=>{timer=setTimeout(()=>reject(new ExecutionCleanupError(`Container cleanup is still pending for workspace ${this.getWorkingDir()}. Keep its workspace and inspect qwen-agent-* containers and qwen-agent-executor-* temporary directories before manual removal.`)),1e3);cleanup.then(resolve36,reject)}).catch(error3=>{console.warn(`Container execution cleanup incomplete: ${String(error3)}`);throw error3}).finally(()=>clearTimeout(timer));const clear=__name(()=>{this.executionCleanupPromise=void 0},"clear");void cleanup.then(clear,clear);return this.executionCleanupPromise}registerExecutionEnvironment(pending){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).registerExecutionEnvironment(pending)}this.executionEnvironments??=new Set;this.executionEnvironments.add(pending);return()=>this.executionEnvironments?.delete(pending)}getSessionWorkflowPlanRevision(){if(!this.isSessionWorkflowEnabled())return void 0;return this.sessionWorkflowPlanRevision}setSessionWorkflowPlanRevision(revision5){if(!this.isSessionWorkflowEnabled()||revision5===void 0||revision5.planId.trim()===""||revision5.sourceCallId.trim()===""){this.sessionWorkflowPlanRevision=void 0;return}const todoIds=Array.from(new Set(revision5.todoIds.filter(todoId=>typeof todoId==="string"&&todoId.trim()!=="")));this.sessionWorkflowPlanRevision=todoIds.length>0?{planId:revision5.planId,sourceCallId:revision5.sourceCallId,todoIds,...revision5.approved?{approved:true}:{}}:void 0}clearSessionWorkflowPlanRevision(){this.sessionWorkflowPlanRevision=void 0}approveSessionWorkflowPlanRevision(){const revision5=this.getSessionWorkflowPlanRevision();if(!revision5||revision5.approved)return;this.setSessionWorkflowPlanRevision({...revision5,approved:true})}isSessionWorkflowTodoContextActive(){return this.isSessionWorkflowEnabled()&&(this.approvalMode==="plan"||this.sessionWorkflowPlanRevision!==void 0)}getModelProposedGoals(){return this.modelProposedGoals}setMcpAppHostSupported(supported){this.mcpAppHostSupported=supported}setGoalProposalHostSupported(supported){this.goalProposalHostSupported=supported}getGoalProposalHostSupported(){return this.goalProposalHostSupported}setGoalProposalTurnKey(turnKey){if(this.goalProposalTurnKey===turnKey)return false;this.goalProposalTurnKey=turnKey;return true}isGoalProposalAvailable(){return resolveInteractionMode(this)==="interactive"||this.goalProposalHostSupported&&this.goalProposalTurnKey!==void 0}hasPendingGoalProposal(){return this.pendingGoalProposal!==void 0}setPendingGoalProposal(proposal){if(this.pendingGoalProposal)return false;this.goalProposalApprovalController=new AbortController;if(this.approvalMode==="plan"){this.goalProposalApprovalController.abort()}this.pendingGoalProposal={...proposal,approvalSignal:this.goalProposalApprovalController.signal};return true}takePendingGoalProposal(expectedTurnKey){const proposal=this.pendingGoalProposal;if(expectedTurnKey!==void 0&&proposal?.turnKey!==expectedTurnKey){return void 0}this.pendingGoalProposal=void 0;return proposal}getSkipWorkflowUsageWarning(){return this.skipWorkflowUsageWarning}getWorkflowSizeGuideline(){return resolveWorkflowSizeGuidelineSetting(this.workflowSizeGuideline)}isWorkflowNameOnly(){return this.workflowNameOnly}setWorkflowSizeGuideline(size){this.workflowSizeGuideline=isWorkflowSizeGuideline(size)?size:void 0}getEmitToolUseSummaries(){const env=process8.env["QWEN_CODE_EMIT_TOOL_USE_SUMMARIES"];if(env==="0"||env==="false")return false;if(env==="1"||env==="true")return true;return this.emitToolUseSummaries}getEnableRecursiveFileSearch(){return this.fileFiltering.enableRecursiveFileSearch}getFileFilteringEnableFuzzySearch(){return this.fileFiltering.enableFuzzySearch}getFileFilteringRespectGitIgnore(){return this.fileFiltering.respectGitIgnore}getFileFilteringRespectQwenIgnore(){return this.fileFiltering.respectQwenIgnore}getFileFilteringOptions(){return{respectGitIgnore:this.fileFiltering.respectGitIgnore,respectQwenIgnore:this.fileFiltering.respectQwenIgnore,customIgnoreFiles:[...this.fileFiltering.customIgnoreFiles]}}getCustomExcludes(){return[]}getFileCheckpointingEnabled(){return!this.shellExecutionSandbox&&this.fileCheckpointingEnabled}enableFileCheckpointing(){if(this.shellExecutionSandbox)throw new Error("File checkpointing is unavailable with tools.executionSandbox.");this.fileCheckpointingEnabled=true;this.fileHistoryService=void 0}getFileHistoryService(){if(!this.fileHistoryService){const service=new FileHistoryService(this.sessionId,this.getFileCheckpointingEnabled(),this.cwd,snapshot=>{if(this.fileHistoryService!==service)return;this.getChatRecordingService()?.recordFileHistorySnapshot(snapshot)});this.fileHistoryService=service;const snapshots=this.sessionData?.fileHistorySnapshots;if(snapshots?.length&&service.isEnabled()){service.restoreFromSnapshots(snapshots);void service.validateRestoredSnapshots().catch(e=>{this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${e}`)})}}return this.fileHistoryService}getProxy(){return normalizeProxyUrl(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){if(!this.fileDiscoveryService){this.fileDiscoveryService=new FileDiscoveryService(this.targetDir,this.fileFiltering.customIgnoreFiles)}return this.fileDiscoveryService}getUsageStatisticsEnabled(){return this.usageStatisticsEnabled}getExtensionRuleSources(){return this.getActiveExtensions().filter(extension=>Boolean(extension.path)).map(extension=>({name:extension.name,dir:path88.join(extension.path,"rules")}))}getExtensionContextFilePaths(){const extensionContextFilePaths=this.getActiveExtensions().flatMap(e=>e.contextFiles);return[...extensionContextFilePaths,...this.outputLanguageFilePath?[this.outputLanguageFilePath]:[]]}getExperimentalZedIntegration(){return this.experimentalZedIntegration}getRestoreAskUserQuestion(){return this.restoreAskUserQuestion}getPreserveRestorableAskUserQuestion(){return this.preserveRestorableAskUserQuestion}suppressRestorableAskUserQuestionPreservation(){this.preserveRestorableAskUserQuestion=false}isSessionWriterLeaseEnabled(){return this.sessionWriterLeaseEnabled}getListExtensions(){return this.listExtensions}getExtensionManager(){return this.extensionManager}getHookSystem(){if(this.shellExecutionSandbox)return void 0;return this.hookSystem}hasHooksForEvent(eventName,sessionId){return this.hookSystem?.hasHooksForEvent(eventName,sessionId??this.getSessionId())??false}getDisableAllHooks(){if(this.shellExecutionSandbox)return true;if(this.hookSystem?.isManaged())return false;return this.disableAllHooks||this.getBareMode()||this.isSafeMode()}getStopHookBlockingCap(){return this.stopHookBlockingCap}getManagedAutoMemoryEnabled(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoMemory&&!this.getBareMode()&&!this.isSafeMode()}getTeamMemoryEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.provisionalWorkspace){return false}const override=process8.env["QWEN_CODE_MEMORY_TEAM"];if(override==="0"){return false}if(override==="1"){return true}return this.enableTeamMemory}getTeamMemorySyncEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.provisionalWorkspace){return false}const override=process8.env["QWEN_CODE_MEMORY_TEAM_SYNC"];if(override==="0"){return false}if(override==="1"){return true}return this.enableTeamMemorySync}getStructuredMemoryRecallEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.isSafeMode())return false;const override=process8.env["QWEN_CODE_MEMORY_STRUCTURED_RECALL"];if(override==="0"){return false}if(override==="1"){return true}return this.enableStructuredMemoryRecall}isManagedMemoryAvailable(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoMemory&&!this.getBareMode()}getManagedAutoDreamEnabled(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoDream&&!this.getBareMode()&&!this.isSafeMode()}getAutoSkillEnabled(){if(this.shellExecutionSandbox)return false;return this.enableAutoSkill&&!this.getBareMode()&&!this.isSafeMode()&&!this.provisionalWorkspace}setAutoSkillEnabled(enabled){this.enableAutoSkill=enabled}getAutoSkillConfirmEnabled(){return this.autoSkillConfirm&&!this.getBareMode()}getMemoryAgentTimeoutMinutes(){return this.memoryAgentTimeoutMinutes}getMemoryAgentMaxTurns(){return this.memoryAgentMaxTurns}getPreventSystemSleepEnabled(){return this.preventSystemSleep&&!this.isSafeMode()}getMemoryManager(){return this.memoryManager}getMessageBus(){return this.messageBus}setMessageBus(messageBus){if(this.messageBus===messageBus){return}this.messageBus=messageBus;this.announceMessageBus(messageBus)}onMessageBusChange(listener){this.messageBusListeners.add(listener);if(this.messageBus){this.notifyMessageBusListener(listener,this.messageBus)}return()=>{this.messageBusListeners.delete(listener)}}notifyMessageBusListener(listener,bus){try{const result=listener(bus);if(result instanceof Promise){result.catch(error3=>{this.debugLogger.debug(`MessageBus observer failed: ${error3}`)})}}catch(error3){this.debugLogger.debug(`MessageBus observer failed: ${error3}`)}}announceMessageBus(bus){for(const listener of[...this.messageBusListeners]){this.notifyMessageBusListener(listener,bus)}}getProjectHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}if(!this.isTrustedFolder()){return void 0}const hooks=this.projectHooks??(this.hasScopedHooks()?void 0:this.hooks);return hooks}getUserHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}const hooks=this.userHooks??(this.hasScopedHooks()?void 0:this.hooks);return hooks}getSystemHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}return this.systemHooks}hasScopedHooks(){return this.systemHooks!==void 0||this.userHooks!==void 0||this.projectHooks!==void 0}setHooksFromSettings(hooks){this.systemHooks=hooks.systemHooks;this.userHooks=hooks.userHooks;this.projectHooks=hooks.projectHooks;this.hooks=hooks.hooks}getExtensions(){if(this.shellExecutionSandbox)return[];const extensions=this.extensionManager.getLoadedExtensions();if(this.overrideExtensions){const overrideExtensionNames=new Set(this.overrideExtensions.map(name2=>name2.toLowerCase()));return extensions.filter(e=>overrideExtensionNames.has(e.name.toLowerCase()))}else{return extensions}}getActiveExtensions(){return this.getExtensions().filter(e=>e.isActive)}getBlockedMcpServers(){const mcpServers={...this.mcpServers||{}};const extensions=this.getActiveExtensions();for(const extension of extensions){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key])return;mcpServers[key]={...server,extensionName:extension.config.name}})}const blockedMcpServers=[];if(this.allowedMcpServers){Object.entries(mcpServers).forEach(([key,server])=>{const isAllowed=matchesAnyServerPattern(key,this.allowedMcpServers);if(!isAllowed){blockedMcpServers.push({name:key,extensionName:server.extensionName||""})}})}return blockedMcpServers}getNoBrowser(){return this.noBrowser}isBrowserLaunchSuppressed(){return this.getNoBrowser()||!shouldAttemptBrowserLaunch()}getIdeMode(){return!this.shellExecutionSandbox&&this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}getAllowedHttpHookUrls(){return this.getBareMode()||this.isSafeMode()?[]:this.allowedHttpHookUrls}getAllowPrivateNetworkHooks(){return this.getBareMode()||this.isSafeMode()?false:this.allowPrivateNetworkHooks}isTrustedFolder(){const context2=ideContextStore.get();if(context2?.workspaceState?.isTrusted!==void 0){return context2.workspaceState.isTrusted}return this.trustedFolder??!this.folderTrust}setIdeMode(value){if(this.shellExecutionSandbox&&value)throw new Error("Tool execution sandbox does not support IDE integration.");this.ideMode=value}getAuthType(){return this.getContentGeneratorConfig()?.authType}getCliVersion(){return this.cliVersion}getChannel(){return this.channel}getJsonFd(){return this.jsonFd}getJsonFile(){return this.jsonFile}getJsonSchema(){return this.jsonSchema}getInputFile(){return this.inputFile}getDefaultFileEncoding(){return this.defaultFileEncoding}getFileSystemService(){return this.fileSystemService}setFileSystemService(fileSystemService){if(this.shellExecutionSandbox){throw new Error("Internal sandbox does not support delegated filesystem services.")}this.fileSystemService=fileSystemService}getChatCompression(){return this.chatCompression}getAutoCompactThreshold(){const threshold=this.autoCompactThreshold;if(typeof threshold==="number"&&threshold>0&&threshold<=1){return threshold}return void 0}isInteractive(){return this.interactive}async getTerminalImageRenderSupport(){return this.terminalImageRenderSupportProvider?this.terminalImageRenderSupportProvider():{available:false,reason:"No terminal image renderer is configured."}}getUseRipgrep(){return this.useRipgrep}getUseBuiltinRipgrep(){return this.useBuiltinRipgrep}getShouldUseNodePtyShell(){return this.shouldUseNodePtyShell}getSkipNextSpeakerCheck(){return this.skipNextSpeakerCheck}getShellExecutionConfig(){return this.shellExecutionConfig}setShellExecutionConfig(config3){this.shellExecutionConfig={terminalWidth:config3.terminalWidth??this.shellExecutionConfig.terminalWidth,terminalHeight:config3.terminalHeight??this.shellExecutionConfig.terminalHeight,showColor:config3.showColor??this.shellExecutionConfig.showColor,pager:Object.prototype.hasOwnProperty.call(config3,"pager")?config3.pager:this.shellExecutionConfig.pager,maxBufferedOutputBytes:config3.maxBufferedOutputBytes??this.shellExecutionConfig.maxBufferedOutputBytes}}getScreenReader(){return this.accessibility.screenReader??false}getSkipLoopDetection(){return this.skipLoopDetection}getLoopProtection(){return this.loopProtection}getMaxToolCallsPerTurn(){if(this.maxToolCallsPerTurn<=0){return Number.POSITIVE_INFINITY}return this.maxToolCallsPerTurn}isMaxToolCallsPerTurnExplicit(){return this.maxToolCallsPerTurnExplicit}getSkipStartupContext(){return this.skipStartupContext}getBareMode(){return this.bareMode}isSafeMode(){return this.safeMode}getTruncateToolOutputThreshold(){if(this.truncateToolOutputThreshold<=0){return Number.POSITIVE_INFINITY}return this.truncateToolOutputThreshold}isTruncateToolOutputThresholdExplicit(){return this.truncateToolOutputThresholdExplicit}getTruncateToolOutputLines(){if(this.truncateToolOutputLines<=0){return Number.POSITIVE_INFINITY}return this.truncateToolOutputLines}getShellDefaultTimeoutMs(){return this.shellDefaultTimeoutMs}getShellHeartbeatIntervalMs(){return this.shellHeartbeatIntervalMs}getToolOutputBatchBudget(){if(this.toolOutputBatchBudget<=0){return Number.POSITIVE_INFINITY}return this.toolOutputBatchBudget}trackToolResultBytes(n){this.toolResultBudget.bytesWritten+=n}getToolResultBytesWritten(){return this.toolResultBudget.bytesWritten}getOutputFormat(){return this.outputFormat}getChatRecordingService(){if(!this.chatRecordingEnabled){return void 0}if(!this.chatRecordingService){this.chatRecordingService=this.createChatRecordingService()}return this.chatRecordingService}getGoalRuntime(){if(!Object.hasOwn(this,"goalRuntime")||!this.chatRecordingEnabled||!this.chatRecordingService||!this.goalRuntime){throw new GoalPersistenceUnavailableError}return this.goalRuntime}async getGoalRuntimeReady(){const runtime=this.getGoalRuntime();if(!Object.hasOwn(this,"goalRuntimeReady")||!this.goalRuntimeReady){throw new GoalPersistenceUnavailableError}return this.goalRuntimeReady.then(()=>runtime)}async getGoalRuntimePrepared(){const runtime=this.getGoalRuntime();if(!this.sessionRestoreRuntime)return this.getGoalRuntimeReady();return runtime.getPreparedRestore().then(()=>runtime)}async rebaseGoalRuntimeFromActiveTranscript(){const runtime=this.getGoalRuntime();const recordingService=this.chatRecordingService;if(!recordingService){throw new GoalPersistenceUnavailableError}const records=await recordingService.readActiveTranscriptChain();this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;runtime.dispose();this.initializeGoalRuntime(records);await this.goalRuntimeReady}bindGoalTurnHost(host){if(!Object.hasOwn(this,"goalRuntime")){throw new GoalPersistenceUnavailableError}const generation2=this.goalTurnHostGeneration+1;this.goalTurnHostGeneration=generation2;this.goalTurnHostUnbind?.();this.goalTurnHost=host;this.goalTurnHostUnbind=this.goalRuntime?.bindHost(host);return()=>{if(this.goalTurnHostGeneration!==generation2||this.goalTurnHost!==host){return}this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.goalTurnHost=void 0}}onChatRecordingFailure(listener){this.chatRecordingFailureListeners.add(listener);return()=>{this.chatRecordingFailureListeners.delete(listener)}}onRequestLifecycle(listener){this.requestLifecycleListeners.add(listener);return()=>this.requestLifecycleListeners.delete(listener)}notifyRequestLifecycle(event){for(const listener of this.requestLifecycleListeners){try{listener(event)}catch(error3){this.debugLogger.warn("Request lifecycle listener failed:",error3)}}}createChatRecordingService(){return new ChatRecordingService(this,event=>{this.notifyChatRecordingFailure(event)},this.sessionWriterLeaseEnabled,this.sessionRestoreRuntime?.recording)}initializeGoalRuntime(records,restoreRuntime){this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Goal runtime replaced"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.settlePendingGoalRestore(new GoalPersistenceUnavailableError("Goal runtime was replaced before the session writer became available"));this.goalProposalApprovalController?.abort();this.goalProposalApprovalController=void 0;this.pendingGoalProposal=void 0;if(!this.chatRecordingService){this.goalRuntime=void 0;this.goalRuntimeReady=void 0;return}const recorder=this.chatRecordingService;const runtime=createGoalRuntime({journal:recorder,evidenceSource:recorder,ledger:recorder,verifier:createGoalVerifier(this),tokenBudgetGrant:this.goalTokenBudgetGrant,turnBudgetGrant:this.goalTurnBudgetGrant,activeTimeBudgetGrantMs:this.goalActiveTimeBudgetGrantMs});runtime.subscribe((snapshot,cause,meta4)=>{if(meta4?.replayed)return;const event=goalStateEventFromSnapshot(snapshot,cause);if(event)logGoalState(this,event)});this.goalRuntime=runtime;if(this.goalTurnHost){this.goalTurnHostUnbind=runtime.bindHost(this.goalTurnHost)}if(restoreRuntime){const preparation=runtime.prepareRestore(records??[]);let resolveActivation;let rejectActivation;const activation=new Promise((resolve36,reject)=>{resolveActivation=resolve36;rejectActivation=reject});this.rejectGoalRestoreActivation=rejectActivation;this.goalRestoreActivation=()=>{const started=runtime.activateRestoredWork();void started.then(resolveActivation,rejectActivation);return started};this.goalRuntimeReady=Promise.all([preparation,activation]).then(()=>runtime)}else if(this.sessionWriterLeaseEnabled&&!recorder.hasWriteOwnership()){const ready=new Promise((resolve36,reject)=>{this.pendingGoalRestore={runtime,resolve:resolve36,reject}});this.goalRuntimeReady=ready}else{this.goalRuntimeReady=runtime.restore(records??[]).then(()=>runtime)}void this.goalRuntimeReady.catch(()=>void 0)}startPendingGoalRestore(){const pending=this.pendingGoalRestore;if(!pending)return;this.pendingGoalRestore=void 0;if(pending.runtime!==this.goalRuntime){pending.reject(new GoalPersistenceUnavailableError("Goal runtime was replaced before the session writer became available"));return}void pending.runtime.restore(this.sessionData?.conversation.messages??[]).then(()=>pending.resolve(pending.runtime),error3=>pending.reject(error3))}settlePendingGoalRestore(error3){const pending=this.pendingGoalRestore;if(!pending)return;this.pendingGoalRestore=void 0;pending.reject(error3)}setSessionRestoreProjection(projection){this.pendingSessionRestoreProjection=projection;this.sessionRestoreRuntime=projection?.runtime;this.restoredFileHistory=false}clearSessionRestoreProjection(){this.pendingSessionRestoreProjection=void 0;this.sessionRestoreRuntime=void 0;this.restoredFileHistory=false;this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Session restore was abandoned"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0}notifyChatRecordingFailure(event){for(const listener of[...this.chatRecordingFailureListeners]){try{const notification=listener(event);if(notification){void notification.catch(error3=>{this.debugLogger.debug("Chat recording failure listener rejected:",error3)})}}catch(error3){this.debugLogger.debug("Chat recording failure listener threw:",error3)}}}getTranscriptPath(){if(!this.chatRecordingEnabled){return""}const projectDir=this.storage.getProjectDir();const sessionId=this.getSessionId();const safeFilename=`${sessionId}.jsonl`;return path88.join(projectDir,"chats",safeFilename)}async assertCanStartTurn(){if(isDerivedConfig(this))return;if(this.chatRecordingService?.hasWriteOwnership()){await this.chatRecordingService.assertCanStartTurn()}}hasSessionWriteOwnership(){if(isDerivedConfig(this))return false;return this.pendingSessionWriterLease!==void 0&&!this.pendingSessionWriterLease.isReleased||this.chatRecordingService?.hasWriteOwnership()===true}setSessionWriterReclaimPolicy(policy){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(this.initialized){throw new SessionWriterUnavailableError}this.sessionWriterReclaimPolicy=policy}setSessionWriterTakeoverPolicy(policy){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(this.initialized){throw new SessionWriterUnavailableError}this.sessionWriterTakeoverPolicy=policy}closeSessionWriter(options2){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(options2?.handoff&&this.sessionWriterTakeoverPolicy==="certified"){this.sessionWriterHandoffRequested=true}this.sessionWriterShutdownRequested=true;this.chatRecordingService?.beginClose({handoff:this.sessionWriterHandoffRequested});this.startPendingSessionWriterRelease();if(this.sessionWriterClosePromise)return this.sessionWriterClosePromise;const pending=this.closeSessionWriterOnce();this.sessionWriterClosePromise=pending;void pending.catch(()=>{if(this.sessionWriterClosePromise===pending){this.sessionWriterClosePromise=void 0}});return pending}async closeSessionWriterOnce(){const failures=[];const activation=this.sessionWriterActivationPromise;try{await activation}catch(error3){if(!(error3 instanceof SessionWriterShutdownError)){failures.push(error3)}}try{await this.chatRecordingService?.close({handoff:this.sessionWriterHandoffRequested})}catch(error3){failures.push(error3)}const pendingLease=activation?void 0:this.pendingSessionWriterLease;if(pendingLease){try{await this.startPendingSessionWriterRelease(pendingLease);if(this.pendingSessionWriterLease===pendingLease&&pendingLease.isReleased&&!pendingLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}}catch(error3){if(error3 instanceof SessionWriterLostError||pendingLease.isReleased&&!pendingLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}failures.push(error3)}finally{if(this.pendingSessionWriterRelease?.lease===pendingLease){this.pendingSessionWriterRelease=void 0}}}if(failures.length===1){throw failures[0]}if(failures.length>1){throw new AggregateError(failures,"Session writer shutdown failed")}}startPendingSessionWriterRelease(lease=this.pendingSessionWriterLease){if(!lease)return void 0;const existing=this.pendingSessionWriterRelease;if(existing?.lease===lease)return existing.promise;if(this.sessionExecutionEngine==="managed")return void 0;const promise=lease.release();this.pendingSessionWriterRelease={lease,promise};void promise.catch(()=>void 0);return promise}getSessionRuntimeBaseDir(){return this.sessionRuntimeBaseDir}getSessionService(){if(!this.sessionService){this.sessionService=new SessionService(this.storage.getProjectRoot(),{runtimeBaseDir:this.sessionRuntimeBaseDir})}return this.sessionService}getFileExclusions(){return this.fileExclusions}getSubagentManager(){return this.subagentManager}getBackgroundTaskRegistry(){return this.backgroundTaskRegistry}getMonitorRegistry(){return this.monitorRegistry}getBackgroundAgentResumeService(){if(!this.backgroundAgentResumeService){this.backgroundAgentResumeService=new BackgroundAgentResumeService(this)}return this.backgroundAgentResumeService}async loadPausedBackgroundAgents(sessionId=this.getSessionId()){if(sessionId!==this.getSessionId()){this.debugLogger.warn(`Refusing to restore background agents for non-current session ${sessionId}.`);return[]}const service=this.getBackgroundAgentResumeService();let recovered;try{recovered=await service.loadPausedBackgroundAgents(sessionId)}catch(error3){this.debugLogger.warn(`Background agent restore failed for session ${sessionId}; continuing without restored agents.`,error3);return[]}if(recovered.length>0&&!this.getBareMode()){this.pendingRecoveredAgentsNotice=service.buildRecoveredBackgroundAgentsModelNotice(recovered.length)}return recovered}consumePendingRecoveredAgentsNotice(){const notice=this.pendingRecoveredAgentsNotice;this.pendingRecoveredAgentsNotice=null;return notice}async resumeBackgroundAgent(agentId,initialInput){return this.getBackgroundAgentResumeService().resumeBackgroundAgent(agentId,initialInput)}async reviveCompletedBackgroundAgent(agentId,initialInput){return this.getBackgroundAgentResumeService().reviveCompletedBackgroundAgent(agentId,initialInput)}abandonBackgroundAgent(agentId){return this.getBackgroundAgentResumeService().abandonBackgroundAgent(agentId)}getBackgroundShellRegistry(){return this.backgroundShellRegistry}getWorkflowRunRegistry(){return this.workflowRunRegistry}getTurnBudget(){return this.turnBudget}getFileReadCache(){if(!Object.prototype.hasOwnProperty.call(this,"fileReadCache")){this.fileReadCache=new FileReadCache}return this.fileReadCache}getFileReadCacheDisabled(){return this.fileReadCacheDisabled}getShouldAvoidPermissionPrompts(){return false}getSkillManager(){return this.skillManager}setModelInvocableCommandsProvider(provider){this.modelInvocableCommandsProvider=provider}getModelInvocableCommandsProvider(){return this.modelInvocableCommandsProvider}setModelInvocableCommandsExecutor(executor){this.modelInvocableCommandsExecutor=executor}getModelInvocableCommandsExecutor(){return this.modelInvocableCommandsExecutor}addInlineAnnouncedSkillKeys(keys2){for(const k2 of keys2){this.pendingInlineAnnouncedSkillKeys.add(k2)}}consumeInlineAnnouncedSkillKeys(){const result=this.pendingInlineAnnouncedSkillKeys;this.pendingInlineAnnouncedSkillKeys=new Set;return result}getPermissionManager(){return this.permissionManager}isWorkspaceAgentSession(){return this.isAgentCollaborationEnabled()&&this.sessionSourceType==="agent"}getWorkflowAncestorTrustProvider(){return this.workflowAncestorTrustProvider}getToolInvocationGuard(){if(this.sessionSourceType==="agent-host"){return createAgentHostToolInvocationGuard(this.toolInvocationGuard,this.getTargetDir(),candidate=>this.getWorkspaceContext().isPathWithinWorkspace(candidate))}if(this.isWorkspaceAgentSession()&&this.isSessionAgentSession()){return createSessionAgentToolInvocationGuard(this.toolInvocationGuard,this.workspaceAgentExecutionAllowedTools,this.workspaceAgentDisallowedTools)}return this.isWorkspaceAgentSession()?createAgentToolInvocationGuard(this.toolInvocationGuard,this.workspaceAgentExecutionAllowedTools):this.toolInvocationGuard}getShellExecutionSandbox(){return this.shellExecutionSandbox}getOnPersistPermissionRule(){return this.onPersistPermissionRuleCallback}async registerLazyTool(registry3,toolName,factory){let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(toolName):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${toolName}", skipping registration:`,error3);return}if(status==="deferred"){registry3.registerPermissionDeferredFactory(toolName,factory)}else if(status==="registered"){registry3.registerFactory(toolName,factory)}}async registerManagedRuntimeTools(registry3){const environment=this.getManagedRuntimeEnvironment();if(!environment)return;const[{createExecutionTools},{wrapExecutionTool}]=await Promise.all([import("./local-execution-environment-S3OR4KSC.js"),import("./execution-tool-VR4TGOI4.js")]);const tools=createExecutionTools(this);for(const name2 of MANAGED_RUNTIME_TOOL_NAMES){const tool=tools.get(name2);if(!tool)continue;let status;try{status=await this.getPermissionManager()?.getToolRegistrationStatus(name2)??"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${name2}", skipping registration:`,error3);continue}if(status==="disabled")continue;registry3.registerRuntimeBackedFactory(name2,async()=>wrapExecutionTool(tool,environment,this),environment,status==="deferred")}}async registerWorkflowTool(registry3){if(registry3.getAllToolNames().includes(ToolNames.WORKFLOW))return true;await this.registerLazyTool(registry3,ToolNames.WORKFLOW,async()=>{const{WorkflowTool}=await import("./workflow-WBGPKVO6.js");return new WorkflowTool(this)});return registry3.getAllToolNames().includes(ToolNames.WORKFLOW)}async registerImageGenerationTool(registry3){if(!this.isImageGenerationEnabled()||registry3.getAllToolNames().includes(ToolNames.IMAGE_GEN)){return}let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(ToolNames.IMAGE_GEN):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${ToolNames.IMAGE_GEN}", skipping registration:`,error3);return}if(status==="disabled")return;const factory=__name(async()=>{const{ImageGenTool}=await import("./image-gen-BOKEFYWN.js");return new ImageGenTool(this)},"factory");if(status==="deferred"){registry3.registerPermissionDeferredFactory(ToolNames.IMAGE_GEN,factory)}else{registry3.registerFactory(ToolNames.IMAGE_GEN,factory)}}async syncAdvisorToolRegistration(registry3){if(!this.getAdvisorModel()||this.getBareMode()||this.isSafeMode()){registry3.unregisterTool(ToolNames.ADVISOR);return}if(this.getDisabledTools().has(ToolNames.ADVISOR))return;registry3.unregisterTool(ToolNames.ADVISOR);await this.registerLazyTool(registry3,ToolNames.ADVISOR,async()=>{const{AdvisorTool}=await import("./advisor-ANUGICJ5.js");return new AdvisorTool(this)});await registry3.ensureTool(ToolNames.ADVISOR)}async registerSessionSourceTool(registry3=this.toolRegistry){if(!this.getSessionSourceService()||this.sdkMode||this.getBareMode()||this.isSafeMode()||registry3.getAllToolNames().includes(ToolNames.RECORD_SOURCE)){return}let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(ToolNames.RECORD_SOURCE):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${ToolNames.RECORD_SOURCE}", skipping registration:`,error3);return}const factory=__name(async()=>{const{RecordSourceTool}=await import("./record-source-QJG4Q6UI.js");return new RecordSourceTool(this)},"factory");if(status==="deferred"){registry3.registerPermissionDeferredFactory(ToolNames.RECORD_SOURCE,factory)}else if(status==="registered"){registry3.registerFactory(ToolNames.RECORD_SOURCE,factory)}}async createToolRegistry(sendSdkMcpMessage,options2){const registry3=new ToolRegistry(this,this.eventEmitter,sendSdkMcpMessage);if(this.sessionExecutionEngine==="managed"){this.applyPendingMcpBudgetCallback(registry3);await this.registerManagedRuntimeTools(registry3);return registry3}const registerLazy=__name((toolName,factory)=>this.registerLazyTool(registry3,toolName,factory),"registerLazy");const registerStructuredOutputIfRequested=__name(async()=>{if(!this.jsonSchema)return;if(options2?.forSubAgent)return;const schema=this.jsonSchema;await registerLazy(ToolNames.STRUCTURED_OUTPUT,async()=>{const{SyntheticOutputTool}=await import("./syntheticOutput-M563X4NP.js");return new SyntheticOutputTool(schema)})},"registerStructuredOutputIfRequested");const registerGoalWorkerTools=__name(async()=>{if(options2?.forSubAgent)return;await registerLazy(ToolNames.GET_GOAL,async()=>{const{GetGoalTool:GetGoalTool2}=await import("./goal-tools-FFMAJW6V.js");return new GetGoalTool2(this)});await registerLazy(ToolNames.UPDATE_GOAL,async()=>{const{UpdateGoalTool:UpdateGoalTool2}=await import("./goal-tools-FFMAJW6V.js");return new UpdateGoalTool2(this)});if(this.getModelProposedGoals()!=="disabled"&&(resolveInteractionMode(this)==="interactive"||this.goalProposalHostSupported)){await registerLazy(ToolNames.PROPOSE_GOAL,async()=>{const{ProposeGoalTool:ProposeGoalTool2}=await import("./goal-tools-FFMAJW6V.js");return new ProposeGoalTool2(this)})}},"registerGoalWorkerTools");const registerExecIfEnabled=__name(async()=>{if(this.getToolMode()!==ToolMode.CodeModeOnly)return;await registerLazy(ToolNames.EXEC,async()=>{const{ExecTool}=await import("./exec-TBIZGHHK.js");return new ExecTool(this)})},"registerExecIfEnabled");const registerHostSessionTools=__name(async()=>{if(this.isTodoWriteEnabled()){await registerLazy(ToolNames.TODO_WRITE,async()=>{const{TodoWriteTool}=await import("./todoWrite-UELI33ZV.js");return new TodoWriteTool(this)})}await registerLazy(ToolNames.WEB_FETCH,async()=>{const{WebFetchTool}=await import("./web-fetch-AYOYV7R4.js");return new WebFetchTool(this)});const hasExplicitWebSearchBackend=!!this.webSearchSettings?.model?.trim()||!!this.webSearchSettings?.baseUrl;if(!this.getBareMode()&&!this.isSafeMode()&&this.webSearchSettings?.enabled!==false&&(this.webSearchSettings?.enabled===true||!hasExplicitWebSearchBackend)){const{evaluateWebSearchGate}=await import("./web-search-DAREKD3Z.js");const gate2=evaluateWebSearchGate(this);if(gate2.ok){await registerLazy(ToolNames.WEB_SEARCH,async()=>{const{WebSearchTool}=await import("./web-search-DAREKD3Z.js");return new WebSearchTool(this)})}else if(!gate2.silent&&!this.webSearchNoticeEmitted&&!options2?.forSubAgent){this.webSearchNoticeEmitted=true;this.warnings.push(gate2.notice)}}},"registerHostSessionTools");const environment=this.getExecutionEnvironment();if(environment){if(this.getCodeModeOnly()){throw new Error("Container execution cannot be combined with tools.codeModeOnly.")}const[{createExecutionTools},{wrapExecutionTool}]=await Promise.all([import("./local-execution-environment-S3OR4KSC.js"),import("./execution-tool-VR4TGOI4.js")]);for(const[name2,tool]of createExecutionTools(this)){if(environment.toolNames&&!environment.toolNames.has(name2))continue;if(name2===ToolNames.LS&&!this.isLsToolEnabled())continue;await registerLazy(name2,async()=>wrapExecutionTool(tool,environment,this))}await registerLazy(ToolNames.TOOL_CALL,async()=>{const{ToolCallTool:ToolCallTool2}=await import("./tool-call-UK56SWCT.js");return new ToolCallTool2(registry3)});await registerLazy(ToolNames.TOOL_SEARCH,async()=>{const{ToolSearchTool}=await import("./tool-search-OWPFLVV5.js");return new ToolSearchTool(this)});if(this.executionEnvironment&&!options2?.forSubAgent){await registerStructuredOutputIfRequested();await registerGoalWorkerTools();if(!this.getBareMode())await registerHostSessionTools()}return registry3}if(this.shellExecutionSandbox){await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-OLZVNTQZ.js");return new ShellTool2(this)});await registerLazy(ToolNames.TASK_STOP,async()=>{const{TaskStopTool}=await import("./task-stop-LPMYWUAI.js");return new TaskStopTool(this)});await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-63ZLWMOW.js");return new ReadFileTool(this)});await registerLazy(ToolNames.WRITE_FILE,async()=>{const{WriteFileTool}=await import("./write-file-EJNMAHQD.js");return new WriteFileTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-3HMQPCHN.js");return new EditTool(this)});await registerLazy(ToolNames.MONITOR,async()=>{const{MonitorTool:MonitorTool2}=await import("./monitor-U5E33JO6.js");return new MonitorTool2(this)});await registerLazy(ToolNames.AGENT,async()=>{const{AgentTool:AgentTool2}=await import("./agent-GNCQDICJ.js");return new AgentTool2(this)});await registerLazy(ToolNames.GLOB,async()=>{const{GlobTool}=await import("./glob-4Q6DCT3F.js");return new GlobTool(this)});await registerLazy(ToolNames.LS,async()=>{const{LSTool}=await import("./ls-ZVZ74DY3.js");return new LSTool(this)});if(resolveInteractionMode(this)!=="headless"){await registerLazy(ToolNames.ASK_USER_QUESTION,async()=>{const{AskUserQuestionTool:AskUserQuestionTool2}=await import("./askUserQuestion-GTSBJH2V.js");return new AskUserQuestionTool2(this)})}await registerExecIfEnabled();await registerStructuredOutputIfRequested();return registry3}if(this.getBareMode()){await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-63ZLWMOW.js");return new ReadFileTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-3HMQPCHN.js");return new EditTool(this)});await registerLazy(ToolNames.NOTEBOOK_EDIT,async()=>{const{NotebookEditTool}=await import("./notebook-edit-MXKD5J2C.js");return new NotebookEditTool(this)});await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-OLZVNTQZ.js");return new ShellTool2(this)});await registerGoalWorkerTools();await registerStructuredOutputIfRequested();await registerExecIfEnabled();this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry3.getAllToolNames())} (${registry3.getAllToolNames().length} tools)`);return registry3}await registerHostSessionTools();await registerExecIfEnabled();await registerGoalWorkerTools();await this.syncAdvisorToolRegistration(registry3);await registerLazy(ToolNames.TOOL_CALL,async()=>{const{ToolCallTool:ToolCallTool2}=await import("./tool-call-UK56SWCT.js");return new ToolCallTool2(registry3)});await registerLazy(ToolNames.TOOL_SEARCH,async()=>{const{ToolSearchTool}=await import("./tool-search-OWPFLVV5.js");return new ToolSearchTool(this)});await registerLazy(ToolNames.READ_MCP_RESOURCE,async()=>{const{ReadMcpResourceTool}=await import("./read-mcp-resource-XDV7EITL.js");return new ReadMcpResourceTool(this)});await registerLazy(ToolNames.AGENT,async()=>{const{AgentTool:AgentTool2}=await import("./agent-GNCQDICJ.js");return new AgentTool2(this)});await registerLazy(ToolNames.LIST_AGENTS,async()=>{const{ListAgentsTool}=await import("./list-agents-N7IJHQFA.js");return new ListAgentsTool(this)});await registerLazy(ToolNames.TASK_STOP,async()=>{const{TaskStopTool}=await import("./task-stop-LPMYWUAI.js");return new TaskStopTool(this)});await registerLazy(ToolNames.SEND_MESSAGE,async()=>{const{SendMessageTool}=await import("./send-message-J526AEBI.js");return new SendMessageTool(this)});if(!options2?.forSubAgent||this.getSkillManager()){await registerLazy(ToolNames.SKILL,async()=>{const{SkillTool}=await import("./skill-XW2AQS7M.js");return new SkillTool(this)})}if(this.isLsToolEnabled()){await registerLazy(ToolNames.LS,async()=>{const{LSTool}=await import("./ls-ZVZ74DY3.js");return new LSTool(this)})}await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-63ZLWMOW.js");return new ReadFileTool(this)});await registerLazy(ToolNames.MANAGE_MEMORY,async()=>{const{ManageMemoryTool}=await import("./manage-memory-JHTUVMDJ.js");return new ManageMemoryTool(this)});await registerLazy(ToolNames.SEARCH_MEMORY,async()=>{const{SearchMemoryTool}=await import("./search-memory-7I5MGDNV.js");return new SearchMemoryTool(this)});await registerLazy(ToolNames.ZOOM_IMAGE,async()=>{const{ZoomImageTool}=await import("./zoom-image-S3OARMYP.js");return new ZoomImageTool(this)});if(this.getUseRipgrep()){let useRipgrep=false;let errorString=void 0;recordStartupEvent("config_initialize_ripgrep_probe_start");try{useRipgrep=await canUseRipgrep(this.getUseBuiltinRipgrep())}catch(error3){errorString=getErrorMessage(error3)}recordStartupEvent("config_initialize_ripgrep_probe_end");if(useRipgrep){await registerLazy(ToolNames.GREP,async()=>{const{RipGrepTool}=await import("./ripGrep-7KBZGTPV.js");return new RipGrepTool(this)})}else{logRipgrepFallback(this,new RipgrepFallbackEvent(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),errorString||"ripgrep is not available"));await registerLazy(ToolNames.GREP,async()=>{const{GrepTool}=await import("./grep-ZPVNGCCV.js");return new GrepTool(this)})}}else{recordStartupEvent("config_initialize_ripgrep_probe_start");recordStartupEvent("config_initialize_ripgrep_probe_end");await registerLazy(ToolNames.GREP,async()=>{const{GrepTool}=await import("./grep-ZPVNGCCV.js");return new GrepTool(this)})}await registerLazy(ToolNames.GLOB,async()=>{const{GlobTool}=await import("./glob-4Q6DCT3F.js");return new GlobTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-3HMQPCHN.js");return new EditTool(this)});await registerLazy(ToolNames.NOTEBOOK_EDIT,async()=>{const{NotebookEditTool}=await import("./notebook-edit-MXKD5J2C.js");return new NotebookEditTool(this)});await registerLazy(ToolNames.WRITE_FILE,async()=>{const{WriteFileTool}=await import("./write-file-EJNMAHQD.js");return new WriteFileTool(this)});await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-OLZVNTQZ.js");return new ShellTool2(this)});await registerLazy(ToolNames.REPORT_FINDINGS,async()=>{const{ReportFindingsTool}=await import("./report-findings-W4ARGZWM.js");return new ReportFindingsTool});const supportsUserInteraction=resolveInteractionMode(this)!=="headless";if(supportsUserInteraction){await registerLazy(ToolNames.ASK_USER_QUESTION,async()=>{const{AskUserQuestionTool:AskUserQuestionTool2}=await import("./askUserQuestion-GTSBJH2V.js");return new AskUserQuestionTool2(this)})}if(!this.sdkMode&&(supportsUserInteraction||options2?.forSubAgent)){await registerLazy(ToolNames.EXIT_PLAN_MODE,async()=>{const{ExitPlanModeTool:ExitPlanModeTool2}=await import("./exitPlanMode-P25OHQJ6.js");return new ExitPlanModeTool2(this)})}if(!this.sdkMode&&supportsUserInteraction){await registerLazy(ToolNames.ENTER_PLAN_MODE,async()=>{const{EnterPlanModeTool}=await import("./enterPlanMode-QHJF4JXZ.js");return new EnterPlanModeTool(this)})}await registerLazy(ToolNames.ENTER_WORKTREE,async()=>{const{EnterWorktreeTool}=await import("./enter-worktree-TSLRJOZG.js");return new EnterWorktreeTool(this)});await registerLazy(ToolNames.EXIT_WORKTREE,async()=>{const{ExitWorktreeTool}=await import("./exit-worktree-MEZOFF3P.js");return new ExitWorktreeTool(this)});if(resolveInteractionMode(this)==="interactive"&&!this.sdkMode&&!this.getScreenReader()&&!options2?.forSubAgent){await registerLazy(ToolNames.DISPLAY_IMAGE,async()=>{const{DisplayImageTool}=await import("./display-image-U4X2TV4R.js");return new DisplayImageTool(this)})}await this.registerImageGenerationTool(registry3);if(this.isArtifactEnabled()){await registerLazy(ToolNames.ARTIFACT,async()=>{const{ArtifactTool}=await import("./artifact-tool-G6TRQYYK.js");return new ArtifactTool(this)})}if(!options2?.forSubAgent){await this.registerSessionSourceTool(registry3)}if(this.isRecordArtifactEnabled()){await registerLazy(ToolNames.RECORD_ARTIFACT,async()=>{const{RecordArtifactTool}=await import("./record-artifact-N7M6CSFX.js");return new RecordArtifactTool(this)})}if(this.isLspEnabled()&&this.getLspClient()){await registerLazy(ToolNames.LSP,async()=>{const{LspTool}=await import("./lsp-VOO45GZP.js");return new LspTool(this)})}await registerStructuredOutputIfRequested();if(this.isCronEnabled()){await registerLazy(ToolNames.CRON_CREATE,async()=>{const{CronCreateTool}=await import("./cron-create-C6JOFIU4.js");return new CronCreateTool(this)});await registerLazy(ToolNames.CRON_LIST,async()=>{const{CronListTool}=await import("./cron-list-6JBPGS4Y.js");return new CronListTool(this)});await registerLazy(ToolNames.CRON_DELETE,async()=>{const{CronDeleteTool}=await import("./cron-delete-RMOEXBIS.js");return new CronDeleteTool(this)});await registerLazy(ToolNames.LOOP_WAKEUP,async()=>{const{LoopWakeupTool}=await import("./loop-wakeup-AJTLMLRX.js");return new LoopWakeupTool(this)})}await registerLazy(ToolNames.AUTOFIX_PR,async()=>{const{AutofixPrTool}=await import("./autofix-pr-IR3DNZ7W.js");return new AutofixPrTool(this)});if(this.getSubSessionSpawner()){await registerLazy(ToolNames.CREATE_SUB_SESSION,async()=>{const{CreateSubSessionTool}=await import("./create-sub-session-XY6UOUPE.js");return new CreateSubSessionTool(this)})}if(this.isAgentTeamEnabled()){await registerLazy(ToolNames.TEAM_CREATE,async()=>{const{TeamCreateTool}=await import("./team-create-S5ZY2UMF.js");return new TeamCreateTool(this)});await registerLazy(ToolNames.TEAM_DELETE,async()=>{const{TeamDeleteTool}=await import("./team-delete-2VUNSDJ3.js");return new TeamDeleteTool(this)});await registerLazy(ToolNames.TEAM_PLAN_APPROVAL,async()=>{const{TeamPlanApprovalTool}=await import("./team-plan-approval-KX6RXEST.js");return new TeamPlanApprovalTool(this)});if(!options2?.forSubAgent){await registerLazy(ToolNames.REQUEST_SHUTDOWN,async()=>{const{RequestShutdownTool}=await import("./request-shutdown-WN34ZXP4.js");return new RequestShutdownTool(this)})}await registerLazy(ToolNames.TASK_CREATE,async()=>{const{TaskCreateTool}=await import("./task-create-KSKNIAXD.js");return new TaskCreateTool(this)});await registerLazy(ToolNames.TASK_UPDATE,async()=>{const{TaskUpdateTool}=await import("./task-update-56FYUVP5.js");return new TaskUpdateTool(this)});await registerLazy(ToolNames.TASK_LIST,async()=>{const{TaskListTool}=await import("./task-list-UGDFER45.js");return new TaskListTool(this)})}if(this.isWorkflowsEnabled()){await this.registerWorkflowTool(registry3)}if(this.isOmniEnabled()){const omniPolicyToolFactories=[[ToolNames.OMNI_DOWNSAMPLE_IMAGE,async()=>new(await import("./downsample-image-GY5NDTCO.js")).OmniDownsampleImageTool(this)],[ToolNames.OMNI_DOWNSCALE_VIDEO,async()=>new(await import("./downscale-video-PCKMG7RJ.js")).OmniDownscaleVideoTool(this)],[ToolNames.OMNI_DOWNSAMPLE_AUDIO,async()=>new(await import("./downsample-audio-PAAE5K4Y.js")).OmniDownsampleAudioTool(this)],[ToolNames.OMNI_EXTRACT_KEYFRAMES,async()=>new(await import("./extract-keyframes-3LZLRQ45.js")).OmniExtractKeyframesTool(this)],[ToolNames.OMNI_EXTRACT_AUDIO,async()=>new(await import("./extract-audio-CT3OOOAG.js")).OmniExtractAudioTool(this)],[ToolNames.OMNI_CLIP_VIDEO,async()=>new(await import("./clip-video-DIWZ7DQN.js")).OmniClipVideoTool(this)],[ToolNames.OMNI_CONVERT_IMAGE,async()=>new(await import("./convert-image-CJEQCVXW.js")).OmniConvertImageTool(this)],[ToolNames.OMNI_TRANSCRIBE_AUDIO,async()=>new(await import("./transcribe-audio-TPAYPRUE.js")).OmniTranscribeAudioTool(this)],[ToolNames.OMNI_CLIP_IMAGE,async()=>new(await import("./clip-image-2LRBIF7D.js")).OmniClipImageTool(this)],[ToolNames.OMNI_CLIP_AUDIO,async()=>new(await import("./clip-audio-5EGXYPZ4.js")).OmniClipAudioTool(this)],[ToolNames.OMNI_CAPTION_IMAGE,async()=>new(await import("./caption-image-4TSC2VJ6.js")).OmniCaptionImageTool(this)],[ToolNames.OMNI_CAPTION_AUDIO,async()=>new(await import("./caption-audio-VO3THSBI.js")).OmniCaptionAudioTool(this)],[ToolNames.OMNI_OCR_IMAGE,async()=>new(await import("./ocr-image-C477GNPR.js")).OmniOcrImageTool(this)],[ToolNames.OMNI_UNDERSTAND_VIDEO_SEGMENTS,async()=>new(await import("./understand-video-segments-UC7EIGH3.js")).OmniUnderstandVideoSegmentsTool(this)]];for(const[name2,factory]of omniPolicyToolFactories){await registerLazy(name2,factory)}const memoryConfig=await this.ensureOmniMemoryConfig();if(memoryConfig.recall.mode==="active"){await registerLazy(ToolNames.OMNI_RECALL_MEDIA_MEMORY,async()=>{const{OmniRecallMediaMemoryTool}=await import("./recall-media-memory-tool-Z4U5XDHQ.js");return new OmniRecallMediaMemoryTool(this)})}}await registerLazy(ToolNames.MONITOR,async()=>{const{MonitorTool:MonitorTool2}=await import("./monitor-U5E33JO6.js");return new MonitorTool2(this)});this.applyPendingMcpBudgetCallback(registry3);if(!options2?.skipDiscovery){await registry3.discoverAllTools()}this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry3.getAllToolNames())} (${registry3.getAllToolNames().length} tools)`);return registry3}applyPendingMcpBudgetCallback(registry3){if(!this.pendingMcpBudgetCallback)return;const mgr=registry3.getMcpClientManager();if(mgr&&typeof mgr.setOnBudgetEvent==="function"){mgr.setOnBudgetEvent(this.pendingMcpBudgetCallback)}this.pendingMcpBudgetCallback=void 0}setMcpBudgetEventCallback(cb){if(this.toolRegistry){const mgr=this.toolRegistry.getMcpClientManager?.();if(mgr&&typeof mgr.setOnBudgetEvent==="function"){mgr.setOnBudgetEvent(cb)}this.pendingMcpBudgetCallback=void 0;return}this.pendingMcpBudgetCallback=cb}subSessionSpawner;currentSessionScheduledTaskCreator;setSubSessionSpawner(spawner){this.subSessionSpawner=spawner}getSubSessionSpawner(){return this.subSessionSpawner}setCurrentSessionScheduledTaskCreator(creator){this.currentSessionScheduledTaskCreator=creator}getCurrentSessionScheduledTaskCreator(){return this.currentSessionScheduledTaskCreator}};function installSessionWorkflowRevisionWriteThrough(wrapper,base2){const ov=wrapper;ov.setSessionWorkflowPlanRevision=revision5=>{base2.setSessionWorkflowPlanRevision(revision5)};ov.clearSessionWorkflowPlanRevision=()=>{base2.clearSessionWorkflowPlanRevision()}}__name(installSessionWorkflowRevisionWriteThrough,"installSessionWorkflowRevisionWriteThrough");var debugLogger124=createDebugLogger("EXIT_PLAN_MODE");var exitPlanModeToolDescription=`Use this tool when you are in plan mode and have finished presenting your plan and are ready to code. This will prompt the user to exit plan mode.
2152
+ `);memoryPressureConfigLogger.warn(fallbackMsg);return{...DEFAULT_PRESSURE_CONFIG}}return config3}__name(loadMemoryPressureConfig,"loadMemoryPressureConfig");var DEFAULT_MAX_SUBAGENT_DEPTH=5;var MAX_SUBAGENT_DEPTH_LIMIT=100;function normalizeMaxSubagentDepth(value){return value==null||!Number.isFinite(value)?DEFAULT_MAX_SUBAGENT_DEPTH:Math.min(MAX_SUBAGENT_DEPTH_LIMIT,Math.max(1,Math.floor(value)))}__name(normalizeMaxSubagentDepth,"normalizeMaxSubagentDepth");function validateMaxSessionTurns(value){const resolved=value??-1;if(!Number.isInteger(resolved)){throw new FatalConfigError(`Invalid maxSessionTurns: must be an integer, got ${String(resolved)}`)}return resolved}__name(validateMaxSessionTurns,"validateMaxSessionTurns");function normalizeGoalTokenBudget(value){if(value===0||value===-1)return Number.POSITIVE_INFINITY;return isValidGoalTokenBudget(value)?value:GOAL_DEFAULT_TOKEN_BUDGET}__name(normalizeGoalTokenBudget,"normalizeGoalTokenBudget");var GOAL_TOKEN_BUDGET_CAP=10*GOAL_DEFAULT_TOKEN_BUDGET;function isValidGoalTokenBudget(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_TOKEN_BUDGET_CAP)}__name(isValidGoalTokenBudget,"isValidGoalTokenBudget");var GOAL_MAX_TURNS_CAP=1e4;var GOAL_MAX_ACTIVE_MINUTES_CAP=7*24*60;function isValidGoalMaxTurns(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_MAX_TURNS_CAP)}__name(isValidGoalMaxTurns,"isValidGoalMaxTurns");function normalizeGoalMaxTurns(value){if(!isValidGoalMaxTurns(value)||value===-1||value===0){return Number.POSITIVE_INFINITY}return value}__name(normalizeGoalMaxTurns,"normalizeGoalMaxTurns");function isValidGoalMaxActiveMinutes(value){return typeof value==="number"&&Number.isInteger(value)&&(value===-1||value>=0&&value<=GOAL_MAX_ACTIVE_MINUTES_CAP)}__name(isValidGoalMaxActiveMinutes,"isValidGoalMaxActiveMinutes");function normalizeGoalMaxActiveMinutes(value){if(!isValidGoalMaxActiveMinutes(value)||value===-1||value===0){return Number.POSITIVE_INFINITY}return value*6e4}__name(normalizeGoalMaxActiveMinutes,"normalizeGoalMaxActiveMinutes");function validateMaxToolCallsPerTurn(value){const resolved=value??DEFAULT_MAX_TOOL_CALLS_PER_TURN;if(!Number.isInteger(resolved)){throw new FatalConfigError(`Invalid maxToolCallsPerTurn: must be an integer, got ${String(resolved)}`)}return resolved}__name(validateMaxToolCallsPerTurn,"validateMaxToolCallsPerTurn");var MAX_MODEL_FALLBACKS=3;function normalizeModelFallbacks(raw){if(!raw||raw.length===0)return[];const seen=new Set;const result=[];for(const entry of raw){const trimmed=entry.trim();if(!trimmed||seen.has(trimmed))continue;seen.add(trimmed);result.push(trimmed);if(result.length>=MAX_MODEL_FALLBACKS)break}return result}__name(normalizeModelFallbacks,"normalizeModelFallbacks");function bareEnabledGrantWarnings(lists,skills,defaultOffNames=new Set){if(lists.enabled.size===0)return[];const registry3=new Set(skills.map(skill=>skill.name.trim().toLowerCase()));const registryNamesByAuthored=new Map;for(const skill of skills){const authored=authoredSkillName(skill).trim().toLowerCase();const registryName=skill.name.trim().toLowerCase();if(authored===registryName)continue;const group=registryNamesByAuthored.get(authored)??[];group.push(registryName);registryNamesByAuthored.set(authored,group)}const warnings=[];for(const[authored,registryNames]of registryNamesByAuthored){if(registry3.has(authored))continue;if(!lists.enabled.has(authored))continue;const plural=registryNames.length>1;const names=registryNames.map(name2=>`'${name2}'`).join(", ");const skillWord=plural?"skills":"skill";const hardNote=lists.hardDisabled.has(authored)?` A bare '${authored}' in skills.disabled also blocks ${plural?"them":"it"} under either spelling, so replacing the grant alone will not enable anything: remove that entry too.`:"";if(lists.defaultDisabled.has(authored)){const offNames=registryNames.filter(name2=>defaultOffNames.has(name2));const onNames=offNames.filter(name2=>lists.enabled.has(name2)&&!lists.hardDisabled.has(name2)&&!lists.hardDisabled.has(authored));const stillOff=offNames.filter(name2=>!onNames.includes(name2));if(stillOff.length){const offPlural=stillOff.length>1;const offList=stillOff.map(name2=>`'${name2}'`).join(", ");const hardQualified=stillOff.filter(name2=>lists.hardDisabled.has(name2));const qualifiedNote=hardQualified.length?` ${hardQualified.map(name2=>`'${name2}'`).join(", ")} in skills.disabled also blocks ${hardQualified.length>1?"them":"it"} under either spelling, so replacing the grant alone will not enable anything: remove ${hardQualified.length>1?"those entries":"that entry"} too.`:"";warnings.push(`Warning: skills.enabled and skills.defaultDisabled both list '${authored}' by bare name. The pair cancels the disablement but no longer enables the extension ${offPlural?"skills":"skill"} ${offList}, which ${offPlural?"default":"defaults"} off. Replace the bare '${authored}' with ${offList} in both skills.enabled and skills.defaultDisabled to enable ${offPlural?"them":"it"}.`+hardNote+qualifiedNote)}if(onNames.length){const onPlural=onNames.length>1;const onList=onNames.map(name2=>`'${name2}'`).join(", ");warnings.push(`Warning: skills.enabled and skills.defaultDisabled both list '${authored}' by bare name, but the qualified ${onPlural?"grants":"grant"} ${onList} in skills.enabled already ${onPlural?"enable":"enables"} ${onPlural?"them":"it"}, so the bare pair changes nothing. Replace the bare '${authored}' with ${onList} in both skills.enabled and skills.defaultDisabled to drop the dead entries.`)}continue}warnings.push(`Warning: skills.enabled lists '${authored}' by bare name, which no longer enables the extension ${skillWord} ${names}. Replace it with ${names}.`+hardNote)}return warnings}__name(bareEnabledGrantWarnings,"bareEnabledGrantWarnings");function bareDisablementBlocksQualifiedGrantWarnings(lists,disabledNames,skills){if(lists.enabled.size===0||disabledNames.size===0)return[];const warnings=[];for(const skill of skills){const authored=authoredSkillName(skill).trim().toLowerCase();const registryName=skill.name.trim().toLowerCase();if(authored===registryName)continue;if(!lists.enabled.has(registryName))continue;if(!disabledNames.has(authored))continue;if(lists.hardDisabled.has(authored)){const unlocked=[...new Set(skills.filter(other2=>{const name2=other2.name.trim().toLowerCase();return name2!==registryName&&(name2===authored||authoredSkillName(other2).trim().toLowerCase()===authored)}).map(other2=>other2.name.trim().toLowerCase()))];const names=__name(list2=>list2.map(name2=>`'${name2}'`).join(", "),"names");const reBlockable=unlocked.filter(name2=>name2!==authored);const notAlone=unlocked.filter(name2=>name2===authored);let sideEffect="";if(unlocked.length){sideEffect=` The removal also re-enables ${names(unlocked)}.`;if(reBlockable.length){sideEffect+=` Add ${names(reBlockable)} to skills.disabled to keep ${reBlockable.length>1?"them":"it"} blocked.`}if(notAlone.length){sideEffect+=` ${names(notAlone)} cannot be blocked on ${notAlone.length>1?"their":"its"} own while '${registryName}' stays enabled, because any entry matching ${names(notAlone)} also matches '${registryName}'.`}}warnings.push(`Warning: skills.enabled opts in '${registryName}' but '${authored}' in skills.disabled still blocks it \u2014 hard entries are never cancelled by skills.enabled. Remove '${authored}' from skills.disabled to enable the skill.`+sideEffect);continue}warnings.push(`Warning: skills.enabled opts in '${registryName}' but a bare '${authored}' entry still blocks it \u2014 disable entries match under either spelling; a skills.defaultDisabled entry is cancelled only by the identical spelling. Write '${registryName}' in both lists, or remove '${authored}'.`)}return warnings}__name(bareDisablementBlocksQualifiedGrantWarnings,"bareDisablementBlocksQualifiedGrantWarnings");function readMemoryPressureRatioEnv(envName,fallback){const raw=process8.env[envName];if(!raw){return fallback}const parsed=Number(raw);if(!Number.isFinite(parsed)){throw new Error(`${envName} must be a finite number`)}return parsed}__name(readMemoryPressureRatioEnv,"readMemoryPressureRatioEnv");var DEFAULT_BARE_CORE_TOOLS=[ToolNames.READ_FILE,ToolNames.EDIT,ToolNames.NOTEBOOK_EDIT,ToolNames.SHELL];var EMPTY_DISABLED_SKILL_NAMES=Object.freeze(new Set);var sessionEnvClaimed=false;var projectDirEnvClaimed=false;var modelEnvClaimed=false;function resolveSensitiveSpanAttributeMaxLength(value){if(value===void 0){return DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH}if(!isValidSensitiveSpanAttributeMaxLength(value)){throw new FatalConfigError(`Invalid telemetry.sensitiveSpanAttributeMaxLength: must be a positive integer no greater than ${SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT}, got ${String(value)}`)}return value}__name(resolveSensitiveSpanAttributeMaxLength,"resolveSensitiveSpanAttributeMaxLength");function resolveCronRecurringMaxAgeDays(setting){const env=process8.env["QWEN_CODE_CRON_MAX_AGE_DAYS"];const fromEnv=env!==void 0&&env.trim()!=="";const raw=fromEnv?Number(env):setting;if(raw===void 0||!Number.isFinite(raw)||raw<0){if(raw!==void 0){console.warn((fromEnv?`QWEN_CODE_CRON_MAX_AGE_DAYS="${env}" is invalid`:`cronRecurringMaxAgeDays=${setting} is invalid`)+`; recurring cron jobs will expire after the ${DEFAULT_RECURRING_MAX_AGE_DAYS}-day default.`)}return DEFAULT_RECURRING_MAX_AGE_DAYS}return normalizeRecurringMaxAge(raw,DEFAULT_RECURRING_MAX_AGE_DAYS)}__name(resolveCronRecurringMaxAgeDays,"resolveCronRecurringMaxAgeDays");var SessionWriterShutdownError=class extends SessionWriterUnavailableError{static{__name(this,"SessionWriterShutdownError")}};function containsErrorByIdentity(error3,candidate){return error3===candidate||error3 instanceof Error&&error3.cause instanceof AggregateError&&error3.cause.errors.includes(candidate)}__name(containsErrorByIdentity,"containsErrorByIdentity");var DERIVED_CONFIG=Symbol("derivedConfig");function isDerivedConfig(config3){return config3[DERIVED_CONFIG]===true}__name(isDerivedConfig,"isDerivedConfig");function deriveApprovalModeConfig(base2,mode,options2={}){const baseApprovalMode=base2.getApprovalMode();const initialMode=getTrustedDerivedApprovalMode(base2,mode);let autoOverrideAcquired=false;const acquireAutoOverride=__name(()=>{if(autoOverrideAcquired||base2.getApprovalMode()==="auto"){return}if(options2.hooks){autoOverrideAcquired=options2.hooks.acquireAutoApprovalOverride();return}base2.getPermissionManager?.()?.stripDangerousRulesForAutoMode();autoOverrideAcquired=true},"acquireAutoOverride");const releaseAutoOverride=__name(()=>{if(!autoOverrideAcquired)return;if(options2.hooks){options2.hooks.releaseAutoApprovalOverride()}else if(base2.getApprovalMode()!=="auto"){base2.getPermissionManager?.()?.restoreDangerousRules()}autoOverrideAcquired=false},"releaseAutoOverride");const derived=deriveConfig(base2,{getApprovalMode:Config.prototype.getApprovalMode});const state=derived;state.approvalMode=initialMode;state.prePlanMode=initialMode==="plan"?baseApprovalMode==="plan"?base2.getPrePlanMode():baseApprovalMode:void 0;state.approvalModeRevision=0;state.manualPlanExitNoticeEventState={...base2.manualPlanExitNoticeEventState??{version:0,kind:"clear"}};state.autoModeDenialState=createDenialState();Object.defineProperty(derived,"setApprovalMode",{value:__name((nextMode,setOptions2)=>{const beforeMode=derived.getApprovalMode();const hadOwnPermissionManager=Object.hasOwn(derived,"permissionManager");const ownPermissionManager=state.permissionManager;state.permissionManager=null;try{Config.prototype.setApprovalMode.call(derived,nextMode,setOptions2)}finally{if(hadOwnPermissionManager){state.permissionManager=ownPermissionManager}else{delete state.permissionManager}}const afterMode=derived.getApprovalMode();if(beforeMode!=="auto"&&afterMode==="auto"){acquireAutoOverride()}else if(beforeMode==="auto"&&afterMode!=="auto"){releaseAutoOverride()}},"value"),writable:true,configurable:true,enumerable:true});if(initialMode==="auto"&&base2.getApprovalMode()!=="auto"){acquireAutoOverride()}return{config:derived,cleanup:releaseAutoOverride}}__name(deriveApprovalModeConfig,"deriveApprovalModeConfig");function deriveAgentConfig(base2,workingDirectory,options2={}){const fileService=new FileDiscoveryService(workingDirectory,options2.customIgnoreFiles);const workspaceContext=new WorkspaceContext(workingDirectory);const derived=deriveConfig(base2,{getTargetDir:__name(()=>workingDirectory,"getTargetDir"),getCwd:__name(()=>workingDirectory,"getCwd"),getWorkingDir:__name(()=>workingDirectory,"getWorkingDir"),getProjectRoot:__name(()=>workingDirectory,"getProjectRoot"),getPlanFilePath:options2.getPlanFilePath,getFileService:__name(()=>fileService,"getFileService"),getWorkspaceContext:__name(()=>workspaceContext,"getWorkspaceContext")});const workspaceState=derived;workspaceState.targetDir=workingDirectory;workspaceState.cwd=workingDirectory;workspaceState.fileDiscoveryService=fileService;workspaceState.workspaceContext=workspaceContext;return{config:derived,fileService,workspaceContext}}__name(deriveAgentConfig,"deriveAgentConfig");function getTrustedDerivedApprovalMode(base2,requestedMode){if((!base2.isTrustedFolder()||base2.isSessionAgentSession?.()===true)&&requestedMode!=="default"&&requestedMode!=="plan"){return"default"}return requestedMode}__name(getTrustedDerivedApprovalMode,"getTrustedDerivedApprovalMode");function deriveWorktreeConfig(base2,worktreePath,options2={}){const fileService=new FileDiscoveryService(worktreePath,options2.customIgnoreFiles);const workspaceContext=new WorkspaceContext(worktreePath);const derived=deriveConfig(base2,{getTargetDir:__name(()=>worktreePath,"getTargetDir"),getCwd:__name(()=>worktreePath,"getCwd"),getWorkingDir:__name(()=>worktreePath,"getWorkingDir"),getProjectRoot:__name(()=>worktreePath,"getProjectRoot"),getFileService:__name(()=>fileService,"getFileService"),getWorkspaceContext:__name(()=>workspaceContext,"getWorkspaceContext")});const workspaceState=derived;workspaceState.targetDir=worktreePath;workspaceState.cwd=worktreePath;workspaceState.fileDiscoveryService=fileService;workspaceState.workspaceContext=workspaceContext;return derived}__name(deriveWorktreeConfig,"deriveWorktreeConfig");function deriveConfig(base2,overrides={}){const shellSandbox=base2.getShellExecutionSandbox?.();if(shellSandbox){for(const key of["getTargetDir","getCwd","getWorkingDir","getProjectRoot"]){assertShellSandboxCwd(shellSandbox,overrides[key]?.()??base2[key]())}}const derived=Object.create(base2);for(const key in overrides){if(!Object.hasOwn(overrides,key))continue;const override=overrides[key];if(override!==void 0){Object.defineProperty(derived,key,{value:override,writable:true,configurable:true,enumerable:true})}}Object.defineProperty(derived,DERIVED_CONFIG,{value:true});return derived}__name(deriveConfig,"deriveConfig");var Config=class _Config{static{__name(this,"Config")}shellExecutionSandbox;sessionId;sessionSourceType;sessionSourceId;sessionData;workflowModeContext=new WorkflowModeContext;initialWorkflowMode;workflowModeReady=false;workflowModeEpoch=0;workflowModeWriteTail=Promise.resolve();workflowModePublishedState;workflowModeListeners=new Set;pendingSessionRestoreProjection;sessionRestoreRuntime;sessionRestoreProjectionSource;sessionExecutionEngine;managedRuntimeEnvironmentFactory;managedRuntimeEnvironment;onManagedEngineQuarantine;managedRuntimeClosing;managedSessionBlock;restoredFileHistory=false;goalRestoreActivation;rejectGoalRestoreActivation;sessionRuntimeBaseDir;provisionalWorkspace;provisionalWorkspaceActivated=false;provisionalWorkspaceActivation;sessionProjectDirRegistered=false;pendingSessionWriterLease;managedSession;managedRuntimeOutcomes;pendingSessionWriterRelease;sessionWriterReclaimPolicy="local";sessionWriterTakeoverPolicy="never";sessionWriterShutdownRequested=false;sessionWriterHandoffRequested=false;sessionWriterActivationPromise;sessionWriterClosePromise;pendingStartupWorktreeNotice=null;pendingRecoveredAgentsNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;resourceRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry;monitorRegistry=new MonitorRegistry;backgroundAgentResumeService;backgroundShellRegistry=new BackgroundShellRegistry;workflowRunRegistry=new WorkflowRunRegistry;turnBudget=new TurnBudget;fileReadCache=new FileReadCache;extensionManager;skillManager=null;bundledGeneratedUi;bundledGeneratedUiActive=false;mcpAppHostSupported=false;bundledGeneratedUiStatus={version:1,enabled:false,reason:"setting-disabled"};permissionManager=null;toolInvocationGuard;workflowAncestorTrustProvider;modelInvocableCommandsProvider=null;modelInvocableCommandsExecutor=null;pendingInlineAnnouncedSkillKeys=new Set;fileSystemService;contentGeneratorConfig;contentGeneratorConfigSources={};contentGenerator;initialAuthType;initialResolvedAuthType;embeddingModel;modelsConfig;modelProvidersConfig;providerProtocolConfig;sandbox;targetDir;workspaceContext;debugMode;inputFormat;outputFormat;includePartialMessages;question;systemPrompt;workspaceAgentName;workspaceAgentExecutionAllowedTools;workspaceAgentDisallowedTools;sessionAgentSession=false;appendSystemPrompt;liveAppendSystemPrompt;outputStyle;coreTools;allowedTools;excludeTools;disabledSlashCommands;disabledSkillNamesProvider;enabledSkillNamesProvider;skillSettingsListsProvider;terminalImageRenderSupportProvider;disabledSkillLevels;customSkillDirs;disabledTools;visibleTools;eagerTools;toolSearchThreshold;toolMode;freeform;permissionsAllow;permissionsAsk;permissionsDeny;permissionsAutoMode;toolDiscoveryCommand;toolCallCommand;mcpServerCommand;mcpServers;recentlyRemovedMcpServers=new Set;topTierMcpServers;runtimeMcpServers=new Map;lspEnabled;lspClient;lspInitializationError;allowedMcpServers;cliAllowedMcpServerNames;excludedMcpServers;pendingMcpServers;mcpToolIdleTimeoutMs;mcpReconcileInProgress=false;mcpReconcilePending=false;mcpReconcilePromise;sessionSubagents;userMemory;staticSystemPrefix;promptToolSnapshot;promptAgentReachable=false;autoMemoryPrompt="";autoMemoryContext="";memoryRecallMode="legacy";memoryCorpusRevision="";memoryRecallModeInitialized=false;sdkMode;memoryFileCount;loadedContextFilePaths=[];conditionalRulesRegistry;contextRuleExcludes;approvalMode;prePlanMode;planExecutionMode;approvalModeRevision=0;manualPlanExitNoticeEventState={version:0,kind:"clear"};manualPlanExitNoticeCursorState={seenVersion:0};autoModeDenialState=createDenialState();accessibility;showResponseTokensPerSecond;telemetrySettings;telemetryInitializationDeferred;outboundCorrelationSettings;gitCoAuthor;usageStatisticsEnabled;fileReadCacheDisabled;activeTodoReminders=new Map;activeTodoWorkChainOwners=new Map;activeTodoReminderTurns=new Map;activeTodoPlanWriterOwner;llmClient;baseLlmClient;cronScheduler=null;fileFiltering;fileDiscoveryService=null;sessionService=void 0;chatRecordingService=void 0;goalRuntime;goalRuntimeReady;pendingGoalProposal;goalProposalApprovalController;pendingGoalRestore;goalTurnHost;goalTurnHostUnbind;goalTurnHostGeneration=0;chatRecordingFailureListeners=new Set;requestLifecycleListeners=new Set;fileCheckpointingEnabled;toolResultBudget={bytesWritten:0};fileHistoryService;proxy;cwd;explicitIncludeDirectories;bugCommand;outputLanguageFilePath;noBrowser;folderTrustFeature;folderTrust;ideMode;maxSessionTurns;goalTokenBudgetGrant;goalTurnBudgetGrant;goalActiveTimeBudgetGrantMs;maxSubagentDepth;maxWallTimeSeconds;maxToolCalls;clearContextOnIdle;sessionTokenLimit;listExtensions;overrideExtensions;cliVersion;runtimeStatusEnabled=false;sessionRegistryActive=false;sessionRegistered=false;sessionRegistrySlot=SHARED_RECORD_SLOT;experimentalZedIntegration=false;restoreAskUserQuestion=false;preserveRestorableAskUserQuestion=false;sessionWriterLeaseEnabled=false;cronEnabled=true;cronRecurringMaxAgeDays;lsToolEnabled=false;todoWriteEnabled=false;agentTeamEnabled=false;unifiedAgentLoopEnabled=false;agentCollaborationEnabled=false;artifactEnabled=true;artifactSnapshotsEnabled=false;artifactAutoOpen=true;artifactPublisher="local";artifactHost;artifactOss;omniEnabled=false;omniMaxUploadFileBytes;omniMaxEstimatedTokens;omniMaxDurationSeconds;omniUrlDownloadMaxFileBytes;omniUploadUrlTtlHours;omniUploadBaseUrl;omniUploadApiKeyEnv;omniUploadModel;omniUploadConfig;omniPolicyTools;omniFixedPolicies;omniTransportGuardPolicies;omniProcessingLimits;omniQuarantineRetentionDays;omniStorageRetentionDays;omniStorageMaxTotalBytes;omniQuarantineMaxBytes;omniMemory;omniProcessingConfig;omniMemoryConfig;omniMediaResourceRegistry;workflowsEnabled;workflowKeywordTriggerEnabled;sessionWorkflowEnabled;sessionWorkflowEnabledProvider;sessionWorkflowPlanRevision;externalAgentExecutor;agentExecutionBackend;executionEnvironmentFactory;executionEnvironment;executionEnvironments;executionShutdown=new AbortController;executionCleanupPromise;modelProposedGoals;goalProposalHostSupported=false;goalProposalTurnKey;skipWorkflowUsageWarning=false;workflowSizeGuideline;workflowNameOnly;emitToolUseSummaries=true;chatRecordingEnabled;loadMemoryFromIncludeDirectories=false;importFormat;chatCompression;autoCompactThreshold;interactive;trustedFolder;useRipgrep;useBuiltinRipgrep;shouldUseNodePtyShell;preventSystemSleep;skipNextSpeakerCheck;shellExecutionConfig;arenaManager=null;arenaManagerChangeCallback=null;arenaAgentClient;teamManager=null;teamManagerChangeCallbacks=new Set;teamContext=null;agentsSettings;worktreeSettings;skipLoopDetection;loopProtection;maxToolCallsPerTurn;maxToolCallsPerTurnExplicit;skipStartupContext;bareMode;safeMode;warnings;ignoredExtensionRules=[];allowedHttpHookUrls;allowPrivateNetworkHooks;onPersistPermissionRuleCallback;initialized=false;initializationPromise;initializationSucceeded=false;initializationSettled=false;shutdownRequested=false;resourceShutdownAfterInitializationScheduled=false;resourceShutdownPromise;proxyDispatcherReady;storage;runtimeStatusWrite=Promise.resolve();sessionRegistryWrite=Promise.resolve();fileExclusions;truncateToolOutputThreshold;truncateToolOutputThresholdExplicit;truncateToolOutputLines;toolOutputBatchBudget;shellDefaultTimeoutMs;shellHeartbeatIntervalMs;eventEmitter;channel;jsonFd;jsonFile;jsonSchema;inputFile;plansDir;plansDirectoryConfigured;defaultFileEncoding;enableManagedAutoMemory;enableManagedAutoDream;enableTeamMemory;enableTeamMemorySync;enableStructuredMemoryRecall;teamMemoryShareabilityChecked=new Set;enableAutoSkill;autoSkillConfirm;memoryAgentTimeoutMinutes;memoryAgentMaxTurns;fastModel;advisorModel;advisorMaxUses;advisorUsage={calls:0};webSearchSettings;webSearchNoticeEmitted=false;webSearchSessionUsage={calls:0};visionModel;compactionModel;reasoningSnapshot;latestReasoningSnapshot;imageModel;visionBridgeTimeoutMs;modelFallbacks;disableAllHooks;stopHookBlockingCap;systemHooks;userHooks;projectHooks;hooks;hookSystem;messageBus;messageBusListeners=new Set;memoryManager;modelChangeListeners=new Set;approvalModeChangeListeners=new Set;ownsModelEnvSlot=false;settingsWatcher;constructor(params){this.executionEnvironment=params.executionEnvironment;if(params.executionEnvironment){this.executionEnvironments=new Set([Promise.resolve(params.executionEnvironment)])}this.agentExecutionBackend=params.agentExecutionBackend;const executionFactory=params.executionEnvironmentFactory;this.executionEnvironmentFactory=executionFactory?(config3,signal)=>executionFactory(config3,AbortSignal.any([signal,this.executionShutdown.signal])):void 0;this.sessionRuntimeBaseDir=Storage.getRuntimeBaseDir();this.shellExecutionSandbox=admitShellSandbox(params,this.sessionRuntimeBaseDir,Storage.getGlobalQwenDir());this.provisionalWorkspace=params.provisionalWorkspace===true;this.sessionId=params.sessionId??randomUUID29();if(!sessionEnvClaimed&&process8.env){process8.env["QWEN_CODE_SESSION_ID"]=this.sessionId;sessionEnvClaimed=true}this.sessionData=params.sessionData;this.sessionRestoreProjectionSource=params.sessionRestoreProjectionSource;this.sessionExecutionEngine=params.sessionExecutionEngine;this.managedRuntimeEnvironmentFactory=params.sessionExecutionEngine==="managed"?params.managedRuntimeEnvironment:void 0;this.onManagedEngineQuarantine=params.sessionExecutionEngine==="managed"?params.onManagedEngineQuarantine:void 0;this.setSessionRestoreProjection(params.sessionRestoreProjection);if(sessionIdContext.getStore()===void 0){setDebugLogSession(this)}this.debugLogger=createDebugLogger();this.embeddingModel=params.embeddingModel??DEFAULT_QWEN_EMBEDDING_MODEL;this.fileSystemService=new StandardFileSystemService;this.sandbox=params.sandbox;this.targetDir=path88.resolve(params.targetDir);this.plansDirectoryConfigured=Boolean(params.plansDirectory?.trim());this.plansDir=Storage.getPlansDir(this.targetDir,params.plansDirectory);this.explicitIncludeDirectories=Array.from(new Set(params.includeDirectories??[]));this.workspaceContext=new WorkspaceContext(this.targetDir,this.explicitIncludeDirectories);this.debugMode=params.debugMode;this.inputFormat=params.inputFormat??"text";const normalizedOutputFormat=normalizeConfigOutputFormat(params.outputFormat??params.output?.format);this.outputFormat=normalizedOutputFormat??"text";this.includePartialMessages=params.includePartialMessages??false;this.question=params.question;this.systemPrompt=params.systemPrompt;this.appendSystemPrompt=params.appendSystemPrompt;this.outputStyle=params.outputStyle;this.coreTools=params.coreTools;this.allowedTools=params.allowedTools;this.excludeTools=params.excludeTools;this.disabledSlashCommands=Object.freeze([...params.disabledSlashCommands??[]]);this.disabledSkillNamesProvider=params.disabledSkillNamesProvider??null;this.enabledSkillNamesProvider=params.enabledSkillNamesProvider??null;this.skillSettingsListsProvider=params.skillSettingsListsProvider??null;this.terminalImageRenderSupportProvider=params.terminalImageRenderSupportProvider??null;this.disabledSkillLevels=new Set(params.disabledSkillLevels??[]);this.customSkillDirs=Object.freeze([...params.customSkillDirs??[]]);this.disabledTools=new Set(params.disabledTools??[]);this.visibleTools=new Set((params.visibleTools??[]).filter(name2=>typeof name2==="string"));this.eagerTools=params.eagerTools===void 0?void 0:Object.freeze(params.eagerTools.filter(name2=>typeof name2==="string"));this.toolSearchThreshold=params.toolSearchThreshold??DEFAULT_TOOL_SEARCH_THRESHOLD;this.permissionsAllow=params.permissions?.allow||[];this.permissionsAsk=params.permissions?.ask||[];this.permissionsDeny=params.permissions?.deny||[];this.permissionsAutoMode=params.permissions?.autoMode??{};this.toolInvocationGuard=params.toolInvocationGuard;this.workflowAncestorTrustProvider=params.workflowAncestorTrustProvider;this.toolDiscoveryCommand=params.toolDiscoveryCommand;this.toolCallCommand=params.toolCallCommand;this.mcpServerCommand=params.mcpServerCommand;this.mcpServers=params.mcpServers;this.topTierMcpServers=params.topTierMcpServers;this.bundledGeneratedUi=Object.freeze({...params.bundledGeneratedUi,enabled:params.bundledGeneratedUi?.enabled===true});this.lspEnabled=params.lsp?.enabled??false;this.lspClient=params.lspClient;this.allowedMcpServers=params.allowedMcpServers;this.cliAllowedMcpServerNames=params.cliAllowedMcpServerNames;this.excludedMcpServers=params.excludedMcpServers;this.pendingMcpServers=params.pendingMcpServers;const envTimeout=process8.env["QWEN_CODE_MCP_TOOL_IDLE_TIMEOUT_MS"];const parsedEnv=envTimeout!==void 0?Number(envTimeout):NaN;this.mcpToolIdleTimeoutMs=params.mcpToolIdleTimeoutMs??(Number.isFinite(parsedEnv)&&parsedEnv>=0?parsedEnv:3e5);this.sessionSubagents=params.sessionSubagents??[];this.sdkMode=params.sdkMode??false;this.userMemory=params.userMemory??"";this.memoryFileCount=params.memoryFileCount??params.geminiMdFileCount??0;this.contextRuleExcludes=params.contextRuleExcludes??[];this.approvalMode=params.approvalMode??"auto";this.accessibility=params.accessibility??{};this.showResponseTokensPerSecond=params.showResponseTokensPerSecond??false;this.telemetrySettings={enabled:params.telemetry?.enabled??false,target:params.telemetry?.target??DEFAULT_TELEMETRY_TARGET,otlpEndpoint:params.telemetry?.otlpEndpoint,otlpProtocol:params.telemetry?.otlpProtocol,otlpTracesEndpoint:params.telemetry?.otlpTracesEndpoint,otlpLogsEndpoint:params.telemetry?.otlpLogsEndpoint,otlpMetricsEndpoint:params.telemetry?.otlpMetricsEndpoint,logPrompts:params.telemetry?.logPrompts??true,userId:params.telemetry?.userId?.trim()||void 0,includeSensitiveSpanAttributes:params.telemetry?.includeSensitiveSpanAttributes??false,sensitiveSpanAttributeMaxLength:resolveSensitiveSpanAttributeMaxLength(params.telemetry?.sensitiveSpanAttributeMaxLength),outfile:params.telemetry?.outfile,resourceAttributes:params.telemetry?.resourceAttributes,metrics:params.telemetry?.metrics,resourceAttributeWarnings:params.telemetry?.resourceAttributeWarnings};this.telemetryInitializationDeferred=params.deferTelemetryInitialization??false;this.outboundCorrelationSettings={propagateTraceContext:params.outboundCorrelation?.propagateTraceContext??false,allowDynamicHeaderValues:params.outboundCorrelation?.allowDynamicHeaderValues===true};this.gitCoAuthor={...normalizeGitCoAuthor(params.gitCoAuthor),name:"Qwen-Coder",email:"qwen-coder@alibabacloud.com"};this.usageStatisticsEnabled=params.usageStatisticsEnabled??true;this.fileReadCacheDisabled=params.sessionExecutionEngine==="managed"||(params.fileReadCacheDisabled??false);this.outputLanguageFilePath=params.outputLanguageFilePath;this.fileFiltering={respectGitIgnore:params.fileFiltering?.respectGitIgnore??true,respectQwenIgnore:params.fileFiltering?.respectQwenIgnore??true,customIgnoreFiles:params.fileFiltering?.customIgnoreFiles??[...DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES],enableRecursiveFileSearch:params.fileFiltering?.enableRecursiveFileSearch??true,enableFuzzySearch:params.fileFiltering?.enableFuzzySearch??true};this.fileCheckpointingEnabled=params.fileCheckpointingEnabled??(!params.sdkMode&&(params.interactive??false));this.proxy=params.proxy;this.cwd=params.cwd??process8.cwd();this.fileDiscoveryService=params.fileDiscoveryService??null;this.bugCommand=params.bugCommand;this.maxSessionTurns=validateMaxSessionTurns(params.maxSessionTurns);this.goalTokenBudgetGrant=normalizeGoalTokenBudget(params.goalTokenBudget);if(params.goalTokenBudget!==void 0&&!isValidGoalTokenBudget(params.goalTokenBudget)){this.debugLogger.warn(`Ignoring invalid goalTokenBudget ${String(params.goalTokenBudget)}: expected a non-negative integer or -1 (no budget); using the default of ${GOAL_DEFAULT_TOKEN_BUDGET}.`)}this.goalTurnBudgetGrant=normalizeGoalMaxTurns(params.goalMaxTurns);if(params.goalMaxTurns!==void 0&&!isValidGoalMaxTurns(params.goalMaxTurns)){this.debugLogger.warn(`Ignoring invalid goalMaxTurns ${String(params.goalMaxTurns)}: expected an integer between 1 and ${GOAL_MAX_TURNS_CAP}, or -1 for no turn ceiling; Goals will run with no turn ceiling.`)}this.goalActiveTimeBudgetGrantMs=normalizeGoalMaxActiveMinutes(params.goalMaxActiveMinutes);if(params.goalMaxActiveMinutes!==void 0&&!isValidGoalMaxActiveMinutes(params.goalMaxActiveMinutes)){this.debugLogger.warn(`Ignoring invalid goalMaxActiveMinutes ${String(params.goalMaxActiveMinutes)}: expected an integer between 1 and ${GOAL_MAX_ACTIVE_MINUTES_CAP}, or -1 for no time ceiling; Goals will run with no time ceiling.`)}this.maxSubagentDepth=normalizeMaxSubagentDepth(params.maxSubagentDepth);this.maxWallTimeSeconds=params.maxWallTimeSeconds??-1;this.maxToolCalls=params.maxToolCalls??-1;const clearContextOnIdle=params.clearContextOnIdle;const toolResultsThresholdMinutes=clearContextOnIdle?.toolResultsThresholdMinutes??60;this.clearContextOnIdle={toolResultsThresholdMinutes,toolResultsNumToKeep:clearContextOnIdle?.toolResultsNumToKeep??5,toolResultsTotalCharsThreshold:clearContextOnIdle?.toolResultsTotalCharsThreshold??((clearContextOnIdle?.toolResultsThresholdMinutes??0)<0?-1:DEFAULT_TOOL_RESULTS_TOTAL_CHARS_THRESHOLD)};this.sessionTokenLimit=params.sessionTokenLimit??-1;this.experimentalZedIntegration=params.experimentalZedIntegration??false;this.restoreAskUserQuestion=params.restoreAskUserQuestion===true;this.preserveRestorableAskUserQuestion=this.restoreAskUserQuestion;this.sessionWriterLeaseEnabled=this.experimentalZedIntegration===true&&params.sessionWriterLeaseEnabled===true;this.cronEnabled=params.cronEnabled??true;this.cronRecurringMaxAgeDays=resolveCronRecurringMaxAgeDays(params.cronRecurringMaxAgeDays);this.lsToolEnabled=params.lsToolEnabled??false;this.todoWriteEnabled=params.todoWriteEnabled??false;this.agentTeamEnabled=params.agentTeamEnabled??false;this.unifiedAgentLoopEnabled=params.unifiedAgentLoopEnabled??false;this.agentCollaborationEnabled=params.agentCollaborationEnabled??false;this.artifactEnabled=params.artifactEnabled??true;this.artifactAutoOpen=params.artifactAutoOpen??true;this.artifactPublisher=params.artifactPublisher??"local";this.artifactHost=params.artifactHost;this.artifactOss=params.artifactOss;this.omniEnabled=params.omniEnabled??false;this.omniMaxUploadFileBytes=params.omniMaxUploadFileBytes;this.omniMaxEstimatedTokens=params.omniMaxEstimatedTokens;this.omniMaxDurationSeconds=params.omniMaxDurationSeconds;this.omniUrlDownloadMaxFileBytes=params.omniUrlDownloadMaxFileBytes;this.omniUploadUrlTtlHours=params.omniUploadUrlTtlHours;this.omniUploadBaseUrl=params.omniUploadBaseUrl;this.omniUploadApiKeyEnv=params.omniUploadApiKeyEnv;this.omniUploadModel=params.omniUploadModel;this.omniPolicyTools=params.omniPolicyTools;this.omniFixedPolicies=params.omniFixedPolicies;this.omniTransportGuardPolicies=params.omniTransportGuardPolicies;this.omniProcessingLimits=params.omniProcessingLimits;this.omniQuarantineRetentionDays=params.omniQuarantineRetentionDays;this.omniQuarantineMaxBytes=params.omniQuarantineMaxBytes;this.omniStorageRetentionDays=params.omniStorageRetentionDays;this.omniStorageMaxTotalBytes=params.omniStorageMaxTotalBytes;this.omniMemory=params.omniMemory;this.workflowsEnabled=params.workflowsEnabled;this.workflowKeywordTriggerEnabled=params.workflowKeywordTriggerEnabled??true;this.sessionWorkflowEnabled=params.sessionWorkflowEnabled??false;this.modelProposedGoals=params.modelProposedGoals??"alwaysAsk";this.skipWorkflowUsageWarning=params.skipWorkflowUsageWarning??false;this.workflowSizeGuideline=isWorkflowSizeGuideline(params.workflowSizeGuideline)?params.workflowSizeGuideline:void 0;this.workflowNameOnly=params.workflowNameOnly===true||process8.env["QWEN_CODE_WORKFLOW_NAME_ONLY"]==="1";this.workflowRunRegistry.setNameOnly(this.workflowNameOnly);this.emitToolUseSummaries=params.emitToolUseSummaries??true;this.listExtensions=params.listExtensions??false;this.overrideExtensions=params.overrideExtensions;this.noBrowser=params.noBrowser??false;this.folderTrustFeature=params.folderTrustFeature??false;this.folderTrust=params.folderTrust??false;this.ideMode=params.ideMode??false;this.modelProvidersConfig=params.modelProvidersConfig;this.providerProtocolConfig=params.providerProtocolConfig;this.cliVersion=params.cliVersion;this.chatRecordingEnabled=params.chatRecording??true;this.loadMemoryFromIncludeDirectories=params.loadMemoryFromIncludeDirectories??false;this.importFormat=params.importFormat??"tree";this.chatCompression=params.chatCompression;this.autoCompactThreshold=params.autoCompactThreshold;this.interactive=params.interactive??false;this.trustedFolder=params.trustedFolder;this.skipLoopDetection=params.skipLoopDetection??false;this.loopProtection=isLoopProtectionMode(params.loopProtection)?params.loopProtection:DEFAULT_LOOP_PROTECTION;this.maxToolCallsPerTurn=validateMaxToolCallsPerTurn(params.maxToolCallsPerTurn);this.maxToolCallsPerTurnExplicit=params.maxToolCallsPerTurn!==void 0;this.skipStartupContext=params.skipStartupContext??false;this.bareMode=params.bareMode??false;this.safeMode=params.safeMode??isSafeModeEnv();this.toolMode=params.codeModeOnly&&!this.bareMode&&!this.safeMode?ToolMode.CodeModeOnly:ToolMode.Direct;this.freeform=this.toolMode===ToolMode.CodeModeOnly&&params.freeform===true;if(this.safeMode){this.debugLogger.info("Safe mode active: hooks, extensions, skills, MCP servers, context files, rules disabled")}this.warnings=params.warnings??[];this.addLegacyPlanLocationWarning();this.allowedHttpHookUrls=params.allowedHttpHookUrls??[];this.allowPrivateNetworkHooks=params.allowPrivateNetworkHooks??false;this.onPersistPermissionRuleCallback=params.onPersistPermissionRule;this.useRipgrep=params.useRipgrep??true;this.useBuiltinRipgrep=params.useBuiltinRipgrep??true;this.shouldUseNodePtyShell=params.shouldUseNodePtyShell??shouldDefaultToNodePty();this.preventSystemSleep=params.preventSystemSleep??true;this.skipNextSpeakerCheck=params.skipNextSpeakerCheck??true;this.shellExecutionConfig={terminalWidth:params.shellExecutionConfig?.terminalWidth??80,terminalHeight:params.shellExecutionConfig?.terminalHeight??24,showColor:params.shellExecutionConfig?.showColor??false,pager:params.shellExecutionConfig?.pager,maxBufferedOutputBytes:params.shellExecutionConfig?.maxBufferedOutputBytes};this.truncateToolOutputThreshold=params.truncateToolOutputThreshold??DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD;this.truncateToolOutputThresholdExplicit=params.truncateToolOutputThreshold!=null;this.truncateToolOutputLines=params.truncateToolOutputLines??DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES;this.toolOutputBatchBudget=params.toolOutputBatchBudget??DEFAULT_TOOL_OUTPUT_BATCH_BUDGET;this.shellDefaultTimeoutMs=params.shellDefaultTimeoutMs!==void 0&&Number.isInteger(params.shellDefaultTimeoutMs)&&params.shellDefaultTimeoutMs>=0&&params.shellDefaultTimeoutMs<=2147483647?params.shellDefaultTimeoutMs:void 0;this.shellHeartbeatIntervalMs=params.shellHeartbeatIntervalMs!==void 0&&Number.isInteger(params.shellHeartbeatIntervalMs)&&params.shellHeartbeatIntervalMs>=0&&params.shellHeartbeatIntervalMs<=2147483647?params.shellHeartbeatIntervalMs:void 0;this.channel=params.channel;this.jsonFd=params.jsonFd;this.jsonFile=params.jsonFile;this.jsonSchema=params.jsonSchema;this.inputFile=params.inputFile;this.defaultFileEncoding=params.defaultFileEncoding;this.storage=new Storage(this.targetDir,this.sessionRuntimeBaseDir);if(!projectDirEnvClaimed&&process8.env){process8.env["QWEN_CODE_PROJECT_DIR"]=this.storage.getProjectDir();projectDirEnvClaimed=true}this.inputFormat=params.inputFormat??"text";this.fileExclusions=new FileExclusions(this);this.eventEmitter=params.eventEmitter;this.arenaAgentClient=ArenaAgentClient.create();this.agentsSettings=params.agents??{};this.backgroundTaskRegistry=new BackgroundTaskRegistry({...this.agentsSettings.maxParallelAgents!==void 0?{maxConcurrentBackgroundAgents:this.agentsSettings.maxParallelAgents}:{},...this.agentsSettings.maxParallelAgentsByModel!==void 0?{maxConcurrentBackgroundAgentsByModel:this.agentsSettings.maxParallelAgentsByModel}:{}});this.worktreeSettings=params.worktree??{};if(params.contextFileName){setMemoryFilename(params.contextFileName)}this.initialAuthType=params.authType??params.generationConfig?.authType;this.modelsConfig=new ModelsConfig({initialAuthType:this.initialAuthType,modelProvidersConfig:this.modelProvidersConfig,providerProtocolConfig:this.providerProtocolConfig,generationConfig:{model:params.model,...params.generationConfig||{},baseUrl:params.generationConfig?.baseUrl},generationConfigSources:params.generationConfigSources,initialRegistryBaseUrl:params.initialModelRegistryBaseUrl,onModelChange:this.handleModelChange.bind(this)});this.initialResolvedAuthType=this.modelsConfig.getCurrentAuthType();if(!modelEnvClaimed&&process8.env){modelEnvClaimed=true;this.ownsModelEnvSlot=true}this.publishModelEnv();if(this.telemetrySettings.enabled&&!this.telemetryInitializationDeferred){void Promise.resolve(initializeTelemetry(this)).catch(error3=>{this.debugLogger.error("Failed to initialize telemetry:",error3)})}const proxyUrl=this.getProxy();if(proxyUrl&&(params.installProxyDispatcher??true)){this.proxyDispatcherReady=loadUndici().then(({EnvHttpProxyAgent,setGlobalDispatcher})=>{setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}));setResolvedProxyUrlForRuntimeFetch(proxyUrl)}).catch(error3=>{this.debugLogger.error("Failed to install proxy dispatcher:",redactProxyError(error3));throw error3});this.proxyDispatcherReady.catch(()=>{})}this.llmClient=new LlmClient(this);this.chatRecordingService=this.chatRecordingEnabled?this.createChatRecordingService():void 0;if(!this.sessionRestoreProjectionSource||this.sessionRestoreRuntime||!this.sessionWriterLeaseEnabled){this.initializeGoalRuntime(this.sessionRestoreRuntime?.goalRecords??this.sessionData?.conversation.messages,this.sessionRestoreRuntime)}this.extensionManager=new ExtensionManager({workspaceDir:this.targetDir,enabledExtensionOverrides:this.overrideExtensions,isWorkspaceTrusted:this.isTrustedFolder(),locale:params.locale,usageStatisticsEnabled:this.usageStatisticsEnabled,proxy:this.proxy});this.enableManagedAutoMemory=params.enableManagedAutoMemory??true;this.enableManagedAutoDream=params.enableManagedAutoDream??true;this.enableTeamMemory=params.enableTeamMemory??false;this.enableTeamMemorySync=params.enableTeamMemorySync??false;this.enableStructuredMemoryRecall=params.enableStructuredMemoryRecall??false;this.enableAutoSkill=params.enableAutoSkill??false;this.autoSkillConfirm=params.autoSkillConfirm??true;this.memoryAgentTimeoutMinutes=params.memoryAgentTimeoutMinutes!==void 0&&params.memoryAgentTimeoutMinutes>=0?params.memoryAgentTimeoutMinutes:void 0;this.memoryAgentMaxTurns=params.memoryAgentMaxTurns!==void 0&&Number.isInteger(params.memoryAgentMaxTurns)&&params.memoryAgentMaxTurns>=0?params.memoryAgentMaxTurns:void 0;this.fastModel=params.fastModel||void 0;this.advisorModel=normalizeAdvisorModel(params.advisorModel);this.advisorMaxUses=isValidAdvisorMaxUses(params.advisorMaxUses)?params.advisorMaxUses:0;this.webSearchSettings=params.webSearch;this.visionModel=params.visionModel||void 0;this.compactionModel=params.compactionModel||void 0;this.imageModel=params.imageModel||void 0;this.visionBridgeTimeoutMs=params.visionBridgeTimeoutMs!==void 0&&Number.isInteger(params.visionBridgeTimeoutMs)&&params.visionBridgeTimeoutMs>0&&params.visionBridgeTimeoutMs<=2147483647?params.visionBridgeTimeoutMs:void 0;this.modelFallbacks=normalizeModelFallbacks(params.modelFallbacks);this.disableAllHooks=params.disableAllHooks??false;this.stopHookBlockingCap=resolveStopHookBlockingCap(params.stopHookBlockingCap);this.systemHooks=params.systemHooks;this.userHooks=params.userHooks;this.projectHooks=params.projectHooks;this.hooks=params.hooks;this.settingsWatcher=params.settingsWatcher;this.memoryManager=new MemoryManager;if(params.workflowMode!==void 0){this.stageInitialWorkflowMode(params.workflowMode)}}async initialize(options2){if(this.executionEnvironment){options2={...options2,skipHooks:true,skipMcpDiscovery:true,skipSkillManager:true,skipFileCheckpointing:true}}if(this.sessionExecutionEngine==="managed"){options2={...options2,skipMcpDiscovery:true}}if(isDerivedConfig(this)){throw new Error("Derived Configs cannot be initialized")}if(this.initialized){if(!this.initializationSettled){options2?.signal?.throwIfAborted();this.debugLogger.debug("Config.initialize() called while initialization is in flight; joining the existing run");await this.initializationPromise;return}await this.initializationPromise;throw Error("Config was already initialized")}if(this.shutdownRequested){throw Error("Config is shutting down")}options2?.signal?.throwIfAborted();this.initialized=true;const initialization=this.initializeOnce(options2);this.initializationPromise=initialization;try{await initialization;this.initializationSucceeded=true}finally{this.initializationSettled=true}}async activateProvisionalWorkspace(){if(!this.provisionalWorkspace||this.provisionalWorkspaceActivated){return}if(this.provisionalWorkspaceActivation){return this.provisionalWorkspaceActivation}const activation=(async()=>{this.getFileService();await this.llmClient.initialize();await this.toolRegistry.warmAll({strict:true});await this.initializeOmniPolicies();logStartSession(this,new StartSessionEvent(this));this.provisionalWorkspaceActivated=true})();this.provisionalWorkspaceActivation=activation;return activation}async initializeOmniPolicies(){if(this.isOmniEnabled()){const{normalizeOmniProcessingConfig}=await import("./config-QVHNAELH.js");this.omniProcessingConfig=normalizeOmniProcessingConfig({fixedPolicies:this.omniFixedPolicies,transportGuardPolicies:this.omniTransportGuardPolicies,limits:this.omniProcessingLimits,policyTools:this.omniPolicyTools,maxUploadFileBytes:this.omniMaxUploadFileBytes,maxEstimatedTokens:this.omniMaxEstimatedTokens,urlTtlHours:this.omniUploadUrlTtlHours},this.toolRegistry);await this.ensureOmniMemoryConfig()}}isProvisionalWorkspace(){return this.provisionalWorkspace}async initializeOnce(options2){try{if(this.shellExecutionSandbox)this.shellExecutionSandbox=await probeShellSandbox(this.shellExecutionSandbox,options2?.signal);const activation=this.activateChatRecording();this.sessionWriterActivationPromise=activation;try{await activation}finally{if(this.sessionWriterActivationPromise===activation){this.sessionWriterActivationPromise=void 0}}options2?.signal?.throwIfAborted();this.workflowModeContext.restore(this.isWorkflowModeSupported()?this.chatRecordingService?.getSessionWorkflowMode():void 0);await this.bindSessionExecutionEngine();registerSessionProjectDir(this.sessionId,this.storage.getProjectDir());this.sessionProjectDirRegistered=true;await this.initializeInternal(options2);this.workflowModeReady=true;if(this.initialWorkflowMode!==void 0){const enabled=this.initialWorkflowMode;this.initialWorkflowMode=void 0;await this.setWorkflowMode(enabled)}this.refreshWorkflowMode()}catch(error3){this.clearSessionRestoreProjection();if(this.sessionProjectDirRegistered){unregisterSessionProjectDir(this.sessionId);this.sessionProjectDirRegistered=false}try{await this.closeSessionWriter()}catch(closeError){if(options2?.signal?.aborted&&containsErrorByIdentity(error3,options2.signal.reason)){this.debugLogger.warn("Chat recording close failed after initialization was aborted:",closeError);options2.signal.throwIfAborted()}if(containsErrorByIdentity(error3,closeError)){throw error3}throw new SessionWriterUnavailableError({cause:new AggregateError([error3,closeError],"Chat recording close failed during failed initialization")})}throw error3}}async bindSessionExecutionEngine(){const engine=this.sessionExecutionEngine;if(engine===void 0)return;if(this.sessionRestoreProjectionSource||this.sessionData){assertSessionExecutionEngine(this.pendingSessionRestoreProjection?.executionEngine,this.sessionId,engine);return}if(this.managedSession)return;await this.chatRecordingService?.recordExecutionEngine(engine)}async initializeInternal(options2){this.debugLogger.info("Config initialization started");await this.proxyDispatcherReady;void refreshModelCatalog();options2?.signal?.throwIfAborted();if(this.isOmniEnabled()){const{normalizeDedicatedOmniUploadConfig}=await import("./upload-config-ML5XEJIF.js");this.omniUploadConfig=normalizeDedicatedOmniUploadConfig({baseUrl:this.omniUploadBaseUrl,apiKeyEnv:this.omniUploadApiKeyEnv,model:this.omniUploadModel});const{assertOmniRuntimeDependencies}=await import("./ffmpeg-3AJSGZKK.js");await assertOmniRuntimeDependencies()}if(options2?.skipFileCheckpointing===true||this.shellExecutionSandbox){this.fileCheckpointingEnabled=false;this.fileHistoryService=void 0}if(!this.provisionalWorkspace){this.getFileService()}this.promptRegistry=new PromptRegistry;this.resourceRegistry=new ResourceRegistry;this.extensionManager.setConfig(this);const explicitExtensionNames=this.isSafeMode()?[]:(this.overrideExtensions??[]).filter(n=>n.trim()!==""&&n.toLowerCase()!=="none");recordStartupEvent("config_initialize_extensions_initial_start");if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.isSafeMode()&&!this.getBareMode()){await this.extensionManager.refreshCache()}else if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.isSafeMode()&&explicitExtensionNames.length>0){await this.extensionManager.refreshCache({names:explicitExtensionNames})}recordStartupEvent("config_initialize_extensions_initial_end");options2?.signal?.throwIfAborted();this.debugLogger.debug("Extension manager initialized");recordStartupEvent("config_initialize_hooks_start");if(!this.shellExecutionSandbox&&(options2?.managedHookDispatcher||!options2?.skipHooks&&!this.getDisableAllHooks())){this.hookSystem=new HookSystem(this,options2?.managedHookDispatcher);await this.hookSystem.initialize();this.debugLogger.debug("Hook system initialized");this.messageBus=new MessageBus;this.messageBus.subscribe("hook-execution-request",async request=>{try{const hookSystem=this.hookSystem;if(!hookSystem){this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:new Error("Hook system not initialized")});return}if(request.signal?.aborted){this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:new Error("Hook execution cancelled (aborted)")});return}assertHookExecutionOwner(request.owner,hookSystem.runtimeId,this.getSessionId());await runWithHookExecutionOwner(request.owner,async()=>{let result;let stopHookCount;const input=request.input||{};const signal=request.signal;switch(request.eventName){case"UserPromptSubmit":result=await hookSystem.fireUserPromptSubmitEvent(input["prompt"]||"",signal,typeof input["submitted_prompt"]==="string"&&input["submitted_prompt"].trim().length>0?input["submitted_prompt"]:void 0);break;case"UserPromptExpansion":result=await hookSystem.fireUserPromptExpansionEvent(input["command_name"]||"",input["command_args"]||"",input["prompt"]||"",signal);break;case"Stop":{const contextUsageData=buildContextUsage(input["context_limit"],input["input_tokens"]??0);const stopResult=await hookSystem.fireStopEvent(input["stop_hook_active"]||false,input["last_assistant_message"]||"",contextUsageData,signal);result=stopResult.finalOutput?createHookOutput("Stop",stopResult.finalOutput):void 0;stopHookCount=stopResult.allOutputs.length;break}case"MessageDisplay":{const messageDisplayResult=await hookSystem.fireMessageDisplayEvent(input["message_id"]||"",input["displayed_text"]||"",input["is_final"]||false,signal);result=messageDisplayResult.finalOutput?createHookOutput("MessageDisplay",messageDisplayResult.finalOutput):void 0;break}case"PreToolUse":{result=await hookSystem.firePreToolUseEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_use_id"]||"",input["permission_mode"]??"default",signal,input["tool_call_id"]||void 0);break}case"PostToolUse":result=await hookSystem.firePostToolUseEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_response"]||{},input["tool_use_id"]||"",input["permission_mode"]||"default",signal,input["tool_call_id"]||void 0,typeof input["duration_ms"]==="number"?input["duration_ms"]:void 0);break;case"PostToolUseFailure":result=await hookSystem.firePostToolUseFailureEvent(input["tool_use_id"]||"",input["tool_name"]||"",input["tool_input"]||{},input["error"]||"",input["is_interrupt"],input["permission_mode"]||"default",signal,input["tool_call_id"]||void 0,typeof input["duration_ms"]==="number"?input["duration_ms"]:void 0);break;case"PostToolBatch":result=await hookSystem.firePostToolBatchEvent(input["tool_calls"]||[],input["permission_mode"]||"default",signal);break;case"Notification":result=await hookSystem.fireNotificationEvent(input["message"]||"",input["notification_type"]||"permission_prompt",input["title"]||void 0,signal);break;case"PermissionRequest":result=await hookSystem.firePermissionRequestEvent(input["tool_name"]||"",input["tool_input"]||{},input["permission_mode"]||"default",input["permission_suggestions"]||void 0,signal);break;case"PermissionDenied":result=await hookSystem.firePermissionDeniedEvent(input["tool_name"]||"",input["tool_input"]||{},input["tool_use_id"]||"",input["reason"]||"classifier_blocked",signal,input["tool_call_id"]||void 0);break;case"SubagentStart":result=await hookSystem.fireSubagentStartEvent(input["agent_id"]||"",input["agent_type"]||"",input["permission_mode"]||"default",signal);break;case"SubagentStop":result=await hookSystem.fireSubagentStopEvent(input["agent_id"]||"",input["agent_type"]||"",input["agent_transcript_path"]||"",input["last_assistant_message"]||"",input["stop_hook_active"]||false,input["permission_mode"]||"default",signal);break;case"SessionStart":result=await hookSystem.fireSessionStartEvent(input["source"],input["model"]||"",input["permission_mode"]||void 0,input["agent_type"],signal);break;case"SessionEnd":result=await hookSystem.fireSessionEndEvent(input["reason"],signal);break;case"SessionDelete":result=await hookSystem.fireSessionDeleteEvent(input["deleted_session_id"]||"",signal);break;case"PreCompact":result=await hookSystem.firePreCompactEvent(input["trigger"],input["custom_instructions"]||"",signal);break;case"PostCompact":result=await hookSystem.firePostCompactEvent(input["trigger"],input["compact_summary"]||"",signal);break;case"InstructionsLoaded":result=await hookSystem.fireInstructionsLoadedEvent(input["file_path"]||"",input["memory_type"],input["load_reason"],{triggerFilePath:input["trigger_file_path"],parentFilePath:input["parent_file_path"]},signal);break;case"StopFailure":result=(await hookSystem.fireStopFailureEvent(input["error"],input["error_details"],input["last_assistant_message"],signal)).finalOutput;break;case"TodoCreated":result=(await hookSystem.fireTodoCreatedEvent(input["todo_id"]||"",input["todo_content"]||"",input["todo_status"],input["all_todos"]||[],input["phase"],signal)).finalOutput;break;case"TodoCompleted":result=(await hookSystem.fireTodoCompletedEvent(input["todo_id"]||"",input["todo_content"]||"",input["previous_status"],input["all_todos"]||[],input["phase"],signal)).finalOutput;break;default:this.debugLogger.warn(`Unknown hook event: ${request.eventName}`);result=void 0}this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:true,output:result,stopHookCount})})}catch(error3){this.debugLogger.warn(`Hook execution failed: ${error3}`);this.messageBus?.publish({type:"hook-execution-response",correlationId:request.correlationId,success:false,error:error3 instanceof Error?error3:new Error(String(error3))})}});this.announceMessageBus(this.messageBus);this.debugLogger.debug("MessageBus initialized with hook subscription")}else{this.debugLogger.debug("Hook system disabled, skipping initialization")}recordStartupEvent("config_initialize_hooks_end");options2?.signal?.throwIfAborted();this.subagentManager=new SubagentManager(this);this.initializeBundledGeneratedUi(options2);recordStartupEvent("config_initialize_skills_start");if(!options2?.skipSkillManager){if(!this.provisionalWorkspace&&this.getAutoSkillEnabled()&&this.isTrustedFolder()){try{const curatorResult=await maybeRunAutoSkillCurator(this.getProjectRoot());if(curatorResult.status==="ran"){this.debugLogger.debug(`Auto-skill curator checked ${curatorResult.result.checked} skill(s) and archived ${curatorResult.result.archived.length}.`)}}catch(error3){this.debugLogger.warn(`Auto-skill curator skipped: ${error3 instanceof Error?error3.message:String(error3)}`)}}this.skillManager=new SkillManager(this);if(this.shellExecutionSandbox||this.getBareMode()||this.isSafeMode()){await this.skillManager.refreshCache()}else{await this.skillManager.startWatching()}this.debugLogger.debug("Skill manager initialized");if(this.skillSettingsListsProvider){try{const lists=this.skillSettingsListsProvider();const skills=await this.skillManager.listSkills();const extensionIdByName=new Map(this.getExtensions().map(extension=>[extension.name,extension.id]));const defaultOffNames=new Set;for(const skill of skills){const extensionId=skill.extensionName?extensionIdByName.get(skill.extensionName):void 0;if(skill.level!=="extension"||!extensionId)continue;const state=this.extensionManager.getExtensionSkillState(extensionId,authoredSkillName(skill));if(state.defaultEnabled===false&&!state.workspaceEnabled){defaultOffNames.add(skill.name.trim().toLowerCase())}}this.warnings.push(...bareEnabledGrantWarnings(lists,skills,defaultOffNames),...bareDisablementBlocksQualifiedGrantWarnings(lists,this.getDisabledSkillNames(),skills))}catch(error3){this.debugLogger.warn(`Skill settings migration warning skipped: ${getErrorMessage(error3)}`)}}}else{this.skillManager=null;this.debugLogger.debug("Skill manager skipped")}recordStartupEvent("config_initialize_skills_end");options2?.signal?.throwIfAborted();this.memoryPressureConfig=loadMemoryPressureConfig();this.memoryPressureMonitor=new MemoryPressureMonitor(this,this.memoryPressureConfig);this.permissionManager=new PermissionManager(this);this.permissionManager.initialize();this.debugLogger.debug("Permission manager initialized");if(this.sessionSubagents.length>0){this.subagentManager.loadSessionSubagents(this.sessionSubagents)}recordStartupEvent("config_initialize_extensions_final_start");if(!this.executionEnvironment&&!this.shellExecutionSandbox&&!this.getBareMode()&&!this.isSafeMode()){await this.extensionManager.refreshCache()}recordStartupEvent("config_initialize_extensions_final_end");options2?.signal?.throwIfAborted();if(!this.provisionalWorkspace){recordStartupEvent("config_initialize_hierarchical_memory_start");await this.refreshHierarchicalMemory("session_start",options2?.signal);recordStartupEvent("config_initialize_hierarchical_memory_end");this.debugLogger.debug("Hierarchical memory loaded")}options2?.signal?.throwIfAborted();const legacyBlockingMcp=process8.env["QWEN_CODE_LEGACY_MCP_BLOCKING"]==="1";const skipInlineMcpDiscovery=this.getBareMode()||this.isSafeMode()||this.provisionalWorkspace||!legacyBlockingMcp||options2?.skipMcpDiscovery===true;recordStartupEvent("config_initialize_tool_registry_start");this.toolRegistry=await this.createToolRegistry(options2?.sendSdkMcpMessage,skipInlineMcpDiscovery?{skipDiscovery:true}:void 0);options2?.signal?.throwIfAborted();recordStartupEvent("config_initialize_tool_registry_end");recordStartupEvent("tool_registry_created",{toolCount:this.toolRegistry.getAllToolNames().length,mcpInline:!skipInlineMcpDiscovery});this.debugLogger.info(`Tool registry initialized with ${this.toolRegistry.getAllToolNames().length} tools`);if(!(options2?.skipLlmInitialization??options2?.skipGeminiInitialization)&&!this.provisionalWorkspace){await this.llmClient.initialize(void 0,options2?.signal);this.debugLogger.info("LLM client initialized")}else{this.debugLogger.info("LLM client initialization skipped")}this.modelsConfig.detectAndCaptureRuntimeModel();if(!this.provisionalWorkspace){recordStartupEvent("config_initialize_tool_warmup_start");await this.toolRegistry.warmAll({strict:options2?.lenientToolWarmup!==true});options2?.signal?.throwIfAborted();recordStartupEvent("config_initialize_tool_warmup_end")}if(!this.provisionalWorkspace){await this.initializeOmniPolicies();options2?.signal?.throwIfAborted()}const hasMcpServers=Object.keys(this.getMcpServers()??{}).length>0;if(!this.shellExecutionSandbox&&skipInlineMcpDiscovery&&(!(this.getBareMode()||this.isSafeMode())||hasMcpServers)&&!this.provisionalWorkspace&&!options2?.skipMcpDiscovery){this.startMcpDiscoveryInBackground()}if(!this.provisionalWorkspace){options2?.signal?.throwIfAborted();logStartSession(this,new StartSessionEvent(this))}this.debugLogger.info("Config initialization completed");if(!this.shellExecutionSandbox&&!this.getBareMode()&&this.sessionSourceType!=="agent-host"&&!this.provisionalWorkspace){void(async()=>{try{const root=findGitRoot(this.targetDir)??this.targetDir;const worktreesDir=path88.join(root,".qwen","worktrees");try{await fsPromises4.access(worktreesDir)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${worktreesDir} does not exist`);return}const removed=await cleanupStaleAgentWorktrees(root);if(removed>0){this.debugLogger.info(`Stale worktree sweep removed ${removed} ephemeral worktree(s) under ${root}`)}else{this.debugLogger.debug(`Stale worktree sweep ran under ${root}: nothing to remove`)}}catch(error3){this.debugLogger.warn(`Stale worktree sweep failed (non-fatal): ${error3}`)}})()}}async openManagedSessionLog(lease){const transcriptPath=this.getTranscriptPath();const sessionKey=localManagedSessionKey(this.storage.getProjectRoot(),this.sessionId);const resources=LocalManagedSessionResourceStore.create({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionKey});const create=isManagedSessionTranscriptSync(transcriptPath)?void 0:await this.publishManagedSessionRoot(resources);const open8=__name(()=>openManagedSession({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionId:this.sessionId,transcriptPath,sessionKey,cwd:this.getProjectRoot(),version:this.getCliVersion()||"unknown",workerId:this.sessionId,activationLeaseDurationMs:MANAGED_ACTIVATION_LEASE_MS,lease,resourceStore:resources,...create===void 0?{}:{create}}),"open");try{return await open8()}catch(error3){if(!(error3 instanceof ManagedSessionUncommittedTailError))throw error3;await LocalManagedSessionAuthority.recoverUncommittedTail({lease,sessionKey});return await open8()}}isLegacyTranscript(){const transcriptPath=this.getTranscriptPath();try{if(fs80.statSync(transcriptPath).size===0)return false}catch{return false}return readManagedExecutionEvidenceSync(transcriptPath)===false}async finishManagedWriter(lease,opened){if(opened){try{await stopAdvancing(opened)}catch{}await lease.sealForHandoff(managedCommitProof(opened));return}const takenOver=lease.takeoverCommitProof;if(takenOver!==void 0){await lease.sealForHandoff(takenOver);return}const transcriptPath=this.getTranscriptPath();const evidence=readManagedExecutionEvidenceSync(transcriptPath);if(evidence===false){await lease.release();return}if(evidence===void 0)return;let scan;try{scan=await LocalJsonlManagedSessionJournalStore.read({transcriptPath,runtimeBaseDir:this.sessionRuntimeBaseDir,sessionKey:localManagedSessionKey(this.storage.getProjectRoot(),this.sessionId)})}catch{return}await lease.sealForHandoff({last_commit_sequence:scan.committed,committed_prefix_hash:scan.lastMarkerDigest??EMPTY_COMMIT_PREFIX_HASH})}async publishManagedSessionRoot(resources){const[definitionRef,rootSnapshotRef]=await Promise.all([resources.publish("managed-session-definition",Buffer.from(JSON.stringify({version:1,engine:"managed",model:this.getModel(),approvalMode:this.getApprovalMode()}),"utf8")),resources.publish("managed-session-root-snapshot",Buffer.from(JSON.stringify({version:1,messages:[]}),"utf8"))]);return{definitionRef,rootSnapshotRef,createdBy:`qwen-code/${this.getCliVersion()||"unknown"}`}}async activateChatRecording(){const managed=this.sessionExecutionEngine==="managed";if(managed&&(!this.chatRecordingEnabled||!this.sessionWriterLeaseEnabled)){throw new SessionExecutionEngineError(this.sessionId,"managed execution requires chat recording and a writer lease")}if(!this.chatRecordingEnabled||!this.sessionWriterLeaseEnabled){return}if(managed&&this.isLegacyTranscript()){throw new SessionExecutionEngineError(this.sessionId,"belongs to legacy, cannot execute with managed")}if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const recorder=this.chatRecordingService;if(!recorder)throw new SessionWriterUnavailableError;let lease;try{const acquire=managed?acquireLocalManagedSessionWriter:SessionWriterLease.acquire;lease=await acquire({runtimeBaseDir:this.sessionRuntimeBaseDir,sessionId:this.sessionId,transcriptPath:this.getTranscriptPath(),processKind:"acp",qwenVersion:this.cliVersion??null,reclaimPolicy:this.sessionWriterReclaimPolicy,takeoverPolicy:managed?"certified":this.sessionWriterTakeoverPolicy,...managed?{lockSchema:{schemaVersion:3,formatVersion:MANAGED_SESSION_FORMAT_VERSION}}:{},onOwnershipAcquired:__name(acquiredLease=>{lease=acquiredLease;this.pendingSessionWriterLease=acquiredLease;if(this.sessionWriterShutdownRequested){this.startPendingSessionWriterRelease(acquiredLease)}},"onOwnershipAcquired")});if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const location=await this.getSessionService().getSessionLocation(this.sessionId);if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}if(location==="archived"){throw new SessionTranscriptChangedError}let authoritative;let projection;if(this.sessionRestoreProjectionSource){addDaemonRequestAttribute("qwen-code.daemon.session_restore.projection_acquisition","after_writer_lease");projection=await this.sessionRestoreProjectionSource();if(managed){assertSessionExecutionEngine(projection?.executionEngine,this.sessionId,"managed")}if(managed&&await prepareLocalManagedSessionWriter(lease,localManagedSessionKey(this.storage.getProjectRoot(),this.sessionId))){projection=await this.sessionRestoreProjectionSource();assertSessionExecutionEngine(projection?.executionEngine,this.sessionId,"managed")}this.setSessionRestoreProjection(projection)}else if(managed&&(this.sessionData||lease.transcriptExistedAtAcquire)){throw new SessionExecutionEngineError(this.sessionId,"managed restore requires a restore projection")}else if(this.sessionData||lease.transcriptExistedAtAcquire){authoritative=await this.getSessionService().loadSession(this.sessionId);if(!authoritative)throw new SessionWriterUnavailableError}else if(location!==void 0){throw new SessionTranscriptChangedError}const persistedTitleInfo=authoritative?this.getSessionService().getSessionTitleInfo(this.sessionId):void 0;await lease.assertOwnedAndUnchanged();if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}this.sessionData=authoritative;if(managed){this.managedSession=await this.openManagedSessionLog(lease);if(this.sessionWriterShutdownRequested){throw new SessionWriterShutdownError}const sequenceBeforeRepair=this.managedSession.authority.committedSequence;await this.getManagedRuntimeOutcomes()?.recoverCommittedReceipts();if(this.sessionRestoreProjectionSource&&this.managedSession.authority.committedSequence!==sequenceBeforeRepair){projection=await this.sessionRestoreProjectionSource();this.setSessionRestoreProjection(projection)}const unresolved=await unresolvedRuntimeWorkReason(this.managedSession.authority);if(unresolved!==void 0){this.blockManagedSession(new ManagedRuntimeOutcomeUnknownError(`The Managed session's log shows Runtime work with an unknown outcome: ${unresolved}.`))}recorder.bindManagedSink(managedRecordWriter(this.managedSession,{transcriptPath:this.getTranscriptPath(),runtimeBaseDir:this.sessionRuntimeBaseDir}))}recorder.activate(lease,authoritative,persistedTitleInfo,projection?.runtime.recording);if(this.sessionRestoreProjectionSource){this.initializeGoalRuntime(projection?.runtime.goalRecords,projection?.runtime)}this.pendingSessionWriterLease=void 0;lease=void 0;this.startPendingGoalRestore()}catch(error3){let failure=error3;const ownedLease=lease??this.pendingSessionWriterLease;let releaseFailureAlreadyReported=false;const abandonedManagedSession=this.managedSession;this.managedSession=void 0;if(managed&&ownedLease){const finishing=this.finishManagedWriter(ownedLease,abandonedManagedSession);void finishing.catch(()=>void 0);this.pendingSessionWriterRelease={lease:ownedLease,promise:finishing}}if(!(failure instanceof SessionWriterError)&&!(failure instanceof ManagedSessionRecordError)&&failure&&typeof failure==="object"&&typeof failure.code==="string"){failure=new SessionWriterUnavailableError({cause:failure})}try{await this.startPendingSessionWriterRelease(ownedLease);if(this.pendingSessionWriterLease===ownedLease&&(ownedLease?.isReleased??true)&&!ownedLease?.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}if(this.sessionWriterShutdownRequested&&failure instanceof SessionWriterLostError&&ownedLease?.isReleased){failure=new SessionWriterShutdownError}}catch(releaseError){if(releaseError instanceof SessionWriterLostError||ownedLease?.isReleased&&!ownedLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}else{releaseFailureAlreadyReported=containsErrorByIdentity(failure,releaseError);if(!releaseFailureAlreadyReported){failure=new SessionWriterUnavailableError({cause:new AggregateError([failure,releaseError],"Session writer lease release failed during activation cleanup")})}}}finally{if(!releaseFailureAlreadyReported&&this.pendingSessionWriterRelease?.lease===ownedLease){this.pendingSessionWriterRelease=void 0}}this.settlePendingGoalRestore(failure);throw failure}}mcpDiscoveryPromise;startMcpDiscoveryInBackground(){const manager=this.toolRegistry.getMcpClientManager?.();if(!manager){this.debugLogger.debug("Skipping background MCP discovery: ToolRegistry has no MCP client manager");return}this.mcpDiscoveryPromise=manager.discoverAllMcpToolsIncremental(this).then(async()=>{try{await this.llmClient?.setTools()}catch(err){this.debugLogger.error(`setTools() after background MCP discovery failed: ${err instanceof Error?err.message:String(err)}`)}}).catch(err=>{this.debugLogger.error(`Background MCP discovery failed: ${err instanceof Error?err.message:String(err)}`)})}async waitForMcpReady(){if(this.mcpDiscoveryPromise){await this.mcpDiscoveryPromise}}getFailedMcpServerNames(){const servers=this.getMcpServers();if(!servers){return[]}const failed=[];for(const name2 of Object.keys(servers)){if(this.isMcpServerDisabled(name2)){continue}if(this.isMcpServerPendingApproval(name2)){continue}if(getMCPServerStatus(name2)!=="connected"){failed.push(name2)}}return failed}async refreshHierarchicalMemory(loadReason="refresh",signal){if(this.executionEnvironment)return;if(this.isSafeMode()){this.setUserMemory("");this.autoMemoryPrompt="";this.autoMemoryContext="";this.setMemoryFileCount(0);this.setContextFilePaths([]);this.conditionalRulesRegistry=new ConditionalRulesRegistry([],this.getWorkingDir());return}const{memoryContent,fileCount,contextFilePaths,conditionalRules,ignoredExtensionRules,projectRoot}=await loadServerHierarchicalMemory(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason,onInstructionsLoaded:createInstructionsLoadedCallback(()=>this.hookSystem,signal),extensionRuleSources:this.getExtensionRuleSources()});this.ignoredExtensionRules=ignoredExtensionRules??[];if(this.isManagedMemoryAvailable()){const teamMemoryEnabled=this.getTeamMemoryEnabled()&&this.isTrustedFolder();if(this.getTeamMemoryEnabled()&&!this.isTrustedFolder()){this.debugLogger.debug("Team memory enabled but inactive: workspace is not trusted.")}const teamProjectRoot=this.getProjectRoot();if(teamMemoryEnabled&&!this.teamMemoryShareabilityChecked.has(teamProjectRoot)){this.teamMemoryShareabilityChecked.add(teamProjectRoot);const shareabilityWarning=getTeamMemoryShareabilityWarning(teamProjectRoot);if(shareabilityWarning){this.warnings.push(shareabilityWarning);this.debugLogger.warn(shareabilityWarning)}}let teamAutoMemoryIndex=null;if(teamMemoryEnabled){let teamRootSecurityBlocked=false;try{teamAutoMemoryIndex=await rebuildTeamAutoMemoryIndex(teamProjectRoot)}catch(err){if(err instanceof TeamMemoryRootSecurityError){teamRootSecurityBlocked=true;this.debugLogger.warn("team memory root failed the symlink/escape safety check; skipping sync",err)}else{this.debugLogger.warn("team memory index rebuild failed (operational); not security-gating sync",err)}}if(!teamRootSecurityBlocked&&this.getTeamMemorySyncEnabled()){const syncResult=await syncTeamMemory(teamProjectRoot,{message:"chore(memory): sync team memory"}).catch(err=>{this.debugLogger.warn("team memory sync failed",err);return void 0});if(syncResult?.skippedReason){this.debugLogger.warn(`team memory sync skipped: ${syncResult.skippedReason}`)}if(syncResult?.pulled){teamAutoMemoryIndex=await rebuildTeamAutoMemoryIndex(teamProjectRoot).catch(()=>teamAutoMemoryIndex)}}}if(!this.memoryRecallModeInitialized){const corpusStatus=this.getStructuredMemoryRecallEnabled()?await this.scanMemoryRecallCorpusStatus().catch(error3=>{this.debugLogger.warn("memory metadata readiness scan failed; preserving the active recall protocol",error3);return void 0}):void 0;this.memoryRecallMode=corpusStatus?.ready?"structured":"legacy";this.memoryCorpusRevision=corpusStatus?.revision??"";this.memoryRecallModeInitialized=true}const[managedAutoMemoryIndexRead,userAutoMemoryIndexRead]=await Promise.all([readAutoMemoryIndexWithStats(this.getProjectRoot()),readUserAutoMemoryIndexWithStats().catch(()=>null)]);this.recordAutoMemoryIndexRead(getAutoMemoryIndexPath(this.getProjectRoot()),managedAutoMemoryIndexRead);this.recordAutoMemoryIndexRead(getUserAutoMemoryIndexPath(),userAutoMemoryIndexRead);const managedAutoMemoryIndex=managedAutoMemoryIndexRead?.content??null;const userAutoMemoryIndex=userAutoMemoryIndexRead?.content??null;this.setUserMemory(memoryContent);const memoryDir=getAutoMemoryRoot(this.getProjectRoot());const userSection={memoryDir:getUserAutoMemoryRoot(),indexContent:userAutoMemoryIndex};const teamSection=teamMemoryEnabled?{memoryDir:getTeamAutoMemoryRoot(this.getProjectRoot()),indexContent:teamAutoMemoryIndex}:void 0;if(this.memoryRecallMode==="structured"){this.autoMemoryPrompt=buildStructuredAutoMemoryPrompt(memoryDir,userSection.memoryDir,teamSection?.memoryDir)}else{const policy=this.memoryManager.buildAutoMemoryPrompt(memoryDir,managedAutoMemoryIndex,userSection,teamSection,{includeIndexes:false});const catalog=buildAutoMemoryIndexContext(memoryDir,managedAutoMemoryIndex,userSection,teamSection);this.autoMemoryPrompt=policy;this.autoMemoryContext=catalog}}else{this.setUserMemory(memoryContent);this.autoMemoryPrompt="";this.autoMemoryContext=""}this.setMemoryFileCount(fileCount);this.setContextFilePaths(contextFilePaths);this.conditionalRulesRegistry=new ConditionalRulesRegistry(conditionalRules,projectRoot)}recordAutoMemoryIndexRead(indexPath,indexRead){if(indexRead===null||this.getFileReadCacheDisabled()){return}this.getFileReadCache().recordRead(indexPath,indexRead.stats,{full:true,cacheable:true})}buildMemoryContextWarning(memoryContent){const contextWindowSize=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??tokenLimit(this.getModel(),"input");if(!contextWindowSize||contextWindowSize<=0||!memoryContent){return void 0}const estimatedTokens=Math.ceil(memoryContent.length/CHARS_PER_TOKEN);const ratioTokens=Math.floor(contextWindowSize*MEMORY_CONTEXT_WARNING_RATIO);const thresholdTokens=Math.min(ratioTokens,MEMORY_CONTEXT_WARNING_MAX_TOKENS);if(estimatedTokens<=thresholdTokens){return void 0}const windowClause=`${Math.round(MEMORY_CONTEXT_WARNING_RATIO*100)}% of this model's ${contextWindowSize.toLocaleString()} token context window`;const bound=thresholdTokens===ratioTokens?windowClause:`${MEMORY_CONTEXT_WARNING_MAX_TOKENS.toLocaleString()} tokens \u2014 the smaller of that and ${windowClause}`;return`Warning: Loaded always-on context (QWEN.md context files + auto-memory) uses about ${estimatedTokens.toLocaleString()} tokens, more than ${bound}. Consider trimming long always-loaded context or moving details into on-demand files.`}getMemoryDiscoveryDirectories(){if(!this.shouldLoadMemoryFromIncludeDirectories()){return[]}if(this.getBareMode()){return this.explicitIncludeDirectories}return[...this.getWorkspaceContext().getDirectories()]}getConditionalRulesRegistry(){return this.conditionalRulesRegistry}setConditionalRulesRegistry(registry3){this.conditionalRulesRegistry=registry3}getContextRuleExcludes(){return this.contextRuleExcludes}getContentGenerator(){return getRuntimeContentGenerator()?.contentGenerator??this.contentGenerator}getModelsConfig(){return this.modelsConfig}updateCredentials(credentials,settingsGenerationConfig){this.modelsConfig.updateCredentials(credentials,settingsGenerationConfig)}reloadModelProvidersConfig(modelProvidersConfig,providerProtocolConfig){this.modelsConfig.reloadModelProvidersConfig(modelProvidersConfig,providerProtocolConfig);this.captureLatestReasoning();this.baseLlmClient?.clearPerModelGeneratorCache()}getReasoningSnapshot(){return this.reasoningSnapshot??=captureReasoningSnapshot(this.getAllConfiguredModels())}stageReasoningOverrides(providers,protocols={}){const previous=this.latestReasoningSnapshot??this.getReasoningSnapshot();const models=this.getAllConfiguredModels().map(model=>{const prior=previous.find(row=>row.id===model.id&&row.authType===model.authType&&row.registryBaseUrl===model.registryBaseUrl);const configured=Object.entries(providers??{}).flatMap(([provider,entries])=>model.authType!=="qwen-oauth"&&resolveProviderProtocol(provider,protocols)===model.authType&&Array.isArray(entries)?entries:[]).find(entry=>entry?.id===model.id&&entry.baseUrl===model.registryBaseUrl);return{...model,capabilities:{...model.capabilities,reasoning:configured?configured.capabilities?.reasoning:prior?prior.reasoning:model.capabilities?.reasoning}}});return this.captureLatestReasoning(models)}captureLatestReasoning(models=this.getAllConfiguredModels()){try{const next=captureReasoningSnapshot(models);for(const row of next){if(row.authType!=="qwen-oauth"||row.reasoning?.profile){validateReasoningCapabilities({model:row.id,authType:row.authType,baseUrl:row.baseUrl},row.reasoning)}}const generation2=this.getContentGeneratorConfig();if(generation2)resolveReasoningForModel(this,{...generation2,reasoningSnapshot:next},generation2.model,true);this.latestReasoningSnapshot=next;return void 0}catch(error3){const message=`Reasoning settings not applied; keeping the previous configuration. ${getErrorMessage(error3)}`;console.warn(message);return message}}applyReasoningOverrides(){if(!this.latestReasoningSnapshot)this.captureLatestReasoning();const next=this.latestReasoningSnapshot;if(!next||JSON.stringify(next)===JSON.stringify(this.reasoningSnapshot))return false;this.reasoningSnapshot=next;const generation2=this.getContentGeneratorConfig();if(generation2)generation2.reasoningSnapshot=next;this.baseLlmClient?.clearPerModelGeneratorCache();this.notifyModelChangeListeners();return true}getModelProvidersConfig(){return this.modelsConfig.getModelProvidersConfig()}getProviderProtocolConfig(){return this.modelsConfig.getProviderProtocolConfig()}syncModelSelection(authType,modelId,baseUrl){this.modelsConfig.syncAfterAuthRefresh(authType,modelId,baseUrl);this.initialResolvedAuthType=void 0}async refreshAuth(authMethod,isInitialAuth){const hookOwner=captureHookExecutionOwner(this,null);if(!this.contentGenerator&&authMethod===this.initialAuthType){authMethod=this.initialResolvedAuthType??authMethod}const priorGeneration={...this.modelsConfig.getGenerationConfig(),authType:this.modelsConfig.getCurrentAuthType()};const priorReasoning=priorGeneration.reasoning;const priorReasoningSource=this.modelsConfig.getGenerationConfigSources()["reasoning"];const priorReasoningEffort=priorReasoning?priorReasoning.effort:void 0;const modelId=this.modelsConfig.getModel();this.modelsConfig.syncAfterAuthRefresh(authMethod,modelId);const requireCached=this.modelsConfig.consumeRequireCachedCredentialsFlag();const{config:config3,sources}=resolveContentGeneratorConfigWithSources(this,authMethod,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()});const newContentGeneratorConfig=config3;const requestModel=getRequestModel(newContentGeneratorConfig);const deepSeekRoute=getBuiltinDeepSeekReasoning({...priorGeneration,model:getRequestModel(priorGeneration)})||getBuiltinDeepSeekReasoning({...newContentGeneratorConfig,model:requestModel});const explicitOff=priorReasoningSource?.kind==="settings"&&priorReasoningSource.settingsPath==="model.reasoningEffort"||priorReasoningSource?.kind==="programmatic"&&priorReasoningSource.detail==="reasoning selection";const preserveReasoningOff=priorReasoning===false&&(requestModel!==newContentGeneratorConfig.model||newContentGeneratorConfig.thinkingMandatory!==true)&&(!deepSeekRoute||explicitOff&&priorGeneration.authType===newContentGeneratorConfig.authType&&priorGeneration.model===newContentGeneratorConfig.model&&priorGeneration.baseUrl===newContentGeneratorConfig.baseUrl&&resolveReasoningForModel(this,newContentGeneratorConfig)?.canDisable!==false);if(preserveReasoningOff){newContentGeneratorConfig.reasoning=false;if(deepSeekRoute&&priorReasoningSource)sources["reasoning"]=priorReasoningSource}this.contentGenerator=await createContentGenerator(newContentGeneratorConfig,this,requireCached?true:isInitialAuth);this.contentGeneratorConfig=newContentGeneratorConfig;this.contentGeneratorConfigSources=sources;this.publishModelEnv();if(priorReasoning===false&&newContentGeneratorConfig.reasoning===false){this.modelsConfig.getGenerationConfig().reasoning=false;if(preserveReasoningOff&&deepSeekRoute&&priorReasoningSource){this.modelsConfig.getGenerationConfigSources()["reasoning"]=priorReasoningSource}}if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}this.baseLlmClient=new BaseLlmClient(this.contentGenerator,this);const messageBus=this.getMessageBus();const hooksEnabled=!this.getDisableAllHooks();if(hooksEnabled&&messageBus){fireNotificationHook(messageBus,`Successfully authenticated with ${authMethod}`,"auth_success","Authentication successful",void 0,hookOwner).catch(()=>{})}}getBaseLlmClient(){if(!this.baseLlmClient){if(this.contentGenerator){this.baseLlmClient=new BaseLlmClient(this.getContentGenerator(),this)}else{throw new Error("BaseLlmClient not initialized. Ensure authentication has occurred and ContentGenerator is ready.")}}return this.baseLlmClient}getSessionId(){return this.sessionId}getSessionExecutionEngine(){return this.sessionExecutionEngine}getManagedRuntimeEnvironment(){if(isDerivedConfig(this))return void 0;if(!this.managedRuntimeEnvironment&&!this.shutdownRequested&&!this.managedRuntimeClosing){this.managedRuntimeEnvironment=this.managedRuntimeEnvironmentFactory?.(this)}return this.managedRuntimeEnvironment}closeManagedRuntime(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).closeManagedRuntime()}if(!this.managedRuntimeClosing){const environment=this.managedRuntimeEnvironment;this.managedRuntimeEnvironment=void 0;this.managedRuntimeClosing=Promise.resolve(environment?.dispose())}return this.managedRuntimeClosing}blockManagedSession(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).blockManagedSession(reason);return}this.managedSessionBlock??=reason}getManagedSessionBlock(){return this.managedSessionBlock}reportManagedEngineQuarantine(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).reportManagedEngineQuarantine(reason);return}this.onManagedEngineQuarantine?.(true,reason)}clearManagedEngineQuarantine(reason){if(isDerivedConfig(this)){Object.getPrototypeOf(this).clearManagedEngineQuarantine(reason);return}this.onManagedEngineQuarantine?.(false,reason)}getManagedRuntimeOutcomes(){if(isDerivedConfig(this)||!this.managedSession)return void 0;return this.managedRuntimeOutcomes??=new LocalManagedRuntimeOutcomes(this.managedSession)}getSessionRestoreRuntime(){return this.sessionRestoreRuntime}consumeSessionRestoreProjection(){const projection=this.pendingSessionRestoreProjection;this.pendingSessionRestoreProjection=void 0;return projection}hydrateSessionRestoreFileHistory(){if(this.restoredFileHistory)return;const snapshots=this.sessionRestoreRuntime?.fileHistorySnapshots;if(!snapshots?.length)return;const service=this.getFileHistoryService();if(!service.isEnabled())return;service.restoreFromSnapshots(snapshots);this.restoredFileHistory=true}finalizeSessionRestore(){const runtime=this.sessionRestoreRuntime;if(!runtime)return;this.sessionRestoreRuntime=void 0;if(runtime.attributionSnapshot){try{CommitAttributionService.getInstance().restoreFromSnapshot(runtime.attributionSnapshot)}catch(error3){this.debugLogger.error(`Session restore attribution activation failed: ${error3}`)}}const activateGoal=this.goalRestoreActivation;this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;if(activateGoal){try{void activateGoal().catch(error3=>{this.debugLogger.error(`Session restore goal activation failed: ${error3}`)})}catch(error3){this.debugLogger.error(`Session restore goal activation failed: ${error3}`)}}if(this.restoredFileHistory&&this.fileHistoryService){try{void this.fileHistoryService.validateRestoredSnapshots().catch(error3=>{this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${error3}`)})}catch(error3){this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${error3}`)}}}applyWorkspaceAgentPersona(systemPrompt,agentName,executionAllowedTools,disallowedTools){if(this.sessionSourceType!=="agent"){throw new Error("A workspace-agent persona may only be applied to an agent session.")}if(this.systemPrompt!==void 0){throw new Error("This session already has a persona; it cannot be changed in place.")}this.systemPrompt=systemPrompt;this.workspaceAgentName=agentName;this.workspaceAgentExecutionAllowedTools=executionAllowedTools?new Set(executionAllowedTools):void 0;this.workspaceAgentDisallowedTools=disallowedTools?[...disallowedTools]:void 0}getWorkspaceAgentName(){return this.workspaceAgentName}markSessionAgentSession(){if(this.sessionSourceType!=="agent"){throw new Error("Only an agent session can be marked as a session-agents session.")}this.sessionAgentSession=true;this.approvalMode="default";this.prePlanMode=void 0;this.planExecutionMode=void 0}isSessionAgentSession(){return this.sessionAgentSession&&this.sessionSourceType==="agent"}setSessionSource(sourceType,sourceId){this.sessionSourceType=sourceType;this.sessionSourceId=sourceId}getSessionSourceType(){return this.sessionSourceType}getSessionSourceId(){return this.sessionSourceId}getWarnings(){const memoryContextWarning=this.buildMemoryContextWarning([this.getUserMemory(),this.getAutoMemoryPrompt(),this.getAutoMemoryContext()].filter(Boolean).join("\n\n"));const ruleWarnings=this.ignoredExtensionRules.map(displayPath=>`Extension rule ${displayPath} has no \`paths:\` and was skipped. An extension's rules must be conditional: a baseline one would be sent with every request, which is the cost a rule exists to avoid. Add \`paths:\` to it, or move the content into the extension's context file.`);const extra=memoryContextWarning?[...ruleWarnings,memoryContextWarning]:ruleWarnings;return extra.length>0?[...this.warnings,...extra]:this.warnings}getDebugLogger(){return this.debugLogger}startNewSession(sessionId,sessionData){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot start new sessions")}if(this.chatRecordingService?.hasWriteOwnership()){throw new SessionWriterUnavailableError}if(Object.hasOwn(this,"goalRuntime")){this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.goalRuntime?.dispose()}const outgoingChatRecordingService=this.chatRecordingService;try{outgoingChatRecordingService?.finalize()}catch{}void outgoingChatRecordingService?.flush().catch(()=>{});const previousSessionId=this.sessionId;const nextSessionId=sessionId??randomUUID29();this.memoryManager.discardExtractCadence(previousSessionId,nextSessionId);const isSessionTransition=nextSessionId!==previousSessionId;if(isSessionTransition){logSessionEnd(this)}this.sessionId=nextSessionId;if(process8.env){process8.env["QWEN_CODE_SESSION_ID"]=this.sessionId}unregisterSessionModel(previousSessionId);this.publishModelEnv();this.sessionData=sessionData;this.workflowModeEpoch++;this.workflowModeContext.retire();if(isSessionTransition){const skillTool=this.toolRegistry?.getTool?.(ToolNames.SKILL);if(skillTool&&"clearLoadedSkills"in skillTool){skillTool.clearLoadedSkills()}this.toolRegistry?.clearReviewedDeclarations?.();this.permissionManager?.clearSessionAllowRules();forgetAutofixPrSession(previousSessionId);forgetAutofixPrSession(nextSessionId);this.webSearchSessionUsage.calls=0;this.advisorUsage.calls=0}this.clearSessionRestoreProjection();this.pendingRecoveredAgentsNotice=null;this.clearActiveTodoReminders();if(sessionIdContext.getStore()===void 0){setDebugLogSession(this)}this.debugLogger=createDebugLogger();outgoingChatRecordingService?.pinSessionIdentity(previousSessionId);this.chatRecordingService=this.chatRecordingEnabled?this.createChatRecordingService():void 0;this.workflowModeContext.restore(this.isWorkflowModeSupported()?this.chatRecordingService?.getSessionWorkflowMode():void 0);this.workflowModePublishedState=void 0;this.refreshWorkflowMode();this.sessionSourceService=this.sessionSourceServiceFactory?.();this.initializeGoalRuntime(this.sessionData?.conversation.messages);this.getFileReadCache().clear();this.toolResultBudget.bytesWritten=0;this.getMemoryPressureMonitor()?.resetForNewSession();this.fileHistoryService=void 0;refreshSessionContext(this.sessionId);CommitAttributionService.resetInstance();if(this.initialized){logStartSession(this,new StartSessionEvent(this),sessionData&&isSessionTransition?previousSessionId:void 0)}if(isSessionTransition){if(this.runtimeStatusEnabled){const oldPath=this.storage.getRuntimeStatusPath(previousSessionId);const newPath=this.storage.getRuntimeStatusPath(this.sessionId);const cliVersion=this.cliVersion??null;const workDir=this.targetDir;const newSessionId=this.sessionId;this.queueRuntimeStatusWrite(async()=>{await clearRuntimeStatus(oldPath);await writeRuntimeStatus(newPath,{sessionId:newSessionId,workDir,qwenVersion:cliVersion})})}if(this.sessionRegistryActive){const workDir=this.targetDir;const newSessionId=this.sessionId;this.queueRetriedSessionRegistryPatch({sessionId:newSessionId,cwd:workDir},"session registry record still names the previous session id; peers addressing this session by its new id will be refused until it is re-asserted")}}return this.sessionId}async reassertSessionRegistryRecord(){if(!this.sessionRegistryActive)return;this.queueRetriedSessionRegistryPatch({sessionId:this.sessionId,cwd:this.targetDir},"session registry record could not be re-asserted; peers may keep addressing a stale session id");await this.sessionRegistryWrite}queueRetriedSessionRegistryPatch(patch,failureWarning){this.queueSessionRegistryWrite(async()=>{const slot=this.sessionRegistrySlot;let applied=await patchSessionRecord(patch,slot);for(let attempt2=0;attempt2<2&&!applied;attempt2+=1){await delay(250);applied=await patchSessionRecord(patch,slot)}if(!applied){this.debugLogger.warn(failureWarning)}})}markRuntimeStatusEnabled(){this.runtimeStatusEnabled=true}trackSessionRegistration(registration){this.sessionRegistryActive=true;this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(async()=>{const outcome=await registration;this.sessionRegistrySlot=outcome.slot;this.sessionRegistered=outcome.registered;if(!this.sessionRegistered)this.sessionRegistryActive=false}).catch(()=>{this.sessionRegistered=false;this.sessionRegistryActive=false})}getSessionRegistrySlot(){return this.sessionRegistrySlot}async whenSessionRegistered(){await this.sessionRegistryWrite.catch(()=>{});return this.sessionRegistered}async updateSessionRegistryIpcPath(ipcPath,ipcToken){if(!this.sessionRegistryActive)return;let applied=false;this.queueSessionRegistryWrite(async()=>{const slot=this.sessionRegistrySlot;applied=await patchSessionRecord({ipcPath,ipcToken},slot);if(ipcPath===void 0||applied)return;for(let attempt2=0;attempt2<2&&!applied;attempt2+=1){await delay(250);applied=await patchSessionRecord({ipcPath,ipcToken},slot)}if(!applied){this.debugLogger.warn("peer inbox address was not published to the session registry; peers cannot discover this session until it restarts")}});await this.sessionRegistryWrite}async unregisterSessionRegistry(){this.sessionRegistryActive=false;this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(async()=>{if(!this.sessionRegistered)return;this.sessionRegistered=false;await unregisterSession(this.sessionRegistrySlot)}).catch(()=>{});await this.sessionRegistryWrite}queueRuntimeStatusWrite(write){this.runtimeStatusWrite=this.runtimeStatusWrite.catch(()=>{}).then(write).catch(()=>{})}queueSessionRegistryWrite(write){this.sessionRegistryWrite=this.sessionRegistryWrite.catch(()=>{}).then(write).catch(()=>{})}async flushRuntimeStatusWrites(){await this.runtimeStatusWrite.catch(()=>{})}async refreshCurrentRuntimeStatus(workDir){const sessionId=this.sessionId;if(this.runtimeStatusEnabled){const sidecarPath=this.storage.getRuntimeStatusPath(sessionId);this.queueRuntimeStatusWrite(async()=>{await writeRuntimeStatus(sidecarPath,{sessionId,workDir,qwenVersion:this.cliVersion??null})})}if(this.sessionRegistryActive){this.queueSessionRegistryWrite(async()=>{await patchSessionRecord({cwd:workDir,name:deriveSessionName(workDir,sessionId)},this.sessionRegistrySlot)})}await this.flushRuntimeStatusWrites()}getResumedSessionData(){return this.sessionData}shouldLoadMemoryFromIncludeDirectories(){return this.loadMemoryFromIncludeDirectories}getImportFormat(){return this.importFormat}getContentGeneratorConfig(){return getRuntimeContentGenerator()?.contentGeneratorConfig??this.contentGeneratorConfig}getContentGeneratorConfigSources(){if(Object.keys(this.contentGeneratorConfigSources).length===0&&this.modelsConfig){return this.modelsConfig.getGenerationConfigSources()}return this.contentGeneratorConfigSources}getModel(){return this.getContentGeneratorConfig()?.model||this.modelsConfig.getModel()}getCurrentModelRegistryBaseUrl(){return this.modelsConfig.getCurrentRegistryBaseUrl()}getCurrentAuthType(){return this.modelsConfig.getCurrentAuthType()}getEffectiveInputModalities(){return this.getContentGeneratorConfig()?.modalities??{}}getModelDisplayName(){return this.modelsConfig.getModelDisplayName(this.getModel())}onModelChange(listener){this.modelChangeListeners.add(listener);return()=>{this.modelChangeListeners.delete(listener)}}notifyModelChangeListeners(){this.publishModelEnv();const model=this.getModel();for(const listener of this.modelChangeListeners){listener(model)}}onApprovalModeChange(listener){this.approvalModeChangeListeners.add(listener);return()=>{this.approvalModeChangeListeners.delete(listener)}}notifyApprovalModeChangeListeners(){if(isDerivedConfig(this))return;for(const listener of this.approvalModeChangeListeners){listener(this.approvalMode,this.prePlanMode)}}publishModelEnv(){if(!process8.env){return}const model=this.getModel();registerSessionModel(this.sessionId,model,this.resolvedModelIdentity());if(this.ownsModelEnvSlot){process8.env["QWEN_CODE_MODEL"]=model;process8.env["QWEN_CODE_MODEL_IDENTITY"]=this.resolvedModelIdentity()}}resolvedModelIdentity(model=this.getModel(),generatorConfig=this.getContentGeneratorConfig()){const authType=generatorConfig?.authType??"";const baseUrl=generatorConfig?.baseUrl??(model===this.getModel()?this.getCurrentModelRegistryBaseUrl():void 0)??"";if(authType===""&&baseUrl==="")return model;const digest2=createHash29("sha256").update(`${authType}\0${baseUrl}`).digest("hex").slice(0,8);return`${model}@${digest2}`}getModelRouteIdentity(model,generatorConfig){return this.resolvedModelIdentity(model,generatorConfig)}getFastModel(){const selector=this.resolveFastModelSelector();if(!selector)return void 0;const available=selector.authType?this.getAllConfiguredModels([selector.authType]):this.getAllConfiguredModels();if(!available.some(model=>model.id===selector.modelId&&!model.voiceOnly&&!model.imageOnly&&!model.visionOnly)){return void 0}const rawSelector=resolveModelId(this.fastModel);if(!rawSelector?.authType)return selector.modelId;const qualified=`${rawSelector.authType}:${selector.modelId}`;const endpoint=this.pinnedAuxEndpoint(this.fastModel,selector.modelId,available);return endpoint?`${qualified}\0${endpoint}`:qualified}pinnedAuxEndpoint(persisted,modelId,available){const endpoint=persisted?.trim().split("\0")[1];if(!endpoint)return void 0;const hits=available.filter(model=>model.id===modelId&&model.baseUrl===endpoint);const matched=hits.find(model=>model.registryBaseUrl!==void 0)??hits[0];if(!matched){this.debugLogger.warn(`Aux endpoint pin dropped for "${modelId}": no configured entry at ${formatVisionModelSettingForLog(endpoint)}; falling back to the first same-id match.`);return void 0}return matched.registryBaseUrl}getWebSearchSettings(){return this.webSearchSettings}getWebSearchSessionUsage(){return this.webSearchSessionUsage}resolveFastModelSelector(){if(!this.fastModel)return void 0;try{const rawSelector=resolveModelId(this.fastModel);if(!rawSelector)return void 0;if(rawSelector.authType)return rawSelector;const currentAuthType=this.getContentGeneratorConfig()?.authType;if(!currentAuthType){this.debugLogger.debug("No active auth type; skipping bare fast model resolution");return void 0}return resolveModelId(this.fastModel,{currentAuthType,getAvailableModels:__name(()=>this.getAllConfiguredModels([currentAuthType]),"getAvailableModels")})}catch{return void 0}}setFastModel(model){this.fastModel=model||void 0}getAdvisorMaxUses(){return this.advisorMaxUses}getAdvisorUseCount(){return this.advisorUsage.calls}tryConsumeAdvisorUse(){if(this.advisorMaxUses>0&&this.advisorUsage.calls>=this.advisorMaxUses)return false;this.advisorUsage.calls+=1;return true}getAdvisorModel(){return this.advisorModel}async setAdvisorModel(model){const normalizedModel=normalizeAdvisorModel(model);if(normalizedModel&&this.getDisabledTools().has(ToolNames.ADVISOR)){return false}this.advisorModel=normalizedModel;if(!this.initialized||!this.toolRegistry){return true}await this.syncAdvisorToolRegistration(this.toolRegistry);await this.llmClient?.setTools();return true}setVisionModel(model){this.visionModel=model||void 0}getCompactionModel(){const selector=this.resolveCompactionModelSelector();if(selector){const available=selector.authType?this.getAllConfiguredModels([selector.authType]):this.getAllConfiguredModels();if(!available.some(m2=>m2.id===selector.modelId&&!m2.fastOnly&&!m2.voiceOnly&&!m2.imageOnly&&!m2.visionOnly)){return void 0}const rawSelector=resolveModelId(this.compactionModel);if(!rawSelector?.authType)return selector.modelId;const qualified=`${rawSelector.authType}:${selector.modelId}`;const endpoint=this.pinnedAuxEndpoint(this.compactionModel,selector.modelId,available);return endpoint?`${qualified}\0${endpoint}`:qualified}return this.getModel()}resolveCompactionModelSelector(){if(!this.compactionModel)return void 0;try{const rawSelector=resolveModelId(this.compactionModel);if(!rawSelector)return void 0;if(rawSelector.authType)return rawSelector;const currentAuthType=this.getContentGeneratorConfig()?.authType;if(!currentAuthType){this.debugLogger.debug("No active auth type; skipping bare compaction model resolution");return void 0}return resolveModelId(this.compactionModel,{currentAuthType,getAvailableModels:__name(()=>this.getAllConfiguredModels([currentAuthType]),"getAvailableModels")})}catch{return void 0}}setCompactionModel(model){this.compactionModel=model||void 0}async setImageModel(model){this.imageModel=model||void 0;if(!this.initialized||!this.toolRegistry){return}if(this.isImageGenerationEnabled()){await this.registerImageGenerationTool(this.toolRegistry);await this.toolRegistry.ensureTool(ToolNames.IMAGE_GEN)}await this.llmClient.setTools()}getModelFallbacks(){return this.modelFallbacks}getReasoningEffort(){const reasoning=this.getContentGeneratorConfig()?.reasoning;if(!reasoning){return void 0}return reasoning.effort}getReasoningEffortOverride(){const cfg=this.getContentGeneratorConfig();if(!cfg||!DashScopeOpenAICompatibleProvider.isDashScopeProvider(cfg)){return void 0}const configuredReasoning=resolveReasoningForModel(this,cfg);const model=getRequestModel(cfg);const tieredModel=isTieredEffortWireModel(model,configuredReasoning);if(!tieredModel)return void 0;const currentEffort=this.getReasoningEffort();const selected=selectDashScopeThinkingKnob(model,cfg.extra_body,cfg.samplingParams,currentEffort,tieredModel);if(!selected||selected.source==="reasoning"||selected.field==="reasoning_effort"&&selected.value===currentEffort){return void 0}if(selected.field==="enable_thinking"&&selected.value===true){if(selected.source!=="extra_body"){return void 0}const below=selectDashScopeThinkingKnob(model,void 0,cfg.samplingParams,currentEffort,tieredModel);if(below?.source==="samplingParams"&&below.field==="reasoning_effort"&&below.value!==currentEffort){return{source:below.source,field:below.field}}return void 0}return{source:selected.source,field:selected.field}}setReasoningEffort(effort){const applyEffort=__name(cfg=>{setGeneratorReasoningEffort(cfg,effort)},"applyEffort");applyEffort(this.contentGeneratorConfig);const runtimeCfg=getRuntimeContentGenerator()?.contentGeneratorConfig;if(runtimeCfg&&runtimeCfg!==this.contentGeneratorConfig){applyEffort(runtimeCfg)}applyEffort(this.modelsConfig?.getGenerationConfig())}isCurrentPrimaryModel(model){if(model.id!==this.getModel())return false;const cfg=this.getContentGeneratorConfig();const primaryAuthType=cfg?.authType;if(primaryAuthType===void 0)return true;if(model.authType!==primaryAuthType)return false;const primaryBaseUrl=cfg?.baseUrl;if(primaryBaseUrl!==void 0&&model.baseUrl!==void 0){return model.baseUrl===primaryBaseUrl}return true}resolveVisionModelSelection(){if(!this.visionModel)return void 0;const visionModelForLog=formatVisionModelSettingForLog(this.visionModel);const parsedSetting=parseVisionModelSetting(this.visionModel);if(!parsedSetting){this.debugLogger.warn(`vision model pin '${visionModelForLog}' could not be parsed; falling back to auto-select`);return void 0}let selector;try{selector=resolveModelId(parsedSetting.selector)}catch{this.debugLogger.warn(`vision model pin '${visionModelForLog}' could not be parsed; falling back to auto-select`);return void 0}if(!selector){this.debugLogger.warn(`vision model pin '${visionModelForLog}' resolved to no selector; falling back to auto-select`);return void 0}const routeMatches=this.getAllConfiguredModels().filter(m2=>m2.id===selector.modelId&&(!selector.authType||m2.authType===selector.authType)&&(!parsedSetting.baseUrl||m2.baseUrl===parsedSetting.baseUrl)&&!m2.fastOnly&&!m2.voiceOnly&&!m2.imageOnly&&!this.isCurrentPrimaryModel(m2));if(routeMatches.length>1){this.debugLogger.warn(`vision model pin '${visionModelForLog}' matched multiple configured routes; falling back to auto-select`);return void 0}const match=routeMatches[0];if(!match){this.debugLogger.warn(`vision model pin '${visionModelForLog}' did not match a usable configured model (removed, mistyped, selector-only, or the primary itself); falling back to auto-select`);return void 0}const agentCapable=isFullTurnVisionCapable(match);return{id:getQualifiedVisionModelId(match),...(parsedSetting.baseUrl??match.baseUrl)&&{baseUrl:parsedSetting.baseUrl??match.baseUrl},...agentCapable&&{agentCapable:true}}}getDefaultVisionBridgeModel(){const explicit=this.resolveVisionModelSelection();if(explicit)return explicit;const contentGeneratorConfig=this.getContentGeneratorConfig();return selectVisionBridgeModel(this.getModel(),this.getAllConfiguredModels(),{authType:contentGeneratorConfig?.authType,baseUrl:contentGeneratorConfig?.baseUrl})}getVisionBridgeTimeoutMs(){return this.visionBridgeTimeoutMs}async setModel(newModel,metadata){await this.modelsConfig.setModel(newModel,metadata);if(this.contentGeneratorConfig){this.contentGeneratorConfig.model=newModel}this.notifyModelChangeListeners()}async handleModelChange(authType,requiresRefresh){this.initialResolvedAuthType=void 0;if(!this.contentGeneratorConfig){return}const priorReasoningEffort=this.getReasoningEffort();if(authType==="qwen-oauth"&&!requiresRefresh){const{config:config3,sources}=resolveContentGeneratorConfigWithSources(this,authType,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()});this.contentGeneratorConfig.reasoningRouteBaseUrl=config3.reasoningRouteBaseUrl;this.contentGeneratorConfig.model=config3.model;this.contentGeneratorConfig.samplingParams=config3.samplingParams;this.contentGeneratorConfig.contextWindowSize=config3.contextWindowSize;this.contentGeneratorConfig.enableCacheControl=config3.enableCacheControl;this.contentGeneratorConfig.enableRequestMetadata=config3.enableRequestMetadata;this.contentGeneratorConfig.forceGlobalCacheScope=config3.forceGlobalCacheScope;this.contentGeneratorConfig.cacheRetention=config3.cacheRetention;this.contentGeneratorConfig.cacheRetentionByBlock=config3.cacheRetentionByBlock;this.contentGeneratorConfig.splitToolMedia=config3.splitToolMedia;this.contentGeneratorConfig.toolResultContentFormat=config3.toolResultContentFormat;this.contentGeneratorConfig.modalities=config3.modalities;if("model"in sources){this.contentGeneratorConfigSources["model"]=sources["model"]}if("modalities"in sources){this.contentGeneratorConfigSources["modalities"]=sources["modalities"]}if("samplingParams"in sources){this.contentGeneratorConfigSources["samplingParams"]=sources["samplingParams"]}if("enableCacheControl"in sources){this.contentGeneratorConfigSources["enableCacheControl"]=sources["enableCacheControl"]}if("enableRequestMetadata"in sources){this.contentGeneratorConfigSources["enableRequestMetadata"]=sources["enableRequestMetadata"]}if("forceGlobalCacheScope"in sources){this.contentGeneratorConfigSources["forceGlobalCacheScope"]=sources["forceGlobalCacheScope"]}if("cacheRetention"in sources){this.contentGeneratorConfigSources["cacheRetention"]=sources["cacheRetention"]}if("cacheRetentionByBlock"in sources){this.contentGeneratorConfigSources["cacheRetentionByBlock"]=sources["cacheRetentionByBlock"]}if("contextWindowSize"in sources){this.contentGeneratorConfigSources["contextWindowSize"]=sources["contextWindowSize"]}if("splitToolMedia"in sources){this.contentGeneratorConfigSources["splitToolMedia"]=sources["splitToolMedia"]}if("toolResultContentFormat"in sources){this.contentGeneratorConfigSources["toolResultContentFormat"]=sources["toolResultContentFormat"]}if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}resetPreloadedContentGenerator(this.contentGenerator);return}await this.refreshAuth(authType);if(priorReasoningEffort){this.setReasoningEffort(priorReasoningEffort)}}getAvailableModels(){return this.modelsConfig.getAvailableModels()}getAvailableModelsForAuthType(authType){return this.modelsConfig.getAvailableModelsForAuthType(authType)}getAllConfiguredModels(authTypes){return this.modelsConfig.getAllConfiguredModels(authTypes)}getResolvedModelConfig(authType,modelId,baseUrl){return this.modelsConfig.getResolvedModel(authType,modelId,baseUrl)}getActiveRuntimeModelSnapshot(){return this.modelsConfig.getActiveRuntimeModelSnapshot()}async switchModel(authType,modelId,options2){await this.modelsConfig.switchModel(authType,modelId,options2);this.notifyModelChangeListeners()}getMaxSessionTurns(){return this.maxSessionTurns}getGoalTokenBudgetGrant(){return this.goalTokenBudgetGrant}getGoalTurnBudgetGrant(){return this.goalTurnBudgetGrant}getGoalActiveTimeBudgetGrantMs(){return this.goalActiveTimeBudgetGrantMs}getMaxSubagentDepth(){return this.maxSubagentDepth}getMaxWallTimeSeconds(){return this.maxWallTimeSeconds}getMaxToolCalls(){return this.maxToolCalls}getClearContextOnIdle(){return this.clearContextOnIdle}getSessionTokenLimit(){return this.sessionTokenLimit}getEmbeddingModel(){return this.embeddingModel}getSandbox(){return this.sandbox}isRestrictiveSandbox(){const sandboxConfig=this.getSandbox();const seatbeltProfile=process8.env["SEATBELT_PROFILE"];return!!sandboxConfig&&sandboxConfig.command==="sandbox-exec"&&!!seatbeltProfile&&seatbeltProfile.startsWith("restrictive-")}getTargetDir(){return this.targetDir}getCurrentSessionArtifactMoves(oldStorage,newStorage){const oldChatsDir=path88.join(oldStorage.getProjectDir(),"chats");const newChatsDir=path88.join(newStorage.getProjectDir(),"chats");return[`${this.sessionId}.jsonl`,`${this.sessionId}.runtime.json`,`${this.sessionId}.worktree.json`,`${this.sessionId}.pr.json`].map(fileName=>({from:path88.join(oldChatsDir,fileName),to:path88.join(newChatsDir,fileName)}))}moveFile(from,to2){try{fs80.renameSync(from,to2)}catch(error3){if(error3.code!=="EXDEV"){throw error3}let copied=false;try{fs80.copyFileSync(from,to2);copied=true;fs80.unlinkSync(from)}catch(fallbackError){if(copied){try{fs80.unlinkSync(to2)}catch{}}throw fallbackError}}}moveCurrentSessionArtifacts(oldStorage,newStorage){const moved=[];for(const{from,to:to2}of this.getCurrentSessionArtifactMoves(oldStorage,newStorage)){if(!fs80.existsSync(from)){continue}fs80.mkdirSync(path88.dirname(to2),{recursive:true});try{this.moveFile(from,to2);moved.push({from,to:to2})}catch(error3){for(const movedArtifact of moved.reverse()){try{fs80.mkdirSync(path88.dirname(movedArtifact.from),{recursive:true});this.moveFile(movedArtifact.to,movedArtifact.from)}catch(rollbackError){this.debugLogger.warn("Failed to roll back moved session artifact",rollbackError)}}throw error3}}}async prepareSessionArtifactMigration(oldStorage,newStorage,oldDir,opts){try{this.chatRecordingService?.finalize();await this.chatRecordingService?.flush()}catch(error3){this.debugLogger.debug("Continuing session artifact migration after chat recording settle failed:",error3)}await this.flushRuntimeStatusWrites();try{this.moveCurrentSessionArtifacts(oldStorage,newStorage)}catch(error3){if(!opts?.skipProcessChdir){try{process8.chdir(oldDir)}catch(rollbackError){this.debugLogger.warn("Failed to roll back working directory after session artifact migration failed",rollbackError)}}throw error3}}async relocateWorkingDirectory(newDir,expectedCanonicalDir,opts){if(this.shellExecutionSandbox){assertShellSandboxCwd(this.shellExecutionSandbox,path88.resolve(newDir))}if(isDerivedConfig(this)){throw new Error("Derived Configs cannot relocate working directories")}if(this.sessionExecutionEngine==="managed"){throw new Error("A Managed session cannot change its directory.")}if(!opts?.skipArtifactMigration&&this.chatRecordingService?.hasWriteOwnership()){throw new SessionWriterUnavailableError}const oldDir=opts?.skipProcessChdir?this.cwd:fs80.realpathSync(process8.cwd());const targetPath=path88.resolve(newDir);const expected=expectedCanonicalDir??fs80.realpathSync(targetPath);if(!fs80.statSync(targetPath).isDirectory()){throw new Error(`Path is not a directory: ${targetPath}`)}const workspaceDirectories=WorkspaceContext.resolveRootDirectories(expected,this.explicitIncludeDirectories);if(!opts?.skipProcessChdir){process8.chdir(targetPath);const actualCwd=fs80.realpathSync(process8.cwd());if(actualCwd!==expected){process8.chdir(oldDir);throw new Error(`Changed directory to ${actualCwd}, expected ${expected}.`)}}else{const actualCanonical=fs80.realpathSync(targetPath);if(actualCanonical!==expected){throw new Error(`Realpath mismatch: resolved ${actualCanonical}, expected ${expected}.`)}}const oldStorage=this.storage;if(!opts?.skipArtifactMigration){const newStorage=new Storage(expected,this.sessionRuntimeBaseDir);await this.prepareSessionArtifactMigration(oldStorage,newStorage,oldDir,opts);this.storage=newStorage;this.chatRecordingService?.resetStoragePaths()}this.backgroundTaskRegistry.disposeResidentAgents();this.targetDir=expected;this.cwd=expected;resetPreloadedContentGenerator(this.contentGenerator);await this.refreshCurrentRuntimeStatus(expected);this.workspaceContext.applyRootDirectories(workspaceDirectories);this.fileDiscoveryService=null;const sessionPrBoundCallback=this.sessionService?.getSessionPrBoundCallback();this.sessionService=void 0;if(sessionPrBoundCallback){this.getSessionService().setSessionPrBoundCallback(sessionPrBoundCallback)}this.fileHistoryService=void 0;this.getFileReadCache().clear();this.memoryRecallMode="legacy";this.memoryCorpusRevision="";this.memoryRecallModeInitialized=false;this.autoMemoryPrompt="";this.autoMemoryContext="";let memoryRefreshError;try{await this.refreshHierarchicalMemory()}catch(error3){memoryRefreshError=error3}let mcpRefreshError;try{await this.waitForMcpReady();await this.refreshMcpServers()}catch(error3){mcpRefreshError=error3}return{...memoryRefreshError!==void 0&&{memoryRefreshError},...mcpRefreshError!==void 0&&{mcpRefreshError}}}setPendingStartupWorktreeNotice(notice){this.pendingStartupWorktreeNotice=notice}consumePendingStartupWorktreeNotice(){const v2=this.pendingStartupWorktreeNotice;this.pendingStartupWorktreeNotice=null;return v2}getProjectRoot(){return this.targetDir}getCwd(){return this.targetDir}getWorkspaceContext(){return this.workspaceContext}getToolRegistry(){return this.toolRegistry}async shutdown(options2){if(isDerivedConfig(this))return;this.shutdownRequested=true;this.workflowModeEpoch++;this.workflowModeContext.retire();this.workflowModeListeners.clear();forgetAutofixPrSession(this.sessionId);void this.shutdownExecutionEnvironments().catch(()=>void 0);this.settingsWatcher?.stopWatching();if(this.managedRuntimeEnvironment||this.managedRuntimeClosing){try{await this.closeManagedRuntime()}catch(error3){this.debugLogger.error("Failed to stop the Managed Runtime worker:",error3)}}const closeWriter=__name(()=>this.closeSessionWriter().catch(error3=>{this.debugLogger.error("Failed to release session writer lease:",error3)}),"closeWriter");const earlyWriterClose=!options2?.skipSessionWriter&&this.initializationPromise!==void 0&&!this.initializationSucceeded?closeWriter():void 0;try{if(!options2?.skipSessionWriter&&!earlyWriterClose){try{this.chatRecordingService?.finalize();await this.chatRecordingService?.flush()}catch{}}try{await this.shutdownResources(options2?.strictResourceCleanup===true)}catch(error3){if(options2?.strictResourceCleanup)throw error3}}finally{if(!options2?.skipSessionWriter){await(earlyWriterClose??closeWriter())}this.chatRecordingFailureListeners.clear();this.requestLifecycleListeners.clear();if(options2?.shutdownTelemetry!==false&&isTelemetrySdkInitialized()){await shutdownTelemetry()}}}async shutdownResources(waitForInitialization){if(waitForInitialization){try{await this.initializationPromise}catch{}}else if(this.initializationPromise&&!this.initializationSettled){this.scheduleResourceShutdownAfterInitialization();return}return this.runResourceShutdown()}scheduleResourceShutdownAfterInitialization(){if(this.resourceShutdownAfterInitializationScheduled||!this.initializationPromise){return}this.resourceShutdownAfterInitializationScheduled=true;void this.initializationPromise.then(()=>this.runResourceShutdown(),()=>this.runResourceShutdown()).catch(error3=>{this.debugLogger.error("Deferred Config resource cleanup failed:",error3)})}runResourceShutdown(){if(this.resourceShutdownPromise){return this.resourceShutdownPromise}const shutdown=this.shutdownResourcesOnce();this.resourceShutdownPromise=shutdown;const clear=__name(()=>{if(this.resourceShutdownPromise===shutdown){this.resourceShutdownPromise=void 0}},"clear");void shutdown.then(clear,clear);return shutdown}async shutdownResourcesOnce(){let resourceError;try{this.memoryManager.cancelMigrations();this.clearSessionRestoreProjection();if(this.sessionProjectDirRegistered){unregisterSessionProjectDir(this.sessionId);this.sessionProjectDirRegistered=false}unregisterSessionModel(this.sessionId);if(Object.hasOwn(this,"goalRuntime")){this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Goal runtime disposed"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.settlePendingGoalRestore(new GoalPersistenceUnavailableError("Config shut down before the session writer became available"));this.goalRuntime?.dispose()}try{await this.lspClient?.stop?.()}catch(lspStopError){this.debugLogger.error("Error stopping LSP client:",lspStopError)}if(this.initialized){this.skillManager?.stopWatching();if(this.toolRegistry){await this.toolRegistry.stop()}this.backgroundTaskRegistry.abortAll();this.monitorRegistry.abortAll({notify:false});this.backgroundShellRegistry.abortAll();this.workflowRunRegistry.abortAll()}}catch(error3){resourceError=error3;this.debugLogger.error("Error during Config shutdown:",error3)}try{await this.shutdownExecutionEnvironments()}catch(cleanupError){const errors=cleanupError instanceof AggregateError?[...cleanupError.errors]:[cleanupError];if(resourceError!==void 0)errors.unshift(resourceError);throw new AggregateError(errors,"Container execution cleanup failed during session shutdown.")}if(resourceError!==void 0)throw resourceError;if(!this.initialized)return;try{await this.cleanupArenaRuntime();await this.cleanupTeamRuntime()}catch(error3){this.debugLogger.error("Error during session runtime cleanup:",error3);throw error3}}getPromptRegistry(){return this.promptRegistry}getResourceRegistry(){return this.resourceRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){const parts=[this.appendSystemPrompt,this.liveAppendSystemPrompt].filter(part=>Boolean(part?.trim()));return parts.length>0?parts.join("\n\n"):void 0}setLiveAppendSystemPrompt(prompt){this.liveAppendSystemPrompt=prompt}getOutputStyle(){return this.outputStyle}setOutputStyle(style){this.outputStyle=style}getCoreTools(){if(this.shellExecutionSandbox)return[ToolNames.SHELL,ToolNames.TASK_STOP,ToolNames.READ_FILE,ToolNames.WRITE_FILE,ToolNames.EDIT,ToolNames.MONITOR,ToolNames.AGENT,ToolNames.EXEC,ToolNames.GLOB,ToolNames.LS,ToolNames.ASK_USER_QUESTION,ToolNames.STRUCTURED_OUTPUT];if(this.getBareMode()){return DEFAULT_BARE_CORE_TOOLS}return this.coreTools}getPermissionsAllow(){const base2=this.permissionsAllow??[];const sdkAllow=[...this.allowedTools??[]];if(sdkAllow.length===0)return base2.length>0?base2:[];const merged=[...base2];for(const t of sdkAllow){if(t&&!merged.includes(t))merged.push(t)}return merged}getPermissionsAsk(){return this.permissionsAsk}getEagerTools(){return this.eagerTools}getPermissionsDeny(){const base2=this.permissionsDeny??[];const sdkDeny=this.excludeTools??[];if(sdkDeny.length===0)return base2.length>0?base2:[];const merged=[...base2];for(const t of sdkDeny){if(t&&!merged.includes(t))merged.push(t)}return merged}getToolDiscoveryCommand(){return this.toolDiscoveryCommand}getDisabledSlashCommands(){return this.disabledSlashCommands}getDisabledSkillNames(){return this.disabledSkillNamesProvider?.()??EMPTY_DISABLED_SKILL_NAMES}hasSkillSettingsListsProvider(){return this.skillSettingsListsProvider!==null}isSkillEnabled(skill){if(skill.level==="bundled"&&skill.name==="generated-ui"&&!this.getBundledGeneratedUiStatus().enabled){return false}const registryName=skill.name.trim().toLowerCase();const authoredName=authoredSkillName(skill).trim().toLowerCase();const extension=skill.level==="extension"?this.getExtensions().find(candidate=>candidate.name===skill.extensionName&&candidate.skills?.some(owned=>owned.name.trim().toLowerCase()===authoredName&&owned.filePath===skill.filePath)):void 0;if(skill.level==="extension"&&!extension?.isActive)return false;const disabledNames=this.getDisabledSkillNames();if(skillRestrictionNames(skill).some(entry=>disabledNames.has(entry))){return false}if(!extension||this.enabledSkillNamesProvider?.().has(registryName)){return true}const state=this.extensionManager.getExtensionSkillState(extension.id,authoredSkillName(skill));return state.workspaceEnabled??state.defaultEnabled}getDisabledSkillLevels(){return this.disabledSkillLevels}getCustomSkillDirs(){return this.customSkillDirs}getDisabledTools(){return this.disabledTools}getVisibleTools(){return this.visibleTools}getToolSearchThreshold(){return this.toolSearchThreshold}getCodeModeOnly(){return this.toolMode===ToolMode.CodeModeOnly}getFreeform(){return this.freeform}getToolMode(){return this.toolMode}setDisabledTools(disabled){this.disabledTools=new Set(disabled)}getToolCallCommand(){return this.toolCallCommand}getMcpServerCommand(){return this.mcpServerCommand}mcpTransportPool;setMcpTransportPool(pool){this.mcpTransportPool=pool}getMcpTransportPool(){return this.mcpTransportPool}getSettingsMcpServers(){return this.mcpServers}getTopTierMcpServers(){return this.topTierMcpServers}getMergedMcpServers(includeBundledGeneratedUi=true){const mcpServers={...this.mcpServers||{}};const extensions=this.getActiveExtensions();for(const extension of extensions){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key])return;mcpServers[key]={...server,extensionName:extension.config.name}})}for(const[name2,cfg]of this.runtimeMcpServers){mcpServers[name2]=cfg}if(includeBundledGeneratedUi&&this.bundledGeneratedUiActive&&this.bundledGeneratedUi.server){mcpServers[BUNDLED_GENERATED_UI_SERVER]=this.bundledGeneratedUi.server}return mcpServers}rendersMcpApps(){return this.mcpAppHostSupported&&this.sessionSourceType!=="channel"}generatedUiUnavailableReason(){if(!this.bundledGeneratedUi.enabled)return"setting-disabled";if(!this.rendersMcpApps())return"unsupported-client";if(this.getBareMode()||this.isSafeMode()||this.sandbox||this.shellExecutionSandbox||this.executionEnvironment||this.sessionExecutionEngine==="managed"||this.provisionalWorkspace||this.getSessionSourceType()==="agent-host"){return"unsupported-runtime"}if(!this.isTrustedFolder())return"workspace-untrusted";if(this.bundledGeneratedUi.unavailableReason){return this.bundledGeneratedUi.unavailableReason}if(!this.bundledGeneratedUi.server||!this.bundledGeneratedUi.skillsDir){return"assets-missing"}if(this.topTierMcpServers?.[BUNDLED_GENERATED_UI_SERVER]||this.getMergedMcpServers(false)[BUNDLED_GENERATED_UI_SERVER]){return"provider-conflict"}const qualified=`mcp__${BUNDLED_GENERATED_UI_SERVER}__${BUNDLED_GENERATED_UI_TOOL}`;if(this.allowedMcpServers&&!matchesAnyServerPattern(BUNDLED_GENERATED_UI_SERVER,this.allowedMcpServers)||this.isMcpServerDisabled(BUNDLED_GENERATED_UI_SERVER)||this.isMcpServerPendingApproval(BUNDLED_GENERATED_UI_SERVER)||[...this.disabledTools].some(name2=>name2===BUNDLED_GENERATED_UI_TOOL||name2===qualified||normalizeMcpToolName(name2)===qualified)){return"policy-disabled"}return void 0}initializeBundledGeneratedUi(options2){const reason=this.bundledGeneratedUi.enabled&&this.rendersMcpApps()&&(options2?.disableBundledGeneratedUi||options2?.skipSkillManager)?"unsupported-runtime":this.generatedUiUnavailableReason();this.bundledGeneratedUiActive=reason===void 0;this.bundledGeneratedUiStatus={version:1,enabled:this.bundledGeneratedUiActive,...reason?{reason}:{}};if(reason&&reason!=="setting-disabled"&&reason!=="unsupported-client"&&this.bundledGeneratedUi.explicit){const warning=`Bundled Generated UI is unavailable (${reason}). Restart the owning session after resolving it.`;this.warnings.push(warning);this.debugLogger.warn(warning)}}getBundledGeneratedUiStatus(){if(!this.bundledGeneratedUiActive){return{...this.bundledGeneratedUiStatus}}const reason=this.generatedUiUnavailableReason();return reason?{version:1,enabled:false,reason}:{version:1,enabled:true}}getBundledGeneratedUiSkillsDir(){return this.getBundledGeneratedUiStatus().enabled?this.bundledGeneratedUi.skillsDir:void 0}isBundledGeneratedUiServer(serverName){return serverName===BUNDLED_GENERATED_UI_SERVER&&this.bundledGeneratedUiActive&&this.getMergedMcpServers()[serverName]===this.bundledGeneratedUi.server}assertGeneratedUiServerNotReplaced(servers){if(this.bundledGeneratedUiActive&&servers?.[BUNDLED_GENERATED_UI_SERVER]){throw new Error("Generated UI is already active as a bundled provider. Restart the owning session to configure a manual generated-ui server.")}}getMcpServers(){if(this.executionEnvironment||this.shellExecutionSandbox||this.sessionExecutionEngine==="managed"){return{}}let mcpServers=this.isSafeMode()?{...this.topTierMcpServers}:this.getMergedMcpServers();if(this.bundledGeneratedUiActive&&!this.getBundledGeneratedUiStatus().enabled){delete mcpServers[BUNDLED_GENERATED_UI_SERVER]}if(this.allowedMcpServers){mcpServers=Object.fromEntries(Object.entries(mcpServers).filter(([key])=>matchesAnyServerPattern(key,this.allowedMcpServers)))}return mcpServers}getExcludedMcpServers(){return this.excludedMcpServers}setExcludedMcpServers(excluded){this.excludedMcpServers=excluded}getMcpToolIdleTimeoutMs(){return this.mcpToolIdleTimeoutMs}isMcpServerDisabled(serverName){if(matchesAnyServerPattern(serverName,this.excludedMcpServers))return true;if(this.mcpServers?.[serverName])return false;for(const extension of this.getActiveExtensions()){if(extension.config.mcpServers?.[serverName]){return this.extensionManager?.getDisabledMcpServers(extension.config.name).includes(serverName)??false}}return false}isMcpServerPendingApproval(serverName){return this.pendingMcpServers?.includes(serverName)??false}approveMcpServerForSession(serverName){if(!this.pendingMcpServers){return}this.pendingMcpServers=this.pendingMcpServers.filter(name2=>name2!==serverName)}addMcpServers(servers){this.assertGeneratedUiServerNotReplaced(servers);if(this.shellExecutionSandbox&&Object.keys(servers).length)throw new Error("Tool execution sandbox does not support MCP servers.");if(this.initialized){throw new Error("Cannot modify mcpServers after initialization")}this.mcpServers={...this.mcpServers,...servers}}setMcpServers(servers){this.assertGeneratedUiServerNotReplaced(servers);if(this.shellExecutionSandbox&&Object.keys(servers??{}).length)throw new Error("Tool execution sandbox does not support MCP servers.");this.mcpServers=servers}setAllowedMcpServers(allowed){this.allowedMcpServers=allowed}getAllowedMcpServers(){return this.allowedMcpServers}getCliAllowedMcpServerNames(){return this.cliAllowedMcpServerNames}setPendingMcpServers(pending){this.pendingMcpServers=pending}getMcpGating(){return{excluded:this.excludedMcpServers,allowed:this.allowedMcpServers,pending:this.pendingMcpServers}}getRecentlyRemovedMcpServers(){return[...this.recentlyRemovedMcpServers]}getMcpServerNames(){return Object.keys(this.getMergedMcpServers())}getMcpServerUnavailableReason(serverName){if(this.recentlyRemovedMcpServers.has(serverName))return"removed";if(!(serverName in this.getMergedMcpServers()))return void 0;if(this.allowedMcpServers&&!matchesAnyServerPattern(serverName,this.allowedMcpServers)){return"not_allowed"}if(matchesAnyServerPattern(serverName,this.excludedMcpServers))return"excluded";if(this.isMcpServerPendingApproval(serverName))return"pending_approval";return void 0}async reinitializeMcpServers(servers){this.debugLogger.debug(`[mcp-hot-reload] reinitializeMcpServers: servers=[${Object.keys(servers??{}).join(", ")}] initialized=${this.initialized} inProgress=${this.mcpReconcileInProgress}`);const prevConfigured=new Set(Object.keys(this.getMergedMcpServers()));this.setMcpServers(servers);const nextConfigured=new Set(Object.keys(this.getMergedMcpServers()));for(const name2 of nextConfigured){this.recentlyRemovedMcpServers.delete(name2)}for(const name2 of prevConfigured){if(!nextConfigured.has(name2)){this.recentlyRemovedMcpServers.add(name2)}}await this.refreshMcpServers()}async refreshMcpServers(){if(this.shellExecutionSandbox||this.sessionExecutionEngine==="managed"){return}if(!this.initialized){this.debugLogger.debug("[mcp-hot-reload] not initialized yet \u2014 deferring to boot-time discovery (no-op)");return}if(this.mcpReconcileInProgress){this.mcpReconcilePending=true;this.debugLogger.debug("[mcp-hot-reload] reconcile already in flight \u2014 coalescing into a follow-up pass");return this.mcpReconcilePromise??Promise.resolve()}this.mcpReconcileInProgress=true;const registry3=this.getToolRegistry();const runReconcile=(async()=>{try{this.debugLogger.debug("[mcp-hot-reload] running incremental reconcile (pass 1)");await registry3.getMcpClientManager().discoverAllMcpToolsIncremental(this);let pass=1;while(this.mcpReconcilePending){this.mcpReconcilePending=false;pass+=1;this.debugLogger.debug(`[mcp-hot-reload] running coalesced incremental reconcile (pass ${pass})`);await registry3.getMcpClientManager().discoverAllMcpToolsIncremental(this)}this.debugLogger.debug(`[mcp-hot-reload] reconcile complete after ${pass} pass(es); live servers=[${Object.keys(this.getMcpServers()??{}).join(", ")}]`)}catch(err){this.debugLogger.error(`[mcp-hot-reload] reconcile failed: ${err instanceof Error?err.stack??err.message:String(err)}`);throw err}finally{this.mcpReconcileInProgress=false;this.mcpReconcilePending=false;this.mcpReconcilePromise=void 0}})();this.mcpReconcilePromise=runReconcile;await runReconcile}addRuntimeMcpServer(name2,config3){this.assertGeneratedUiServerNotReplaced({[name2]:config3});if(this.shellExecutionSandbox)throw new Error("Tool execution sandbox does not support MCP servers.");this.runtimeMcpServers.set(name2,config3)}getRuntimeMcpServers(){return Object.fromEntries(this.runtimeMcpServers)}removeRuntimeMcpServer(name2){return this.runtimeMcpServers.delete(name2)}isLspEnabled(){return this.lspEnabled&&!this.shellExecutionSandbox&&!this.getBareMode()&&!this.provisionalWorkspace}getLspClient(){return this.lspClient}getLspStatusSnapshot(){if(!this.isLspEnabled()){return this.createLspStatusSnapshot(false)}const clientSnapshot=this.lspClient?.getStatusSnapshot?.();if(clientSnapshot){return{...clientSnapshot,enabled:true,initializationError:this.lspInitializationError??clientSnapshot.initializationError}}if(this.lspClient){return{...this.createLspStatusSnapshot(true,this.lspInitializationError),statusUnavailable:true}}return this.createLspStatusSnapshot(true,this.lspInitializationError??"LSP client is not initialized")}createLspStatusSnapshot(enabled,initializationError){return{enabled,configuredServers:0,readyServers:0,failedServers:0,inProgressServers:0,notStartedServers:0,servers:[],...initializationError?{initializationError}:{}}}setLspClient(client){if(this.shellExecutionSandbox&&client)throw new Error("Tool execution sandbox does not support LSP.");if(this.initialized){throw new Error("Cannot set LSP client after initialization")}this.lspClient=client}setLspInitializationError(error3){if(this.initialized){throw new Error("Cannot set LSP status after initialization")}this.setRuntimeLspInitializationError(error3)}setRuntimeLspInitializationError(error3){this.lspInitializationError=error3 instanceof Error?error3.message:error3}async reinitializeLsp(){if(!this.isLspEnabled()||!this.lspClient?.reinitialize){return void 0}try{const result=await this.lspClient.reinitialize();if(result.reconcile.failed.length>0){this.setRuntimeLspInitializationError(`LSP reload partially failed: ${result.reconcile.failed.join(", ")}`)}else{this.setRuntimeLspInitializationError(void 0)}return result}catch(error3){this.setRuntimeLspInitializationError(error3 instanceof Error?error3:String(error3));throw error3}}getSessionSubagents(){return this.sessionSubagents}setSessionSubagents(subagents){if(this.initialized){throw new Error("Cannot modify sessionSubagents after initialization")}this.sessionSubagents=subagents}getSdkMode(){return this.sdkMode}setSdkMode(value){this.sdkMode=value}getUserMemory(){return this.userMemory}getStaticSystemPrefix(){return this.staticSystemPrefix}setStaticSystemPrefix(prefix2){this.staticSystemPrefix=prefix2}getPromptToolSnapshot(){return this.promptToolSnapshot}setPromptToolSnapshot(names){this.promptToolSnapshot=names}getPromptAgentReachable(){return this.promptAgentReachable}setPromptAgentReachable(reachable){this.promptAgentReachable=reachable}getAutoMemoryPrompt(){return this.autoMemoryPrompt}getAutoMemoryContext(){return this.memoryRecallMode==="legacy"&&this.getAutoMemoryPrompt()?this.autoMemoryContext:""}getMemoryRecallMode(){return this.memoryRecallMode}async prepareMemoryRecallTransition(){if(!this.getManagedAutoMemoryEnabled())return void 0;if(!this.getStructuredMemoryRecallEnabled())return void 0;if(this.memoryRecallMode==="structured")return void 0;const status=await this.scanMemoryRecallCorpusStatus();if(!status.ready){this.memoryCorpusRevision=status.revision;return void 0}const projectRoot=this.getProjectRoot();const teamEnabled=this.getTeamMemoryEnabled()&&this.isTrustedFolder();const configuredProjectRoot=getAutoMemoryRoot(projectRoot);await Promise.all([...getProjectMetadataMigrationRoots(projectRoot,this.isTrustedFolder()).map(root=>root===configuredProjectRoot?rebuildManagedAutoMemoryIndex(projectRoot):rebuildAutoMemoryIndexAtRoot(root,"project")),rebuildUserAutoMemoryIndex(),...teamEnabled?[rebuildTeamAutoMemoryIndex(projectRoot)]:[]].map(pending=>pending.catch(error3=>{this.debugLogger.debug(`Memory index rebuild failed during recall transition: ${error3 instanceof Error?error3.message:String(error3)}`)})));const autoMemoryPrompt=await buildStructuredAutoMemoryPrompt(getAutoMemoryRoot(projectRoot),getUserAutoMemoryRoot(),teamEnabled?getTeamAutoMemoryRoot(projectRoot):void 0);const confirmed=await this.scanMemoryRecallCorpusStatus();if(confirmed.revision!==status.revision)return void 0;return{from:"legacy",to:"structured",revision:confirmed.revision,autoMemoryPrompt,previousRevision:this.memoryCorpusRevision,previousAutoMemoryPrompt:this.autoMemoryPrompt}}async confirmMemoryRecallTransition(transition){if(transition.from!==this.memoryRecallMode)return false;const status=await this.scanMemoryRecallCorpusStatus();return status.revision===transition.revision&&(status.ready?"structured":"legacy")===transition.to}commitMemoryRecallTransition(transition){if(transition.from!==this.memoryRecallMode)return;this.memoryRecallMode=transition.to;this.memoryCorpusRevision=transition.revision;this.autoMemoryPrompt=transition.autoMemoryPrompt;this.memoryRecallModeInitialized=true}rollbackMemoryRecallTransition(transition){if(this.memoryRecallMode!==transition.to)return;this.memoryRecallMode=transition.from;this.memoryCorpusRevision=transition.previousRevision;this.autoMemoryPrompt=transition.previousAutoMemoryPrompt}scanMemoryRecallCorpusStatus(){return scanMemoryMetadataCorpusStatus({projectRoot:this.getProjectRoot(),teamMemoryEnabled:this.getTeamMemoryEnabled(),trustedProject:this.isTrustedFolder()})}getOutputLanguageFilePath(){return this.outputLanguageFilePath}setOutputLanguageFilePath(filePath){this.outputLanguageFilePath=filePath}setUserMemory(newUserMemory){this.userMemory=newUserMemory}getMemoryFileCount(){return this.memoryFileCount}setMemoryFileCount(count4){this.memoryFileCount=count4}getGeminiMdFileCount(){return this.getMemoryFileCount()}setGeminiMdFileCount(count4){this.setMemoryFileCount(count4)}getContextFilePaths(){return this.loadedContextFilePaths}setContextFilePaths(paths){this.loadedContextFilePaths=paths}getArenaManager(){return this.arenaManager}setArenaManager(manager){if(this.shellExecutionSandbox&&manager)throw new Error("Tool execution sandbox does not support agent arenas.");this.arenaManager=manager;this.arenaManagerChangeCallback?.(manager)}onArenaManagerChange(cb){this.arenaManagerChangeCallback=cb}getArenaAgentClient(){return this.arenaAgentClient}getAgentsSettings(){return this.agentsSettings}getTeamManager(){return this.teamManager}setTeamManager(manager){if(this.shellExecutionSandbox&&manager)throw new Error("Tool execution sandbox does not support agent teams.");this.teamManager=manager;for(const cb of this.teamManagerChangeCallbacks){cb(manager)}}onTeamManagerChange(cb,previous){if(previous){this.teamManagerChangeCallbacks.delete(previous)}if(cb){this.teamManagerChangeCallbacks.add(cb)}}getTeamContext(){return this.teamContext}setTeamContext(ctx){this.teamContext=ctx}async cleanupTeamRuntime(){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot clean up Team runtime")}const manager=this.teamManager;if(!manager){return}await manager.cleanup();this.setTeamManager(null);this.setTeamContext(null)}getWorktreeSymlinkDirectories(){return this.worktreeSettings.symlinkDirectories??[]}async cleanupArenaRuntime(force){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot clean up Arena runtime")}const manager=this.arenaManager;if(!manager){return}if(!force&&this.agentsSettings.arena?.preserveArtifacts){await manager.cleanupRuntime()}else{await manager.cleanup()}this.setArenaManager(null)}getApprovalMode(){return this.approvalMode}getSessionApprovalMode(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).getSessionApprovalMode()}return this.getApprovalMode()}getAutoModeSettings(){return this.permissionsAutoMode}getAutoModeDenialState(){return this.autoModeDenialState}setAutoModeDenialState(state){this.autoModeDenialState=state}getPrePlanMode(){return this.prePlanMode??"default"}getPlanExecutionMode(){return Object.hasOwn(this,"planExecutionMode")?this.planExecutionMode:void 0}setPlanMode(enabled,executionMode){if(isDerivedConfig(this)){throw new Error("Derived Configs cannot change plan workflow mode")}if(executionMode==="plan"){throw new Error("Plan is not an execution approval mode")}if(this.isSessionAgentSession?.()===true&&executionMode!=="default"){throw new Error(SESSION_AGENT_APPROVAL_MODE_ERROR)}if(!this.isTrustedFolder()&&executionMode!=="default"){throw new TrustGateError("Cannot enable privileged approval modes in an untrusted folder.")}const previousMode=this.approvalMode;const previousExecutionMode=this.planExecutionMode;if(enabled)this.planExecutionMode=executionMode;try{this.setApprovalMode(enabled?"plan":executionMode)}catch(error3){this.planExecutionMode=previousExecutionMode;throw error3}if(enabled&&previousMode==="plan"&&previousExecutionMode!==executionMode){this.notifyApprovalModeChangeListeners()}}getApprovalModeRevision(){return this.approvalModeRevision}getManualPlanExitNoticeEventState(){if(!Object.prototype.hasOwnProperty.call(this,"manualPlanExitNoticeEventState")&&Object.prototype.hasOwnProperty.call(this,"approvalMode")){const inheritedEvent=this.manualPlanExitNoticeEventState;this.manualPlanExitNoticeEventState=inheritedEvent?{...inheritedEvent}:{version:0,kind:"clear"}}return this.manualPlanExitNoticeEventState}getOwnManualPlanExitNoticeCursorState(){if(!Object.prototype.hasOwnProperty.call(this,"manualPlanExitNoticeCursorState")){this.manualPlanExitNoticeCursorState={seenVersion:0}}return this.manualPlanExitNoticeCursorState}setApprovalMode(mode,options2){if(isDerivedConfig(this)&&!Object.prototype.hasOwnProperty.call(this,"setApprovalMode")){throw new Error("Derived Configs cannot change approval mode")}if(this.isSessionAgentSession?.()===true&&mode!=="default"&&mode!=="plan"){throw new Error(SESSION_AGENT_APPROVAL_MODE_ERROR)}if(!this.isTrustedFolder()&&mode!=="default"&&mode!=="plan"){throw new TrustGateError("Cannot enable privileged approval modes in an untrusted folder.")}const fromMode=this.approvalMode;if(this.permissionManager){if(mode==="auto"&&fromMode!=="auto"){this.permissionManager.stripDangerousRulesForAutoMode()}else if(fromMode==="auto"&&mode!=="auto"){this.permissionManager.restoreDangerousRules()}}let noticeEvent=_Config.prototype.getManualPlanExitNoticeEventState.call(this);if(!Object.prototype.hasOwnProperty.call(this,"approvalMode")){noticeEvent={...noticeEvent};this.manualPlanExitNoticeEventState=noticeEvent}if(mode==="plan"&&fromMode!=="plan"){if(!isDerivedConfig(this)){this.goalProposalApprovalController?.abort()}this.prePlanMode=fromMode;noticeEvent.version++;noticeEvent.kind="clear"}else if(mode!=="plan"&&fromMode==="plan"){this.prePlanMode=void 0;noticeEvent.version++;noticeEvent.kind=options2?.fromApprovedPlanExit||options2?.fromSessionRestore?"clear":"manual-exit";if(options2?.fromApprovedPlanExit&&Object.getPrototypeOf(this)===_Config.prototype){this.approveSessionWorkflowPlanRevision()}}if(fromMode!==mode){this.autoModeDenialState=resetDenialState();if(!isDerivedConfig(this)&&mode!=="plan"&&fromMode!=="plan"){clearSessionCommits()}}this.approvalMode=mode;if(mode!=="plan")this.planExecutionMode=void 0;if(fromMode!==mode){this.approvalModeRevision++;if(!isDerivedConfig(this)){this.notifyApprovalModeChangeListeners()}}}takePendingManualPlanExitNotice(){const event=_Config.prototype.getManualPlanExitNoticeEventState.call(this);const cursor=_Config.prototype.getOwnManualPlanExitNoticeCursorState.call(this);if(event.version<=cursor.seenVersion){return void 0}cursor.seenVersion=event.version;if(event.kind!=="manual-exit"||this.approvalMode==="plan"){return void 0}return{version:event.version,currentMode:this.approvalMode}}restorePendingManualPlanExitNotice(version4){const event=_Config.prototype.getManualPlanExitNoticeEventState.call(this);const cursor=_Config.prototype.getOwnManualPlanExitNoticeCursorState.call(this);if(event.version===version4&&event.kind==="manual-exit"&&this.approvalMode!=="plan"&&cursor.seenVersion===version4){cursor.seenVersion=Math.max(0,version4-1)}}consumePendingManualPlanExitNotice(){return _Config.prototype.takePendingManualPlanExitNotice.call(this)!==void 0}getPlansDir(){return this.plansDir}getPlansAnchorTargetDir(){if(Object.prototype.hasOwnProperty.call(this,"plansDirectoryConfigured")){return this.targetDir}let current2=Object.getPrototypeOf(this);while(current2!==null&&current2!==_Config.prototype){if(Object.prototype.hasOwnProperty.call(current2,"plansDirectoryConfigured")){return current2.targetDir}current2=Object.getPrototypeOf(current2)}return this.targetDir}assertPlansDirWithinTargetDir(){if(!this.plansDirectoryConfigured){return}Storage.assertPathWithinDirectory(this.plansDir,this.getPlansAnchorTargetDir(),`plansDirectory must resolve within the project root.`)}assertPlanFilePathWithinTargetDir(filePath){if(!this.plansDirectoryConfigured){return}Storage.assertPathWithinDirectory(filePath,this.getPlansAnchorTargetDir(),`plansDirectory must resolve within the project root.`)}addLegacyPlanLocationWarning(){try{if(!this.plansDirectoryConfigured){return}const legacyPlansDir=Storage.getPlansDir();const legacyPlanFiles=this.getPlanFileNames(legacyPlansDir);if(legacyPlanFiles.length===0){return}const configuredPlanFiles=new Set(this.getPlanFileNames(this.plansDir));const hiddenLegacyPlanFiles=legacyPlanFiles.filter(fileName=>!configuredPlanFiles.has(fileName));if(hiddenLegacyPlanFiles.length===0){return}this.warnings.push(`Warning: Saved plan files exist at ${legacyPlansDir}, but plansDirectory is configured to use ${this.plansDir}. Move existing plan files to ${this.plansDir} if you want to keep using them.`)}catch(err){const message=`Failed to check legacy plan directory migration warning: ${err instanceof Error?err.message:String(err)}`;this.warnings.push(message);this.debugLogger.warn(message,err)}}getPlanFileNames(plansDir){try{return fs80.readdirSync(plansDir).filter(entry=>entry.endsWith(".md"))}catch(err){const code=err.code;if(code==="ENOENT"){return[]}if(code==="EACCES"||code==="EPERM"){const message=`Failed to read plan directory ${plansDir}: ${err instanceof Error?err.message:String(err)}`;this.warnings.push(message);this.debugLogger.warn(message,err);return[]}throw err}}getPlanFilePath(){return path88.join(this.plansDir,`${Storage.sanitizePlanSessionId(this.sessionId)}.md`)}savePlan(plan){this.assertPlansDirWithinTargetDir();const filePath=this.getPlanFilePath();const dir=path88.dirname(filePath);fs80.mkdirSync(dir,{recursive:true});const tmpPath=filePath+".tmp";fs80.writeFileSync(tmpPath,plan,"utf-8");try{fs80.renameSync(tmpPath,filePath)}catch(err){if(err.code!=="EXDEV"){throw err}fs80.copyFileSync(tmpPath,filePath);fs80.unlinkSync(tmpPath)}try{this.assertPlanFilePathWithinTargetDir(filePath)}catch(err){try{fs80.unlinkSync(filePath)}catch{}throw err}}loadPlan(){this.assertPlansDirWithinTargetDir();const filePath=this.getPlanFilePath();this.assertPlanFilePathWithinTargetDir(filePath);try{return fs80.readFileSync(filePath,"utf-8")}catch(error3){if(typeof error3==="object"&&error3!==null&&"code"in error3&&error3.code==="ENOENT"){return void 0}throw error3}}getInputFormat(){return this.inputFormat}getIncludePartialMessages(){return this.includePartialMessages}getAccessibility(){return this.accessibility}getShowResponseTokensPerSecond(){return this.showResponseTokensPerSecond}getTelemetryEnabled(){return this.telemetrySettings.enabled??false}isTelemetryInitializationDeferred(){return this.telemetryInitializationDeferred}getTelemetryLogPromptsEnabled(){return this.telemetrySettings.logPrompts??true}getTelemetryUserId(){return this.telemetrySettings.userId}getTelemetryIncludeSensitiveSpanAttributes(){return this.telemetrySettings.includeSensitiveSpanAttributes??false}getTelemetrySensitiveSpanAttributeMaxLength(){return this.telemetrySettings.sensitiveSpanAttributeMaxLength}getTelemetryOtlpEndpoint(){return this.telemetrySettings.otlpEndpoint??DEFAULT_OTLP_ENDPOINT}getTelemetryOtlpProtocol(){return this.telemetrySettings.otlpProtocol??"grpc"}getTelemetryOtlpTracesEndpoint(){return this.telemetrySettings.otlpTracesEndpoint}getTelemetryOtlpLogsEndpoint(){return this.telemetrySettings.otlpLogsEndpoint}getTelemetryOtlpMetricsEndpoint(){return this.telemetrySettings.otlpMetricsEndpoint}getTelemetryTarget(){return this.telemetrySettings.target??DEFAULT_TELEMETRY_TARGET}getTelemetryResourceAttributes(){return this.telemetrySettings.resourceAttributes??{}}getTelemetryMetricsIncludeSessionId(){return this.telemetrySettings.metrics?.includeSessionId??false}getTelemetryResourceAttributeWarnings(){return this.telemetrySettings.resourceAttributeWarnings??[]}getOutboundCorrelationPropagateTraceContext(){return this.outboundCorrelationSettings.propagateTraceContext??false}getOutboundAllowDynamicHeaderValues(){return this.outboundCorrelationSettings.allowDynamicHeaderValues??false}getTelemetryOutfile(){return this.telemetrySettings.outfile}getGitCoAuthor(){return this.gitCoAuthor}getLlmClient(){return this.llmClient}getGeminiClient(){return this.getLlmClient()}getOwnActiveTodoReminders(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoReminders")){this.activeTodoReminders=new Map}return this.activeTodoReminders}getOwnActiveTodoWorkChainOwners(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoWorkChainOwners")){this.activeTodoWorkChainOwners=new Map}return this.activeTodoWorkChainOwners}getOwnActiveTodoReminderTurns(){if(!Object.prototype.hasOwnProperty.call(this,"activeTodoReminderTurns")){this.activeTodoReminderTurns=new Map}return this.activeTodoReminderTurns}getActiveTodoWorkChainOwner(promptId,fallbackOwner=promptId){return this.getOwnActiveTodoWorkChainOwners().get(promptId)??fallbackOwner}getActiveTodoReminder(promptId){return this.getOwnActiveTodoReminders().get(this.getActiveTodoWorkChainOwner(promptId))}getActiveTodoPlanWriterOwner(){return this.activeTodoPlanWriterOwner}recordActiveTodoPlanWriter(promptId){this.activeTodoPlanWriterOwner=this.getActiveTodoWorkChainOwner(promptId)}takeActiveTodoReminder(promptId,force=false){const owner=this.getActiveTodoWorkChainOwner(promptId);const reminder=this.getOwnActiveTodoReminders().get(owner);if(!reminder)return void 0;const turns=this.getOwnActiveTodoReminderTurns();const elapsed=(turns.get(owner)??0)+1;if(!force&&elapsed<ACTIVE_TODO_REMINDER_REFRESH_TURNS){turns.set(owner,elapsed);return void 0}turns.set(owner,0);return reminder}setActiveTodoReminder(promptId,reminder){const reminders=this.getOwnActiveTodoReminders();const owner=this.getActiveTodoWorkChainOwner(promptId);if(reminder){reminders.set(owner,reminder);this.getOwnActiveTodoReminderTurns().set(owner,0)}else{reminders.clear();this.getOwnActiveTodoReminderTurns().clear();this.activeTodoPlanWriterOwner=void 0}}startActiveTodoWorkChain(promptId,continuedFrom){const reminders=this.getOwnActiveTodoReminders();const owners=this.getOwnActiveTodoWorkChainOwners();if(!continuedFrom){reminders.clear();owners.clear();this.getOwnActiveTodoReminderTurns().clear();owners.set(promptId,promptId);return}const owner=this.getActiveTodoWorkChainOwner(continuedFrom);for(const reminderOwner of reminders.keys()){if(reminderOwner!==owner)reminders.delete(reminderOwner)}for(const[mappedPromptId,mappedOwner]of owners){if(mappedOwner!==owner)owners.delete(mappedPromptId)}owners.delete(continuedFrom);owners.set(promptId,owner)}startAutomaticActiveTodoWorkChain(promptId,continuedFrom){const reminders=this.getOwnActiveTodoReminders();const owners=this.getOwnActiveTodoWorkChainOwners();const owner=continuedFrom?this.getActiveTodoWorkChainOwner(continuedFrom):promptId;owners.set(promptId,owner);if(owner===promptId)reminders.delete(owner)}endAutomaticActiveTodoWorkChain(promptId){const owners=this.getOwnActiveTodoWorkChainOwners();const owner=this.getActiveTodoWorkChainOwner(promptId);owners.delete(promptId);if(![...owners.values()].includes(owner)){this.getOwnActiveTodoReminders().delete(owner)}}clearActiveTodoReminders(){this.getOwnActiveTodoReminders().clear();this.getOwnActiveTodoWorkChainOwners().clear();this.getOwnActiveTodoReminderTurns().clear();this.activeTodoPlanWriterOwner=void 0}getMemoryPressureMonitor(){if(!Object.prototype.hasOwnProperty.call(this,"memoryPressureMonitor")){const inheritedMonitor=this.memoryPressureMonitor;if(inheritedMonitor){const inheritedConfig=this.memoryPressureConfig;if(!inheritedConfig){throw new Error("Inherited memory pressure monitor is missing config")}this.memoryPressureConfig={...inheritedConfig};this.memoryPressureMonitor=new MemoryPressureMonitor(this,this.memoryPressureConfig)}}return this.memoryPressureMonitor}getCronScheduler(){if(!this.cronScheduler){this.cronScheduler=new CronScheduler(this.getProjectRoot(),this.getCronRecurringMaxAgeDays()*24*60*60*1e3,{runGate:createCronGateRunner(this)})}return this.cronScheduler}getCronRecurringMaxAgeDays(){return this.cronRecurringMaxAgeDays}isCronEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_DISABLE_CRON"]==="1")return false;return this.cronEnabled}isLsToolEnabled(){if(this.lsToolEnabled)return true;return this.getCoreTools()?.some(name2=>parseRule(name2).toolName===ToolNames.LS)??false}isTodoWriteEnabled(){return this.todoWriteEnabled}isAgentTeamEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_ENABLE_AGENT_TEAM"]==="1")return true;return this.agentTeamEnabled}isUnifiedAgentLoopEnabled(){if(process8.env["QWEN_CODE_ENABLE_UNIFIED_AGENT_LOOP"]==="1")return true;return this.unifiedAgentLoopEnabled}isAgentCollaborationEnabled(){if(process8.env["QWEN_CODE_ENABLE_AGENT_COLLABORATION"]==="1"){return true}return this.agentCollaborationEnabled}isArtifactEnabled(){if(this.shellExecutionSandbox)return false;if(process8.env["QWEN_CODE_DISABLE_ARTIFACT"]==="1")return false;if(this.sdkMode)return false;if(!this.interactive&&!this.isArtifactSnapshotsEnabled())return false;if(process8.env["QWEN_CODE_ENABLE_ARTIFACT"]==="1")return true;return this.artifactEnabled}sessionSourceService;sessionSourceServiceFactory;setSessionSourceServiceFactory(factory){this.sessionSourceServiceFactory=factory;this.sessionSourceService=factory()}getSessionSourceService(){return Object.hasOwn(this,"sessionSourceService")?this.sessionSourceService:void 0}isRecordArtifactEnabled(){if(process8.env["QWEN_CODE_DISABLE_ARTIFACT"]==="1")return false;if(this.sdkMode)return false;if(process8.env["QWEN_CODE_ENABLE_ARTIFACT"]==="1")return true;return this.artifactEnabled}getArtifactPublisherKind(){return this.artifactPublisher}isArtifactSnapshotsEnabled(){return this.artifactSnapshotsEnabled&&this.chatRecordingEnabled}setArtifactSnapshotsEnabled(enabled){this.artifactSnapshotsEnabled=enabled}getArtifactHostConfig(){return this.artifactHost}getArtifactOssConfig(){return this.artifactOss}isOmniEnabled(){if(this.bareMode)return false;if(process8.env["QWEN_CODE_ENABLE_OMNI"]==="1")return true;return this.omniEnabled}getOmniMaxUploadFileBytes(){return this.omniMaxUploadFileBytes}getOmniMaxEstimatedTokens(){return this.omniMaxEstimatedTokens}getOmniMaxDurationSeconds(){return this.omniMaxDurationSeconds}getOmniUrlDownloadMaxFileBytes(){return this.omniUrlDownloadMaxFileBytes}getOmniUploadUrlTtlHours(){return this.omniUploadUrlTtlHours}getOmniUploadConfig(){return this.omniUploadConfig}getOmniPolicyToolsSettings(){return this.omniPolicyTools}async loadOmniMediaReader(){return import("./omni-CUJ52EW5.js")}getOmniProcessingConfig(){return this.omniProcessingConfig}getOmniMemoryConfig(){return this.omniMemoryConfig}async ensureOmniMemoryConfig(){if(!this.omniMemoryConfig){const{normalizeOmniMemoryConfig}=await import("./config-NOIFIDXC.js");this.omniMemoryConfig=normalizeOmniMemoryConfig(this.omniMemory)}return this.omniMemoryConfig}getOmniMediaResourceRegistry(){this.omniMediaResourceRegistry??=new MediaResourceRegistry;return this.omniMediaResourceRegistry}getOmniQuarantineRetentionDays(){const days=this.omniQuarantineRetentionDays;return typeof days==="number"&&Number.isFinite(days)&&days>0?days:7}getOmniQuarantineMaxBytes(){const bytes=this.omniQuarantineMaxBytes;return typeof bytes==="number"&&Number.isFinite(bytes)&&bytes>0?bytes:5*1024*1024*1024}getOmniStorageRetentionDays(){const days=this.omniStorageRetentionDays;return typeof days==="number"&&Number.isFinite(days)&&days>=1?days:14}getOmniStorageMaxTotalBytes(){const bytes=this.omniStorageMaxTotalBytes;return typeof bytes==="number"&&Number.isFinite(bytes)&&bytes>0?bytes:20*1024*1024*1024}resolveImageGenerationModel(setting){const parsedSetting=parseVisionModelSetting(setting);if(!parsedSetting)return void 0;let selector;try{selector=resolveModelId(parsedSetting.selector)}catch{return void 0}if(!selector)return void 0;const routeMatches=this.getAllConfiguredModels().filter(model=>isImageGenerationCapable(model)&&!model.fastOnly&&!model.voiceOnly&&model.id===selector.modelId&&(!selector.authType||model.authType===selector.authType)&&(!parsedSetting.baseUrl||model.baseUrl===parsedSetting.baseUrl));if(routeMatches.length!==1)return void 0;const match=routeMatches[0];const apiKeyEnv=match.envKey?.trim();const configuredBaseUrl=match.registryBaseUrl?.trim();if(!apiKeyEnv||!configuredBaseUrl)return void 0;const baseUrl=normalizeImageGenerationBaseUrl(parsedSetting.baseUrl??configuredBaseUrl);if(!baseUrl)return void 0;return{model:match.id,baseUrl,apiKeyEnv}}getImageGenerationConfig(){if(this.bareMode||this.safeMode)return void 0;return this.resolveImageGenerationModel(this.imageModel)}isImageGenerationEnabled(){if(this.shellExecutionSandbox)return false;return this.getImageGenerationConfig()!==void 0}shouldAutoOpenArtifact(){if(this.isArtifactSnapshotsEnabled())return false;if(process8.env["QWEN_ARTIFACT_NO_AUTO_OPEN"]==="1")return false;return this.artifactAutoOpen&&!this.isBrowserLaunchSuppressed()}isWorkflowsEnabled(){if(this.shellExecutionSandbox)return false;if(this.provisionalWorkspace)return false;if(process8.env["QWEN_CODE_DISABLE_WORKFLOWS"]==="1")return false;if(process8.env["QWEN_CODE_ENABLE_WORKFLOWS"]==="1")return true;return this.workflowsEnabled??false}setWorkflowsEnabled(enabled){this.workflowsEnabled=enabled;this.refreshWorkflowMode()}isWorkflowModeSupported(){return!isDerivedConfig(this)&&this.chatRecordingEnabled&&this.sessionExecutionEngine!=="managed"&&!this.executionEnvironment&&this.sessionSourceType!=="agent"&&this.sessionSourceType!=="agent-host"&&!this.shutdownRequested&&!this.sessionWriterShutdownRequested}getWorkflowMode(){if(!this.isWorkflowModeSupported()){return{requested:false,available:false,effective:false,reason:"unsupported"}}const requested=this.workflowModeContext.getRequested();if(!this.workflowModeReady){return{requested,available:false,effective:false,reason:"initializing"}}let available=false;try{available=resolveWorkflowContext(this)!==null}catch{}return{requested,available,effective:requested&&available,...!available?{reason:"workflow_unavailable"}:{}}}stageInitialWorkflowMode(enabled){if(typeof enabled!=="boolean"){throw new Error("Workflow mode must be a boolean")}if(!this.isWorkflowModeSupported()){throw new Error("Workflow mode is unsupported for this session")}if(this.initialized){throw new Error("Initial workflow mode must be staged before initialization")}if(this.initialWorkflowMode!==void 0&&this.initialWorkflowMode!==enabled){throw new Error("Conflicting initial workflow mode values")}this.initialWorkflowMode=enabled}async setWorkflowMode(enabled){if(typeof enabled!=="boolean"){throw new Error("Workflow mode must be a boolean")}if(!this.isWorkflowModeSupported()){throw new Error("Workflow mode is unsupported for this session")}if(getInvocationContext()?.workflowModeWriteAllowed===false){throw new Error("Workspace is not trusted.")}if(!this.workflowModeReady){throw new Error("Workflow mode is not initialized")}if(this.getLlmClient().isTelemetrySwapInProgress()){throw new Error("A session switch is in progress. Try again in a moment.")}const epoch=this.workflowModeEpoch;const recorder=this.chatRecordingService;const write=this.workflowModeWriteTail.then(async()=>{if(epoch!==this.workflowModeEpoch||recorder!==this.chatRecordingService||!this.isWorkflowModeSupported()){throw new Error("Workflow mode session changed")}const state=this.getWorkflowMode();if(enabled&&!state.available){throw new Error("Workflow mode is unavailable in this session")}if(!recorder)throw new SessionWriterUnavailableError;await recorder.recordSessionWorkflowMode(enabled);if(epoch!==this.workflowModeEpoch||recorder!==this.chatRecordingService||!this.isWorkflowModeSupported()){throw new Error("Workflow mode session changed")}const changed=!this.workflowModeContext.hasRecord()||this.workflowModeContext.getRequested()!==enabled;this.workflowModeContext.setRequested(enabled);if(changed)this.workflowModePublishedState=void 0;this.refreshWorkflowMode();return this.getWorkflowMode()});this.workflowModeWriteTail=write.then(()=>void 0,()=>void 0);return write}onWorkflowModeChange(listener){if(!this.isWorkflowModeSupported())return()=>{};this.workflowModeListeners.add(listener);return()=>this.workflowModeListeners.delete(listener)}refreshWorkflowMode(){if(isDerivedConfig(this))return;const state=Object.freeze(this.getWorkflowMode());this.workflowModeContext.observeAvailability(state.available);const previous=this.workflowModePublishedState;this.workflowModePublishedState=state;if(previous?.requested===state.requested&&previous.available===state.available&&previous.reason===state.reason){return}for(const listener of this.workflowModeListeners){try{listener(state)}catch(error3){this.debugLogger.warn("Workflow mode listener failed:",error3)}}}resetWorkflowModeContext(){if(this.isWorkflowModeSupported()){this.workflowModeContext.resetContext()}}hasWorkflowModeContext(){return this.isWorkflowModeSupported()&&this.workflowModeContext.hasContext()}async captureWorkflowModeState(){await this.workflowModeWriteTail;return this.isWorkflowModeSupported()?this.workflowModeContext.snapshot():new WorkflowModeContext().snapshot()}restoreWorkflowModeState(snapshot){if(!this.isWorkflowModeSupported())return;this.workflowModeEpoch++;this.workflowModeContext.restoreSnapshot(snapshot);this.chatRecordingService?.restoreSessionWorkflowMode(snapshot.recorded?snapshot.requested:void 0);this.workflowModeContext.resetContext();this.refreshWorkflowMode()}prepareWorkflowMode(keyword){if(!this.isWorkflowModeSupported()||!this.workflowModeReady){return{reminder:keyword?.reminder}}this.refreshWorkflowMode();let context2=null;try{context2=resolveWorkflowContext(this)}catch{}return this.workflowModeContext.prepare(context2,keyword)}getWorkflowKeywordTriggerEnabled(){return this.workflowKeywordTriggerEnabled}setWorkflowKeywordTriggerEnabled(enabled){this.workflowKeywordTriggerEnabled=enabled}async enableReviewWorkflow(){if(this.shellExecutionSandbox||this.workflowsEnabled===false||!isTopLevelSession()||this.getBareMode()||this.provisionalWorkspace||process8.env["QWEN_CODE_DISABLE_WORKFLOWS"]==="1"){return}if(await this.registerWorkflowTool(this.getToolRegistry())){this.setWorkflowsEnabled(true);await this.getLlmClient().setTools()}}isSessionWorkflowEnabled(){if(this.shellExecutionSandbox)return false;return this.sessionWorkflowEnabledProvider?.()??this.sessionWorkflowEnabled}setSessionWorkflowEnabledProvider(provider){this.sessionWorkflowEnabledProvider=provider;if(!this.isSessionWorkflowEnabled()){this.sessionWorkflowPlanRevision=void 0}}setExternalAgentExecutor(executor){this.externalAgentExecutor=executor}getExternalAgentExecutor(){return this.externalAgentExecutor}getAgentExecutionBackend(){return this.agentExecutionBackend}getExecutionEnvironmentFactory(){return this.shutdownRequested||this.executionShutdown.signal.aborted?void 0:this.executionEnvironmentFactory}getExecutionEnvironment(){return this.executionEnvironment}shutdownExecutionEnvironments(){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).shutdownExecutionEnvironments()}this.executionShutdown.abort();if(this.executionCleanupPromise)return this.executionCleanupPromise;const cleanup=Promise.allSettled([...this.executionEnvironments??[]].map(async pending=>{let environment;try{environment=await pending}catch(error3){if(error3 instanceof ExecutionCleanupError){if(!error3.retryCleanup)throw error3;await error3.retryCleanup()}this.executionEnvironments?.delete(pending);return}await environment.dispose();this.executionEnvironments?.delete(pending)})).then(results=>{const errors=results.flatMap(result=>result.status==="rejected"?[result.reason]:[]);if(errors.length)throw new AggregateError(errors,errors.map(String).join("; "))});let timer;this.executionCleanupPromise=new Promise((resolve36,reject)=>{timer=setTimeout(()=>reject(new ExecutionCleanupError(`Container cleanup is still pending for workspace ${this.getWorkingDir()}. Keep its workspace and inspect qwen-agent-* containers and qwen-agent-executor-* temporary directories before manual removal.`)),1e3);cleanup.then(resolve36,reject)}).catch(error3=>{console.warn(`Container execution cleanup incomplete: ${String(error3)}`);throw error3}).finally(()=>clearTimeout(timer));const clear=__name(()=>{this.executionCleanupPromise=void 0},"clear");void cleanup.then(clear,clear);return this.executionCleanupPromise}registerExecutionEnvironment(pending){if(isDerivedConfig(this)){return Object.getPrototypeOf(this).registerExecutionEnvironment(pending)}this.executionEnvironments??=new Set;this.executionEnvironments.add(pending);return()=>this.executionEnvironments?.delete(pending)}getSessionWorkflowPlanRevision(){if(!this.isSessionWorkflowEnabled())return void 0;return this.sessionWorkflowPlanRevision}setSessionWorkflowPlanRevision(revision5){if(!this.isSessionWorkflowEnabled()||revision5===void 0||revision5.planId.trim()===""||revision5.sourceCallId.trim()===""){this.sessionWorkflowPlanRevision=void 0;return}const todoIds=Array.from(new Set(revision5.todoIds.filter(todoId=>typeof todoId==="string"&&todoId.trim()!=="")));this.sessionWorkflowPlanRevision=todoIds.length>0?{planId:revision5.planId,sourceCallId:revision5.sourceCallId,todoIds,...revision5.approved?{approved:true}:{}}:void 0}clearSessionWorkflowPlanRevision(){this.sessionWorkflowPlanRevision=void 0}approveSessionWorkflowPlanRevision(){const revision5=this.getSessionWorkflowPlanRevision();if(!revision5||revision5.approved)return;this.setSessionWorkflowPlanRevision({...revision5,approved:true})}isSessionWorkflowTodoContextActive(){return this.isSessionWorkflowEnabled()&&(this.approvalMode==="plan"||this.sessionWorkflowPlanRevision!==void 0)}getModelProposedGoals(){return this.modelProposedGoals}setMcpAppHostSupported(supported){this.mcpAppHostSupported=supported}setGoalProposalHostSupported(supported){this.goalProposalHostSupported=supported}getGoalProposalHostSupported(){return this.goalProposalHostSupported}setGoalProposalTurnKey(turnKey){if(this.goalProposalTurnKey===turnKey)return false;this.goalProposalTurnKey=turnKey;return true}isGoalProposalAvailable(){return resolveInteractionMode(this)==="interactive"||this.goalProposalHostSupported&&this.goalProposalTurnKey!==void 0}hasPendingGoalProposal(){return this.pendingGoalProposal!==void 0}setPendingGoalProposal(proposal){if(this.pendingGoalProposal)return false;this.goalProposalApprovalController=new AbortController;if(this.approvalMode==="plan"){this.goalProposalApprovalController.abort()}this.pendingGoalProposal={...proposal,approvalSignal:this.goalProposalApprovalController.signal};return true}takePendingGoalProposal(expectedTurnKey){const proposal=this.pendingGoalProposal;if(expectedTurnKey!==void 0&&proposal?.turnKey!==expectedTurnKey){return void 0}this.pendingGoalProposal=void 0;return proposal}getSkipWorkflowUsageWarning(){return this.skipWorkflowUsageWarning}getWorkflowSizeGuideline(){return resolveWorkflowSizeGuidelineSetting(this.workflowSizeGuideline)}isWorkflowNameOnly(){return this.workflowNameOnly}setWorkflowSizeGuideline(size){this.workflowSizeGuideline=isWorkflowSizeGuideline(size)?size:void 0}getEmitToolUseSummaries(){const env=process8.env["QWEN_CODE_EMIT_TOOL_USE_SUMMARIES"];if(env==="0"||env==="false")return false;if(env==="1"||env==="true")return true;return this.emitToolUseSummaries}getEnableRecursiveFileSearch(){return this.fileFiltering.enableRecursiveFileSearch}getFileFilteringEnableFuzzySearch(){return this.fileFiltering.enableFuzzySearch}getFileFilteringRespectGitIgnore(){return this.fileFiltering.respectGitIgnore}getFileFilteringRespectQwenIgnore(){return this.fileFiltering.respectQwenIgnore}getFileFilteringOptions(){return{respectGitIgnore:this.fileFiltering.respectGitIgnore,respectQwenIgnore:this.fileFiltering.respectQwenIgnore,customIgnoreFiles:[...this.fileFiltering.customIgnoreFiles]}}getCustomExcludes(){return[]}getFileCheckpointingEnabled(){return!this.shellExecutionSandbox&&this.fileCheckpointingEnabled}enableFileCheckpointing(){if(this.shellExecutionSandbox)throw new Error("File checkpointing is unavailable with tools.executionSandbox.");this.fileCheckpointingEnabled=true;this.fileHistoryService=void 0}getFileHistoryService(){if(!this.fileHistoryService){const service=new FileHistoryService(this.sessionId,this.getFileCheckpointingEnabled(),this.cwd,snapshot=>{if(this.fileHistoryService!==service)return;this.getChatRecordingService()?.recordFileHistorySnapshot(snapshot)});this.fileHistoryService=service;const snapshots=this.sessionData?.fileHistorySnapshots;if(snapshots?.length&&service.isEnabled()){service.restoreFromSnapshots(snapshots);void service.validateRestoredSnapshots().catch(e=>{this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${e}`)})}}return this.fileHistoryService}getProxy(){return normalizeProxyUrl(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){if(!this.fileDiscoveryService){this.fileDiscoveryService=new FileDiscoveryService(this.targetDir,this.fileFiltering.customIgnoreFiles)}return this.fileDiscoveryService}getUsageStatisticsEnabled(){return this.usageStatisticsEnabled}getExtensionRuleSources(){return this.getActiveExtensions().filter(extension=>Boolean(extension.path)).map(extension=>({name:extension.name,dir:path88.join(extension.path,"rules")}))}getExtensionContextFilePaths(){const extensionContextFilePaths=this.getActiveExtensions().flatMap(e=>e.contextFiles);return[...extensionContextFilePaths,...this.outputLanguageFilePath?[this.outputLanguageFilePath]:[]]}getExperimentalZedIntegration(){return this.experimentalZedIntegration}getRestoreAskUserQuestion(){return this.restoreAskUserQuestion}getPreserveRestorableAskUserQuestion(){return this.preserveRestorableAskUserQuestion}suppressRestorableAskUserQuestionPreservation(){this.preserveRestorableAskUserQuestion=false}isSessionWriterLeaseEnabled(){return this.sessionWriterLeaseEnabled}getListExtensions(){return this.listExtensions}getExtensionManager(){return this.extensionManager}getHookSystem(){if(this.shellExecutionSandbox)return void 0;return this.hookSystem}hasHooksForEvent(eventName,sessionId){return this.hookSystem?.hasHooksForEvent(eventName,sessionId??this.getSessionId())??false}getDisableAllHooks(){if(this.shellExecutionSandbox)return true;if(this.hookSystem?.isManaged())return false;return this.disableAllHooks||this.getBareMode()||this.isSafeMode()}getStopHookBlockingCap(){return this.stopHookBlockingCap}getManagedAutoMemoryEnabled(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoMemory&&!this.getBareMode()&&!this.isSafeMode()}getTeamMemoryEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.provisionalWorkspace){return false}const override=process8.env["QWEN_CODE_MEMORY_TEAM"];if(override==="0"){return false}if(override==="1"){return true}return this.enableTeamMemory}getTeamMemorySyncEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.provisionalWorkspace){return false}const override=process8.env["QWEN_CODE_MEMORY_TEAM_SYNC"];if(override==="0"){return false}if(override==="1"){return true}return this.enableTeamMemorySync}getStructuredMemoryRecallEnabled(){if(this.shellExecutionSandbox)return false;if(this.getBareMode()||this.isSafeMode())return false;const override=process8.env["QWEN_CODE_MEMORY_STRUCTURED_RECALL"];if(override==="0"){return false}if(override==="1"){return true}return this.enableStructuredMemoryRecall}isManagedMemoryAvailable(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoMemory&&!this.getBareMode()}getManagedAutoDreamEnabled(){if(this.shellExecutionSandbox)return false;return this.enableManagedAutoDream&&!this.getBareMode()&&!this.isSafeMode()}getAutoSkillEnabled(){if(this.shellExecutionSandbox)return false;return this.enableAutoSkill&&!this.getBareMode()&&!this.isSafeMode()&&!this.provisionalWorkspace}setAutoSkillEnabled(enabled){this.enableAutoSkill=enabled}getAutoSkillConfirmEnabled(){return this.autoSkillConfirm&&!this.getBareMode()}getMemoryAgentTimeoutMinutes(){return this.memoryAgentTimeoutMinutes}getMemoryAgentMaxTurns(){return this.memoryAgentMaxTurns}getPreventSystemSleepEnabled(){return this.preventSystemSleep&&!this.isSafeMode()}getMemoryManager(){return this.memoryManager}getMessageBus(){return this.messageBus}setMessageBus(messageBus){if(this.messageBus===messageBus){return}this.messageBus=messageBus;this.announceMessageBus(messageBus)}onMessageBusChange(listener){this.messageBusListeners.add(listener);if(this.messageBus){this.notifyMessageBusListener(listener,this.messageBus)}return()=>{this.messageBusListeners.delete(listener)}}notifyMessageBusListener(listener,bus){try{const result=listener(bus);if(result instanceof Promise){result.catch(error3=>{this.debugLogger.debug(`MessageBus observer failed: ${error3}`)})}}catch(error3){this.debugLogger.debug(`MessageBus observer failed: ${error3}`)}}announceMessageBus(bus){for(const listener of[...this.messageBusListeners]){this.notifyMessageBusListener(listener,bus)}}getProjectHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}if(!this.isTrustedFolder()){return void 0}const hooks=this.projectHooks??(this.hasScopedHooks()?void 0:this.hooks);return hooks}getUserHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}const hooks=this.userHooks??(this.hasScopedHooks()?void 0:this.hooks);return hooks}getSystemHooks(){if(this.getBareMode()||this.isSafeMode()){return void 0}return this.systemHooks}hasScopedHooks(){return this.systemHooks!==void 0||this.userHooks!==void 0||this.projectHooks!==void 0}setHooksFromSettings(hooks){this.systemHooks=hooks.systemHooks;this.userHooks=hooks.userHooks;this.projectHooks=hooks.projectHooks;this.hooks=hooks.hooks}getExtensions(){if(this.shellExecutionSandbox)return[];const extensions=this.extensionManager.getLoadedExtensions();if(this.overrideExtensions){const overrideExtensionNames=new Set(this.overrideExtensions.map(name2=>name2.toLowerCase()));return extensions.filter(e=>overrideExtensionNames.has(e.name.toLowerCase()))}else{return extensions}}getActiveExtensions(){return this.getExtensions().filter(e=>e.isActive)}getBlockedMcpServers(){const mcpServers={...this.mcpServers||{}};const extensions=this.getActiveExtensions();for(const extension of extensions){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key])return;mcpServers[key]={...server,extensionName:extension.config.name}})}const blockedMcpServers=[];if(this.allowedMcpServers){Object.entries(mcpServers).forEach(([key,server])=>{const isAllowed=matchesAnyServerPattern(key,this.allowedMcpServers);if(!isAllowed){blockedMcpServers.push({name:key,extensionName:server.extensionName||""})}})}return blockedMcpServers}getNoBrowser(){return this.noBrowser}isBrowserLaunchSuppressed(){return this.getNoBrowser()||!shouldAttemptBrowserLaunch()}getIdeMode(){return!this.shellExecutionSandbox&&this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}getAllowedHttpHookUrls(){return this.getBareMode()||this.isSafeMode()?[]:this.allowedHttpHookUrls}getAllowPrivateNetworkHooks(){return this.getBareMode()||this.isSafeMode()?false:this.allowPrivateNetworkHooks}isTrustedFolder(){const context2=ideContextStore.get();if(context2?.workspaceState?.isTrusted!==void 0){return context2.workspaceState.isTrusted}return this.trustedFolder??!this.folderTrust}setIdeMode(value){if(this.shellExecutionSandbox&&value)throw new Error("Tool execution sandbox does not support IDE integration.");this.ideMode=value}getAuthType(){return this.getContentGeneratorConfig()?.authType}getCliVersion(){return this.cliVersion}getChannel(){return this.channel}getJsonFd(){return this.jsonFd}getJsonFile(){return this.jsonFile}getJsonSchema(){return this.jsonSchema}getInputFile(){return this.inputFile}getDefaultFileEncoding(){return this.defaultFileEncoding}getFileSystemService(){return this.fileSystemService}setFileSystemService(fileSystemService){if(this.shellExecutionSandbox){throw new Error("Internal sandbox does not support delegated filesystem services.")}this.fileSystemService=fileSystemService}getChatCompression(){return this.chatCompression}getAutoCompactThreshold(){const threshold=this.autoCompactThreshold;if(typeof threshold==="number"&&threshold>0&&threshold<=1){return threshold}return void 0}isInteractive(){return this.interactive}async getTerminalImageRenderSupport(){return this.terminalImageRenderSupportProvider?this.terminalImageRenderSupportProvider():{available:false,reason:"No terminal image renderer is configured."}}getUseRipgrep(){return this.useRipgrep}getUseBuiltinRipgrep(){return this.useBuiltinRipgrep}getShouldUseNodePtyShell(){return this.shouldUseNodePtyShell}getSkipNextSpeakerCheck(){return this.skipNextSpeakerCheck}getShellExecutionConfig(){return this.shellExecutionConfig}setShellExecutionConfig(config3){this.shellExecutionConfig={terminalWidth:config3.terminalWidth??this.shellExecutionConfig.terminalWidth,terminalHeight:config3.terminalHeight??this.shellExecutionConfig.terminalHeight,showColor:config3.showColor??this.shellExecutionConfig.showColor,pager:Object.prototype.hasOwnProperty.call(config3,"pager")?config3.pager:this.shellExecutionConfig.pager,maxBufferedOutputBytes:config3.maxBufferedOutputBytes??this.shellExecutionConfig.maxBufferedOutputBytes}}getScreenReader(){return this.accessibility.screenReader??false}getSkipLoopDetection(){return this.skipLoopDetection}getLoopProtection(){return this.loopProtection}getMaxToolCallsPerTurn(){if(this.maxToolCallsPerTurn<=0){return Number.POSITIVE_INFINITY}return this.maxToolCallsPerTurn}isMaxToolCallsPerTurnExplicit(){return this.maxToolCallsPerTurnExplicit}getSkipStartupContext(){return this.skipStartupContext}getBareMode(){return this.bareMode}isSafeMode(){return this.safeMode}getTruncateToolOutputThreshold(){if(this.truncateToolOutputThreshold<=0){return Number.POSITIVE_INFINITY}return this.truncateToolOutputThreshold}isTruncateToolOutputThresholdExplicit(){return this.truncateToolOutputThresholdExplicit}getTruncateToolOutputLines(){if(this.truncateToolOutputLines<=0){return Number.POSITIVE_INFINITY}return this.truncateToolOutputLines}getShellDefaultTimeoutMs(){return this.shellDefaultTimeoutMs}getShellHeartbeatIntervalMs(){return this.shellHeartbeatIntervalMs}getToolOutputBatchBudget(){if(this.toolOutputBatchBudget<=0){return Number.POSITIVE_INFINITY}return this.toolOutputBatchBudget}trackToolResultBytes(n){this.toolResultBudget.bytesWritten+=n}getToolResultBytesWritten(){return this.toolResultBudget.bytesWritten}getOutputFormat(){return this.outputFormat}getChatRecordingService(){if(!this.chatRecordingEnabled){return void 0}if(!this.chatRecordingService){this.chatRecordingService=this.createChatRecordingService()}return this.chatRecordingService}getGoalRuntime(){if(!Object.hasOwn(this,"goalRuntime")||!this.chatRecordingEnabled||!this.chatRecordingService||!this.goalRuntime){throw new GoalPersistenceUnavailableError}return this.goalRuntime}async getGoalRuntimeReady(){const runtime=this.getGoalRuntime();if(!Object.hasOwn(this,"goalRuntimeReady")||!this.goalRuntimeReady){throw new GoalPersistenceUnavailableError}return this.goalRuntimeReady.then(()=>runtime)}async getGoalRuntimePrepared(){const runtime=this.getGoalRuntime();if(!this.sessionRestoreRuntime)return this.getGoalRuntimeReady();return runtime.getPreparedRestore().then(()=>runtime)}async rebaseGoalRuntimeFromActiveTranscript(){const runtime=this.getGoalRuntime();const recordingService=this.chatRecordingService;if(!recordingService){throw new GoalPersistenceUnavailableError}const records=await recordingService.readActiveTranscriptChain();this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;runtime.dispose();this.initializeGoalRuntime(records);await this.goalRuntimeReady}bindGoalTurnHost(host){if(!Object.hasOwn(this,"goalRuntime")){throw new GoalPersistenceUnavailableError}const generation2=this.goalTurnHostGeneration+1;this.goalTurnHostGeneration=generation2;this.goalTurnHostUnbind?.();this.goalTurnHost=host;this.goalTurnHostUnbind=this.goalRuntime?.bindHost(host);return()=>{if(this.goalTurnHostGeneration!==generation2||this.goalTurnHost!==host){return}this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.goalTurnHost=void 0}}onChatRecordingFailure(listener){this.chatRecordingFailureListeners.add(listener);return()=>{this.chatRecordingFailureListeners.delete(listener)}}onRequestLifecycle(listener){this.requestLifecycleListeners.add(listener);return()=>this.requestLifecycleListeners.delete(listener)}notifyRequestLifecycle(event){for(const listener of this.requestLifecycleListeners){try{listener(event)}catch(error3){this.debugLogger.warn("Request lifecycle listener failed:",error3)}}}createChatRecordingService(){return new ChatRecordingService(this,event=>{this.notifyChatRecordingFailure(event)},this.sessionWriterLeaseEnabled,this.sessionRestoreRuntime?.recording)}initializeGoalRuntime(records,restoreRuntime){this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Goal runtime replaced"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0;this.goalTurnHostUnbind?.();this.goalTurnHostUnbind=void 0;this.settlePendingGoalRestore(new GoalPersistenceUnavailableError("Goal runtime was replaced before the session writer became available"));this.goalProposalApprovalController?.abort();this.goalProposalApprovalController=void 0;this.pendingGoalProposal=void 0;if(!this.chatRecordingService){this.goalRuntime=void 0;this.goalRuntimeReady=void 0;return}const recorder=this.chatRecordingService;const runtime=createGoalRuntime({journal:recorder,evidenceSource:recorder,ledger:recorder,verifier:createGoalVerifier(this),tokenBudgetGrant:this.goalTokenBudgetGrant,turnBudgetGrant:this.goalTurnBudgetGrant,activeTimeBudgetGrantMs:this.goalActiveTimeBudgetGrantMs});runtime.subscribe((snapshot,cause,meta4)=>{if(meta4?.replayed)return;const event=goalStateEventFromSnapshot(snapshot,cause);if(event)logGoalState(this,event)});this.goalRuntime=runtime;if(this.goalTurnHost){this.goalTurnHostUnbind=runtime.bindHost(this.goalTurnHost)}if(restoreRuntime){const preparation=runtime.prepareRestore(records??[]);let resolveActivation;let rejectActivation;const activation=new Promise((resolve36,reject)=>{resolveActivation=resolve36;rejectActivation=reject});this.rejectGoalRestoreActivation=rejectActivation;this.goalRestoreActivation=()=>{const started=runtime.activateRestoredWork();void started.then(resolveActivation,rejectActivation);return started};this.goalRuntimeReady=Promise.all([preparation,activation]).then(()=>runtime)}else if(this.sessionWriterLeaseEnabled&&!recorder.hasWriteOwnership()){const ready=new Promise((resolve36,reject)=>{this.pendingGoalRestore={runtime,resolve:resolve36,reject}});this.goalRuntimeReady=ready}else{this.goalRuntimeReady=runtime.restore(records??[]).then(()=>runtime)}void this.goalRuntimeReady.catch(()=>void 0)}startPendingGoalRestore(){const pending=this.pendingGoalRestore;if(!pending)return;this.pendingGoalRestore=void 0;if(pending.runtime!==this.goalRuntime){pending.reject(new GoalPersistenceUnavailableError("Goal runtime was replaced before the session writer became available"));return}void pending.runtime.restore(this.sessionData?.conversation.messages??[]).then(()=>pending.resolve(pending.runtime),error3=>pending.reject(error3))}settlePendingGoalRestore(error3){const pending=this.pendingGoalRestore;if(!pending)return;this.pendingGoalRestore=void 0;pending.reject(error3)}setSessionRestoreProjection(projection){this.pendingSessionRestoreProjection=projection;this.sessionRestoreRuntime=projection?.runtime;this.restoredFileHistory=false}clearSessionRestoreProjection(){this.pendingSessionRestoreProjection=void 0;this.sessionRestoreRuntime=void 0;this.restoredFileHistory=false;this.rejectGoalRestoreActivation?.(new GoalPersistenceUnavailableError("Session restore was abandoned"));this.goalRestoreActivation=void 0;this.rejectGoalRestoreActivation=void 0}notifyChatRecordingFailure(event){for(const listener of[...this.chatRecordingFailureListeners]){try{const notification=listener(event);if(notification){void notification.catch(error3=>{this.debugLogger.debug("Chat recording failure listener rejected:",error3)})}}catch(error3){this.debugLogger.debug("Chat recording failure listener threw:",error3)}}}getTranscriptPath(){if(!this.chatRecordingEnabled){return""}const projectDir=this.storage.getProjectDir();const sessionId=this.getSessionId();const safeFilename=`${sessionId}.jsonl`;return path88.join(projectDir,"chats",safeFilename)}async assertCanStartTurn(){if(isDerivedConfig(this))return;if(this.chatRecordingService?.hasWriteOwnership()){await this.chatRecordingService.assertCanStartTurn()}}hasSessionWriteOwnership(){if(isDerivedConfig(this))return false;return this.pendingSessionWriterLease!==void 0&&!this.pendingSessionWriterLease.isReleased||this.chatRecordingService?.hasWriteOwnership()===true}setSessionWriterReclaimPolicy(policy){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(this.initialized){throw new SessionWriterUnavailableError}this.sessionWriterReclaimPolicy=policy}setSessionWriterTakeoverPolicy(policy){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(this.initialized){throw new SessionWriterUnavailableError}this.sessionWriterTakeoverPolicy=policy}closeSessionWriter(options2){if(isDerivedConfig(this)){throw new SessionWriterUnavailableError}if(options2?.handoff&&this.sessionWriterTakeoverPolicy==="certified"){this.sessionWriterHandoffRequested=true}this.sessionWriterShutdownRequested=true;this.chatRecordingService?.beginClose({handoff:this.sessionWriterHandoffRequested});this.startPendingSessionWriterRelease();if(this.sessionWriterClosePromise)return this.sessionWriterClosePromise;const pending=this.closeSessionWriterOnce();this.sessionWriterClosePromise=pending;void pending.catch(()=>{if(this.sessionWriterClosePromise===pending){this.sessionWriterClosePromise=void 0}});return pending}async closeSessionWriterOnce(){const failures=[];const activation=this.sessionWriterActivationPromise;try{await activation}catch(error3){if(!(error3 instanceof SessionWriterShutdownError)){failures.push(error3)}}try{await this.chatRecordingService?.close({handoff:this.sessionWriterHandoffRequested})}catch(error3){failures.push(error3)}const pendingLease=activation?void 0:this.pendingSessionWriterLease;if(pendingLease){try{await this.startPendingSessionWriterRelease(pendingLease);if(this.pendingSessionWriterLease===pendingLease&&pendingLease.isReleased&&!pendingLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}}catch(error3){if(error3 instanceof SessionWriterLostError||pendingLease.isReleased&&!pendingLease.isReleaseDurabilityPending){this.pendingSessionWriterLease=void 0}failures.push(error3)}finally{if(this.pendingSessionWriterRelease?.lease===pendingLease){this.pendingSessionWriterRelease=void 0}}}if(failures.length===1){throw failures[0]}if(failures.length>1){throw new AggregateError(failures,"Session writer shutdown failed")}}startPendingSessionWriterRelease(lease=this.pendingSessionWriterLease){if(!lease)return void 0;const existing=this.pendingSessionWriterRelease;if(existing?.lease===lease)return existing.promise;if(this.sessionExecutionEngine==="managed")return void 0;const promise=lease.release();this.pendingSessionWriterRelease={lease,promise};void promise.catch(()=>void 0);return promise}getSessionRuntimeBaseDir(){return this.sessionRuntimeBaseDir}getSessionService(){if(!this.sessionService){this.sessionService=new SessionService(this.storage.getProjectRoot(),{runtimeBaseDir:this.sessionRuntimeBaseDir})}return this.sessionService}getFileExclusions(){return this.fileExclusions}getSubagentManager(){return this.subagentManager}getBackgroundTaskRegistry(){return this.backgroundTaskRegistry}getMonitorRegistry(){return this.monitorRegistry}getBackgroundAgentResumeService(){if(!this.backgroundAgentResumeService){this.backgroundAgentResumeService=new BackgroundAgentResumeService(this)}return this.backgroundAgentResumeService}async loadPausedBackgroundAgents(sessionId=this.getSessionId()){if(sessionId!==this.getSessionId()){this.debugLogger.warn(`Refusing to restore background agents for non-current session ${sessionId}.`);return[]}const service=this.getBackgroundAgentResumeService();let recovered;try{recovered=await service.loadPausedBackgroundAgents(sessionId)}catch(error3){this.debugLogger.warn(`Background agent restore failed for session ${sessionId}; continuing without restored agents.`,error3);return[]}if(recovered.length>0&&!this.getBareMode()){this.pendingRecoveredAgentsNotice=service.buildRecoveredBackgroundAgentsModelNotice(recovered.length)}return recovered}consumePendingRecoveredAgentsNotice(){const notice=this.pendingRecoveredAgentsNotice;this.pendingRecoveredAgentsNotice=null;return notice}async resumeBackgroundAgent(agentId,initialInput){return this.getBackgroundAgentResumeService().resumeBackgroundAgent(agentId,initialInput)}async reviveCompletedBackgroundAgent(agentId,initialInput){return this.getBackgroundAgentResumeService().reviveCompletedBackgroundAgent(agentId,initialInput)}abandonBackgroundAgent(agentId){return this.getBackgroundAgentResumeService().abandonBackgroundAgent(agentId)}getBackgroundShellRegistry(){return this.backgroundShellRegistry}getWorkflowRunRegistry(){return this.workflowRunRegistry}getTurnBudget(){return this.turnBudget}getFileReadCache(){if(!Object.prototype.hasOwnProperty.call(this,"fileReadCache")){this.fileReadCache=new FileReadCache}return this.fileReadCache}getFileReadCacheDisabled(){return this.fileReadCacheDisabled}getShouldAvoidPermissionPrompts(){return false}getSkillManager(){return this.skillManager}setModelInvocableCommandsProvider(provider){this.modelInvocableCommandsProvider=provider}getModelInvocableCommandsProvider(){return this.modelInvocableCommandsProvider}setModelInvocableCommandsExecutor(executor){this.modelInvocableCommandsExecutor=executor}getModelInvocableCommandsExecutor(){return this.modelInvocableCommandsExecutor}addInlineAnnouncedSkillKeys(keys2){for(const k2 of keys2){this.pendingInlineAnnouncedSkillKeys.add(k2)}}consumeInlineAnnouncedSkillKeys(){const result=this.pendingInlineAnnouncedSkillKeys;this.pendingInlineAnnouncedSkillKeys=new Set;return result}getPermissionManager(){return this.permissionManager}isWorkspaceAgentSession(){return this.isAgentCollaborationEnabled()&&this.sessionSourceType==="agent"}getWorkflowAncestorTrustProvider(){return this.workflowAncestorTrustProvider}getToolInvocationGuard(){if(this.sessionSourceType==="agent-host"){return createAgentHostToolInvocationGuard(this.toolInvocationGuard,this.getTargetDir(),candidate=>this.getWorkspaceContext().isPathWithinWorkspace(candidate))}if(this.isWorkspaceAgentSession()&&this.isSessionAgentSession()){return createSessionAgentToolInvocationGuard(this.toolInvocationGuard,this.workspaceAgentExecutionAllowedTools,this.workspaceAgentDisallowedTools)}return this.isWorkspaceAgentSession()?createAgentToolInvocationGuard(this.toolInvocationGuard,this.workspaceAgentExecutionAllowedTools):this.toolInvocationGuard}getShellExecutionSandbox(){return this.shellExecutionSandbox}getOnPersistPermissionRule(){return this.onPersistPermissionRuleCallback}async registerLazyTool(registry3,toolName,factory){let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(toolName):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${toolName}", skipping registration:`,error3);return}if(status==="deferred"){registry3.registerPermissionDeferredFactory(toolName,factory)}else if(status==="registered"){registry3.registerFactory(toolName,factory)}}async registerManagedRuntimeTools(registry3){const environment=this.getManagedRuntimeEnvironment();if(!environment)return;const[{createExecutionTools},{wrapExecutionTool}]=await Promise.all([import("./local-execution-environment-OBA6VWYL.js"),import("./execution-tool-HADWGMIG.js")]);const tools=createExecutionTools(this);for(const name2 of MANAGED_RUNTIME_TOOL_NAMES){const tool=tools.get(name2);if(!tool)continue;let status;try{status=await this.getPermissionManager()?.getToolRegistrationStatus(name2)??"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${name2}", skipping registration:`,error3);continue}if(status==="disabled")continue;registry3.registerRuntimeBackedFactory(name2,async()=>wrapExecutionTool(tool,environment,this),environment,status==="deferred")}}async registerWorkflowTool(registry3){if(registry3.getAllToolNames().includes(ToolNames.WORKFLOW))return true;await this.registerLazyTool(registry3,ToolNames.WORKFLOW,async()=>{const{WorkflowTool}=await import("./workflow-WNPHX42I.js");return new WorkflowTool(this)});return registry3.getAllToolNames().includes(ToolNames.WORKFLOW)}async registerImageGenerationTool(registry3){if(!this.isImageGenerationEnabled()||registry3.getAllToolNames().includes(ToolNames.IMAGE_GEN)){return}let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(ToolNames.IMAGE_GEN):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${ToolNames.IMAGE_GEN}", skipping registration:`,error3);return}if(status==="disabled")return;const factory=__name(async()=>{const{ImageGenTool}=await import("./image-gen-BOKEFYWN.js");return new ImageGenTool(this)},"factory");if(status==="deferred"){registry3.registerPermissionDeferredFactory(ToolNames.IMAGE_GEN,factory)}else{registry3.registerFactory(ToolNames.IMAGE_GEN,factory)}}async syncAdvisorToolRegistration(registry3){if(!this.getAdvisorModel()||this.getBareMode()||this.isSafeMode()){registry3.unregisterTool(ToolNames.ADVISOR);return}if(this.getDisabledTools().has(ToolNames.ADVISOR))return;registry3.unregisterTool(ToolNames.ADVISOR);await this.registerLazyTool(registry3,ToolNames.ADVISOR,async()=>{const{AdvisorTool}=await import("./advisor-7JGQPS7X.js");return new AdvisorTool(this)});await registry3.ensureTool(ToolNames.ADVISOR)}async registerSessionSourceTool(registry3=this.toolRegistry){if(!this.getSessionSourceService()||this.sdkMode||this.getBareMode()||this.isSafeMode()||registry3.getAllToolNames().includes(ToolNames.RECORD_SOURCE)){return}let status="registered";try{const permissionManager=this.getPermissionManager();status=permissionManager?await permissionManager.getToolRegistrationStatus(ToolNames.RECORD_SOURCE):"registered"}catch(error3){this.debugLogger.warn(`Failed to check permissions for tool "${ToolNames.RECORD_SOURCE}", skipping registration:`,error3);return}const factory=__name(async()=>{const{RecordSourceTool}=await import("./record-source-QJG4Q6UI.js");return new RecordSourceTool(this)},"factory");if(status==="deferred"){registry3.registerPermissionDeferredFactory(ToolNames.RECORD_SOURCE,factory)}else if(status==="registered"){registry3.registerFactory(ToolNames.RECORD_SOURCE,factory)}}async createToolRegistry(sendSdkMcpMessage,options2){const registry3=new ToolRegistry(this,this.eventEmitter,sendSdkMcpMessage);if(this.sessionExecutionEngine==="managed"){this.applyPendingMcpBudgetCallback(registry3);await this.registerManagedRuntimeTools(registry3);return registry3}const registerLazy=__name((toolName,factory)=>this.registerLazyTool(registry3,toolName,factory),"registerLazy");const registerStructuredOutputIfRequested=__name(async()=>{if(!this.jsonSchema)return;if(options2?.forSubAgent)return;const schema=this.jsonSchema;await registerLazy(ToolNames.STRUCTURED_OUTPUT,async()=>{const{SyntheticOutputTool}=await import("./syntheticOutput-M563X4NP.js");return new SyntheticOutputTool(schema)})},"registerStructuredOutputIfRequested");const registerGoalWorkerTools=__name(async()=>{if(options2?.forSubAgent)return;await registerLazy(ToolNames.GET_GOAL,async()=>{const{GetGoalTool:GetGoalTool2}=await import("./goal-tools-43XV33BT.js");return new GetGoalTool2(this)});await registerLazy(ToolNames.UPDATE_GOAL,async()=>{const{UpdateGoalTool:UpdateGoalTool2}=await import("./goal-tools-43XV33BT.js");return new UpdateGoalTool2(this)});if(this.getModelProposedGoals()!=="disabled"&&(resolveInteractionMode(this)==="interactive"||this.goalProposalHostSupported)){await registerLazy(ToolNames.PROPOSE_GOAL,async()=>{const{ProposeGoalTool:ProposeGoalTool2}=await import("./goal-tools-43XV33BT.js");return new ProposeGoalTool2(this)})}},"registerGoalWorkerTools");const registerExecIfEnabled=__name(async()=>{if(this.getToolMode()!==ToolMode.CodeModeOnly)return;await registerLazy(ToolNames.EXEC,async()=>{const{ExecTool}=await import("./exec-TBIZGHHK.js");return new ExecTool(this)})},"registerExecIfEnabled");const registerHostSessionTools=__name(async()=>{if(this.isTodoWriteEnabled()){await registerLazy(ToolNames.TODO_WRITE,async()=>{const{TodoWriteTool}=await import("./todoWrite-UELI33ZV.js");return new TodoWriteTool(this)})}await registerLazy(ToolNames.WEB_FETCH,async()=>{const{WebFetchTool}=await import("./web-fetch-42ZR4FEZ.js");return new WebFetchTool(this)});const hasExplicitWebSearchBackend=!!this.webSearchSettings?.model?.trim()||!!this.webSearchSettings?.baseUrl;if(!this.getBareMode()&&!this.isSafeMode()&&this.webSearchSettings?.enabled!==false&&(this.webSearchSettings?.enabled===true||!hasExplicitWebSearchBackend)){const{evaluateWebSearchGate}=await import("./web-search-74NLPMZJ.js");const gate2=evaluateWebSearchGate(this);if(gate2.ok){await registerLazy(ToolNames.WEB_SEARCH,async()=>{const{WebSearchTool}=await import("./web-search-74NLPMZJ.js");return new WebSearchTool(this)})}else if(!gate2.silent&&!this.webSearchNoticeEmitted&&!options2?.forSubAgent){this.webSearchNoticeEmitted=true;this.warnings.push(gate2.notice)}}},"registerHostSessionTools");const environment=this.getExecutionEnvironment();if(environment){if(this.getCodeModeOnly()){throw new Error("Container execution cannot be combined with tools.codeModeOnly.")}const[{createExecutionTools},{wrapExecutionTool}]=await Promise.all([import("./local-execution-environment-OBA6VWYL.js"),import("./execution-tool-HADWGMIG.js")]);for(const[name2,tool]of createExecutionTools(this)){if(environment.toolNames&&!environment.toolNames.has(name2))continue;if(name2===ToolNames.LS&&!this.isLsToolEnabled())continue;await registerLazy(name2,async()=>wrapExecutionTool(tool,environment,this))}await registerLazy(ToolNames.TOOL_CALL,async()=>{const{ToolCallTool:ToolCallTool2}=await import("./tool-call-LVB4NCDT.js");return new ToolCallTool2(registry3)});await registerLazy(ToolNames.TOOL_SEARCH,async()=>{const{ToolSearchTool}=await import("./tool-search-OG73QAQZ.js");return new ToolSearchTool(this)});if(this.executionEnvironment&&!options2?.forSubAgent){await registerStructuredOutputIfRequested();await registerGoalWorkerTools();if(!this.getBareMode())await registerHostSessionTools()}return registry3}if(this.shellExecutionSandbox){await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-WYQDZWL7.js");return new ShellTool2(this)});await registerLazy(ToolNames.TASK_STOP,async()=>{const{TaskStopTool}=await import("./task-stop-LPMYWUAI.js");return new TaskStopTool(this)});await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-VNZNSD6X.js");return new ReadFileTool(this)});await registerLazy(ToolNames.WRITE_FILE,async()=>{const{WriteFileTool}=await import("./write-file-UMJVKE4S.js");return new WriteFileTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-XCECLEH3.js");return new EditTool(this)});await registerLazy(ToolNames.MONITOR,async()=>{const{MonitorTool:MonitorTool2}=await import("./monitor-RD2PFK42.js");return new MonitorTool2(this)});await registerLazy(ToolNames.AGENT,async()=>{const{AgentTool:AgentTool2}=await import("./agent-PNKQJGDO.js");return new AgentTool2(this)});await registerLazy(ToolNames.GLOB,async()=>{const{GlobTool}=await import("./glob-NLWCQRMS.js");return new GlobTool(this)});await registerLazy(ToolNames.LS,async()=>{const{LSTool}=await import("./ls-ZVZ74DY3.js");return new LSTool(this)});if(resolveInteractionMode(this)!=="headless"){await registerLazy(ToolNames.ASK_USER_QUESTION,async()=>{const{AskUserQuestionTool:AskUserQuestionTool2}=await import("./askUserQuestion-GTSBJH2V.js");return new AskUserQuestionTool2(this)})}await registerExecIfEnabled();await registerStructuredOutputIfRequested();return registry3}if(this.getBareMode()){await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-VNZNSD6X.js");return new ReadFileTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-XCECLEH3.js");return new EditTool(this)});await registerLazy(ToolNames.NOTEBOOK_EDIT,async()=>{const{NotebookEditTool}=await import("./notebook-edit-YLRN3UZT.js");return new NotebookEditTool(this)});await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-WYQDZWL7.js");return new ShellTool2(this)});await registerGoalWorkerTools();await registerStructuredOutputIfRequested();await registerExecIfEnabled();this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry3.getAllToolNames())} (${registry3.getAllToolNames().length} tools)`);return registry3}await registerHostSessionTools();await registerExecIfEnabled();await registerGoalWorkerTools();await this.syncAdvisorToolRegistration(registry3);await registerLazy(ToolNames.TOOL_CALL,async()=>{const{ToolCallTool:ToolCallTool2}=await import("./tool-call-LVB4NCDT.js");return new ToolCallTool2(registry3)});await registerLazy(ToolNames.TOOL_SEARCH,async()=>{const{ToolSearchTool}=await import("./tool-search-OG73QAQZ.js");return new ToolSearchTool(this)});await registerLazy(ToolNames.READ_MCP_RESOURCE,async()=>{const{ReadMcpResourceTool}=await import("./read-mcp-resource-XDV7EITL.js");return new ReadMcpResourceTool(this)});await registerLazy(ToolNames.AGENT,async()=>{const{AgentTool:AgentTool2}=await import("./agent-PNKQJGDO.js");return new AgentTool2(this)});await registerLazy(ToolNames.LIST_AGENTS,async()=>{const{ListAgentsTool}=await import("./list-agents-N7IJHQFA.js");return new ListAgentsTool(this)});await registerLazy(ToolNames.TASK_STOP,async()=>{const{TaskStopTool}=await import("./task-stop-LPMYWUAI.js");return new TaskStopTool(this)});await registerLazy(ToolNames.SEND_MESSAGE,async()=>{const{SendMessageTool}=await import("./send-message-TFZX7KI7.js");return new SendMessageTool(this)});if(!options2?.forSubAgent||this.getSkillManager()){await registerLazy(ToolNames.SKILL,async()=>{const{SkillTool}=await import("./skill-FYPT6AU7.js");return new SkillTool(this)})}if(this.isLsToolEnabled()){await registerLazy(ToolNames.LS,async()=>{const{LSTool}=await import("./ls-ZVZ74DY3.js");return new LSTool(this)})}await registerLazy(ToolNames.READ_FILE,async()=>{const{ReadFileTool}=await import("./read-file-VNZNSD6X.js");return new ReadFileTool(this)});await registerLazy(ToolNames.MANAGE_MEMORY,async()=>{const{ManageMemoryTool}=await import("./manage-memory-PX5PZJKZ.js");return new ManageMemoryTool(this)});await registerLazy(ToolNames.SEARCH_MEMORY,async()=>{const{SearchMemoryTool}=await import("./search-memory-TC2Z34QN.js");return new SearchMemoryTool(this)});await registerLazy(ToolNames.ZOOM_IMAGE,async()=>{const{ZoomImageTool}=await import("./zoom-image-76XYHQ3Z.js");return new ZoomImageTool(this)});if(this.getUseRipgrep()){let useRipgrep=false;let errorString=void 0;recordStartupEvent("config_initialize_ripgrep_probe_start");try{useRipgrep=await canUseRipgrep(this.getUseBuiltinRipgrep())}catch(error3){errorString=getErrorMessage(error3)}recordStartupEvent("config_initialize_ripgrep_probe_end");if(useRipgrep){await registerLazy(ToolNames.GREP,async()=>{const{RipGrepTool}=await import("./ripGrep-4W5B5FOE.js");return new RipGrepTool(this)})}else{logRipgrepFallback(this,new RipgrepFallbackEvent(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),errorString||"ripgrep is not available"));await registerLazy(ToolNames.GREP,async()=>{const{GrepTool}=await import("./grep-ZPVNGCCV.js");return new GrepTool(this)})}}else{recordStartupEvent("config_initialize_ripgrep_probe_start");recordStartupEvent("config_initialize_ripgrep_probe_end");await registerLazy(ToolNames.GREP,async()=>{const{GrepTool}=await import("./grep-ZPVNGCCV.js");return new GrepTool(this)})}await registerLazy(ToolNames.GLOB,async()=>{const{GlobTool}=await import("./glob-NLWCQRMS.js");return new GlobTool(this)});await registerLazy(ToolNames.EDIT,async()=>{const{EditTool}=await import("./edit-XCECLEH3.js");return new EditTool(this)});await registerLazy(ToolNames.NOTEBOOK_EDIT,async()=>{const{NotebookEditTool}=await import("./notebook-edit-YLRN3UZT.js");return new NotebookEditTool(this)});await registerLazy(ToolNames.WRITE_FILE,async()=>{const{WriteFileTool}=await import("./write-file-UMJVKE4S.js");return new WriteFileTool(this)});await registerLazy(ToolNames.SHELL,async()=>{const{ShellTool:ShellTool2}=await import("./shell-WYQDZWL7.js");return new ShellTool2(this)});await registerLazy(ToolNames.REPORT_FINDINGS,async()=>{const{ReportFindingsTool}=await import("./report-findings-W4ARGZWM.js");return new ReportFindingsTool});const supportsUserInteraction=resolveInteractionMode(this)!=="headless";if(supportsUserInteraction){await registerLazy(ToolNames.ASK_USER_QUESTION,async()=>{const{AskUserQuestionTool:AskUserQuestionTool2}=await import("./askUserQuestion-GTSBJH2V.js");return new AskUserQuestionTool2(this)})}if(!this.sdkMode&&(supportsUserInteraction||options2?.forSubAgent)){await registerLazy(ToolNames.EXIT_PLAN_MODE,async()=>{const{ExitPlanModeTool:ExitPlanModeTool2}=await import("./exitPlanMode-76B5HDLT.js");return new ExitPlanModeTool2(this)})}if(!this.sdkMode&&supportsUserInteraction){await registerLazy(ToolNames.ENTER_PLAN_MODE,async()=>{const{EnterPlanModeTool}=await import("./enterPlanMode-SEN2PMRM.js");return new EnterPlanModeTool(this)})}await registerLazy(ToolNames.ENTER_WORKTREE,async()=>{const{EnterWorktreeTool}=await import("./enter-worktree-TSLRJOZG.js");return new EnterWorktreeTool(this)});await registerLazy(ToolNames.EXIT_WORKTREE,async()=>{const{ExitWorktreeTool}=await import("./exit-worktree-MEZOFF3P.js");return new ExitWorktreeTool(this)});if(resolveInteractionMode(this)==="interactive"&&!this.sdkMode&&!this.getScreenReader()&&!options2?.forSubAgent){await registerLazy(ToolNames.DISPLAY_IMAGE,async()=>{const{DisplayImageTool}=await import("./display-image-U4X2TV4R.js");return new DisplayImageTool(this)})}await this.registerImageGenerationTool(registry3);if(this.isArtifactEnabled()){await registerLazy(ToolNames.ARTIFACT,async()=>{const{ArtifactTool}=await import("./artifact-tool-G6TRQYYK.js");return new ArtifactTool(this)})}if(!options2?.forSubAgent){await this.registerSessionSourceTool(registry3)}if(this.isRecordArtifactEnabled()){await registerLazy(ToolNames.RECORD_ARTIFACT,async()=>{const{RecordArtifactTool}=await import("./record-artifact-N7M6CSFX.js");return new RecordArtifactTool(this)})}if(this.isLspEnabled()&&this.getLspClient()){await registerLazy(ToolNames.LSP,async()=>{const{LspTool}=await import("./lsp-VOO45GZP.js");return new LspTool(this)})}await registerStructuredOutputIfRequested();if(this.isCronEnabled()){await registerLazy(ToolNames.CRON_CREATE,async()=>{const{CronCreateTool}=await import("./cron-create-RFGGKTL7.js");return new CronCreateTool(this)});await registerLazy(ToolNames.CRON_LIST,async()=>{const{CronListTool}=await import("./cron-list-6JBPGS4Y.js");return new CronListTool(this)});await registerLazy(ToolNames.CRON_DELETE,async()=>{const{CronDeleteTool}=await import("./cron-delete-RMOEXBIS.js");return new CronDeleteTool(this)});await registerLazy(ToolNames.LOOP_WAKEUP,async()=>{const{LoopWakeupTool}=await import("./loop-wakeup-4MSRX3DY.js");return new LoopWakeupTool(this)})}await registerLazy(ToolNames.AUTOFIX_PR,async()=>{const{AutofixPrTool}=await import("./autofix-pr-IR3DNZ7W.js");return new AutofixPrTool(this)});if(this.getSubSessionSpawner()){await registerLazy(ToolNames.CREATE_SUB_SESSION,async()=>{const{CreateSubSessionTool}=await import("./create-sub-session-XY6UOUPE.js");return new CreateSubSessionTool(this)})}if(this.isAgentTeamEnabled()){await registerLazy(ToolNames.TEAM_CREATE,async()=>{const{TeamCreateTool}=await import("./team-create-R77PRZ5U.js");return new TeamCreateTool(this)});await registerLazy(ToolNames.TEAM_DELETE,async()=>{const{TeamDeleteTool}=await import("./team-delete-2VUNSDJ3.js");return new TeamDeleteTool(this)});await registerLazy(ToolNames.TEAM_PLAN_APPROVAL,async()=>{const{TeamPlanApprovalTool}=await import("./team-plan-approval-6DCRKB5I.js");return new TeamPlanApprovalTool(this)});if(!options2?.forSubAgent){await registerLazy(ToolNames.REQUEST_SHUTDOWN,async()=>{const{RequestShutdownTool}=await import("./request-shutdown-WN34ZXP4.js");return new RequestShutdownTool(this)})}await registerLazy(ToolNames.TASK_CREATE,async()=>{const{TaskCreateTool}=await import("./task-create-KSKNIAXD.js");return new TaskCreateTool(this)});await registerLazy(ToolNames.TASK_UPDATE,async()=>{const{TaskUpdateTool}=await import("./task-update-56FYUVP5.js");return new TaskUpdateTool(this)});await registerLazy(ToolNames.TASK_LIST,async()=>{const{TaskListTool}=await import("./task-list-UGDFER45.js");return new TaskListTool(this)})}if(this.isWorkflowsEnabled()){await this.registerWorkflowTool(registry3)}if(this.isOmniEnabled()){const omniPolicyToolFactories=[[ToolNames.OMNI_DOWNSAMPLE_IMAGE,async()=>new(await import("./downsample-image-GY5NDTCO.js")).OmniDownsampleImageTool(this)],[ToolNames.OMNI_DOWNSCALE_VIDEO,async()=>new(await import("./downscale-video-PCKMG7RJ.js")).OmniDownscaleVideoTool(this)],[ToolNames.OMNI_DOWNSAMPLE_AUDIO,async()=>new(await import("./downsample-audio-PAAE5K4Y.js")).OmniDownsampleAudioTool(this)],[ToolNames.OMNI_EXTRACT_KEYFRAMES,async()=>new(await import("./extract-keyframes-3LZLRQ45.js")).OmniExtractKeyframesTool(this)],[ToolNames.OMNI_EXTRACT_AUDIO,async()=>new(await import("./extract-audio-CT3OOOAG.js")).OmniExtractAudioTool(this)],[ToolNames.OMNI_CLIP_VIDEO,async()=>new(await import("./clip-video-DIWZ7DQN.js")).OmniClipVideoTool(this)],[ToolNames.OMNI_CONVERT_IMAGE,async()=>new(await import("./convert-image-CJEQCVXW.js")).OmniConvertImageTool(this)],[ToolNames.OMNI_TRANSCRIBE_AUDIO,async()=>new(await import("./transcribe-audio-TPAYPRUE.js")).OmniTranscribeAudioTool(this)],[ToolNames.OMNI_CLIP_IMAGE,async()=>new(await import("./clip-image-2LRBIF7D.js")).OmniClipImageTool(this)],[ToolNames.OMNI_CLIP_AUDIO,async()=>new(await import("./clip-audio-5EGXYPZ4.js")).OmniClipAudioTool(this)],[ToolNames.OMNI_CAPTION_IMAGE,async()=>new(await import("./caption-image-4TSC2VJ6.js")).OmniCaptionImageTool(this)],[ToolNames.OMNI_CAPTION_AUDIO,async()=>new(await import("./caption-audio-VO3THSBI.js")).OmniCaptionAudioTool(this)],[ToolNames.OMNI_OCR_IMAGE,async()=>new(await import("./ocr-image-C477GNPR.js")).OmniOcrImageTool(this)],[ToolNames.OMNI_UNDERSTAND_VIDEO_SEGMENTS,async()=>new(await import("./understand-video-segments-UC7EIGH3.js")).OmniUnderstandVideoSegmentsTool(this)]];for(const[name2,factory]of omniPolicyToolFactories){await registerLazy(name2,factory)}const memoryConfig=await this.ensureOmniMemoryConfig();if(memoryConfig.recall.mode==="active"){await registerLazy(ToolNames.OMNI_RECALL_MEDIA_MEMORY,async()=>{const{OmniRecallMediaMemoryTool}=await import("./recall-media-memory-tool-Z4U5XDHQ.js");return new OmniRecallMediaMemoryTool(this)})}}await registerLazy(ToolNames.MONITOR,async()=>{const{MonitorTool:MonitorTool2}=await import("./monitor-RD2PFK42.js");return new MonitorTool2(this)});this.applyPendingMcpBudgetCallback(registry3);if(!options2?.skipDiscovery){await registry3.discoverAllTools()}this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry3.getAllToolNames())} (${registry3.getAllToolNames().length} tools)`);return registry3}applyPendingMcpBudgetCallback(registry3){if(!this.pendingMcpBudgetCallback)return;const mgr=registry3.getMcpClientManager();if(mgr&&typeof mgr.setOnBudgetEvent==="function"){mgr.setOnBudgetEvent(this.pendingMcpBudgetCallback)}this.pendingMcpBudgetCallback=void 0}setMcpBudgetEventCallback(cb){if(this.toolRegistry){const mgr=this.toolRegistry.getMcpClientManager?.();if(mgr&&typeof mgr.setOnBudgetEvent==="function"){mgr.setOnBudgetEvent(cb)}this.pendingMcpBudgetCallback=void 0;return}this.pendingMcpBudgetCallback=cb}subSessionSpawner;currentSessionScheduledTaskCreator;setSubSessionSpawner(spawner){this.subSessionSpawner=spawner}getSubSessionSpawner(){return this.subSessionSpawner}setCurrentSessionScheduledTaskCreator(creator){this.currentSessionScheduledTaskCreator=creator}getCurrentSessionScheduledTaskCreator(){return this.currentSessionScheduledTaskCreator}};function installSessionWorkflowRevisionWriteThrough(wrapper,base2){const ov=wrapper;ov.setSessionWorkflowPlanRevision=revision5=>{base2.setSessionWorkflowPlanRevision(revision5)};ov.clearSessionWorkflowPlanRevision=()=>{base2.clearSessionWorkflowPlanRevision()}}__name(installSessionWorkflowRevisionWriteThrough,"installSessionWorkflowRevisionWriteThrough");var debugLogger124=createDebugLogger("EXIT_PLAN_MODE");var exitPlanModeToolDescription=`Use this tool when you are in plan mode and have finished presenting your plan and are ready to code. This will prompt the user to exit plan mode.
2152
2153
 
2153
2154
  ## When to Use This Tool
2154
2155
  IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.