@qwen-code/qwen-code 0.26.2-preview.0 → 0.26.2-preview.1

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 (300) hide show
  1. package/chunks/{MaxSizedBox-K6YUM3DX.js → MaxSizedBox-EGHZ2BPF.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-75IC33SN.js → StandaloneSessionPicker-UVCW6YW3.js} +1 -1
  3. package/chunks/{acp-subagent-executor-3NHBJRPL.js → acp-subagent-executor-AQ7AWSD4.js} +1 -1
  4. package/chunks/{acpAgent-JT6KQPTH.js → acpAgent-IV7JAGD7.js} +3 -3
  5. package/chunks/{advisor-TI2UVEZK.js → advisor-UZ4TF65D.js} +1 -1
  6. package/chunks/{agent-SWIZZZMY.js → agent-CNLVAWDD.js} +1 -1
  7. package/chunks/{agent-headless-USWEJ4GW.js → agent-headless-ZJUJLUJS.js} +1 -1
  8. package/chunks/{agent-host-client-ZFIMQX33.js → agent-host-client-SN5V2KBH.js} +1 -1
  9. package/chunks/{agent-host-connections-LOFD7O7Q.js → agent-host-connections-VKMAJIIU.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-HMLEI4FI.js → anthropicContentGenerator-QTJVPAMI.js} +1 -1
  11. package/chunks/{autofix-pr-NKR2VSLB.js → autofix-pr-U7GNSH27.js} +1 -1
  12. package/chunks/{batch-JQZ3TOHA.js → batch-MBEWETXN.js} +1 -1
  13. package/chunks/{bridge-EIWWT4P6.js → bridge-TEJLNYV3.js} +1 -1
  14. package/chunks/{channel-settings-store-FLRLUA67.js → channel-settings-store-QNCKWWBL.js} +1 -1
  15. package/chunks/{chunk-244YTFYD.js → chunk-23KDY7UW.js} +1 -1
  16. package/chunks/{chunk-7TDMQJTD.js → chunk-2DWWSMTV.js} +1 -1
  17. package/chunks/{chunk-UU2LTNSF.js → chunk-3IZMVLVZ.js} +1 -1
  18. package/chunks/{chunk-B6T4ESBM.js → chunk-3JI7IKJL.js} +1 -1
  19. package/chunks/{chunk-Y5TT2G3N.js → chunk-427MARCP.js} +1 -1
  20. package/chunks/{chunk-KX7JS2P7.js → chunk-4NNNGSQY.js} +3 -3
  21. package/chunks/{chunk-6TQS2WQO.js → chunk-4RM7KY3Z.js} +2 -2
  22. package/chunks/{chunk-YL3N2UGG.js → chunk-5X7S4AE6.js} +5 -5
  23. package/chunks/{chunk-K2HAY5PY.js → chunk-5XAECBED.js} +1 -1
  24. package/chunks/{chunk-VCHFBETO.js → chunk-66KKSLUO.js} +1 -1
  25. package/chunks/{chunk-BSJR2KEF.js → chunk-6CIIDUZW.js} +1 -1
  26. package/chunks/{chunk-22CLK7PK.js → chunk-7EBRMQYW.js} +1 -1
  27. package/chunks/{chunk-J4TFGZ4A.js → chunk-7FSC2NKA.js} +1 -1
  28. package/chunks/{chunk-6JFC5M6B.js → chunk-A5TAAMML.js} +1 -1
  29. package/chunks/{chunk-DHHACQVN.js → chunk-AOYSX44A.js} +1 -1
  30. package/chunks/{chunk-VFVZ2DY7.js → chunk-AZCMQ3DD.js} +2 -2
  31. package/chunks/{chunk-BQJXWIMR.js → chunk-B6F7CVBP.js} +1 -1
  32. package/chunks/{chunk-OVPEAKOQ.js → chunk-BDQOLT37.js} +1 -1
  33. package/chunks/{chunk-5SYUBQNO.js → chunk-BIWEUAKG.js} +1 -1
  34. package/chunks/{chunk-BZM66PQO.js → chunk-BJ5R7LOM.js} +1 -1
  35. package/chunks/{chunk-4R2OHBH3.js → chunk-BKUFRNME.js} +1 -1
  36. package/chunks/{chunk-NIYWNFVF.js → chunk-BNZSPX2I.js} +1 -1
  37. package/chunks/{chunk-FJV2ECNY.js → chunk-D2URRVOK.js} +1 -1
  38. package/chunks/{chunk-GT6CHVAI.js → chunk-DANP7CMW.js} +1 -1
  39. package/chunks/{chunk-FHFLD4DR.js → chunk-DBHLRZGI.js} +1 -1
  40. package/chunks/{chunk-Y2UXZJLM.js → chunk-DL7TKH2E.js} +2 -2
  41. package/chunks/{chunk-MCQE2U7N.js → chunk-DOWKH5OZ.js} +6 -6
  42. package/chunks/{chunk-UHRLBY3C.js → chunk-DPHQJPCU.js} +1 -1
  43. package/chunks/{chunk-PV2VT25U.js → chunk-DPNGBOI7.js} +1 -1
  44. package/chunks/{chunk-NCDNF7UJ.js → chunk-DXRXF4QD.js} +1 -1
  45. package/chunks/{chunk-OCVRMNEQ.js → chunk-DZ3GV34J.js} +1 -1
  46. package/chunks/{chunk-3QIAXWWW.js → chunk-EU2MKUK4.js} +1 -1
  47. package/chunks/{chunk-KMAVI6FB.js → chunk-EVBUXPGM.js} +1 -1
  48. package/chunks/{chunk-BVSTV4JM.js → chunk-F3ZRU2SA.js} +1 -1
  49. package/chunks/{chunk-TBZY477Y.js → chunk-FCZYH27X.js} +1 -1
  50. package/chunks/{chunk-JCOK67LT.js → chunk-FNDMWG43.js} +1 -1
  51. package/chunks/{chunk-5SF32OGU.js → chunk-GDXLJJSW.js} +1 -1
  52. package/chunks/{chunk-SO6FCPRI.js → chunk-GZYIXB7Y.js} +1 -1
  53. package/chunks/{chunk-WZPTWC7X.js → chunk-HHNAH4IH.js} +1 -1
  54. package/chunks/{chunk-7KCAOXNL.js → chunk-HOKROBQZ.js} +1 -1
  55. package/chunks/{chunk-34ZBUQJV.js → chunk-IGPAATQW.js} +1 -1
  56. package/chunks/{chunk-2ZTRKK2O.js → chunk-INFBJDWM.js} +1 -1
  57. package/chunks/{chunk-IEJ2CGRN.js → chunk-J3R7ZNSA.js} +1 -1
  58. package/chunks/{chunk-KT5MPRYB.js → chunk-JCRS367I.js} +1 -1
  59. package/chunks/{chunk-7JWJTRP6.js → chunk-JFVXZFMV.js} +1 -1
  60. package/chunks/{chunk-47LP4MBD.js → chunk-JKMGS2VD.js} +1 -1
  61. package/chunks/{chunk-WRJ3PMDZ.js → chunk-JUQ7T2MV.js} +1 -1
  62. package/chunks/{chunk-NZX3UWNF.js → chunk-KQ4TDFNE.js} +1 -1
  63. package/chunks/{chunk-X7D4VKMX.js → chunk-L6BKKN42.js} +1 -1
  64. package/chunks/{chunk-YG5HVFMY.js → chunk-L7Y6MOHS.js} +1 -1
  65. package/chunks/{chunk-UFTIUKD4.js → chunk-LGYXZJI3.js} +1 -1
  66. package/chunks/{chunk-JQGGILML.js → chunk-LPOEVTKD.js} +1 -1
  67. package/chunks/{chunk-5KI55A6S.js → chunk-LRXS7ZI2.js} +1 -1
  68. package/chunks/{chunk-CKVHEYXW.js → chunk-LYYVSCNL.js} +1 -1
  69. package/chunks/{chunk-LIIMQ4DI.js → chunk-LZNBHBAJ.js} +6 -6
  70. package/chunks/{chunk-H4GDEXMF.js → chunk-M3C6RDGC.js} +1 -1
  71. package/chunks/{chunk-KKKUB3RQ.js → chunk-MNVMHVQJ.js} +1 -1
  72. package/chunks/{chunk-2B3W7IQY.js → chunk-MVGQFFIK.js} +1 -1
  73. package/chunks/{chunk-Q35A2RGO.js → chunk-NC7BCZPQ.js} +1 -1
  74. package/chunks/{chunk-2ZOTG3NW.js → chunk-NE627MUW.js} +1 -1
  75. package/chunks/{chunk-W4P2EN3V.js → chunk-NZNRCPGE.js} +1 -1
  76. package/chunks/{chunk-YPDQJQ3S.js → chunk-P3M4WWRA.js} +1 -1
  77. package/chunks/{chunk-DVB36ASH.js → chunk-P534ONQN.js} +1 -1
  78. package/chunks/{chunk-EL5J4ESB.js → chunk-QF44NNSC.js} +1 -1
  79. package/chunks/{chunk-IQPJOBPI.js → chunk-QHGCDHNW.js} +1 -1
  80. package/chunks/{chunk-EVZC4KEQ.js → chunk-QWJX7NIP.js} +1 -1
  81. package/chunks/{chunk-J2TJL2F4.js → chunk-S53G54DW.js} +2 -2
  82. package/chunks/{chunk-3A6LFJJV.js → chunk-SMNFL3AD.js} +1 -1
  83. package/chunks/{chunk-WDO3K3P2.js → chunk-TOBNWST4.js} +1 -1
  84. package/chunks/{chunk-AVGJ4HE3.js → chunk-TQSBUHAM.js} +1 -1
  85. package/chunks/{chunk-ABUS7DNN.js → chunk-TW5QEP2J.js} +1 -1
  86. package/chunks/{chunk-WYM4Z4D5.js → chunk-UEB2F43V.js} +1 -1
  87. package/chunks/{chunk-FUUPMVD2.js → chunk-UPPE4I6H.js} +1 -1
  88. package/chunks/{chunk-UHBJVFZA.js → chunk-US42COBM.js} +1 -1
  89. package/chunks/{chunk-RMQNBSMK.js → chunk-UUY6XSQI.js} +1 -1
  90. package/chunks/{chunk-UVQUQNCA.js → chunk-UZI3IA27.js} +1 -1
  91. package/chunks/{chunk-SXJ2E33J.js → chunk-V6VMUJ47.js} +1 -1
  92. package/chunks/{chunk-5UFCNJGN.js → chunk-VG2ZINTO.js} +1 -1
  93. package/chunks/{chunk-JPPPJ2GN.js → chunk-VJI6MHWX.js} +1 -1
  94. package/chunks/{chunk-AUI7WVSU.js → chunk-VOBNHBCJ.js} +1 -1
  95. package/chunks/{chunk-3BNJDZHU.js → chunk-VUEZWMI4.js} +1 -1
  96. package/chunks/{chunk-LMNKCL55.js → chunk-W7ZX6WB3.js} +2 -2
  97. package/chunks/{chunk-HVS6V2UZ.js → chunk-WA2LKUVP.js} +1 -1
  98. package/chunks/{chunk-7APLU2XE.js → chunk-WFFCJ5PF.js} +1 -1
  99. package/chunks/{chunk-3TD4WAG5.js → chunk-WQY5GE65.js} +1 -1
  100. package/chunks/{chunk-3YWRMF6C.js → chunk-WSESLSKK.js} +1 -1
  101. package/chunks/{chunk-NILCQMZ7.js → chunk-XFJV5NYT.js} +1 -1
  102. package/chunks/{chunk-LGBGUITT.js → chunk-XIYLRIW4.js} +1 -1
  103. package/chunks/{chunk-KS74L67R.js → chunk-XQ2NYKJH.js} +1 -1
  104. package/chunks/{chunk-JB2NOB6W.js → chunk-Y3VRWG52.js} +1 -1
  105. package/chunks/{chunk-GVZ6D2NL.js → chunk-YBISME5B.js} +1 -1
  106. package/chunks/{chunk-2C2253QI.js → chunk-YJNWPSB3.js} +1 -1
  107. package/chunks/{chunk-O2T3GQ6F.js → chunk-YWVV5STA.js} +1 -1
  108. package/chunks/{chunk-MAQZSOHI.js → chunk-ZH4J3FL6.js} +1 -1
  109. package/chunks/{chunk-THNEKTPK.js → chunk-ZSKCF6DI.js} +1 -1
  110. package/chunks/{chunk-Z7BAHKO5.js → chunk-ZW6456SD.js} +1 -1
  111. package/chunks/{chunk-DMSZ2TB3.js → chunk-ZWM3LLT7.js} +1 -1
  112. package/chunks/{codex-subagent-executor-DQ5LQQWO.js → codex-subagent-executor-DWWT7246.js} +1 -1
  113. package/chunks/{config-utils-CY6HLKZ5.js → config-utils-NGZB522W.js} +1 -1
  114. package/chunks/{contextCommand-SGBWI7O6.js → contextCommand-7QCW2YNX.js} +1 -1
  115. package/chunks/{core-runtime-4DP27LCC.js → core-runtime-PSVNDJPD.js} +1 -1
  116. package/chunks/{create-sub-session-ECPDZMBX.js → create-sub-session-JTSEMEJE.js} +1 -1
  117. package/chunks/{cron-create-OO4OG3EI.js → cron-create-VGIDTUMX.js} +1 -1
  118. package/chunks/{daemon-git-worktree-guard-OYDNHT7P.js → daemon-git-worktree-guard-IQRGS7IH.js} +1 -1
  119. package/chunks/{daemon-status-provider-JGDLXPC6.js → daemon-status-provider-R4MYCYPG.js} +1 -1
  120. package/chunks/{daemon-trust-policy-5HRARS54.js → daemon-trust-policy-VAUKFZ2N.js} +1 -1
  121. package/chunks/{daemon-trust-policy-monitor-RM7FVIIC.js → daemon-trust-policy-monitor-E5HIO6RP.js} +1 -1
  122. package/chunks/{deferred-core-runtime-3CXBZIOG.js → deferred-core-runtime-FLOFQJPU.js} +1 -1
  123. package/chunks/{edit-DJPESAAY.js → edit-OOVQUGKV.js} +1 -1
  124. package/chunks/{enterPlanMode-IHBLRIF3.js → enterPlanMode-AUWVTQLT.js} +1 -1
  125. package/chunks/{environment-JN5SD347.js → environment-RM5OXYP4.js} +1 -1
  126. package/chunks/{errors-NUJCME3Y.js → errors-CLDJGHVD.js} +1 -1
  127. package/chunks/{execution-tool-I3SWG6I3.js → execution-tool-JFBVOKPW.js} +1 -1
  128. package/chunks/{execution-worker-62UZMAMJ.js → execution-worker-MNJZD72W.js} +1 -1
  129. package/chunks/{exitPlanMode-JIC4V3FE.js → exitPlanMode-PC6XG4TW.js} +1 -1
  130. package/chunks/{fast-path-NIOIL5YI.js → fast-path-V4DN3CRZ.js} +1 -1
  131. package/chunks/{glob-EQ4QNAHF.js → glob-DTZROBDS.js} +1 -1
  132. package/chunks/{goal-tools-DYTTSBQG.js → goal-tools-FUVGTY33.js} +1 -1
  133. package/chunks/{handleAutoUpdate-44BTG5L5.js → handleAutoUpdate-U4LVTHGU.js} +1 -1
  134. package/chunks/{i18n-FTHZAHCT.js → i18n-XOKNDFYP.js} +1 -1
  135. package/chunks/{initializer-MSGKXC75.js → initializer-XBR5J4CY.js} +1 -1
  136. package/chunks/{installationInfo-4XJMJJYU.js → installationInfo-4AOEOUI6.js} +1 -1
  137. package/chunks/{interactive-mod-session-DFLRYO2Q.js → interactive-mod-session-YGZK2JK2.js} +1 -1
  138. package/chunks/{list-ODZ7Z6VI.js → list-TCGKVPH4.js} +1 -1
  139. package/chunks/{llm-O64DHKP7.js → llm-SKFTN5UN.js} +4 -4
  140. package/chunks/{llm-content-generator-SK24I6QS.js → llm-content-generator-GWHXT3WS.js} +1 -1
  141. package/chunks/{loadedSettingsAdapter-6PEBUZT5.js → loadedSettingsAdapter-ZALZGZE7.js} +1 -1
  142. package/chunks/{local-ED3UEKWP.js → local-RWTWYS5Z.js} +1 -1
  143. package/chunks/{local-execution-environment-PUKES5LO.js → local-execution-environment-R6JWLD65.js} +1 -1
  144. package/chunks/{loggingContentGenerator-UHOJVSRR.js → loggingContentGenerator-UJV6QFOY.js} +1 -1
  145. package/chunks/{loop-wakeup-NSJQETPZ.js → loop-wakeup-BU2RRYHA.js} +1 -1
  146. package/chunks/{manage-memory-5RRB6FLH.js → manage-memory-XI57JN4T.js} +1 -1
  147. package/chunks/{managed-execution-engine-MZAP7SK6.js → managed-execution-engine-BA5PABMP.js} +1 -1
  148. package/chunks/{managed-local-serve-XMES3HXL.js → managed-local-serve-MFKN22K6.js} +1 -1
  149. package/chunks/{managed-npm-update-R5KGY7G2.js → managed-npm-update-ZGN43NUA.js} +1 -1
  150. package/chunks/{managed-runtime-attestation-worker-O2KNHHV6.js → managed-runtime-attestation-worker-YN2VBGYN.js} +1 -1
  151. package/chunks/{managed-runtime-bootstrap-HOTLM6DE.js → managed-runtime-bootstrap-SGQVMUJE.js} +1 -1
  152. package/chunks/{managed-runtime-session-worker-QZX44ZTD.js → managed-runtime-session-worker-4UMF3VBY.js} +1 -1
  153. package/chunks/{managed-runtime-ssh-worker-U425WQ65.js → managed-runtime-ssh-worker-7XA6KRBN.js} +1 -1
  154. package/chunks/{managed-session-authority-THHDHCBP.js → managed-session-authority-IJGYAOEL.js} +1 -1
  155. package/chunks/{mcp-AR7EK4WY.js → mcp-V3L7B5YK.js} +1 -1
  156. package/chunks/{memory-C2TSF6BK.js → memory-3T6FPNAK.js} +1 -1
  157. package/chunks/{model-call-collection-25WR55OH.js → model-call-collection-WTTITWWM.js} +1 -1
  158. package/chunks/{model-configuration-KC7DQGKV.js → model-configuration-T6SSGI4J.js} +1 -1
  159. package/chunks/{modelConfigUtils-QEHMVLSQ.js → modelConfigUtils-TQA25QJC.js} +1 -1
  160. package/chunks/{monitor-PDQUZD23.js → monitor-5ZAOJSEE.js} +1 -1
  161. package/chunks/{nonInteractiveCli-WY2YFONU.js → nonInteractiveCli-YFINLVA7.js} +1 -1
  162. package/chunks/{nonInteractiveToolExecutor-7RJZYPHJ.js → nonInteractiveToolExecutor-DE3WACL5.js} +1 -1
  163. package/chunks/{notebook-edit-P4ITXF5H.js → notebook-edit-UK6HBRO3.js} +1 -1
  164. package/chunks/{omni-AYUPB2QM.js → omni-65LF5QK4.js} +1 -1
  165. package/chunks/{openaiContentGenerator-V5IK4ITO.js → openaiContentGenerator-HX7NCSV5.js} +1 -1
  166. package/chunks/{openaiResponsesContentGenerator-DYDH6KWT.js → openaiResponsesContentGenerator-CFA6U6Y5.js} +1 -1
  167. package/chunks/{pidfile-INPBL2DK.js → pidfile-ZVKJUNTZ.js} +1 -1
  168. package/chunks/{processUtils-J4UDEDS4.js → processUtils-VS6CJT7E.js} +1 -1
  169. package/chunks/{prompt-terminal-ledger-QLOQWHYE.js → prompt-terminal-ledger-UF5RDB57.js} +1 -1
  170. package/chunks/{qwenContentGenerator-RU43XKKB.js → qwenContentGenerator-GM3ZSI7E.js} +1 -1
  171. package/chunks/{reactive-degrade-2Q3Z3KAR.js → reactive-degrade-TSAQWZ5F.js} +1 -1
  172. package/chunks/{read-file-472BQ25I.js → read-file-J267NT45.js} +1 -1
  173. package/chunks/{resumeHistoryUtils-7SUFKZDC.js → resumeHistoryUtils-IM46VFDV.js} +1 -1
  174. package/chunks/{review-WX52IWJR.js → review-4B64XTCL.js} +1 -1
  175. package/chunks/{ripGrep-4GPGLKAM.js → ripGrep-YLOSXO7P.js} +1 -1
  176. package/chunks/{run-qwen-serve-MXK4RBKL.js → run-qwen-serve-SAHEC44O.js} +1 -1
  177. package/chunks/{runtime-WHU3AGFT.js → runtime-SJDZHV6J.js} +1 -1
  178. package/chunks/{sandboxConfig-7DBXEQJH.js → sandboxConfig-47EXXMUA.js} +1 -1
  179. package/chunks/{scheduled-tasks-O5RV6G6U.js → scheduled-tasks-E6RCTUUS.js} +1 -1
  180. package/chunks/{scheduler-HLMS5LR5.js → scheduler-SE3IWIWA.js} +1 -1
  181. package/chunks/{search-memory-PYND7ZX3.js → search-memory-2W7VJC4Q.js} +1 -1
  182. package/chunks/{send-message-TMLYTQOI.js → send-message-63YGQP6G.js} +1 -1
  183. package/chunks/{serve-EBNBRAME.js → serve-F4ML2WNL.js} +1 -1
  184. package/chunks/{server-63BRDBL5.js → server-S56IB4TT.js} +3 -3
  185. package/chunks/{session-XB6J4CZD.js → session-2CUVLZ4H.js} +1 -1
  186. package/chunks/{session-attachments-root-PFK475N2.js → session-attachments-root-FINBX7K5.js} +1 -1
  187. package/chunks/{session-execution-engine-selector-P6TJTCKR.js → session-execution-engine-selector-UGC7DGUN.js} +1 -1
  188. package/chunks/{session-pr-refresh-PM7VAQTV.js → session-pr-refresh-KQLQ4MZY.js} +1 -1
  189. package/chunks/{sessionService-PO3LLZIZ.js → sessionService-Q6N7LF7Z.js} +1 -1
  190. package/chunks/{settings-JDQSRXP3.js → settings-23I6H76E.js} +1 -1
  191. package/chunks/{shell-JCEX3HKM.js → shell-IUECEVVY.js} +1 -1
  192. package/chunks/{skill-JSZBONIZ.js → skill-YKUETMPC.js} +1 -1
  193. package/chunks/{skill-settings-YGFG6GPN.js → skill-settings-ODYXOPCA.js} +1 -1
  194. package/chunks/{spawnChannel-VIIWSWTL.js → spawnChannel-7XU2SRWZ.js} +1 -1
  195. package/chunks/{standalone-update-2UU6FQZL.js → standalone-update-SWI2RL3L.js} +1 -1
  196. package/chunks/{start-opentui-ui-OSZZNSLY.js → start-opentui-ui-T53QJGCH.js} +1 -1
  197. package/chunks/{startInteractiveUI-FFH66MYH.js → startInteractiveUI-USTZGQOE.js} +1 -1
  198. package/chunks/{team-create-TKGDJ3NU.js → team-create-4A2XUE3D.js} +1 -1
  199. package/chunks/{team-plan-approval-3VJF4G6Z.js → team-plan-approval-4TS5CYN6.js} +1 -1
  200. package/chunks/{terminal-image-renderer-T3VJRZGP.js → terminal-image-renderer-C7553YV6.js} +1 -1
  201. package/chunks/{theme-manager-ZGUFLFUI.js → theme-manager-GTW75GOO.js} +1 -1
  202. package/chunks/{tool-call-3EQS5KSE.js → tool-call-YTUMWL3A.js} +1 -1
  203. package/chunks/{tool-result-media-7LFNVQ6E.js → tool-result-media-JYOYBX4J.js} +1 -1
  204. package/chunks/{tool-search-UDZ4S7T5.js → tool-search-Y4XTT2WF.js} +1 -1
  205. package/chunks/{total-session-admission-U4MII4RA.js → total-session-admission-EMJ5NRGL.js} +1 -1
  206. package/chunks/{trustedFolders-2NQJCIN3.js → trustedFolders-YG6WAVRE.js} +1 -1
  207. package/chunks/{update-relaunch-YKLWSCLC.js → update-relaunch-4QYQRCP4.js} +1 -1
  208. package/chunks/{updateCheck-YDLTQQRU.js → updateCheck-VRFPSX4G.js} +1 -1
  209. package/chunks/{upload-config-5QQKWF4O.js → upload-config-UCKGUYYQ.js} +1 -1
  210. package/chunks/{useAutoAcceptIndicator-AJS4WTU2.js → useAutoAcceptIndicator-2VGLKD7B.js} +1 -1
  211. package/chunks/{validateNonInterActiveAuth-AETOT7ZW.js → validateNonInterActiveAuth-GGMQXKKU.js} +1 -1
  212. package/chunks/{version-IB6DLRAG.js → version-Y46PG7II.js} +1 -1
  213. package/chunks/{web-fetch-LS3QARNR.js → web-fetch-7MPU555L.js} +1 -1
  214. package/chunks/{web-search-FGHRIVEB.js → web-search-HU2CL2X2.js} +1 -1
  215. package/chunks/{workflow-FX6XNETQ.js → workflow-U3D34QQX.js} +1 -1
  216. package/chunks/{workflow-ancestor-trust-5XXBGN6F.js → workflow-ancestor-trust-OWC4YTMR.js} +1 -1
  217. package/chunks/{workspace-agents-UJKLYPUK.js → workspace-agents-KHLAWSAR.js} +1 -1
  218. package/chunks/{workspace-providers-status-4JOHMTAW.js → workspace-providers-status-T57SE3YX.js} +1 -1
  219. package/chunks/{workspace-recovery-worker-XFEYQ4TP.js → workspace-recovery-worker-VYQ723ZE.js} +1 -1
  220. package/chunks/{workspace-registration-store-LWAPVNYC.js → workspace-registration-store-I7PR3A2Y.js} +1 -1
  221. package/chunks/{workspace-registry-M7OC376O.js → workspace-registry-YYUBXCLH.js} +1 -1
  222. package/chunks/{workspace-runtime-coordinator-CYHIL47L.js → workspace-runtime-coordinator-5ICAQO7W.js} +1 -1
  223. package/chunks/{workspace-service-43VZZ56B.js → workspace-service-YROWXOLQ.js} +1 -1
  224. package/chunks/{workspace-skills-status-V2TT6UJQ.js → workspace-skills-status-DKKQDTZJ.js} +1 -1
  225. package/chunks/{workspace-trust-reconciler-YZ4AG5ZW.js → workspace-trust-reconciler-3FPMUZDO.js} +1 -1
  226. package/chunks/{write-file-TGEH5MEZ.js → write-file-7QQVYFDT.js} +1 -1
  227. package/chunks/{zoom-image-TT6R7H2H.js → zoom-image-WL5EB6Q7.js} +1 -1
  228. package/cli.js +2 -2
  229. package/execution-worker.js +1 -1
  230. package/export-transcript-document.js +1 -1
  231. package/package.json +3 -3
  232. package/web-shell/assets/{PierreFilePreview-OsApm5-S.js → PierreFilePreview-BZ17f56_.js} +1 -1
  233. package/web-shell/assets/{SpreadsheetPreview-I1v1EzV7.js → SpreadsheetPreview-Bvkvr_5u.js} +1 -1
  234. package/web-shell/assets/{WorkspaceFileBrowser-BO6aug7i.js → WorkspaceFileBrowser-BJ_I4Uoz.js} +1 -1
  235. package/web-shell/assets/{abnfDiagram-VCTEODGH-DxuLMyN0.js → abnfDiagram-VCTEODGH-iuaBM15V.js} +1 -1
  236. package/web-shell/assets/{agents-route-CSJf6QPO.js → agents-route-CycwfNSC.js} +1 -1
  237. package/web-shell/assets/{arc-3--LekYQ.js → arc-C0lt8n55.js} +1 -1
  238. package/web-shell/assets/{architectureDiagram-5GKGNRK7-Dihq4uto.js → architectureDiagram-5GKGNRK7-Bw326d-A.js} +1 -1
  239. package/web-shell/assets/{blockDiagram-NRAW4CY4-BnaRPM2o.js → blockDiagram-NRAW4CY4-CHtFgBjV.js} +1 -1
  240. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BtC94eMa.js → c4Diagram-UCG6FXSJ-Bx66oJT9.js} +1 -1
  241. package/web-shell/assets/channel-CRJuO00u.js +1 -0
  242. package/web-shell/assets/{chunk-2Q5K7J3B-2ZTXWP6M.js → chunk-2Q5K7J3B-BIshvfa_.js} +1 -1
  243. package/web-shell/assets/{chunk-5VM5RSS4-DBh7DP1F.js → chunk-5VM5RSS4-BZeRS6uD.js} +1 -1
  244. package/web-shell/assets/{chunk-F27PBJKO-xzqbWXBw.js → chunk-F27PBJKO-El-CGY2R.js} +1 -1
  245. package/web-shell/assets/{chunk-G27WJ6UU-DxnCrpxK.js → chunk-G27WJ6UU-DO8ZfQL_.js} +1 -1
  246. package/web-shell/assets/{chunk-JWPE2WC7-BPjRsozm.js → chunk-JWPE2WC7-yYFrrKAj.js} +1 -1
  247. package/web-shell/assets/{chunk-LCL6LL3I-Q2HgB3lf.js → chunk-LCL6LL3I-BFGuOKN0.js} +1 -1
  248. package/web-shell/assets/{chunk-POPQ4Y6H-9tlPaKu-.js → chunk-POPQ4Y6H-GRHK6sdV.js} +1 -1
  249. package/web-shell/assets/{chunk-SVP7TREG-DkNdOHCU.js → chunk-SVP7TREG-DwDu6GqZ.js} +1 -1
  250. package/web-shell/assets/{chunk-XXDRQBXY-D0G-Dhfi.js → chunk-XXDRQBXY-RoNDjkIy.js} +1 -1
  251. package/web-shell/assets/classDiagram-DTDB5LWJ-pPPByLA7.js +1 -0
  252. package/web-shell/assets/classDiagram-v2-JRS7N3AN-pPPByLA7.js +1 -0
  253. package/web-shell/assets/{cose-bilkent-JH36ORCC-Ck0tHxul.js → cose-bilkent-JH36ORCC-CYNiiONE.js} +1 -1
  254. package/web-shell/assets/{cynefin-OW5HDTMX-a4-NTMHi.js → cynefin-OW5HDTMX-DC1_lDIG.js} +1 -1
  255. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Pg41Zbf2.js → cynefinDiagram-5FMLGOSQ-D2VxKm2n.js} +1 -1
  256. package/web-shell/assets/{dagre-3AP2YEHR-DT_ZmqkF.js → dagre-3AP2YEHR-C4_BHzpM.js} +1 -1
  257. package/web-shell/assets/{diagram-S7CK7UJ4-hapdMOl1.js → diagram-S7CK7UJ4-BpAO4-Gv.js} +1 -1
  258. package/web-shell/assets/{diagram-UQ7AKVKN-YZ0nbk56.js → diagram-UQ7AKVKN-DqUsFdsX.js} +1 -1
  259. package/web-shell/assets/{diagram-VSXAHHWV-DA_yNbWy.js → diagram-VSXAHHWV-DcMXIYMy.js} +1 -1
  260. package/web-shell/assets/{diagram-VX7I27RA-DoULuCLT.js → diagram-VX7I27RA-I3nr09ex.js} +1 -1
  261. package/web-shell/assets/{diagram-Z3DM3KII-B5c9o9zL.js → diagram-Z3DM3KII-CN-gvsTo.js} +1 -1
  262. package/web-shell/assets/{docx-preview-BulxdBjs.js → docx-preview-31J6RsS0.js} +1 -1
  263. package/web-shell/assets/{ebnfDiagram-PWID7BFC-B5hgIg3m.js → ebnfDiagram-PWID7BFC-DOQvLWlM.js} +1 -1
  264. package/web-shell/assets/{erDiagram-SSCWMZ5O-BEfEPozi.js → erDiagram-SSCWMZ5O-Cb5ijFZh.js} +1 -1
  265. package/web-shell/assets/{flowDiagram-A5DVABFB-CQHNk92v.js → flowDiagram-A5DVABFB-BecqqjnZ.js} +1 -1
  266. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-BabdVgIM.js → ganttDiagram-EL5Y4UJY-DWY5vzQl.js} +1 -1
  267. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-ujRZBFUo.js → gitGraphDiagram-WWUBYQGX-DqBnsZmZ.js} +1 -1
  268. package/web-shell/assets/{index-B9uXebIR.js → index-DDmiUW3b.js} +6 -6
  269. package/web-shell/assets/{index-DSZXdZnu.js → index-DabH7kHA.js} +1 -1
  270. package/web-shell/assets/{infoDiagram-RXCK75RN-CUHj9jJC.js → infoDiagram-RXCK75RN-MlotyOdT.js} +1 -1
  271. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-CulW_q81.js → ishikawaDiagram-5VMMS53U-Daq_85C7.js} +1 -1
  272. package/web-shell/assets/{journeyDiagram-EYS64GPL-BR46CvRQ.js → journeyDiagram-EYS64GPL-OipivCxL.js} +1 -1
  273. package/web-shell/assets/{kanban-definition-3QL26DDD-HAoUqzFy.js → kanban-definition-3QL26DDD-zqaz7dLu.js} +1 -1
  274. package/web-shell/assets/{layout-DYLl7fyA.js → layout-Bi3msQMQ.js} +1 -1
  275. package/web-shell/assets/{linear-DPXABjDZ.js → linear-D4gPORvD.js} +1 -1
  276. package/web-shell/assets/{mermaid.core-Bi30Gi0n.js → mermaid.core-BUnytF7a.js} +6 -6
  277. package/web-shell/assets/{mindmap-definition-FBJOCRG2-B1_lUq4o.js → mindmap-definition-FBJOCRG2-B_X4iChu.js} +1 -1
  278. package/web-shell/assets/{pegDiagram-XKGWAZYB-Cy8tjJJC.js → pegDiagram-XKGWAZYB-z4wYBoBW.js} +1 -1
  279. package/web-shell/assets/{pieDiagram-E7YTZNPT-D6waLVVi.js → pieDiagram-E7YTZNPT-Dvyg6FYo.js} +1 -1
  280. package/web-shell/assets/{quadrantDiagram-AXDQQJYC--6ehi_FI.js → quadrantDiagram-AXDQQJYC-CJBWU2Dk.js} +1 -1
  281. package/web-shell/assets/{railroadDiagram-O6MQD6OU-BhLy40X4.js → railroadDiagram-O6MQD6OU-Dl_An1O0.js} +1 -1
  282. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-BVNXTgNP.js → requirementDiagram-EFPCY7ZU-Tw8FwaYU.js} +1 -1
  283. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BHgTytxV.js → sankeyDiagram-P5KCCOFB-BCPCkbR0.js} +1 -1
  284. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-CgOsTvhu.js → sequenceDiagram-WJ2MYXX4-DDj7uFTG.js} +1 -1
  285. package/web-shell/assets/{sizeCapture-X5ZJPWSS-vCQBQ5FI.js → sizeCapture-X5ZJPWSS-B9eVSpKb.js} +1 -1
  286. package/web-shell/assets/{stateDiagram-HBIQ2CUA-DytMYRWJ.js → stateDiagram-HBIQ2CUA-Bf4BZP_V.js} +1 -1
  287. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BPJi6Gre.js +1 -0
  288. package/web-shell/assets/{swimlanes-XN3QIQJK-CTGnifOP.js → swimlanes-XN3QIQJK-dyTWsZFj.js} +1 -1
  289. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bw4NRtJQ.js +8 -0
  290. package/web-shell/assets/{timeline-definition-24CTP7MA-DEJ1cbn2.js → timeline-definition-24CTP7MA-DVl1A4uL.js} +1 -1
  291. package/web-shell/assets/{vennDiagram-4TSXK5OY-K1e4SjS0.js → vennDiagram-4TSXK5OY-Boosxy9D.js} +1 -1
  292. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DEX-GkRp.js → wardleyDiagram-VM6X3IG4-C6wlY8jy.js} +1 -1
  293. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-B6wYXreH.js → xychartDiagram-S5SC5T6Z-CkzZe3ro.js} +1 -1
  294. package/web-shell/index.html +1 -1
  295. package/web-shell/sw.js +1 -1
  296. package/web-shell/assets/channel-CLVrtVFX.js +0 -1
  297. package/web-shell/assets/classDiagram-DTDB5LWJ-Df2T70oB.js +0 -1
  298. package/web-shell/assets/classDiagram-v2-JRS7N3AN-Df2T70oB.js +0 -1
  299. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CcjUJGng.js +0 -1
  300. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dt8NvQfX.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{effectiveSessionScope,multiSessionCompatibilityError,parseMessageRoutingConfig,parseSessionRotationConfig}from"./chunk-FJUXMWZW.js";import{UNSAFE_OBJECT_KEYS,getPlugin}from"./chunk-MHZY2JYX.js";import{CHANNEL_OUTPUT_MODE_FIELD,parseChannelOutputMode}from"./chunk-44WSAMWG.js";import{loadSettings,saveSettings}from"./chunk-2B3W7IQY.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import{isDeepStrictEqual}from"node:util";var ChannelSettingsError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="ChannelSettingsError"}static{__name(this,"ChannelSettingsError")}};function revisionOf(channels,startupNames){return createHash("sha256").update(JSON.stringify({channels,startupNames})).digest("hex")}__name(revisionOf,"revisionOf");function applySecretUpdate(current,update){validateSecretUpdate(update);if(update.operation==="preserve")return current;if(update.operation==="clear")return void 0;if(typeof update.value!=="string"||update.value.length===0){throw invalidSecret("Secret replacements must be non-empty strings.")}return update.value}__name(applySecretUpdate,"applySecretUpdate");function invalidSecret(message){return new ChannelSettingsError("channel_settings_invalid_secret",message)}__name(invalidSecret,"invalidSecret");function invalidConfig(message){return new ChannelSettingsError("channel_settings_invalid_config",message)}__name(invalidConfig,"invalidConfig");function assertSafeChannelName(name){if(UNSAFE_OBJECT_KEYS.has(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is not allowed.`)}}__name(assertSafeChannelName,"assertSafeChannelName");function assertUpsertChannelName(name){assertSafeChannelName(name);if(isAllStartupName(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is reserved for startup selection.`)}}__name(assertUpsertChannelName,"assertUpsertChannelName");function isAllStartupName(name){return name.trim()==="all"}__name(isAllStartupName,"isAllStartupName");function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord,"isRecord");function isEnvironmentReference(value){return/^\$[A-Za-z_][A-Za-z0-9_]*$/.test(value)}__name(isEnvironmentReference,"isEnvironmentReference");function assertStringRecord(key,value,allowedKeys){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){if(!allowedKeys.has(nestedKey)||typeof nestedValue!=="string"){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}}__name(assertStringRecord,"assertStringRecord");function assertSharedField(key,value,previous){if(key==="messageRoutes"||key==="defaultMessageRoute"){return true}if(key==="multiSession"){if(typeof value!=="boolean"){throw invalidConfig(`Channel field "${key}" must be a boolean.`)}return true}if(key==="sessionRotation"){try{parseSessionRotationConfig("settings",value)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}return true}if(key==="groupSenderPolicy"||key==="allowedGroupUsers"){throw invalidConfig(`Channel field "${key}" moved to groups["*"].${key==="groupSenderPolicy"?"senders":"allowedUsers"}.`)}const enumValues={privatePolicy:new Set(["disabled","allowlist","pairing","open"]),senderPolicy:new Set(["allowlist","pairing","open"]),dmPolicy:new Set(["open","disabled"]),groupPolicy:new Set(["disabled","allowlist","pairing","open"]),sessionScope:new Set(["user","thread","chat_thread","single"]),dispatchMode:new Set(["steer","followup","collect"])};if(Object.hasOwn(enumValues,key)){if(typeof value!=="string"||!enumValues[key].has(value)){throw invalidConfig(`Channel field "${key}" has an invalid value.`)}return true}if(["model","cwd","approvalMode","instructions"].includes(key)){if(typeof value!=="string"){throw invalidConfig(`Channel field "${key}" must be a string.`)}return true}if(key==="allowedUsers"||key==="operators"){if(!Array.isArray(value)||value.some(item=>typeof item!=="string")){throw invalidConfig(`Channel field "${key}" must be a string array.`)}return true}if(key==="groups"){if(!isRecord(value)){if(containsUnsafeObjectKey(value)||!isDeepStrictEqual(previous,value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}return true}const previousGroups=isRecord(previous)?previous:{};for(const[groupId,groupConfig]of Object.entries(value)){if(UNSAFE_OBJECT_KEYS.has(groupId)||!isRecord(groupConfig)){throw invalidConfig(`Channel field "${key}.${groupId}" is invalid.`)}const previousGroup=isRecord(previousGroups[groupId])?previousGroups[groupId]:{};for(const[nestedKey,nestedValue]of Object.entries(groupConfig)){const known=["requireMention","dispatchMode","groupHistoryLimit","senders","allowedUsers"].includes(nestedKey);const valid=nestedKey==="requireMention"&&typeof nestedValue==="boolean"||nestedKey==="dispatchMode"&&typeof nestedValue==="string"&&["collect","steer","followup"].includes(nestedValue)||nestedKey==="groupHistoryLimit"&&typeof nestedValue==="number"&&Number.isFinite(nestedValue)||nestedKey==="senders"&&typeof nestedValue==="string"&&["open","allowlist"].includes(nestedValue)||nestedKey==="allowedUsers"&&Array.isArray(nestedValue)&&nestedValue.every(item=>typeof item==="string");if(known&&!valid&&!(nestedKey!=="senders"&&Object.hasOwn(previousGroup,nestedKey)&&isDeepStrictEqual(previousGroup[nestedKey],nestedValue)&&!containsUnsafeObjectKey(nestedValue))){throw invalidConfig(`Channel field "${key}.${groupId}.${nestedKey}" is invalid.`)}if(!known){assertPreservedUnknownField(`${key}.${groupId}`,nestedKey,nestedValue,previousGroup)}}}return true}if(key==="groupHistoryLimit"){if(typeof value!=="number"||!Number.isFinite(value)){throw invalidConfig(`Channel field "${key}" must be a number.`)}return true}if(key==="identity"){assertStringRecord(key,value,new Set(["id","displayName","description"]));return true}if(key==="memoryScope"){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){const valid=nestedKey==="namespace"&&typeof nestedValue==="string"||nestedKey==="mode"&&nestedValue==="metadata-only";if(!valid){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}return true}return false}__name(assertSharedField,"assertSharedField");function containsUnsafeObjectKey(value){if(Array.isArray(value)){return value.some(item=>containsUnsafeObjectKey(item))}if(!isRecord(value))return false;return Object.entries(value).some(([key,nested])=>UNSAFE_OBJECT_KEYS.has(key)||containsUnsafeObjectKey(nested))}__name(containsUnsafeObjectKey,"containsUnsafeObjectKey");function assertDescriptorValue(field,value,path=field.key,previous){if(field.kind==="object"){if(isDeepStrictEqual(previous,value)&&!containsUnsafeObjectKey(value)){return}if(!isRecord(value)){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}const previousRecord=isRecord(previous)?previous:{};const properties=new Map(field.properties.map(property=>[property.key,property]));for(const[key,nestedValue]of Object.entries(value)){const property=properties.get(key);if(!property){assertPreservedUnknownField(path,key,nestedValue,previousRecord);continue}assertDescriptorValue(property,nestedValue,`${path}.${key}`,Object.hasOwn(previousRecord,key)?previousRecord[key]:void 0)}assertRequiredFields(field.properties,value,path);return}const invalidEnvironment=typeof value==="string"&&isEnvironmentReference(value)&&!field.envResolvable;if(invalidEnvironment){throw invalidConfig(`Channel field "${path}" does not support environment references.`)}const valid=(field.kind==="string"||field.kind==="secret")&&typeof value==="string"&&value.length>0||field.kind==="boolean"&&typeof value==="boolean"||field.kind==="number"&&typeof value==="number"&&Number.isFinite(value)&&(field.exclusiveMinimum===void 0||value>field.exclusiveMinimum)||field.kind==="enum"&&typeof value==="string"&&field.options?.some(option=>option.value===value)===true||field.kind==="string-list"&&Array.isArray(value)&&value.every(item=>typeof item==="string")||field.kind==="record"&&isRecord(value)&&Object.values(value).every(v=>typeof v==="string")&&!containsUnsafeObjectKey(value);if(!valid){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}}__name(assertDescriptorValue,"assertDescriptorValue");function assertRequiredFields(fields,values,path){for(const field of fields){if(!field.required)continue;const value=Object.hasOwn(values,field.key)?values[field.key]:void 0;if(value===void 0||value===null||value===""){const fieldPath=path?`${path}.${field.key}`:field.key;throw invalidConfig(`Channel field "${fieldPath}" is required.`)}}}__name(assertRequiredFields,"assertRequiredFields");function assertPreservedUnknownField(path,key,value,previous){const fieldPath=path?`${path}.${key}`:key;if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}if(containsUnsafeObjectKey(value)){throw invalidConfig(`Channel field "${fieldPath}" cannot use a reserved key.`)}if(Object.hasOwn(previous,key)&&isDeepStrictEqual(previous[key],value)){return}throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}__name(assertPreservedUnknownField,"assertPreservedUnknownField");function assertManagedConfig(config,previous,fields){const descriptorFields=new Map(fields.map(field=>[field.key,field]));for(const[key,value]of Object.entries(config)){if(key==="type")continue;const field=descriptorFields.get(key);if(field){assertDescriptorValue(field,value,field.key,Object.hasOwn(previous,key)?previous[key]:void 0);continue}if(assertSharedField(key,value,Object.hasOwn(previous,key)?previous[key]:void 0)){continue}assertPreservedUnknownField(void 0,key,value,previous)}assertRequiredFields(fields,config)}__name(assertManagedConfig,"assertManagedConfig");function validateSecretUpdate(update){if(!isRecord(update)){throw invalidSecret("Secret updates must be objects.")}const operation=update["operation"];const keys=Object.keys(update).sort();const valid=(operation==="preserve"||operation==="clear")&&keys.length===1&&keys[0]==="operation"||operation==="replace"&&keys.length===2&&keys[0]==="operation"&&keys[1]==="value"&&typeof update["value"]==="string"&&update["value"].length>0;if(!valid){throw invalidSecret("Secret updates contain an invalid operation.")}}__name(validateSecretUpdate,"validateSecretUpdate");function assertValidChannelSecretUpdates(updates){if(!isRecord(updates)){throw invalidSecret("Secret updates must be objects.")}for(const[key,update]of Object.entries(updates)){if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidSecret(`Secret update ${JSON.stringify(key)} is invalid.`)}validateSecretUpdate(update)}}__name(assertValidChannelSecretUpdates,"assertValidChannelSecretUpdates");function channelSettingsScope(workspaceCwd){const loaded=loadSettings(workspaceCwd,{skipLoadEnvironment:true});return loaded.workspaceSettingsActive?loaded.workspace:loaded.user}__name(channelSettingsScope,"channelSettingsScope");function channelRecordMap(value){const rawChannels=isRecord(value)?value:{};const channels={};for(const[name,config]of Object.entries(rawChannels)){if(UNSAFE_OBJECT_KEYS.has(name))continue;if(isRecord(config))channels[name]=config}return channels}__name(channelRecordMap,"channelRecordMap");function snapshotFrom(values){return{revision:revisionOf(values.channels,values.startupNames),channels:{...values.channels},startupNames:[...values.startupNames]}}__name(snapshotFrom,"snapshotFrom");function workspaceValues(workspaceCwd){const scope=channelSettingsScope(workspaceCwd);const settings=scope.settings;const startupNames=Array.isArray(settings.serve?.channels)?settings.serve.channels.filter(name=>typeof name==="string"):[];return{channels:channelRecordMap(settings.channels),storedChannels:channelRecordMap(scope.originalSettings.channels),startupNames}}__name(workspaceValues,"workspaceValues");var WorkspaceChannelSettingsStore=class{constructor(workspaceCwd){this.workspaceCwd=workspaceCwd}static{__name(this,"WorkspaceChannelSettingsStore")}snapshot(){return snapshotFrom(workspaceValues(this.workspaceCwd))}async upsert(name,options){assertUpsertChannelName(name);const secretUpdates=options.secrets===void 0?{}:options.secrets;assertValidChannelSecretUpdates(secretUpdates);const plugin=await getPlugin(options.config.type);if(!plugin?.management){throw new ChannelSettingsError("channel_settings_unmanageable",`Channel type "${options.config.type}" does not provide safe management metadata.`)}const secretKeys=new Set(plugin.management.fields.filter(field=>field.kind==="secret").map(field=>field.key));const envResolvableKeys=new Set(plugin.management.fields.filter(field=>field.envResolvable).map(field=>field.key));for(const key of Object.keys(secretUpdates)){if(!secretKeys.has(key)){throw invalidSecret(`Channel type "${options.config.type}" does not declare "${key}" as a secret.`)}}for(const key of secretKeys){if(Object.hasOwn(options.config,key)){throw invalidSecret(`Secret "${key}" must use an explicit preserve, replace, or clear operation.`)}}const{current,storedChannels}=this.assertRevision(options.expectedRevision);const storedPrevious=current.channels[name]??{};const hasPreviousOfType=storedPrevious["type"]===options.config.type;const previous=hasPreviousOfType?storedPrevious:{};const storedOnDisk=storedChannels[name]??{};const previousOnDisk=hasPreviousOfType?storedOnDisk:{};const nextConfig={...options.config};const storedReferences={};for(const key of secretKeys){const update=secretUpdates[key]??{operation:"preserve"};const value=applySecretUpdate(previous[key],update);if(value!==void 0)nextConfig[key]=value;if(update.operation==="preserve"&&previousOnDisk[key]!==void 0&&envResolvableKeys.has(key)){storedReferences[key]=previousOnDisk[key]}}for(const field of plugin.management.fields){const key=field.key;if(!field.envResolvable||secretKeys.has(key))continue;const onDisk=previousOnDisk[key];if(typeof onDisk!=="string"||!isEnvironmentReference(onDisk)){continue}if(nextConfig[key]!==previous[key])continue;storedReferences[key]=onDisk}try{parseChannelOutputMode(name,nextConfig["outputMode"],plugin.supportsOutputMode===true)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}assertManagedConfig(nextConfig,previous,plugin.supportsOutputMode===true?[...plugin.management.fields,CHANNEL_OUTPUT_MODE_FIELD]:plugin.management.fields);const multiSessionError=multiSessionCompatibilityError(name,{multiSession:nextConfig["multiSession"]===true,sessionRotation:parseSessionRotationConfig(name,nextConfig["sessionRotation"]),sessionScope:effectiveSessionScope(nextConfig,nextConfig["multiSession"]===true,plugin),groupHistoryLimit:nextConfig["groupHistoryLimit"],groups:isRecord(nextConfig["groups"])?nextConfig["groups"]:{},webhooks:nextConfig["webhooks"]});if(multiSessionError)throw invalidConfig(multiSessionError);try{const routing=parseMessageRoutingConfig(name,nextConfig);if(routing.messageRoutes!==void 0)nextConfig["messageRoutes"]=routing.messageRoutes;if(routing.defaultMessageRoute!==void 0)nextConfig["defaultMessageRoute"]=routing.defaultMessageRoute}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}let crossFieldError;try{crossFieldError=plugin.management.validateConfig?.(nextConfig);if(crossFieldError instanceof Promise){void crossFieldError.catch(()=>{})}}catch(error){throw invalidConfig(`Channel validateConfig failed: ${error instanceof Error?error.message:String(error)}`)}if(crossFieldError!==void 0){throw invalidConfig(typeof crossFieldError==="string"?crossFieldError:"Channel validateConfig must return a string error message.")}const channels={...storedChannels,[name]:{...nextConfig,...storedReferences}};saveSettings(channelSettingsScope(this.workspaceCwd),{channels},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async remove(name,options){assertSafeChannelName(name);const{current,storedChannels}=this.assertRevision(options.expectedRevision);const configured=Object.hasOwn(current.channels,name);if(!configured){if(!current.startupNames.includes(name))return current;saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:current.startupNames.filter(startupName=>startupName!==name)}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}const channels={...storedChannels};delete channels[name];const hasAllSentinel=current.startupNames.some(isAllStartupName);const startupNames=hasAllSentinel?Object.keys(channels).some(channelName=>!isAllStartupName(channelName))?["all"]:[]:current.startupNames.filter(startupName=>startupName!==name);saveSettings(channelSettingsScope(this.workspaceCwd),{channels,serve:{channels:startupNames}},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async setStartupNames(names,options){for(const name of names){assertSafeChannelName(name)}this.assertRevision(options.expectedRevision);saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:[...names]}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}assertRevision(expectedRevision){const values=workspaceValues(this.workspaceCwd);const current=snapshotFrom(values);if(current.revision!==expectedRevision){throw new ChannelSettingsError("channel_settings_conflict","Channel settings changed; reload before trying again.")}return{current,storedChannels:values.storedChannels}}};export{ChannelSettingsError,assertValidChannelSecretUpdates,WorkspaceChannelSettingsStore};
