gerege-cli 0.26.5 → 0.26.6

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-QCIXIS4P.js} +1 -1
  3. package/chunks/{StandaloneSessionPicker-UNORCVYY.js → StandaloneSessionPicker-BAFAIRT7.js} +1 -1
  4. package/chunks/{acp-subagent-executor-623ZUTJT.js → acp-subagent-executor-TPVXURLW.js} +1 -1
  5. package/chunks/{acpAgent-MTTDTK2C.js → acpAgent-67UN66PB.js} +3 -3
  6. package/chunks/{advisor-ANUGICJ5.js → advisor-SAXMI4QZ.js} +1 -1
  7. package/chunks/{agent-GNCQDICJ.js → agent-KV7BXY6C.js} +1 -1
  8. package/chunks/{agent-headless-OPUXAXQM.js → agent-headless-FQX3JGG6.js} +1 -1
  9. package/chunks/{agent-host-client-K6GRPTFD.js → agent-host-client-L5EHC4AC.js} +1 -1
  10. package/chunks/{agent-host-connections-MF3YBZU2.js → agent-host-connections-EDBMCVQF.js} +1 -1
  11. package/chunks/{anthropicContentGenerator-OK4PFE5Y.js → anthropicContentGenerator-V7TX2NXP.js} +1 -1
  12. package/chunks/{autofix-pr-MABTGEHZ.js → autofix-pr-WP34NYHL.js} +1 -1
  13. package/chunks/{batch-V2NJT3M5.js → batch-XFVQ4BLM.js} +1 -1
  14. package/chunks/{bridge-BJQ627CX.js → bridge-AE7AFEXB.js} +1 -1
  15. package/chunks/{channel-settings-store-4JMCI4UR.js → channel-settings-store-X63P5OVT.js} +1 -1
  16. package/chunks/{chunk-ZN57TOVA.js → chunk-2DU2WMTL.js} +1 -1
  17. package/chunks/{chunk-Z5XENA4A.js → chunk-2JGTWRZJ.js} +8 -7
  18. package/chunks/{chunk-MTW3A3KT.js → chunk-2LWJGXTW.js} +1 -1
  19. package/chunks/{chunk-OCBJCZC2.js → chunk-2N3NBTYJ.js} +1 -1
  20. package/chunks/{chunk-WI4UMN3Q.js → chunk-2TAJ5STJ.js} +1 -1
  21. package/chunks/{chunk-EIILQ6KT.js → chunk-32XHDDIA.js} +1 -1
  22. package/chunks/{chunk-FNXO5KWB.js → chunk-34HC2AXI.js} +2 -2
  23. package/chunks/{chunk-2X3UF2CF.js → chunk-3W32X2DH.js} +1 -1
  24. package/chunks/{chunk-CKZRJP4F.js → chunk-4ME3BUJK.js} +1 -1
  25. package/chunks/{chunk-NVSKOSFG.js → chunk-4NDJKNN6.js} +1 -1
  26. package/chunks/{chunk-BRPJ5EHA.js → chunk-5EXL4TKQ.js} +1 -1
  27. package/chunks/{chunk-3XBJYUWP.js → chunk-65ME4BOH.js} +1 -1
  28. package/chunks/{chunk-TQTIEK2W.js → chunk-7453BHJO.js} +1 -1
  29. package/chunks/{chunk-HSYBIGMS.js → chunk-76FSYQTG.js} +1 -1
  30. package/chunks/{chunk-FNB3DPQZ.js → chunk-7RNOS7R4.js} +1 -1
  31. package/chunks/{chunk-H57IX45A.js → chunk-AEKEZRIU.js} +1 -1
  32. package/chunks/{chunk-CXGGC4NO.js → chunk-AEZYXPFS.js} +1 -1
  33. package/chunks/{chunk-NGOIJH7K.js → chunk-AFO5ER23.js} +1 -1
  34. package/chunks/{chunk-UY2ET2AL.js → chunk-AYVCT5FF.js} +1 -1
  35. package/chunks/{chunk-QOYRDEXR.js → chunk-B37YY4XU.js} +1 -1
  36. package/chunks/{chunk-IDUGQMTP.js → chunk-BAUMVH4Q.js} +1 -1
  37. package/chunks/{chunk-CAPG7UVH.js → chunk-BCI62WSL.js} +1 -1
  38. package/chunks/{chunk-USJFJZ23.js → chunk-BGELKSQ4.js} +1 -1
  39. package/chunks/{chunk-6X73W4TL.js → chunk-BHIDG6VZ.js} +1 -1
  40. package/chunks/{chunk-26ISBUM7.js → chunk-BPFFRPWE.js} +6 -6
  41. package/chunks/{chunk-YGHM5CDT.js → chunk-BQZF3UKI.js} +1 -1
  42. package/chunks/{chunk-3NQESE5K.js → chunk-CBE6ZIHU.js} +1 -1
  43. package/chunks/{chunk-DEMXCA3K.js → chunk-CF6SZJNP.js} +1 -1
  44. package/chunks/{chunk-2VCDJ6UF.js → chunk-CGDFZEER.js} +1 -1
  45. package/chunks/{chunk-3WQPUP5U.js → chunk-CUP2TNJK.js} +1 -1
  46. package/chunks/{chunk-2IGE2K5V.js → chunk-DA6LOBSB.js} +1 -1
  47. package/chunks/{chunk-HFV6CQWE.js → chunk-EFIRES46.js} +1 -1
  48. package/chunks/{chunk-E5YRAQXM.js → chunk-EKRUF347.js} +1 -1
  49. package/chunks/{chunk-KN27BFXM.js → chunk-ELDZ4MNL.js} +1 -1
  50. package/chunks/{chunk-ADTFKUH2.js → chunk-ET5M5WFN.js} +1 -1
  51. package/chunks/{chunk-IBYFSHBB.js → chunk-EXIFPXMB.js} +1 -1
  52. package/chunks/{chunk-IA4K4PGK.js → chunk-EYPLBTMI.js} +1 -1
  53. package/chunks/{chunk-DTTC4ZKY.js → chunk-FEP6W4NJ.js} +1 -1
  54. package/chunks/{chunk-FHBGTZ4K.js → chunk-FKL3V5BO.js} +1 -1
  55. package/chunks/{chunk-Q5E5SOY2.js → chunk-FKZ46GKL.js} +1 -1
  56. package/chunks/{chunk-OPYGNTZP.js → chunk-FYBJGRX7.js} +1 -1
  57. package/chunks/{chunk-FPZPCZFS.js → chunk-G6DALGGS.js} +1 -1
  58. package/chunks/{chunk-3Y6LSWEW.js → chunk-GBSRWT7J.js} +1 -1
  59. package/chunks/{chunk-SMYBY353.js → chunk-GHIFIXNX.js} +1 -1
  60. package/chunks/{chunk-DE53B2R7.js → chunk-GRAECADD.js} +1 -1
  61. package/chunks/{chunk-UJYOILZR.js → chunk-GSPGIGO5.js} +3 -3
  62. package/chunks/{chunk-5UZT4SXG.js → chunk-H3IR3GIE.js} +1 -1
  63. package/chunks/{chunk-ADZI3OFT.js → chunk-HOG66S6K.js} +1 -1
  64. package/chunks/{chunk-WB34KMOT.js → chunk-HTAUIJB4.js} +1 -1
  65. package/chunks/{chunk-MPAR4JBP.js → chunk-I6PUY2T3.js} +1 -1
  66. package/chunks/{chunk-5ZQWQ3RK.js → chunk-IZ5MWA6E.js} +1 -1
  67. package/chunks/{chunk-7IERHQ63.js → chunk-JEDL4IKF.js} +1 -1
  68. package/chunks/{chunk-RVJJFDF3.js → chunk-JH3V5SPA.js} +1 -1
  69. package/chunks/{chunk-SELRSZFK.js → chunk-JRTOPEM3.js} +1 -1
  70. package/chunks/{chunk-SQQORHMS.js → chunk-JWNKPINR.js} +1 -1
  71. package/chunks/{chunk-55RVKT4O.js → chunk-KJGRCIVY.js} +1 -1
  72. package/chunks/{chunk-GSOBASYW.js → chunk-KZNYALFU.js} +1 -1
  73. package/chunks/{chunk-FDUXQAGW.js → chunk-LBLLWAKK.js} +1 -1
  74. package/chunks/{chunk-ZSVSRF4C.js → chunk-LT3J74BZ.js} +1 -1
  75. package/chunks/{chunk-AMTFJVDD.js → chunk-LTE4N6L3.js} +1 -1
  76. package/chunks/{chunk-F26LTWDZ.js → chunk-M6KB5RVD.js} +1 -1
  77. package/chunks/{chunk-2PY7R7GG.js → chunk-MGATL4OA.js} +1 -1
  78. package/chunks/{chunk-KGJ47CI5.js → chunk-MPVQDYPH.js} +1 -1
  79. package/chunks/{chunk-BBOJUFMW.js → chunk-MTDBCIDA.js} +1 -1
  80. package/chunks/{chunk-ZYTG6R7S.js → chunk-MYV7GY3H.js} +1 -1
  81. package/chunks/{chunk-4GC5HJZO.js → chunk-N7PWZBXV.js} +1 -1
  82. package/chunks/{chunk-2NOMOJWE.js → chunk-NA4ZF2FE.js} +2 -2
  83. package/chunks/{chunk-7MTBINFX.js → chunk-NEKPQLFY.js} +2 -2
  84. package/chunks/{chunk-ABJGFEES.js → chunk-NO7VTKRL.js} +1 -1
  85. package/chunks/{chunk-OHXQYU6S.js → chunk-NONBHCXP.js} +1 -1
  86. package/chunks/{chunk-ZOBX6C7E.js → chunk-NVOI6UDQ.js} +1 -1
  87. package/chunks/{chunk-YLAI26PX.js → chunk-OJ4K62S2.js} +1 -1
  88. package/chunks/{chunk-CCOUFBOY.js → chunk-OK7LBM5G.js} +1 -1
  89. package/chunks/{chunk-POA4NX4N.js → chunk-OOJ2AQT3.js} +1 -1
  90. package/chunks/{chunk-5WLKN3GD.js → chunk-OU7CEG7Q.js} +1 -1
  91. package/chunks/{chunk-4TYTJQWR.js → chunk-P3JEEDQZ.js} +1 -1
  92. package/chunks/{chunk-AQWHCRKY.js → chunk-P62S5JGM.js} +1 -1
  93. package/chunks/{chunk-B6D3KTUK.js → chunk-QDCUR3JB.js} +1 -1
  94. package/chunks/{chunk-XFLLE2J3.js → chunk-RSLTOIG5.js} +2 -2
  95. package/chunks/{chunk-ISGF3BVD.js → chunk-RXN7DUMP.js} +2 -2
  96. package/chunks/{chunk-PN62SUYK.js → chunk-SKGJ26HQ.js} +1 -1
  97. package/chunks/{chunk-62NLMVVT.js → chunk-SP6CQ3MO.js} +1 -1
  98. package/chunks/{chunk-4EQWJTJR.js → chunk-T2YTHAJW.js} +1 -1
  99. package/chunks/{chunk-NO26JN24.js → chunk-T53VMDXH.js} +1 -1
  100. package/chunks/{chunk-X4BFEDWU.js → chunk-T5DKF33F.js} +1 -1
  101. package/chunks/{chunk-KKBOCRPF.js → chunk-TB4AUC2L.js} +1 -1
  102. package/chunks/{chunk-Q6QS5JTK.js → chunk-U3Q72OGV.js} +1 -1
  103. package/chunks/{chunk-FLJLUMQF.js → chunk-UKLXKJKL.js} +1 -1
  104. package/chunks/{chunk-IH2PFVWO.js → chunk-VD2GSW64.js} +1 -1
  105. package/chunks/{chunk-VDRE7U3P.js → chunk-VRKYBH5G.js} +5 -5
  106. package/chunks/{chunk-MOPJNP5I.js → chunk-W2RQIZ6B.js} +1 -1
  107. package/chunks/{chunk-2LLPGSUK.js → chunk-W5Z4BWWA.js} +1 -1
  108. package/chunks/{chunk-CNFA5UUM.js → chunk-W66WWTOP.js} +1 -1
  109. package/chunks/{chunk-C56YJIEI.js → chunk-WGFX3EL3.js} +1 -1
  110. package/chunks/{chunk-6NI33TVK.js → chunk-X2TY7VTY.js} +1 -1
  111. package/chunks/{chunk-FIM7MM25.js → chunk-XISR37DQ.js} +1 -1
  112. package/chunks/{chunk-KDYUZBZC.js → chunk-YH2XRWRF.js} +1 -1
  113. package/chunks/{chunk-UBXLQ6TP.js → chunk-ZENMAISJ.js} +1 -1
  114. package/chunks/{codex-subagent-executor-EK3A2WBH.js → codex-subagent-executor-OLMGVPVS.js} +1 -1
  115. package/chunks/{config-utils-DLOK7OLM.js → config-utils-OWY5G5Y2.js} +1 -1
  116. package/chunks/{contextCommand-AVCUCHQC.js → contextCommand-IXFUZH65.js} +1 -1
  117. package/chunks/{core-runtime-QSS4ZTG6.js → core-runtime-O4LC4NY3.js} +1 -1
  118. package/chunks/{create-sub-session-PNF7QDKC.js → create-sub-session-6F7C3TMT.js} +1 -1
  119. package/chunks/{cron-create-C6JOFIU4.js → cron-create-2422NBSJ.js} +1 -1
  120. package/chunks/{daemon-git-worktree-guard-5XZAZ7D2.js → daemon-git-worktree-guard-EWPQA6NO.js} +1 -1
  121. package/chunks/{daemon-status-provider-MRNELSNJ.js → daemon-status-provider-FAHOXNFW.js} +1 -1
  122. package/chunks/{daemon-trust-policy-26CMW3WY.js → daemon-trust-policy-L3DM6AI5.js} +1 -1
  123. package/chunks/{daemon-trust-policy-monitor-3DWO6NQY.js → daemon-trust-policy-monitor-HNPY5KJ4.js} +1 -1
  124. package/chunks/{deferred-core-runtime-DEC3N46T.js → deferred-core-runtime-JF42NQJK.js} +1 -1
  125. package/chunks/{edit-3HMQPCHN.js → edit-E5LEI2LL.js} +1 -1
  126. package/chunks/{enterPlanMode-QHJF4JXZ.js → enterPlanMode-3COTUV5V.js} +1 -1
  127. package/chunks/{environment-NGIBJWOT.js → environment-XBBIB3VA.js} +1 -1
  128. package/chunks/{errors-MSTGCVGJ.js → errors-LNMQ7TUK.js} +1 -1
  129. package/chunks/{execution-tool-VR4TGOI4.js → execution-tool-QDDKJD2K.js} +1 -1
  130. package/chunks/{execution-worker-EJH7HIE2.js → execution-worker-TXGZRZXE.js} +1 -1
  131. package/chunks/{exitPlanMode-P25OHQJ6.js → exitPlanMode-Z7QEMWPE.js} +1 -1
  132. package/chunks/{fast-path-II433ZDP.js → fast-path-M6K2RACY.js} +1 -1
  133. package/chunks/{glob-4Q6DCT3F.js → glob-N2QT4U7U.js} +1 -1
  134. package/chunks/{goal-tools-FFMAJW6V.js → goal-tools-CUSQD3DG.js} +1 -1
  135. package/chunks/{handleAutoUpdate-QNM26NZK.js → handleAutoUpdate-QF2YQHF6.js} +1 -1
  136. package/chunks/{i18n-L5URVOBB.js → i18n-AGOA6MUI.js} +1 -1
  137. package/chunks/{initializer-NQ2NECYP.js → initializer-FRKYDUSX.js} +1 -1
  138. package/chunks/{installationInfo-BCTXASUM.js → installationInfo-OKA4WXAS.js} +1 -1
  139. package/chunks/{interactive-mod-session-PPTBI37E.js → interactive-mod-session-MWYN5IFK.js} +1 -1
  140. package/chunks/{list-7TE5TUZJ.js → list-DE7VUIR2.js} +1 -1
  141. package/chunks/{llm-BWWKUBBZ.js → llm-N3JGJHYC.js} +4 -4
  142. package/chunks/{llm-content-generator-QOTGPBYC.js → llm-content-generator-VMUBA7OJ.js} +1 -1
  143. package/chunks/{loadedSettingsAdapter-THAGI5M2.js → loadedSettingsAdapter-5C36OZ7N.js} +1 -1
  144. package/chunks/{local-7BTAGV4J.js → local-BE624O3A.js} +1 -1
  145. package/chunks/{local-execution-environment-S3OR4KSC.js → local-execution-environment-OPGM7Y6L.js} +1 -1
  146. package/chunks/{loggingContentGenerator-AXJ5E5RS.js → loggingContentGenerator-2MHAI6JR.js} +1 -1
  147. package/chunks/{loop-wakeup-AJTLMLRX.js → loop-wakeup-BDLATBXH.js} +1 -1
  148. package/chunks/{manage-memory-JHTUVMDJ.js → manage-memory-BBCEIIWB.js} +1 -1
  149. package/chunks/{managed-execution-engine-U6GNJ4U4.js → managed-execution-engine-SRFALTCX.js} +1 -1
  150. package/chunks/{managed-local-serve-P4ZXVRBU.js → managed-local-serve-ICNAS3E6.js} +1 -1
  151. package/chunks/{managed-npm-update-UDUILNR5.js → managed-npm-update-CTL6LH5Z.js} +1 -1
  152. package/chunks/{managed-runtime-attestation-worker-P34ZBNRG.js → managed-runtime-attestation-worker-ZRDWKXCI.js} +1 -1
  153. package/chunks/{managed-runtime-bootstrap-CLMYNPH5.js → managed-runtime-bootstrap-6NTGZXQL.js} +1 -1
  154. package/chunks/{managed-runtime-session-worker-7H7AZJBV.js → managed-runtime-session-worker-RKQBBFR6.js} +1 -1
  155. package/chunks/{managed-runtime-ssh-worker-5KEMC7FD.js → managed-runtime-ssh-worker-FCGV6FSW.js} +1 -1
  156. package/chunks/{managed-session-authority-CFUZ45HT.js → managed-session-authority-C7IW6TJX.js} +1 -1
  157. package/chunks/{mcp-YMG4RVMC.js → mcp-VC4CJPE5.js} +1 -1
  158. package/chunks/{memory-7STURUXK.js → memory-S6OJA3ZD.js} +1 -1
  159. package/chunks/mn-JMS6SWTO.js +8 -0
  160. package/chunks/{model-call-collection-WBWTO3EG.js → model-call-collection-MJZWRQSU.js} +1 -1
  161. package/chunks/{model-configuration-6KCZZSZD.js → model-configuration-SKU6L3QI.js} +1 -1
  162. package/chunks/{modelConfigUtils-Z2EKFSPN.js → modelConfigUtils-TJCB6NXT.js} +1 -1
  163. package/chunks/{monitor-U5E33JO6.js → monitor-M3PNLCYP.js} +1 -1
  164. package/chunks/{nonInteractiveCli-BVCL5I5R.js → nonInteractiveCli-MR7JLAWU.js} +1 -1
  165. package/chunks/{nonInteractiveToolExecutor-B4EUOMYF.js → nonInteractiveToolExecutor-YKA6JMTY.js} +1 -1
  166. package/chunks/{notebook-edit-MXKD5J2C.js → notebook-edit-ENTFB5D7.js} +1 -1
  167. package/chunks/{omni-I5YECZBW.js → omni-6YBX4R6K.js} +1 -1
  168. package/chunks/{openaiContentGenerator-Q5SINFJJ.js → openaiContentGenerator-XRXX33FY.js} +1 -1
  169. package/chunks/{openaiResponsesContentGenerator-R3XCZLZY.js → openaiResponsesContentGenerator-L6ONEHMR.js} +1 -1
  170. package/chunks/{pidfile-UOGUNUTK.js → pidfile-XR4JF2Z6.js} +1 -1
  171. package/chunks/{processUtils-QGQGZHBA.js → processUtils-GQYNJRBJ.js} +1 -1
  172. package/chunks/{prompt-terminal-ledger-L57JMVSR.js → prompt-terminal-ledger-7BM7YDLG.js} +1 -1
  173. package/chunks/{qwenContentGenerator-UKZ237LC.js → qwenContentGenerator-QSA32XEL.js} +1 -1
  174. package/chunks/{reactive-degrade-3OM3HWVA.js → reactive-degrade-TFNBAAPZ.js} +1 -1
  175. package/chunks/{read-file-63ZLWMOW.js → read-file-VD7OFO2E.js} +1 -1
  176. package/chunks/{resumeHistoryUtils-R5YQS4YQ.js → resumeHistoryUtils-2B4KPI7G.js} +1 -1
  177. package/chunks/{review-AT6OWVDO.js → review-C365WGCW.js} +1 -1
  178. package/chunks/{ripGrep-7KBZGTPV.js → ripGrep-D7WPMBXR.js} +1 -1
  179. package/chunks/{run-qwen-serve-CLBG7W6F.js → run-qwen-serve-NZWQHWQA.js} +1 -1
  180. package/chunks/{runtime-R3QIGB7U.js → runtime-J6SPBSCS.js} +1 -1
  181. package/chunks/{sandboxConfig-PM3ZRQYV.js → sandboxConfig-QS2XBPZG.js} +1 -1
  182. package/chunks/{scheduled-tasks-PUMNN5XV.js → scheduled-tasks-YNNIOOPM.js} +1 -1
  183. package/chunks/{scheduler-KTPM226B.js → scheduler-KCMSPHON.js} +1 -1
  184. package/chunks/{search-memory-7I5MGDNV.js → search-memory-EUBJ7IAV.js} +1 -1
  185. package/chunks/{send-message-J526AEBI.js → send-message-CWWZUPSK.js} +1 -1
  186. package/chunks/{serve-KLTMPK4W.js → serve-4CB4BWJ5.js} +1 -1
  187. package/chunks/{server-VLRNY6KG.js → server-JNANUIGC.js} +3 -3
  188. package/chunks/{session-2EB57NXY.js → session-3LQLXPUA.js} +1 -1
  189. package/chunks/{session-attachments-root-I7TESMWL.js → session-attachments-root-BWIVWFHJ.js} +1 -1
  190. package/chunks/{session-execution-engine-selector-5FAMSPSO.js → session-execution-engine-selector-5OLRX57L.js} +1 -1
  191. package/chunks/{session-pr-refresh-JCPVQPNJ.js → session-pr-refresh-RLF3EXS3.js} +1 -1
  192. package/chunks/{sessionService-YRW2IFPR.js → sessionService-U7ACD2HP.js} +1 -1
  193. package/chunks/{settings-KO2Q47JP.js → settings-FTGWYTUH.js} +1 -1
  194. package/chunks/{shell-OLZVNTQZ.js → shell-E4RENYQC.js} +1 -1
  195. package/chunks/{skill-XW2AQS7M.js → skill-OLNPHRWB.js} +1 -1
  196. package/chunks/{skill-settings-TKAVQ4XP.js → skill-settings-R2BV2GEK.js} +1 -1
  197. package/chunks/{spawnChannel-MBGCTK2J.js → spawnChannel-LOPAR5T2.js} +1 -1
  198. package/chunks/{standalone-update-A3YLLIAN.js → standalone-update-IGDX2RGN.js} +1 -1
  199. package/chunks/{start-opentui-ui-G5ROAR4V.js → start-opentui-ui-33QLBNRC.js} +1 -1
  200. package/chunks/{startInteractiveUI-PZQR4U53.js → startInteractiveUI-RQKHD7MM.js} +1 -1
  201. package/chunks/{team-create-S5ZY2UMF.js → team-create-HAVKHNU5.js} +1 -1
  202. package/chunks/{team-plan-approval-KX6RXEST.js → team-plan-approval-7MCQX67C.js} +1 -1
  203. package/chunks/{terminal-image-renderer-SCJREXE6.js → terminal-image-renderer-XT5JVEO6.js} +1 -1
  204. package/chunks/{theme-manager-DZSM4EBR.js → theme-manager-DR5EYGLT.js} +1 -1
  205. package/chunks/{tool-call-UK56SWCT.js → tool-call-LZHZ5RVH.js} +1 -1
  206. package/chunks/{tool-result-media-JLLSLGFL.js → tool-result-media-XCXCF4YC.js} +1 -1
  207. package/chunks/{tool-search-OWPFLVV5.js → tool-search-K6S3ON7M.js} +1 -1
  208. package/chunks/{total-session-admission-NQU4ACKH.js → total-session-admission-LGSS2VWS.js} +1 -1
  209. package/chunks/{trustedFolders-N7GXFYSF.js → trustedFolders-IIR2UZRL.js} +1 -1
  210. package/chunks/{update-relaunch-5SPXXHM2.js → update-relaunch-WVIFX5CN.js} +1 -1
  211. package/chunks/{updateCheck-VXUIX2XG.js → updateCheck-CMEWLLZJ.js} +1 -1
  212. package/chunks/{upload-config-OWLL4SRQ.js → upload-config-TCCFCNCD.js} +1 -1
  213. package/chunks/{useAutoAcceptIndicator-OUYRR56F.js → useAutoAcceptIndicator-5RTTH3OW.js} +1 -1
  214. package/chunks/{validateNonInterActiveAuth-PSVJO5HK.js → validateNonInterActiveAuth-AO336KDX.js} +1 -1
  215. package/chunks/{version-C26S7UAW.js → version-JYWKKMNP.js} +1 -1
  216. package/chunks/{web-fetch-AYOYV7R4.js → web-fetch-HWTAWXFM.js} +1 -1
  217. package/chunks/{web-search-DAREKD3Z.js → web-search-HAI5LW3G.js} +1 -1
  218. package/chunks/{workflow-WBGPKVO6.js → workflow-BZ2YFGF6.js} +1 -1
  219. package/chunks/{workflow-ancestor-trust-GEEB53TB.js → workflow-ancestor-trust-26TFXFPO.js} +1 -1
  220. package/chunks/{workspace-agents-IMAQME4W.js → workspace-agents-DLI4JQJZ.js} +1 -1
  221. package/chunks/{workspace-providers-status-VALHVEU2.js → workspace-providers-status-64C7DJZU.js} +1 -1
  222. package/chunks/{workspace-recovery-worker-AIAVRDGU.js → workspace-recovery-worker-IFRT3KKP.js} +1 -1
  223. package/chunks/{workspace-registration-store-FXEGZG3L.js → workspace-registration-store-MYKJM2SK.js} +1 -1
  224. package/chunks/{workspace-registry-GYFFHWCD.js → workspace-registry-GZJRONAY.js} +1 -1
  225. package/chunks/{workspace-runtime-coordinator-VZ462TLU.js → workspace-runtime-coordinator-44KW6HSN.js} +1 -1
  226. package/chunks/{workspace-service-5DIZM4IZ.js → workspace-service-YHTSZYYD.js} +1 -1
  227. package/chunks/{workspace-skills-status-DOOBVL5N.js → workspace-skills-status-NEB62X24.js} +1 -1
  228. package/chunks/{workspace-trust-reconciler-LOICVUVW.js → workspace-trust-reconciler-HZLOOZWM.js} +1 -1
  229. package/chunks/{write-file-EJNMAHQD.js → write-file-HD5LHXGL.js} +1 -1
  230. package/chunks/{zoom-image-S3OARMYP.js → zoom-image-W4BMRC5T.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 +53 -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{CHECKPOINT_HISTORY_KIND,HOSTED_MODEL_REQUEST_BYTES,HOSTED_RECOVERY_RESOURCE_KINDS,MANAGED_EXTENSION_RECORD_BODIES,MANAGED_MESSAGE_CHUNKS_KIND,ManagedSessionCommitRejectedError,ManagedSessionConflictError,checkpointHistoryPage,checkpointStorageBody,hostedRecoveryReferences,isPagedHarnessCheckpoint,managedMessageChunkParts,managedToolDigest,parseHostedRecoveryResource,scanManagedSessionJournal,tryParseHarnessCheckpointV1}from"./chunk-Z5XENA4A.js";import{MANAGED_SESSION_COMMIT_SUBTYPE,MANAGED_SESSION_EVENT_SUBTYPE,MANAGED_SESSION_HEADER_SUBTYPE,MANAGED_SESSION_LIMITS,MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,ManagedSessionAppendUnsettledError,ManagedSessionJournalFencedError,ManagedSessionRecordError,assertManagedSessionDurableRef,assertManagedSessionStableId,isToolResultPageAt,managedSessionEventRefs,managedSessionKeysEqual,parseManagedSessionCommitMarker,parseManagedSessionEvent,parseManagedSessionHeader,parseManagedSessionRecordJson,parseToolResultManifestBytes,parseToolResultPageBytes,parseToolResultPrefixRequest,parseToolResultPublishRequest,parseToolResultSealRequest}from"./chunk-OMSVOFTC.js";import{validateSkillName}from"./chunk-CV2UAEZA.js";import{renderAvailableSkillsBlock}from"./chunk-IRINPFG7.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var RULE_KINDS=["allow","ask","deny"];var SHELL=new Set(["Bash","Shell","ShellTool","run_shell_command","monitor","Monitor","MonitorTool"]);var WEB=new Set(["WebFetch","WebFetchTool","web_fetch"]);var TOOL=/^[A-Za-z_][A-Za-z0-9_.:-]*$/u;var MCP=/^mcp__[A-Za-z0-9_.:-]+(?:__[A-Za-z0-9_.:-]+)?\*?$/u;var DOMAIN=/^domain:(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/u;var encoder=new TextEncoder;function validRule(rule){if(!rule||rule!==rule.trim()||new RegExp("\\p{Cc}","u").test(rule)||encoder.encode(rule).length>512)return false;const open=rule.indexOf("(");if(open<0)return rule.startsWith("mcp__")?MCP.test(rule):TOOL.test(rule);if(!rule.endsWith(")"))return false;const tool=rule.slice(0,open);const specifier=rule.slice(open+1,-1);return!!specifier&&specifier===specifier.trim()&&(SHELL.has(tool)||WEB.has(tool)&&DOMAIN.test(specifier))}__name(validRule,"validRule");function parseManagedPermissionRules(value){const invalid3=__name(()=>new Error("Invalid portable permission rules."),"invalid");if(!value||typeof value!=="object"||Array.isArray(value))throw invalid3();const fields=value;if(Object.keys(fields).length!==3||RULE_KINDS.some(kind=>!Object.hasOwn(fields,kind)))throw invalid3();let total=0;const result={};for(const kind of RULE_KINDS){const rules=fields[kind];if(!Array.isArray(rules)||rules.length>32||rules.some(rule=>typeof rule!=="string"||!validRule(rule))||new Set(rules).size!==rules.length)throw invalid3();total+=rules.length;result[kind]=[...rules]}if(total>64||encoder.encode(JSON.stringify(result)).length>8192)throw invalid3();return result}__name(parseManagedPermissionRules,"parseManagedPermissionRules");function nonEmptyManagedPermissionRules(rules){return rules&&RULE_KINDS.some(kind=>rules[kind].length>0)?rules:void 0}__name(nonEmptyManagedPermissionRules,"nonEmptyManagedPermissionRules");import{createHash as createHash2,randomBytes,randomUUID}from"node:crypto";import{isIPv4}from"node:net";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";var HOSTED_TOOL_RESULT_RESOURCE_LIMITS={[MANAGED_TOOL_RESULT_KINDS.content]:1024*1024,[MANAGED_TOOL_RESULT_KINDS.page]:MANAGED_TOOL_RESULT_LIMITS.maxPageBytes,[MANAGED_TOOL_RESULT_KINDS.manifest]:MANAGED_TOOL_RESULT_LIMITS.maxManifestBytes};function digest(bytes){return createHash("sha256").update(bytes).digest("hex")}__name(digest,"digest");function id(captureId,streamId,ordinal){return digest(Buffer.from(JSON.stringify([captureId,streamId,ordinal])))}__name(id,"id");function ref(resourceId,bytes){return{resourceId,kind:MANAGED_TOOL_RESULT_KINDS.content,schemaVersion:1,byteLength:bytes.length,digest:digest(bytes)}}__name(ref,"ref");var conflict={status:"refused",code:"managed_tool_result_conflict"};var invalid={status:"refused",code:"managed_tool_result_invalid"};var corrupt={status:"refused",code:"managed_tool_result_digest_mismatch"};var ok=__name(result=>({status:"ok",result}),"ok");var ResourceToolResultSegmentStore=class{constructor(resources){this.resources=resources}static{__name(this,"ResourceToolResultSegmentStore")}captureId;streams=new Map;closed=false;tail=Promise.resolve();enqueue(action){if(this.closed)return Promise.reject(new Error("Tool result store closed."));const result=this.tail.then(action);this.tail=result.catch(()=>void 0);return result}stream(captureId,streamId){if(streamId!=="stdout"&&streamId!=="stderr"||this.captureId!==void 0&&this.captureId!==captureId)return void 0;this.captureId=captureId;let stream=this.streams.get(streamId);if(!stream){stream={receipts:[],hash:createHash("sha256"),byteLength:0,sealed:false};this.streams.set(streamId,stream)}return stream}publish(request){return this.enqueue(async()=>{let input;try{input=parseToolResultPublishRequest(request)}catch{return invalid}if(input.bytes.byteLength>1024*1024)return invalid;const bytes=Buffer.from(input.bytes);const receipt={ordinal:input.ordinal,byteLength:bytes.length,digest:digest(bytes)};if(input.expectedDigest!==null&&input.expectedDigest!==receipt.digest)return corrupt;const stream=this.stream(input.captureId,input.streamId);if(!stream)return conflict;const prior=stream.receipts[input.ordinal];if(prior)return JSON.stringify(prior)===JSON.stringify(receipt)?ok(prior):conflict;if(stream.sealed||input.ordinal!==stream.receipts.length)return conflict;const resourceId=id(input.captureId,input.streamId,input.ordinal);const published=await this.resources.publish(MANAGED_TOOL_RESULT_KINDS.content,bytes,resourceId);const expected=ref(resourceId,bytes);if(Object.entries(expected).some(([key,value])=>published[key]!==value))throw new Error("Tool result publication receipt changed.");stream.receipts.push(receipt);stream.hash.update(bytes);stream.byteLength+=bytes.length;return ok(receipt)})}seal(request){return this.enqueue(async()=>{let input;try{input=parseToolResultSealRequest(request)}catch{return invalid}const stream=this.stream(input.captureId,input.streamId);if(!stream)return conflict;const receipt=this.prefixOf(stream);if(input.segmentCount!==receipt.segmentCount)return conflict;if(input.byteLength!==receipt.byteLength||input.digest!==receipt.digest)return stream.sealed?conflict:corrupt;const seal={segmentCount:input.segmentCount,byteLength:input.byteLength,digest:input.digest};const bytes=Buffer.from(JSON.stringify(seal));await this.resources.publish(MANAGED_TOOL_RESULT_KINDS.content,bytes,id(input.captureId,input.streamId,"seal"));stream.sealed=true;return ok(seal)})}prefixOf(stream){return{segmentCount:stream.receipts.length,byteLength:stream.byteLength,digest:stream.hash.copy().digest("hex"),sealed:stream.sealed}}prefix(request){return this.enqueue(async()=>{let input;try{input=parseToolResultPrefixRequest(request)}catch{return invalid}const stream=this.stream(input.captureId,input.streamId);return stream?ok(this.prefixOf(stream)):conflict})}async read(resource,kind,max){const validated=assertManagedSessionDurableRef({...resource},"tool result resource");if(validated.kind!==kind||validated.schemaVersion!==1||validated.byteLength>max){throw new Error("Tool result resource exceeds its bound.")}const bytes=await this.resources.read(validated);if(bytes.length!==validated.byteLength||digest(bytes)!==validated.digest)throw new Error("Corrupt tool result resource.");return bytes}readRange(request){return this.enqueue(async()=>{const{offset,length}=request;if(!Number.isSafeInteger(offset)||offset<0||!Number.isSafeInteger(length)||length<0||length>MANAGED_TOOL_RESULT_LIMITS.maxSegmentBytes)return invalid;const manifest=parseToolResultManifestBytes(await this.read(request.manifestRef,MANAGED_TOOL_RESULT_KINDS.manifest,MANAGED_TOOL_RESULT_LIMITS.maxManifestBytes));for(const key of["tenantId","sessionId","turnId","executionCallId","callId","invocationDigest","bindingGeneration","captureId","revision"]){if(manifest[key]!==request.expectedIdentity?.[key])return conflict}const index=manifest.contents.findIndex(entry2=>entry2.streamId===request.streamId);const entry=manifest.contents[index];if(!entry||!("pages"in entry.body)||offset>entry.byteLength||length>entry.byteLength-offset)return invalid;if(entry.state==="sealed"){const seal=Buffer.from(JSON.stringify({segmentCount:entry.body.pages.reduce((sum,page)=>sum+page.segmentCount,0),byteLength:entry.byteLength,digest:entry.digest}));await this.read(ref(id(manifest.captureId,entry.streamId,"seal"),seal),MANAGED_TOOL_RESULT_KINDS.content,1024)}const output=Buffer.alloc(length);for(const[pageIndex,pageRef]of entry.body.pages.entries()){const page=parseToolResultPageBytes(await this.read(pageRef.ref,MANAGED_TOOL_RESULT_KINDS.page,MANAGED_TOOL_RESULT_LIMITS.maxPageBytes));if(!isToolResultPageAt(manifest,index,pageIndex,page))return conflict;let position=page.offset;for(const[segmentIndex,segment]of page.segments.entries()){const end=position+segment.byteLength;if(position<offset+length&&end>offset){const bytes=await this.read({resourceId:id(manifest.captureId,entry.streamId,page.firstOrdinal+segmentIndex),kind:MANAGED_TOOL_RESULT_KINDS.content,schemaVersion:1,...segment},MANAGED_TOOL_RESULT_KINDS.content,1024*1024);const from=Math.max(position,offset);const to=Math.min(end,offset+length);bytes.copy(output,from-offset,from-position,to-position)}position=end}}return ok(output)})}async close(){this.closed=true;await this.tail;this.streams.clear()}};var HTTP_MANAGED_SESSION_STORE_CONTRACT={tenantHeader:"X-Qwen-Tenant-Id",writerTokenHeader:"X-Qwen-Managed-Writer-Token",maxInlineResourceBytes:64*1024,maxResourcesPerTransaction:1024,minimumWriterTokenLength:32,maximumWriterTokenLength:512,minimumLeaseDurationMs:1e3,maximumLeaseDurationMs:3e5};var MAX_ATTACHMENT_INPUT_BYTES=8*1024*1024;var MAX_NATIVE_SNAPSHOT_PAGE_BYTES=16*1024*1024;function managedSessionInlineResourceBytes(kind){if(kind==="managed-checkpoint")return MANAGED_SESSION_LIMITS.maxEventBytes;if(kind==="managed-input")return MAX_ATTACHMENT_INPUT_BYTES;if(kind==="managed-agent-skills")return 2*1024*1024;if(kind==="hosted-model-request")return HOSTED_MODEL_REQUEST_BYTES;return HTTP_MANAGED_SESSION_STORE_CONTRACT.maxInlineResourceBytes}__name(managedSessionInlineResourceBytes,"managedSessionInlineResourceBytes");var WRITER_TOKEN=new RegExp(`^[A-Za-z0-9_-]{${HTTP_MANAGED_SESSION_STORE_CONTRACT.minimumWriterTokenLength},${HTTP_MANAGED_SESSION_STORE_CONTRACT.maximumWriterTokenLength}}$`);var DEFAULT_LEASE_DURATION_MS=6e4;var DEFAULT_REQUEST_TIMEOUT_MS=3e4;var debugLogger=createDebugLogger("MANAGED_SESSION_STORE");function isLoopbackHostname(hostname){const lower=hostname.toLowerCase();return lower==="localhost"||lower.endsWith(".localhost")||isIPv4(lower)&&lower.startsWith("127.")||lower==="[::1]"}__name(isLoopbackHostname,"isLoopbackHostname");var ManagedSessionStoreHttpError=class extends ManagedSessionRecordError{constructor(status,remoteCode,message,contentionExhausted,details,route){super(message);this.status=status;this.remoteCode=remoteCode;this.contentionExhausted=contentionExhausted;this.details=details;this.route=route;this.name="ManagedSessionStoreHttpError"}static{__name(this,"ManagedSessionStoreHttpError")}writerRefusalContext};var ManagedSessionStoreTransportError=class extends ManagedSessionRecordError{static{__name(this,"ManagedSessionStoreTransportError")}};function isUncertainStoreFailure(error){return error instanceof ManagedSessionStoreHttpError&&(error.status===429||error.status>=500)||error instanceof ManagedSessionStoreTransportError||error instanceof TypeError||error instanceof DOMException&&["AbortError","TimeoutError"].includes(error.name)}__name(isUncertainStoreFailure,"isUncertainStoreFailure");function asError(error){return error instanceof Error?error:new Error(String(error))}__name(asError,"asError");function createHttpManagedSessionStores(options){const resources=new HttpManagedSessionResourceStore;const client=new ManagedSessionStoreHttpClient(options,resources);resources.bind(client);return{journalStore:new HttpManagedSessionJournalStore(client),resourceStore:resources,publication:{owner:__name(()=>client.publicationOwner(),"owner"),request:__name((path,body,token)=>client.publicationRequest(path,body,token),"request"),rememberAdmission:__name((publicationId,ref2)=>client.rememberAdmission(publicationId,ref2),"rememberAdmission")},toolResultResources:{publish:__name((kind,bytes,resourceId)=>client.publishToolResult(kind,bytes,resourceId),"publish"),read:__name(ref2=>client.readResource(ref2),"read")},csiRetirement:{joinWriter:__name(()=>client.joinOriginalCsiWriter(),"joinWriter"),prepare:__name(records=>client.prepareOriginalCsiCommit(records),"prepare"),complete:__name(retirementId=>client.completeOriginalCsiRetirement(retirementId),"complete")},assertWritable:__name(()=>client.assertWritable(),"assertWritable"),stopLocal:__name(()=>client.stopLocal(),"stopLocal"),quiesceOwnership:__name(placement=>client.quiesceOwnership(placement),"quiesceOwnership"),releaseOwnership:__name(request=>client.releaseOwnership(request),"releaseOwnership"),close:__name(()=>client.seal(),"close"),setLifecycleAuthority:__name(authority=>client.setLifecycleAuthority(authority),"setLifecycleAuthority"),authorizeLifecycle:__name(kind=>client.authorizeLifecycle(kind),"authorizeLifecycle"),authorizeOrdinary:__name(kind=>client.authorizeOrdinary(kind),"authorizeOrdinary"),approvalSelection:__name(()=>client.approvalSelection(),"approvalSelection"),claimUserMessages:__name((promptId,initialOnly)=>client.claimUserMessages(promptId,initialOnly),"claimUserMessages")}}__name(createHttpManagedSessionStores,"createHttpManagedSessionStores");var HttpManagedSessionJournalStore=class{constructor(client){this.client=client}static{__name(this,"HttpManagedSessionJournalStore")}handle;opening;async open(request){if(!managedSessionKeysEqual(request.sessionKey,this.client.sessionKey)){throw new ManagedSessionRecordError("the HTTP Managed Session store belongs to a different session.")}if(this.handle!==void 0)return this.handle;if(this.opening!==void 0)return this.opening;const opening=(async()=>{await this.client.acquireWriter();const handle=new HttpManagedSessionJournalHandle(this.client);this.handle=handle;return handle})();this.opening=opening;try{return await opening}finally{if(this.opening===opening)this.opening=void 0}}};var HttpManagedSessionJournalHandle=class{constructor(client){this.client=client;this.sessionKey=client.sessionKey}static{__name(this,"HttpManagedSessionJournalHandle")}sessionKey;read(options={}){return this.client.readJournal(options.maxBytes)}async appendTransaction(records){try{await this.client.appendTransaction(records)}catch(error){if(!(error instanceof ManagedSessionCommitRejectedError)&&!(error instanceof ManagedSessionAppendUnsettledError))this.client.stopWriterRenewal();throw error}}renewActivation(request){return this.client.renewActivation(request)}async settleAppend(){try{return await this.client.settleAppend()}catch(error){if(!(error instanceof ManagedSessionAppendUnsettledError)){this.client.stopWriterRenewal();await this.client.seal().catch(()=>void 0)}throw error}}blockRecovery(request){return this.client.blockRecovery(request)}seal(){return this.client.seal()}get writerSealed(){return this.client.writerSealed}abort(){return this.client.seal()}};var EXTENSION_RECORD_KINDS=new Set(Object.keys(MANAGED_EXTENSION_RECORD_BODIES).map(domain=>`managed-${domain}`));var HttpManagedSessionResourceStore=class{static{__name(this,"HttpManagedSessionResourceStore")}staged=new Map;client;bind(client){this.client=client}async publish(kind,source){const safeKind=assertManagedSessionStableId(kind,"resource kind");const maxBytes=managedSessionInlineResourceBytes(safeKind);if(source.byteLength>maxBytes){throw new ManagedSessionRecordError(`resource bytes exceed the ${maxBytes}-byte inline limit (kind=${safeKind}, bytes=${source.byteLength}); OSS storage is not enabled.`)}const bytes=Buffer.from(source);const ref2={resourceId:randomUUID(),kind:safeKind,schemaVersion:1,byteLength:bytes.byteLength,digest:sha256(bytes)};this.staged.set(ref2.resourceId,{ref:ref2,bytes});return ref2}async read(ref2){const validated=assertManagedSessionDurableRef(ref2,"resource");const staged=this.staged.get(validated.resourceId);if(staged!==void 0){requireSameRef(staged.ref,validated);return Buffer.from(staged.bytes)}if(this.client===void 0){throw new ManagedSessionRecordError("the HTTP Managed Session resource store is not bound.")}return this.client.readResource(validated)}async commitResources(refs){const closure=new Map;const pending=[...refs];while(pending.length>0){const ref2=pending.pop();const existing=closure.get(ref2.resourceId);if(existing!==void 0){requireSameRef(existing,ref2);continue}closure.set(ref2.resourceId,ref2);if(closure.size>HTTP_MANAGED_SESSION_STORE_CONTRACT.maxResourcesPerTransaction){throw new ManagedSessionRecordError(`a Managed Session transaction references more than ${HTTP_MANAGED_SESSION_STORE_CONTRACT.maxResourcesPerTransaction} resources.`)}const staged=this.staged.get(ref2.resourceId);if(staged!==void 0){requireSameRef(staged.ref,ref2);const nested=collectNestedResourceRefs(ref2,staged.bytes);pending.push(...ref2.kind===CHECKPOINT_HISTORY_KIND?nested.filter(child=>this.staged.has(child.resourceId)):nested)}else if(ref2.kind!==CHECKPOINT_HISTORY_KIND&&isReferenceContainer(ref2.kind)){pending.push(...collectNestedResourceRefs(ref2,await this.read(ref2)))}}return[...closure.values()].map(ref2=>{const staged=this.staged.get(ref2.resourceId);if(staged!==void 0)requireSameRef(staged.ref,ref2);return{resourceId:ref2.resourceId,kind:ref2.kind,schemaVersion:ref2.schemaVersion,byteLength:ref2.byteLength,digest:ref2.digest,...staged===void 0?{}:{bytesBase64:staged.bytes.toString("base64")}}})}releaseCommitted(refs){for(const ref2 of refs)this.staged.delete(ref2.resourceId)}clear(){this.staged.clear()}};var ManagedSessionStoreHttpClient=class{constructor(options,resources){this.resources=resources;this.sessionKey=options.sessionKey;this.writerId=assertManagedSessionStableId(options.writerId,"writerId");this.writerToken=options.writerToken??randomBytes(32).toString("base64url");if(!WRITER_TOKEN.test(this.writerToken)){throw new ManagedSessionRecordError("writerToken must be a 32-512 character Base64URL secret.")}this.leaseDurationMs=options.leaseDurationMs??DEFAULT_LEASE_DURATION_MS;if(!Number.isInteger(this.leaseDurationMs)||this.leaseDurationMs<HTTP_MANAGED_SESSION_STORE_CONTRACT.minimumLeaseDurationMs||this.leaseDurationMs>HTTP_MANAGED_SESSION_STORE_CONTRACT.maximumLeaseDurationMs){throw new ManagedSessionRecordError("leaseDurationMs must be an integer from 1000 through 300000.")}this.requestTimeoutMs=options.requestTimeoutMs??DEFAULT_REQUEST_TIMEOUT_MS;if(!Number.isInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1){throw new ManagedSessionRecordError("requestTimeoutMs must be a positive integer.")}const parsed=new URL(options.baseUrl);if(parsed.protocol!=="http:"&&parsed.protocol!=="https:"||parsed.username!==""||parsed.password!==""||parsed.search!==""||parsed.hash!==""){throw new ManagedSessionRecordError("baseUrl must be an HTTP(S) URL without credentials, query, or fragment.")}if(parsed.protocol==="http:"&&!isLoopbackHostname(parsed.hostname)&&options.allowInsecureHttp!==true){throw new ManagedSessionRecordError("baseUrl uses plaintext HTTP on a non-loopback host; writer tokens would cross the wire unencrypted. Pass allowInsecureHttp: true to opt in.")}this.baseUrl=parsed.toString().replace(/\/$/,"");this.fetchFn=options.fetchFn??globalThis.fetch}static{__name(this,"ManagedSessionStoreHttpClient")}sessionKey;baseUrl;writerId;writerToken;leaseDurationMs;requestTimeoutMs;fetchFn;grant;renewPromise;ownershipRelease;acquirePromise;renewingAuthority;renewTimer;renewalStopped=false;retirementJoin;writerRenewalFailures=[];preparedRetirement;sealed=false;locallyStopped=false;lifecycleAuthority;pendingAppend;get writerSealed(){return this.sealed}setLifecycleAuthority(authority){this.lifecycleAuthority=authority}async authorizeOrdinary(kind){await this.assertWritable();await this.json("/execution:authorize","POST",{...kind?{kind}:{},workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:this.grant.writerGeneration})}async claimUserMessages(promptId,initialOnly){await this.assertWritable();let value;try{value=await this.json("/user-messages:claim","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:this.grant.writerGeneration,promptId,initialOnly:initialOnly??false})}catch(error){if(error instanceof ManagedSessionStoreHttpError&&error.status===404&&error.remoteCode==="not_found")return[];throw error}if(!Array.isArray(value)||value.length>32)throw corrupt2("invalid user message queue.");return value.map(entry=>{const message=asRecord(entry,"queued user message");if(typeof message["id"]!=="string"||!message["id"].startsWith("umsg_")||!Number.isSafeInteger(message["revision"])||Number(message["revision"])<1||!Array.isArray(message["input"]))throw corrupt2("invalid queued user message.");return{id:message["id"],revision:Number(message["revision"]),input:message["input"]}})}async approvalSelection(){await this.assertWritable();const value=await this.json("/approval:query","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:this.grant.writerGeneration});if(value===null)return void 0;const selection=asRecord(value,"approval selection");if(Object.keys(selection).length!==(selection["permissionRules"]===void 0?2:3)||!["default","auto-edit","yolo","auto"].includes(String(selection["mode"]))||typeof selection["mode"]!=="string"||typeof selection["revision"]!=="number"||!Number.isSafeInteger(selection["revision"])||selection["revision"]<0)throw corrupt2("approval selection is invalid.");let permissionRules;try{permissionRules=selection["permissionRules"]===void 0?void 0:nonEmptyManagedPermissionRules(parseManagedPermissionRules(selection["permissionRules"]))}catch{throw corrupt2("approval selection rules are invalid.")}if(selection["revision"]===0&&(selection["mode"]==="auto"||permissionRules))throw corrupt2("approval selection revision is invalid.");return{mode:selection["mode"],revision:selection["revision"],...permissionRules?{permissionRules}:{}}}async authorizeLifecycle(kind){if(kind)await this.assertWritable();const grant=this.grant;if(!grant)throw new ManagedSessionRecordError("the HTTP Managed Session writer is not active.");await this.json("/lifecycle:authorize","POST",{...kind?{kind}:{},workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration})}publicationAdmissions=new Map;async acquireWriter(){if(this.ownershipRelease)throw corrupt2("ownership release has fenced this writer.");if(this.grant!==void 0||this.sealed||this.locallyStopped){throw new ManagedSessionRecordError("the HTTP Managed Session writer is already opened or sealed.")}const grant=parseWriterGrant(await this.json("/writers:acquire","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,leaseMillis:this.leaseDurationMs}));this.grant=grant;debugLogger.debug(`Managed Session Store writer acquired: session=${this.sessionKey.sessionId} writerId=${this.writerId} acquiredWriterGeneration=${grant.writerGeneration} journalRevision=${grant.journalRevision} committedSequence=${grant.committedSequence} leaseUntil=${new Date(grant.leaseUntil).toISOString()}`);this.scheduleRenewal()}async readJournal(maxBytes){await this.ensureWriter();const response=asRecord(await this.json(`/restore?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}&includeNativeSnapshot=true`,"GET"),"restore head");const head=parseRestoreHead(response);const usesSnapshot=response["nativeSnapshot"]!=null;this.requireHeadMatchesGrant(head);debugLogger.debug(`Managed Session Store restore head matches grant: session=${this.sessionKey.sessionId} writerId=${this.writerId} acquiredWriterGeneration=${this.requireGrant().writerGeneration} headGeneration=${head.writerGeneration} journalRevision=${head.journalRevision} committedSequence=${head.committedSequence} state=${head.state} storageVersion=${head.storageVersion}`);const chunks=[];let afterRevision=0;let activationEpoch=0;let committedSequence=0;let lastCommitDigest=null;let latestCheckpointResourceId=null;const append=__name(value=>{const transaction=parseStoredTransaction(value);if(transaction.journalRevision!==afterRevision+1||usesSnapshot&&transaction.journalRevision>head.journalRevision){throw corrupt2("transaction revisions are not contiguous.")}const bytes2=decodeBase64(transaction.recordBytesBase64,"recordBytesBase64");if(bytes2.byteLength!==transaction.byteLength||sha256(bytes2)!==transaction.recordDigest){throw corrupt2("transaction bytes do not match their metadata.")}const descriptor=describeTransaction(decodeRecords(bytes2),bytes2,activationEpoch,this.sessionKey);requireStoredTransactionMatches(transaction,descriptor);if(usesSnapshot&&(transaction.previousCommitDigest!==lastCommitDigest||(afterRevision===0?transaction.operation!=="session.create"||transaction.eventCount!==0:transaction.operation==="session.create"||transaction.firstSequence!==committedSequence+1))){throw corrupt2("snapshot transaction chain is discontinuous.")}activationEpoch=descriptor.activationEpoch;committedSequence=transaction.lastSequence;lastCommitDigest=transaction.commitDigest;latestCheckpointResourceId=descriptor.latestCheckpointResourceId??latestCheckpointResourceId;chunks.push(bytes2);afterRevision=transaction.journalRevision;return descriptor},"append");if(usesSnapshot){const snapshot=await this.readNativeSnapshot(response["nativeSnapshot"],head,append);if(afterRevision!==snapshot.coveredJournalRevision||committedSequence!==snapshot.committedSequence||lastCommitDigest!==snapshot.lastCommitDigest||activationEpoch!==snapshot.activationEpoch||latestCheckpointResourceId!==snapshot.latestCheckpointResourceId){throw corrupt2("snapshot prefix does not match its manifest.")}}while(afterRevision<head.journalRevision){await this.ensureWriter();const limit=usesSnapshot?Math.min(100,head.journalRevision-afterRevision):100;const page=asRecord(await this.json(`/transactions?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}&afterRevision=${afterRevision}&limit=${limit}`,"GET"),"transaction page");const transactions=asArray(page["transactions"],"transactions");if(transactions.length===0){throw corrupt2("transaction page did not advance the journal.")}for(const value of transactions){append(value)}const nextRevision=safeCounter(page["nextRevision"],"nextRevision");const hasMore=boolean(page["hasMore"],"hasMore");if(nextRevision!==afterRevision){throw corrupt2("transaction page nextRevision is inconsistent.")}if(!hasMore&&afterRevision!==head.journalRevision){throw corrupt2("transaction page ended before the journal head.")}}const bytes=Buffer.concat(chunks);const scan=scanManagedSessionJournal(bytes,this.sessionKey,usesSnapshot?void 0:maxBytes);if((usesSnapshot||maxBytes===void 0)&&(scan.committed!==head.committedSequence||scan.lastMarkerDigest!==head.lastCommitDigest||(scan.activation?.epoch??0)!==head.activationEpoch||usesSnapshot&&latestCheckpointResourceId!==head.latestCheckpointResourceId)){throw corrupt2("journal bytes do not match the durable head.")}if(usesSnapshot){await this.ensureWriter();const current=parseRestoreHead(await this.json(`/restore?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}`,"GET"));this.requireHeadMatchesGrant(current);this.requireHeadMatchesGrant(head);if(current.journalRevision<head.journalRevision||current.committedSequence<head.committedSequence)throw corrupt2("restore head regressed while reading the snapshot.")}this.grant={...this.requireGrant(),writerGeneration:head.writerGeneration,leaseUntil:this.requireGrant().leaseUntil,journalRevision:head.journalRevision,committedSequence:head.committedSequence,lastCommitDigest:head.lastCommitDigest,activationEpoch:head.activationEpoch};const result=usesSnapshot&&maxBytes!==void 0?scanManagedSessionJournal(bytes,this.sessionKey,maxBytes):scan;return maxBytes===void 0?applyActivationLease(result,head.activationLease):result}async renewActivation(activation){if(!this.requireGrant().activationLeaseRenewal)return void 0;let reacquiring=false;try{if(this.requireGrant().leaseUntil<=Date.now()){reacquiring=true;await this.reacquireWriter();reacquiring=false}await this.ensureWriter();const grant=this.requireGrant();const renewed=parseWriterGrant(await this.json("/writers:renew","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,leaseMillis:this.leaseDurationMs,activation}));if(renewed.writerGeneration!==grant.writerGeneration||renewed.journalRevision!==grant.journalRevision||renewed.committedSequence!==grant.committedSequence||renewed.lastCommitDigest!==grant.lastCommitDigest||renewed.activationEpoch!==grant.activationEpoch||!renewed.activationLease)throw corrupt2("activation renewal changed the journal head.");this.grant=renewed;this.scheduleRenewal();return renewed.activationLease}catch(error){if(error instanceof ManagedSessionStoreHttpError&&(error.status===409&&["workspace_lifecycle_admission_closed","workspace_lifecycle_claim_fenced"].includes(error.remoteCode)||this.lifecycleAuthority&&(error.status===403||error.status===409&&(error.remoteCode.startsWith("workspace_lifecycle_")||error.remoteCode==="workspace_unavailable"))))throw new ManagedSessionCommitRejectedError(error);if(isUncertainStoreFailure(error)||!reacquiring&&this.requireGrant().leaseUntil<=Date.now()&&error instanceof ManagedSessionStoreHttpError&&error.status===409&&error.remoteCode==="managed_session_writer_conflict")throw new ManagedSessionAppendUnsettledError(asError(error));this.stopWriterRenewal();throw error}}async readNativeSnapshot(value,head,append){const descriptor=asRecord(value,"native snapshot descriptor");const raw=asRecord(descriptor["snapshot"],"native snapshot manifest");const manifestRef=assertManagedSessionDurableRef(descriptor["manifest"],"native manifest");const snapshot={snapshotId:string(raw["snapshotId"],"snapshotId"),coveredJournalRevision:safeCounter(raw["coveredJournalRevision"],"coveredJournalRevision"),committedSequence:safeCounter(raw["committedSequence"],"committedSequence"),lastCommitDigest:nullableDigest(raw["lastCommitDigest"],"lastCommitDigest"),activationEpoch:safeCounter(raw["activationEpoch"],"activationEpoch"),latestCheckpointResourceId:nullableString(raw["latestCheckpointResourceId"],"latestCheckpointResourceId"),resourceCount:safeCounter(raw["resourceCount"],"resourceCount"),lastPageDigest:digest2(raw["lastPageDigest"],"lastPageDigest")};const storageVersion=safeCounter(raw["storageVersion"],"snapshot storageVersion");if(raw["format"]!=="qwen-managed-native-session-snapshot/1"||raw["payloadFormat"]!=="committed-prefix-v1"||raw["tenantId"]!==this.sessionKey.tenantId||raw["workspaceId"]!==this.sessionKey.workspaceId||raw["sessionId"]!==this.sessionKey.sessionId||snapshot.snapshotId.length===0||Buffer.byteLength(snapshot.snapshotId,"utf8")>512||![1,2].includes(storageVersion)||storageVersion>head.storageVersion||snapshot.coveredJournalRevision<1||snapshot.coveredJournalRevision>head.journalRevision||snapshot.committedSequence>head.committedSequence||snapshot.activationEpoch>head.activationEpoch||raw["pageCount"]!==snapshot.coveredJournalRevision||manifestRef.kind!=="managed-native-journal-snapshot"||manifestRef.schemaVersion!==1||manifestRef.byteLength>MAX_NATIVE_SNAPSHOT_PAGE_BYTES){throw corrupt2("native snapshot scope, format or coverage is invalid.")}const resources=new Map;let after=0;let previousDigest=null;while(after<snapshot.coveredJournalRevision){await this.ensureWriter();const result=asRecord(await this.json(`/journal-snapshots/${encodeURIComponent(snapshot.snapshotId)}/pages?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}&afterRevision=${after}&limit=100`,"GET"),"native snapshot pages");const pages=asArray(result["pages"],"native snapshot pages");if(pages.length===0||pages.length>100)throw corrupt2("native snapshot pages did not advance.");let responseBytes=0;for(const item of pages){const stored=asRecord(item,"native snapshot page");const ref2=assertManagedSessionDurableRef(stored["resource"],"native page resource");if(ref2.kind!=="managed-native-journal-snapshot-page"||ref2.schemaVersion!==1||ref2.byteLength>MAX_NATIVE_SNAPSHOT_PAGE_BYTES||string(stored["bytesBase64"],"native page bytes").length>Math.ceil(ref2.byteLength/3)*4){throw corrupt2("native snapshot page resource is invalid.")}const bytes=decodeBase64(string(stored["bytesBase64"],"native page bytes"),"native page bytes");responseBytes+=bytes.byteLength;if(bytes.byteLength!==ref2.byteLength||sha256(bytes)!==ref2.digest||responseBytes>MAX_NATIVE_SNAPSHOT_PAGE_BYTES)throw corrupt2("native snapshot page digest or size is invalid.");const page=asRecord(parseManagedSessionRecordJson(bytes.toString("utf8"),MAX_NATIVE_SNAPSHOT_PAGE_BYTES),"native snapshot page body");if(stored["journalRevision"]!==after+1||page["journalRevision"]!==after+1||page["previousPageDigest"]!==previousDigest||after>=snapshot.coveredJournalRevision){throw corrupt2("native snapshot page chain is discontinuous.")}const census=asArray(page["resources"],"native resource census");if(census.length>HTTP_MANAGED_SESSION_STORE_CONTRACT.maxResourcesPerTransaction)throw corrupt2("native resource census is too large.");const seen=new Set;const added=[];for(const item2 of census){const{bytesBase64,...metadata}=asRecord(item2,"native resource");const resource=assertManagedSessionDurableRef(metadata,"native resource");if(bytesBase64!=null||seen.has(resource.resourceId)||["managed-native-journal-snapshot","managed-native-journal-snapshot-page"].includes(resource.kind)||resources.has(resource.resourceId)&&!isDeepStrictEqual(resources.get(resource.resourceId),resource)){throw corrupt2("native resource census conflicts.")}seen.add(resource.resourceId);if(!resources.has(resource.resourceId))added.push(resource);resources.set(resource.resourceId,resource)}const transaction=asRecord(page["transaction"],"native snapshot transaction");if(transaction["journalRevision"]!==after+1)throw corrupt2("native snapshot transaction revision conflicts.");const declared=append(transaction).refs;for(const resource of added){const body=await this.readResource(resource);declared.push(...collectNestedResourceRefs(resource,body))}for(const resource of declared){if(!isDeepStrictEqual(resources.get(resource.resourceId),resource))throw corrupt2("native resource dependency is missing or conflicting.")}previousDigest=ref2.digest;after++}if(safeCounter(result["nextRevision"],"nextRevision")!==after||boolean(result["hasMore"],"hasMore")!==after<snapshot.coveredJournalRevision){throw corrupt2("native snapshot cursor is inconsistent.")}}if(previousDigest!==snapshot.lastPageDigest||resources.size!==snapshot.resourceCount){throw corrupt2("native snapshot digest or resource count conflicts.")}return snapshot}async appendTransaction(records){if(this.pendingAppend!==void 0)await this.settleAppend();try{await this.ensureWriter()}catch(error){const grant2=this.grant;if(isUncertainStoreFailure(error)||grant2!==void 0&&grant2.leaseUntil<=Date.now()&&error instanceof ManagedSessionStoreHttpError&&error.status===409){this.pendingAppend={recordDigest:sha256(encodeRecords(records)),baseRevision:grant2?.journalRevision??0};throw new ManagedSessionAppendUnsettledError(asError(error))}throw error}const grant=this.requireGrant();const{recordBytes,descriptor,commitResources,publicationId,commitBody,needsVersionTwo}=await this.commitBody(records,grant);let committed;const contentionDeadline=Date.now()+this.requestTimeoutMs;for(let attempt=0;;attempt++){try{committed=publicationId===void 0?await this.json(needsVersionTwo?"/transactions:commit-v2":"/transactions:commit","POST",commitBody,contentionDeadline):await this.publicationRequest(`/publications/${encodeURIComponent(publicationId)}/receipts/commit`,commitBody,void 0,contentionDeadline);break}catch(error){await this.annotateWriterRefusal(error);if(descriptor.operation==="manageMcp"&&error instanceof ManagedSessionStoreHttpError&&error.status===409&&["unsupported_feature","turn_active","session_context_busy"].includes(error.remoteCode))throw new ManagedSessionCommitRejectedError(error);if(attempt===0&&error instanceof ManagedSessionStoreHttpError&&(error.status===409&&(error.remoteCode==="workspace_lifecycle_admission_closed"||error.remoteCode==="workspace_lifecycle_claim_fenced"||error.remoteCode==="child_run_lineage_minted"||error.remoteCode==="session_message_lineage_refused"||error.remoteCode==="context_compression_authorization_revoked"||descriptor.operation==="contextCompression"&&error.remoteCode==="workspace_unavailable")||this.lifecycleAuthority&&(error.status===403||error.status===409&&(error.remoteCode.startsWith("workspace_lifecycle_")||error.remoteCode==="workspace_unavailable"))))throw new ManagedSessionCommitRejectedError(error);const uncertain=isUncertainStoreFailure(error);const contentionSpent=error instanceof ManagedSessionStoreHttpError&&(error.contentionExhausted===true||publicationId===void 0&&error.status===503&&error.remoteCode==="tenant_guard_contended"&&contentionDeadline-Date.now()<=250);const exhausted=attempt>=2;const unsettled=!contentionSpent&&(isUncertainStoreFailure(error)||grant.leaseUntil<=Date.now()&&error instanceof ManagedSessionStoreHttpError&&error.status===409);if(!uncertain||contentionSpent||exhausted&&(descriptor.operation!=="renewActivation"||this.renewalStopped||grant.leaseUntil<=Date.now())){if(unsettled){this.pendingAppend={recordDigest:sha256(recordBytes),baseRevision:grant.journalRevision,commitResources,descriptor};throw new ManagedSessionAppendUnsettledError(asError(error))}throw error}await new Promise(resolve=>setTimeout(resolve,exhausted?Math.min(1e3,grant.leaseUntil-Date.now()):250));if(exhausted&&(this.renewalStopped||grant.leaseUntil<=Date.now())){if(unsettled){this.pendingAppend={recordDigest:sha256(recordBytes),baseRevision:grant.journalRevision,commitResources,descriptor};throw new ManagedSessionAppendUnsettledError(asError(error))}throw error}}}const receipt=asRecord(committed,"commit receipt");const revision=safeCounter(receipt["journalRevision"],"journalRevision");if(revision!==grant.journalRevision+1||(publicationId===void 0?string(receipt["transactionId"],"transactionId")!==descriptor.transactionId||string(receipt["commandId"],"commandId")!==descriptor.commandId||string(receipt["operation"],"operation")!==descriptor.operation||safeCounter(receipt["firstSequence"],"firstSequence")!==descriptor.firstSequence||safeCounter(receipt["lastSequence"],"lastSequence")!==descriptor.lastSequence||safeCounter(receipt["committedSequence"],"committedSequence")!==descriptor.lastSequence||nullableDigest(receipt["commitDigest"],"commitDigest")!==descriptor.commitDigest:safeCounter(receipt["historyRevision"],"historyRevision")!==descriptor.lastSequence||!descriptor.refs.some(ref2=>ref2.resourceId===asRecord(receipt["toolOutcomeRef"],"toolOutcomeRef")["resourceId"]))){throw corrupt2("commit receipt does not match the submitted transaction.")}this.grant={...this.requireGrant(),journalRevision:revision,committedSequence:descriptor.lastSequence,lastCommitDigest:descriptor.commitDigest,activationEpoch:descriptor.activationEpoch};this.resources.releaseCommitted(commitResources);for(const ref2 of descriptor.refs)this.publicationAdmissions.delete(ref2.resourceId)}async settleAppend(){const pending=this.pendingAppend;if(pending===void 0)return"absent";let reacquired=false;for(;;){try{if(this.grant===void 0){throw new ManagedSessionRecordError("the HTTP Managed Session writer is not active.")}if(this.grant.leaseUntil<=Date.now())await this.reacquireWriter();const head=parseRestoreHead(await this.json(`/restore?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}`,"GET"));this.requireHeadMatchesGrant(head);if(head.journalRevision===pending.baseRevision){this.pendingAppend=void 0;this.adoptHead(head);return"absent"}if(pending.descriptor===void 0||head.journalRevision!==pending.baseRevision+1){throw new ManagedSessionJournalFencedError(`the journal advanced to revision ${head.journalRevision} past this writer's ${pending.baseRevision} while its append outcome was unknown; the Session needs a takeover.`)}const page=asRecord(await this.json(`/transactions?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}&afterRevision=${pending.baseRevision}&limit=1`,"GET"),"transaction page");const rows=asArray(page["transactions"],"transactions");const stored=parseStoredTransaction(rows[0]);if(stored.journalRevision!==head.journalRevision||stored.recordDigest!==pending.recordDigest){throw new ManagedSessionJournalFencedError("the journal holds a different transaction at this append position; the Session needs a takeover.")}this.resources.releaseCommitted(pending.commitResources??[]);for(const ref2 of pending.descriptor.refs)this.publicationAdmissions.delete(ref2.resourceId);this.pendingAppend=void 0;this.adoptHead(head);return"landed"}catch(error){if(error instanceof ManagedSessionAppendUnsettledError)throw error;const lapsed=this.grant!==void 0&&this.grant.leaseUntil<=Date.now();if(!reacquired&&lapsed&&error instanceof ManagedSessionStoreHttpError&&error.status===409){reacquired=true;continue}if(isUncertainStoreFailure(error))throw new ManagedSessionAppendUnsettledError(asError(error));throw error}}}adoptHead(head){this.grant={...this.requireGrant(),journalRevision:head.journalRevision,committedSequence:head.committedSequence,lastCommitDigest:head.lastCommitDigest,activationEpoch:head.activationEpoch};this.scheduleRenewal()}async commitBody(records,grant){const recordBytes=encodeRecords(records);const descriptor=describeTransaction(records,recordBytes,grant.activationEpoch,this.sessionKey);if(descriptor.previousCommitDigest!==grant.lastCommitDigest){throw new ManagedSessionRecordError("the transaction does not extend the HTTP journal head.")}const commitResources=await this.resources.commitResources(descriptor.refs);const needsVersionTwo=commitResources.some(resource=>HOSTED_RECOVERY_RESOURCE_KINDS.has(resource.kind)||resource.kind==="managed-action-options"&&resource.bytesBase64&&JSON.parse(Buffer.from(resource.bytesBase64,"base64").toString("utf8")).v===3)||records.some(record=>{const event=record.managedSession;return event?.kind==="message.retracted"&&event.payload?.["sourceBootId"]!==void 0});if(needsVersionTwo&&grant.supportedStorageVersion<2)throw new ManagedSessionRecordError("Managed Session Store does not support Hosted recovery storage version 2.");const publicationIds=new Set(descriptor.refs.flatMap(ref2=>{const id2=this.publicationAdmissions.get(ref2.resourceId);return id2===void 0?[]:[id2]}));if(publicationIds.size>1){throw new ManagedSessionRecordError("Transaction mixes publication admissions.")}const publicationId=[...publicationIds][0];const commitBody={workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,expectedJournalRevision:grant.journalRevision,expectedCommittedSequence:grant.committedSequence,transactionId:descriptor.transactionId,operation:descriptor.operation,commandId:descriptor.commandId,contentDigest:descriptor.contentDigest,firstSequence:descriptor.firstSequence,lastSequence:descriptor.lastSequence,eventCount:descriptor.eventCount,eventsDigest:descriptor.eventsDigest,previousCommitDigest:descriptor.previousCommitDigest,commitDigest:descriptor.commitDigest,activationEpoch:descriptor.activationEpoch,latestCheckpointResourceId:descriptor.latestCheckpointResourceId,recordCount:records.length,recordBytesBase64:recordBytes.toString("base64"),recordDigest:sha256(recordBytes),resources:commitResources};return{recordBytes,descriptor,commitResources,publicationId,commitBody,needsVersionTwo}}joinOriginalCsiWriter(){if(this.retirementJoin)return this.retirementJoin;this.stopRenewal();const renewal=this.renewPromise;if(this.acquirePromise||this.pendingAppend)return Promise.reject(corrupt2("original CSI writer has unresolved authority."));this.retirementJoin=(async()=>{await renewal;if(this.writerRenewalFailures.length)throw this.writerRenewalFailures[0];const grant=this.requireGrant();if(grant.writerGeneration!==1||grant.activationEpoch!==1||grant.leaseUntil<=Date.now()){throw corrupt2("original CSI writer cannot prepare retirement.")}})();return this.retirementJoin}async prepareOriginalCsiCommit(records){if(!this.retirementJoin)throw corrupt2("original CSI writer has not joined.");await this.retirementJoin;const recordDigest=sha256(encodeRecords(records));if(this.preparedRetirement){if(recordDigest!==this.preparedRetirement.recordDigest)throw corrupt2("original CSI preparation conflicts.");const{commitBodyBase64:commitBodyBase642,preparedCommitSha256:preparedCommitSha2562}=this.preparedRetirement;return{commitBodyBase64:commitBodyBase642,preparedCommitSha256:preparedCommitSha2562}}const{descriptor,commitResources,publicationId,commitBody}=await this.commitBody(records,this.requireGrant());if(descriptor.operation!=="releaseActivation"||descriptor.eventCount!==1||records.length!==2||descriptor.latestCheckpointResourceId!==null||publicationId!==void 0||commitResources.length!==1||commitResources[0].kind!=="managed-activation-boundary"||commitResources[0].bytesBase64===void 0){throw corrupt2("original CSI release preparation is invalid.")}const bytes=Buffer.from(JSON.stringify(commitBody),"utf8");this.preparedRetirement={recordDigest,commitBodyBase64:bytes.toString("base64"),preparedCommitSha256:sha256(bytes)};const{commitBodyBase64,preparedCommitSha256}=this.preparedRetirement;return{commitBodyBase64,preparedCommitSha256}}async completeOriginalCsiRetirement(retirementId){assertManagedSessionStableId(retirementId,"retirementId");const readStatus=__name((value,previous)=>{const status2=asRecord(value,"CSI retirement status");const stage=status2["stage"];if(Object.keys(status2).sort().join(",")!=="cutSha256,finalizeReceiptSha256,format,frozenRequestSha256,progressVersion,retirementId,stage"||status2["format"]!=="qwen-csi-application-retirement/1"||status2["retirementId"]!==retirementId||!["SETTLING","FROZEN","CUT","DRAINED"].includes(String(stage))){throw corrupt2("original CSI retirement status conflicts.")}const progressVersion=safeCounter(status2["progressVersion"],"progressVersion");const frozenRequestSha256=nullableDigest(status2["frozenRequestSha256"],"frozenRequestSha256");const cutSha256=nullableDigest(status2["cutSha256"],"cutSha256");const finalizeReceiptSha256=nullableDigest(status2["finalizeReceiptSha256"],"finalizeReceiptSha256");if(progressVersion!==["SETTLING","FROZEN","CUT","DRAINED"].indexOf(String(stage))+1||stage==="SETTLING"!==(frozenRequestSha256===null)||["SETTLING","FROZEN"].includes(String(stage))!==(cutSha256===null)||stage==="DRAINED"!==(finalizeReceiptSha256!==null)){throw corrupt2("original CSI retirement progress is incomplete.")}if(previous&&(progressVersion<previous.progressVersion||previous.frozenRequestSha256!==null&&frozenRequestSha256!==previous.frozenRequestSha256||previous.cutSha256!==null&&cutSha256!==previous.cutSha256)){throw corrupt2("original CSI retirement status changed its saved progress.")}return{format:"qwen-csi-application-retirement/1",retirementId,stage,progressVersion,frozenRequestSha256,cutSha256,finalizeReceiptSha256}},"readStatus");let status=readStatus(await this.json(`/csi-retirement?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}&retirementId=${encodeURIComponent(retirementId)}`,"GET"));const identity={format:"qwen-csi-application-retirement/1",workspaceId:this.sessionKey.workspaceId,retirementId};if(status.stage==="SETTLING"){if(!this.preparedRetirement)throw corrupt2("original CSI retirement has no prepared body.");status=readStatus(await this.json("/csi-retirement:freeze","POST",{...identity,commitBodyBase64:this.preparedRetirement.commitBodyBase64}),status);if(status.stage==="SETTLING")throw corrupt2("original CSI retirement did not freeze.")}if(status.stage==="FROZEN"){status=readStatus(await this.json("/csi-retirement:cut","POST",{...identity,frozenRequestSha256:status.frozenRequestSha256}),status);if(status.stage!=="CUT"&&status.stage!=="DRAINED")throw corrupt2("original CSI retirement did not commit its cut.")}if(status.stage==="CUT"){status=readStatus(await this.json("/csi-retirement:finalize","POST",{...identity,cutSha256:status.cutSha256}),status)}if(status.stage!=="DRAINED")throw corrupt2("original CSI retirement has not drained.");return status}async publicationOwner(){await this.ensureWriter();return{writerId:this.writerId,writerGeneration:this.requireGrant().writerGeneration}}rememberAdmission(publicationId,ref2){assertManagedSessionStableId(publicationId,"publicationId");const checked=assertManagedSessionDurableRef(ref2,"admission ref");if(checked.kind!=="managed-tool-outcome")throw new ManagedSessionRecordError("Publication admission kind is invalid.");const previous=this.publicationAdmissions.get(checked.resourceId);if(previous!==void 0&&previous!==publicationId)throw new ManagedSessionRecordError("Publication admission conflicts.");this.publicationAdmissions.set(checked.resourceId,publicationId)}async publicationRequest(path,body,token,contentionDeadline){await this.ensureWriter();if(!/^\/(?:grants|receipts\/verify|publications\/[a-z0-9_-]{1,128}\/(?:finished|admissions\/prepare|receipts\/commit))$/u.test(path))throw new ManagedSessionRecordError("Publication owner path is invalid.");const readOnly=path.endsWith("/finished");const method=readOnly?"GET":"POST";return this.withRetry(readOnly,method,path,async timeoutMs=>{const url=`${this.baseUrl}/internal/managed-tool-publications/v1/sessions/${encodeURIComponent(this.sessionKey.sessionId)}${path}?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}`;const response=await this.fetchFn(url,{method,headers:{Accept:"application/json","X-Qwen-Managed-Max-Readable-Storage-Version":"2",...readOnly?{}:{"Content-Type":"application/json"},[HTTP_MANAGED_SESSION_STORE_CONTRACT.tenantHeader]:this.sessionKey.tenantId,[HTTP_MANAGED_SESSION_STORE_CONTRACT.writerTokenHeader]:this.writerToken,"X-Qwen-Managed-Writer-Id":this.writerId,"X-Qwen-Managed-Writer-Generation":String(this.requireGrant().writerGeneration),...token?{"X-Qwen-Tool-Publication-Token":token}:{}},...readOnly?{}:{body:JSON.stringify(body)},redirect:"error",signal:AbortSignal.timeout(timeoutMs)});if(!response.ok){const error=await readHttpError(response);throw new ManagedSessionStoreHttpError(response.status,error.code,error.message,void 0,error.details,`${method} ${path}`)}if(response.headers.get("Cache-Control")!=="no-store")throw corrupt2("Publication response is missing Cache-Control: no-store.");return readBoundedPublicationJson(response)},contentionDeadline)}async readResource(ref2){await this.ensureWriter();const path=`/resources/${encodeURIComponent(ref2.resourceId)}?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}`;return this.withRetry(true,"GET",path,async timeoutMs=>{const response=await this.request(path,"GET",void 0,timeoutMs,"application/octet-stream, application/json");if(!response.body)throw corrupt2("resource response has no body.");const reader=response.body.getReader();const chunks=[];let length=0;try{while(true){let chunk;try{chunk=await reader.read()}catch(error){if(error instanceof TypeError||error instanceof DOMException){throw new ManagedSessionStoreTransportError(`Managed Session Store response failed: ${error.message}.`)}throw error}if(chunk.done)break;length+=chunk.value.byteLength;if(length>ref2.byteLength){await reader.cancel();throw corrupt2("resource response exceeds its declared length.")}chunks.push(chunk.value)}}finally{reader.releaseLock()}const bytes=Buffer.concat(chunks);if(response.headers.get("X-Qwen-Resource-Kind")!==ref2.kind||response.headers.get("X-Qwen-Resource-Schema-Version")!==String(ref2.schemaVersion)||response.headers.get("X-Qwen-Resource-Digest")!==ref2.digest||bytes.byteLength!==ref2.byteLength||sha256(bytes)!==ref2.digest){throw corrupt2(`resource ${ref2.resourceId} failed integrity verification.`)}return bytes})}async assertWritable(){await this.renewWriter()}async publishToolResult(kind,source,resourceId=randomUUID()){const limit=HOSTED_TOOL_RESULT_RESOURCE_LIMITS[kind];if(!Object.hasOwn(HOSTED_TOOL_RESULT_RESOURCE_LIMITS,kind)||source.byteLength<1||source.byteLength>limit){throw new ManagedSessionRecordError("Unsupported tool result resource or size.")}assertManagedSessionStableId(resourceId,"tool result resourceId");const bytes=Buffer.from(source);const ref2={resourceId,kind,schemaVersion:1,byteLength:bytes.length,digest:sha256(bytes)};await this.ensureWriter();const grant=this.requireGrant();const receipt=assertManagedSessionDurableRef(await this.json("/tool-results:publish","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,...ref2,bytesBase64:bytes.toString("base64")}),"tool result publication");requireSameRef(receipt,ref2);return ref2}async blockRecovery(request){await this.ensureWriter();const grant=this.requireGrant();const receipt=asRecord(await this.json("/recovery:block","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,recoveryStatus:request.status,recoveryDetailCode:request.detailCode}),"recovery state receipt");if(safeCounter(receipt["writerGeneration"],"writerGeneration")!==grant.writerGeneration||string(receipt["recoveryStatus"],"recoveryStatus")!==request.status||string(receipt["recoveryDetailCode"],"recoveryDetailCode")!==request.detailCode){throw corrupt2("recovery state receipt does not match the active writer request.")}}async seal(){if(this.retirementJoin)throw corrupt2("original CSI retirement owns the final boundary.");await this.acquirePromise?.catch(()=>void 0);return this.sealGrant()}async sealGrant(){if(this.sealed)return;const grant=this.grant;this.stopWriterRenewal();if(grant===void 0){this.sealed=true;this.resources.clear();return}const receipt=asRecord(await this.json("/writers:seal","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration}),"seal receipt");if(safeCounter(receipt["writerGeneration"],"writerGeneration")!==grant.writerGeneration||string(receipt["state"],"state")!=="SEALED"){throw corrupt2("seal receipt does not match the active writer.")}this.sealed=true;this.stopRenewal();this.resources.clear()}async stopLocal(){this.locallyStopped=true;this.stopRenewal();await this.renewPromise?.catch(()=>void 0);await this.acquirePromise?.catch(()=>void 0)}async releaseOwnership(request){assertManagedSessionStableId(request.operationId,"release operationId");assertManagedSessionStableId(request.instanceId,"release instanceId");if(request.bootId!==this.writerId||!Number.isSafeInteger(request.placementEpoch)||request.placementEpoch<1)throw corrupt2("ownership release does not match the writer.");if(!this.ownershipRelease){const grant=this.requireGrant();if(request.commitProof.lastCommitSequence!==grant.committedSequence||request.commitProof.committedPrefixHash!==grant.lastCommitDigest)throw corrupt2("ownership release does not match the committed head.");this.stopWriterRenewal();this.ownershipRelease={request:{...request,commitProof:{...request.commitProof}},body:{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,journalRevision:grant.journalRevision,...request,commitProof:{...request.commitProof}}}}const release=this.ownershipRelease;if(request.operationId!==release.request.operationId||request.instanceId!==release.request.instanceId||request.bootId!==release.request.bootId||request.placementEpoch!==release.request.placementEpoch||request.commitProof.lastCommitSequence!==release.request.commitProof.lastCommitSequence||request.commitProof.committedPrefixHash!==release.request.commitProof.committedPrefixHash)throw corrupt2("ownership release identity changed.");if(release.receipt)return release.receipt;await this.renewPromise?.catch(()=>void 0);const value=asRecord(await this.json("/writers:release-ownership","POST",release.body),"ownership release receipt");const proof=asRecord(value["commitProof"],"release commit proof");const receipt={format:"qwen-hosted-harness-release/1",state:"RELEASED",tenantId:string(value["tenantId"],"tenantId"),workspaceId:string(value["workspaceId"],"workspaceId"),sessionId:string(value["sessionId"],"sessionId"),operationId:string(value["operationId"],"operationId"),instanceId:string(value["instanceId"],"instanceId"),bootId:string(value["bootId"],"bootId"),placementEpoch:safeCounter(value["placementEpoch"],"placementEpoch"),writerGeneration:safeCounter(value["writerGeneration"],"writerGeneration"),journalRevision:safeCounter(value["journalRevision"],"journalRevision"),committedSequence:safeCounter(value["committedSequence"],"committedSequence"),commitProof:{lastCommitSequence:safeCounter(proof["lastCommitSequence"],"lastCommitSequence"),committedPrefixHash:digest2(proof["committedPrefixHash"],"committedPrefixHash")}};if(value["format"]!==receipt.format||value["state"]!==receipt.state||!managedSessionKeysEqual(receipt,this.sessionKey)||receipt.operationId!==request.operationId||receipt.instanceId!==request.instanceId||receipt.bootId!==request.bootId||receipt.placementEpoch!==request.placementEpoch||receipt.writerGeneration!==release.body["writerGeneration"]||receipt.journalRevision!==release.body["journalRevision"]||receipt.committedSequence!==request.commitProof.lastCommitSequence||receipt.commitProof.lastCommitSequence!==request.commitProof.lastCommitSequence||receipt.commitProof.committedPrefixHash!==request.commitProof.committedPrefixHash)throw corrupt2("ownership release receipt does not match the request.");release.receipt=receipt;this.sealed=true;this.resources.clear();return receipt}async quiesceOwnership(placement){const grant=this.requireGrant();const response=asRecord(await this.json("/writers:quiesce-ownership","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,...placement}),"ownership quiesce receipt");if(response["state"]!=="QUIESCING")throw corrupt2("ownership quiesce was not acknowledged.")}stopWriterRenewal(){this.renewalStopped=true;this.stopRenewal()}async ensureWriter(){if(this.ownershipRelease)throw corrupt2("ownership release has fenced this writer.");if(this.retirementJoin)throw corrupt2("original CSI writer admission is closed.");if(this.acquirePromise!==void 0)await this.acquirePromise.catch(()=>void 0);const grant=this.requireGrant();if(grant.leaseUntil-Date.now()<=this.leaseDurationMs/3){await this.renewWriter()}}async reacquireWriter(){const expired=this.grant;this.stopRenewal();await this.renewPromise?.catch(()=>void 0);this.grant=void 0;const acquire=(async()=>{await this.acquireWriter();if(this.sealed||this.locallyStopped)await this.sealGrant()})();this.acquirePromise=acquire;try{await acquire}catch(error){this.grant=expired;throw error}finally{if(this.acquirePromise===acquire)this.acquirePromise=void 0}}renewWriter(){if(this.ownershipRelease)return Promise.reject(corrupt2("ownership release has fenced this writer."));if(this.retirementJoin)return Promise.reject(corrupt2("original CSI writer renewal is closed."));if(this.locallyStopped){return Promise.reject(new ManagedSessionRecordError("the HTTP Managed Session writer is locally stopped."))}if(this.renewPromise!==void 0){if(this.lifecycleAuthority?.operationId===this.renewingAuthority?.operationId&&this.lifecycleAuthority?.claimGeneration===this.renewingAuthority?.claimGeneration)return this.renewPromise;const renewAgain=__name(()=>this.renewWriter(),"renewAgain");return this.renewPromise.then(renewAgain,renewAgain)}const grant=this.requireGrant();this.renewingAuthority=this.lifecycleAuthority?{...this.lifecycleAuthority}:void 0;const renewal=(async()=>{const renewed=parseWriterGrant(await this.json("/writers:renew","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,leaseMillis:this.leaseDurationMs}));if(renewed.writerGeneration!==grant.writerGeneration){throw corrupt2("writer generation changed during renewal.")}this.grant={...this.requireGrant(),leaseUntil:renewed.leaseUntil,supportedStorageVersion:renewed.supportedStorageVersion};this.scheduleRenewal()})();const noted=renewal.catch(async error=>{this.writerRenewalFailures.push(error);await this.annotateWriterRefusal(error);throw error});this.renewPromise=noted.finally(()=>{this.renewPromise=void 0});return this.renewPromise}async annotateWriterRefusal(error){if(!(error instanceof ManagedSessionStoreHttpError)||error.status!==409)return;const grant=this.grant;const grantView=grant===void 0?"grant=absent":`grantGeneration=${grant.writerGeneration} grantRevision=${grant.journalRevision} grantCommitted=${grant.committedSequence}`;let headView;try{const head=parseRestoreHead(await this.json(`/restore?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}`,"GET"));headView=`headGeneration=${head.writerGeneration} headRevision=${head.journalRevision} headCommitted=${head.committedSequence} state=${head.state}`}catch(probe){headView=`headProbeFailed(${probe instanceof Error?probe.message:String(probe)})`}const detail=`writerId=${this.writerId} ${grantView} ${headView}`;error.writerRefusalContext=detail;debugLogger.debug(`Managed Session Store writer refused: session=${this.sessionKey.sessionId} ${detail}`)}scheduleRenewal(retrying=false){this.stopRenewal();if(this.renewalStopped||this.sealed||this.locallyStopped||this.retirementJoin||this.grant===void 0||this.grant.leaseUntil<=Date.now())return;const delay=Math.max(250,Math.min(retrying?1e3:Math.floor(this.leaseDurationMs/2),this.grant.leaseUntil-Date.now()-500));this.renewTimer=setTimeout(()=>{void this.renewWriter().catch(error=>{if(error instanceof ManagedSessionStoreTransportError||error instanceof ManagedSessionStoreHttpError&&[500,502,503,504].includes(error.status)){this.scheduleRenewal(true)}})},delay);this.renewTimer.unref()}stopRenewal(){if(this.renewTimer!==void 0)clearTimeout(this.renewTimer);this.renewTimer=void 0}requireHeadMatchesGrant(head){const grant=this.requireGrant();if(head.state!=="ACTIVE"||![1,2].includes(head.storageVersion)||head.writerGeneration!==grant.writerGeneration||head.recoveryStatus!=="READY"||head.compactedThroughRevision!==0){throw corrupt2("restore head is not readable by this writer.")}if(head.journalRevision<grant.journalRevision||head.committedSequence<grant.committedSequence){throw corrupt2(`restore head regressed below this writer's committed position (head ${head.journalRevision}/${head.committedSequence} < grant ${grant.journalRevision}/${grant.committedSequence}).`)}}requireGrant(){if(this.grant===void 0||this.sealed||this.locallyStopped){throw new ManagedSessionRecordError("the HTTP Managed Session writer is not active.")}return this.grant}async json(path,method,body,contentionDeadline){return this.withRetry(method==="GET"||path==="/writers:renew",method,path,async timeoutMs=>{const response=await this.request(path,method,body,timeoutMs);try{return await response.json()}catch(error){if(error instanceof TypeError||error instanceof DOMException&&["AbortError","TimeoutError"].includes(error.name)){throw new ManagedSessionStoreTransportError(`Managed Session Store response failed: ${error.message}.`)}throw corrupt2(`Managed Session Store returned invalid JSON: ${error instanceof Error?error.message:String(error)}.`)}},contentionDeadline)}async withRetry(retryable,method,path,run,contentionDeadline){const deadline=Date.now()+this.requestTimeoutMs;const guardDeadline=Math.min(deadline,contentionDeadline??deadline);let attempt=0;let guardRetries=0;let contendedRefusal;for(;;){attempt++;try{const attemptDeadline=guardRetries>0?guardDeadline:deadline;return await run(Math.max(1,attemptDeadline-Date.now()))}catch(error){const contended=error instanceof ManagedSessionStoreHttpError&&error.status===503&&error.remoteCode==="tenant_guard_contended";if(contended)contendedRefusal=error;if(contended&&guardDeadline-Date.now()>250){debugLogger.debug(`Managed Session Store ${method} ${path} attempt ${attempt} found the tenant guard contended; retrying.`);guardRetries++;await new Promise(resolve=>setTimeout(resolve,250));continue}const transient=error instanceof ManagedSessionStoreTransportError||error instanceof ManagedSessionStoreHttpError&&[500,502,503,504].includes(error.status);if(!retryable||!transient||contended||attempt-guardRetries>=3||Date.now()>=deadline){if(contendedRefusal!==void 0&&guardDeadline-Date.now()<=250){throw new ManagedSessionStoreHttpError(contendedRefusal.status,contendedRefusal.remoteCode,attempt>1?`Managed Session Store ${method} ${path} failed after ${attempt} attempts: ${contendedRefusal.message}`:`Managed Session Store ${method} ${path} failed: ${contendedRefusal.message}`,guardRetries>0||void 0,contendedRefusal.details,contendedRefusal.route)}if(transient){const detail=attempt>1?`Managed Session Store ${method} ${path} failed after ${attempt} attempts: ${error instanceof Error?error.message:String(error)}`:`Managed Session Store ${method} ${path} failed: ${error instanceof Error?error.message:String(error)}`;if(error instanceof ManagedSessionStoreHttpError)throw new ManagedSessionStoreHttpError(error.status,error.remoteCode,detail,void 0,error.details,error.route);if(error instanceof ManagedSessionStoreTransportError)throw new ManagedSessionStoreTransportError(detail)}throw error}debugLogger.debug(`Managed Session Store ${method} ${path} attempt ${attempt} failed (${error instanceof Error?error.message:String(error)}); retrying.`);await new Promise(resolve=>setTimeout(resolve,200*(attempt-guardRetries)+Math.floor(Math.random()*100)))}}}async request(path,method,body,timeoutMs=this.requestTimeoutMs,accept="application/json"){if(this.ownershipRelease&&path!=="/writers:release-ownership")throw corrupt2("ownership release has fenced this writer.");if(this.locallyStopped){throw new ManagedSessionRecordError("the HTTP Managed Session writer is locally stopped.")}let response;try{response=await this.fetchFn(`${this.sessionUrl()}${path}`,{method,redirect:"error",headers:{Accept:accept,"X-Qwen-Managed-Max-Readable-Storage-Version":"2",[HTTP_MANAGED_SESSION_STORE_CONTRACT.tenantHeader]:this.sessionKey.tenantId,[HTTP_MANAGED_SESSION_STORE_CONTRACT.writerTokenHeader]:this.writerToken,...this.lifecycleAuthority?{"X-Qwen-Lifecycle-Operation-Id":this.lifecycleAuthority.operationId,"X-Qwen-Lifecycle-Claim-Generation":String(this.lifecycleAuthority.claimGeneration)}:{},...body===void 0?{}:{"Content-Type":"application/json"}},...body===void 0?{}:{body:JSON.stringify(body)},signal:AbortSignal.timeout(timeoutMs)})}catch(error){throw new ManagedSessionStoreTransportError(`Managed Session Store request failed: ${error instanceof Error?error.message:String(error)}.`)}if(!response.ok){const error=await readHttpError(response);throw new ManagedSessionStoreHttpError(response.status,error.code,error.message,void 0,error.details,`${method} ${path}`)}if(response.headers.get("Cache-Control")!=="no-store"){throw corrupt2("Managed Session Store response is missing Cache-Control: no-store.")}return response}sessionUrl(){return`${this.baseUrl}/internal/managed-session-store/v1/sessions/${encodeURIComponent(this.sessionKey.sessionId)}`}};function describeTransaction(records,bytes,currentActivationEpoch,expectedSessionKey){const possibleHeader=records.length===2?envelope(records[1],"possible genesis header record"):void 0;if(possibleHeader?.["subtype"]===MANAGED_SESSION_HEADER_SUBTYPE){const first=envelope(records[0],"genesis engine record");if(first["subtype"]!=="session_execution_engine"){throw new ManagedSessionRecordError("the genesis transaction must contain the engine and Managed header.")}const header=parseManagedSessionHeader(possibleHeader["managedSession"]);if(!managedSessionKeysEqual(header.sessionKey,expectedSessionKey)||first["sessionId"]!==expectedSessionKey.sessionId||possibleHeader["sessionId"]!==expectedSessionKey.sessionId){throw new ManagedSessionRecordError("the genesis transaction belongs to a different session.")}const digest3=sha256(bytes);return{transactionId:`session.create:${header.sessionKey.sessionId}`,operation:"session.create",commandId:`session.create:${header.sessionKey.sessionId}`,contentDigest:digest3,firstSequence:0,lastSequence:0,eventCount:0,eventsDigest:null,previousCommitDigest:null,commitDigest:null,activationEpoch:currentActivationEpoch,latestCheckpointResourceId:null,refs:dedupeRefs([header.definitionRef,header.rootSnapshotRef,...header.baseTranscriptProof===void 0?[]:[header.baseTranscriptProof]])}}if(records.length<2){throw new ManagedSessionRecordError("a Managed Session transaction must include events and a commit marker.")}const eventRecords=records.slice(0,-1).map((record,index)=>{const parsed=envelope(record,`event record ${index+1}`);if(parsed["subtype"]!==MANAGED_SESSION_EVENT_SUBTYPE){throw new ManagedSessionRecordError("a Managed Session transaction contains a non-event record.")}const event=parseManagedSessionEvent(parsed["managedSession"]);if(!managedSessionKeysEqual(event.sessionKey,expectedSessionKey)||parsed["sessionId"]!==expectedSessionKey.sessionId){throw new ManagedSessionRecordError("the event transaction belongs to a different session.")}return event});const markerRecord=envelope(records[records.length-1],"commit record");if(markerRecord["subtype"]!==MANAGED_SESSION_COMMIT_SUBTYPE){throw new ManagedSessionRecordError("a Managed Session transaction must end with a commit marker.")}if(markerRecord["sessionId"]!==expectedSessionKey.sessionId){throw new ManagedSessionRecordError("the commit marker belongs to a different session.")}const marker=parseManagedSessionCommitMarker(markerRecord["managedSession"]);let activationEpoch=currentActivationEpoch;let latestCheckpointResourceId=null;for(const event of eventRecords){if(event.kind==="activation.changed"){activationEpoch=event.payload["epoch"]}if(event.kind==="checkpoint.committed"){const ref2=assertManagedSessionDurableRef(event.payload["stateRef"],"checkpoint state");if(ref2.kind==="managed-checkpoint"){latestCheckpointResourceId=ref2.resourceId}}}return{transactionId:marker.transactionId,operation:marker.operation,commandId:marker.commandId,contentDigest:marker.contentDigest,firstSequence:marker.firstSequence,lastSequence:marker.lastSequence,eventCount:marker.eventCount,eventsDigest:marker.eventsDigest,previousCommitDigest:marker.previousCommitDigest,commitDigest:managedToolDigest(marker,MANAGED_SESSION_LIMITS.maxCommitMarkerBytes),activationEpoch,latestCheckpointResourceId,refs:dedupeRefs(eventRecords.flatMap(event=>managedSessionEventRefs(event)))}}__name(describeTransaction,"describeTransaction");function dedupeRefs(found){const refs=new Map;for(const ref2 of found){const existing=refs.get(ref2.resourceId);if(existing!==void 0)requireSameRef(existing,ref2);else refs.set(ref2.resourceId,ref2)}return[...refs.values()]}__name(dedupeRefs,"dedupeRefs");function collectRefs(records){const refs=new Map;const pending=[...records];while(pending.length>0){const value=pending.pop();if(Array.isArray(value)){pending.push(...value);continue}if(value===null||typeof value!=="object")continue;const record=value;if(Object.hasOwn(record,"resourceId")&&Object.hasOwn(record,"kind")&&Object.hasOwn(record,"schemaVersion")&&Object.hasOwn(record,"byteLength")&&Object.hasOwn(record,"digest")){const ref2=assertManagedSessionDurableRef(record,"resource ref");const existing=refs.get(ref2.resourceId);if(existing!==void 0)requireSameRef(existing,ref2);else refs.set(ref2.resourceId,ref2);continue}pending.push(...Object.values(record))}return[...refs.values()]}__name(collectRefs,"collectRefs");function encodeRecords(records){if(records.length<1){throw new ManagedSessionRecordError("a Managed Session transaction must contain records.")}const bytes=Buffer.from(records.map(record=>JSON.stringify(record)).join("\n")+"\n","utf8");if(bytes.byteLength>MANAGED_SESSION_LIMITS.maxTransactionBytes){throw new ManagedSessionRecordError(`transaction exceeds ${MANAGED_SESSION_LIMITS.maxTransactionBytes} bytes.`)}return bytes}__name(encodeRecords,"encodeRecords");function decodeRecords(bytes){const text=bytes.toString("utf8");if(!text.endsWith("\n"))throw corrupt2("transaction is not complete JSONL.");return text.slice(0,-1).split("\n").map(line=>parseManagedSessionRecordJson(line,MANAGED_SESSION_LIMITS.maxEventBytes))}__name(decodeRecords,"decodeRecords");function envelope(value,label){const parsed=parseManagedSessionRecordJson(JSON.stringify(value),MANAGED_SESSION_LIMITS.maxEventBytes);return asRecord(parsed,label)}__name(envelope,"envelope");function parseStoredTransaction(value){const record=asRecord(value,"stored transaction");if(string(record["recordEncoding"],"recordEncoding")!=="identity"){throw corrupt2("stored transaction encoding is not supported.")}return{journalRevision:safeCounter(record["journalRevision"],"journalRevision"),transactionId:string(record["transactionId"],"transactionId"),operation:string(record["operation"],"operation"),commandId:string(record["commandId"],"commandId"),contentDigest:digest2(record["contentDigest"],"contentDigest"),firstSequence:safeCounter(record["firstSequence"],"firstSequence"),lastSequence:safeCounter(record["lastSequence"],"lastSequence"),eventCount:safeCounter(record["eventCount"],"eventCount"),eventsDigest:nullableDigest(record["eventsDigest"],"eventsDigest"),previousCommitDigest:nullableDigest(record["previousCommitDigest"],"previousCommitDigest"),commitDigest:nullableDigest(record["commitDigest"],"commitDigest"),activationEpoch:safeCounter(record["activationEpoch"],"activationEpoch"),latestCheckpointResourceId:nullableString(record["latestCheckpointResourceId"],"latestCheckpointResourceId"),recordBytesBase64:string(record["recordBytesBase64"],"recordBytesBase64"),byteLength:safeCounter(record["byteLength"],"byteLength"),recordDigest:digest2(record["recordDigest"],"recordDigest")}}__name(parseStoredTransaction,"parseStoredTransaction");function requireStoredTransactionMatches(stored,descriptor){if(stored.transactionId!==descriptor.transactionId||stored.operation!==descriptor.operation||stored.commandId!==descriptor.commandId||stored.contentDigest!==descriptor.contentDigest||stored.firstSequence!==descriptor.firstSequence||stored.lastSequence!==descriptor.lastSequence||stored.eventCount!==descriptor.eventCount||stored.eventsDigest!==descriptor.eventsDigest||stored.previousCommitDigest!==descriptor.previousCommitDigest||stored.commitDigest!==descriptor.commitDigest||stored.activationEpoch!==descriptor.activationEpoch||stored.latestCheckpointResourceId!==descriptor.latestCheckpointResourceId){throw corrupt2("stored transaction metadata does not match its records.")}}__name(requireStoredTransactionMatches,"requireStoredTransactionMatches");function parseWriterGrant(value){const record=asRecord(value,"writer grant");return{activationLeaseRenewal:record["activationLeaseRenewal"]===true,...record["activationLease"]==null?{}:{activationLease:parseActivationLease(record["activationLease"])},supportedStorageVersion:record["supportedStorageVersion"]===void 0?1:safeCounter(record["supportedStorageVersion"],"supportedStorageVersion"),writerGeneration:safeCounter(record["writerGeneration"],"writerGeneration"),leaseUntil:safeCounter(record["leaseUntil"],"leaseUntil"),journalRevision:safeCounter(record["journalRevision"],"journalRevision"),committedSequence:safeCounter(record["committedSequence"],"committedSequence"),lastCommitDigest:nullableDigest(record["lastCommitDigest"],"lastCommitDigest"),activationEpoch:safeCounter(record["activationEpoch"],"activationEpoch")}}__name(parseWriterGrant,"parseWriterGrant");function parseRestoreHead(value){const record=asRecord(value,"restore head");return{...record["activationLease"]==null?{}:{activationLease:parseActivationLease(record["activationLease"])},state:string(record["state"],"state"),storageVersion:safeCounter(record["storageVersion"],"storageVersion"),writerGeneration:safeCounter(record["writerGeneration"],"writerGeneration"),journalRevision:safeCounter(record["journalRevision"],"journalRevision"),committedSequence:safeCounter(record["committedSequence"],"committedSequence"),lastCommitDigest:nullableDigest(record["lastCommitDigest"],"lastCommitDigest"),activationEpoch:safeCounter(record["activationEpoch"],"activationEpoch"),latestCheckpointResourceId:nullableString(record["latestCheckpointResourceId"],"latestCheckpointResourceId"),compactedThroughRevision:safeCounter(record["compactedThroughRevision"],"compactedThroughRevision"),recoveryStatus:string(record["recoveryStatus"],"recoveryStatus"),recoveryDetailCode:nullableString(record["recoveryDetailCode"],"recoveryDetailCode")}}__name(parseRestoreHead,"parseRestoreHead");function parseActivationLease(value){const lease=asRecord(value,"activation lease");return{activationId:assertManagedSessionStableId(string(lease["activationId"],"activationId"),"activationId"),epoch:safeCounter(lease["epoch"],"activation epoch"),renewalSeq:safeCounter(lease["renewalSeq"],"activation renewalSeq"),expiresAt:safeCounter(lease["expiresAt"],"activation expiresAt")}}__name(parseActivationLease,"parseActivationLease");function applyActivationLease(scan,lease){if(!lease)return scan;const activation=scan.activation;if(!activation||activation.phase!=="active"||activation.activationId!==lease.activationId||activation.epoch!==lease.epoch||lease.renewalSeq<activation.renewalSeq||lease.expiresAt<activation.expiresAt)throw corrupt2("activation lease conflicts with the journal.");return{...scan,activation:{...activation,...lease}}}__name(applyActivationLease,"applyActivationLease");function collectNestedResourceRefs(ref2,bytes){if(ref2.kind===MANAGED_MESSAGE_CHUNKS_KIND){return managedMessageChunkParts(ref2.kind,bytes)}if(ref2.kind==="managed-tool-outcome-chunks"){const manifest=asRecord(JSON.parse(bytes.toString("utf8")),"outcome chunks");if(Object.keys(manifest).length!==1||!("parts"in manifest)){throw corrupt2("outcome chunk manifest fields conflict.")}const parts=asArray(manifest["parts"],"outcome parts");if(parts.length<2||parts.length>69){throw corrupt2("outcome chunk count exceeds its bounds.")}return parts.map(part=>{const checked=assertManagedSessionDurableRef(part,"outcome chunk part");if(checked.kind!=="managed-tool-outcome-part"){throw corrupt2("outcome chunks must reference outcome parts.")}return checked})}if(ref2.kind===CHECKPOINT_HISTORY_KIND)return collectRefs([checkpointHistoryPage(bytes)]);if(ref2.kind==="managed-checkpoint"){if(isPagedHarnessCheckpoint(bytes))return collectRefs([checkpointStorageBody(bytes)]);const parsed=tryParseHarnessCheckpointV1(bytes);return parsed.ok?collectRefs([parsed.checkpoint]):[]}if(ref2.kind==="managed-file_history"){const record=asRecord(parseManagedSessionRecordJson(bytes.toString("utf8"),MANAGED_SESSION_LIMITS.maxEventBytes),"file history");return record["schemaVersion"]===2&&record["profile"]==="csi-files-retirement/1"?collectRefs([record["preparation"]]):[]}if(HOSTED_RECOVERY_RESOURCE_KINDS.has(ref2.kind)){return hostedRecoveryReferences(parseHostedRecoveryResource(bytes,void 0,ref2.kind))}if(EXTENSION_RECORD_KINDS.has(ref2.kind)||ref2.kind==="managed-definition"||ref2.kind==="managed-action-options"||ref2.kind==="managed-hook-plan"||ref2.kind==="managed-hook-message-chunks"){const record=parseManagedSessionRecordJson(bytes.toString("utf8"),MANAGED_SESSION_LIMITS.maxEventBytes);if(ref2.kind==="managed-hook-plan")return collectRefs([record.messagesRef]);if(ref2.kind==="managed-hook-message-chunks")return collectRefs(record.parts);return collectRefs([record])}if(ref2.kind===MANAGED_TOOL_RESULT_KINDS.manifest){try{return collectRefs([parseToolResultManifestBytes(bytes)])}catch{return[]}}if(ref2.kind==="managed-input"){try{return collectRefs([parseManagedSessionRecordJson(bytes.toString("utf8"),MANAGED_SESSION_LIMITS.maxEventBytes)])}catch{return[]}}return[]}__name(collectNestedResourceRefs,"collectNestedResourceRefs");function isReferenceContainer(kind){return EXTENSION_RECORD_KINDS.has(kind)||HOSTED_RECOVERY_RESOURCE_KINDS.has(kind)||["managed-definition","managed-checkpoint",CHECKPOINT_HISTORY_KIND,"managed-file_history","managed-action-options","managed-hook-plan","managed-hook-message-chunks",MANAGED_MESSAGE_CHUNKS_KIND,"managed-tool-outcome-chunks"].includes(kind)}__name(isReferenceContainer,"isReferenceContainer");function requireSameRef(left,right){if(left.resourceId!==right.resourceId||left.kind!==right.kind||left.schemaVersion!==right.schemaVersion||left.byteLength!==right.byteLength||left.digest!==right.digest){throw new ManagedSessionRecordError(`resource ${right.resourceId} was reused with different metadata.`)}}__name(requireSameRef,"requireSameRef");async function readHttpError(response){try{const body=asRecord(await response.json(),"error response");const error=asRecord(body["error"],"error");const details={};for(const[key,value]of Object.entries(error))if(key!=="code"&&key!=="message"&&(typeof value==="string"||typeof value==="number"||typeof value==="boolean"))details[key]=value;return{code:string(error["code"],"error.code"),message:string(error["message"],"error.message"),...Object.keys(details).length>0?{details}:{}}}catch{return{code:"managed_session_store_http_error",message:`Managed Session Store returned HTTP ${response.status}.`}}}__name(readHttpError,"readHttpError");async function readBoundedPublicationJson(response){const reader=response.body?.getReader();if(!reader)throw corrupt2("Publication response has no body.");const chunks=[];let length=0;try{while(true){const item=await reader.read();if(item.done)break;length+=item.value.byteLength;if(length>4*1024*1024)throw corrupt2("Publication response exceeds its byte limit.");chunks.push(item.value)}}finally{reader.releaseLock()}return JSON.parse(Buffer.concat(chunks).toString("utf8"))}__name(readBoundedPublicationJson,"readBoundedPublicationJson");function asRecord(value,label){if(value===null||typeof value!=="object"||Array.isArray(value)){throw corrupt2(`${label} must be an object.`)}return value}__name(asRecord,"asRecord");function asArray(value,label){if(!Array.isArray(value))throw corrupt2(`${label} must be an array.`);return value}__name(asArray,"asArray");function string(value,label){if(typeof value!=="string"||value.length===0){throw corrupt2(`${label} must be a non-empty string.`)}return value}__name(string,"string");function nullableString(value,label){return value===null||value===void 0?null:string(value,label)}__name(nullableString,"nullableString");function boolean(value,label){if(typeof value!=="boolean")throw corrupt2(`${label} must be boolean.`);return value}__name(boolean,"boolean");function safeCounter(value,label){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0){throw corrupt2(`${label} must be a non-negative safe integer.`)}return value}__name(safeCounter,"safeCounter");function digest2(value,label){const result=string(value,label);if(!/^[0-9a-f]{64}$/.test(result)){throw corrupt2(`${label} must be a lowercase SHA-256 digest.`)}return result}__name(digest2,"digest");function nullableDigest(value,label){return value===null||value===void 0?null:digest2(value,label)}__name(nullableDigest,"nullableDigest");function decodeBase64(value,label){if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)){throw corrupt2(`${label} must be canonical Base64.`)}return Buffer.from(value,"base64")}__name(decodeBase64,"decodeBase64");function sha256(value){return createHash2("sha256").update(value).digest("hex")}__name(sha256,"sha256");function corrupt2(message){return new ManagedSessionRecordError(`Managed Session Store: ${message}`)}__name(corrupt2,"corrupt");init_esbuild_shims();import{createHash as createHash3}from"node:crypto";var HOSTED_SKILL_CATALOG_MAX_BYTES=2*1024*1024;var HOSTED_SKILL_APPROVAL_REFUSAL="Hosted Skill loading cannot request approval; the PreToolUse Hook must allow or deny this instruction-only call.";var HOSTED_SKILL_BATCH_REFUSAL="Load Skills in a separate tool batch before calling Workspace tools.";function parseSessionSkillsRef(value){if(value===void 0)return void 0;const ref2=assertManagedSessionDurableRef(value,"Session Skills");if(ref2.kind!=="managed-agent-skills"||ref2.schemaVersion!==1||ref2.byteLength>HOSTED_SKILL_CATALOG_MAX_BYTES)throw new Error("Invalid Session Skills reference.");return ref2}__name(parseSessionSkillsRef,"parseSessionSkillsRef");function sameSessionSkillsRef(a,b){return a?.resourceId===b?.resourceId&&a?.kind===b?.kind&&a?.schemaVersion===b?.schemaVersion&&a?.byteLength===b?.byteLength&&a?.digest===b?.digest}__name(sameSessionSkillsRef,"sameSessionSkillsRef");function invalid2(){throw new Error("Invalid Hosted skill catalog.")}__name(invalid2,"invalid");function boundedText(value,maxBytes){return typeof value==="string"&&value.trim().length>0&&!/[\ud800-\udfff]/u.test(value)&&Buffer.byteLength(value,"utf8")<=maxBytes}__name(boundedText,"boundedText");function parseHostedSkills(value){if(!Array.isArray(value)||value.length>256||Buffer.byteLength(JSON.stringify(value),"utf8")>HOSTED_SKILL_CATALOG_MAX_BYTES)invalid2();const names=new Set;return Object.freeze(value.map(item=>{if(!item||typeof item!=="object"||Array.isArray(item))invalid2();const skill=item;if(Object.keys(skill).some(key=>!["name","description","body","base_directory","model_invocable","user_invocable","asset_directory"].includes(key))||!boundedText(skill["name"],128)||!boundedText(skill["description"],4096)||!boundedText(skill["body"],512*1024))invalid2();for(const field of["model_invocable","user_invocable"]){if(skill[field]!==void 0&&typeof skill[field]!=="boolean")invalid2()}validateSkillName(skill["name"]);if(names.has(skill["name"]))invalid2();names.add(skill["name"]);const base=skill["base_directory"];const asset=skill["asset_directory"];if(asset!==void 0&&(typeof asset!=="string"||!/^extension:\/\/[A-Za-z0-9._:-]+\/(?:[^\\\s]*\/?)$/u.test(asset)||asset.split("/").some(part=>part===".."||part===".")))invalid2();if(base!==void 0){if(!boundedText(base,4096)||/[\\:]/u.test(base)||[...base].some(character=>{const code=character.codePointAt(0);return code<=31||code>=127&&code<=159})||base!=="."&&base.split("/").some(segment=>!segment||segment==="."||segment===".."))invalid2()}return Object.freeze({name:skill["name"],description:skill["description"],body:skill["body"],...asset===void 0?{}:{asset_directory:asset},...base===void 0?{}:{base_directory:base},...skill["model_invocable"]===void 0?{}:{model_invocable:skill["model_invocable"]},...skill["user_invocable"]===void 0?{}:{user_invocable:skill["user_invocable"]}})}))}__name(parseHostedSkills,"parseHostedSkills");async function readHostedSkills(ref2,resources){if(!ref2)return[];if(ref2.kind!=="managed-agent-skills"||ref2.schemaVersion!==1||ref2.byteLength>HOSTED_SKILL_CATALOG_MAX_BYTES)throw new Error("Invalid agent skills reference.");const bytes=await resources.read(ref2);if(bytes.byteLength!==ref2.byteLength||createHash3("sha256").update(bytes).digest("hex")!==ref2.digest)throw new Error("Agent skills do not match their reference.");return parseHostedSkills(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)))}__name(readHostedSkills,"readHostedSkills");var HostedSkillCatalog=class{constructor(skills,commands=[]){this.commands=commands;this.skills=parseHostedSkills(skills);const names=new Set(this.skills.map(skill=>skill.name));for(const command of commands){validateSkillName(command.name);if(names.has(command.name)||!boundedText(command.description,4096)||!boundedText(command.prompt,512*1024))invalid2();names.add(command.name)}}static{__name(this,"HostedSkillCatalog")}skills;entries(){return this.skills}command(args){if(!args||typeof args!=="object")return void 0;return this.commands.find(command=>command.name===args.skill)}userArguments(name,prompt){return this.commands.some(command=>command.name===name)?{args:prompt.trimStart().slice(name.length+1).trimStart()}:{}}instructions(){const available=[...this.skills.filter(skill=>skill.model_invocable!==false),...this.commands.filter(command=>command.modelInvocable).map(command=>({name:command.name,description:command.description}))];if(!available.length)return void 0;return`The following published skills are available. Use the skill tool to load their instructions when relevant.
3
+ import{CHECKPOINT_HISTORY_KIND,HOSTED_MODEL_REQUEST_BYTES,HOSTED_RECOVERY_RESOURCE_KINDS,MANAGED_EXTENSION_RECORD_BODIES,MANAGED_MESSAGE_CHUNKS_KIND,ManagedSessionCommitRejectedError,ManagedSessionConflictError,checkpointHistoryPage,checkpointStorageBody,hostedRecoveryReferences,isPagedHarnessCheckpoint,managedMessageChunkParts,managedToolDigest,parseHostedRecoveryResource,scanManagedSessionJournal,tryParseHarnessCheckpointV1}from"./chunk-2JGTWRZJ.js";import{MANAGED_SESSION_COMMIT_SUBTYPE,MANAGED_SESSION_EVENT_SUBTYPE,MANAGED_SESSION_HEADER_SUBTYPE,MANAGED_SESSION_LIMITS,MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,ManagedSessionAppendUnsettledError,ManagedSessionJournalFencedError,ManagedSessionRecordError,assertManagedSessionDurableRef,assertManagedSessionStableId,isToolResultPageAt,managedSessionEventRefs,managedSessionKeysEqual,parseManagedSessionCommitMarker,parseManagedSessionEvent,parseManagedSessionHeader,parseManagedSessionRecordJson,parseToolResultManifestBytes,parseToolResultPageBytes,parseToolResultPrefixRequest,parseToolResultPublishRequest,parseToolResultSealRequest}from"./chunk-OMSVOFTC.js";import{validateSkillName}from"./chunk-CV2UAEZA.js";import{renderAvailableSkillsBlock}from"./chunk-IRINPFG7.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var RULE_KINDS=["allow","ask","deny"];var SHELL=new Set(["Bash","Shell","ShellTool","run_shell_command","monitor","Monitor","MonitorTool"]);var WEB=new Set(["WebFetch","WebFetchTool","web_fetch"]);var TOOL=/^[A-Za-z_][A-Za-z0-9_.:-]*$/u;var MCP=/^mcp__[A-Za-z0-9_.:-]+(?:__[A-Za-z0-9_.:-]+)?\*?$/u;var DOMAIN=/^domain:(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/u;var encoder=new TextEncoder;function validRule(rule){if(!rule||rule!==rule.trim()||new RegExp("\\p{Cc}","u").test(rule)||encoder.encode(rule).length>512)return false;const open=rule.indexOf("(");if(open<0)return rule.startsWith("mcp__")?MCP.test(rule):TOOL.test(rule);if(!rule.endsWith(")"))return false;const tool=rule.slice(0,open);const specifier=rule.slice(open+1,-1);return!!specifier&&specifier===specifier.trim()&&(SHELL.has(tool)||WEB.has(tool)&&DOMAIN.test(specifier))}__name(validRule,"validRule");function parseManagedPermissionRules(value){const invalid3=__name(()=>new Error("Invalid portable permission rules."),"invalid");if(!value||typeof value!=="object"||Array.isArray(value))throw invalid3();const fields=value;if(Object.keys(fields).length!==3||RULE_KINDS.some(kind=>!Object.hasOwn(fields,kind)))throw invalid3();let total=0;const result={};for(const kind of RULE_KINDS){const rules=fields[kind];if(!Array.isArray(rules)||rules.length>32||rules.some(rule=>typeof rule!=="string"||!validRule(rule))||new Set(rules).size!==rules.length)throw invalid3();total+=rules.length;result[kind]=[...rules]}if(total>64||encoder.encode(JSON.stringify(result)).length>8192)throw invalid3();return result}__name(parseManagedPermissionRules,"parseManagedPermissionRules");function nonEmptyManagedPermissionRules(rules){return rules&&RULE_KINDS.some(kind=>rules[kind].length>0)?rules:void 0}__name(nonEmptyManagedPermissionRules,"nonEmptyManagedPermissionRules");import{createHash as createHash2,randomBytes,randomUUID}from"node:crypto";import{isIPv4}from"node:net";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";var HOSTED_TOOL_RESULT_RESOURCE_LIMITS={[MANAGED_TOOL_RESULT_KINDS.content]:1024*1024,[MANAGED_TOOL_RESULT_KINDS.page]:MANAGED_TOOL_RESULT_LIMITS.maxPageBytes,[MANAGED_TOOL_RESULT_KINDS.manifest]:MANAGED_TOOL_RESULT_LIMITS.maxManifestBytes};function digest(bytes){return createHash("sha256").update(bytes).digest("hex")}__name(digest,"digest");function id(captureId,streamId,ordinal){return digest(Buffer.from(JSON.stringify([captureId,streamId,ordinal])))}__name(id,"id");function ref(resourceId,bytes){return{resourceId,kind:MANAGED_TOOL_RESULT_KINDS.content,schemaVersion:1,byteLength:bytes.length,digest:digest(bytes)}}__name(ref,"ref");var conflict={status:"refused",code:"managed_tool_result_conflict"};var invalid={status:"refused",code:"managed_tool_result_invalid"};var corrupt={status:"refused",code:"managed_tool_result_digest_mismatch"};var ok=__name(result=>({status:"ok",result}),"ok");var ResourceToolResultSegmentStore=class{constructor(resources){this.resources=resources}static{__name(this,"ResourceToolResultSegmentStore")}captureId;streams=new Map;closed=false;tail=Promise.resolve();enqueue(action){if(this.closed)return Promise.reject(new Error("Tool result store closed."));const result=this.tail.then(action);this.tail=result.catch(()=>void 0);return result}stream(captureId,streamId){if(streamId!=="stdout"&&streamId!=="stderr"||this.captureId!==void 0&&this.captureId!==captureId)return void 0;this.captureId=captureId;let stream=this.streams.get(streamId);if(!stream){stream={receipts:[],hash:createHash("sha256"),byteLength:0,sealed:false};this.streams.set(streamId,stream)}return stream}publish(request){return this.enqueue(async()=>{let input;try{input=parseToolResultPublishRequest(request)}catch{return invalid}if(input.bytes.byteLength>1024*1024)return invalid;const bytes=Buffer.from(input.bytes);const receipt={ordinal:input.ordinal,byteLength:bytes.length,digest:digest(bytes)};if(input.expectedDigest!==null&&input.expectedDigest!==receipt.digest)return corrupt;const stream=this.stream(input.captureId,input.streamId);if(!stream)return conflict;const prior=stream.receipts[input.ordinal];if(prior)return JSON.stringify(prior)===JSON.stringify(receipt)?ok(prior):conflict;if(stream.sealed||input.ordinal!==stream.receipts.length)return conflict;const resourceId=id(input.captureId,input.streamId,input.ordinal);const published=await this.resources.publish(MANAGED_TOOL_RESULT_KINDS.content,bytes,resourceId);const expected=ref(resourceId,bytes);if(Object.entries(expected).some(([key,value])=>published[key]!==value))throw new Error("Tool result publication receipt changed.");stream.receipts.push(receipt);stream.hash.update(bytes);stream.byteLength+=bytes.length;return ok(receipt)})}seal(request){return this.enqueue(async()=>{let input;try{input=parseToolResultSealRequest(request)}catch{return invalid}const stream=this.stream(input.captureId,input.streamId);if(!stream)return conflict;const receipt=this.prefixOf(stream);if(input.segmentCount!==receipt.segmentCount)return conflict;if(input.byteLength!==receipt.byteLength||input.digest!==receipt.digest)return stream.sealed?conflict:corrupt;const seal={segmentCount:input.segmentCount,byteLength:input.byteLength,digest:input.digest};const bytes=Buffer.from(JSON.stringify(seal));await this.resources.publish(MANAGED_TOOL_RESULT_KINDS.content,bytes,id(input.captureId,input.streamId,"seal"));stream.sealed=true;return ok(seal)})}prefixOf(stream){return{segmentCount:stream.receipts.length,byteLength:stream.byteLength,digest:stream.hash.copy().digest("hex"),sealed:stream.sealed}}prefix(request){return this.enqueue(async()=>{let input;try{input=parseToolResultPrefixRequest(request)}catch{return invalid}const stream=this.stream(input.captureId,input.streamId);return stream?ok(this.prefixOf(stream)):conflict})}async read(resource,kind,max){const validated=assertManagedSessionDurableRef({...resource},"tool result resource");if(validated.kind!==kind||validated.schemaVersion!==1||validated.byteLength>max){throw new Error("Tool result resource exceeds its bound.")}const bytes=await this.resources.read(validated);if(bytes.length!==validated.byteLength||digest(bytes)!==validated.digest)throw new Error("Corrupt tool result resource.");return bytes}readRange(request){return this.enqueue(async()=>{const{offset,length}=request;if(!Number.isSafeInteger(offset)||offset<0||!Number.isSafeInteger(length)||length<0||length>MANAGED_TOOL_RESULT_LIMITS.maxSegmentBytes)return invalid;const manifest=parseToolResultManifestBytes(await this.read(request.manifestRef,MANAGED_TOOL_RESULT_KINDS.manifest,MANAGED_TOOL_RESULT_LIMITS.maxManifestBytes));for(const key of["tenantId","sessionId","turnId","executionCallId","callId","invocationDigest","bindingGeneration","captureId","revision"]){if(manifest[key]!==request.expectedIdentity?.[key])return conflict}const index=manifest.contents.findIndex(entry2=>entry2.streamId===request.streamId);const entry=manifest.contents[index];if(!entry||!("pages"in entry.body)||offset>entry.byteLength||length>entry.byteLength-offset)return invalid;if(entry.state==="sealed"){const seal=Buffer.from(JSON.stringify({segmentCount:entry.body.pages.reduce((sum,page)=>sum+page.segmentCount,0),byteLength:entry.byteLength,digest:entry.digest}));await this.read(ref(id(manifest.captureId,entry.streamId,"seal"),seal),MANAGED_TOOL_RESULT_KINDS.content,1024)}const output=Buffer.alloc(length);for(const[pageIndex,pageRef]of entry.body.pages.entries()){const page=parseToolResultPageBytes(await this.read(pageRef.ref,MANAGED_TOOL_RESULT_KINDS.page,MANAGED_TOOL_RESULT_LIMITS.maxPageBytes));if(!isToolResultPageAt(manifest,index,pageIndex,page))return conflict;let position=page.offset;for(const[segmentIndex,segment]of page.segments.entries()){const end=position+segment.byteLength;if(position<offset+length&&end>offset){const bytes=await this.read({resourceId:id(manifest.captureId,entry.streamId,page.firstOrdinal+segmentIndex),kind:MANAGED_TOOL_RESULT_KINDS.content,schemaVersion:1,...segment},MANAGED_TOOL_RESULT_KINDS.content,1024*1024);const from=Math.max(position,offset);const to=Math.min(end,offset+length);bytes.copy(output,from-offset,from-position,to-position)}position=end}}return ok(output)})}async close(){this.closed=true;await this.tail;this.streams.clear()}};var HTTP_MANAGED_SESSION_STORE_CONTRACT={tenantHeader:"X-Qwen-Tenant-Id",writerTokenHeader:"X-Qwen-Managed-Writer-Token",maxInlineResourceBytes:64*1024,maxResourcesPerTransaction:1024,minimumWriterTokenLength:32,maximumWriterTokenLength:512,minimumLeaseDurationMs:1e3,maximumLeaseDurationMs:3e5};var MAX_ATTACHMENT_INPUT_BYTES=8*1024*1024;var MAX_NATIVE_SNAPSHOT_PAGE_BYTES=16*1024*1024;function managedSessionInlineResourceBytes(kind){if(kind==="managed-checkpoint")return MANAGED_SESSION_LIMITS.maxEventBytes;if(kind==="managed-input")return MAX_ATTACHMENT_INPUT_BYTES;if(kind==="managed-agent-skills")return 2*1024*1024;if(kind==="hosted-model-request")return HOSTED_MODEL_REQUEST_BYTES;return HTTP_MANAGED_SESSION_STORE_CONTRACT.maxInlineResourceBytes}__name(managedSessionInlineResourceBytes,"managedSessionInlineResourceBytes");var WRITER_TOKEN=new RegExp(`^[A-Za-z0-9_-]{${HTTP_MANAGED_SESSION_STORE_CONTRACT.minimumWriterTokenLength},${HTTP_MANAGED_SESSION_STORE_CONTRACT.maximumWriterTokenLength}}$`);var DEFAULT_LEASE_DURATION_MS=6e4;var DEFAULT_REQUEST_TIMEOUT_MS=3e4;var debugLogger=createDebugLogger("MANAGED_SESSION_STORE");function isLoopbackHostname(hostname){const lower=hostname.toLowerCase();return lower==="localhost"||lower.endsWith(".localhost")||isIPv4(lower)&&lower.startsWith("127.")||lower==="[::1]"}__name(isLoopbackHostname,"isLoopbackHostname");var ManagedSessionStoreHttpError=class extends ManagedSessionRecordError{constructor(status,remoteCode,message,contentionExhausted,details,route){super(message);this.status=status;this.remoteCode=remoteCode;this.contentionExhausted=contentionExhausted;this.details=details;this.route=route;this.name="ManagedSessionStoreHttpError"}static{__name(this,"ManagedSessionStoreHttpError")}writerRefusalContext};var ManagedSessionStoreTransportError=class extends ManagedSessionRecordError{static{__name(this,"ManagedSessionStoreTransportError")}};function isUncertainStoreFailure(error){return error instanceof ManagedSessionStoreHttpError&&(error.status===429||error.status>=500)||error instanceof ManagedSessionStoreTransportError||error instanceof TypeError||error instanceof DOMException&&["AbortError","TimeoutError"].includes(error.name)}__name(isUncertainStoreFailure,"isUncertainStoreFailure");function asError(error){return error instanceof Error?error:new Error(String(error))}__name(asError,"asError");function createHttpManagedSessionStores(options){const resources=new HttpManagedSessionResourceStore;const client=new ManagedSessionStoreHttpClient(options,resources);resources.bind(client);return{journalStore:new HttpManagedSessionJournalStore(client),resourceStore:resources,publication:{owner:__name(()=>client.publicationOwner(),"owner"),request:__name((path,body,token)=>client.publicationRequest(path,body,token),"request"),rememberAdmission:__name((publicationId,ref2)=>client.rememberAdmission(publicationId,ref2),"rememberAdmission")},toolResultResources:{publish:__name((kind,bytes,resourceId)=>client.publishToolResult(kind,bytes,resourceId),"publish"),read:__name(ref2=>client.readResource(ref2),"read")},csiRetirement:{joinWriter:__name(()=>client.joinOriginalCsiWriter(),"joinWriter"),prepare:__name(records=>client.prepareOriginalCsiCommit(records),"prepare"),complete:__name(retirementId=>client.completeOriginalCsiRetirement(retirementId),"complete")},assertWritable:__name(()=>client.assertWritable(),"assertWritable"),stopLocal:__name(()=>client.stopLocal(),"stopLocal"),quiesceOwnership:__name(placement=>client.quiesceOwnership(placement),"quiesceOwnership"),releaseOwnership:__name(request=>client.releaseOwnership(request),"releaseOwnership"),close:__name(()=>client.seal(),"close"),setLifecycleAuthority:__name(authority=>client.setLifecycleAuthority(authority),"setLifecycleAuthority"),authorizeLifecycle:__name(kind=>client.authorizeLifecycle(kind),"authorizeLifecycle"),authorizeOrdinary:__name(kind=>client.authorizeOrdinary(kind),"authorizeOrdinary"),approvalSelection:__name(()=>client.approvalSelection(),"approvalSelection"),claimUserMessages:__name((promptId,initialOnly)=>client.claimUserMessages(promptId,initialOnly),"claimUserMessages")}}__name(createHttpManagedSessionStores,"createHttpManagedSessionStores");var HttpManagedSessionJournalStore=class{constructor(client){this.client=client}static{__name(this,"HttpManagedSessionJournalStore")}handle;opening;async open(request){if(!managedSessionKeysEqual(request.sessionKey,this.client.sessionKey)){throw new ManagedSessionRecordError("the HTTP Managed Session store belongs to a different session.")}if(this.handle!==void 0)return this.handle;if(this.opening!==void 0)return this.opening;const opening=(async()=>{await this.client.acquireWriter();const handle=new HttpManagedSessionJournalHandle(this.client);this.handle=handle;return handle})();this.opening=opening;try{return await opening}finally{if(this.opening===opening)this.opening=void 0}}};var HttpManagedSessionJournalHandle=class{constructor(client){this.client=client;this.sessionKey=client.sessionKey}static{__name(this,"HttpManagedSessionJournalHandle")}sessionKey;read(options={}){return this.client.readJournal(options.maxBytes)}async appendTransaction(records){try{await this.client.appendTransaction(records)}catch(error){if(!(error instanceof ManagedSessionCommitRejectedError)&&!(error instanceof ManagedSessionAppendUnsettledError))this.client.stopWriterRenewal();throw error}}renewActivation(request){return this.client.renewActivation(request)}async settleAppend(){try{return await this.client.settleAppend()}catch(error){if(!(error instanceof ManagedSessionAppendUnsettledError)){this.client.stopWriterRenewal();await this.client.seal().catch(()=>void 0)}throw error}}blockRecovery(request){return this.client.blockRecovery(request)}seal(){return this.client.seal()}get writerSealed(){return this.client.writerSealed}abort(){return this.client.seal()}};var EXTENSION_RECORD_KINDS=new Set(Object.keys(MANAGED_EXTENSION_RECORD_BODIES).map(domain=>`managed-${domain}`));var HttpManagedSessionResourceStore=class{static{__name(this,"HttpManagedSessionResourceStore")}staged=new Map;client;bind(client){this.client=client}async publish(kind,source){const safeKind=assertManagedSessionStableId(kind,"resource kind");const maxBytes=managedSessionInlineResourceBytes(safeKind);if(source.byteLength>maxBytes){throw new ManagedSessionRecordError(`resource bytes exceed the ${maxBytes}-byte inline limit (kind=${safeKind}, bytes=${source.byteLength}); OSS storage is not enabled.`)}const bytes=Buffer.from(source);const ref2={resourceId:randomUUID(),kind:safeKind,schemaVersion:1,byteLength:bytes.byteLength,digest:sha256(bytes)};this.staged.set(ref2.resourceId,{ref:ref2,bytes});return ref2}async read(ref2){const validated=assertManagedSessionDurableRef(ref2,"resource");const staged=this.staged.get(validated.resourceId);if(staged!==void 0){requireSameRef(staged.ref,validated);return Buffer.from(staged.bytes)}if(this.client===void 0){throw new ManagedSessionRecordError("the HTTP Managed Session resource store is not bound.")}return this.client.readResource(validated)}async commitResources(refs){const closure=new Map;const pending=[...refs];while(pending.length>0){const ref2=pending.pop();const existing=closure.get(ref2.resourceId);if(existing!==void 0){requireSameRef(existing,ref2);continue}closure.set(ref2.resourceId,ref2);if(closure.size>HTTP_MANAGED_SESSION_STORE_CONTRACT.maxResourcesPerTransaction){throw new ManagedSessionRecordError(`a Managed Session transaction references more than ${HTTP_MANAGED_SESSION_STORE_CONTRACT.maxResourcesPerTransaction} resources.`)}const staged=this.staged.get(ref2.resourceId);if(staged!==void 0){requireSameRef(staged.ref,ref2);const nested=collectNestedResourceRefs(ref2,staged.bytes);pending.push(...ref2.kind===CHECKPOINT_HISTORY_KIND?nested.filter(child=>this.staged.has(child.resourceId)):nested)}else if(ref2.kind!==CHECKPOINT_HISTORY_KIND&&isReferenceContainer(ref2.kind)){pending.push(...collectNestedResourceRefs(ref2,await this.read(ref2)))}}return[...closure.values()].map(ref2=>{const staged=this.staged.get(ref2.resourceId);if(staged!==void 0)requireSameRef(staged.ref,ref2);return{resourceId:ref2.resourceId,kind:ref2.kind,schemaVersion:ref2.schemaVersion,byteLength:ref2.byteLength,digest:ref2.digest,...staged===void 0?{}:{bytesBase64:staged.bytes.toString("base64")}}})}releaseCommitted(refs){for(const ref2 of refs)this.staged.delete(ref2.resourceId)}clear(){this.staged.clear()}};var ManagedSessionStoreHttpClient=class{constructor(options,resources){this.resources=resources;this.sessionKey=options.sessionKey;this.writerId=assertManagedSessionStableId(options.writerId,"writerId");this.writerToken=options.writerToken??randomBytes(32).toString("base64url");if(!WRITER_TOKEN.test(this.writerToken)){throw new ManagedSessionRecordError("writerToken must be a 32-512 character Base64URL secret.")}this.leaseDurationMs=options.leaseDurationMs??DEFAULT_LEASE_DURATION_MS;if(!Number.isInteger(this.leaseDurationMs)||this.leaseDurationMs<HTTP_MANAGED_SESSION_STORE_CONTRACT.minimumLeaseDurationMs||this.leaseDurationMs>HTTP_MANAGED_SESSION_STORE_CONTRACT.maximumLeaseDurationMs){throw new ManagedSessionRecordError("leaseDurationMs must be an integer from 1000 through 300000.")}this.requestTimeoutMs=options.requestTimeoutMs??DEFAULT_REQUEST_TIMEOUT_MS;if(!Number.isInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1){throw new ManagedSessionRecordError("requestTimeoutMs must be a positive integer.")}const parsed=new URL(options.baseUrl);if(parsed.protocol!=="http:"&&parsed.protocol!=="https:"||parsed.username!==""||parsed.password!==""||parsed.search!==""||parsed.hash!==""){throw new ManagedSessionRecordError("baseUrl must be an HTTP(S) URL without credentials, query, or fragment.")}if(parsed.protocol==="http:"&&!isLoopbackHostname(parsed.hostname)&&options.allowInsecureHttp!==true){throw new ManagedSessionRecordError("baseUrl uses plaintext HTTP on a non-loopback host; writer tokens would cross the wire unencrypted. Pass allowInsecureHttp: true to opt in.")}this.baseUrl=parsed.toString().replace(/\/$/,"");this.fetchFn=options.fetchFn??globalThis.fetch}static{__name(this,"ManagedSessionStoreHttpClient")}sessionKey;baseUrl;writerId;writerToken;leaseDurationMs;requestTimeoutMs;fetchFn;grant;renewPromise;ownershipRelease;acquirePromise;renewingAuthority;renewTimer;renewalStopped=false;retirementJoin;writerRenewalFailures=[];preparedRetirement;sealed=false;locallyStopped=false;lifecycleAuthority;pendingAppend;get writerSealed(){return this.sealed}setLifecycleAuthority(authority){this.lifecycleAuthority=authority}async authorizeOrdinary(kind){await this.assertWritable();await this.json("/execution:authorize","POST",{...kind?{kind}:{},workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:this.grant.writerGeneration})}async claimUserMessages(promptId,initialOnly){await this.assertWritable();let value;try{value=await this.json("/user-messages:claim","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:this.grant.writerGeneration,promptId,initialOnly:initialOnly??false})}catch(error){if(error instanceof ManagedSessionStoreHttpError&&error.status===404&&error.remoteCode==="not_found")return[];throw error}if(!Array.isArray(value)||value.length>32)throw corrupt2("invalid user message queue.");return value.map(entry=>{const message=asRecord(entry,"queued user message");if(typeof message["id"]!=="string"||!message["id"].startsWith("umsg_")||!Number.isSafeInteger(message["revision"])||Number(message["revision"])<1||!Array.isArray(message["input"]))throw corrupt2("invalid queued user message.");return{id:message["id"],revision:Number(message["revision"]),input:message["input"]}})}async approvalSelection(){await this.assertWritable();const value=await this.json("/approval:query","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:this.grant.writerGeneration});if(value===null)return void 0;const selection=asRecord(value,"approval selection");if(Object.keys(selection).length!==(selection["permissionRules"]===void 0?2:3)||!["default","auto-edit","yolo","auto"].includes(String(selection["mode"]))||typeof selection["mode"]!=="string"||typeof selection["revision"]!=="number"||!Number.isSafeInteger(selection["revision"])||selection["revision"]<0)throw corrupt2("approval selection is invalid.");let permissionRules;try{permissionRules=selection["permissionRules"]===void 0?void 0:nonEmptyManagedPermissionRules(parseManagedPermissionRules(selection["permissionRules"]))}catch{throw corrupt2("approval selection rules are invalid.")}if(selection["revision"]===0&&(selection["mode"]==="auto"||permissionRules))throw corrupt2("approval selection revision is invalid.");return{mode:selection["mode"],revision:selection["revision"],...permissionRules?{permissionRules}:{}}}async authorizeLifecycle(kind){if(kind)await this.assertWritable();const grant=this.grant;if(!grant)throw new ManagedSessionRecordError("the HTTP Managed Session writer is not active.");await this.json("/lifecycle:authorize","POST",{...kind?{kind}:{},workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration})}publicationAdmissions=new Map;async acquireWriter(){if(this.ownershipRelease)throw corrupt2("ownership release has fenced this writer.");if(this.grant!==void 0||this.sealed||this.locallyStopped){throw new ManagedSessionRecordError("the HTTP Managed Session writer is already opened or sealed.")}const grant=parseWriterGrant(await this.json("/writers:acquire","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,leaseMillis:this.leaseDurationMs}));this.grant=grant;debugLogger.debug(`Managed Session Store writer acquired: session=${this.sessionKey.sessionId} writerId=${this.writerId} acquiredWriterGeneration=${grant.writerGeneration} journalRevision=${grant.journalRevision} committedSequence=${grant.committedSequence} leaseUntil=${new Date(grant.leaseUntil).toISOString()}`);this.scheduleRenewal()}async readJournal(maxBytes){await this.ensureWriter();const response=asRecord(await this.json(`/restore?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}&includeNativeSnapshot=true`,"GET"),"restore head");const head=parseRestoreHead(response);const usesSnapshot=response["nativeSnapshot"]!=null;this.requireHeadMatchesGrant(head);debugLogger.debug(`Managed Session Store restore head matches grant: session=${this.sessionKey.sessionId} writerId=${this.writerId} acquiredWriterGeneration=${this.requireGrant().writerGeneration} headGeneration=${head.writerGeneration} journalRevision=${head.journalRevision} committedSequence=${head.committedSequence} state=${head.state} storageVersion=${head.storageVersion}`);const chunks=[];let afterRevision=0;let activationEpoch=0;let committedSequence=0;let lastCommitDigest=null;let latestCheckpointResourceId=null;const append=__name(value=>{const transaction=parseStoredTransaction(value);if(transaction.journalRevision!==afterRevision+1||usesSnapshot&&transaction.journalRevision>head.journalRevision){throw corrupt2("transaction revisions are not contiguous.")}const bytes2=decodeBase64(transaction.recordBytesBase64,"recordBytesBase64");if(bytes2.byteLength!==transaction.byteLength||sha256(bytes2)!==transaction.recordDigest){throw corrupt2("transaction bytes do not match their metadata.")}const descriptor=describeTransaction(decodeRecords(bytes2),bytes2,activationEpoch,this.sessionKey);requireStoredTransactionMatches(transaction,descriptor);if(usesSnapshot&&(transaction.previousCommitDigest!==lastCommitDigest||(afterRevision===0?transaction.operation!=="session.create"||transaction.eventCount!==0:transaction.operation==="session.create"||transaction.firstSequence!==committedSequence+1))){throw corrupt2("snapshot transaction chain is discontinuous.")}activationEpoch=descriptor.activationEpoch;committedSequence=transaction.lastSequence;lastCommitDigest=transaction.commitDigest;latestCheckpointResourceId=descriptor.latestCheckpointResourceId??latestCheckpointResourceId;chunks.push(bytes2);afterRevision=transaction.journalRevision;return descriptor},"append");if(usesSnapshot){const snapshot=await this.readNativeSnapshot(response["nativeSnapshot"],head,append);if(afterRevision!==snapshot.coveredJournalRevision||committedSequence!==snapshot.committedSequence||lastCommitDigest!==snapshot.lastCommitDigest||activationEpoch!==snapshot.activationEpoch||latestCheckpointResourceId!==snapshot.latestCheckpointResourceId){throw corrupt2("snapshot prefix does not match its manifest.")}}while(afterRevision<head.journalRevision){await this.ensureWriter();const limit=usesSnapshot?Math.min(100,head.journalRevision-afterRevision):100;const page=asRecord(await this.json(`/transactions?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}&afterRevision=${afterRevision}&limit=${limit}`,"GET"),"transaction page");const transactions=asArray(page["transactions"],"transactions");if(transactions.length===0){throw corrupt2("transaction page did not advance the journal.")}for(const value of transactions){append(value)}const nextRevision=safeCounter(page["nextRevision"],"nextRevision");const hasMore=boolean(page["hasMore"],"hasMore");if(nextRevision!==afterRevision){throw corrupt2("transaction page nextRevision is inconsistent.")}if(!hasMore&&afterRevision!==head.journalRevision){throw corrupt2("transaction page ended before the journal head.")}}const bytes=Buffer.concat(chunks);const scan=scanManagedSessionJournal(bytes,this.sessionKey,usesSnapshot?void 0:maxBytes);if((usesSnapshot||maxBytes===void 0)&&(scan.committed!==head.committedSequence||scan.lastMarkerDigest!==head.lastCommitDigest||(scan.activation?.epoch??0)!==head.activationEpoch||usesSnapshot&&latestCheckpointResourceId!==head.latestCheckpointResourceId)){throw corrupt2("journal bytes do not match the durable head.")}if(usesSnapshot){await this.ensureWriter();const current=parseRestoreHead(await this.json(`/restore?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}`,"GET"));this.requireHeadMatchesGrant(current);this.requireHeadMatchesGrant(head);if(current.journalRevision<head.journalRevision||current.committedSequence<head.committedSequence)throw corrupt2("restore head regressed while reading the snapshot.")}this.grant={...this.requireGrant(),writerGeneration:head.writerGeneration,leaseUntil:this.requireGrant().leaseUntil,journalRevision:head.journalRevision,committedSequence:head.committedSequence,lastCommitDigest:head.lastCommitDigest,activationEpoch:head.activationEpoch};const result=usesSnapshot&&maxBytes!==void 0?scanManagedSessionJournal(bytes,this.sessionKey,maxBytes):scan;return maxBytes===void 0?applyActivationLease(result,head.activationLease):result}async renewActivation(activation){if(!this.requireGrant().activationLeaseRenewal)return void 0;let reacquiring=false;try{if(this.requireGrant().leaseUntil<=Date.now()){reacquiring=true;await this.reacquireWriter();reacquiring=false}await this.ensureWriter();const grant=this.requireGrant();const renewed=parseWriterGrant(await this.json("/writers:renew","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,leaseMillis:this.leaseDurationMs,activation}));if(renewed.writerGeneration!==grant.writerGeneration||renewed.journalRevision!==grant.journalRevision||renewed.committedSequence!==grant.committedSequence||renewed.lastCommitDigest!==grant.lastCommitDigest||renewed.activationEpoch!==grant.activationEpoch||!renewed.activationLease)throw corrupt2("activation renewal changed the journal head.");this.grant=renewed;this.scheduleRenewal();return renewed.activationLease}catch(error){if(error instanceof ManagedSessionStoreHttpError&&(error.status===409&&["workspace_lifecycle_admission_closed","workspace_lifecycle_claim_fenced"].includes(error.remoteCode)||this.lifecycleAuthority&&(error.status===403||error.status===409&&(error.remoteCode.startsWith("workspace_lifecycle_")||error.remoteCode==="workspace_unavailable"))))throw new ManagedSessionCommitRejectedError(error);if(isUncertainStoreFailure(error)||!reacquiring&&this.requireGrant().leaseUntil<=Date.now()&&error instanceof ManagedSessionStoreHttpError&&error.status===409&&error.remoteCode==="managed_session_writer_conflict")throw new ManagedSessionAppendUnsettledError(asError(error));this.stopWriterRenewal();throw error}}async readNativeSnapshot(value,head,append){const descriptor=asRecord(value,"native snapshot descriptor");const raw=asRecord(descriptor["snapshot"],"native snapshot manifest");const manifestRef=assertManagedSessionDurableRef(descriptor["manifest"],"native manifest");const snapshot={snapshotId:string(raw["snapshotId"],"snapshotId"),coveredJournalRevision:safeCounter(raw["coveredJournalRevision"],"coveredJournalRevision"),committedSequence:safeCounter(raw["committedSequence"],"committedSequence"),lastCommitDigest:nullableDigest(raw["lastCommitDigest"],"lastCommitDigest"),activationEpoch:safeCounter(raw["activationEpoch"],"activationEpoch"),latestCheckpointResourceId:nullableString(raw["latestCheckpointResourceId"],"latestCheckpointResourceId"),resourceCount:safeCounter(raw["resourceCount"],"resourceCount"),lastPageDigest:digest2(raw["lastPageDigest"],"lastPageDigest")};const storageVersion=safeCounter(raw["storageVersion"],"snapshot storageVersion");if(raw["format"]!=="qwen-managed-native-session-snapshot/1"||raw["payloadFormat"]!=="committed-prefix-v1"||raw["tenantId"]!==this.sessionKey.tenantId||raw["workspaceId"]!==this.sessionKey.workspaceId||raw["sessionId"]!==this.sessionKey.sessionId||snapshot.snapshotId.length===0||Buffer.byteLength(snapshot.snapshotId,"utf8")>512||![1,2].includes(storageVersion)||storageVersion>head.storageVersion||snapshot.coveredJournalRevision<1||snapshot.coveredJournalRevision>head.journalRevision||snapshot.committedSequence>head.committedSequence||snapshot.activationEpoch>head.activationEpoch||raw["pageCount"]!==snapshot.coveredJournalRevision||manifestRef.kind!=="managed-native-journal-snapshot"||manifestRef.schemaVersion!==1||manifestRef.byteLength>MAX_NATIVE_SNAPSHOT_PAGE_BYTES){throw corrupt2("native snapshot scope, format or coverage is invalid.")}const resources=new Map;let after=0;let previousDigest=null;while(after<snapshot.coveredJournalRevision){await this.ensureWriter();const result=asRecord(await this.json(`/journal-snapshots/${encodeURIComponent(snapshot.snapshotId)}/pages?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}&afterRevision=${after}&limit=100`,"GET"),"native snapshot pages");const pages=asArray(result["pages"],"native snapshot pages");if(pages.length===0||pages.length>100)throw corrupt2("native snapshot pages did not advance.");let responseBytes=0;for(const item of pages){const stored=asRecord(item,"native snapshot page");const ref2=assertManagedSessionDurableRef(stored["resource"],"native page resource");if(ref2.kind!=="managed-native-journal-snapshot-page"||ref2.schemaVersion!==1||ref2.byteLength>MAX_NATIVE_SNAPSHOT_PAGE_BYTES||string(stored["bytesBase64"],"native page bytes").length>Math.ceil(ref2.byteLength/3)*4){throw corrupt2("native snapshot page resource is invalid.")}const bytes=decodeBase64(string(stored["bytesBase64"],"native page bytes"),"native page bytes");responseBytes+=bytes.byteLength;if(bytes.byteLength!==ref2.byteLength||sha256(bytes)!==ref2.digest||responseBytes>MAX_NATIVE_SNAPSHOT_PAGE_BYTES)throw corrupt2("native snapshot page digest or size is invalid.");const page=asRecord(parseManagedSessionRecordJson(bytes.toString("utf8"),MAX_NATIVE_SNAPSHOT_PAGE_BYTES),"native snapshot page body");if(stored["journalRevision"]!==after+1||page["journalRevision"]!==after+1||page["previousPageDigest"]!==previousDigest||after>=snapshot.coveredJournalRevision){throw corrupt2("native snapshot page chain is discontinuous.")}const census=asArray(page["resources"],"native resource census");if(census.length>HTTP_MANAGED_SESSION_STORE_CONTRACT.maxResourcesPerTransaction)throw corrupt2("native resource census is too large.");const seen=new Set;const added=[];for(const item2 of census){const{bytesBase64,...metadata}=asRecord(item2,"native resource");const resource=assertManagedSessionDurableRef(metadata,"native resource");if(bytesBase64!=null||seen.has(resource.resourceId)||["managed-native-journal-snapshot","managed-native-journal-snapshot-page"].includes(resource.kind)||resources.has(resource.resourceId)&&!isDeepStrictEqual(resources.get(resource.resourceId),resource)){throw corrupt2("native resource census conflicts.")}seen.add(resource.resourceId);if(!resources.has(resource.resourceId))added.push(resource);resources.set(resource.resourceId,resource)}const transaction=asRecord(page["transaction"],"native snapshot transaction");if(transaction["journalRevision"]!==after+1)throw corrupt2("native snapshot transaction revision conflicts.");const declared=append(transaction).refs;for(const resource of added){const body=await this.readResource(resource);declared.push(...collectNestedResourceRefs(resource,body))}for(const resource of declared){if(!isDeepStrictEqual(resources.get(resource.resourceId),resource))throw corrupt2("native resource dependency is missing or conflicting.")}previousDigest=ref2.digest;after++}if(safeCounter(result["nextRevision"],"nextRevision")!==after||boolean(result["hasMore"],"hasMore")!==after<snapshot.coveredJournalRevision){throw corrupt2("native snapshot cursor is inconsistent.")}}if(previousDigest!==snapshot.lastPageDigest||resources.size!==snapshot.resourceCount){throw corrupt2("native snapshot digest or resource count conflicts.")}return snapshot}async appendTransaction(records){if(this.pendingAppend!==void 0)await this.settleAppend();try{await this.ensureWriter()}catch(error){const grant2=this.grant;if(isUncertainStoreFailure(error)||grant2!==void 0&&grant2.leaseUntil<=Date.now()&&error instanceof ManagedSessionStoreHttpError&&error.status===409){this.pendingAppend={recordDigest:sha256(encodeRecords(records)),baseRevision:grant2?.journalRevision??0};throw new ManagedSessionAppendUnsettledError(asError(error))}throw error}const grant=this.requireGrant();const{recordBytes,descriptor,commitResources,publicationId,commitBody,needsVersionTwo}=await this.commitBody(records,grant);let committed;const contentionDeadline=Date.now()+this.requestTimeoutMs;for(let attempt=0;;attempt++){try{committed=publicationId===void 0?await this.json(needsVersionTwo?"/transactions:commit-v2":"/transactions:commit","POST",commitBody,contentionDeadline):await this.publicationRequest(`/publications/${encodeURIComponent(publicationId)}/receipts/commit`,commitBody,void 0,contentionDeadline);break}catch(error){await this.annotateWriterRefusal(error);if(descriptor.operation==="manageMcp"&&error instanceof ManagedSessionStoreHttpError&&error.status===409&&["unsupported_feature","turn_active","session_context_busy"].includes(error.remoteCode))throw new ManagedSessionCommitRejectedError(error);if(attempt===0&&error instanceof ManagedSessionStoreHttpError&&(error.status===409&&(error.remoteCode==="workspace_lifecycle_admission_closed"||error.remoteCode==="workspace_lifecycle_claim_fenced"||error.remoteCode==="child_run_lineage_minted"||error.remoteCode==="session_message_lineage_refused"||error.remoteCode==="context_compression_authorization_revoked"||descriptor.operation==="contextCompression"&&error.remoteCode==="workspace_unavailable")||this.lifecycleAuthority&&(error.status===403||error.status===409&&(error.remoteCode.startsWith("workspace_lifecycle_")||error.remoteCode==="workspace_unavailable"))))throw new ManagedSessionCommitRejectedError(error);const uncertain=isUncertainStoreFailure(error);const contentionSpent=error instanceof ManagedSessionStoreHttpError&&(error.contentionExhausted===true||publicationId===void 0&&error.status===503&&error.remoteCode==="tenant_guard_contended"&&contentionDeadline-Date.now()<=250);const exhausted=attempt>=2;const unsettled=!contentionSpent&&(isUncertainStoreFailure(error)||grant.leaseUntil<=Date.now()&&error instanceof ManagedSessionStoreHttpError&&error.status===409);if(!uncertain||contentionSpent||exhausted&&(descriptor.operation!=="renewActivation"||this.renewalStopped||grant.leaseUntil<=Date.now())){if(unsettled){this.pendingAppend={recordDigest:sha256(recordBytes),baseRevision:grant.journalRevision,commitResources,descriptor};throw new ManagedSessionAppendUnsettledError(asError(error))}throw error}await new Promise(resolve=>setTimeout(resolve,exhausted?Math.min(1e3,grant.leaseUntil-Date.now()):250));if(exhausted&&(this.renewalStopped||grant.leaseUntil<=Date.now())){if(unsettled){this.pendingAppend={recordDigest:sha256(recordBytes),baseRevision:grant.journalRevision,commitResources,descriptor};throw new ManagedSessionAppendUnsettledError(asError(error))}throw error}}}const receipt=asRecord(committed,"commit receipt");const revision=safeCounter(receipt["journalRevision"],"journalRevision");if(revision!==grant.journalRevision+1||(publicationId===void 0?string(receipt["transactionId"],"transactionId")!==descriptor.transactionId||string(receipt["commandId"],"commandId")!==descriptor.commandId||string(receipt["operation"],"operation")!==descriptor.operation||safeCounter(receipt["firstSequence"],"firstSequence")!==descriptor.firstSequence||safeCounter(receipt["lastSequence"],"lastSequence")!==descriptor.lastSequence||safeCounter(receipt["committedSequence"],"committedSequence")!==descriptor.lastSequence||nullableDigest(receipt["commitDigest"],"commitDigest")!==descriptor.commitDigest:safeCounter(receipt["historyRevision"],"historyRevision")!==descriptor.lastSequence||!descriptor.refs.some(ref2=>ref2.resourceId===asRecord(receipt["toolOutcomeRef"],"toolOutcomeRef")["resourceId"]))){throw corrupt2("commit receipt does not match the submitted transaction.")}this.grant={...this.requireGrant(),journalRevision:revision,committedSequence:descriptor.lastSequence,lastCommitDigest:descriptor.commitDigest,activationEpoch:descriptor.activationEpoch};this.resources.releaseCommitted(commitResources);for(const ref2 of descriptor.refs)this.publicationAdmissions.delete(ref2.resourceId)}async settleAppend(){const pending=this.pendingAppend;if(pending===void 0)return"absent";let reacquired=false;for(;;){try{if(this.grant===void 0){throw new ManagedSessionRecordError("the HTTP Managed Session writer is not active.")}if(this.grant.leaseUntil<=Date.now())await this.reacquireWriter();const head=parseRestoreHead(await this.json(`/restore?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}`,"GET"));this.requireHeadMatchesGrant(head);if(head.journalRevision===pending.baseRevision){this.pendingAppend=void 0;this.adoptHead(head);return"absent"}if(pending.descriptor===void 0||head.journalRevision!==pending.baseRevision+1){throw new ManagedSessionJournalFencedError(`the journal advanced to revision ${head.journalRevision} past this writer's ${pending.baseRevision} while its append outcome was unknown; the Session needs a takeover.`)}const page=asRecord(await this.json(`/transactions?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}&afterRevision=${pending.baseRevision}&limit=1`,"GET"),"transaction page");const rows=asArray(page["transactions"],"transactions");const stored=parseStoredTransaction(rows[0]);if(stored.journalRevision!==head.journalRevision||stored.recordDigest!==pending.recordDigest){throw new ManagedSessionJournalFencedError("the journal holds a different transaction at this append position; the Session needs a takeover.")}this.resources.releaseCommitted(pending.commitResources??[]);for(const ref2 of pending.descriptor.refs)this.publicationAdmissions.delete(ref2.resourceId);this.pendingAppend=void 0;this.adoptHead(head);return"landed"}catch(error){if(error instanceof ManagedSessionAppendUnsettledError)throw error;const lapsed=this.grant!==void 0&&this.grant.leaseUntil<=Date.now();if(!reacquired&&lapsed&&error instanceof ManagedSessionStoreHttpError&&error.status===409){reacquired=true;continue}if(isUncertainStoreFailure(error))throw new ManagedSessionAppendUnsettledError(asError(error));throw error}}}adoptHead(head){this.grant={...this.requireGrant(),journalRevision:head.journalRevision,committedSequence:head.committedSequence,lastCommitDigest:head.lastCommitDigest,activationEpoch:head.activationEpoch};this.scheduleRenewal()}async commitBody(records,grant){const recordBytes=encodeRecords(records);const descriptor=describeTransaction(records,recordBytes,grant.activationEpoch,this.sessionKey);if(descriptor.previousCommitDigest!==grant.lastCommitDigest){throw new ManagedSessionRecordError("the transaction does not extend the HTTP journal head.")}const commitResources=await this.resources.commitResources(descriptor.refs);const needsVersionTwo=commitResources.some(resource=>HOSTED_RECOVERY_RESOURCE_KINDS.has(resource.kind)||resource.kind==="managed-action-options"&&resource.bytesBase64&&JSON.parse(Buffer.from(resource.bytesBase64,"base64").toString("utf8")).v===3)||records.some(record=>{const event=record.managedSession;return event?.kind==="message.retracted"&&event.payload?.["sourceBootId"]!==void 0});if(needsVersionTwo&&grant.supportedStorageVersion<2)throw new ManagedSessionRecordError("Managed Session Store does not support Hosted recovery storage version 2.");const publicationIds=new Set(descriptor.refs.flatMap(ref2=>{const id2=this.publicationAdmissions.get(ref2.resourceId);return id2===void 0?[]:[id2]}));if(publicationIds.size>1){throw new ManagedSessionRecordError("Transaction mixes publication admissions.")}const publicationId=[...publicationIds][0];const commitBody={workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,expectedJournalRevision:grant.journalRevision,expectedCommittedSequence:grant.committedSequence,transactionId:descriptor.transactionId,operation:descriptor.operation,commandId:descriptor.commandId,contentDigest:descriptor.contentDigest,firstSequence:descriptor.firstSequence,lastSequence:descriptor.lastSequence,eventCount:descriptor.eventCount,eventsDigest:descriptor.eventsDigest,previousCommitDigest:descriptor.previousCommitDigest,commitDigest:descriptor.commitDigest,activationEpoch:descriptor.activationEpoch,latestCheckpointResourceId:descriptor.latestCheckpointResourceId,recordCount:records.length,recordBytesBase64:recordBytes.toString("base64"),recordDigest:sha256(recordBytes),resources:commitResources};return{recordBytes,descriptor,commitResources,publicationId,commitBody,needsVersionTwo}}joinOriginalCsiWriter(){if(this.retirementJoin)return this.retirementJoin;this.stopRenewal();const renewal=this.renewPromise;if(this.acquirePromise||this.pendingAppend)return Promise.reject(corrupt2("original CSI writer has unresolved authority."));this.retirementJoin=(async()=>{await renewal;if(this.writerRenewalFailures.length)throw this.writerRenewalFailures[0];const grant=this.requireGrant();if(grant.writerGeneration!==1||grant.activationEpoch!==1||grant.leaseUntil<=Date.now()){throw corrupt2("original CSI writer cannot prepare retirement.")}})();return this.retirementJoin}async prepareOriginalCsiCommit(records){if(!this.retirementJoin)throw corrupt2("original CSI writer has not joined.");await this.retirementJoin;const recordDigest=sha256(encodeRecords(records));if(this.preparedRetirement){if(recordDigest!==this.preparedRetirement.recordDigest)throw corrupt2("original CSI preparation conflicts.");const{commitBodyBase64:commitBodyBase642,preparedCommitSha256:preparedCommitSha2562}=this.preparedRetirement;return{commitBodyBase64:commitBodyBase642,preparedCommitSha256:preparedCommitSha2562}}const{descriptor,commitResources,publicationId,commitBody}=await this.commitBody(records,this.requireGrant());if(descriptor.operation!=="releaseActivation"||descriptor.eventCount!==1||records.length!==2||descriptor.latestCheckpointResourceId!==null||publicationId!==void 0||commitResources.length!==1||commitResources[0].kind!=="managed-activation-boundary"||commitResources[0].bytesBase64===void 0){throw corrupt2("original CSI release preparation is invalid.")}const bytes=Buffer.from(JSON.stringify(commitBody),"utf8");this.preparedRetirement={recordDigest,commitBodyBase64:bytes.toString("base64"),preparedCommitSha256:sha256(bytes)};const{commitBodyBase64,preparedCommitSha256}=this.preparedRetirement;return{commitBodyBase64,preparedCommitSha256}}async completeOriginalCsiRetirement(retirementId){assertManagedSessionStableId(retirementId,"retirementId");const readStatus=__name((value,previous)=>{const status2=asRecord(value,"CSI retirement status");const stage=status2["stage"];if(Object.keys(status2).sort().join(",")!=="cutSha256,finalizeReceiptSha256,format,frozenRequestSha256,progressVersion,retirementId,stage"||status2["format"]!=="qwen-csi-application-retirement/1"||status2["retirementId"]!==retirementId||!["SETTLING","FROZEN","CUT","DRAINED"].includes(String(stage))){throw corrupt2("original CSI retirement status conflicts.")}const progressVersion=safeCounter(status2["progressVersion"],"progressVersion");const frozenRequestSha256=nullableDigest(status2["frozenRequestSha256"],"frozenRequestSha256");const cutSha256=nullableDigest(status2["cutSha256"],"cutSha256");const finalizeReceiptSha256=nullableDigest(status2["finalizeReceiptSha256"],"finalizeReceiptSha256");if(progressVersion!==["SETTLING","FROZEN","CUT","DRAINED"].indexOf(String(stage))+1||stage==="SETTLING"!==(frozenRequestSha256===null)||["SETTLING","FROZEN"].includes(String(stage))!==(cutSha256===null)||stage==="DRAINED"!==(finalizeReceiptSha256!==null)){throw corrupt2("original CSI retirement progress is incomplete.")}if(previous&&(progressVersion<previous.progressVersion||previous.frozenRequestSha256!==null&&frozenRequestSha256!==previous.frozenRequestSha256||previous.cutSha256!==null&&cutSha256!==previous.cutSha256)){throw corrupt2("original CSI retirement status changed its saved progress.")}return{format:"qwen-csi-application-retirement/1",retirementId,stage,progressVersion,frozenRequestSha256,cutSha256,finalizeReceiptSha256}},"readStatus");let status=readStatus(await this.json(`/csi-retirement?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}&retirementId=${encodeURIComponent(retirementId)}`,"GET"));const identity={format:"qwen-csi-application-retirement/1",workspaceId:this.sessionKey.workspaceId,retirementId};if(status.stage==="SETTLING"){if(!this.preparedRetirement)throw corrupt2("original CSI retirement has no prepared body.");status=readStatus(await this.json("/csi-retirement:freeze","POST",{...identity,commitBodyBase64:this.preparedRetirement.commitBodyBase64}),status);if(status.stage==="SETTLING")throw corrupt2("original CSI retirement did not freeze.")}if(status.stage==="FROZEN"){status=readStatus(await this.json("/csi-retirement:cut","POST",{...identity,frozenRequestSha256:status.frozenRequestSha256}),status);if(status.stage!=="CUT"&&status.stage!=="DRAINED")throw corrupt2("original CSI retirement did not commit its cut.")}if(status.stage==="CUT"){status=readStatus(await this.json("/csi-retirement:finalize","POST",{...identity,cutSha256:status.cutSha256}),status)}if(status.stage!=="DRAINED")throw corrupt2("original CSI retirement has not drained.");return status}async publicationOwner(){await this.ensureWriter();return{writerId:this.writerId,writerGeneration:this.requireGrant().writerGeneration}}rememberAdmission(publicationId,ref2){assertManagedSessionStableId(publicationId,"publicationId");const checked=assertManagedSessionDurableRef(ref2,"admission ref");if(checked.kind!=="managed-tool-outcome")throw new ManagedSessionRecordError("Publication admission kind is invalid.");const previous=this.publicationAdmissions.get(checked.resourceId);if(previous!==void 0&&previous!==publicationId)throw new ManagedSessionRecordError("Publication admission conflicts.");this.publicationAdmissions.set(checked.resourceId,publicationId)}async publicationRequest(path,body,token,contentionDeadline){await this.ensureWriter();if(!/^\/(?:grants|receipts\/verify|publications\/[a-z0-9_-]{1,128}\/(?:finished|admissions\/prepare|receipts\/commit))$/u.test(path))throw new ManagedSessionRecordError("Publication owner path is invalid.");const readOnly=path.endsWith("/finished");const method=readOnly?"GET":"POST";return this.withRetry(readOnly,method,path,async timeoutMs=>{const url=`${this.baseUrl}/internal/managed-tool-publications/v1/sessions/${encodeURIComponent(this.sessionKey.sessionId)}${path}?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}`;const response=await this.fetchFn(url,{method,headers:{Accept:"application/json","X-Qwen-Managed-Max-Readable-Storage-Version":"2",...readOnly?{}:{"Content-Type":"application/json"},[HTTP_MANAGED_SESSION_STORE_CONTRACT.tenantHeader]:this.sessionKey.tenantId,[HTTP_MANAGED_SESSION_STORE_CONTRACT.writerTokenHeader]:this.writerToken,"X-Qwen-Managed-Writer-Id":this.writerId,"X-Qwen-Managed-Writer-Generation":String(this.requireGrant().writerGeneration),...token?{"X-Qwen-Tool-Publication-Token":token}:{}},...readOnly?{}:{body:JSON.stringify(body)},redirect:"error",signal:AbortSignal.timeout(timeoutMs)});if(!response.ok){const error=await readHttpError(response);throw new ManagedSessionStoreHttpError(response.status,error.code,error.message,void 0,error.details,`${method} ${path}`)}if(response.headers.get("Cache-Control")!=="no-store")throw corrupt2("Publication response is missing Cache-Control: no-store.");return readBoundedPublicationJson(response)},contentionDeadline)}async readResource(ref2){await this.ensureWriter();const path=`/resources/${encodeURIComponent(ref2.resourceId)}?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}`;return this.withRetry(true,"GET",path,async timeoutMs=>{const response=await this.request(path,"GET",void 0,timeoutMs,"application/octet-stream, application/json");if(!response.body)throw corrupt2("resource response has no body.");const reader=response.body.getReader();const chunks=[];let length=0;try{while(true){let chunk;try{chunk=await reader.read()}catch(error){if(error instanceof TypeError||error instanceof DOMException){throw new ManagedSessionStoreTransportError(`Managed Session Store response failed: ${error.message}.`)}throw error}if(chunk.done)break;length+=chunk.value.byteLength;if(length>ref2.byteLength){await reader.cancel();throw corrupt2("resource response exceeds its declared length.")}chunks.push(chunk.value)}}finally{reader.releaseLock()}const bytes=Buffer.concat(chunks);if(response.headers.get("X-Qwen-Resource-Kind")!==ref2.kind||response.headers.get("X-Qwen-Resource-Schema-Version")!==String(ref2.schemaVersion)||response.headers.get("X-Qwen-Resource-Digest")!==ref2.digest||bytes.byteLength!==ref2.byteLength||sha256(bytes)!==ref2.digest){throw corrupt2(`resource ${ref2.resourceId} failed integrity verification.`)}return bytes})}async assertWritable(){await this.renewWriter()}async publishToolResult(kind,source,resourceId=randomUUID()){const limit=HOSTED_TOOL_RESULT_RESOURCE_LIMITS[kind];if(!Object.hasOwn(HOSTED_TOOL_RESULT_RESOURCE_LIMITS,kind)||source.byteLength<1||source.byteLength>limit){throw new ManagedSessionRecordError("Unsupported tool result resource or size.")}assertManagedSessionStableId(resourceId,"tool result resourceId");const bytes=Buffer.from(source);const ref2={resourceId,kind,schemaVersion:1,byteLength:bytes.length,digest:sha256(bytes)};await this.ensureWriter();const grant=this.requireGrant();const receipt=assertManagedSessionDurableRef(await this.json("/tool-results:publish","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,...ref2,bytesBase64:bytes.toString("base64")}),"tool result publication");requireSameRef(receipt,ref2);return ref2}async blockRecovery(request){await this.ensureWriter();const grant=this.requireGrant();const receipt=asRecord(await this.json("/recovery:block","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,recoveryStatus:request.status,recoveryDetailCode:request.detailCode}),"recovery state receipt");if(safeCounter(receipt["writerGeneration"],"writerGeneration")!==grant.writerGeneration||string(receipt["recoveryStatus"],"recoveryStatus")!==request.status||string(receipt["recoveryDetailCode"],"recoveryDetailCode")!==request.detailCode){throw corrupt2("recovery state receipt does not match the active writer request.")}}async seal(){if(this.retirementJoin)throw corrupt2("original CSI retirement owns the final boundary.");await this.acquirePromise?.catch(()=>void 0);return this.sealGrant()}async sealGrant(){if(this.sealed)return;const grant=this.grant;this.stopWriterRenewal();if(grant===void 0){this.sealed=true;this.resources.clear();return}const receipt=asRecord(await this.json("/writers:seal","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration}),"seal receipt");if(safeCounter(receipt["writerGeneration"],"writerGeneration")!==grant.writerGeneration||string(receipt["state"],"state")!=="SEALED"){throw corrupt2("seal receipt does not match the active writer.")}this.sealed=true;this.stopRenewal();this.resources.clear()}async stopLocal(){this.locallyStopped=true;this.stopRenewal();await this.renewPromise?.catch(()=>void 0);await this.acquirePromise?.catch(()=>void 0)}async releaseOwnership(request){assertManagedSessionStableId(request.operationId,"release operationId");assertManagedSessionStableId(request.instanceId,"release instanceId");if(request.bootId!==this.writerId||!Number.isSafeInteger(request.placementEpoch)||request.placementEpoch<1)throw corrupt2("ownership release does not match the writer.");if(!this.ownershipRelease){const grant=this.requireGrant();if(request.commitProof.lastCommitSequence!==grant.committedSequence||request.commitProof.committedPrefixHash!==grant.lastCommitDigest)throw corrupt2("ownership release does not match the committed head.");this.stopWriterRenewal();this.ownershipRelease={request:{...request,commitProof:{...request.commitProof}},body:{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,journalRevision:grant.journalRevision,...request,commitProof:{...request.commitProof}}}}const release=this.ownershipRelease;if(request.operationId!==release.request.operationId||request.instanceId!==release.request.instanceId||request.bootId!==release.request.bootId||request.placementEpoch!==release.request.placementEpoch||request.commitProof.lastCommitSequence!==release.request.commitProof.lastCommitSequence||request.commitProof.committedPrefixHash!==release.request.commitProof.committedPrefixHash)throw corrupt2("ownership release identity changed.");if(release.receipt)return release.receipt;await this.renewPromise?.catch(()=>void 0);const value=asRecord(await this.json("/writers:release-ownership","POST",release.body),"ownership release receipt");const proof=asRecord(value["commitProof"],"release commit proof");const receipt={format:"qwen-hosted-harness-release/1",state:"RELEASED",tenantId:string(value["tenantId"],"tenantId"),workspaceId:string(value["workspaceId"],"workspaceId"),sessionId:string(value["sessionId"],"sessionId"),operationId:string(value["operationId"],"operationId"),instanceId:string(value["instanceId"],"instanceId"),bootId:string(value["bootId"],"bootId"),placementEpoch:safeCounter(value["placementEpoch"],"placementEpoch"),writerGeneration:safeCounter(value["writerGeneration"],"writerGeneration"),journalRevision:safeCounter(value["journalRevision"],"journalRevision"),committedSequence:safeCounter(value["committedSequence"],"committedSequence"),commitProof:{lastCommitSequence:safeCounter(proof["lastCommitSequence"],"lastCommitSequence"),committedPrefixHash:digest2(proof["committedPrefixHash"],"committedPrefixHash")}};if(value["format"]!==receipt.format||value["state"]!==receipt.state||!managedSessionKeysEqual(receipt,this.sessionKey)||receipt.operationId!==request.operationId||receipt.instanceId!==request.instanceId||receipt.bootId!==request.bootId||receipt.placementEpoch!==request.placementEpoch||receipt.writerGeneration!==release.body["writerGeneration"]||receipt.journalRevision!==release.body["journalRevision"]||receipt.committedSequence!==request.commitProof.lastCommitSequence||receipt.commitProof.lastCommitSequence!==request.commitProof.lastCommitSequence||receipt.commitProof.committedPrefixHash!==request.commitProof.committedPrefixHash)throw corrupt2("ownership release receipt does not match the request.");release.receipt=receipt;this.sealed=true;this.resources.clear();return receipt}async quiesceOwnership(placement){const grant=this.requireGrant();const response=asRecord(await this.json("/writers:quiesce-ownership","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,...placement}),"ownership quiesce receipt");if(response["state"]!=="QUIESCING")throw corrupt2("ownership quiesce was not acknowledged.")}stopWriterRenewal(){this.renewalStopped=true;this.stopRenewal()}async ensureWriter(){if(this.ownershipRelease)throw corrupt2("ownership release has fenced this writer.");if(this.retirementJoin)throw corrupt2("original CSI writer admission is closed.");if(this.acquirePromise!==void 0)await this.acquirePromise.catch(()=>void 0);const grant=this.requireGrant();if(grant.leaseUntil-Date.now()<=this.leaseDurationMs/3){await this.renewWriter()}}async reacquireWriter(){const expired=this.grant;this.stopRenewal();await this.renewPromise?.catch(()=>void 0);this.grant=void 0;const acquire=(async()=>{await this.acquireWriter();if(this.sealed||this.locallyStopped)await this.sealGrant()})();this.acquirePromise=acquire;try{await acquire}catch(error){this.grant=expired;throw error}finally{if(this.acquirePromise===acquire)this.acquirePromise=void 0}}renewWriter(){if(this.ownershipRelease)return Promise.reject(corrupt2("ownership release has fenced this writer."));if(this.retirementJoin)return Promise.reject(corrupt2("original CSI writer renewal is closed."));if(this.locallyStopped){return Promise.reject(new ManagedSessionRecordError("the HTTP Managed Session writer is locally stopped."))}if(this.renewPromise!==void 0){if(this.lifecycleAuthority?.operationId===this.renewingAuthority?.operationId&&this.lifecycleAuthority?.claimGeneration===this.renewingAuthority?.claimGeneration)return this.renewPromise;const renewAgain=__name(()=>this.renewWriter(),"renewAgain");return this.renewPromise.then(renewAgain,renewAgain)}const grant=this.requireGrant();this.renewingAuthority=this.lifecycleAuthority?{...this.lifecycleAuthority}:void 0;const renewal=(async()=>{const renewed=parseWriterGrant(await this.json("/writers:renew","POST",{workspaceId:this.sessionKey.workspaceId,writerId:this.writerId,writerGeneration:grant.writerGeneration,leaseMillis:this.leaseDurationMs}));if(renewed.writerGeneration!==grant.writerGeneration){throw corrupt2("writer generation changed during renewal.")}this.grant={...this.requireGrant(),leaseUntil:renewed.leaseUntil,supportedStorageVersion:renewed.supportedStorageVersion};this.scheduleRenewal()})();const noted=renewal.catch(async error=>{this.writerRenewalFailures.push(error);await this.annotateWriterRefusal(error);throw error});this.renewPromise=noted.finally(()=>{this.renewPromise=void 0});return this.renewPromise}async annotateWriterRefusal(error){if(!(error instanceof ManagedSessionStoreHttpError)||error.status!==409)return;const grant=this.grant;const grantView=grant===void 0?"grant=absent":`grantGeneration=${grant.writerGeneration} grantRevision=${grant.journalRevision} grantCommitted=${grant.committedSequence}`;let headView;try{const head=parseRestoreHead(await this.json(`/restore?workspaceId=${encodeURIComponent(this.sessionKey.workspaceId)}`,"GET"));headView=`headGeneration=${head.writerGeneration} headRevision=${head.journalRevision} headCommitted=${head.committedSequence} state=${head.state}`}catch(probe){headView=`headProbeFailed(${probe instanceof Error?probe.message:String(probe)})`}const detail=`writerId=${this.writerId} ${grantView} ${headView}`;error.writerRefusalContext=detail;debugLogger.debug(`Managed Session Store writer refused: session=${this.sessionKey.sessionId} ${detail}`)}scheduleRenewal(retrying=false){this.stopRenewal();if(this.renewalStopped||this.sealed||this.locallyStopped||this.retirementJoin||this.grant===void 0||this.grant.leaseUntil<=Date.now())return;const delay=Math.max(250,Math.min(retrying?1e3:Math.floor(this.leaseDurationMs/2),this.grant.leaseUntil-Date.now()-500));this.renewTimer=setTimeout(()=>{void this.renewWriter().catch(error=>{if(error instanceof ManagedSessionStoreTransportError||error instanceof ManagedSessionStoreHttpError&&[500,502,503,504].includes(error.status)){this.scheduleRenewal(true)}})},delay);this.renewTimer.unref()}stopRenewal(){if(this.renewTimer!==void 0)clearTimeout(this.renewTimer);this.renewTimer=void 0}requireHeadMatchesGrant(head){const grant=this.requireGrant();if(head.state!=="ACTIVE"||![1,2].includes(head.storageVersion)||head.writerGeneration!==grant.writerGeneration||head.recoveryStatus!=="READY"||head.compactedThroughRevision!==0){throw corrupt2("restore head is not readable by this writer.")}if(head.journalRevision<grant.journalRevision||head.committedSequence<grant.committedSequence){throw corrupt2(`restore head regressed below this writer's committed position (head ${head.journalRevision}/${head.committedSequence} < grant ${grant.journalRevision}/${grant.committedSequence}).`)}}requireGrant(){if(this.grant===void 0||this.sealed||this.locallyStopped){throw new ManagedSessionRecordError("the HTTP Managed Session writer is not active.")}return this.grant}async json(path,method,body,contentionDeadline){return this.withRetry(method==="GET"||path==="/writers:renew",method,path,async timeoutMs=>{const response=await this.request(path,method,body,timeoutMs);try{return await response.json()}catch(error){if(error instanceof TypeError||error instanceof DOMException&&["AbortError","TimeoutError"].includes(error.name)){throw new ManagedSessionStoreTransportError(`Managed Session Store response failed: ${error.message}.`)}throw corrupt2(`Managed Session Store returned invalid JSON: ${error instanceof Error?error.message:String(error)}.`)}},contentionDeadline)}async withRetry(retryable,method,path,run,contentionDeadline){const deadline=Date.now()+this.requestTimeoutMs;const guardDeadline=Math.min(deadline,contentionDeadline??deadline);let attempt=0;let guardRetries=0;let contendedRefusal;for(;;){attempt++;try{const attemptDeadline=guardRetries>0?guardDeadline:deadline;return await run(Math.max(1,attemptDeadline-Date.now()))}catch(error){const contended=error instanceof ManagedSessionStoreHttpError&&error.status===503&&error.remoteCode==="tenant_guard_contended";if(contended)contendedRefusal=error;if(contended&&guardDeadline-Date.now()>250){debugLogger.debug(`Managed Session Store ${method} ${path} attempt ${attempt} found the tenant guard contended; retrying.`);guardRetries++;await new Promise(resolve=>setTimeout(resolve,250));continue}const transient=error instanceof ManagedSessionStoreTransportError||error instanceof ManagedSessionStoreHttpError&&[500,502,503,504].includes(error.status);if(!retryable||!transient||contended||attempt-guardRetries>=3||Date.now()>=deadline){if(contendedRefusal!==void 0&&guardDeadline-Date.now()<=250){throw new ManagedSessionStoreHttpError(contendedRefusal.status,contendedRefusal.remoteCode,attempt>1?`Managed Session Store ${method} ${path} failed after ${attempt} attempts: ${contendedRefusal.message}`:`Managed Session Store ${method} ${path} failed: ${contendedRefusal.message}`,guardRetries>0||void 0,contendedRefusal.details,contendedRefusal.route)}if(transient){const detail=attempt>1?`Managed Session Store ${method} ${path} failed after ${attempt} attempts: ${error instanceof Error?error.message:String(error)}`:`Managed Session Store ${method} ${path} failed: ${error instanceof Error?error.message:String(error)}`;if(error instanceof ManagedSessionStoreHttpError)throw new ManagedSessionStoreHttpError(error.status,error.remoteCode,detail,void 0,error.details,error.route);if(error instanceof ManagedSessionStoreTransportError)throw new ManagedSessionStoreTransportError(detail)}throw error}debugLogger.debug(`Managed Session Store ${method} ${path} attempt ${attempt} failed (${error instanceof Error?error.message:String(error)}); retrying.`);await new Promise(resolve=>setTimeout(resolve,200*(attempt-guardRetries)+Math.floor(Math.random()*100)))}}}async request(path,method,body,timeoutMs=this.requestTimeoutMs,accept="application/json"){if(this.ownershipRelease&&path!=="/writers:release-ownership")throw corrupt2("ownership release has fenced this writer.");if(this.locallyStopped){throw new ManagedSessionRecordError("the HTTP Managed Session writer is locally stopped.")}let response;try{response=await this.fetchFn(`${this.sessionUrl()}${path}`,{method,redirect:"error",headers:{Accept:accept,"X-Qwen-Managed-Max-Readable-Storage-Version":"2",[HTTP_MANAGED_SESSION_STORE_CONTRACT.tenantHeader]:this.sessionKey.tenantId,[HTTP_MANAGED_SESSION_STORE_CONTRACT.writerTokenHeader]:this.writerToken,...this.lifecycleAuthority?{"X-Qwen-Lifecycle-Operation-Id":this.lifecycleAuthority.operationId,"X-Qwen-Lifecycle-Claim-Generation":String(this.lifecycleAuthority.claimGeneration)}:{},...body===void 0?{}:{"Content-Type":"application/json"}},...body===void 0?{}:{body:JSON.stringify(body)},signal:AbortSignal.timeout(timeoutMs)})}catch(error){throw new ManagedSessionStoreTransportError(`Managed Session Store request failed: ${error instanceof Error?error.message:String(error)}.`)}if(!response.ok){const error=await readHttpError(response);throw new ManagedSessionStoreHttpError(response.status,error.code,error.message,void 0,error.details,`${method} ${path}`)}if(response.headers.get("Cache-Control")!=="no-store"){throw corrupt2("Managed Session Store response is missing Cache-Control: no-store.")}return response}sessionUrl(){return`${this.baseUrl}/internal/managed-session-store/v1/sessions/${encodeURIComponent(this.sessionKey.sessionId)}`}};function describeTransaction(records,bytes,currentActivationEpoch,expectedSessionKey){const possibleHeader=records.length===2?envelope(records[1],"possible genesis header record"):void 0;if(possibleHeader?.["subtype"]===MANAGED_SESSION_HEADER_SUBTYPE){const first=envelope(records[0],"genesis engine record");if(first["subtype"]!=="session_execution_engine"){throw new ManagedSessionRecordError("the genesis transaction must contain the engine and Managed header.")}const header=parseManagedSessionHeader(possibleHeader["managedSession"]);if(!managedSessionKeysEqual(header.sessionKey,expectedSessionKey)||first["sessionId"]!==expectedSessionKey.sessionId||possibleHeader["sessionId"]!==expectedSessionKey.sessionId){throw new ManagedSessionRecordError("the genesis transaction belongs to a different session.")}const digest3=sha256(bytes);return{transactionId:`session.create:${header.sessionKey.sessionId}`,operation:"session.create",commandId:`session.create:${header.sessionKey.sessionId}`,contentDigest:digest3,firstSequence:0,lastSequence:0,eventCount:0,eventsDigest:null,previousCommitDigest:null,commitDigest:null,activationEpoch:currentActivationEpoch,latestCheckpointResourceId:null,refs:dedupeRefs([header.definitionRef,header.rootSnapshotRef,...header.baseTranscriptProof===void 0?[]:[header.baseTranscriptProof]])}}if(records.length<2){throw new ManagedSessionRecordError("a Managed Session transaction must include events and a commit marker.")}const eventRecords=records.slice(0,-1).map((record,index)=>{const parsed=envelope(record,`event record ${index+1}`);if(parsed["subtype"]!==MANAGED_SESSION_EVENT_SUBTYPE){throw new ManagedSessionRecordError("a Managed Session transaction contains a non-event record.")}const event=parseManagedSessionEvent(parsed["managedSession"]);if(!managedSessionKeysEqual(event.sessionKey,expectedSessionKey)||parsed["sessionId"]!==expectedSessionKey.sessionId){throw new ManagedSessionRecordError("the event transaction belongs to a different session.")}return event});const markerRecord=envelope(records[records.length-1],"commit record");if(markerRecord["subtype"]!==MANAGED_SESSION_COMMIT_SUBTYPE){throw new ManagedSessionRecordError("a Managed Session transaction must end with a commit marker.")}if(markerRecord["sessionId"]!==expectedSessionKey.sessionId){throw new ManagedSessionRecordError("the commit marker belongs to a different session.")}const marker=parseManagedSessionCommitMarker(markerRecord["managedSession"]);let activationEpoch=currentActivationEpoch;let latestCheckpointResourceId=null;for(const event of eventRecords){if(event.kind==="activation.changed"){activationEpoch=event.payload["epoch"]}if(event.kind==="checkpoint.committed"){const ref2=assertManagedSessionDurableRef(event.payload["stateRef"],"checkpoint state");if(ref2.kind==="managed-checkpoint"){latestCheckpointResourceId=ref2.resourceId}}}return{transactionId:marker.transactionId,operation:marker.operation,commandId:marker.commandId,contentDigest:marker.contentDigest,firstSequence:marker.firstSequence,lastSequence:marker.lastSequence,eventCount:marker.eventCount,eventsDigest:marker.eventsDigest,previousCommitDigest:marker.previousCommitDigest,commitDigest:managedToolDigest(marker,MANAGED_SESSION_LIMITS.maxCommitMarkerBytes),activationEpoch,latestCheckpointResourceId,refs:dedupeRefs(eventRecords.flatMap(event=>managedSessionEventRefs(event)))}}__name(describeTransaction,"describeTransaction");function dedupeRefs(found){const refs=new Map;for(const ref2 of found){const existing=refs.get(ref2.resourceId);if(existing!==void 0)requireSameRef(existing,ref2);else refs.set(ref2.resourceId,ref2)}return[...refs.values()]}__name(dedupeRefs,"dedupeRefs");function collectRefs(records){const refs=new Map;const pending=[...records];while(pending.length>0){const value=pending.pop();if(Array.isArray(value)){pending.push(...value);continue}if(value===null||typeof value!=="object")continue;const record=value;if(Object.hasOwn(record,"resourceId")&&Object.hasOwn(record,"kind")&&Object.hasOwn(record,"schemaVersion")&&Object.hasOwn(record,"byteLength")&&Object.hasOwn(record,"digest")){const ref2=assertManagedSessionDurableRef(record,"resource ref");const existing=refs.get(ref2.resourceId);if(existing!==void 0)requireSameRef(existing,ref2);else refs.set(ref2.resourceId,ref2);continue}pending.push(...Object.values(record))}return[...refs.values()]}__name(collectRefs,"collectRefs");function encodeRecords(records){if(records.length<1){throw new ManagedSessionRecordError("a Managed Session transaction must contain records.")}const bytes=Buffer.from(records.map(record=>JSON.stringify(record)).join("\n")+"\n","utf8");if(bytes.byteLength>MANAGED_SESSION_LIMITS.maxTransactionBytes){throw new ManagedSessionRecordError(`transaction exceeds ${MANAGED_SESSION_LIMITS.maxTransactionBytes} bytes.`)}return bytes}__name(encodeRecords,"encodeRecords");function decodeRecords(bytes){const text=bytes.toString("utf8");if(!text.endsWith("\n"))throw corrupt2("transaction is not complete JSONL.");return text.slice(0,-1).split("\n").map(line=>parseManagedSessionRecordJson(line,MANAGED_SESSION_LIMITS.maxEventBytes))}__name(decodeRecords,"decodeRecords");function envelope(value,label){const parsed=parseManagedSessionRecordJson(JSON.stringify(value),MANAGED_SESSION_LIMITS.maxEventBytes);return asRecord(parsed,label)}__name(envelope,"envelope");function parseStoredTransaction(value){const record=asRecord(value,"stored transaction");if(string(record["recordEncoding"],"recordEncoding")!=="identity"){throw corrupt2("stored transaction encoding is not supported.")}return{journalRevision:safeCounter(record["journalRevision"],"journalRevision"),transactionId:string(record["transactionId"],"transactionId"),operation:string(record["operation"],"operation"),commandId:string(record["commandId"],"commandId"),contentDigest:digest2(record["contentDigest"],"contentDigest"),firstSequence:safeCounter(record["firstSequence"],"firstSequence"),lastSequence:safeCounter(record["lastSequence"],"lastSequence"),eventCount:safeCounter(record["eventCount"],"eventCount"),eventsDigest:nullableDigest(record["eventsDigest"],"eventsDigest"),previousCommitDigest:nullableDigest(record["previousCommitDigest"],"previousCommitDigest"),commitDigest:nullableDigest(record["commitDigest"],"commitDigest"),activationEpoch:safeCounter(record["activationEpoch"],"activationEpoch"),latestCheckpointResourceId:nullableString(record["latestCheckpointResourceId"],"latestCheckpointResourceId"),recordBytesBase64:string(record["recordBytesBase64"],"recordBytesBase64"),byteLength:safeCounter(record["byteLength"],"byteLength"),recordDigest:digest2(record["recordDigest"],"recordDigest")}}__name(parseStoredTransaction,"parseStoredTransaction");function requireStoredTransactionMatches(stored,descriptor){if(stored.transactionId!==descriptor.transactionId||stored.operation!==descriptor.operation||stored.commandId!==descriptor.commandId||stored.contentDigest!==descriptor.contentDigest||stored.firstSequence!==descriptor.firstSequence||stored.lastSequence!==descriptor.lastSequence||stored.eventCount!==descriptor.eventCount||stored.eventsDigest!==descriptor.eventsDigest||stored.previousCommitDigest!==descriptor.previousCommitDigest||stored.commitDigest!==descriptor.commitDigest||stored.activationEpoch!==descriptor.activationEpoch||stored.latestCheckpointResourceId!==descriptor.latestCheckpointResourceId){throw corrupt2("stored transaction metadata does not match its records.")}}__name(requireStoredTransactionMatches,"requireStoredTransactionMatches");function parseWriterGrant(value){const record=asRecord(value,"writer grant");return{activationLeaseRenewal:record["activationLeaseRenewal"]===true,...record["activationLease"]==null?{}:{activationLease:parseActivationLease(record["activationLease"])},supportedStorageVersion:record["supportedStorageVersion"]===void 0?1:safeCounter(record["supportedStorageVersion"],"supportedStorageVersion"),writerGeneration:safeCounter(record["writerGeneration"],"writerGeneration"),leaseUntil:safeCounter(record["leaseUntil"],"leaseUntil"),journalRevision:safeCounter(record["journalRevision"],"journalRevision"),committedSequence:safeCounter(record["committedSequence"],"committedSequence"),lastCommitDigest:nullableDigest(record["lastCommitDigest"],"lastCommitDigest"),activationEpoch:safeCounter(record["activationEpoch"],"activationEpoch")}}__name(parseWriterGrant,"parseWriterGrant");function parseRestoreHead(value){const record=asRecord(value,"restore head");return{...record["activationLease"]==null?{}:{activationLease:parseActivationLease(record["activationLease"])},state:string(record["state"],"state"),storageVersion:safeCounter(record["storageVersion"],"storageVersion"),writerGeneration:safeCounter(record["writerGeneration"],"writerGeneration"),journalRevision:safeCounter(record["journalRevision"],"journalRevision"),committedSequence:safeCounter(record["committedSequence"],"committedSequence"),lastCommitDigest:nullableDigest(record["lastCommitDigest"],"lastCommitDigest"),activationEpoch:safeCounter(record["activationEpoch"],"activationEpoch"),latestCheckpointResourceId:nullableString(record["latestCheckpointResourceId"],"latestCheckpointResourceId"),compactedThroughRevision:safeCounter(record["compactedThroughRevision"],"compactedThroughRevision"),recoveryStatus:string(record["recoveryStatus"],"recoveryStatus"),recoveryDetailCode:nullableString(record["recoveryDetailCode"],"recoveryDetailCode")}}__name(parseRestoreHead,"parseRestoreHead");function parseActivationLease(value){const lease=asRecord(value,"activation lease");return{activationId:assertManagedSessionStableId(string(lease["activationId"],"activationId"),"activationId"),epoch:safeCounter(lease["epoch"],"activation epoch"),renewalSeq:safeCounter(lease["renewalSeq"],"activation renewalSeq"),expiresAt:safeCounter(lease["expiresAt"],"activation expiresAt")}}__name(parseActivationLease,"parseActivationLease");function applyActivationLease(scan,lease){if(!lease)return scan;const activation=scan.activation;if(!activation||activation.phase!=="active"||activation.activationId!==lease.activationId||activation.epoch!==lease.epoch||lease.renewalSeq<activation.renewalSeq||lease.expiresAt<activation.expiresAt)throw corrupt2("activation lease conflicts with the journal.");return{...scan,activation:{...activation,...lease}}}__name(applyActivationLease,"applyActivationLease");function collectNestedResourceRefs(ref2,bytes){if(ref2.kind===MANAGED_MESSAGE_CHUNKS_KIND){return managedMessageChunkParts(ref2.kind,bytes)}if(ref2.kind==="managed-tool-outcome-chunks"){const manifest=asRecord(JSON.parse(bytes.toString("utf8")),"outcome chunks");if(Object.keys(manifest).length!==1||!("parts"in manifest)){throw corrupt2("outcome chunk manifest fields conflict.")}const parts=asArray(manifest["parts"],"outcome parts");if(parts.length<2||parts.length>69){throw corrupt2("outcome chunk count exceeds its bounds.")}return parts.map(part=>{const checked=assertManagedSessionDurableRef(part,"outcome chunk part");if(checked.kind!=="managed-tool-outcome-part"){throw corrupt2("outcome chunks must reference outcome parts.")}return checked})}if(ref2.kind===CHECKPOINT_HISTORY_KIND)return collectRefs([checkpointHistoryPage(bytes)]);if(ref2.kind==="managed-checkpoint"){if(isPagedHarnessCheckpoint(bytes))return collectRefs([checkpointStorageBody(bytes)]);const parsed=tryParseHarnessCheckpointV1(bytes);return parsed.ok?collectRefs([parsed.checkpoint]):[]}if(ref2.kind==="managed-file_history"){const record=asRecord(parseManagedSessionRecordJson(bytes.toString("utf8"),MANAGED_SESSION_LIMITS.maxEventBytes),"file history");return record["schemaVersion"]===2&&record["profile"]==="csi-files-retirement/1"?collectRefs([record["preparation"]]):[]}if(HOSTED_RECOVERY_RESOURCE_KINDS.has(ref2.kind)){return hostedRecoveryReferences(parseHostedRecoveryResource(bytes,void 0,ref2.kind))}if(EXTENSION_RECORD_KINDS.has(ref2.kind)||ref2.kind==="managed-definition"||ref2.kind==="managed-action-options"||ref2.kind==="managed-hook-plan"||ref2.kind==="managed-hook-message-chunks"){const record=parseManagedSessionRecordJson(bytes.toString("utf8"),MANAGED_SESSION_LIMITS.maxEventBytes);if(ref2.kind==="managed-hook-plan")return collectRefs([record.messagesRef]);if(ref2.kind==="managed-hook-message-chunks")return collectRefs(record.parts);return collectRefs([record])}if(ref2.kind===MANAGED_TOOL_RESULT_KINDS.manifest){try{return collectRefs([parseToolResultManifestBytes(bytes)])}catch{return[]}}if(ref2.kind==="managed-input"){try{return collectRefs([parseManagedSessionRecordJson(bytes.toString("utf8"),MANAGED_SESSION_LIMITS.maxEventBytes)])}catch{return[]}}return[]}__name(collectNestedResourceRefs,"collectNestedResourceRefs");function isReferenceContainer(kind){return EXTENSION_RECORD_KINDS.has(kind)||HOSTED_RECOVERY_RESOURCE_KINDS.has(kind)||["managed-definition","managed-checkpoint",CHECKPOINT_HISTORY_KIND,"managed-file_history","managed-action-options","managed-hook-plan","managed-hook-message-chunks",MANAGED_MESSAGE_CHUNKS_KIND,"managed-tool-outcome-chunks"].includes(kind)}__name(isReferenceContainer,"isReferenceContainer");function requireSameRef(left,right){if(left.resourceId!==right.resourceId||left.kind!==right.kind||left.schemaVersion!==right.schemaVersion||left.byteLength!==right.byteLength||left.digest!==right.digest){throw new ManagedSessionRecordError(`resource ${right.resourceId} was reused with different metadata.`)}}__name(requireSameRef,"requireSameRef");async function readHttpError(response){try{const body=asRecord(await response.json(),"error response");const error=asRecord(body["error"],"error");const details={};for(const[key,value]of Object.entries(error))if(key!=="code"&&key!=="message"&&(typeof value==="string"||typeof value==="number"||typeof value==="boolean"))details[key]=value;return{code:string(error["code"],"error.code"),message:string(error["message"],"error.message"),...Object.keys(details).length>0?{details}:{}}}catch{return{code:"managed_session_store_http_error",message:`Managed Session Store returned HTTP ${response.status}.`}}}__name(readHttpError,"readHttpError");async function readBoundedPublicationJson(response){const reader=response.body?.getReader();if(!reader)throw corrupt2("Publication response has no body.");const chunks=[];let length=0;try{while(true){const item=await reader.read();if(item.done)break;length+=item.value.byteLength;if(length>4*1024*1024)throw corrupt2("Publication response exceeds its byte limit.");chunks.push(item.value)}}finally{reader.releaseLock()}return JSON.parse(Buffer.concat(chunks).toString("utf8"))}__name(readBoundedPublicationJson,"readBoundedPublicationJson");function asRecord(value,label){if(value===null||typeof value!=="object"||Array.isArray(value)){throw corrupt2(`${label} must be an object.`)}return value}__name(asRecord,"asRecord");function asArray(value,label){if(!Array.isArray(value))throw corrupt2(`${label} must be an array.`);return value}__name(asArray,"asArray");function string(value,label){if(typeof value!=="string"||value.length===0){throw corrupt2(`${label} must be a non-empty string.`)}return value}__name(string,"string");function nullableString(value,label){return value===null||value===void 0?null:string(value,label)}__name(nullableString,"nullableString");function boolean(value,label){if(typeof value!=="boolean")throw corrupt2(`${label} must be boolean.`);return value}__name(boolean,"boolean");function safeCounter(value,label){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0){throw corrupt2(`${label} must be a non-negative safe integer.`)}return value}__name(safeCounter,"safeCounter");function digest2(value,label){const result=string(value,label);if(!/^[0-9a-f]{64}$/.test(result)){throw corrupt2(`${label} must be a lowercase SHA-256 digest.`)}return result}__name(digest2,"digest");function nullableDigest(value,label){return value===null||value===void 0?null:digest2(value,label)}__name(nullableDigest,"nullableDigest");function decodeBase64(value,label){if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)){throw corrupt2(`${label} must be canonical Base64.`)}return Buffer.from(value,"base64")}__name(decodeBase64,"decodeBase64");function sha256(value){return createHash2("sha256").update(value).digest("hex")}__name(sha256,"sha256");function corrupt2(message){return new ManagedSessionRecordError(`Managed Session Store: ${message}`)}__name(corrupt2,"corrupt");init_esbuild_shims();import{createHash as createHash3}from"node:crypto";var HOSTED_SKILL_CATALOG_MAX_BYTES=2*1024*1024;var HOSTED_SKILL_APPROVAL_REFUSAL="Hosted Skill loading cannot request approval; the PreToolUse Hook must allow or deny this instruction-only call.";var HOSTED_SKILL_BATCH_REFUSAL="Load Skills in a separate tool batch before calling Workspace tools.";function parseSessionSkillsRef(value){if(value===void 0)return void 0;const ref2=assertManagedSessionDurableRef(value,"Session Skills");if(ref2.kind!=="managed-agent-skills"||ref2.schemaVersion!==1||ref2.byteLength>HOSTED_SKILL_CATALOG_MAX_BYTES)throw new Error("Invalid Session Skills reference.");return ref2}__name(parseSessionSkillsRef,"parseSessionSkillsRef");function sameSessionSkillsRef(a,b){return a?.resourceId===b?.resourceId&&a?.kind===b?.kind&&a?.schemaVersion===b?.schemaVersion&&a?.byteLength===b?.byteLength&&a?.digest===b?.digest}__name(sameSessionSkillsRef,"sameSessionSkillsRef");function invalid2(){throw new Error("Invalid Hosted skill catalog.")}__name(invalid2,"invalid");function boundedText(value,maxBytes){return typeof value==="string"&&value.trim().length>0&&!/[\ud800-\udfff]/u.test(value)&&Buffer.byteLength(value,"utf8")<=maxBytes}__name(boundedText,"boundedText");function parseHostedSkills(value){if(!Array.isArray(value)||value.length>256||Buffer.byteLength(JSON.stringify(value),"utf8")>HOSTED_SKILL_CATALOG_MAX_BYTES)invalid2();const names=new Set;return Object.freeze(value.map(item=>{if(!item||typeof item!=="object"||Array.isArray(item))invalid2();const skill=item;if(Object.keys(skill).some(key=>!["name","description","body","base_directory","model_invocable","user_invocable","asset_directory"].includes(key))||!boundedText(skill["name"],128)||!boundedText(skill["description"],4096)||!boundedText(skill["body"],512*1024))invalid2();for(const field of["model_invocable","user_invocable"]){if(skill[field]!==void 0&&typeof skill[field]!=="boolean")invalid2()}validateSkillName(skill["name"]);if(names.has(skill["name"]))invalid2();names.add(skill["name"]);const base=skill["base_directory"];const asset=skill["asset_directory"];if(asset!==void 0&&(typeof asset!=="string"||!/^extension:\/\/[A-Za-z0-9._:-]+\/(?:[^\\\s]*\/?)$/u.test(asset)||asset.split("/").some(part=>part===".."||part===".")))invalid2();if(base!==void 0){if(!boundedText(base,4096)||/[\\:]/u.test(base)||[...base].some(character=>{const code=character.codePointAt(0);return code<=31||code>=127&&code<=159})||base!=="."&&base.split("/").some(segment=>!segment||segment==="."||segment===".."))invalid2()}return Object.freeze({name:skill["name"],description:skill["description"],body:skill["body"],...asset===void 0?{}:{asset_directory:asset},...base===void 0?{}:{base_directory:base},...skill["model_invocable"]===void 0?{}:{model_invocable:skill["model_invocable"]},...skill["user_invocable"]===void 0?{}:{user_invocable:skill["user_invocable"]}})}))}__name(parseHostedSkills,"parseHostedSkills");async function readHostedSkills(ref2,resources){if(!ref2)return[];if(ref2.kind!=="managed-agent-skills"||ref2.schemaVersion!==1||ref2.byteLength>HOSTED_SKILL_CATALOG_MAX_BYTES)throw new Error("Invalid agent skills reference.");const bytes=await resources.read(ref2);if(bytes.byteLength!==ref2.byteLength||createHash3("sha256").update(bytes).digest("hex")!==ref2.digest)throw new Error("Agent skills do not match their reference.");return parseHostedSkills(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)))}__name(readHostedSkills,"readHostedSkills");var HostedSkillCatalog=class{constructor(skills,commands=[]){this.commands=commands;this.skills=parseHostedSkills(skills);const names=new Set(this.skills.map(skill=>skill.name));for(const command of commands){validateSkillName(command.name);if(names.has(command.name)||!boundedText(command.description,4096)||!boundedText(command.prompt,512*1024))invalid2();names.add(command.name)}}static{__name(this,"HostedSkillCatalog")}skills;entries(){return this.skills}command(args){if(!args||typeof args!=="object")return void 0;return this.commands.find(command=>command.name===args.skill)}userArguments(name,prompt){return this.commands.some(command=>command.name===name)?{args:prompt.trimStart().slice(name.length+1).trimStart()}:{}}instructions(){const available=[...this.skills.filter(skill=>skill.model_invocable!==false),...this.commands.filter(command=>command.modelInvocable).map(command=>({name:command.name,description:command.description}))];if(!available.length)return void 0;return`The following published skills are available. Use the skill tool to load their instructions when relevant.
4
4
  ${renderAvailableSkillsBlock(available)}`}invocations(prompt){const names=new Set;let remaining=prompt;for(;;){const match=/^\s*\/([^\s/]+)(?=\s|$)/u.exec(remaining);if(!match||!this.skills.some(skill=>skill.name===match[1]&&skill.user_invocable!==false)&&!this.commands.some(command=>command.name===match[1]))return[...names];names.add(match[1]);if(this.commands.some(command=>command.name===match[1]))return[...names];remaining=remaining.slice(match[0].length)}}declaration(){const available=[...this.skills.filter(skill=>skill.model_invocable!==false),...this.commands.filter(command=>command.modelInvocable)];if(!available.length&&!this.commands.length)return void 0;return{name:"skill",description:"Load the instructions of a published skill in a separate batch before calling other tools. Loading does not run scripts or change tool permissions.",parametersJsonSchema:{type:"object",properties:{skill:{type:"string",enum:available.map(skill=>skill.name)},...this.commands.length?{args:{type:"string"}}:{}},required:["skill"],additionalProperties:false}}}validationError(args,origin){if(!args||typeof args!=="object"||Array.isArray(args))return"Hosted Skill requires only a skill name.";const values=args;const command=this.command(args);if((command?Object.keys(values).some(key=>!["skill","args"].includes(key))||values["args"]!==void 0&&typeof values["args"]!=="string":Object.keys(values).length!==1)||typeof values["skill"]!=="string")return"Hosted Skill requires only a skill name; arguments and activation options are unsupported.";if(command)return origin==="model"&&!command.modelInvocable?"This command may only be invoked by the user.":void 0;if(!this.skills.some(skill2=>skill2.name===values["skill"]))return`Skill ${JSON.stringify(values["skill"])} is not published for this Session.`;const skill=this.skills.find(entry=>entry.name===values["skill"]);if(origin==="model"&&skill.model_invocable===false)return"This Skill may only be invoked by the user.";if(origin==="user"&&skill.user_invocable===false)return"This Skill is not user-invocable.";return void 0}response(args){const error=this.validationError(args);if(error)throw new Error(error);const name=args.skill;if(this.command(args))throw new Error("Extension commands require the durable command expansion pipeline.");const skill=this.skills.find(entry=>entry.name===name);return skill.asset_directory?`Base directory for this skill: ${skill.asset_directory}
5
5
  Resolve asset paths relative to this directory with the Workspace tools.
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{SessionOrganizationService}from"./chunk-Z5XENA4A.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function createSessionOrganizationService(workspaceCwd){return new SessionOrganizationService(workspaceCwd,message=>{writeStderrLine(`qwen serve: session-org: ${message}`)})}__name(createSessionOrganizationService,"createSessionOrganizationService");export{createSessionOrganizationService};
3
+ import{SessionOrganizationService}from"./chunk-2JGTWRZJ.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function createSessionOrganizationService(workspaceCwd){return new SessionOrganizationService(workspaceCwd,message=>{writeStderrLine(`qwen serve: session-org: ${message}`)})}__name(createSessionOrganizationService,"createSessionOrganizationService");export{createSessionOrganizationService};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team