3
+ import{effectiveSessionScope,multiSessionCompatibilityError,parseMessageRoutingConfig,parseSessionRotationConfig}from"./chunk-FJUXMWZW.js";import{UNSAFE_OBJECT_KEYS,getPlugin}from"./chunk-MHZY2JYX.js";import{CHANNEL_OUTPUT_MODE_FIELD,parseChannelOutputMode}from"./chunk-44WSAMWG.js";import{loadSettings,saveSettings}from"./chunk-MVGQFFIK.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import{isDeepStrictEqual}from"node:util";var ChannelSettingsError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="ChannelSettingsError"}static{__name(this,"ChannelSettingsError")}};function revisionOf(channels,startupNames){return createHash("sha256").update(JSON.stringify({channels,startupNames})).digest("hex")}__name(revisionOf,"revisionOf");function applySecretUpdate(current,update){validateSecretUpdate(update);if(update.operation==="preserve")return current;if(update.operation==="clear")return void 0;if(typeof update.value!=="string"||update.value.length===0){throw invalidSecret("Secret replacements must be non-empty strings.")}return update.value}__name(applySecretUpdate,"applySecretUpdate");function invalidSecret(message){return new ChannelSettingsError("channel_settings_invalid_secret",message)}__name(invalidSecret,"invalidSecret");function invalidConfig(message){return new ChannelSettingsError("channel_settings_invalid_config",message)}__name(invalidConfig,"invalidConfig");function assertSafeChannelName(name){if(UNSAFE_OBJECT_KEYS.has(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is not allowed.`)}}__name(assertSafeChannelName,"assertSafeChannelName");function assertUpsertChannelName(name){assertSafeChannelName(name);if(isAllStartupName(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is reserved for startup selection.`)}}__name(assertUpsertChannelName,"assertUpsertChannelName");function isAllStartupName(name){return name.trim()==="all"}__name(isAllStartupName,"isAllStartupName");function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord,"isRecord");function isEnvironmentReference(value){return/^\$[A-Za-z_][A-Za-z0-9_]*$/.test(value)}__name(isEnvironmentReference,"isEnvironmentReference");function assertStringRecord(key,value,allowedKeys){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){if(!allowedKeys.has(nestedKey)||typeof nestedValue!=="string"){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}}__name(assertStringRecord,"assertStringRecord");function assertSharedField(key,value,previous){if(key==="messageRoutes"||key==="defaultMessageRoute"){return true}if(key==="multiSession"){if(typeof value!=="boolean"){throw invalidConfig(`Channel field "${key}" must be a boolean.`)}return true}if(key==="sessionRotation"){try{parseSessionRotationConfig("settings",value)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}return true}if(key==="groupSenderPolicy"||key==="allowedGroupUsers"){throw invalidConfig(`Channel field "${key}" moved to groups["*"].${key==="groupSenderPolicy"?"senders":"allowedUsers"}.`)}const enumValues={privatePolicy:new Set(["disabled","allowlist","pairing","open"]),senderPolicy:new Set(["allowlist","pairing","open"]),dmPolicy:new Set(["open","disabled"]),groupPolicy:new Set(["disabled","allowlist","pairing","open"]),sessionScope:new Set(["user","thread","chat_thread","single"]),dispatchMode:new Set(["steer","followup","collect"])};if(Object.hasOwn(enumValues,key)){if(typeof value!=="string"||!enumValues[key].has(value)){throw invalidConfig(`Channel field "${key}" has an invalid value.`)}return true}if(["model","cwd","approvalMode","instructions"].includes(key)){if(typeof value!=="string"){throw invalidConfig(`Channel field "${key}" must be a string.`)}return true}if(key==="allowedUsers"||key==="operators"){if(!Array.isArray(value)||value.some(item=>typeof item!=="string")){throw invalidConfig(`Channel field "${key}" must be a string array.`)}return true}if(key==="groups"){if(!isRecord(value)){if(containsUnsafeObjectKey(value)||!isDeepStrictEqual(previous,value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}return true}const previousGroups=isRecord(previous)?previous:{};for(const[groupId,groupConfig]of Object.entries(value)){if(UNSAFE_OBJECT_KEYS.has(groupId)||!isRecord(groupConfig)){throw invalidConfig(`Channel field "${key}.${groupId}" is invalid.`)}const previousGroup=isRecord(previousGroups[groupId])?previousGroups[groupId]:{};for(const[nestedKey,nestedValue]of Object.entries(groupConfig)){const known=["requireMention","dispatchMode","groupHistoryLimit","senders","allowedUsers"].includes(nestedKey);const valid=nestedKey==="requireMention"&&typeof nestedValue==="boolean"||nestedKey==="dispatchMode"&&typeof nestedValue==="string"&&["collect","steer","followup"].includes(nestedValue)||nestedKey==="groupHistoryLimit"&&typeof nestedValue==="number"&&Number.isFinite(nestedValue)||nestedKey==="senders"&&typeof nestedValue==="string"&&["open","allowlist"].includes(nestedValue)||nestedKey==="allowedUsers"&&Array.isArray(nestedValue)&&nestedValue.every(item=>typeof item==="string");if(known&&!valid&&!(nestedKey!=="senders"&&Object.hasOwn(previousGroup,nestedKey)&&isDeepStrictEqual(previousGroup[nestedKey],nestedValue)&&!containsUnsafeObjectKey(nestedValue))){throw invalidConfig(`Channel field "${key}.${groupId}.${nestedKey}" is invalid.`)}if(!known){assertPreservedUnknownField(`${key}.${groupId}`,nestedKey,nestedValue,previousGroup)}}}return true}if(key==="groupHistoryLimit"){if(typeof value!=="number"||!Number.isFinite(value)){throw invalidConfig(`Channel field "${key}" must be a number.`)}return true}if(key==="identity"){assertStringRecord(key,value,new Set(["id","displayName","description"]));return true}if(key==="memoryScope"){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){const valid=nestedKey==="namespace"&&typeof nestedValue==="string"||nestedKey==="mode"&&nestedValue==="metadata-only";if(!valid){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}return true}return false}__name(assertSharedField,"assertSharedField");function containsUnsafeObjectKey(value){if(Array.isArray(value)){return value.some(item=>containsUnsafeObjectKey(item))}if(!isRecord(value))return false;return Object.entries(value).some(([key,nested])=>UNSAFE_OBJECT_KEYS.has(key)||containsUnsafeObjectKey(nested))}__name(containsUnsafeObjectKey,"containsUnsafeObjectKey");function assertDescriptorValue(field,value,path=field.key,previous){if(field.kind==="object"){if(isDeepStrictEqual(previous,value)&&!containsUnsafeObjectKey(value)){return}if(!isRecord(value)){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}const previousRecord=isRecord(previous)?previous:{};const properties=new Map(field.properties.map(property=>[property.key,property]));for(const[key,nestedValue]of Object.entries(value)){const property=properties.get(key);if(!property){assertPreservedUnknownField(path,key,nestedValue,previousRecord);continue}assertDescriptorValue(property,nestedValue,`${path}.${key}`,Object.hasOwn(previousRecord,key)?previousRecord[key]:void 0)}assertRequiredFields(field.properties,value,path);return}const invalidEnvironment=typeof value==="string"&&isEnvironmentReference(value)&&!field.envResolvable;if(invalidEnvironment){throw invalidConfig(`Channel field "${path}" does not support environment references.`)}const valid=(field.kind==="string"||field.kind==="secret")&&typeof value==="string"&&value.length>0||field.kind==="boolean"&&typeof value==="boolean"||field.kind==="number"&&typeof value==="number"&&Number.isFinite(value)&&(field.exclusiveMinimum===void 0||value>field.exclusiveMinimum)||field.kind==="enum"&&typeof value==="string"&&field.options?.some(option=>option.value===value)===true||field.kind==="string-list"&&Array.isArray(value)&&value.every(item=>typeof item==="string")||field.kind==="record"&&isRecord(value)&&Object.values(value).every(v=>typeof v==="string")&&!containsUnsafeObjectKey(value);if(!valid){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}}__name(assertDescriptorValue,"assertDescriptorValue");function assertRequiredFields(fields,values,path){for(const field of fields){if(!field.required)continue;const value=Object.hasOwn(values,field.key)?values[field.key]:void 0;if(value===void 0||value===null||value===""){const fieldPath=path?`${path}.${field.key}`:field.key;throw invalidConfig(`Channel field "${fieldPath}" is required.`)}}}__name(assertRequiredFields,"assertRequiredFields");function assertPreservedUnknownField(path,key,value,previous){const fieldPath=path?`${path}.${key}`:key;if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}if(containsUnsafeObjectKey(value)){throw invalidConfig(`Channel field "${fieldPath}" cannot use a reserved key.`)}if(Object.hasOwn(previous,key)&&isDeepStrictEqual(previous[key],value)){return}throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}__name(assertPreservedUnknownField,"assertPreservedUnknownField");function assertManagedConfig(config,previous,fields){const descriptorFields=new Map(fields.map(field=>[field.key,field]));for(const[key,value]of Object.entries(config)){if(key==="type")continue;const field=descriptorFields.get(key);if(field){assertDescriptorValue(field,value,field.key,Object.hasOwn(previous,key)?previous[key]:void 0);continue}if(assertSharedField(key,value,Object.hasOwn(previous,key)?previous[key]:void 0)){continue}assertPreservedUnknownField(void 0,key,value,previous)}assertRequiredFields(fields,config)}__name(assertManagedConfig,"assertManagedConfig");function validateSecretUpdate(update){if(!isRecord(update)){throw invalidSecret("Secret updates must be objects.")}const operation=update["operation"];const keys=Object.keys(update).sort();const valid=(operation==="preserve"||operation==="clear")&&keys.length===1&&keys[0]==="operation"||operation==="replace"&&keys.length===2&&keys[0]==="operation"&&keys[1]==="value"&&typeof update["value"]==="string"&&update["value"].length>0;if(!valid){throw invalidSecret("Secret updates contain an invalid operation.")}}__name(validateSecretUpdate,"validateSecretUpdate");function assertValidChannelSecretUpdates(updates){if(!isRecord(updates)){throw invalidSecret("Secret updates must be objects.")}for(const[key,update]of Object.entries(updates)){if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidSecret(`Secret update ${JSON.stringify(key)} is invalid.`)}validateSecretUpdate(update)}}__name(assertValidChannelSecretUpdates,"assertValidChannelSecretUpdates");function channelSettingsScope(workspaceCwd){const loaded=loadSettings(workspaceCwd,{skipLoadEnvironment:true});return loaded.workspaceSettingsActive?loaded.workspace:loaded.user}__name(channelSettingsScope,"channelSettingsScope");function channelRecordMap(value){const rawChannels=isRecord(value)?value:{};const channels={};for(const[name,config]of Object.entries(rawChannels)){if(UNSAFE_OBJECT_KEYS.has(name))continue;if(isRecord(config))channels[name]=config}return channels}__name(channelRecordMap,"channelRecordMap");function snapshotFrom(values){return{revision:revisionOf(values.channels,values.startupNames),channels:{...values.channels},startupNames:[...values.startupNames]}}__name(snapshotFrom,"snapshotFrom");function workspaceValues(workspaceCwd){const scope=channelSettingsScope(workspaceCwd);const settings=scope.settings;const startupNames=Array.isArray(settings.serve?.channels)?settings.serve.channels.filter(name=>typeof name==="string"):[];return{channels:channelRecordMap(settings.channels),storedChannels:channelRecordMap(scope.originalSettings.channels),startupNames}}__name(workspaceValues,"workspaceValues");var WorkspaceChannelSettingsStore=class{constructor(workspaceCwd){this.workspaceCwd=workspaceCwd}static{__name(this,"WorkspaceChannelSettingsStore")}snapshot(){return snapshotFrom(workspaceValues(this.workspaceCwd))}async upsert(name,options){assertUpsertChannelName(name);const secretUpdates=options.secrets===void 0?{}:options.secrets;assertValidChannelSecretUpdates(secretUpdates);const plugin=await getPlugin(options.config.type);if(!plugin?.management){throw new ChannelSettingsError("channel_settings_unmanageable",`Channel type "${options.config.type}" does not provide safe management metadata.`)}const secretKeys=new Set(plugin.management.fields.filter(field=>field.kind==="secret").map(field=>field.key));const envResolvableKeys=new Set(plugin.management.fields.filter(field=>field.envResolvable).map(field=>field.key));for(const key of Object.keys(secretUpdates)){if(!secretKeys.has(key)){throw invalidSecret(`Channel type "${options.config.type}" does not declare "${key}" as a secret.`)}}for(const key of secretKeys){if(Object.hasOwn(options.config,key)){throw invalidSecret(`Secret "${key}" must use an explicit preserve, replace, or clear operation.`)}}const{current,storedChannels}=this.assertRevision(options.expectedRevision);const storedPrevious=current.channels[name]??{};const hasPreviousOfType=storedPrevious["type"]===options.config.type;const previous=hasPreviousOfType?storedPrevious:{};const storedOnDisk=storedChannels[name]??{};const previousOnDisk=hasPreviousOfType?storedOnDisk:{};const nextConfig={...options.config};const storedReferences={};for(const key of secretKeys){const update=secretUpdates[key]??{operation:"preserve"};const value=applySecretUpdate(previous[key],update);if(value!==void 0)nextConfig[key]=value;if(update.operation==="preserve"&&previousOnDisk[key]!==void 0&&envResolvableKeys.has(key)){storedReferences[key]=previousOnDisk[key]}}for(const field of plugin.management.fields){const key=field.key;if(!field.envResolvable||secretKeys.has(key))continue;const onDisk=previousOnDisk[key];if(typeof onDisk!=="string"||!isEnvironmentReference(onDisk)){continue}if(nextConfig[key]!==previous[key])continue;storedReferences[key]=onDisk}try{parseChannelOutputMode(name,nextConfig["outputMode"],plugin.supportsOutputMode===true)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}assertManagedConfig(nextConfig,previous,plugin.supportsOutputMode===true?[...plugin.management.fields,CHANNEL_OUTPUT_MODE_FIELD]:plugin.management.fields);const multiSessionError=multiSessionCompatibilityError(name,{multiSession:nextConfig["multiSession"]===true,sessionRotation:parseSessionRotationConfig(name,nextConfig["sessionRotation"]),sessionScope:effectiveSessionScope(nextConfig,nextConfig["multiSession"]===true,plugin),groupHistoryLimit:nextConfig["groupHistoryLimit"],groups:isRecord(nextConfig["groups"])?nextConfig["groups"]:{},webhooks:nextConfig["webhooks"]});if(multiSessionError)throw invalidConfig(multiSessionError);try{const routing=parseMessageRoutingConfig(name,nextConfig);if(routing.messageRoutes!==void 0)nextConfig["messageRoutes"]=routing.messageRoutes;if(routing.defaultMessageRoute!==void 0)nextConfig["defaultMessageRoute"]=routing.defaultMessageRoute}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}let crossFieldError;try{crossFieldError=plugin.management.validateConfig?.(nextConfig);if(crossFieldError instanceof Promise){void crossFieldError.catch(()=>{})}}catch(error){throw invalidConfig(`Channel validateConfig failed: ${error instanceof Error?error.message:String(error)}`)}if(crossFieldError!==void 0){throw invalidConfig(typeof crossFieldError==="string"?crossFieldError:"Channel validateConfig must return a string error message.")}const channels={...storedChannels,[name]:{...nextConfig,...storedReferences}};saveSettings(channelSettingsScope(this.workspaceCwd),{channels},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async remove(name,options){assertSafeChannelName(name);const{current,storedChannels}=this.assertRevision(options.expectedRevision);const configured=Object.hasOwn(current.channels,name);if(!configured){if(!current.startupNames.includes(name))return current;saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:current.startupNames.filter(startupName=>startupName!==name)}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}const channels={...storedChannels};delete channels[name];const hasAllSentinel=current.startupNames.some(isAllStartupName);const startupNames=hasAllSentinel?Object.keys(channels).some(channelName=>!isAllStartupName(channelName))?["all"]:[]:current.startupNames.filter(startupName=>startupName!==name);saveSettings(channelSettingsScope(this.workspaceCwd),{channels,serve:{channels:startupNames}},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async setStartupNames(names,options){for(const name of names){assertSafeChannelName(name)}this.assertRevision(options.expectedRevision);saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:[...names]}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}assertRevision(expectedRevision){const values=workspaceValues(this.workspaceCwd);const current=snapshotFrom(values);if(current.revision!==expectedRevision){throw new ChannelSettingsError("channel_settings_conflict","Channel settings changed; reload before trying again.")}return{current,storedChannels:values.storedChannels}}};export{ChannelSettingsError,assertValidChannelSecretUpdates,WorkspaceChannelSettingsStore};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{registerCleanup}from"./chunk-UFTIUKD4.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var MAX_PROFILES=5;var RATE_LIMIT_MS=3e4;var MIN_FREE_BYTES_AFTER_WRITE=256*1024*1024;var DEFAULT_SAMPLING_INTERVAL_US=1e3;var ESTIMATED_PROFILE_BYTES=10*1024*1024;var state="idle";var session=null;var initialized=false;var signalHandlerRegistered=false;var lastWriteByDir=new Map;function initCpuProfiler(){if(initialized)return;initialized=true;registerSignalHandler();registerCleanup(async()=>{if(state==="recording"){const result=await stopCpuProfile();if(result.ok){process.stderr.write(`[cpu-profiler] Profile written: ${result.filePath}
3
+ import{registerCleanup}from"./chunk-LGYXZJI3.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var MAX_PROFILES=5;var RATE_LIMIT_MS=3e4;var MIN_FREE_BYTES_AFTER_WRITE=256*1024*1024;var DEFAULT_SAMPLING_INTERVAL_US=1e3;var ESTIMATED_PROFILE_BYTES=10*1024*1024;var state="idle";var session=null;var initialized=false;var signalHandlerRegistered=false;var lastWriteByDir=new Map;function initCpuProfiler(){if(initialized)return;initialized=true;registerSignalHandler();registerCleanup(async()=>{if(state==="recording"){const result=await stopCpuProfile();if(result.ok){process.stderr.write(`[cpu-profiler] Profile written: ${result.filePath}
4
4
  `)}}});const enabled=process.env["QWEN_CODE_CPU_PROFILE"]==="1";if(!enabled)return;void startCpuProfile().then(result=>{if(!result.ok){process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}
5
5
  `)}})}__name(initCpuProfiler,"initCpuProfiler");async function startCpuProfile(opts){if(state!=="idle"){return{ok:false,error:state==="recording"?"CPU profiling is already in progress.":"CPU profiler is currently stopping. Please wait a moment and try again."}}state="recording";try{const inspectorSession=await getOrCreateSession();await inspectorSession.post("Profiler.enable");await inspectorSession.post("Profiler.setSamplingInterval",{interval:opts?.samplingInterval??DEFAULT_SAMPLING_INTERVAL_US});await inspectorSession.post("Profiler.start");return{ok:true}}catch(error){state="idle";disconnectSession();return{ok:false,error:formatError(error)}}}__name(startCpuProfile,"startCpuProfile");async function stopCpuProfile(options){if(state!=="recording"){return{ok:false,error:state==="idle"?"CPU profiler is not recording.":"CPU profiler is already stopping."}}const outputDir=options?.outputDir??defaultOutputDir();const now=options?.now??new Date;const rateLimitMs=options?.rateLimitMs??RATE_LIMIT_MS;const maxProfiles=options?.maxProfiles??MAX_PROFILES;try{enforceRateLimit(outputDir,now,rateLimitMs)}catch(error){state="idle";if(session){session.post("Profiler.stop").catch(()=>{});session.post("Profiler.disable").catch(()=>{})}disconnectSession();return{ok:false,error:formatError(error)}}state="stopping";try{if(!session){throw new Error("Inspector session lost unexpectedly during Profiler.stop; the profile data could not be retrieved.")}const result=await session.post("Profiler.stop");if(!result.profile){throw new Error("V8 Profiler.stop returned an empty profile; recording may have been interrupted.")}await session.post("Profiler.disable");fs.mkdirSync(outputDir,{recursive:true,mode:448});try{fs.chmodSync(outputDir,448)}catch{}checkDiskSpace(outputDir);const filePath=path.join(outputDir,`qwen-code-cpu-${process.pid}-${formatTimestamp(now)}.cpuprofile`);try{fs.writeFileSync(filePath,JSON.stringify(result.profile),{mode:384})}catch(writeError){try{fs.rmSync(filePath,{force:true})}catch{}throw writeError}recordWrite(outputDir,now);cleanupOldProfiles(outputDir,maxProfiles);state="idle";return{ok:true,filePath}}catch(error){state="idle";disconnectSession();return{ok:false,error:formatError(error)}}}__name(stopCpuProfile,"stopCpuProfile");function isCpuProfileRecording(){return state==="recording"}__name(isCpuProfileRecording,"isCpuProfileRecording");function registerSignalHandler(){if(signalHandlerRegistered)return;if(process.platform==="win32")return;signalHandlerRegistered=true;process.on("SIGUSR1",handleSigusr1)}__name(registerSignalHandler,"registerSignalHandler");function defaultOutputDir(){return path.join(os.homedir(),".qwen","cpu-profiles")}__name(defaultOutputDir,"defaultOutputDir");function formatTimestamp(now){return now.toISOString().replace(/[:.]/g,"-")}__name(formatTimestamp,"formatTimestamp");function formatError(error){return error instanceof Error?error.message:String(error)}__name(formatError,"formatError");var sessionFactory=null;async function getOrCreateSession(){if(session)return session;if(sessionFactory){session=await sessionFactory();return session}const inspectorModule=await import("node:inspector/promises");const newSession=new inspectorModule.Session;newSession.connect();session=newSession;return session}__name(getOrCreateSession,"getOrCreateSession");function disconnectSession(){if(session){try{session.disconnect()}catch{}session=null}}__name(disconnectSession,"disconnectSession");function handleSigusr1(){if(state==="idle"){void startCpuProfile().then(result=>{if(result.ok){process.stderr.write(`[cpu-profiler] Recording started (PID ${process.pid}). Send SIGUSR1 again to stop.
6
6
  `)}else{process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
3
  import{remarkParse,unified}from"./chunk-AZ3CKMCT.js";import{estimateTextTokens}from"./chunk-RP57XAJ2.js";import{ignoreBrokenPipe}from"./chunk-SLPJ4OII.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{homedir}from"node:os";import path2 from"node:path";import*as fs2 from"node:fs/promises";init_esbuild_shims();init_esbuild_shims();var MEMORY_IMPORT_BUDGET={maxCalls:32,maxReservedTokens:512e3,batchSections:8,sourceBytes:65536,contextBytes:32768,outputTokens:8192,promptBytes:32768};function packMemoryImportSections(sections){const groups=new Map;for(const section of[...sections].sort((a,b)=>a.id.localeCompare(b.id))){const key=`${section.scope??""}:${section.groupId}`;const group=groups.get(key)??[];group.push(section);groups.set(key,group)}const batches=[];for(const group of groups.values()){let batch=[];let bytes=0;for(const section of group){const size=Buffer.byteLength(section.content);if(batch.length&&(batch.length===MEMORY_IMPORT_BUDGET.batchSections||bytes+size>MEMORY_IMPORT_BUDGET.sourceBytes)){batches.push(batch);batch=[];bytes=0}batch.push(section);bytes+=size}if(batch.length)batches.push(batch)}return batches}__name(packMemoryImportSections,"packMemoryImportSections");function estimateMemoryImport(sections){const batches=packMemoryImportSections(sections);const modelCalls=batches.length*2;const sourceTokens=sections.reduce((n,section)=>n+estimateTextTokens(section.content),0);const sourceBytes=Buffer.byteLength(JSON.stringify(sections.map(({id,content})=>({id,content}))));const reservedTokens=modelCalls*(MEMORY_IMPORT_BUDGET.contextBytes+MEMORY_IMPORT_BUDGET.promptBytes+MEMORY_IMPORT_BUDGET.outputTokens+1024)+sourceBytes+modelCalls;return{basis:"source-only-with-context-reserve",modelCalls,sourceTokens,maxOutputTokens:modelCalls*MEMORY_IMPORT_BUDGET.outputTokens,reservedTokens,exceedsBudget:modelCalls>MEMORY_IMPORT_BUDGET.maxCalls||reservedTokens>MEMORY_IMPORT_BUDGET.maxReservedTokens,limits:MEMORY_IMPORT_BUDGET}}__name(estimateMemoryImport,"estimateMemoryImport");import{createHash}from"node:crypto";import*as fs from"node:fs/promises";import path from"node:path";import{constants}from"node:fs";var MemoryImportRequestError=class extends Error{static{__name(this,"MemoryImportRequestError")}};var IMPORT_LIMITS={files:256,fileBytes:512*1024,totalBytes:8*1024*1024,sectionBytes:64*1024,headings:4096,markdownLines:16384,inlineMarkers:4096};function digest(value){return createHash("sha256").update(value).digest("hex")}__name(digest,"digest");function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(record,"record");function validSourcePath(value){return value.length<=512&&!/[\\\p{Cc}]/u.test(value)&&!value.startsWith("/")&&!/^[a-z]:/i.test(value)&&value.split("/").every(part=>part!==""&&part!=="."&&part!=="..")&&(/^(?:MEMORY|memory_summary)\.md$/.test(value)||/^rollout_summaries\/[\w.-]+\.md$/.test(value))}__name(validSourcePath,"validSourcePath");function validateSource(value){if(!record(value)||value["version"]!==1||value["source"]!=="codex"||!Array.isArray(value["files"])||value["files"].length===0||value["files"].length>IMPORT_LIMITS.files)throw new MemoryImportRequestError("Invalid version 1 Codex source set.");let bytes=0;const seen=new Set;const files=value["files"].map(file=>{if(!record(file)||typeof file["path"]!=="string"||!validSourcePath(file["path"])||typeof file["content"]!=="string"||file["content"].includes("\0"))throw new MemoryImportRequestError("Invalid Codex Markdown resource. Only memory Markdown and rollout_summaries/*.md are accepted.");const size=Buffer.byteLength(file["content"]);bytes+=size;if(size>IMPORT_LIMITS.fileBytes||bytes>IMPORT_LIMITS.totalBytes||seen.has(file["path"].toLowerCase()))throw new MemoryImportRequestError("Source exceeds limits or contains duplicate paths.");seen.add(file["path"].toLowerCase());return{path:file["path"],content:file["content"]}});if(!files.some(file=>file.path==="MEMORY.md"||file.path==="memory_summary.md"))throw new MemoryImportRequestError("Select the Codex memories folder containing MEMORY.md or memory_summary.md.");return{version:1,source:"codex",files:files.sort((a,b)=>a.path.localeCompare(b.path))}}__name(validateSource,"validateSource");var parser=unified().use(remarkParse);function headingTitle(raw){const atx=raw.match(/^ {0,3}#{1,6}(?:[\t ]+|$)/);if(atx)return raw.slice(atx[0].length).replace(/[\t ]+#+[\t ]*$/,"").trim();return raw.split(/\r\n|[\r\n]/).slice(0,-1).join(" ").trim()}__name(headingTitle,"headingTitle");function scopeFor(content,title,summary){const scopes=[];for(const match of content.matchAll(/(?:^|[\s;(])cwd\s*[=:]\s*(?:`([^`\n]+)`|([^\r\n,;()\s]+))/gim)){if(match[1]!==void 0){scopes.push({value:match[1].trim(),quoted:true,prose:false});continue}const trailing=content.slice(match.index+match[0].length).split(/\r\n|[\r\n]/,1)[0].trim();scopes.push({value:match[2].trim(),quoted:false,prose:/[^\s,;()]/.test(trailing)})}const heading=title.trim();if(/^(?:\/|[A-Za-z]:[\\/])/.test(heading))scopes.push({value:heading.replace(/^`|`$/g,""),quoted:false,prose:false});const strip=__name(value=>value.replace(/[\\/]+$/,"").replace(/[.:!?'"]+$/,""),"strip");const unique=[...new Set(scopes.map(scope=>strip(scope.value)))];if(unique.length===1&&/^(?:\/|[A-Za-z]:[\\/])/.test(unique[0])&&scopes.every(scope=>!scope.prose&&!/[*?{}[\]\p{Cc}]|\bcwd\s*[=:]/u.test(scope.value)&&(scope.quoted||!/\s/.test(scope.value))))return{suggestedScope:"project",sourceProject:unique[0],reason:"Source project hint; explicit target mapping is required."};if(scopes.length)return{suggestedScope:"unassigned",reason:"Ambiguous or unsupported project scope; assign explicitly."};if(summary&&/^(?:user profile|user preferences)$/i.test(title))return{suggestedScope:"user",reason:"Explicit user-level summary section."};return{suggestedScope:"unassigned",reason:"No reliable project scope; assign explicitly."}}__name(scopeFor,"scopeFor");function previewSource(input){const source=validateSource(input);const sections=[];const warnings=[];let headingCount=0;let lineCount=0;let markerCount=0;let expandedBytes=0;const paths=new Set(source.files.map(file=>file.path));const referenced=new Set;for(const file of source.files.filter(f=>!f.path.startsWith("rollout_summaries/"))){for(const match of file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g))referenced.add(match[0])}for(const ref of referenced)if(!paths.has(ref))warnings.push(`Missing referenced Markdown: ${ref}`);for(const file of source.files){if(file.path.startsWith("rollout_summaries/")&&!referenced.has(file.path)){warnings.push(`Unreferenced supporting resource excluded: ${file.path}`);continue}const atxCandidates=file.content.match(/^ {0,3}#{1,6}(?:[\t ]|$)/gm)?.length??0;if(headingCount+atxCandidates>4*IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");for(let i=0;i<file.content.length;i++){const char=file.content[i];if(char==="\n"||char==="\r"&&file.content[i+1]!=="\n")lineCount++;if("*_~[]<>!`&\\".includes(char))markerCount++;if(lineCount>IMPORT_LIMITS.markdownLines||markerCount>IMPORT_LIMITS.inlineMarkers)throw new MemoryImportRequestError("Source exceeds the Markdown complexity limit; split it into smaller source sets before importing.")}const tree=parser.parse(file.content);const headings=tree.children.filter(node=>node.type==="heading").map((node,index,nodes)=>({offset:node.position.start.offset,line:node.position.start.line,depth:node.depth,title:headingTitle(file.content.slice(node.position.start.offset,node.position.end.offset)),preface:file.content.slice(node.position.start.offset,nodes[index+1]?.position.start.offset).trim()}));headingCount+=headings.length;if(headingCount>IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");const scopedDepths=headings.filter(heading=>/^(?:`?\/|`?[A-Za-z]:[\\/])/.test(heading.title)||/\bcwd\s*[=:]/i.test(heading.preface)).map(heading=>heading.depth);const minDepth=headings.length?Math.min(...headings.map(h=>h.depth)):1;const depth=Math.max(file.path==="memory_summary.md"?2:minDepth,...scopedDepths);const boundaries=headings.filter(heading=>heading.depth<=depth);if(!boundaries.length||boundaries[0].offset>0)boundaries.unshift({offset:0,line:1,title:file.path,depth:0,preface:""});for(let i=0;i<boundaries.length;i++){const boundary=boundaries[i];const own=file.content.slice(boundary.offset,boundaries[i+1]?.offset).trim();if(!own||/^v\d+$/.test(own)||own.split(/\r\n|[\r\n]/).every(line=>!line.trim()||/^#{1,6}\s/.test(line)))continue;const ancestors=[];for(const heading of headings){if(heading.offset>=boundary.offset)break;while(ancestors.length&&ancestors.at(-1).depth>=heading.depth)ancestors.pop();ancestors.push(heading)}while(ancestors.length&&ancestors.at(-1).depth>=boundary.depth)ancestors.pop();const parts=[...ancestors.map(heading=>heading.preface),own];expandedBytes+=parts.reduce((bytes,part)=>bytes+Buffer.byteLength(part),0)+2*(parts.length-1);if(expandedBytes>IMPORT_LIMITS.totalBytes)throw new MemoryImportRequestError("Source expanded context exceeds 8 MiB; split shared context and project groups before importing.");const content=parts.join("\n\n");let scope=scopeFor(content,boundary.title,file.path==="memory_summary.md");if(scope.suggestedScope==="unassigned"&&!/\bcwd\s*[=:]/i.test(content)){const parent=ancestors.at(-1);if(parent)scope=scopeFor(content,parent.title,file.path==="memory_summary.md")}const references=[...new Set(Array.from(content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0]))];const selectable=Buffer.byteLength(content)<=IMPORT_LIMITS.sectionBytes;if(!selectable)warnings.push(`${file.path}:${boundary.line}: section exceeds ${IMPORT_LIMITS.sectionBytes} bytes; split it before import.`);const id=digest(`${file.path}\0${content}`);if(sections.some(section=>section.id===id))continue;sections.push({id,groupId:digest(`${scope.suggestedScope}\0${scope.sourceProject??""}`),title:boundary.title,path:file.path,line:boundary.line,content,references,...scope,selectable})}}const groups=new Map;for(const section of sections){const group=groups.get(section.groupId)??{id:section.groupId,scope:section.suggestedScope,sourceProject:section.sourceProject,sectionIds:[]};group.sectionIds.push(section.id);groups.set(group.id,group)}return{version:1,kind:"preview",digest:digest(JSON.stringify(source)),groups:[...groups.values()].map(group=>({...group,estimate:estimateMemoryImport(sections.filter(section=>section.selectable&&section.groupId===group.id))})),sections,warnings,estimate:estimateMemoryImport(sections.filter(section=>section.selectable))}}__name(previewSource,"previewSource");async function readLocalSource(directory){const root=await fs.realpath(directory);const files=[];const read=__name(async relative=>{const file=path.join(root,relative);const info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>IMPORT_LIMITS.fileBytes)throw new Error("Source must contain regular bounded Markdown files.");const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));try{const opened=await handle.stat();if(!opened.isFile()||opened.size>IMPORT_LIMITS.fileBytes)throw new Error("Source changed while opening.");const buffer=Buffer.alloc(IMPORT_LIMITS.fileBytes+1);let length=0;while(length<buffer.length){const read2=await handle.read(buffer,length,buffer.length-length,null);if(!read2.bytesRead)break;length+=read2.bytesRead}if(length>IMPORT_LIMITS.fileBytes||files.reduce((sum,entry)=>sum+Buffer.byteLength(entry.content),length)>IMPORT_LIMITS.totalBytes)throw new Error("Source exceeds byte limits.");files.push({path:relative,content:buffer.subarray(0,length).toString("utf8")})}finally{await handle.close()}},"read");for(const name of["MEMORY.md","memory_summary.md"]){try{await read(name)}catch(error){if(error.code!=="ENOENT")throw error}}const refs=new Set(files.flatMap(file=>Array.from(file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0])));if(refs.size+files.length>IMPORT_LIMITS.files)throw new Error("Too many referenced source files.");if(refs.size){const dir=await fs.lstat(path.join(root,"rollout_summaries")).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(dir&&(!dir.isDirectory()||dir.isSymbolicLink()))throw new Error("Supporting resource directory must not be a symlink.");if(dir)for(const ref of refs){try{await read(ref)}catch(error){if(error.code!=="ENOENT")throw error}}}return validateSource({version:1,source:"codex",files})}__name(readLocalSource,"readLocalSource");var writeStdoutLineFlushed=__name(message=>new Promise((resolve,reject)=>process.stdout.write(message.endsWith("\n")?message:`${message}
4
- `,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-ED3UEKWP.js");const service=await createLocalMemoryImportService();let task=await service.submit(source,selection,args["idempotency-key"]);if(args["retry"])task=await service.retry(task.id);task=await service.idle(task.id);await writeStdoutLineFlushed(JSON.stringify(task));if(task.status!=="completed"||task.items.some(item=>item.status==="conflict"))process.exitCode=1},"handler")}).demandCommand(1).version(false),"builder"),handler:__name(()=>{},"handler")};export{MEMORY_IMPORT_BUDGET,packMemoryImportSections,MemoryImportRequestError,digest,previewSource,memoryCommand};
4
+ `,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-RWTWYS5Z.js");const service=await createLocalMemoryImportService();let task=await service.submit(source,selection,args["idempotency-key"]);if(args["retry"])task=await service.retry(task.id);task=await service.idle(task.id);await writeStdoutLineFlushed(JSON.stringify(task));if(task.status!=="completed"||task.items.some(item=>item.status==="conflict"))process.exitCode=1},"handler")}).demandCommand(1).version(false),"builder"),handler:__name(()=>{},"handler")};export{MEMORY_IMPORT_BUDGET,packMemoryImportSections,MemoryImportRequestError,digest,previewSource,memoryCommand};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2026 Qwen Team
@@ -2,7 +2,7 @@
2
2
  "use strict";
3
3
  import{resolvePolicyToolSettings}from"./chunk-IV3HAIUN.js";import{MEDIA_MEMORY_FILE_NAME}from"./chunk-UYYQB2TU.js";import{DEFAULT_OMNI_PROCESSING_LIMITS,conditionUsesNamespace,evaluateFixedPolicyCondition}from"./chunk-HN5UYLPU.js";import{OBJECT_EXTENSION_RE}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile}from"./chunk-ZBHL2CXR.js";import{OmniJsonCacheFile}from"./chunk-AMGUAA4G.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var AUDIO_TOKENS_PER_SECOND=7;var VISUAL_PIXELS_PER_TOKEN=32*32*2;function usable(value){return value!==void 0&&Number.isFinite(value)&&value>0}__name(usable,"usable");function estimateRawResourceTokens(media){const unavailable={estimatedTokenCount:0,method:"raw-resource-v1",status:"unavailable"};switch(media.modality){case"audio":{const durationMs=media.metadata.durationMs;if(!usable(durationMs))return unavailable;return{estimatedTokenCount:Math.ceil(durationMs/1e3*AUDIO_TOKENS_PER_SECOND),method:"raw-resource-v1",status:"ok"}}case"image":{const{width,height,frameCount}=media.metadata;if(!usable(width)||!usable(height))return unavailable;const frames=usable(frameCount)?frameCount:1;return{estimatedTokenCount:Math.ceil(width*height*frames/VISUAL_PIXELS_PER_TOKEN),method:"raw-resource-v1",status:"ok"}}case"video":{const{width,height,durationMs,frameRate}=media.metadata;if(!usable(width)||!usable(height)||!usable(durationMs)||!usable(frameRate)){return unavailable}const frameCount=Math.ceil(durationMs/1e3*frameRate);return{estimatedTokenCount:Math.ceil(width*height*frameCount/VISUAL_PIXELS_PER_TOKEN),method:"raw-resource-v1",status:"ok"}}default:return unavailable}}__name(estimateRawResourceTokens,"estimateRawResourceTokens");init_esbuild_shims();import{createHash}from"node:crypto";import path from"node:path";var MAX_CACHED_DISCLOSURE_LENGTH=2048;var FINGERPRINT_EXCLUDED_KEYS=new Set(["inputPath","outputDir","resourceId"]);function stableStringify(value){if(Array.isArray(value)){return`[${value.map(stableStringify).join(",")}]`}if(typeof value==="object"&&value!==null){const record=value;const body=Object.keys(record).sort().map(k=>`${JSON.stringify(k)}:${stableStringify(record[k])}`).join(",");return`{${body}}`}return JSON.stringify(value)??"null"}__name(stableStringify,"stableStringify");function computePolicyFingerprint(toolName,args,toolVersion="1"){const tunables={};for(const[k,v]of Object.entries(args)){if(!FINGERPRINT_EXCLUDED_KEYS.has(k)&&v!==void 0){tunables[k]=v}}return createHash("sha256").update(`${toolName}
4
4
  ${stableStringify(tunables)}
5
- ${toolVersion}`).digest("hex")}__name(computePolicyFingerprint,"computePolicyFingerprint");var OmniDegradationCache=class{static{__name(this,"OmniDegradationCache")}file;constructor(omniRootDir){this.file=new OmniJsonCacheFile(path.join(omniRootDir,"policy-cache.json"),"omni:policy-cache")}key(originalSha256,policyFingerprint){return`${originalSha256}|${policyFingerprint}`}async get(originalSha256,policyFingerprint){return this.file.access(null,entries=>{const key=this.key(originalSha256,policyFingerprint);const entry=entries[key];if(!entry)return{result:null};if(!/^[0-9a-f]{64}$/.test(entry.degradedSha256)||typeof entry.extension!=="string"||!OBJECT_EXTENSION_RE.test(entry.extension)||typeof entry.disclosure!=="string"||entry.disclosure.length===0||entry.disclosure.length>MAX_CACHED_DISCLOSURE_LENGTH||typeof entry.mimeType!=="string"||entry.mimeType.length===0||entry.role!==void 0&&(typeof entry.role!=="string"||entry.role.length===0)){delete entries[key];return{result:null,changed:true}}return{result:entry}})}async put(originalSha256,policyFingerprint,entry){return this.file.access(void 0,entries=>{entries[this.key(originalSha256,policyFingerprint)]={...entry,createdAt:new Date().toISOString()};return{result:void 0,changed:true}})}async removeByOriginalSha256(originalSha256){return this.file.access(void 0,entries=>{const prefix=`${originalSha256}|`;let changed=false;for(const k of Object.keys(entries)){if(k.startsWith(prefix)){delete entries[k];changed=true}}return{result:void 0,changed}})}async removeByDegradedSha256(degradedSha256){return this.file.access(void 0,entries=>{let changed=false;for(const[k,v]of Object.entries(entries)){if(v.degradedSha256===degradedSha256){delete entries[k];changed=true}}return{result:void 0,changed}})}};init_esbuild_shims();var DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES=1024*1024*1024;var OmniTransportGuardError=class extends Error{static{__name(this,"OmniTransportGuardError")}sessionResourceId;constructor(message,options){super(message,options);this.name="OmniTransportGuardError"}};function effectiveMaxUploadFileBytes(config){const configured=config.getOmniMaxUploadFileBytes?.();return configured!==void 0&&configured>0?configured:DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES}__name(effectiveMaxUploadFileBytes,"effectiveMaxUploadFileBytes");function assertWithinByteLimit(config,sizeBytes,displayName){const maxBytes=effectiveMaxUploadFileBytes(config);if(sizeBytes>maxBytes){throw new OmniTransportGuardError(`${displayName} exceeds the omni upload limit: ${sizeBytes} bytes > ${maxBytes} bytes (omni.processing.transportGuard.maxUploadFileBytes). Reduce the file size before retrying.`)}}__name(assertWithinByteLimit,"assertWithinByteLimit");function assertWithinDurationLimit(config,media,displayName){const maxSeconds=config.getOmniMaxDurationSeconds?.();if(maxSeconds===void 0||maxSeconds<=0)return;const durationMs=media.metadata.durationMs;if(durationMs===void 0||!Number.isFinite(durationMs))return;const seconds=durationMs/1e3;if(seconds>maxSeconds){throw new OmniTransportGuardError(`${displayName} exceeds the omni duration limit: ${Math.round(seconds)}s > ${maxSeconds}s (omni.processing.transportGuard.maxDurationSeconds). Clip a shorter span \u2014 downscaling cannot bring a long file within a duration limit.`)}}__name(assertWithinDurationLimit,"assertWithinDurationLimit");function assertWithinTokenLimit(config,media,displayName){const estimate=estimateRawResourceTokens(media);const maxTokens=config.getOmniMaxEstimatedTokens?.();if(maxTokens===void 0||maxTokens<=0)return estimate;if(estimate.status!=="ok")return estimate;if(estimate.estimatedTokenCount>maxTokens){throw new OmniTransportGuardError(`${displayName} exceeds the omni estimated-token limit: ~${estimate.estimatedTokenCount} tokens (${estimate.method}) > ${maxTokens} (omni.processing.transportGuard.maxEstimatedTokens). Reduce duration/resolution or raise the limit.`)}return estimate}__name(assertWithinTokenLimit,"assertWithinTokenLimit");init_esbuild_shims();import fs from"node:fs/promises";import path2 from"node:path";var debugLogger=createDebugLogger("omni:gc");var OBJECT_NAME_RE=/^([0-9a-f]{64})\.[A-Za-z0-9][A-Za-z0-9.]*$/;var SKIPPED={ran:false,deletedObjects:0,deletedBytes:0,remainingBytes:0,derivationsSuspended:false};var gcOnce=new Map;var suspendedRoots=new Set;function effectiveOmniStorageMaxTotalBytes(config){const configured=config.getOmniStorageMaxTotalBytes();const floor=10*effectiveMaxUploadFileBytes(config);if(configured<floor){debugLogger.warn(`omni.storage.maxTotalBytes (${configured}) is below 10\xD7 the transport guard's single-media limit; using ${floor} bytes instead (the budget must hold at least ten normal uploads).`);return floor}return configured}__name(effectiveOmniStorageMaxTotalBytes,"effectiveOmniStorageMaxTotalBytes");function isOmniDerivationSuspended(omniRootDir){return suspendedRoots.has(path2.resolve(omniRootDir))}__name(isOmniDerivationSuspended,"isOmniDerivationSuspended");async function settleOmniGc(omniRootDir){const existing=gcOnce.get(path2.resolve(omniRootDir));if(existing)await existing}__name(settleOmniGc,"settleOmniGc");async function isRealDirectory(p){try{return(await fs.lstat(p)).isDirectory()}catch{return false}}__name(isRealDirectory,"isRealDirectory");async function listObjects(objectsDir){const out=[];if(!await isRealDirectory(objectsDir))return out;let shards;try{shards=await fs.readdir(objectsDir)}catch{return out}for(const shard of shards){const shardDir=path2.join(objectsDir,shard);if(!await isRealDirectory(shardDir))continue;let names;try{names=await fs.readdir(shardDir)}catch{continue}for(const name of names){const match=OBJECT_NAME_RE.exec(name);if(!match)continue;const filePath=path2.join(shardDir,name);try{const st=await fs.lstat(filePath);if(!st.isFile())continue;out.push({sha256:match[1],filePath,mtimeMs:st.mtimeMs,sizeBytes:st.size})}catch{}}}return out}__name(listObjects,"listObjects");async function deleteObject(object,options){try{await fs.rm(object.filePath,{force:true})}catch(err){debugLogger.debug(`gc: failed to delete ${object.sha256}: ${err instanceof Error?err.message:err}`);return false}try{await options.uploadCache?.removeBySha256(object.sha256)}catch{}try{await options.degradationCache?.removeByOriginalSha256(object.sha256);await options.degradationCache?.removeByDegradedSha256(object.sha256)}catch{}debugLogger.debug(`gc: deleted unreferenced object ${object.sha256} (${object.sizeBytes} bytes)`);return true}__name(deleteObject,"deleteObject");function runOmniGcOnce(options){const rootKey=path2.resolve(options.store.getOmniRootDir());const existing=gcOnce.get(rootKey);if(existing)return existing;const run=sweep(options,rootKey).catch(err=>{debugLogger.debug(`gc: run failed, skipped: ${err instanceof Error?err.message:err}`);return SKIPPED});gcOnce.set(rootKey,run);return run}__name(runOmniGcOnce,"runOmniGcOnce");async function recentlyRecoveredFromCorruption(omniRootDir,retentionDays,nowMs){const prefix=`${MEDIA_MEMORY_FILE_NAME}.corrupt-`;let names;try{names=await fs.readdir(omniRootDir)}catch{return false}const cutoff=nowMs-retentionDays*24*36e5;for(const name of names){if(!name.startsWith(prefix))continue;const stamp=Number(name.slice(prefix.length));if(Number.isFinite(stamp)&&stamp>=cutoff)return true;try{const st=await fs.lstat(path2.join(omniRootDir,name));if(st.mtimeMs>=cutoff)return true}catch{return true}}return false}__name(recentlyRecoveredFromCorruption,"recentlyRecoveredFromCorruption");async function sweep(options,rootKey){const nowMsForGuard=options.nowMs??Date.now();const refs=await options.memoryService.collectManagedRefs();if(refs===null){debugLogger.debug("gc: memory snapshot unreadable, skipping run");return SKIPPED}if(await recentlyRecoveredFromCorruption(options.store.getOmniRootDir(),options.retentionDays,nowMsForGuard)){debugLogger.debug("gc: memory ledger recently recovered from corruption, skipping run");return SKIPPED}const objectsDir=options.store.getObjectsDir();for(const fileRef of options.registry?.activeFileRefs()??[]){const name=path2.basename(fileRef);const match=OBJECT_NAME_RE.exec(name);if(match&&fileRef.startsWith(objectsDir))refs.add(match[1])}const nowMs=options.nowMs??Date.now();const cutoffMs=nowMs-options.retentionDays*24*36e5;const objects=await listObjects(objectsDir);let deletedObjects=0;let deletedBytes=0;const survivors=[];const touchedSinceListing=__name(async(object,freshCutoffMs)=>{try{return(await fs.lstat(object.filePath)).mtimeMs>=freshCutoffMs}catch{return true}},"touchedSinceListing");for(const object of objects){if(refs.has(object.sha256)||object.mtimeMs>=cutoffMs){survivors.push(object);continue}if(await touchedSinceListing(object,cutoffMs)){survivors.push(object);continue}if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes}else{survivors.push(object)}}let remainingBytes=survivors.reduce((sum,o)=>sum+o.sizeBytes,0);if(remainingBytes>options.maxTotalBytes){const freshRefs=await options.memoryService.collectManagedRefs();if(freshRefs===null){debugLogger.debug("gc: ledger unreadable at budget pass, skipping budget deletions")}else{const unreferenced=survivors.filter(o=>!refs.has(o.sha256)&&!freshRefs.has(o.sha256)).sort((a,b)=>a.mtimeMs-b.mtimeMs);for(const object of unreferenced){if(remainingBytes<=options.maxTotalBytes)break;if(await touchedSinceListing(object,nowMs))continue;if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes;remainingBytes-=object.sizeBytes}}}}const derivationsSuspended=remainingBytes>options.maxTotalBytes;if(derivationsSuspended){suspendedRoots.add(rootKey);debugLogger.warn(`omni object store over budget with only referenced objects left (${remainingBytes} > ${options.maxTotalBytes} bytes); new policy derivations are suspended for this session. Raise omni.storage.maxTotalBytes or delete memory records you no longer need \u2014 either change takes effect at the next session start (the GC runs once per process).`)}else{suspendedRoots.delete(rootKey)}if(deletedObjects>0){debugLogger.debug(`gc: removed ${deletedObjects} object(s) / ${deletedBytes} bytes; ${remainingBytes} bytes remain`)}return{ran:true,deletedObjects,deletedBytes,remainingBytes,derivationsSuspended}}__name(sweep,"sweep");init_esbuild_shims();import{createHash as createHash2,randomBytes}from"node:crypto";import fs2 from"node:fs/promises";import path3 from"node:path";var debugLogger2=createDebugLogger("omni:policy");var MAX_FILE_ARTIFACT_BYTES=256*1024;var OmniPolicyExecutionError=class extends Error{constructor(message,policyId,options){super(message,options);this.policyId=policyId;this.name="OmniPolicyExecutionError"}static{__name(this,"OmniPolicyExecutionError")}};function resolveArtifactSelector(artifacts,kind,role){if(role!==void 0){const byRole=artifacts[`role:${role}`];if(byRole)return byRole}const byKind=artifacts[`kind:${kind}`];if(byKind)return byKind;return artifacts["*"]??"retain"}__name(resolveArtifactSelector,"resolveArtifactSelector");function resourceConditionContext(recognized,shared){const resource={};const set=__name((field,value)=>{if(typeof value==="number"&&!Number.isNaN(value)){resource[field]=value}},"set");const m=recognized.metadata;set("sizeBytes",recognized.sizeBytes);set("durationMs",m.durationMs);set("width",m.width);set("height",m.height);set("maxWidth",m.width);set("maxHeight",m.height);set("frameRate",m.frameRate);set("frameCount",m.frameCount);set("bitRate",m.bitRate);set("sampleRateHz",m.sampleRateHz);set("channels",m.channels);const estimate=estimateRawResourceTokens(recognized);if(estimate.status==="ok"){set("estimatedTokenCount",estimate.estimatedTokenCount)}return{resource,...shared}}__name(resourceConditionContext,"resourceConditionContext");var MEMORY_ROLE_FIELDS={transcript:"hasTranscript",ocr:"hasOcr",caption:"hasCaption",summary:"hasSummary",keyframe:"hasKeyframes",clip:"hasClip"};async function memoryConditionNamespace(memory,binding){if(!memory||!binding)return void 0;const roles=await memory.service.collectVersionOutputRoles(binding);if(!roles)return void 0;const namespace={};for(const field of Object.values(MEMORY_ROLE_FIELDS)){namespace[field]=0}for(const role of roles){const field=MEMORY_ROLE_FIELDS[role];if(field)namespace[field]=1}return namespace}__name(memoryConditionNamespace,"memoryConditionNamespace");function requestConditionNamespace(items){let total=0;for(const item of items){if(!item.deliver)continue;const estimate=estimateRawResourceTokens(item.recognized);if(estimate.status!=="ok")return void 0;total+=estimate.estimatedTokenCount}return{totalEstimatedMediaTokens:total}}__name(requestConditionNamespace,"requestConditionNamespace");function sortPolicies(policies){return[...policies].sort((a,b)=>b.priority-a.priority||a.id.localeCompare(b.id))}__name(sortPolicies,"sortPolicies");var resourceGates=new Map;async function acquireResourceSlot(rootDir,limit){const effectiveLimit=Math.max(1,Math.floor(limit));let gate=resourceGates.get(rootDir);if(!gate){gate={active:0,waiters:[]};resourceGates.set(rootDir,gate)}const heldGate=gate;if(heldGate.active>=effectiveLimit){await new Promise(resolve=>heldGate.waiters.push(resolve))}else{heldGate.active++}let released=false;return()=>{if(released)return;released=true;const next=heldGate.waiters.shift();if(next){next();return}heldGate.active--;if(heldGate.active===0&&heldGate.waiters.length===0){resourceGates.delete(rootDir)}}}__name(acquireResourceSlot,"acquireResourceSlot");async function runFixedPolicies(config,source,options){const policies=sortPolicies(options.policies);const limits=options.limits??DEFAULT_OMNI_PROCESSING_LIMITS;const releaseSlot=await acquireResourceSlot(options.store.getOmniRootDir(),limits.maxConcurrentResources);try{return await runFixedPoliciesUnbounded(config,source,options,{policies,limits})}finally{releaseSlot()}}__name(runFixedPolicies,"runFixedPolicies");async function runFixedPoliciesUnbounded(config,source,options,normalized){const{policies,limits}=normalized;const cache=options.degradationCache??new OmniDegradationCache(options.store.getOmniRootDir());const records=[];const fileDeliveries=[];const items=[{filePath:source.filePath,recognized:source.recognized,label:source.displayName,origin:source.origin,sha256:source.sha256,memoryBinding:options.memory?.sourceBinding,lineageRuns:new Map,depth:0,deliver:true,process:true}];let runsUsed=0;let artifactsProduced=0;let derivedBytesProduced=0;let budgetExhausted=false;const stopOnBudget=__name((policy,item,reason)=>{budgetExhausted=true;records.push({policyId:policy.id,toolName:policy.toolName,outcome:"budget_exhausted",resource:item.label,error:reason});debugLogger2.debug(`per-root policy budget exhausted on ${item.label}: ${reason}; no further derivation for this root (committed deliveries stand)`)},"stopOnBudget");for(let i=0;i<items.length&&!budgetExhausted;i++){const item=items[i];if(!item.process)continue;if(item.recognized.modality==="image"&&(item.recognized.metadata.frameCount??1)>1){debugLogger2.debug(`animated image ${item.label} (${item.recognized.metadata.frameCount} frames) excluded from policy matching (D9)`);continue}const needsMemoryNamespace=policies.some(policy=>policy.when&&conditionUsesNamespace(policy.when,"memory"));const sharedConditionContext={request:options.conditionContext?.request??requestConditionNamespace(items),session:options.conditionContext?.session,memory:needsMemoryNamespace?await memoryConditionNamespace(options.memory,item.memoryBinding):void 0};for(const policy of policies){if(!policy.mediaTypes.includes(item.recognized.modality))continue;if(!policy.origins.includes(item.origin))continue;const runs=item.lineageRuns.get(policy.id)??0;if(runs>=policy.maxRunsPerLineage)continue;if(policy.when){const evaluation=evaluateFixedPolicyCondition(policy.when,resourceConditionContext(item.recognized,sharedConditionContext));if(evaluation.outcome==="no_match")continue;if(evaluation.outcome==="unavailable"&&policy.onConditionUnavailable==="skip"){records.push({policyId:policy.id,toolName:policy.toolName,outcome:"condition_unavailable",resource:item.label,missingFields:evaluation.missingFields});continue}}if(runsUsed>=limits.maxPolicyRunsPerRoot){stopOnBudget(policy,item,`maxPolicyRunsPerRoot (${limits.maxPolicyRunsPerRoot}) reached`);break}runsUsed++;item.lineageRuns.set(policy.id,runs+1);try{const execution=await executePolicy(config,item,policy,options.store,cache,options.signal,options.memory&&item.memoryBinding?{service:options.memory.service,source:item.memoryBinding}:void 0);records.push({policyId:policy.id,toolName:policy.toolName,outcome:execution.outcome,resource:item.label});if(execution.outcome==="no_op")continue;if(policy.output.source==="omit")item.deliver=false;const childDepth=item.depth+1;const depthAllowsReprocess=childDepth<limits.maxLineageDepth;if(policy.output.reprocessMedia&&!depthAllowsReprocess){debugLogger2.debug(`maxLineageDepth (${limits.maxLineageDepth}) reached under ${item.label}; derivatives deliver but do not re-enter policy matching`)}for(const derived of execution.derived){artifactsProduced++;derivedBytesProduced+=derived.recognized.sizeBytes;items.push({...derived,label:`${item.label} \u2192 ${policy.id}`,origin:"policy",lineageRuns:new Map(item.lineageRuns),depth:childDepth,deliver:resolveArtifactSelector(policy.output.artifacts,derived.recognized.modality,derived.role)==="include",process:policy.output.reprocessMedia&&depthAllowsReprocess})}for(const file of execution.derivedFiles){artifactsProduced++;derivedBytesProduced+=file.sizeBytes;if(resolveArtifactSelector(policy.output.artifacts,"file",file.role)==="include"){fileDeliveries.push(file)}}if(artifactsProduced>limits.maxArtifactsPerRoot){stopOnBudget(policy,item,`maxArtifactsPerRoot (${limits.maxArtifactsPerRoot}) exceeded`);break}if(derivedBytesProduced>limits.maxDerivedBytesPerRoot){stopOnBudget(policy,item,`maxDerivedBytesPerRoot (${limits.maxDerivedBytesPerRoot}) exceeded`);break}}catch(err){if(options.signal?.aborted)throw err;const message=err instanceof Error?err.message:String(err);records.push({policyId:policy.id,toolName:policy.toolName,outcome:"failed",resource:item.label,error:message});debugLogger2.debug(`fixed policy ${policy.id} (${policy.toolName}) failed on ${item.label}: ${message}`);if(policy.onFailure==="abort"||policy.stage==="transport_guard"){throw new OmniPolicyExecutionError(`Fixed policy ${policy.id} failed: ${message}`,policy.id,{cause:err})}}}}return{deliveries:items.filter(item=>item.deliver).map(item=>({filePath:item.filePath,recognized:item.recognized,sha256:item.sha256,disclosure:item.disclosure,degraded:item.degraded,memoryBinding:item.memoryBinding})),fileDeliveries,records}}__name(runFixedPoliciesUnbounded,"runFixedPoliciesUnbounded");async function executePolicy(config,item,policy,store,cache,signal,memory){const tool=config.getToolRegistry().getTool(policy.toolName);const descriptor=tool?.mediaPolicyDescriptor;if(!descriptor){throw new Error(`tool ${policy.toolName} is not a registered media-policy tool`)}item.sha256??=await hashFileSha256(item.filePath,signal);const settingsDefaults=resolvePolicyToolSettings(config,policy.toolName);const effectiveArguments={...settingsDefaults,...policy.arguments};const fingerprint=computePolicyFingerprint(policy.toolName,effectiveArguments,descriptor.version);const startedAt=new Date().toISOString();if(memory){const reusable=await memory.service.findReusableOutputs(item.sha256,fingerprint);const rebuilt=reusable?await rebuildReusedOutputs(reusable,descriptor,store,signal):void 0;if(rebuilt){debugLogger2.debug(`memory reuse hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026 outputs=${rebuilt.outputs.length} (tool not executed)`);const commit=await memory.service.commitPolicySucceeded({invocationId:"memory-reuse",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:rebuilt.outputs});return{outcome:"succeeded",derived:rebuilt.derived.map(d=>({...d,memoryBinding:commit?.mediaBindings.get(d.sha256)})),derivedFiles:rebuilt.derivedFiles}}}const hit=await cache.get(item.sha256,fingerprint);if(hit){try{const objectPath=store.objectPathFor(hit.degradedSha256,hit.extension);const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(stat?.isFile()&&!stat.isSymbolicLink()){const actualSha256=await hashFileSha256(objectPath,signal);if(actualSha256===hit.degradedSha256){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(declared){debugLogger2.debug(`degradation cache hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026`);const commit=memory?await memory.service.commitPolicySucceeded({invocationId:"cache-hit",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:[{kind:"media",objectPath,sha256:hit.degradedSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:hit.role,disclosure:hit.disclosure}]}):void 0;return{outcome:"cache_hit",derived:[{filePath:objectPath,recognized,sha256:hit.degradedSha256,disclosure:hit.disclosure,degraded:true,role:hit.role,memoryBinding:commit?.mediaBindings.get(hit.degradedSha256)}],derivedFiles:[]}}debugLogger2.debug(`degradation cache hit for policy=${policy.id} recognized as undeclared media type ${recognized.detectedMimeType}; dropping the entry and re-transcoding`)}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`degradation cache hit could not be verified for policy=${policy.id}: ${err instanceof Error?err.message:String(err)}; dropping the entry and re-transcoding`)}await cache.removeByDegradedSha256(hit.degradedSha256)}await settleOmniGc(store.getOmniRootDir());if(isOmniDerivationSuspended(store.getOmniRootDir())){throw new Error(`omni object store is over its byte budget with only memory-referenced objects left; new policy derivations are suspended. Raise omni.storage.maxTotalBytes or delete memory records you no longer need, then start a new session \u2014 the budget is re-evaluated once per process.`)}const invocationId=randomBytes(8).toString("hex");const stagingDir=await store.createStagingDir(invocationId);let failure;try{const request={callId:invocationId,name:policy.toolName,args:{...effectiveArguments,inputPath:item.filePath,outputDir:stagingDir},isClientInitiated:true,prompt_id:`omni-fixed-policy-${invocationId}`,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage}};const{executeToolCall}=await import("./nonInteractiveToolExecutor-7RJZYPHJ.js");const response=await executeToolCall(config,request,signal??new AbortController().signal,{recordToolResult:false});if(response.error){throw new Error(response.error.message,{cause:response.error})}const batch=response.policyArtifacts;if(!batch||batch.artifacts.length===0){throw new Error(`tool ${policy.toolName} succeeded but produced no policy artifacts`)}const validated=await Promise.all(batch.artifacts.map(artifact=>validateArtifact(artifact,descriptor,stagingDir,signal)));assertRequiredOutputsPresent(descriptor,validated,policy.toolName);if(validated.every(a=>a.sha256===item.sha256)){return{outcome:"no_op",derived:[],derivedFiles:[]}}const promoted=await Promise.all(validated.map(async artifact=>{const mimeType=artifact.kind==="media"?artifact.recognized.detectedMimeType:artifact.mimeType;const put=await store.putFile(artifact.absolutePath,artifact.sha256,extensionForMime(mimeType),signal);return{artifact,objectPath:put.objectPath}}));const derived=[];const derivedFiles=[];for(const{artifact,objectPath}of promoted){if(artifact.kind==="media"){derived.push({filePath:objectPath,recognized:artifact.recognized,sha256:artifact.sha256,disclosure:artifact.disclosure,degraded:artifact.lossy,role:artifact.role})}else{derivedFiles.push({filePath:objectPath,role:artifact.role,mimeType:artifact.mimeType,text:artifact.text,sha256:artifact.sha256,sizeBytes:artifact.sizeBytes,disclosure:artifact.disclosure})}}if(memory){const outputs=promoted.map(({artifact,objectPath})=>artifact.kind==="media"?{kind:"media",objectPath,sha256:artifact.sha256,mediaType:artifact.recognized.modality,metadata:artifact.recognized.metadata,sizeBytes:artifact.recognized.sizeBytes,mimeType:artifact.recognized.detectedMimeType,role:artifact.role,disclosure:artifact.disclosure}:{kind:"text",objectPath,sha256:artifact.sha256,mimeType:artifact.mimeType,text:artifact.text,sizeBytes:artifact.sizeBytes,role:artifact.role,disclosure:artifact.disclosure});const commit=await memory.service.commitPolicySucceeded({invocationId,source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs});if(commit){for(const entry of derived){entry.memoryBinding=commit.mediaBindings.get(entry.sha256)}}}if(validated.length===1&&validated[0].kind==="media"&&validated[0].disclosure){await cache.put(item.sha256,fingerprint,{degradedSha256:validated[0].sha256,extension:extensionForMime(validated[0].recognized.detectedMimeType),disclosure:validated[0].disclosure,mimeType:validated[0].recognized.detectedMimeType,...validated[0].role!==void 0?{role:validated[0].role}:{}})}return{outcome:"succeeded",derived,derivedFiles}}catch(err){failure=err;throw err}finally{if(failure===void 0||signal?.aborted){await store.removeStagingDir(invocationId).catch(()=>{})}else{try{await store.quarantineInvocation(invocationId,{policyId:policy.id,toolName:policy.toolName,reason:failure instanceof Error?failure.message:String(failure)})}catch{await store.removeStagingDir(invocationId).catch(()=>{})}}}}__name(executePolicy,"executePolicy");async function rebuildReusedOutputs(reusable,descriptor,store,signal){const outputs=[];const derived=[];const derivedFiles=[];try{for(const record of reusable.outputs){const objectPath=record.objectPath??store.objectPathFor(record.sha256,extensionForMime(record.mimeType));const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink())return void 0;if(await hashFileSha256(objectPath,signal)!==record.sha256){return void 0}if(record.kind==="media"){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!declared)return void 0;outputs.push({kind:"media",objectPath,sha256:record.sha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:record.role,disclosure:record.disclosure});derived.push({filePath:objectPath,recognized,sha256:record.sha256,disclosure:record.disclosure,degraded:record.disclosure!==void 0,role:record.role})}else{const text=await fs2.readFile(objectPath,"utf8");outputs.push({kind:"text",objectPath,sha256:record.sha256,mimeType:record.mimeType,text,sizeBytes:record.sizeBytes,role:record.role,disclosure:record.disclosure});derivedFiles.push({filePath:objectPath,role:record.role,mimeType:record.mimeType,text,sha256:record.sha256,sizeBytes:record.sizeBytes,disclosure:record.disclosure})}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`memory reuse could not be verified, re-deriving: ${err instanceof Error?err.message:String(err)}`);return void 0}return{outputs,derived,derivedFiles}}__name(rebuildReusedOutputs,"rebuildReusedOutputs");async function validateArtifact(artifact,descriptor,stagingDir,signal){if(artifact.storage!=="workspace"||!artifact.workspacePath){throw new Error(`policy artifact "${artifact.title}" is not a workspace file`)}const absolutePath=path3.resolve(stagingDir,artifact.workspacePath);if(!absolutePath.startsWith(stagingDir+path3.sep)){throw new Error(`policy artifact "${artifact.title}" escapes the staging directory`)}const stat=await fs2.lstat(absolutePath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink()){throw new Error(`policy artifact "${artifact.title}" is missing or not a regular file`)}const rawRole=artifact.metadata?.["omniRole"];const role=typeof rawRole==="string"&&rawRole?rawRole:void 0;const rawDisclosure=artifact.metadata?.["omniDisclosure"];const disclosure=typeof rawDisclosure==="string"&&rawDisclosure?rawDisclosure:void 0;if(artifact.kind==="file"){const spec2=descriptor.outputs.find(o=>o.kind==="file"&&(o.role===void 0||o.role===role)&&artifact.mimeType!==void 0&&o.mimeTypes?.includes(artifact.mimeType));if(!spec2){throw new Error(`policy artifact "${artifact.title}" (file, role ${role??"none"}, ${artifact.mimeType??"no mimeType"}) matches no declared file output`)}if(stat.size>MAX_FILE_ARTIFACT_BYTES){throw new Error(`policy artifact "${artifact.title}" exceeds the file-artifact size budget (${stat.size} > ${MAX_FILE_ARTIFACT_BYTES} bytes)`)}const bytes=await fs2.readFile(absolutePath);let text;try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new Error(`policy artifact "${artifact.title}" is not valid UTF-8 text`)}if(spec2.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"file",absolutePath,mimeType:artifact.mimeType,text,sizeBytes:bytes.byteLength,sha256:createHash2("sha256").update(bytes).digest("hex"),disclosure,lossy:spec2.lossy===true,role}}const recognized=await recognizeMediaFile(absolutePath,{signal});const spec=descriptor.outputs.find(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!spec){throw new Error(`policy artifact "${artifact.title}" has undeclared media type ${recognized.detectedMimeType}`)}if(artifact.kind!==recognized.modality){throw new Error(`policy artifact "${artifact.title}" declares kind ${String(artifact.kind)} but contains ${recognized.modality} content`)}if(spec.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"media",absolutePath,recognized,sha256:await hashFileSha256(absolutePath,signal),disclosure,lossy:spec.lossy===true,role}}__name(validateArtifact,"validateArtifact");function assertRequiredOutputsPresent(descriptor,validated,toolName){for(const spec of descriptor.outputs){if(!spec.required)continue;let produced;if(spec.kind==="media"){produced=validated.some(a=>a.kind==="media"&&spec.mimeTypes?.includes(a.recognized.detectedMimeType))}else if(spec.kind==="file"){produced=validated.some(a=>a.kind==="file"&&(spec.role===void 0||a.role===spec.role)&&spec.mimeTypes?.includes(a.mimeType))}else{continue}if(!produced){throw new Error(`tool ${toolName} did not produce its required ${spec.kind} ${spec.mimeTypes?.join("/")??spec.role??""} output`)}}}__name(assertRequiredOutputsPresent,"assertRequiredOutputsPresent");export{estimateRawResourceTokens,computePolicyFingerprint,OmniDegradationCache,DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES,OmniTransportGuardError,effectiveMaxUploadFileBytes,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveOmniStorageMaxTotalBytes,runOmniGcOnce,OmniPolicyExecutionError,runFixedPolicies,validateArtifact,assertRequiredOutputsPresent};
5
+ ${toolVersion}`).digest("hex")}__name(computePolicyFingerprint,"computePolicyFingerprint");var OmniDegradationCache=class{static{__name(this,"OmniDegradationCache")}file;constructor(omniRootDir){this.file=new OmniJsonCacheFile(path.join(omniRootDir,"policy-cache.json"),"omni:policy-cache")}key(originalSha256,policyFingerprint){return`${originalSha256}|${policyFingerprint}`}async get(originalSha256,policyFingerprint){return this.file.access(null,entries=>{const key=this.key(originalSha256,policyFingerprint);const entry=entries[key];if(!entry)return{result:null};if(!/^[0-9a-f]{64}$/.test(entry.degradedSha256)||typeof entry.extension!=="string"||!OBJECT_EXTENSION_RE.test(entry.extension)||typeof entry.disclosure!=="string"||entry.disclosure.length===0||entry.disclosure.length>MAX_CACHED_DISCLOSURE_LENGTH||typeof entry.mimeType!=="string"||entry.mimeType.length===0||entry.role!==void 0&&(typeof entry.role!=="string"||entry.role.length===0)){delete entries[key];return{result:null,changed:true}}return{result:entry}})}async put(originalSha256,policyFingerprint,entry){return this.file.access(void 0,entries=>{entries[this.key(originalSha256,policyFingerprint)]={...entry,createdAt:new Date().toISOString()};return{result:void 0,changed:true}})}async removeByOriginalSha256(originalSha256){return this.file.access(void 0,entries=>{const prefix=`${originalSha256}|`;let changed=false;for(const k of Object.keys(entries)){if(k.startsWith(prefix)){delete entries[k];changed=true}}return{result:void 0,changed}})}async removeByDegradedSha256(degradedSha256){return this.file.access(void 0,entries=>{let changed=false;for(const[k,v]of Object.entries(entries)){if(v.degradedSha256===degradedSha256){delete entries[k];changed=true}}return{result:void 0,changed}})}};init_esbuild_shims();var DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES=1024*1024*1024;var OmniTransportGuardError=class extends Error{static{__name(this,"OmniTransportGuardError")}sessionResourceId;constructor(message,options){super(message,options);this.name="OmniTransportGuardError"}};function effectiveMaxUploadFileBytes(config){const configured=config.getOmniMaxUploadFileBytes?.();return configured!==void 0&&configured>0?configured:DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES}__name(effectiveMaxUploadFileBytes,"effectiveMaxUploadFileBytes");function assertWithinByteLimit(config,sizeBytes,displayName){const maxBytes=effectiveMaxUploadFileBytes(config);if(sizeBytes>maxBytes){throw new OmniTransportGuardError(`${displayName} exceeds the omni upload limit: ${sizeBytes} bytes > ${maxBytes} bytes (omni.processing.transportGuard.maxUploadFileBytes). Reduce the file size before retrying.`)}}__name(assertWithinByteLimit,"assertWithinByteLimit");function assertWithinDurationLimit(config,media,displayName){const maxSeconds=config.getOmniMaxDurationSeconds?.();if(maxSeconds===void 0||maxSeconds<=0)return;const durationMs=media.metadata.durationMs;if(durationMs===void 0||!Number.isFinite(durationMs))return;const seconds=durationMs/1e3;if(seconds>maxSeconds){throw new OmniTransportGuardError(`${displayName} exceeds the omni duration limit: ${Math.round(seconds)}s > ${maxSeconds}s (omni.processing.transportGuard.maxDurationSeconds). Clip a shorter span \u2014 downscaling cannot bring a long file within a duration limit.`)}}__name(assertWithinDurationLimit,"assertWithinDurationLimit");function assertWithinTokenLimit(config,media,displayName){const estimate=estimateRawResourceTokens(media);const maxTokens=config.getOmniMaxEstimatedTokens?.();if(maxTokens===void 0||maxTokens<=0)return estimate;if(estimate.status!=="ok")return estimate;if(estimate.estimatedTokenCount>maxTokens){throw new OmniTransportGuardError(`${displayName} exceeds the omni estimated-token limit: ~${estimate.estimatedTokenCount} tokens (${estimate.method}) > ${maxTokens} (omni.processing.transportGuard.maxEstimatedTokens). Reduce duration/resolution or raise the limit.`)}return estimate}__name(assertWithinTokenLimit,"assertWithinTokenLimit");init_esbuild_shims();import fs from"node:fs/promises";import path2 from"node:path";var debugLogger=createDebugLogger("omni:gc");var OBJECT_NAME_RE=/^([0-9a-f]{64})\.[A-Za-z0-9][A-Za-z0-9.]*$/;var SKIPPED={ran:false,deletedObjects:0,deletedBytes:0,remainingBytes:0,derivationsSuspended:false};var gcOnce=new Map;var suspendedRoots=new Set;function effectiveOmniStorageMaxTotalBytes(config){const configured=config.getOmniStorageMaxTotalBytes();const floor=10*effectiveMaxUploadFileBytes(config);if(configured<floor){debugLogger.warn(`omni.storage.maxTotalBytes (${configured}) is below 10\xD7 the transport guard's single-media limit; using ${floor} bytes instead (the budget must hold at least ten normal uploads).`);return floor}return configured}__name(effectiveOmniStorageMaxTotalBytes,"effectiveOmniStorageMaxTotalBytes");function isOmniDerivationSuspended(omniRootDir){return suspendedRoots.has(path2.resolve(omniRootDir))}__name(isOmniDerivationSuspended,"isOmniDerivationSuspended");async function settleOmniGc(omniRootDir){const existing=gcOnce.get(path2.resolve(omniRootDir));if(existing)await existing}__name(settleOmniGc,"settleOmniGc");async function isRealDirectory(p){try{return(await fs.lstat(p)).isDirectory()}catch{return false}}__name(isRealDirectory,"isRealDirectory");async function listObjects(objectsDir){const out=[];if(!await isRealDirectory(objectsDir))return out;let shards;try{shards=await fs.readdir(objectsDir)}catch{return out}for(const shard of shards){const shardDir=path2.join(objectsDir,shard);if(!await isRealDirectory(shardDir))continue;let names;try{names=await fs.readdir(shardDir)}catch{continue}for(const name of names){const match=OBJECT_NAME_RE.exec(name);if(!match)continue;const filePath=path2.join(shardDir,name);try{const st=await fs.lstat(filePath);if(!st.isFile())continue;out.push({sha256:match[1],filePath,mtimeMs:st.mtimeMs,sizeBytes:st.size})}catch{}}}return out}__name(listObjects,"listObjects");async function deleteObject(object,options){try{await fs.rm(object.filePath,{force:true})}catch(err){debugLogger.debug(`gc: failed to delete ${object.sha256}: ${err instanceof Error?err.message:err}`);return false}try{await options.uploadCache?.removeBySha256(object.sha256)}catch{}try{await options.degradationCache?.removeByOriginalSha256(object.sha256);await options.degradationCache?.removeByDegradedSha256(object.sha256)}catch{}debugLogger.debug(`gc: deleted unreferenced object ${object.sha256} (${object.sizeBytes} bytes)`);return true}__name(deleteObject,"deleteObject");function runOmniGcOnce(options){const rootKey=path2.resolve(options.store.getOmniRootDir());const existing=gcOnce.get(rootKey);if(existing)return existing;const run=sweep(options,rootKey).catch(err=>{debugLogger.debug(`gc: run failed, skipped: ${err instanceof Error?err.message:err}`);return SKIPPED});gcOnce.set(rootKey,run);return run}__name(runOmniGcOnce,"runOmniGcOnce");async function recentlyRecoveredFromCorruption(omniRootDir,retentionDays,nowMs){const prefix=`${MEDIA_MEMORY_FILE_NAME}.corrupt-`;let names;try{names=await fs.readdir(omniRootDir)}catch{return false}const cutoff=nowMs-retentionDays*24*36e5;for(const name of names){if(!name.startsWith(prefix))continue;const stamp=Number(name.slice(prefix.length));if(Number.isFinite(stamp)&&stamp>=cutoff)return true;try{const st=await fs.lstat(path2.join(omniRootDir,name));if(st.mtimeMs>=cutoff)return true}catch{return true}}return false}__name(recentlyRecoveredFromCorruption,"recentlyRecoveredFromCorruption");async function sweep(options,rootKey){const nowMsForGuard=options.nowMs??Date.now();const refs=await options.memoryService.collectManagedRefs();if(refs===null){debugLogger.debug("gc: memory snapshot unreadable, skipping run");return SKIPPED}if(await recentlyRecoveredFromCorruption(options.store.getOmniRootDir(),options.retentionDays,nowMsForGuard)){debugLogger.debug("gc: memory ledger recently recovered from corruption, skipping run");return SKIPPED}const objectsDir=options.store.getObjectsDir();for(const fileRef of options.registry?.activeFileRefs()??[]){const name=path2.basename(fileRef);const match=OBJECT_NAME_RE.exec(name);if(match&&fileRef.startsWith(objectsDir))refs.add(match[1])}const nowMs=options.nowMs??Date.now();const cutoffMs=nowMs-options.retentionDays*24*36e5;const objects=await listObjects(objectsDir);let deletedObjects=0;let deletedBytes=0;const survivors=[];const touchedSinceListing=__name(async(object,freshCutoffMs)=>{try{return(await fs.lstat(object.filePath)).mtimeMs>=freshCutoffMs}catch{return true}},"touchedSinceListing");for(const object of objects){if(refs.has(object.sha256)||object.mtimeMs>=cutoffMs){survivors.push(object);continue}if(await touchedSinceListing(object,cutoffMs)){survivors.push(object);continue}if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes}else{survivors.push(object)}}let remainingBytes=survivors.reduce((sum,o)=>sum+o.sizeBytes,0);if(remainingBytes>options.maxTotalBytes){const freshRefs=await options.memoryService.collectManagedRefs();if(freshRefs===null){debugLogger.debug("gc: ledger unreadable at budget pass, skipping budget deletions")}else{const unreferenced=survivors.filter(o=>!refs.has(o.sha256)&&!freshRefs.has(o.sha256)).sort((a,b)=>a.mtimeMs-b.mtimeMs);for(const object of unreferenced){if(remainingBytes<=options.maxTotalBytes)break;if(await touchedSinceListing(object,nowMs))continue;if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes;remainingBytes-=object.sizeBytes}}}}const derivationsSuspended=remainingBytes>options.maxTotalBytes;if(derivationsSuspended){suspendedRoots.add(rootKey);debugLogger.warn(`omni object store over budget with only referenced objects left (${remainingBytes} > ${options.maxTotalBytes} bytes); new policy derivations are suspended for this session. Raise omni.storage.maxTotalBytes or delete memory records you no longer need \u2014 either change takes effect at the next session start (the GC runs once per process).`)}else{suspendedRoots.delete(rootKey)}if(deletedObjects>0){debugLogger.debug(`gc: removed ${deletedObjects} object(s) / ${deletedBytes} bytes; ${remainingBytes} bytes remain`)}return{ran:true,deletedObjects,deletedBytes,remainingBytes,derivationsSuspended}}__name(sweep,"sweep");init_esbuild_shims();import{createHash as createHash2,randomBytes}from"node:crypto";import fs2 from"node:fs/promises";import path3 from"node:path";var debugLogger2=createDebugLogger("omni:policy");var MAX_FILE_ARTIFACT_BYTES=256*1024;var OmniPolicyExecutionError=class extends Error{constructor(message,policyId,options){super(message,options);this.policyId=policyId;this.name="OmniPolicyExecutionError"}static{__name(this,"OmniPolicyExecutionError")}};function resolveArtifactSelector(artifacts,kind,role){if(role!==void 0){const byRole=artifacts[`role:${role}`];if(byRole)return byRole}const byKind=artifacts[`kind:${kind}`];if(byKind)return byKind;return artifacts["*"]??"retain"}__name(resolveArtifactSelector,"resolveArtifactSelector");function resourceConditionContext(recognized,shared){const resource={};const set=__name((field,value)=>{if(typeof value==="number"&&!Number.isNaN(value)){resource[field]=value}},"set");const m=recognized.metadata;set("sizeBytes",recognized.sizeBytes);set("durationMs",m.durationMs);set("width",m.width);set("height",m.height);set("maxWidth",m.width);set("maxHeight",m.height);set("frameRate",m.frameRate);set("frameCount",m.frameCount);set("bitRate",m.bitRate);set("sampleRateHz",m.sampleRateHz);set("channels",m.channels);const estimate=estimateRawResourceTokens(recognized);if(estimate.status==="ok"){set("estimatedTokenCount",estimate.estimatedTokenCount)}return{resource,...shared}}__name(resourceConditionContext,"resourceConditionContext");var MEMORY_ROLE_FIELDS={transcript:"hasTranscript",ocr:"hasOcr",caption:"hasCaption",summary:"hasSummary",keyframe:"hasKeyframes",clip:"hasClip"};async function memoryConditionNamespace(memory,binding){if(!memory||!binding)return void 0;const roles=await memory.service.collectVersionOutputRoles(binding);if(!roles)return void 0;const namespace={};for(const field of Object.values(MEMORY_ROLE_FIELDS)){namespace[field]=0}for(const role of roles){const field=MEMORY_ROLE_FIELDS[role];if(field)namespace[field]=1}return namespace}__name(memoryConditionNamespace,"memoryConditionNamespace");function requestConditionNamespace(items){let total=0;for(const item of items){if(!item.deliver)continue;const estimate=estimateRawResourceTokens(item.recognized);if(estimate.status!=="ok")return void 0;total+=estimate.estimatedTokenCount}return{totalEstimatedMediaTokens:total}}__name(requestConditionNamespace,"requestConditionNamespace");function sortPolicies(policies){return[...policies].sort((a,b)=>b.priority-a.priority||a.id.localeCompare(b.id))}__name(sortPolicies,"sortPolicies");var resourceGates=new Map;async function acquireResourceSlot(rootDir,limit){const effectiveLimit=Math.max(1,Math.floor(limit));let gate=resourceGates.get(rootDir);if(!gate){gate={active:0,waiters:[]};resourceGates.set(rootDir,gate)}const heldGate=gate;if(heldGate.active>=effectiveLimit){await new Promise(resolve=>heldGate.waiters.push(resolve))}else{heldGate.active++}let released=false;return()=>{if(released)return;released=true;const next=heldGate.waiters.shift();if(next){next();return}heldGate.active--;if(heldGate.active===0&&heldGate.waiters.length===0){resourceGates.delete(rootDir)}}}__name(acquireResourceSlot,"acquireResourceSlot");async function runFixedPolicies(config,source,options){const policies=sortPolicies(options.policies);const limits=options.limits??DEFAULT_OMNI_PROCESSING_LIMITS;const releaseSlot=await acquireResourceSlot(options.store.getOmniRootDir(),limits.maxConcurrentResources);try{return await runFixedPoliciesUnbounded(config,source,options,{policies,limits})}finally{releaseSlot()}}__name(runFixedPolicies,"runFixedPolicies");async function runFixedPoliciesUnbounded(config,source,options,normalized){const{policies,limits}=normalized;const cache=options.degradationCache??new OmniDegradationCache(options.store.getOmniRootDir());const records=[];const fileDeliveries=[];const items=[{filePath:source.filePath,recognized:source.recognized,label:source.displayName,origin:source.origin,sha256:source.sha256,memoryBinding:options.memory?.sourceBinding,lineageRuns:new Map,depth:0,deliver:true,process:true}];let runsUsed=0;let artifactsProduced=0;let derivedBytesProduced=0;let budgetExhausted=false;const stopOnBudget=__name((policy,item,reason)=>{budgetExhausted=true;records.push({policyId:policy.id,toolName:policy.toolName,outcome:"budget_exhausted",resource:item.label,error:reason});debugLogger2.debug(`per-root policy budget exhausted on ${item.label}: ${reason}; no further derivation for this root (committed deliveries stand)`)},"stopOnBudget");for(let i=0;i<items.length&&!budgetExhausted;i++){const item=items[i];if(!item.process)continue;if(item.recognized.modality==="image"&&(item.recognized.metadata.frameCount??1)>1){debugLogger2.debug(`animated image ${item.label} (${item.recognized.metadata.frameCount} frames) excluded from policy matching (D9)`);continue}const needsMemoryNamespace=policies.some(policy=>policy.when&&conditionUsesNamespace(policy.when,"memory"));const sharedConditionContext={request:options.conditionContext?.request??requestConditionNamespace(items),session:options.conditionContext?.session,memory:needsMemoryNamespace?await memoryConditionNamespace(options.memory,item.memoryBinding):void 0};for(const policy of policies){if(!policy.mediaTypes.includes(item.recognized.modality))continue;if(!policy.origins.includes(item.origin))continue;const runs=item.lineageRuns.get(policy.id)??0;if(runs>=policy.maxRunsPerLineage)continue;if(policy.when){const evaluation=evaluateFixedPolicyCondition(policy.when,resourceConditionContext(item.recognized,sharedConditionContext));if(evaluation.outcome==="no_match")continue;if(evaluation.outcome==="unavailable"&&policy.onConditionUnavailable==="skip"){records.push({policyId:policy.id,toolName:policy.toolName,outcome:"condition_unavailable",resource:item.label,missingFields:evaluation.missingFields});continue}}if(runsUsed>=limits.maxPolicyRunsPerRoot){stopOnBudget(policy,item,`maxPolicyRunsPerRoot (${limits.maxPolicyRunsPerRoot}) reached`);break}runsUsed++;item.lineageRuns.set(policy.id,runs+1);try{const execution=await executePolicy(config,item,policy,options.store,cache,options.signal,options.memory&&item.memoryBinding?{service:options.memory.service,source:item.memoryBinding}:void 0);records.push({policyId:policy.id,toolName:policy.toolName,outcome:execution.outcome,resource:item.label});if(execution.outcome==="no_op")continue;if(policy.output.source==="omit")item.deliver=false;const childDepth=item.depth+1;const depthAllowsReprocess=childDepth<limits.maxLineageDepth;if(policy.output.reprocessMedia&&!depthAllowsReprocess){debugLogger2.debug(`maxLineageDepth (${limits.maxLineageDepth}) reached under ${item.label}; derivatives deliver but do not re-enter policy matching`)}for(const derived of execution.derived){artifactsProduced++;derivedBytesProduced+=derived.recognized.sizeBytes;items.push({...derived,label:`${item.label} \u2192 ${policy.id}`,origin:"policy",lineageRuns:new Map(item.lineageRuns),depth:childDepth,deliver:resolveArtifactSelector(policy.output.artifacts,derived.recognized.modality,derived.role)==="include",process:policy.output.reprocessMedia&&depthAllowsReprocess})}for(const file of execution.derivedFiles){artifactsProduced++;derivedBytesProduced+=file.sizeBytes;if(resolveArtifactSelector(policy.output.artifacts,"file",file.role)==="include"){fileDeliveries.push(file)}}if(artifactsProduced>limits.maxArtifactsPerRoot){stopOnBudget(policy,item,`maxArtifactsPerRoot (${limits.maxArtifactsPerRoot}) exceeded`);break}if(derivedBytesProduced>limits.maxDerivedBytesPerRoot){stopOnBudget(policy,item,`maxDerivedBytesPerRoot (${limits.maxDerivedBytesPerRoot}) exceeded`);break}}catch(err){if(options.signal?.aborted)throw err;const message=err instanceof Error?err.message:String(err);records.push({policyId:policy.id,toolName:policy.toolName,outcome:"failed",resource:item.label,error:message});debugLogger2.debug(`fixed policy ${policy.id} (${policy.toolName}) failed on ${item.label}: ${message}`);if(policy.onFailure==="abort"||policy.stage==="transport_guard"){throw new OmniPolicyExecutionError(`Fixed policy ${policy.id} failed: ${message}`,policy.id,{cause:err})}}}}return{deliveries:items.filter(item=>item.deliver).map(item=>({filePath:item.filePath,recognized:item.recognized,sha256:item.sha256,disclosure:item.disclosure,degraded:item.degraded,memoryBinding:item.memoryBinding})),fileDeliveries,records}}__name(runFixedPoliciesUnbounded,"runFixedPoliciesUnbounded");async function executePolicy(config,item,policy,store,cache,signal,memory){const tool=config.getToolRegistry().getTool(policy.toolName);const descriptor=tool?.mediaPolicyDescriptor;if(!descriptor){throw new Error(`tool ${policy.toolName} is not a registered media-policy tool`)}item.sha256??=await hashFileSha256(item.filePath,signal);const settingsDefaults=resolvePolicyToolSettings(config,policy.toolName);const effectiveArguments={...settingsDefaults,...policy.arguments};const fingerprint=computePolicyFingerprint(policy.toolName,effectiveArguments,descriptor.version);const startedAt=new Date().toISOString();if(memory){const reusable=await memory.service.findReusableOutputs(item.sha256,fingerprint);const rebuilt=reusable?await rebuildReusedOutputs(reusable,descriptor,store,signal):void 0;if(rebuilt){debugLogger2.debug(`memory reuse hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026 outputs=${rebuilt.outputs.length} (tool not executed)`);const commit=await memory.service.commitPolicySucceeded({invocationId:"memory-reuse",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:rebuilt.outputs});return{outcome:"succeeded",derived:rebuilt.derived.map(d=>({...d,memoryBinding:commit?.mediaBindings.get(d.sha256)})),derivedFiles:rebuilt.derivedFiles}}}const hit=await cache.get(item.sha256,fingerprint);if(hit){try{const objectPath=store.objectPathFor(hit.degradedSha256,hit.extension);const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(stat?.isFile()&&!stat.isSymbolicLink()){const actualSha256=await hashFileSha256(objectPath,signal);if(actualSha256===hit.degradedSha256){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(declared){debugLogger2.debug(`degradation cache hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026`);const commit=memory?await memory.service.commitPolicySucceeded({invocationId:"cache-hit",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:[{kind:"media",objectPath,sha256:hit.degradedSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:hit.role,disclosure:hit.disclosure}]}):void 0;return{outcome:"cache_hit",derived:[{filePath:objectPath,recognized,sha256:hit.degradedSha256,disclosure:hit.disclosure,degraded:true,role:hit.role,memoryBinding:commit?.mediaBindings.get(hit.degradedSha256)}],derivedFiles:[]}}debugLogger2.debug(`degradation cache hit for policy=${policy.id} recognized as undeclared media type ${recognized.detectedMimeType}; dropping the entry and re-transcoding`)}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`degradation cache hit could not be verified for policy=${policy.id}: ${err instanceof Error?err.message:String(err)}; dropping the entry and re-transcoding`)}await cache.removeByDegradedSha256(hit.degradedSha256)}await settleOmniGc(store.getOmniRootDir());if(isOmniDerivationSuspended(store.getOmniRootDir())){throw new Error(`omni object store is over its byte budget with only memory-referenced objects left; new policy derivations are suspended. Raise omni.storage.maxTotalBytes or delete memory records you no longer need, then start a new session \u2014 the budget is re-evaluated once per process.`)}const invocationId=randomBytes(8).toString("hex");const stagingDir=await store.createStagingDir(invocationId);let failure;try{const request={callId:invocationId,name:policy.toolName,args:{...effectiveArguments,inputPath:item.filePath,outputDir:stagingDir},isClientInitiated:true,prompt_id:`omni-fixed-policy-${invocationId}`,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage}};const{executeToolCall}=await import("./nonInteractiveToolExecutor-DE3WACL5.js");const response=await executeToolCall(config,request,signal??new AbortController().signal,{recordToolResult:false});if(response.error){throw new Error(response.error.message,{cause:response.error})}const batch=response.policyArtifacts;if(!batch||batch.artifacts.length===0){throw new Error(`tool ${policy.toolName} succeeded but produced no policy artifacts`)}const validated=await Promise.all(batch.artifacts.map(artifact=>validateArtifact(artifact,descriptor,stagingDir,signal)));assertRequiredOutputsPresent(descriptor,validated,policy.toolName);if(validated.every(a=>a.sha256===item.sha256)){return{outcome:"no_op",derived:[],derivedFiles:[]}}const promoted=await Promise.all(validated.map(async artifact=>{const mimeType=artifact.kind==="media"?artifact.recognized.detectedMimeType:artifact.mimeType;const put=await store.putFile(artifact.absolutePath,artifact.sha256,extensionForMime(mimeType),signal);return{artifact,objectPath:put.objectPath}}));const derived=[];const derivedFiles=[];for(const{artifact,objectPath}of promoted){if(artifact.kind==="media"){derived.push({filePath:objectPath,recognized:artifact.recognized,sha256:artifact.sha256,disclosure:artifact.disclosure,degraded:artifact.lossy,role:artifact.role})}else{derivedFiles.push({filePath:objectPath,role:artifact.role,mimeType:artifact.mimeType,text:artifact.text,sha256:artifact.sha256,sizeBytes:artifact.sizeBytes,disclosure:artifact.disclosure})}}if(memory){const outputs=promoted.map(({artifact,objectPath})=>artifact.kind==="media"?{kind:"media",objectPath,sha256:artifact.sha256,mediaType:artifact.recognized.modality,metadata:artifact.recognized.metadata,sizeBytes:artifact.recognized.sizeBytes,mimeType:artifact.recognized.detectedMimeType,role:artifact.role,disclosure:artifact.disclosure}:{kind:"text",objectPath,sha256:artifact.sha256,mimeType:artifact.mimeType,text:artifact.text,sizeBytes:artifact.sizeBytes,role:artifact.role,disclosure:artifact.disclosure});const commit=await memory.service.commitPolicySucceeded({invocationId,source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs});if(commit){for(const entry of derived){entry.memoryBinding=commit.mediaBindings.get(entry.sha256)}}}if(validated.length===1&&validated[0].kind==="media"&&validated[0].disclosure){await cache.put(item.sha256,fingerprint,{degradedSha256:validated[0].sha256,extension:extensionForMime(validated[0].recognized.detectedMimeType),disclosure:validated[0].disclosure,mimeType:validated[0].recognized.detectedMimeType,...validated[0].role!==void 0?{role:validated[0].role}:{}})}return{outcome:"succeeded",derived,derivedFiles}}catch(err){failure=err;throw err}finally{if(failure===void 0||signal?.aborted){await store.removeStagingDir(invocationId).catch(()=>{})}else{try{await store.quarantineInvocation(invocationId,{policyId:policy.id,toolName:policy.toolName,reason:failure instanceof Error?failure.message:String(failure)})}catch{await store.removeStagingDir(invocationId).catch(()=>{})}}}}__name(executePolicy,"executePolicy");async function rebuildReusedOutputs(reusable,descriptor,store,signal){const outputs=[];const derived=[];const derivedFiles=[];try{for(const record of reusable.outputs){const objectPath=record.objectPath??store.objectPathFor(record.sha256,extensionForMime(record.mimeType));const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink())return void 0;if(await hashFileSha256(objectPath,signal)!==record.sha256){return void 0}if(record.kind==="media"){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!declared)return void 0;outputs.push({kind:"media",objectPath,sha256:record.sha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:record.role,disclosure:record.disclosure});derived.push({filePath:objectPath,recognized,sha256:record.sha256,disclosure:record.disclosure,degraded:record.disclosure!==void 0,role:record.role})}else{const text=await fs2.readFile(objectPath,"utf8");outputs.push({kind:"text",objectPath,sha256:record.sha256,mimeType:record.mimeType,text,sizeBytes:record.sizeBytes,role:record.role,disclosure:record.disclosure});derivedFiles.push({filePath:objectPath,role:record.role,mimeType:record.mimeType,text,sha256:record.sha256,sizeBytes:record.sizeBytes,disclosure:record.disclosure})}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`memory reuse could not be verified, re-deriving: ${err instanceof Error?err.message:String(err)}`);return void 0}return{outputs,derived,derivedFiles}}__name(rebuildReusedOutputs,"rebuildReusedOutputs");async function validateArtifact(artifact,descriptor,stagingDir,signal){if(artifact.storage!=="workspace"||!artifact.workspacePath){throw new Error(`policy artifact "${artifact.title}" is not a workspace file`)}const absolutePath=path3.resolve(stagingDir,artifact.workspacePath);if(!absolutePath.startsWith(stagingDir+path3.sep)){throw new Error(`policy artifact "${artifact.title}" escapes the staging directory`)}const stat=await fs2.lstat(absolutePath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink()){throw new Error(`policy artifact "${artifact.title}" is missing or not a regular file`)}const rawRole=artifact.metadata?.["omniRole"];const role=typeof rawRole==="string"&&rawRole?rawRole:void 0;const rawDisclosure=artifact.metadata?.["omniDisclosure"];const disclosure=typeof rawDisclosure==="string"&&rawDisclosure?rawDisclosure:void 0;if(artifact.kind==="file"){const spec2=descriptor.outputs.find(o=>o.kind==="file"&&(o.role===void 0||o.role===role)&&artifact.mimeType!==void 0&&o.mimeTypes?.includes(artifact.mimeType));if(!spec2){throw new Error(`policy artifact "${artifact.title}" (file, role ${role??"none"}, ${artifact.mimeType??"no mimeType"}) matches no declared file output`)}if(stat.size>MAX_FILE_ARTIFACT_BYTES){throw new Error(`policy artifact "${artifact.title}" exceeds the file-artifact size budget (${stat.size} > ${MAX_FILE_ARTIFACT_BYTES} bytes)`)}const bytes=await fs2.readFile(absolutePath);let text;try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new Error(`policy artifact "${artifact.title}" is not valid UTF-8 text`)}if(spec2.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"file",absolutePath,mimeType:artifact.mimeType,text,sizeBytes:bytes.byteLength,sha256:createHash2("sha256").update(bytes).digest("hex"),disclosure,lossy:spec2.lossy===true,role}}const recognized=await recognizeMediaFile(absolutePath,{signal});const spec=descriptor.outputs.find(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!spec){throw new Error(`policy artifact "${artifact.title}" has undeclared media type ${recognized.detectedMimeType}`)}if(artifact.kind!==recognized.modality){throw new Error(`policy artifact "${artifact.title}" declares kind ${String(artifact.kind)} but contains ${recognized.modality} content`)}if(spec.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"media",absolutePath,recognized,sha256:await hashFileSha256(absolutePath,signal),disclosure,lossy:spec.lossy===true,role}}__name(validateArtifact,"validateArtifact");function assertRequiredOutputsPresent(descriptor,validated,toolName){for(const spec of descriptor.outputs){if(!spec.required)continue;let produced;if(spec.kind==="media"){produced=validated.some(a=>a.kind==="media"&&spec.mimeTypes?.includes(a.recognized.detectedMimeType))}else if(spec.kind==="file"){produced=validated.some(a=>a.kind==="file"&&(spec.role===void 0||a.role===spec.role)&&spec.mimeTypes?.includes(a.mimeType))}else{continue}if(!produced){throw new Error(`tool ${toolName} did not produce its required ${spec.kind} ${spec.mimeTypes?.join("/")??spec.role??""} output`)}}}__name(assertRequiredOutputsPresent,"assertRequiredOutputsPresent");export{estimateRawResourceTokens,computePolicyFingerprint,OmniDegradationCache,DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES,OmniTransportGuardError,effectiveMaxUploadFileBytes,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveOmniStorageMaxTotalBytes,runOmniGcOnce,OmniPolicyExecutionError,runFixedPolicies,validateArtifact,assertRequiredOutputsPresent};
6
6
  /**
7
7
  * @license
8
8
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{SessionService,TURN_INTERRUPTION_HISTORY_TAIL_COUNT,buildSessionHistoryFromConversation,detectTurnInterruption,effectiveHistoryEnd}from"./chunk-LIIMQ4DI.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{closeSync as closeSync2,openSync as openSync2,readSync as readSync2,statSync as statSync2}from"node:fs";init_esbuild_shims();import{appendFileSync,closeSync,mkdirSync,openSync,readFileSync,readSync,statSync}from"node:fs";import*as path from"node:path";function isPromptLedgerTerminalRecord(record){return"terminal"in record}__name(isPromptLedgerTerminalRecord,"isPromptLedgerTerminalRecord");function appendPromptLedgerRecord(filePath,record){mkdirSync(path.dirname(filePath),{recursive:true});sealTornTailSync(filePath);appendFileSync(filePath,`${JSON.stringify(record)}
3
+ import{SessionService,TURN_INTERRUPTION_HISTORY_TAIL_COUNT,buildSessionHistoryFromConversation,detectTurnInterruption,effectiveHistoryEnd}from"./chunk-LZNBHBAJ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{closeSync as closeSync2,openSync as openSync2,readSync as readSync2,statSync as statSync2}from"node:fs";init_esbuild_shims();import{appendFileSync,closeSync,mkdirSync,openSync,readFileSync,readSync,statSync}from"node:fs";import*as path from"node:path";function isPromptLedgerTerminalRecord(record){return"terminal"in record}__name(isPromptLedgerTerminalRecord,"isPromptLedgerTerminalRecord");function appendPromptLedgerRecord(filePath,record){mkdirSync(path.dirname(filePath),{recursive:true});sealTornTailSync(filePath);appendFileSync(filePath,`${JSON.stringify(record)}
4
4
  `,{encoding:"utf8",mode:384})}__name(appendPromptLedgerRecord,"appendPromptLedgerRecord");function sealTornTailSync(filePath){let stats;try{stats=statSync(filePath)}catch(error){if(error.code==="ENOENT")return;throw error}if(stats.size===0)return;const fd=openSync(filePath,"r");try{const lastByte=Buffer.alloc(1);const bytesRead=readSync(fd,lastByte,0,1,stats.size-1);if(bytesRead===1&&lastByte[0]!==10){appendFileSync(filePath,"\n","utf8")}}finally{closeSync(fd)}}__name(sealTornTailSync,"sealTornTailSync");function coercePromptLedgerRecord(value){if(typeof value!=="object"||value===null)return void 0;const record=value;const promptId=record["promptId"];const at=record["at"];if(record["v"]!==1||typeof promptId!=="string")return void 0;if(typeof at!=="number"||!Number.isFinite(at))return void 0;if(record["state"]==="in_flight"){const tailUuid=record["tailUuid"];return{v:1,promptId,state:"in_flight",...typeof tailUuid==="string"&&tailUuid.length>0?{tailUuid}:{},at}}const terminal=record["terminal"];if(terminal!=="completed"&&terminal!=="cancelled"&&terminal!=="error"&&terminal!=="interrupted"){return void 0}const code=record["code"];const stopReason=record["stopReason"];return{v:1,promptId,terminal,...typeof code==="string"?{code}:{},...typeof stopReason==="string"?{stopReason}:{},at}}__name(coercePromptLedgerRecord,"coercePromptLedgerRecord");function readPromptLedgerRecords(filePath,options){let contents;let dropFirstLine=false;try{const tailBytes=options?.tailBytes;if(tailBytes===void 0){contents=readFileSync(filePath,"utf8")}else{const size=statSync(filePath).size;if(size<=tailBytes){contents=readFileSync(filePath,"utf8")}else{const fd=openSync(filePath,"r");try{const buffer=Buffer.alloc(tailBytes);const bytesRead=readSync(fd,buffer,0,tailBytes,size-tailBytes);contents=buffer.subarray(0,bytesRead).toString("utf8");dropFirstLine=true}finally{closeSync(fd)}}}}catch(error){if(error.code==="ENOENT")return[];throw error}const records=[];const lines=contents.split("\n");for(let i=dropFirstLine?1:0;i<lines.length;i++){const line=lines[i];if(line===void 0||line.length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch{continue}const record=coercePromptLedgerRecord(parsed);if(record!==void 0)records.push(record)}return records}__name(readPromptLedgerRecords,"readPromptLedgerRecords");function danglingInFlightPromptIds(records){const latest=new Map;for(const record of records){latest.set(record.promptId,record)}const dangling=[];for(const[promptId,record]of latest){if(!isPromptLedgerTerminalRecord(record))dangling.push(promptId)}return dangling}__name(danglingInFlightPromptIds,"danglingInFlightPromptIds");var PROMPT_TERMINALS_RESPONSE_LIMIT=64;function recentPromptTerminalRecords(records){const terminals=records.filter(isPromptLedgerTerminalRecord);return terminals.length<=PROMPT_TERMINALS_RESPONSE_LIMIT?terminals:terminals.slice(-PROMPT_TERMINALS_RESPONSE_LIMIT)}__name(recentPromptTerminalRecords,"recentPromptTerminalRecords");function createPromptLedgerSink(workspaceCwd,sessionRuntimeBaseDir){const sessionService=new SessionService(workspaceCwd,{runtimeBaseDir:sessionRuntimeBaseDir});return{appendSync(sessionId,record){appendPromptLedgerRecord(sessionService.getPromptLedgerPath(sessionId),record)},transcriptTailUuid(sessionId){return readTranscriptTailUuid(sessionService.getSessionTranscriptPath(sessionId))}}}__name(createPromptLedgerSink,"createPromptLedgerSink");var TRANSCRIPT_TAIL_BYTES=64*1024;function readTranscriptTailUuid(transcriptPath){let contents;try{const size=statSync2(transcriptPath).size;if(size===0)return void 0;const windowBytes=Math.min(size,TRANSCRIPT_TAIL_BYTES);const buffer=Buffer.alloc(windowBytes);const fd=openSync2(transcriptPath,"r");try{readSync2(fd,buffer,0,windowBytes,size-windowBytes)}finally{closeSync2(fd)}contents=buffer.toString("utf8")}catch{return void 0}const lines=contents.split("\n");for(let i=lines.length-1;i>=0;i--){const line=lines[i];if(line===void 0||line.length===0)continue;try{const uuid=JSON.parse(line).uuid;return typeof uuid==="string"&&uuid.length>0?uuid:void 0}catch{return void 0}}return void 0}__name(readTranscriptTailUuid,"readTranscriptTailUuid");async function reconcileDanglingPromptTerminals(sessionService,sessionId){const ledgerPath=sessionService.getPromptLedgerPath(sessionId);let records;try{records=readPromptLedgerRecords(ledgerPath)}catch{return}const snapshotLength=records.length;const dangling=danglingInFlightPromptIds(records);if(dangling.length===0)return;if(dangling.length>1)return;const target=dangling[0];if(target===void 0)return;const settledPromptIds=new Set(records.filter(isPromptLedgerTerminalRecord).map(r=>r.promptId));let targetAdmission;for(const record2 of records){if(!isPromptLedgerTerminalRecord(record2)&&!settledPromptIds.has(record2.promptId)){targetAdmission=record2}}if(targetAdmission===void 0||targetAdmission.promptId!==target){return}let resumed;try{resumed=await sessionService.loadSession(sessionId)}catch{return}if(resumed===void 0)return;const messages=resumed.conversation.messages;const admissionMarker=targetAdmission.tailUuid;let markerIndex=-1;if(admissionMarker!==void 0){markerIndex=messages.findIndex(record2=>record2.uuid===admissionMarker);let wroteAfterMarker=false;for(let i=markerIndex+1;i<messages.length;i++){const record2=messages[i];if(record2===void 0||record2.type==="system")continue;if(!record2.message||record2.subtype==="realtime_message")continue;wroteAfterMarker=true;break}if(markerIndex<0||!wroteAfterMarker)return}let lastVisibleWriteMs=NaN;let lastVisibleNonSystem;let compressedAfterAdmission=false;let localCommandCompleted=false;const admissionAt=targetAdmission.at;const isAfterAdmission=__name((idx,writeMs)=>admissionMarker!==void 0?idx>markerIndex:Number.isFinite(writeMs)&&writeMs>=admissionAt,"isAfterAdmission");for(let idx=0;idx<messages.length;idx++){const record2=messages[idx];const writeMs=Date.parse(record2.timestamp);if(record2.type==="system"){if(isCompressionResetRecord(record2)){if(isAfterAdmission(idx,writeMs))compressedAfterAdmission=true}else if(!localCommandCompleted&&isAfterAdmission(idx,writeMs)&&isLocalSlashCommandResult(record2,lastVisibleNonSystem)){localCommandCompleted=true}continue}if(!record2.message||record2.subtype==="realtime_message")continue;if(record2.provenance==="system")continue;if(record2.subtype==="agent_mention"||record2.subtype==="agent_message"){continue}if(Number.isFinite(writeMs))lastVisibleWriteMs=writeMs;lastVisibleNonSystem=record2}let lastOtherTerminalAt=0;for(const record2 of records){if(isPromptLedgerTerminalRecord(record2)&&record2.promptId!==target){if(record2.code==="prompt_deadline_exceeded")return;lastOtherTerminalAt=Math.max(lastOtherTerminalAt,record2.at)}}if(compressedAfterAdmission||!Number.isFinite(lastVisibleWriteMs)||lastVisibleWriteMs<=targetAdmission.at||lastVisibleWriteMs<=lastOtherTerminalAt){return}const{apiHistory,completedToolCallIds}=buildSessionHistoryFromConversation(resumed.conversation);const classifiableEnd=effectiveHistoryEnd(apiHistory);const historyTail=apiHistory.slice(Math.max(0,classifiableEnd-TURN_INTERRUPTION_HISTORY_TAIL_COUNT),classifiableEnd);const verdict=detectTurnInterruption(historyTail,completedToolCallIds);const interrupted=verdict.kind!=="none"||tailHoldsAnyFunctionCall(historyTail);const lastVisibleNonSystemType=lastVisibleNonSystem?.type;if(!interrupted&&lastVisibleNonSystemType!=="assistant"&&lastVisibleNonSystemType!=="tool_result"&&!localCommandCompleted){return}let refetch;try{refetch=readPromptLedgerRecords(ledgerPath)}catch{return}if(refetch.length!==snapshotLength)return;const record=interrupted?{v:1,promptId:target,terminal:"interrupted",code:"daemon_lost",at:Date.now()}:{v:1,promptId:target,terminal:"completed",stopReason:"reconstructed_from_transcript",at:Date.now()};try{appendPromptLedgerRecord(ledgerPath,record)}catch{}}__name(reconcileDanglingPromptTerminals,"reconcileDanglingPromptTerminals");function isCompressionResetRecord(record){if(record.type!=="system"||record.subtype!=="chat_compression"){return false}return Boolean(record.systemPayload?.compressedHistory)}__name(isCompressionResetRecord,"isCompressionResetRecord");function isLocalSlashCommandResult(record,previous){if(record.subtype!=="slash_command")return false;const payload=record.systemPayload;const items=payload?.outputHistoryItems;const parts=previous?.message?.parts;const first=parts?.[0];return payload?.phase==="result"&&payload.sentToModel!==true&&Array.isArray(items)&&items.length>0&&items.every(item=>item["type"]==="assistant")&&previous?.type==="user"&&previous.subtype===void 0&&previous.message?.role==="user"&&parts?.length===1&&first!==void 0&&typeof first.text==="string"&&Object.keys(first).length===1&&first.text===payload.rawCommand}__name(isLocalSlashCommandResult,"isLocalSlashCommandResult");function tailHoldsAnyFunctionCall(history){const last=history[history.length-1];if(last?.role!=="model")return false;return(last.parts??[]).some(part=>part.functionCall!==void 0)}__name(tailHoldsAnyFunctionCall,"tailHoldsAnyFunctionCall");var RECENT_TERMINALS_TAIL_BYTES=256*1024;function readRecentPromptTerminals(sessionService,sessionId){try{const terminals=recentPromptTerminalRecords(readPromptLedgerRecords(sessionService.getPromptLedgerPath(sessionId),{tailBytes:RECENT_TERMINALS_TAIL_BYTES}));return terminals.length>0?terminals:void 0}catch{return void 0}}__name(readRecentPromptTerminals,"readRecentPromptTerminals");function withPromptTerminals(session,terminals){if(terminals===void 0||terminals.length===0)return session;return{...session,promptTerminals:[...terminals]}}__name(withPromptTerminals,"withPromptTerminals");export{createPromptLedgerSink,readTranscriptTailUuid,reconcileDanglingPromptTerminals,readRecentPromptTerminals,withPromptTerminals};
5
5
  /**
6
6
  * @license
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{appEvents}from"./chunk-YL3N2UGG.js";import{assembleMcpServers,getPendingGatedMcpServers,getPromptableMcpServers}from"./chunk-WRJ3PMDZ.js";import{getMCPServerStatus}from"./chunk-TNCN2JX2.js";import{require_fast_deep_equal}from"./chunk-3KUHQGOS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var debugLogger=createDebugLogger("MCP_HOT_RELOAD");var modelProvidersDebugLogger=createDebugLogger("MODEL_PROVIDERS_HOT_RELOAD");function mcpServersEqual(a,b){return(0,import_fast_deep_equal.default)(a??{},b??{})}__name(mcpServersEqual,"mcpServersEqual");function mcpGatingEqual(a,b){const norm=__name(xs=>[...xs??[]].sort(),"norm");const allowedEqual=a.allowed===void 0===(b.allowed===void 0)&&(0,import_fast_deep_equal.default)(norm(a.allowed),norm(b.allowed));return(0,import_fast_deep_equal.default)(norm(a.excluded),norm(b.excluded))&&allowedEqual&&(0,import_fast_deep_equal.default)(norm(a.pending),norm(b.pending))}__name(mcpGatingEqual,"mcpGatingEqual");function recomputeMcpGating(settings,assembled,cwd,bootAllowed,isYolo){const settingsAllowed=settings.merged.mcp?.allowed?.filter(Boolean);const excluded=settings.merged.mcp?.excluded?.filter(Boolean);let allowed=settingsAllowed;if(bootAllowed){allowed=settingsAllowed?settingsAllowed.filter(n=>bootAllowed.includes(n)):[...bootAllowed]}return{allowed,excluded:excluded&&excluded.length>0?excluded:void 0,pending:isYolo?void 0:getPendingGatedMcpServers(assembled,cwd)}}__name(recomputeMcpGating,"recomputeMcpGating");function registerMcpHotReload(watcher,settings,config,topTierMcpServers){debugLogger.debug("registered MCP hot-reload listener on SettingsWatcher");return watcher.addChangeListener(async events=>{debugLogger.debug(`settings change fired (${events.length} event(s)): ${events.map(e=>`${e.scope}:${e.changeType}`).join(", ")}`);const cwd=config.getTargetDir();const next=config.getBareMode()||config.isSafeMode()?{...topTierMcpServers}:assembleMcpServers(settings.merged.mcpServers,cwd,topTierMcpServers);const isYolo=config.getApprovalMode()==="yolo";const bootAllowed=config.getCliAllowedMcpServerNames();const nextGating=config.getBareMode()||config.isSafeMode()?{allowed:bootAllowed?[...bootAllowed]:void 0}:recomputeMcpGating(settings,next,cwd,bootAllowed,isYolo);const prevServers=config.getSettingsMcpServers();const prevGating=config.getMcpGating();debugLogger.debug(`assembled servers: prev=[${Object.keys(prevServers??{}).join(", ")}] next=[${Object.keys(next).join(", ")}]`);debugLogger.debug(`gating next: excluded=[${(nextGating.excluded??[]).join(", ")}] allowed=[${(nextGating.allowed??[]).join(", ")}] pending=[${(nextGating.pending??[]).join(", ")}]`);const serversChanged=!mcpServersEqual(prevServers,next);const gatingChanged=!mcpGatingEqual(prevGating,nextGating);if(!serversChanged&&!gatingChanged){debugLogger.debug("no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile");return}debugLogger.debug(`MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`);const promptable=getPromptableMcpServers(next,cwd);config.setExcludedMcpServers(nextGating.excluded??[]);config.setAllowedMcpServers(nextGating.allowed);config.setPendingMcpServers(nextGating.pending);try{await config.reinitializeMcpServers(next);const finalStatuses=Object.keys(next).map(name=>`${name}=${getMCPServerStatus(name)}`).join(", ");debugLogger.debug(`reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`)}catch(err){debugLogger.error(`reinitializeMcpServers threw: ${err instanceof Error?err.stack??err.message:String(err)}`);appEvents.emit("log-error","Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details.")}if(!isYolo&&promptable.length>0){debugLogger.debug(`gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed"}: [${promptable.join(", ")}]`);appEvents.emit("mcp-pending-approval-changed")}})}__name(registerMcpHotReload,"registerMcpHotReload");function registerModelProvidersHotReload(watcher,settings,config){modelProvidersDebugLogger.debug("registered modelProviders hot-reload listener on SettingsWatcher");let refreshAuthRetryPending=false;const reconcile=__name(async()=>{const next=settings.merged.modelProviders;const providersUnchanged=(0,import_fast_deep_equal.default)(config.getModelProvidersConfig()??{},next??{});if(providersUnchanged&&!refreshAuthRetryPending){return}if(!providersUnchanged){modelProvidersDebugLogger.debug("modelProviders changed \u2014 reloading model registry");try{config.reloadModelProvidersConfig(next)}catch(err){modelProvidersDebugLogger.error(`reloadModelProvidersConfig threw: ${err instanceof Error?err.stack??err.message:String(err)}`);return}}const authType=config.getAuthType();if(!authType){return}try{await config.refreshAuth(authType,true);refreshAuthRetryPending=false}catch(err){const alreadyPending=refreshAuthRetryPending;refreshAuthRetryPending=true;modelProvidersDebugLogger.error(`refreshAuth after modelProviders reload threw: ${err instanceof Error?err.stack??err.message:String(err)}`);if(!alreadyPending){appEvents.emit("log-error",`Model provider settings reloaded, but re-authenticating the active model failed: ${err instanceof Error?err.message:String(err)}. Select a model with /model or restart to apply the change.`)}}},"reconcile");void reconcile();return watcher.addChangeListener(reconcile)}__name(registerModelProvidersHotReload,"registerModelProvidersHotReload");export{recomputeMcpGating,registerMcpHotReload,registerModelProvidersHotReload};
3
+ import{appEvents}from"./chunk-5X7S4AE6.js";import{assembleMcpServers,getPendingGatedMcpServers,getPromptableMcpServers}from"./chunk-JUQ7T2MV.js";import{getMCPServerStatus}from"./chunk-TNCN2JX2.js";import{require_fast_deep_equal}from"./chunk-3KUHQGOS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var debugLogger=createDebugLogger("MCP_HOT_RELOAD");var modelProvidersDebugLogger=createDebugLogger("MODEL_PROVIDERS_HOT_RELOAD");function mcpServersEqual(a,b){return(0,import_fast_deep_equal.default)(a??{},b??{})}__name(mcpServersEqual,"mcpServersEqual");function mcpGatingEqual(a,b){const norm=__name(xs=>[...xs??[]].sort(),"norm");const allowedEqual=a.allowed===void 0===(b.allowed===void 0)&&(0,import_fast_deep_equal.default)(norm(a.allowed),norm(b.allowed));return(0,import_fast_deep_equal.default)(norm(a.excluded),norm(b.excluded))&&allowedEqual&&(0,import_fast_deep_equal.default)(norm(a.pending),norm(b.pending))}__name(mcpGatingEqual,"mcpGatingEqual");function recomputeMcpGating(settings,assembled,cwd,bootAllowed,isYolo){const settingsAllowed=settings.merged.mcp?.allowed?.filter(Boolean);const excluded=settings.merged.mcp?.excluded?.filter(Boolean);let allowed=settingsAllowed;if(bootAllowed){allowed=settingsAllowed?settingsAllowed.filter(n=>bootAllowed.includes(n)):[...bootAllowed]}return{allowed,excluded:excluded&&excluded.length>0?excluded:void 0,pending:isYolo?void 0:getPendingGatedMcpServers(assembled,cwd)}}__name(recomputeMcpGating,"recomputeMcpGating");function registerMcpHotReload(watcher,settings,config,topTierMcpServers){debugLogger.debug("registered MCP hot-reload listener on SettingsWatcher");return watcher.addChangeListener(async events=>{debugLogger.debug(`settings change fired (${events.length} event(s)): ${events.map(e=>`${e.scope}:${e.changeType}`).join(", ")}`);const cwd=config.getTargetDir();const next=config.getBareMode()||config.isSafeMode()?{...topTierMcpServers}:assembleMcpServers(settings.merged.mcpServers,cwd,topTierMcpServers);const isYolo=config.getApprovalMode()==="yolo";const bootAllowed=config.getCliAllowedMcpServerNames();const nextGating=config.getBareMode()||config.isSafeMode()?{allowed:bootAllowed?[...bootAllowed]:void 0}:recomputeMcpGating(settings,next,cwd,bootAllowed,isYolo);const prevServers=config.getSettingsMcpServers();const prevGating=config.getMcpGating();debugLogger.debug(`assembled servers: prev=[${Object.keys(prevServers??{}).join(", ")}] next=[${Object.keys(next).join(", ")}]`);debugLogger.debug(`gating next: excluded=[${(nextGating.excluded??[]).join(", ")}] allowed=[${(nextGating.allowed??[]).join(", ")}] pending=[${(nextGating.pending??[]).join(", ")}]`);const serversChanged=!mcpServersEqual(prevServers,next);const gatingChanged=!mcpGatingEqual(prevGating,nextGating);if(!serversChanged&&!gatingChanged){debugLogger.debug("no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile");return}debugLogger.debug(`MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`);const promptable=getPromptableMcpServers(next,cwd);config.setExcludedMcpServers(nextGating.excluded??[]);config.setAllowedMcpServers(nextGating.allowed);config.setPendingMcpServers(nextGating.pending);try{await config.reinitializeMcpServers(next);const finalStatuses=Object.keys(next).map(name=>`${name}=${getMCPServerStatus(name)}`).join(", ");debugLogger.debug(`reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`)}catch(err){debugLogger.error(`reinitializeMcpServers threw: ${err instanceof Error?err.stack??err.message:String(err)}`);appEvents.emit("log-error","Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details.")}if(!isYolo&&promptable.length>0){debugLogger.debug(`gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed"}: [${promptable.join(", ")}]`);appEvents.emit("mcp-pending-approval-changed")}})}__name(registerMcpHotReload,"registerMcpHotReload");function registerModelProvidersHotReload(watcher,settings,config){modelProvidersDebugLogger.debug("registered modelProviders hot-reload listener on SettingsWatcher");let refreshAuthRetryPending=false;const reconcile=__name(async()=>{const next=settings.merged.modelProviders;const providersUnchanged=(0,import_fast_deep_equal.default)(config.getModelProvidersConfig()??{},next??{});if(providersUnchanged&&!refreshAuthRetryPending){return}if(!providersUnchanged){modelProvidersDebugLogger.debug("modelProviders changed \u2014 reloading model registry");try{config.reloadModelProvidersConfig(next)}catch(err){modelProvidersDebugLogger.error(`reloadModelProvidersConfig threw: ${err instanceof Error?err.stack??err.message:String(err)}`);return}}const authType=config.getAuthType();if(!authType){return}try{await config.refreshAuth(authType,true);refreshAuthRetryPending=false}catch(err){const alreadyPending=refreshAuthRetryPending;refreshAuthRetryPending=true;modelProvidersDebugLogger.error(`refreshAuth after modelProviders reload threw: ${err instanceof Error?err.stack??err.message:String(err)}`);if(!alreadyPending){appEvents.emit("log-error",`Model provider settings reloaded, but re-authenticating the active model failed: ${err instanceof Error?err.message:String(err)}. Select a model with /model or restart to apply the change.`)}}},"reconcile");void reconcile();return watcher.addChangeListener(reconcile)}__name(registerModelProvidersHotReload,"registerModelProvidersHotReload");export{recomputeMcpGating,registerMcpHotReload,registerModelProvidersHotReload};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{sanitizeProviderBaseUrl}from"./chunk-GT4TCQ3R.js";import{resolveModelConfig}from"./chunk-LIIMQ4DI.js";import{getBuiltinDeepSeekReasoning,resolveModelSelectionAuthType,resolveProviderProtocol,stripRuntimeSnapshotPrefix,tryResolveModelProtocol}from"./chunk-OVPEAKOQ.js";import{MODEL_GENERATION_CONFIG_FIELDS}from"./chunk-OCVRMNEQ.js";import{REASONING_EFFORT_TIERS,normalizeReasoningEffort}from"./chunk-HEDN54OB.js";import{AuthType}from"./chunk-ZZZAYAJW.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var AUTH_ENV_MODEL_VARS={["openai"]:["OPENAI_MODEL","QWEN_MODEL"],["openai-responses"]:["OPENAI_MODEL"],["gemini"]:["GEMINI_MODEL"],["vertex-ai"]:["GOOGLE_MODEL"],["anthropic"]:["ANTHROPIC_MODEL"],["qwen-oauth"]:[]};function collectProviderModelsForProtocol(modelProviders,providerProtocol,protocol){if(!modelProviders){return[]}const out=[];for(const[providerId,models]of Object.entries(modelProviders)){if(!Array.isArray(models)){continue}out.push(...models.filter(model=>tryResolveModelProtocol(providerId,model,providerProtocol)===protocol))}return out}__name(collectProviderModelsForProtocol,"collectProviderModelsForProtocol");function findProviderIdForModel(modelProviders,providerProtocol,protocol,modelProvider){if(!modelProviders||!modelProvider){return void 0}for(const[providerId,models]of Object.entries(modelProviders)){if(!Array.isArray(models)){continue}if(models.includes(modelProvider)&&tryResolveModelProtocol(providerId,modelProvider,providerProtocol)===protocol){return providerId}}return void 0}__name(findProviderIdForModel,"findProviderIdForModel");function buildSkippedProviderWarnings(modelProviders,providerProtocol){if(!modelProviders){return[]}const warnings=[];const known=Object.values(AuthType).filter(value=>value!=="openai-responses").join(", ");for(const[providerId,models]of Object.entries(modelProviders)){if(!Array.isArray(models)||models.length===0){continue}const protocol=resolveProviderProtocol(providerId,providerProtocol);if(protocol==="qwen-oauth"&&providerId!=="qwen-oauth"){warnings.push(`Warning: modelProviders provider "${providerId}" maps to "qwen-oauth" via providerProtocol, but qwen-oauth uses hard-coded models only; its ${models.length} model(s) are ignored.`);continue}if(protocol!==void 0){continue}const mapped=providerProtocol&&Object.hasOwn(providerProtocol,providerId)?providerProtocol[providerId]:void 0;warnings.push(mapped!==void 0?`Warning: providerProtocol["${providerId}"] = "${mapped}" is not a known protocol (expected one of: ${known}); its ${models.length} model(s) are ignored.`:`Warning: modelProviders provider "${providerId}" is not a built-in protocol (${known}) and has no providerProtocol mapping; its ${models.length} model(s) are ignored. Add providerProtocol["${providerId}"] (e.g. "openai") to enable them.`)}return warnings}__name(buildSkippedProviderWarnings,"buildSkippedProviderWarnings");function getIgnoredTopLevelGenerationConfigFields(settingsGenerationConfig,modelProvider){if(!settingsGenerationConfig||!modelProvider){return[]}const providerGenerationConfig=modelProvider.generationConfig??{};return MODEL_GENERATION_CONFIG_FIELDS.filter(field=>Object.hasOwn(settingsGenerationConfig,field)&&!Object.hasOwn(providerGenerationConfig,field))}__name(getIgnoredTopLevelGenerationConfigFields,"getIgnoredTopLevelGenerationConfigFields");function buildIgnoredTopLevelGenerationConfigWarning(providerId,modelProvider,ignoredFields){if(ignoredFields.length===0){return void 0}const fieldList=ignoredFields.map(field=>`model.generationConfig.${field}`).join(", ");const isSingular=ignoredFields.length===1;const verb=isSingular?"is":"are";const fieldReference=isSingular?"this field":"these fields";const pronoun=isSingular?"it":"them";return`Warning: ${fieldList} ${verb} ignored for provider model "${modelProvider.id}" from modelProviders.${providerId}. Move ${fieldReference} to modelProviders.${providerId}[].generationConfig for that model if you want ${pronoun} to apply.`}__name(buildIgnoredTopLevelGenerationConfigWarning,"buildIgnoredTopLevelGenerationConfigWarning");function getAuthTypeFromEnv(env=process.env){if(env["QWEN_OAUTH"]){return"qwen-oauth"}if(env["OPENAI_API_KEY"]&&(env["OPENAI_MODEL"]||env["QWEN_MODEL"])&&env["OPENAI_BASE_URL"]){return"openai"}if(env["GEMINI_API_KEY"]&&env["GEMINI_MODEL"]){return"gemini"}if(env["GOOGLE_API_KEY"]&&env["GOOGLE_MODEL"]){return"vertex-ai"}if(env["GOOGLE_CLOUD_PROJECT"]&&env["GOOGLE_MODEL"]){return"vertex-ai"}if(env["ANTHROPIC_API_KEY"]&&env["ANTHROPIC_MODEL"]&&env["ANTHROPIC_BASE_URL"]){return"anthropic"}return void 0}__name(getAuthTypeFromEnv,"getAuthTypeFromEnv");function resolveCliGenerationConfig(inputs){const{argv,settings,selectedAuthType}=inputs;const env=inputs.env??process.env;let resolvedModel;let sourceEnvVar;let resolvedFromSettings=false;if(argv.model){resolvedModel=argv.model}else if(settings.model?.name){resolvedModel=stripRuntimeSnapshotPrefix(settings.model.name);resolvedFromSettings=true}else if(selectedAuthType&&AUTH_ENV_MODEL_VARS[selectedAuthType]){for(const envVar of AUTH_ENV_MODEL_VARS[selectedAuthType]){if(env[envVar]){resolvedModel=env[envVar];sourceEnvVar=envVar;break}}}const authType=selectedAuthType&&resolvedModel!==void 0?resolveModelSelectionAuthType(selectedAuthType,resolvedModel,settings.modelProviders,settings.providerProtocol,resolvedFromSettings?settings.model?.baseUrl:void 0):selectedAuthType;let modelProvider;let disambiguationWarning;if(resolvedModel&&authType&&settings.modelProviders){const providers=collectProviderModelsForProtocol(settings.modelProviders,settings.providerProtocol,authType);if(providers.length>0){const persistedBaseUrl=settings.model?.baseUrl;if(resolvedFromSettings&&persistedBaseUrl){const exactMatch=providers.find(p=>p.id===resolvedModel&&p.baseUrl===persistedBaseUrl);modelProvider=exactMatch??providers.find(p=>p.id===resolvedModel);if(!exactMatch&&modelProvider){const fallbackBaseUrl=modelProvider.baseUrl===void 0?"(default baseUrl)":sanitizeProviderBaseUrl(modelProvider.baseUrl);disambiguationWarning=`Persisted model.baseUrl '${sanitizeProviderBaseUrl(persistedBaseUrl)}' no longer matches any provider for model '${resolvedModel}' (authType '${authType}'); using the first id match ('${fallbackBaseUrl}'). Re-select the model to update it.`}}else{modelProvider=providers.find(p=>p.id===resolvedModel)}}}const allModelEnvVars=Object.values(AUTH_ENV_MODEL_VARS).flat();const filteredEnv={...env};if(sourceEnvVar){for(const envVar of allModelEnvVars){if(envVar!==sourceEnvVar){delete filteredEnv[envVar]}}}else{for(const envVar of allModelEnvVars){delete filteredEnv[envVar]}}const configSources={authType,cli:{model:argv.model,apiKey:argv.openaiApiKey,baseUrl:argv.openaiBaseUrl},settings:{model:settings.model?.name?stripRuntimeSnapshotPrefix(settings.model.name):void 0,apiKey:settings.security?.auth?.apiKey,baseUrl:settings.security?.auth?.baseUrl,generationConfig:settings.model?.generationConfig},modelProvider,env:filteredEnv};const resolved=resolveModelConfig(configSources);const ignoredGenerationConfigWarning=authType&&modelProvider?buildIgnoredTopLevelGenerationConfigWarning(findProviderIdForModel(settings.modelProviders,settings.providerProtocol,authType,modelProvider)??authType,modelProvider,getIgnoredTopLevelGenerationConfigFields(settings.model?.generationConfig,modelProvider)):void 0;const enableOpenAILogging=(typeof argv.openaiLogging==="undefined"?settings.model?.enableOpenAILogging:argv.openaiLogging)??false;const openAILoggingDir=argv.openaiLoggingDir||settings.model?.openAILoggingDir;const generationConfig={...resolved.config,enableOpenAILogging,openAILoggingDir};const rawReasoningEffort=settings.model?.reasoningEffort;const reasoningDisabled=rawReasoningEffort==="none";const reasoningEffort=reasoningDisabled?void 0:normalizeReasoningEffort(rawReasoningEffort);const invalidReasoningEffortWarning=rawReasoningEffort&&!reasoningDisabled&&!reasoningEffort?`Ignoring invalid model.reasoningEffort "${rawReasoningEffort}"; expected one of: none, ${REASONING_EFFORT_TIERS.join(", ")}.`:void 0;if(reasoningDisabled&&generationConfig.thinkingMandatory!==true){generationConfig.reasoning=false;if(getBuiltinDeepSeekReasoning({...generationConfig,authType})){resolved.sources["reasoning"]={kind:"settings",settingsPath:"model.reasoningEffort"}}}else if(reasoningEffort&&generationConfig.reasoning!==false){generationConfig.reasoning={...generationConfig.reasoning??{},effort:reasoningEffort}}return{authType,model:resolved.config.model||"",apiKey:resolved.config.apiKey||"",baseUrl:resolved.config.baseUrl||"",generationConfig,...modelProvider?{registryBaseUrl:modelProvider.baseUrl??null}:{},sources:resolved.sources,warnings:[...resolved.warnings,...invalidReasoningEffortWarning?[invalidReasoningEffortWarning]:[],...disambiguationWarning?[disambiguationWarning]:[],...ignoredGenerationConfigWarning?[ignoredGenerationConfigWarning]:[],...buildSkippedProviderWarnings(settings.modelProviders,settings.providerProtocol)]}}__name(resolveCliGenerationConfig,"resolveCliGenerationConfig");export{collectProviderModelsForProtocol,getAuthTypeFromEnv,resolveCliGenerationConfig};
3
+ import{sanitizeProviderBaseUrl}from"./chunk-GT4TCQ3R.js";import{resolveModelConfig}from"./chunk-LZNBHBAJ.js";import{getBuiltinDeepSeekReasoning,resolveModelSelectionAuthType,resolveProviderProtocol,stripRuntimeSnapshotPrefix,tryResolveModelProtocol}from"./chunk-BDQOLT37.js";import{MODEL_GENERATION_CONFIG_FIELDS}from"./chunk-DZ3GV34J.js";import{REASONING_EFFORT_TIERS,normalizeReasoningEffort}from"./chunk-HEDN54OB.js";import{AuthType}from"./chunk-ZZZAYAJW.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var AUTH_ENV_MODEL_VARS={["openai"]:["OPENAI_MODEL","QWEN_MODEL"],["openai-responses"]:["OPENAI_MODEL"],["gemini"]:["GEMINI_MODEL"],["vertex-ai"]:["GOOGLE_MODEL"],["anthropic"]:["ANTHROPIC_MODEL"],["qwen-oauth"]:[]};function collectProviderModelsForProtocol(modelProviders,providerProtocol,protocol){if(!modelProviders){return[]}const out=[];for(const[providerId,models]of Object.entries(modelProviders)){if(!Array.isArray(models)){continue}out.push(...models.filter(model=>tryResolveModelProtocol(providerId,model,providerProtocol)===protocol))}return out}__name(collectProviderModelsForProtocol,"collectProviderModelsForProtocol");function findProviderIdForModel(modelProviders,providerProtocol,protocol,modelProvider){if(!modelProviders||!modelProvider){return void 0}for(const[providerId,models]of Object.entries(modelProviders)){if(!Array.isArray(models)){continue}if(models.includes(modelProvider)&&tryResolveModelProtocol(providerId,modelProvider,providerProtocol)===protocol){return providerId}}return void 0}__name(findProviderIdForModel,"findProviderIdForModel");function buildSkippedProviderWarnings(modelProviders,providerProtocol){if(!modelProviders){return[]}const warnings=[];const known=Object.values(AuthType).filter(value=>value!=="openai-responses").join(", ");for(const[providerId,models]of Object.entries(modelProviders)){if(!Array.isArray(models)||models.length===0){continue}const protocol=resolveProviderProtocol(providerId,providerProtocol);if(protocol==="qwen-oauth"&&providerId!=="qwen-oauth"){warnings.push(`Warning: modelProviders provider "${providerId}" maps to "qwen-oauth" via providerProtocol, but qwen-oauth uses hard-coded models only; its ${models.length} model(s) are ignored.`);continue}if(protocol!==void 0){continue}const mapped=providerProtocol&&Object.hasOwn(providerProtocol,providerId)?providerProtocol[providerId]:void 0;warnings.push(mapped!==void 0?`Warning: providerProtocol["${providerId}"] = "${mapped}" is not a known protocol (expected one of: ${known}); its ${models.length} model(s) are ignored.`:`Warning: modelProviders provider "${providerId}" is not a built-in protocol (${known}) and has no providerProtocol mapping; its ${models.length} model(s) are ignored. Add providerProtocol["${providerId}"] (e.g. "openai") to enable them.`)}return warnings}__name(buildSkippedProviderWarnings,"buildSkippedProviderWarnings");function getIgnoredTopLevelGenerationConfigFields(settingsGenerationConfig,modelProvider){if(!settingsGenerationConfig||!modelProvider){return[]}const providerGenerationConfig=modelProvider.generationConfig??{};return MODEL_GENERATION_CONFIG_FIELDS.filter(field=>Object.hasOwn(settingsGenerationConfig,field)&&!Object.hasOwn(providerGenerationConfig,field))}__name(getIgnoredTopLevelGenerationConfigFields,"getIgnoredTopLevelGenerationConfigFields");function buildIgnoredTopLevelGenerationConfigWarning(providerId,modelProvider,ignoredFields){if(ignoredFields.length===0){return void 0}const fieldList=ignoredFields.map(field=>`model.generationConfig.${field}`).join(", ");const isSingular=ignoredFields.length===1;const verb=isSingular?"is":"are";const fieldReference=isSingular?"this field":"these fields";const pronoun=isSingular?"it":"them";return`Warning: ${fieldList} ${verb} ignored for provider model "${modelProvider.id}" from modelProviders.${providerId}. Move ${fieldReference} to modelProviders.${providerId}[].generationConfig for that model if you want ${pronoun} to apply.`}__name(buildIgnoredTopLevelGenerationConfigWarning,"buildIgnoredTopLevelGenerationConfigWarning");function getAuthTypeFromEnv(env=process.env){if(env["QWEN_OAUTH"]){return"qwen-oauth"}if(env["OPENAI_API_KEY"]&&(env["OPENAI_MODEL"]||env["QWEN_MODEL"])&&env["OPENAI_BASE_URL"]){return"openai"}if(env["GEMINI_API_KEY"]&&env["GEMINI_MODEL"]){return"gemini"}if(env["GOOGLE_API_KEY"]&&env["GOOGLE_MODEL"]){return"vertex-ai"}if(env["GOOGLE_CLOUD_PROJECT"]&&env["GOOGLE_MODEL"]){return"vertex-ai"}if(env["ANTHROPIC_API_KEY"]&&env["ANTHROPIC_MODEL"]&&env["ANTHROPIC_BASE_URL"]){return"anthropic"}return void 0}__name(getAuthTypeFromEnv,"getAuthTypeFromEnv");function resolveCliGenerationConfig(inputs){const{argv,settings,selectedAuthType}=inputs;const env=inputs.env??process.env;let resolvedModel;let sourceEnvVar;let resolvedFromSettings=false;if(argv.model){resolvedModel=argv.model}else if(settings.model?.name){resolvedModel=stripRuntimeSnapshotPrefix(settings.model.name);resolvedFromSettings=true}else if(selectedAuthType&&AUTH_ENV_MODEL_VARS[selectedAuthType]){for(const envVar of AUTH_ENV_MODEL_VARS[selectedAuthType]){if(env[envVar]){resolvedModel=env[envVar];sourceEnvVar=envVar;break}}}const authType=selectedAuthType&&resolvedModel!==void 0?resolveModelSelectionAuthType(selectedAuthType,resolvedModel,settings.modelProviders,settings.providerProtocol,resolvedFromSettings?settings.model?.baseUrl:void 0):selectedAuthType;let modelProvider;let disambiguationWarning;if(resolvedModel&&authType&&settings.modelProviders){const providers=collectProviderModelsForProtocol(settings.modelProviders,settings.providerProtocol,authType);if(providers.length>0){const persistedBaseUrl=settings.model?.baseUrl;if(resolvedFromSettings&&persistedBaseUrl){const exactMatch=providers.find(p=>p.id===resolvedModel&&p.baseUrl===persistedBaseUrl);modelProvider=exactMatch??providers.find(p=>p.id===resolvedModel);if(!exactMatch&&modelProvider){const fallbackBaseUrl=modelProvider.baseUrl===void 0?"(default baseUrl)":sanitizeProviderBaseUrl(modelProvider.baseUrl);disambiguationWarning=`Persisted model.baseUrl '${sanitizeProviderBaseUrl(persistedBaseUrl)}' no longer matches any provider for model '${resolvedModel}' (authType '${authType}'); using the first id match ('${fallbackBaseUrl}'). Re-select the model to update it.`}}else{modelProvider=providers.find(p=>p.id===resolvedModel)}}}const allModelEnvVars=Object.values(AUTH_ENV_MODEL_VARS).flat();const filteredEnv={...env};if(sourceEnvVar){for(const envVar of allModelEnvVars){if(envVar!==sourceEnvVar){delete filteredEnv[envVar]}}}else{for(const envVar of allModelEnvVars){delete filteredEnv[envVar]}}const configSources={authType,cli:{model:argv.model,apiKey:argv.openaiApiKey,baseUrl:argv.openaiBaseUrl},settings:{model:settings.model?.name?stripRuntimeSnapshotPrefix(settings.model.name):void 0,apiKey:settings.security?.auth?.apiKey,baseUrl:settings.security?.auth?.baseUrl,generationConfig:settings.model?.generationConfig},modelProvider,env:filteredEnv};const resolved=resolveModelConfig(configSources);const ignoredGenerationConfigWarning=authType&&modelProvider?buildIgnoredTopLevelGenerationConfigWarning(findProviderIdForModel(settings.modelProviders,settings.providerProtocol,authType,modelProvider)??authType,modelProvider,getIgnoredTopLevelGenerationConfigFields(settings.model?.generationConfig,modelProvider)):void 0;const enableOpenAILogging=(typeof argv.openaiLogging==="undefined"?settings.model?.enableOpenAILogging:argv.openaiLogging)??false;const openAILoggingDir=argv.openaiLoggingDir||settings.model?.openAILoggingDir;const generationConfig={...resolved.config,enableOpenAILogging,openAILoggingDir};const rawReasoningEffort=settings.model?.reasoningEffort;const reasoningDisabled=rawReasoningEffort==="none";const reasoningEffort=reasoningDisabled?void 0:normalizeReasoningEffort(rawReasoningEffort);const invalidReasoningEffortWarning=rawReasoningEffort&&!reasoningDisabled&&!reasoningEffort?`Ignoring invalid model.reasoningEffort "${rawReasoningEffort}"; expected one of: none, ${REASONING_EFFORT_TIERS.join(", ")}.`:void 0;if(reasoningDisabled&&generationConfig.thinkingMandatory!==true){generationConfig.reasoning=false;if(getBuiltinDeepSeekReasoning({...generationConfig,authType})){resolved.sources["reasoning"]={kind:"settings",settingsPath:"model.reasoningEffort"}}}else if(reasoningEffort&&generationConfig.reasoning!==false){generationConfig.reasoning={...generationConfig.reasoning??{},effort:reasoningEffort}}return{authType,model:resolved.config.model||"",apiKey:resolved.config.apiKey||"",baseUrl:resolved.config.baseUrl||"",generationConfig,...modelProvider?{registryBaseUrl:modelProvider.baseUrl??null}:{},sources:resolved.sources,warnings:[...resolved.warnings,...invalidReasoningEffortWarning?[invalidReasoningEffortWarning]:[],...disambiguationWarning?[disambiguationWarning]:[],...ignoredGenerationConfigWarning?[ignoredGenerationConfigWarning]:[],...buildSkippedProviderWarnings(settings.modelProviders,settings.providerProtocol)]}}__name(resolveCliGenerationConfig,"resolveCliGenerationConfig");export{collectProviderModelsForProtocol,getAuthTypeFromEnv,resolveCliGenerationConfig};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{LEASE_PREFIX,REVIEW_TMP_DIR,inertPath,reviewBranch,reviewTrustStateDir}from"./chunk-2ZTRKK2O.js";import{writeStderrLineSafe}from"./chunk-SLPJ4OII.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync}from"node:child_process";import{randomBytes}from"node:crypto";import{existsSync,lstatSync,mkdirSync,readFileSync,readdirSync,renameSync,rmdirSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,relative,resolve}from"node:path";var GIT_TIMEOUT_MS=12e4;var debugLogger=createDebugLogger("REVIEW_WORKTREE_LEASE");function gitOptions(timeout){return{stdio:"ignore",timeout,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}}__name(gitOptions,"gitOptions");function validTarget(target){return/^pr-\d+$/.test(target)}__name(validTarget,"validTarget");function isReviewLeaseFile(fileName){if(!fileName.startsWith(LEASE_PREFIX)||!fileName.endsWith(".json")){return false}const target=fileName.slice(LEASE_PREFIX.length,fileName.length-".json".length);return validTarget(target)}__name(isReviewLeaseFile,"isReviewLeaseFile");function leaseDirectory(repositoryRoot){return reviewTrustStateDir(repositoryRoot)}__name(leaseDirectory,"leaseDirectory");function legacyLeasePath(repositoryRoot,target){return join(repositoryRoot,REVIEW_TMP_DIR,`${LEASE_PREFIX}${target}.json`)}__name(legacyLeasePath,"legacyLeasePath");function leasePath(repositoryRoot,target){return join(leaseDirectory(repositoryRoot),`${LEASE_PREFIX}${target}.json`)}__name(leasePath,"leasePath");function clearReviewWorktreeLease(repositoryRoot,target){if(!validTarget(target))return;const root=resolve(repositoryRoot);rmSync(leasePath(root,target),{force:true});reclaimBaseTreeTrust(root,target);const legacy=legacyLeasePath(root,target);try{rmSync(legacy,{force:true,recursive:true})}catch(error){writeStderrLineSafe(`warning: could not remove the pre-move review lease at ${legacy} (${error.code??error}); the trusted lease for ${target} is released, but a build from before the lease move will keep seeing this one until it is deleted by hand.`)}}__name(clearReviewWorktreeLease,"clearReviewWorktreeLease");function clearReviewWorktreeLeaseIfOwned(repositoryRoot,target,owner){const lease=readReviewWorktreeLease(repositoryRoot,target);if(!lease||lease.sessionId!==owner.sessionId||lease.promptId!==owner.promptId){return}clearReviewWorktreeLease(repositoryRoot,target)}__name(clearReviewWorktreeLeaseIfOwned,"clearReviewWorktreeLeaseIfOwned");function mintIdentity(){return Math.floor(Date.now()/1e3)*2**20+randomBytes(3).readUIntBE(0,3)%2**20}__name(mintIdentity,"mintIdentity");function recordReviewWorktreeLeaseMergeBase(repositoryRoot,target,mergeBaseSha,sessionId,options={}){if(!validTarget(target)||!mergeBaseSha)return;const stale=options.stale===true;const root=resolve(repositoryRoot);const path=leasePath(root,target);const existing=readLease(path);if(!existing)return;if(sessionId!==void 0&&existing.sessionId!==sessionId)return;if(existing.mergeBaseSha===mergeBaseSha&&existing.mergeBaseStale===true===stale){return}const previous=existing.mergeBaseSha??existing.priorMergeBaseSha;const next={...existing,mergeBaseSha,mergeBaseStale:stale,priorMergeBaseSha:mergeBaseSha,priorMergeBaseStale:stale,priorMergeBaseCurrent:true,identity:previous===void 0||previous===mergeBaseSha?existing.identity??mintIdentity():mintIdentity()};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
3
+ import{LEASE_PREFIX,REVIEW_TMP_DIR,inertPath,reviewBranch,reviewTrustStateDir}from"./chunk-INFBJDWM.js";import{writeStderrLineSafe}from"./chunk-SLPJ4OII.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync}from"node:child_process";import{randomBytes}from"node:crypto";import{existsSync,lstatSync,mkdirSync,readFileSync,readdirSync,renameSync,rmdirSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,relative,resolve}from"node:path";var GIT_TIMEOUT_MS=12e4;var debugLogger=createDebugLogger("REVIEW_WORKTREE_LEASE");function gitOptions(timeout){return{stdio:"ignore",timeout,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}}__name(gitOptions,"gitOptions");function validTarget(target){return/^pr-\d+$/.test(target)}__name(validTarget,"validTarget");function isReviewLeaseFile(fileName){if(!fileName.startsWith(LEASE_PREFIX)||!fileName.endsWith(".json")){return false}const target=fileName.slice(LEASE_PREFIX.length,fileName.length-".json".length);return validTarget(target)}__name(isReviewLeaseFile,"isReviewLeaseFile");function leaseDirectory(repositoryRoot){return reviewTrustStateDir(repositoryRoot)}__name(leaseDirectory,"leaseDirectory");function legacyLeasePath(repositoryRoot,target){return join(repositoryRoot,REVIEW_TMP_DIR,`${LEASE_PREFIX}${target}.json`)}__name(legacyLeasePath,"legacyLeasePath");function leasePath(repositoryRoot,target){return join(leaseDirectory(repositoryRoot),`${LEASE_PREFIX}${target}.json`)}__name(leasePath,"leasePath");function clearReviewWorktreeLease(repositoryRoot,target){if(!validTarget(target))return;const root=resolve(repositoryRoot);rmSync(leasePath(root,target),{force:true});reclaimBaseTreeTrust(root,target);const legacy=legacyLeasePath(root,target);try{rmSync(legacy,{force:true,recursive:true})}catch(error){writeStderrLineSafe(`warning: could not remove the pre-move review lease at ${legacy} (${error.code??error}); the trusted lease for ${target} is released, but a build from before the lease move will keep seeing this one until it is deleted by hand.`)}}__name(clearReviewWorktreeLease,"clearReviewWorktreeLease");function clearReviewWorktreeLeaseIfOwned(repositoryRoot,target,owner){const lease=readReviewWorktreeLease(repositoryRoot,target);if(!lease||lease.sessionId!==owner.sessionId||lease.promptId!==owner.promptId){return}clearReviewWorktreeLease(repositoryRoot,target)}__name(clearReviewWorktreeLeaseIfOwned,"clearReviewWorktreeLeaseIfOwned");function mintIdentity(){return Math.floor(Date.now()/1e3)*2**20+randomBytes(3).readUIntBE(0,3)%2**20}__name(mintIdentity,"mintIdentity");function recordReviewWorktreeLeaseMergeBase(repositoryRoot,target,mergeBaseSha,sessionId,options={}){if(!validTarget(target)||!mergeBaseSha)return;const stale=options.stale===true;const root=resolve(repositoryRoot);const path=leasePath(root,target);const existing=readLease(path);if(!existing)return;if(sessionId!==void 0&&existing.sessionId!==sessionId)return;if(existing.mergeBaseSha===mergeBaseSha&&existing.mergeBaseStale===true===stale){return}const previous=existing.mergeBaseSha??existing.priorMergeBaseSha;const next={...existing,mergeBaseSha,mergeBaseStale:stale,priorMergeBaseSha:mergeBaseSha,priorMergeBaseStale:stale,priorMergeBaseCurrent:true,identity:previous===void 0||previous===mergeBaseSha?existing.identity??mintIdentity():mintIdentity()};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
4
4
  `)}catch(error){debugLogger.debug(`Failed to record the merge base in ${path}:`,error)}}__name(recordReviewWorktreeLeaseMergeBase,"recordReviewWorktreeLeaseMergeBase");function atomicWriteLease(path,data){const tmp=`${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{writeFileSync(tmp,data,{encoding:"utf8",flag:"wx"});renameSync(tmp,path)}catch(error){try{rmSync(tmp,{force:true})}catch{}throw error}}__name(atomicWriteLease,"atomicWriteLease");function reclaimBaseTreeTrust(root,target){const dir=join(leaseDirectory(root),"base-tree",target);let entries;try{entries=readdirSync(dir)}catch(error){if(error.code!=="ENOENT"){debugLogger.debug(`Failed to reclaim base-tree trust state for ${target}:`,error)}return}for(const name of entries){if(name.endsWith(".lock"))continue;try{rmSync(join(dir,name),{recursive:true,force:true})}catch(error){debugLogger.debug(`Failed to reclaim base-tree trust state ${name} for ${target}:`,error)}}try{rmdirSync(dir)}catch{}}__name(reclaimBaseTreeTrust,"reclaimBaseTreeTrust");function restoreReviewWorktreeLeaseMergeBase(repositoryRoot,target,sessionId){if(!validTarget(target)||!sessionId)return;const path=leasePath(resolve(repositoryRoot),target);const existing=readLease(path);if(!existing||existing.sessionId!==sessionId)return;if(existing.mergeBaseSha!==void 0)return;if(existing.priorMergeBaseResumable!==true)return;const next={...existing,mergeBaseSha:existing.priorMergeBaseSha,mergeBaseStale:existing.priorMergeBaseStale===true,priorMergeBaseCurrent:true};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
5
5
  `)}catch(error){debugLogger.debug(`Failed to restore the merge base in ${path}:`,error)}}__name(restoreReviewWorktreeLeaseMergeBase,"restoreReviewWorktreeLeaseMergeBase");function createReviewWorktreeLease(params){if(!params.sessionId||!params.promptId||!validTarget(params.target)){return}const repositoryRoot=resolve(params.repositoryRoot);const path=leasePath(repositoryRoot,params.target);const leaseFor=__name((identity,prior)=>{const lease={sessionId:params.sessionId,promptId:params.promptId,target:params.target,repositoryRoot,worktreePath:resolve(repositoryRoot,params.worktreePath),branch:params.branch,identity,...prior===void 0?{}:{priorMergeBaseSha:prior.sha,priorMergeBaseStale:prior.stale,priorMergeBaseResumable:prior.resumable}};return`${JSON.stringify(lease,null,2)}
6
6
  `},"leaseFor");let data=leaseFor(mintIdentity());mkdirSync(leaseDirectory(repositoryRoot),{recursive:true,mode:448});const legacy=legacyLeasePath(repositoryRoot,params.target);try{writeFileSync(path,data,{encoding:"utf8",flag:"wx"})}catch(error){if(error.code!=="EEXIST")throw error;const existing=readLease(path);if(existing&&existing.sessionId!==params.sessionId){throw new Error(`review worktree lease for ${params.target} is held by another session (session ${existing.sessionId}) at ${path}; it was acquired between the gate read and the lease write \u2014 retry`)}if(existing){data=leaseFor(typeof existing.identity==="number"&&Number.isFinite(existing.identity)?existing.identity:mintIdentity(),existing.mergeBaseSha!==void 0?{sha:existing.mergeBaseSha,stale:existing.mergeBaseStale===true,resumable:existing.priorMergeBaseCurrent===true}:existing.priorMergeBaseSha!==void 0?{sha:existing.priorMergeBaseSha,stale:existing.priorMergeBaseStale===true,resumable:existing.priorMergeBaseCurrent===true}:void 0)}atomicWriteLease(path,data)}mirrorLeaseAtLegacyPath(legacy,data,params.sessionId,params.target)}__name(createReviewWorktreeLease,"createReviewWorktreeLease");function mirrorLeaseAtLegacyPath(legacy,data,sessionId,target){try{mkdirSync(dirname(legacy),{recursive:true});writeFileSync(legacy,data,{encoding:"utf8",flag:"wx"});return}catch(error){if(error.code!=="EEXIST"){warnMirrorSkipped(legacy,error);return}}const displaced=readLease(legacy);const tmp=`${legacy}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{writeFileSync(tmp,data,{encoding:"utf8",flag:"wx"});renameSync(tmp,legacy)}catch(error){try{rmSync(tmp,{force:true})}catch{}warnMirrorSkipped(legacy,error);return}if(displaced&&displaced.sessionId!==sessionId){writeStderrLineSafe(`warning: replaced the pre-move review lease for ${target} at ${legacy} (recorded session ${inertSessionId(displaced.sessionId)}) \u2014 if a pre-move build is still reviewing ${target} on this machine, its worktree is no longer protected; otherwise this was residue or a plant, and it is gone.`)}}__name(mirrorLeaseAtLegacyPath,"mirrorLeaseAtLegacyPath");function inertSessionId(id){const inert=inertPath(id);return inert.length>120?`${inert.slice(0,120)}\u2026`:inert}__name(inertSessionId,"inertSessionId");function warnMirrorSkipped(legacy,error){writeStderrLineSafe(`warning: could not mirror the review worktree lease to the pre-move path ${legacy} (${error.code??error}); the acquisition stands on the new-path lease, but builds from before the lease move will not see this lock.`)}__name(warnMirrorSkipped,"warnMirrorSkipped");function readLease(path){try{if(!lstatSync(path).isFile()){rmSync(path,{force:true,recursive:true});return null}}catch(error){if(error.code!=="ENOENT"){debugLogger.debug(`Failed to inspect review lease ${path}:`,error)}return null}try{const value=JSON.parse(readFileSync(path,"utf8"));if(typeof value.sessionId!=="string"||typeof value.promptId!=="string"||typeof value.target!=="string"||typeof value.repositoryRoot!=="string"||typeof value.worktreePath!=="string"||typeof value.branch!=="string"||value.identity!==void 0&&(typeof value.identity!=="number"||!Number.isFinite(value.identity))||value.mergeBaseSha!==void 0&&typeof value.mergeBaseSha!=="string"||value.priorMergeBaseSha!==void 0&&typeof value.priorMergeBaseSha!=="string"||value.mergeBaseStale!==void 0&&typeof value.mergeBaseStale!=="boolean"||value.priorMergeBaseStale!==void 0&&typeof value.priorMergeBaseStale!=="boolean"||value.priorMergeBaseCurrent!==void 0&&typeof value.priorMergeBaseCurrent!=="boolean"||value.priorMergeBaseResumable!==void 0&&typeof value.priorMergeBaseResumable!=="boolean"){return null}return value}catch(error){debugLogger.debug(`Failed to read review lease ${path}:`,error);return null}}__name(readLease,"readLease");function readReviewWorktreeLease(repositoryRoot,target){return readReviewWorktreeLeaseAt(repositoryRoot,target)?.lease??null}__name(readReviewWorktreeLease,"readReviewWorktreeLease");function readReviewWorktreeLeaseAt(repositoryRoot,target){if(!validTarget(target))return null;const root=resolve(repositoryRoot);const current=leasePath(root,target);const lease=readLease(current);return lease?{lease,path:current}:null}__name(readReviewWorktreeLeaseAt,"readReviewWorktreeLeaseAt");function reviewLeaseHeldByAnotherSession(lease){if(!lease)return false;const sessionId=process.env["QWEN_CODE_SESSION_ID"]?.trim();return!sessionId||lease.sessionId!==sessionId}__name(reviewLeaseHeldByAnotherSession,"reviewLeaseHeldByAnotherSession");function sameLease(a,b){return b!==null&&a.sessionId===b.sessionId&&a.promptId===b.promptId&&a.target===b.target&&a.repositoryRoot===b.repositoryRoot&&a.worktreePath===b.worktreePath&&a.branch===b.branch}__name(sameLease,"sameLease");function removeLeaseWorktree(lease,gitTimeout){const prMatch=/^pr-(\d+)$/.exec(lease.target);if(!prMatch||lease.branch!==reviewBranch(prMatch[1])){debugLogger.debug(`Rejected invalid review lease ${lease.target}`);return false}const repositoryRoot=resolve(lease.repositoryRoot);const worktreePath=resolve(lease.worktreePath);const reviewTmpRoot=resolve(repositoryRoot,REVIEW_TMP_DIR);const worktreeRelative=relative(reviewTmpRoot,worktreePath);if(worktreeRelative===""||worktreeRelative.startsWith("..")||isAbsolute(worktreeRelative)){debugLogger.debug(`Rejected review lease outside ${REVIEW_TMP_DIR}: ${worktreePath}`);return false}try{execFileSync("git",["-C",repositoryRoot,"worktree","remove",worktreePath,"--force"],gitOptions(gitTimeout))}catch(error){debugLogger.debug(`Git failed to remove review worktree ${lease.target}:`,error);try{rmSync(worktreePath,{recursive:true,force:true});execFileSync("git",["-C",repositoryRoot,"worktree","prune"],gitOptions(gitTimeout))}catch(fallbackError){debugLogger.debug(`Fallback failed to remove review worktree ${lease.target}:`,fallbackError);return false}}let branchExists=true;try{execFileSync("git",["-C",repositoryRoot,"show-ref","--verify","--quiet",`refs/heads/${lease.branch}`],gitOptions(gitTimeout))}catch(error){if(error.status!==1){debugLogger.debug(`Failed to inspect review branch ${lease.branch}:`,error);return false}branchExists=false}if(branchExists){try{execFileSync("git",["-C",repositoryRoot,"branch","-D",lease.branch],gitOptions(gitTimeout))}catch(error){debugLogger.debug(`Failed to delete review branch ${lease.branch}:`,error);return false}}return!existsSync(worktreePath)}__name(removeLeaseWorktree,"removeLeaseWorktree");function cleanupReviewWorktreeLeases(params){try{const repositoryRoot=resolve(params.repositoryRoot);const newLeaseDirectory=leaseDirectory(repositoryRoot);if(!existsSync(newLeaseDirectory))return;let entries;try{entries=readdirSync(newLeaseDirectory)}catch(error){debugLogger.debug(`Failed to list ${newLeaseDirectory} for lease cleanup:`,error);return}for(const entry of entries){if(!isReviewLeaseFile(entry))continue;const path=join(newLeaseDirectory,basename(entry));const lease=readLease(path);if(!lease||lease.sessionId!==params.sessionId||lease.promptId!==params.promptId||resolve(lease.repositoryRoot)!==repositoryRoot){continue}if(!removeLeaseWorktree(lease,params.gitTimeout??GIT_TIMEOUT_MS)){continue}rmSync(path,{force:true});reclaimBaseTreeTrust(repositoryRoot,lease.target);const twin=join(repositoryRoot,REVIEW_TMP_DIR,basename(entry));try{if(sameLease(lease,readLease(twin))){rmSync(twin,{force:true})}}catch(error){debugLogger.debug(`Failed to remove legacy lease twin ${twin}:`,error)}}}catch(error){debugLogger.debug("Failed to clean up review worktree leases:",error)}}__name(cleanupReviewWorktreeLeases,"cleanupReviewWorktreeLeases");export{isReviewLeaseFile,clearReviewWorktreeLease,clearReviewWorktreeLeaseIfOwned,recordReviewWorktreeLeaseMergeBase,restoreReviewWorktreeLeaseMergeBase,createReviewWorktreeLease,readReviewWorktreeLease,readReviewWorktreeLeaseAt,reviewLeaseHeldByAnotherSession,cleanupReviewWorktreeLeases};