@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{DashScopeUploader}from"./chunk-RKDS7A4H.js";import{OmniDegradationCache,OmniTransportGuardError,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveMaxUploadFileBytes,effectiveOmniStorageMaxTotalBytes,estimateRawResourceTokens,runFixedPolicies,runOmniGcOnce}from"./chunk-SXJ2E33J.js";import{MEDIA_DETECTOR_VERSION,MediaMemoryService}from"./chunk-UYYQB2TU.js";import{runStartupRecoveryOnce}from"./chunk-HN5UYLPU.js";import{OmniObjectStore,prepareOmniDownloadsDir}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile,sniffMediaType}from"./chunk-ZBHL2CXR.js";import{isFfmpegAvailable,isFfprobeAvailable}from"./chunk-NIOS3B3V.js";import{isOmniDeliveryActive}from"./chunk-EL5J4ESB.js";import{requireEffectiveOmniUploadConfig}from"./chunk-PV2VT25U.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX,formatDisclosureText,formatOmissionText,formatResourceHandleText,formatTranscriptText,harnessPathAnnotationPart,isHarnessAnnotationPart,parseResourceHandleText,parseResourcePathText,splitAnnotationBody,unescapeAnnotationName}from"./chunk-SW54YEPK.js";import{isPermittedRedirect,isPrivateHost,resolveNetworkTarget}from"./chunk-OZGM5CCE.js";import{ImageViewError,boundImageBuffer,sniffBoundableImageMime}from"./chunk-Z6AR5XE5.js";import{TOOL_RESULT_MEDIA_REMEDY,clampInlineMediaPart,getMaxInlineMediaBytes}from"./chunk-Q6UAOTP3.js";import{detectRuntime,loadUndici}from"./chunk-ZZZAYAJW.js";import{DEFAULT_UPLOAD_CACHE_TTL_HOURS,OmniUploadCache}from"./chunk-HTW7PYHK.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{isAbortError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import path4 from"node:path";import fs4 from"node:fs/promises";init_esbuild_shims();function buildSessionConditionNamespace(config,reservedOutputTokens){const session={reservedOutputTokens};const windowSize=config.getContentGeneratorConfig?.()?.contextWindowSize;const contextWindowTokens=typeof windowSize==="number"&&Number.isFinite(windowSize)&&windowSize>0?windowSize:void 0;if(contextWindowTokens!==void 0){session.contextWindowTokens=contextWindowTokens}let promptTokenCount;try{const count=config.getGeminiClient?.()?.getChat?.()?.getLastPromptTokenCount();if(typeof count==="number"&&Number.isFinite(count)&&count>=0){promptTokenCount=count}}catch{}if(promptTokenCount!==void 0){session.promptTokenCount=promptTokenCount}if(contextWindowTokens!==void 0&&promptTokenCount!==void 0){session.availableContextTokens=Math.max(0,contextWindowTokens-promptTokenCount-reservedOutputTokens)}return session}__name(buildSessionConditionNamespace,"buildSessionConditionNamespace");init_esbuild_shims();import{randomBytes}from"node:crypto";import{once}from"node:events";import{createWriteStream}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var debugLogger=createDebugLogger("omni:download");var OmniDownloadError=class extends Error{static{__name(this,"OmniDownloadError")}constructor(message,options){super(message,options);this.name="OmniDownloadError"}};var RESOLVE_TIMEOUT_MS=3e4;var HEADER_TIMEOUT_MS=3e4;var IDLE_TIMEOUT_MS=6e4;var MAX_REDIRECTS=5;function parseHttpUrlRef(pathName){if(!/^https?:\/\//i.test(pathName))return null;try{return new URL(pathName)}catch{return null}}__name(parseHttpUrlRef,"parseHttpUrlRef");function scrubPathsFromMessage(message){return message.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`\\/]+){2,}[\\/]?/g,match=>path.basename(match))}__name(scrubPathsFromMessage,"scrubPathsFromMessage");function formatCauseChain(err){const parts=[];let cause=err instanceof Error?err.cause:void 0;for(let depth=0;cause!=null&&depth<4;depth++){const code=cause.code;const message=cause instanceof Error?cause.message:typeof cause==="string"?cause:void 0;if(typeof code==="string"&&message&&!message.includes(code)){parts.push(`${code}: ${message}`)}else if(message){parts.push(message)}else if(typeof code==="string"){parts.push(code)}cause=cause instanceof Error?cause.cause:void 0}return parts.length>0?scrubPathsFromMessage(parts.join("; ")):void 0}__name(formatCauseChain,"formatCauseChain");function detectConfiguredProxy(undici){for(const key of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY","all_proxy","ALL_PROXY"]){if(process.env[key])return true}try{return undici.getGlobalDispatcher()instanceof undici.EnvHttpProxyAgent}catch{return false}}__name(detectConfiguredProxy,"detectConfiguredProxy");async function downloadMediaUrl(params){const{url,downloadsDir,maxBytes,signal,resolveTimeoutMs=RESOLVE_TIMEOUT_MS,headerTimeoutMs=HEADER_TIMEOUT_MS,idleTimeoutMs=IDLE_TIMEOUT_MS}=params;const resolveTarget=params.resolveTarget??(target=>resolveNetworkTarget(target,"public",signal));if(isPrivateHost(url)){throw new OmniDownloadError(`URL host is not publicly routable (refused for safety): ${new URL(url).hostname}`)}let parsed;try{parsed=new URL(url)}catch{throw new OmniDownloadError("URL media ref is not a valid URL (refused).")}if(parsed.protocol!=="https:"){throw new OmniDownloadError(`URL media must be https (refused for safety): ${parsed.protocol}//${parsed.hostname}`)}if(parsed.username||parsed.password){throw new OmniDownloadError(`URL media must not embed credentials (refused for safety): ${parsed.hostname}`)}const runtime=detectRuntime();if(runtime!=="node"){throw new OmniDownloadError(`URL media requires the Node runtime to verify the connection target (refused for safety on ${runtime}): use a local file path instead of a URL, or run under Node.`)}const undici=await loadUndici();const proxied=params.detectProxy?params.detectProxy():detectConfiguredProxy(undici);if(proxied){throw new OmniDownloadError(`URL media fetching is not supported behind a proxy yet (refused): the connection pinning that enforces SSRF protection cannot be applied through a proxy. Download the file manually and use a local path instead.`)}try{await prepareOmniDownloadsDir(downloadsDir)}catch(err){throw new OmniDownloadError(`Could not prepare the downloads directory for URL media: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}const partPath=path.join(downloadsDir,`${randomBytes(8).toString("hex")}.part`);let currentUrl=url;let dispatcher;try{for(let redirects=0;;redirects++){let target;const resolveAbort=new AbortController;const resolveTimer=setTimeout(()=>resolveAbort.abort(new Error("resolve timeout")),resolveTimeoutMs);try{const pending=resolveTarget(currentUrl);pending.catch(()=>{});target=await Promise.race([pending,new Promise((_,reject)=>{resolveAbort.signal.addEventListener("abort",()=>reject(resolveAbort.signal.reason),{once:true})})])}catch(err){if(signal?.aborted)throw err;if(resolveAbort.signal.aborted){throw new OmniDownloadError(`Download timed out resolving ${new URL(currentUrl).hostname} (${resolveTimeoutMs/1e3}s)`)}const text=err instanceof Error?err.message:String(err);const reason=/blocked address/i.test(text)?"resolved to a non-public address":/did not resolve/i.test(text)?"did not resolve":"could not be verified";throw new OmniDownloadError(`URL host ${reason} (refused for safety): ${new URL(currentUrl).hostname}`,{cause:err})}finally{clearTimeout(resolveTimer)}if(!target.lookup){throw new OmniDownloadError(`URL host cannot be safely bound to a verified address (refused for safety): ${new URL(currentUrl).hostname}`)}const fetchFn=params.fetchFn??undici.fetch;const previousDispatcher=dispatcher;dispatcher=new undici.Agent({connect:{lookup:target.lookup}});await previousDispatcher?.close().catch(()=>{});const headerAbort=new AbortController;const headerTimer=setTimeout(()=>headerAbort.abort(new Error("header timeout")),headerTimeoutMs);const combined=AbortSignal.any(signal?[signal,headerAbort.signal]:[headerAbort.signal]);let res;try{res=await fetchFn(currentUrl,{redirect:"manual",signal:combined,dispatcher})}catch(err){if(signal?.aborted)throw err;if(headerAbort.signal.aborted){throw new OmniDownloadError(`Download timed out waiting for response headers from ${new URL(currentUrl).hostname} (${headerTimeoutMs/1e3}s)`)}const detail=err instanceof Error?scrubPathsFromMessage(err.message):String(err);const causeDetail=formatCauseChain(err);throw new OmniDownloadError(`Download request failed for ${new URL(currentUrl).hostname}: ${detail}${causeDetail?` (${causeDetail})`:""}`,{cause:err})}finally{clearTimeout(headerTimer)}if(res.status>=300&&res.status<400){await res.body?.cancel().catch(()=>{});const location=res.headers.get("location");if(!location||redirects>=MAX_REDIRECTS){throw new OmniDownloadError(`Too many or invalid redirects downloading from ${new URL(currentUrl).hostname}`)}let redirectUrl;try{redirectUrl=new URL(location,currentUrl).toString()}catch{throw new OmniDownloadError(`Redirect with a malformed Location header from ${new URL(currentUrl).hostname}`)}if(!isPermittedRedirect(currentUrl,redirectUrl)){throw new OmniDownloadError(`Cross-origin redirect refused: ${new URL(currentUrl).hostname} \u2192 ${new URL(redirectUrl).hostname}`)}currentUrl=redirectUrl;continue}if(!res.ok){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download failed: HTTP ${res.status} from ${new URL(currentUrl).hostname}`)}const contentLength=Number(res.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>maxBytes){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download exceeds the omni media limit: Content-Length ${contentLength} > ${maxBytes} bytes.`)}if(!res.body){throw new OmniDownloadError("Download response had no body.")}let written=0;const idleAbort=new AbortController;let idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);const streamSignal=AbortSignal.any(signal?[signal,idleAbort.signal]:[idleAbort.signal]);try{const source=Readable.fromWeb(res.body,{signal:streamSignal});const counter=__name(async function*(src){for await(const chunk of src){clearTimeout(idleTimer);idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);written+=chunk.length;if(written>maxBytes){throw new OmniDownloadError(`Download exceeds the omni media limit: >${maxBytes} bytes received.`)}yield chunk}},"counter");const destination=createWriteStream(partPath,{mode:384});await once(destination,"open");await pipeline(source,counter,destination)}catch(err){if(signal?.aborted)throw err;if(err instanceof OmniDownloadError)throw err;if(idleAbort.signal.aborted){throw new OmniDownloadError(`Download stalled from ${new URL(currentUrl).hostname}: no data for ${idleTimeoutMs/1e3}s`)}throw new OmniDownloadError(`Download interrupted from ${new URL(currentUrl).hostname}: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}finally{clearTimeout(idleTimer)}debugLogger.debug(`downloaded ${written} bytes from ${new URL(currentUrl).hostname}`);return{partPath}}}catch(err){await fs.rm(partPath,{force:true});throw err}finally{await dispatcher?.close().catch(()=>{})}}__name(downloadMediaUrl,"downloadMediaUrl");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import fs2 from"node:fs/promises";import path2 from"node:path";var debugLogger2=createDebugLogger("omni:tool-result");var MAX_UPLOADS_PER_TOOL_RESULT=8;var MAX_UPLOAD_BYTES_PER_TOOL_RESULT=128*1024*1024;async function boundDeclinedInlinePart(part,bytes,signal){const inline=part.inlineData;if(!inline?.data)return part;const inlineByteCeiling=getMaxInlineMediaBytes();let boundedPart=part;if(sniffBoundableImageMime(bytes.subarray(0,12))){try{const view=await boundImageBuffer(bytes,`tool-result media (${inline.mimeType??"unknown"})`,signal,inlineByteCeiling);if(view){boundedPart={inlineData:{...inline,data:view.bytes.toString("base64"),mimeType:view.mimeType}}}}catch(error){if(!(error instanceof ImageViewError)){throw error}debugLogger2.debug(`tool-result media kept inline could not be bounded: ${error.message}`)}}return clampInlineMediaPart(boundedPart,inlineByteCeiling,TOOL_RESULT_MEDIA_REMEDY)}__name(boundDeclinedInlinePart,"boundDeclinedInlinePart");async function processToolResultOmniMedia(responseParts,config,signal){if(!isOmniDeliveryActive(config))return responseParts;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};let changed=false;let uploadsRemaining=MAX_UPLOADS_PER_TOOL_RESULT;let uploadBytesRemaining=MAX_UPLOAD_BYTES_PER_TOOL_RESULT;const keepInline=__name(async(part,bytes)=>{const kept=await boundDeclinedInlinePart(part,bytes,signal);if(kept!==part)changed=true;return[kept]},"keepInline");const convertPart=__name(async part=>{const inline=part.inlineData;if(!inline?.data||!inline.mimeType)return[part];const top=inline.mimeType.split("/")[0];if(top!=="image"&&top!=="audio"&&top!=="video")return[part];const bytes=Buffer.from(inline.data,"base64");const sniffed=sniffMediaType(bytes.subarray(0,4096));if(!sniffed)return keepInline(part,bytes);if(!modalities[sniffed.modality]){return keepInline(part,bytes)}if(uploadsRemaining<=0||bytes.length>uploadBytesRemaining){debugLogger2.debug(`tool-result media budget exhausted; keeping part inline (${bytes.length} bytes)`);return keepInline(part,bytes)}const store=new OmniObjectStore(config.storage.getQwenDir());let tempPath;const displayName=inline.displayName??`tool-media.${top}`;try{const stagingDir=await prepareOmniDownloadsDir(path2.join(store.getOmniRootDir(),"downloads"));tempPath=path2.join(stagingDir,`${randomBytes2(8).toString("hex")}.part`);await fs2.writeFile(tempPath,bytes,{mode:384});const delivery=await processMediaForOmniDelivery(tempPath,config,{expectedModality:sniffed.modality,signal,displayName,origin:"tool"});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);uploadsRemaining-=delivery.additionalMedia?.filter(e=>!e.omission).length??0;const handleParts=delivery.resourceId?[{text:formatResourceHandleText(displayName,delivery.resourceId)}]:[];if(delivery.omission){changed=true;return[...handleParts,{text:formatOmissionText(displayName,delivery.omission.reason)},...additionalParts,...transcriptParts]}if(!delivery.fileUri&&transcriptParts.length>0){changed=true;return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},...additionalParts,...transcriptParts]:[...handleParts,...additionalParts,...transcriptParts]}changed=true;uploadsRemaining--;uploadBytesRemaining-=bytes.length;const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},fileDataPart,...additionalParts,...transcriptParts]:[...handleParts,fileDataPart,...additionalParts,...transcriptParts]}catch(err){if(signal.aborted)throw err;if(err instanceof OmniTransportGuardError){changed=true;return[...err.sessionResourceId?[{text:formatResourceHandleText(displayName,err.sessionResourceId)}]:[],{text:`[Tool media part withheld by the omni transport guard: ${err.message}]`}]}debugLogger2.debug(`tool-result media upload failed, keeping inline: ${err instanceof Error?err.message:String(err)}`);return keepInline(part,bytes)}finally{if(tempPath!==void 0){await fs2.rm(tempPath,{force:true}).catch(()=>{})}}},"convertPart");const result=[];for(const part of responseParts){const nested=part.functionResponse?.parts;if(Array.isArray(nested)&&nested.length>0){const convertedNested=[];let nestedChanged=false;for(const nestedPart of nested){const converted=await convertPart(nestedPart);if(converted.length!==1||converted[0]!==nestedPart){nestedChanged=true}convertedNested.push(...converted)}if(nestedChanged){result.push({...part,functionResponse:{...part.functionResponse,parts:convertedNested}});changed=true}else{result.push(part)}continue}result.push(...await convertPart(part))}return changed?result:responseParts}__name(processToolResultOmniMedia,"processToolResultOmniMedia");init_esbuild_shims();import fs3 from"node:fs/promises";import path3 from"node:path";var debugLogger3=createDebugLogger("omni:export");function textOfPart(part){if(typeof part==="string")return part;if(typeof part==="object"&&part!==null&&"text"in part){const text=part.text;return typeof text==="string"?text:void 0}return void 0}__name(textOfPart,"textOfPart");function functionResponseOfPart(part){if(typeof part!=="object"||part===null)return void 0;const response=part.functionResponse;if(typeof response!=="object"||response===null)return void 0;const{id,parts}=response;return{id,...Array.isArray(parts)?{parts}:{}}}__name(functionResponseOfPart,"functionResponseOfPart");function isThoughtPart(part){return typeof part==="object"&&part!==null&&part.thought===true}__name(isThoughtPart,"isThoughtPart");function functionCallOfPart(part){if(typeof part!=="object"||part===null)return void 0;const fc=part.functionCall;if(typeof fc!=="object"||fc===null)return void 0;const{id,name,args}=fc;if(typeof name!=="string")return void 0;const cleanArgs=typeof args==="object"&&args!==null?{...args}:void 0;return{...typeof id==="string"?{callId:id}:{},name,...cleanArgs?{args:cleanArgs}:{}}}__name(functionCallOfPart,"functionCallOfPart");function stripSystemReminders(text){return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"")}__name(stripSystemReminders,"stripSystemReminders");function mediaFor(turn,name){let media=turn.media.get(name);if(!media){media={name,disclosures:[],transcripts:[]};turn.media.set(name,media)}return media}__name(mediaFor,"mediaFor");function consumeAnnotationPart(turn,text,isHarnessAnnotation){if(text.startsWith(OMNI_RESOURCE_HANDLE_TEXT_PREFIX)){const resourceId=parseResourceHandleText(text);if(resourceId){const body=text.slice(OMNI_RESOURCE_HANDLE_TEXT_PREFIX.length);const name=unescapeAnnotationName(body.slice(0,body.length-resourceId.length-1));mediaFor(turn,name).resourceId=resourceId;return true}return false}if(text.startsWith(OMNI_RESOURCE_PATH_TEXT_PREFIX)){if(!isHarnessAnnotation)return false;const filePath=parseResourcePathText(text);if(filePath){mediaFor(turn,filePath.split(/[\\/]/).pop()??filePath);return true}return false}for(const[prefix,apply]of[[OMNI_DISCLOSURE_TEXT_PREFIX,(m,payload)=>{m.disclosures.push(payload)}],[OMNI_OMISSION_TEXT_PREFIX,(m,payload)=>{m.omitted=payload}],[OMNI_TRANSCRIPT_TEXT_PREFIX,(m,payload)=>{m.transcripts.push(payload)}]]){if(!text.startsWith(prefix))continue;const split=splitAnnotationBody(text.slice(prefix.length));if(!split)return false;apply(mediaFor(turn,split.name),split.payload);return true}return false}__name(consumeAnnotationPart,"consumeAnnotationPart");function consumeRecordParts(turn,record,collectProse){const parts=(record.message?.parts??[]).flatMap(part=>[part,...functionResponseOfPart(part)?.parts??[]]);for(const part of parts){const raw=textOfPart(part);if(raw===void 0)continue;const withoutReminders=stripSystemReminders(raw);const forAnnotation=withoutReminders.replace(/^\s+/,"");if(consumeAnnotationPart(turn,forAnnotation,isHarnessAnnotationPart(part)))continue;const prose=withoutReminders.trim();if(!prose)continue;if(collectProse)turn.requestTexts.push(prose)}}__name(consumeRecordParts,"consumeRecordParts");function finishTurn(turn,sessionId){return{kind:"turn",sessionId,turnIndex:turn.turnIndex,...turn.timestamp!==void 0?{timestamp:turn.timestamp}:{},request:{text:turn.requestTexts.join("\n"),media:[...turn.media.values()],...turn.recall!==void 0?{recall:turn.recall}:{}},response:{text:turn.responseTexts.join("\n"),toolCalls:turn.toolCalls}}}__name(finishTurn,"finishTurn");function activeChainRecords(records){const byUuid=new Map;for(const record of records){if(typeof record.uuid==="string")byUuid.set(record.uuid,record)}if(byUuid.size===0)return records;let leaf;for(let i=records.length-1;i>=0;i--){if(typeof records[i].uuid==="string"){leaf=records[i];break}}if(!leaf)return records;const active=new Set;let current=leaf;while(current?.uuid&&!active.has(current.uuid)){active.add(current.uuid);current=typeof current.parentUuid==="string"?byUuid.get(current.parentUuid):void 0}return records.filter(r=>typeof r.uuid!=="string"||active.has(r.uuid))}__name(activeChainRecords,"activeChainRecords");function buildTurnRecords(transcriptLines){const turns=[];let sessionId="";let current;for(const record of activeChainRecords(transcriptLines)){if(typeof record.sessionId==="string"&&sessionId===""){sessionId=record.sessionId}if(record.type==="user"&&record.subtype===void 0){if(current)turns.push(finishTurn(current,sessionId));current={turnIndex:turns.length,...record.timestamp!==void 0?{timestamp:record.timestamp}:{},requestTexts:[],media:new Map,responseTexts:[],toolCalls:[]};consumeRecordParts(current,record,true);continue}if(!current)continue;if(record.type==="system"&&record.subtype==="omni_recall"){current.recall=record.systemPayload;continue}if(record.type==="tool_result"){consumeRecordParts(current,record,false);continue}if(record.type==="assistant"){for(const part of record.message?.parts??[]){if(isThoughtPart(part))continue;const text=textOfPart(part);if(text!==void 0&&text.trim()){current.responseTexts.push(text);continue}const call=functionCallOfPart(part);if(call)current.toolCalls.push(call)}}}if(current)turns.push(finishTurn(current,sessionId));return turns}__name(buildTurnRecords,"buildTurnRecords");async function readSnapshotRaw(omniRootDir){const filePath=path3.join(omniRootDir,"memory.json");let raw;try{raw=await fs3.readFile(filePath,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||[parsed.files,parsed.versions,parsed.executions,parsed.entries].some(c=>typeof c!=="object"||c===null||Array.isArray(c))){throw new Error("unexpected snapshot shape")}return parsed}catch(err){debugLogger3.debug(`trajectory export: memory unreadable, exporting transcript only: ${err instanceof Error?err.message:err}`);return void 0}}__name(readSnapshotRaw,"readSnapshotRaw");function buildMemoryRecords(snapshot){const files=[];const executions=[];for(const version of Object.values(snapshot.versions)){try{const file=snapshot.files[version.fileId];if(!file)continue;files.push({kind:"file",fileId:version.fileId,fileVersionId:version.fileVersionId,rootFileId:file.rootFileId,sha256:version.sha256,mediaType:version.mediaType,origin:file.origin,sizeBytes:version.sizeBytes,mimeType:version.mimeType,source:version.source,...version.producedByExecutionId!==void 0?{producedByExecutionId:version.producedByExecutionId}:{},...version.parentVersionId!==void 0?{parentVersionId:version.parentVersionId}:{},createdAt:version.createdAt})}catch{}}for(const execution of Object.values(snapshot.executions)){try{const outputs=execution.outputRefs.flatMap(entryId=>{const entry=snapshot.entries[entryId];if(!entry)return[];return[{kind:entry.kind,...entry.role!==void 0?{role:entry.role}:{},...entry.artifactRef?.managedId?.startsWith("sha256/")?{sha256:entry.artifactRef.managedId.slice("sha256/".length)}:{},...entry.artifactRef?.mimeType!==void 0?{mimeType:entry.artifactRef.mimeType}:{},...entry.artifactRef?.sizeBytes!==void 0?{sizeBytes:entry.artifactRef.sizeBytes}:{},...entry.disclosure!==void 0?{disclosure:entry.disclosure}:{}}]});executions.push({kind:"execution",executionId:execution.executionId,invocationId:execution.invocationId,executionOrigin:execution.executionOrigin,toolName:execution.toolName,...execution.toolVersion!==void 0?{toolVersion:execution.toolVersion}:{},finalArguments:execution.finalArguments,omniConfigHash:execution.omniConfigHash,sourceVersionId:execution.sourceVersionId,rootFileId:execution.rootFileId,startedAt:execution.startedAt,completedAt:execution.completedAt,...execution.reusedExecutionId!==void 0?{reusedExecutionId:execution.reusedExecutionId}:{},outputs})}catch{}}return{files,executions}}__name(buildMemoryRecords,"buildMemoryRecords");function filterToSession(memory,turns,transcriptLines){const callIds=new Set;for(const record of activeChainRecords(transcriptLines)){if(record.type!=="tool_result")continue;for(const part of record.message?.parts??[]){const id=functionResponseOfPart(part)?.id;if(typeof id==="string")callIds.add(id)}}const mediaNames=new Set;for(const turn of turns){for(const call of turn.response.toolCalls){if(call.callId)callIds.add(call.callId)}for(const media of turn.request.media)mediaNames.add(media.name)}const filesByVersion=new Map(memory.files.map(f=>[f.fileVersionId,f]));const versionsByFile=new Map;for(const f of memory.files){const list=versionsByFile.get(f.fileId)??[];list.push(f);versionsByFile.set(f.fileId,list)}const includedFiles=new Set;const includedExecutions=new Set;const includeFile=__name(fileId=>{if(!fileId||includedFiles.has(fileId))return false;if(!versionsByFile.has(fileId))return false;includedFiles.add(fileId);return true},"includeFile");for(const f of memory.files){if(mediaNames.has(f.source.locator))includeFile(f.fileId)}for(const e of memory.executions){if(callIds.has(e.invocationId))includedExecutions.add(e.executionId)}let changed=true;while(changed){changed=false;for(const e of memory.executions){const sourceFile=filesByVersion.get(e.sourceVersionId)?.fileId;if(!includedExecutions.has(e.executionId)){if(sourceFile&&includedFiles.has(sourceFile)){includedExecutions.add(e.executionId);changed=true}else{continue}}if(includeFile(sourceFile))changed=true}for(const f of memory.files){if(includedFiles.has(f.fileId))continue;if(f.producedByExecutionId!==void 0&&includedExecutions.has(f.producedByExecutionId)){includeFile(f.fileId);changed=true}}}return{files:memory.files.filter(f=>includedFiles.has(f.fileId)),executions:memory.executions.filter(e=>includedExecutions.has(e.executionId))}}__name(filterToSession,"filterToSession");async function exportOmniTrajectory(options){const raw=await fs3.readFile(options.transcriptPath,"utf8");const transcriptLines=[];for(const line of raw.split("\n")){if(!line.trim())continue;try{transcriptLines.push(JSON.parse(line))}catch{}}const turns=buildTurnRecords(transcriptLines);const records=[...turns];const snapshot=await readSnapshotRaw(options.omniRootDir);const memoryRecords=snapshot?filterToSession(buildMemoryRecords(snapshot),turns,transcriptLines):{files:[],executions:[]};records.push(...memoryRecords.files.sort((a,b)=>a.fileVersionId.localeCompare(b.fileVersionId)),...memoryRecords.executions.sort((a,b)=>a.executionId.localeCompare(b.executionId)));return records}__name(exportOmniTrajectory,"exportOmniTrajectory");function serializeOmniTrajectory(records){return records.map(r=>JSON.stringify(r)).join("\n")+"\n"}__name(serializeOmniTrajectory,"serializeOmniTrajectory");async function writeOmniTrajectoryJsonl(options){const outPath=path3.resolve(options.outPath);if(outPath===path3.resolve(options.transcriptPath)){throw new Error("trajectory outPath must differ from the transcript path")}const records=await exportOmniTrajectory(options);await fs3.mkdir(path3.dirname(outPath),{recursive:true});await fs3.writeFile(outPath,serializeOmniTrajectory(records),"utf8");return{records:records.length}}__name(writeOmniTrajectoryJsonl,"writeOmniTrajectoryJsonl");var debugLogger4=createDebugLogger("omni");function sanitizeErrorMessage(err,knownPaths=[]){let msg=err instanceof Error?err.message:String(err);for(const known of knownPaths){if(!known)continue;msg=msg.split(known).join(path4.basename(known));const segments=known.split(/[\\/]+/).filter(Boolean);if(/^[A-Za-z]:$/.test(segments[0]??""))segments.shift();if(segments.length>=2){const spelled=segments.map(segment=>segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");msg=msg.replace(new RegExp(`(?:[A-Za-z]:)?[\\\\/]*${spelled}`,"g"),()=>path4.basename(known))}}return msg.replace(/(?:\/[^/\s'"]+)+\/([^/\s'"]+)/g,"$1").replace(/(?:[A-Za-z]:)?(?:\\[^\\\s'"]+)+\\([^\\\s'"]+)/g,"$1")}__name(sanitizeErrorMessage,"sanitizeErrorMessage");function buildAdditionalMediaParts(displayName,additionalMedia){const parts=[];for(const extra of additionalMedia??[]){if(extra.disclosure){parts.push({text:formatDisclosureText(displayName,extra.disclosure)})}if(extra.omission){parts.push({text:formatOmissionText(displayName,extra.omission.reason)})}else{parts.push({fileData:{fileUri:extra.fileUri,mimeType:extra.mimeType,displayName}})}}return parts}__name(buildAdditionalMediaParts,"buildAdditionalMediaParts");function buildTranscriptParts(displayName,transcripts){const parts=[];for(const t of transcripts??[]){if(t.disclosure){parts.push({text:formatDisclosureText(displayName,t.disclosure)})}parts.push({text:formatTranscriptText(displayName,t.text)})}return parts}__name(buildTranscriptParts,"buildTranscriptParts");var OmniDeliveryError=class extends Error{static{__name(this,"OmniDeliveryError")}constructor(message,options){super(message,options);this.name="OmniDeliveryError"}};function evaluateTransportLimits(config,recognized,displayName){try{assertWithinByteLimit(config,recognized.sizeBytes,displayName);assertWithinDurationLimit(config,recognized,displayName);return{estimate:assertWithinTokenLimit(config,recognized,displayName)}}catch(err){if(err instanceof OmniTransportGuardError){return{estimate:estimateRawResourceTokens(recognized),violation:err.message}}throw err}}__name(evaluateTransportLimits,"evaluateTransportLimits");async function processMediaForOmniDelivery(filePath,config,options){const{expectedModality,signal}=options??{};const displayName=options?.displayName??path4.basename(filePath);const[ffmpeg,ffprobe]=await Promise.all([isFfmpegAvailable(),isFfprobeAvailable()]);if(!ffmpeg||!ffprobe){throw new OmniDeliveryError("ffmpeg/ffprobe not available; omni media delivery requires both on PATH.")}await fs4.stat(filePath).catch(err=>{throw new OmniDeliveryError(`Cannot stat media file ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})});let recognized;try{recognized=await recognizeMediaFile(filePath,{expectedModality,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Media recognition failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})}const store=new OmniObjectStore(config.storage.getQwenDir());const uploadConfig=requireEffectiveOmniUploadConfig(config);const cacheScope=createHash("sha256").update(`${uploadConfig.baseUrl}|${uploadConfig.apiKey}`).digest("hex").slice(0,16);const configuredTtl=config.getOmniUploadUrlTtlHours?.();const uploadCache=new OmniUploadCache(store.getOmniRootDir(),configuredTtl===void 0?DEFAULT_UPLOAD_CACHE_TTL_HOURS:configuredTtl,cacheScope);await runStartupRecoveryOnce(store,uploadCache,{quarantineRetentionDays:config.getOmniQuarantineRetentionDays?.(),quarantineMaxBytes:config.getOmniQuarantineMaxBytes?.(),degradationCache:new OmniDegradationCache(store.getOmniRootDir())});const processingConfig=config.getOmniProcessingConfig?.();const conditionContext=processingConfig?{session:buildSessionConditionNamespace(config,processingConfig.limits.reservedOutputTokens)}:void 0;const memoryConfig=config.getOmniMemoryConfig?.();const memoryService=memoryConfig?new MediaMemoryService(store.getOmniRootDir(),{maxInlineTextBytes:memoryConfig.collection.maxInlineTextBytes}):void 0;if(memoryService){void runOmniGcOnce({store,memoryService,registry:config.getOmniMediaResourceRegistry?.(),uploadCache,degradationCache:new OmniDegradationCache(store.getOmniRootDir()),retentionDays:config.getOmniStorageRetentionDays?.()??14,maxTotalBytes:typeof config.getOmniStorageMaxTotalBytes==="function"?effectiveOmniStorageMaxTotalBytes(config):20*1024*1024*1024})}const registry=memoryService?config.getOmniMediaResourceRegistry?.():void 0;const bindSessionResource=__name((item,fileRefOverride)=>registry&&item.memoryBinding?registry.bind({...item.memoryBinding,fileRef:fileRefOverride??item.filePath,mediaType:item.recognized.modality}):void 0,"bindSessionResource");let sourceSha256;let sourceBinding;let sourceFileRef=filePath;if(memoryService){try{sourceSha256=await hashFileSha256(filePath,signal)}catch(err){if(signal?.aborted)throw err;debugLogger4.debug(`omni memory: hashing ${displayName} failed, skipping collection: ${sanitizeErrorMessage(err,[filePath])}`)}if(sourceSha256){const origin=options?.origin??"user";const ephemeralSource=origin==="tool"||options?.sourceUrl!==void 0;sourceFileRef=ephemeralSource?store.objectPathFor(sourceSha256,extensionForMime(recognized.detectedMimeType)):filePath;sourceBinding=await memoryService.recordFileRecognized({fileRef:sourceFileRef,sha256:sourceSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,origin,source:options?.sourceUrl!==void 0?{protocol:"url",locator:options.sourceUrl}:origin==="tool"?{protocol:"managed",locator:`sha256/${sourceSha256}`}:{protocol:"local",locator:displayName},recognition:{ingestionConfigHash:"",detectorVersion:MEDIA_DETECTOR_VERSION,probeStatus:"complete"}})}}let final={filePath,recognized,sha256:sourceSha256,memoryBinding:sourceBinding};const sessionResourceId=bindSessionResource(final,sourceFileRef)?.resourceId;const guardRejection=__name((message,options2)=>{const err=new OmniTransportGuardError(message,options2);if(sessionResourceId!==void 0){err.sessionResourceId=sessionResourceId}return err},"guardRejection");let extraDeliveries=[];const transcripts=[];const collectTranscripts=__name(files=>{for(const file of files){transcripts.push({text:file.text,disclosure:file.disclosure})}},"collectTranscripts");const textOnlyDelivery=__name((recognizedFinal,tokenEstimate2,extras)=>({fileUri:"",mimeType:recognizedFinal.detectedMimeType,sha256:"",recognized:recognizedFinal,tokenEstimate:tokenEstimate2,deduped:false,uploadCacheHit:false,degraded:true,transcripts,resourceId:sessionResourceId,...extras}),"textOnlyDelivery");const policies=processingConfig?.fixedPolicies??[];if(policies.length>0){let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath,recognized,displayName,origin:options?.origin??"user",sha256:sourceSha256},{store,policies,signal,limits:processingConfig?.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Fixed-policy processing failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&transcripts.length>0){return textOnlyDelivery(recognized,evaluateTransportLimits(config,recognized,displayName).estimate)}if(deliveries.length===0){throw new OmniDeliveryError(`Fixed policies produced 0 media deliverables for ${displayName}; exactly one is supported.`)}final=deliveries[0];extraDeliveries=deliveries.slice(1);for(const delivery of deliveries)bindSessionResource(delivery)}const uploadModel=uploadConfig.model;const uploadResource=__name(async(item,estimate)=>{let sha256;try{sha256=item.sha256??await hashFileSha256(item.filePath,signal)}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to hash media file ${displayName}: ${sanitizeErrorMessage(err,[item.filePath])}`,{cause:err})}const cachedUrl=await uploadCache.get(sha256,uploadModel);if(cachedUrl){debugLogger4.debug(`omni upload cache hit: sha256=${sha256.slice(0,12)}\u2026 model=${uploadModel}`);return{fileUri:cachedUrl,sha256,deduped:true,uploadCacheHit:true}}const extension=extensionForMime(item.recognized.detectedMimeType);let objectPath;let deduped;try{const put=await store.putFile(item.filePath,sha256,extension,signal);objectPath=put.objectPath;deduped=put.deduped}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to store media in the omni object store: ${sanitizeErrorMessage(err,[item.filePath,store.getOmniRootDir()])}`,{cause:err})}const uploader=new DashScopeUploader({apiKey:uploadConfig.apiKey,baseUrl:uploadConfig.baseUrl});let fileUri;try{fileUri=await uploader.uploadFile({filePath:objectPath,model:uploadModel,mimeType:item.recognized.detectedMimeType,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(sanitizeErrorMessage(err,[objectPath,store.getOmniRootDir()]),{cause:err})}debugLogger4.debug(`omni ${item.recognized.modality} delivered: sha256=${sha256.slice(0,12)}\u2026 size=${item.recognized.sizeBytes} est=${estimate.estimatedTokenCount}(${estimate.status}) deduped=${deduped} degraded=${item.degraded===true} uri=${fileUri}`);await uploadCache.put(sha256,uploadModel,fileUri);return{fileUri,sha256,deduped,uploadCacheHit:false}},"uploadResource");const processAdditionalMedia=__name(async()=>{if(extraDeliveries.length===0)return void 0;return Promise.all(extraDeliveries.map(async extra=>{const extraGuard=evaluateTransportLimits(config,extra.recognized,displayName);if(extraGuard.violation){debugLogger4.debug(`omni additional ${extra.recognized.modality} explicitly omitted (transport guard): ${extraGuard.violation}`);return{fileUri:"",mimeType:extra.recognized.detectedMimeType,sha256:extra.sha256??"",disclosure:extra.disclosure,omission:{reason:extraGuard.violation}}}const uploaded2=await uploadResource(extra,extraGuard.estimate);return{fileUri:uploaded2.fileUri,mimeType:extra.recognized.detectedMimeType,sha256:uploaded2.sha256,disclosure:extra.disclosure}}))},"processAdditionalMedia");let guard=evaluateTransportLimits(config,final.recognized,displayName);if(guard.violation&&processingConfig){const maxPasses=processingConfig.limits.maxTransportPasses;for(let pass=0;guard.violation&&pass<maxPasses;pass++){const guardPolicies=processingConfig.transportGuardPolicies.filter(p=>p.mediaTypes.includes(final.recognized.modality));if(guardPolicies.length===0)break;let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath:final.filePath,recognized:final.recognized,displayName,origin:options?.origin??"user",sha256:final.sha256},{store,policies:guardPolicies,signal,limits:processingConfig.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding:final.memoryBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw guardRejection(`Transport-guard processing failed for ${displayName}: ${sanitizeErrorMessage(err,[final.filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&fileDeliveries.length>0){return textOnlyDelivery(final.recognized,guard.estimate,{disclosure:final.disclosure,additionalMedia:await processAdditionalMedia()})}if(deliveries.length!==1){throw guardRejection(`Transport-guard policies produced ${deliveries.length} media deliverables for ${displayName}; exactly one is supported.`)}if(deliveries[0].filePath===final.filePath){break}const priorDisclosure=final.disclosure;final=deliveries[0];if(priorDisclosure&&final.disclosure){final={...final,disclosure:`${priorDisclosure}\uFF1B${final.disclosure}`}}else if(priorDisclosure){final={...final,disclosure:priorDisclosure}}bindSessionResource(final);guard=evaluateTransportLimits(config,final.recognized,displayName)}}if(guard.violation){if(!processingConfig){throw guardRejection(guard.violation)}debugLogger4.debug(`omni ${final.recognized.modality} explicitly omitted (transport guard): ${guard.violation}`);return{fileUri:"",mimeType:final.recognized.detectedMimeType,sha256:final.sha256??"",recognized:final.recognized,tokenEstimate:guard.estimate,deduped:false,uploadCacheHit:false,disclosure:final.disclosure,degraded:final.degraded,omission:{reason:guard.violation},transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}const tokenEstimate=guard.estimate;const uploaded=await uploadResource(final,tokenEstimate);return{fileUri:uploaded.fileUri,mimeType:final.recognized.detectedMimeType,sha256:uploaded.sha256,recognized:final.recognized,tokenEstimate,deduped:uploaded.deduped,uploadCacheHit:uploaded.uploadCacheHit,disclosure:final.disclosure,degraded:final.degraded,transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}__name(processMediaForOmniDelivery,"processMediaForOmniDelivery");async function readMediaViaOmniDelivery(params){const{filePath,config,displayName,relativePathForDisplay,expectedModality,signal}=params;try{const delivery=await processMediaForOmniDelivery(filePath,config,{expectedModality,signal});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);const handleParts=(()=>{if(!delivery.resourceId)return[];const binding=config.getOmniMediaResourceRegistry?.()?.resolve(delivery.resourceId);if(binding&&binding.fileRef===filePath&&!/[\r\n]/.test(filePath)){return[harnessPathAnnotationPart(filePath)]}return[{text:formatResourceHandleText(displayName,delivery.resourceId)}]})();if(delivery.omission){const omissionPart={text:formatOmissionText(displayName,delivery.omission.reason)};return{llmContent:transcriptParts.length>0||additionalParts.length>0||handleParts.length>0?[...handleParts,omissionPart,...additionalParts,...transcriptParts]:omissionPart.text,returnDisplay:`Media omitted by the omni transport guard: ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}if(!delivery.fileUri&&transcriptParts.length>0){const disclosureParts=delivery.disclosure?[{text:formatDisclosureText(displayName,delivery.disclosure)}]:[];return{llmContent:[...handleParts,...disclosureParts,...additionalParts,...transcriptParts],returnDisplay:`Read ${delivery.recognized.modality} as transcript (omni policy): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};const parts=[...handleParts];const{width,height}=delivery.recognized.metadata;if(delivery.recognized.modality==="image"&&width!==void 0&&height!==void 0){parts.push({text:delivery.disclosure?`Image ${displayName}: delivered at ${width}x${height} px after degradation. Use zoom_image to inspect details \u2014 it reads the original file.`:`Image ${displayName}: full resolution ${width}x${height} px. Use zoom_image for a closer look at details.`})}if(delivery.disclosure){parts.push({text:formatDisclosureText(displayName,delivery.disclosure)})}parts.push(fileDataPart);parts.push(...additionalParts);parts.push(...transcriptParts);const llmContent=parts.length===1?fileDataPart:parts;return{llmContent,returnDisplay:`Read ${delivery.recognized.modality} file (omni upload): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}catch(err){if(isAbortError(err)||signal?.aborted)throw err;const message=sanitizeErrorMessage(err,[filePath]);return{llmContent:`[Omni media delivery failed for ${displayName}: ${message}]`,returnDisplay:`Failed to deliver media via omni upload: ${relativePathForDisplay}`,error:`Omni media delivery failed: ${displayName}: ${message}`,errorType:"read_content_failure"}}}__name(readMediaViaOmniDelivery,"readMediaViaOmniDelivery");function effectiveMaxDownloadFileBytes(config){const uploadCap=effectiveMaxUploadFileBytes(config);const configured=config.getOmniUrlDownloadMaxFileBytes?.();if(configured!==void 0&&configured>0){return Math.min(configured,uploadCap)}return uploadCap}__name(effectiveMaxDownloadFileBytes,"effectiveMaxDownloadFileBytes");export{OmniDownloadError,parseHttpUrlRef,downloadMediaUrl,exportOmniTrajectory,serializeOmniTrajectory,writeOmniTrajectoryJsonl,sanitizeErrorMessage,buildAdditionalMediaParts,buildTranscriptParts,OmniDeliveryError,processMediaForOmniDelivery,readMediaViaOmniDelivery,effectiveMaxDownloadFileBytes,processToolResultOmniMedia};
3
+ import{DashScopeUploader}from"./chunk-RKDS7A4H.js";import{OmniDegradationCache,OmniTransportGuardError,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveMaxUploadFileBytes,effectiveOmniStorageMaxTotalBytes,estimateRawResourceTokens,runFixedPolicies,runOmniGcOnce}from"./chunk-V6VMUJ47.js";import{MEDIA_DETECTOR_VERSION,MediaMemoryService}from"./chunk-UYYQB2TU.js";import{runStartupRecoveryOnce}from"./chunk-HN5UYLPU.js";import{OmniObjectStore,prepareOmniDownloadsDir}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile,sniffMediaType}from"./chunk-ZBHL2CXR.js";import{isFfmpegAvailable,isFfprobeAvailable}from"./chunk-NIOS3B3V.js";import{isOmniDeliveryActive}from"./chunk-QF44NNSC.js";import{requireEffectiveOmniUploadConfig}from"./chunk-DPNGBOI7.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX,formatDisclosureText,formatOmissionText,formatResourceHandleText,formatTranscriptText,harnessPathAnnotationPart,isHarnessAnnotationPart,parseResourceHandleText,parseResourcePathText,splitAnnotationBody,unescapeAnnotationName}from"./chunk-SW54YEPK.js";import{isPermittedRedirect,isPrivateHost,resolveNetworkTarget}from"./chunk-OZGM5CCE.js";import{ImageViewError,boundImageBuffer,sniffBoundableImageMime}from"./chunk-Z6AR5XE5.js";import{TOOL_RESULT_MEDIA_REMEDY,clampInlineMediaPart,getMaxInlineMediaBytes}from"./chunk-Q6UAOTP3.js";import{detectRuntime,loadUndici}from"./chunk-ZZZAYAJW.js";import{DEFAULT_UPLOAD_CACHE_TTL_HOURS,OmniUploadCache}from"./chunk-HTW7PYHK.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{isAbortError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import path4 from"node:path";import fs4 from"node:fs/promises";init_esbuild_shims();function buildSessionConditionNamespace(config,reservedOutputTokens){const session={reservedOutputTokens};const windowSize=config.getContentGeneratorConfig?.()?.contextWindowSize;const contextWindowTokens=typeof windowSize==="number"&&Number.isFinite(windowSize)&&windowSize>0?windowSize:void 0;if(contextWindowTokens!==void 0){session.contextWindowTokens=contextWindowTokens}let promptTokenCount;try{const count=config.getGeminiClient?.()?.getChat?.()?.getLastPromptTokenCount();if(typeof count==="number"&&Number.isFinite(count)&&count>=0){promptTokenCount=count}}catch{}if(promptTokenCount!==void 0){session.promptTokenCount=promptTokenCount}if(contextWindowTokens!==void 0&&promptTokenCount!==void 0){session.availableContextTokens=Math.max(0,contextWindowTokens-promptTokenCount-reservedOutputTokens)}return session}__name(buildSessionConditionNamespace,"buildSessionConditionNamespace");init_esbuild_shims();import{randomBytes}from"node:crypto";import{once}from"node:events";import{createWriteStream}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var debugLogger=createDebugLogger("omni:download");var OmniDownloadError=class extends Error{static{__name(this,"OmniDownloadError")}constructor(message,options){super(message,options);this.name="OmniDownloadError"}};var RESOLVE_TIMEOUT_MS=3e4;var HEADER_TIMEOUT_MS=3e4;var IDLE_TIMEOUT_MS=6e4;var MAX_REDIRECTS=5;function parseHttpUrlRef(pathName){if(!/^https?:\/\//i.test(pathName))return null;try{return new URL(pathName)}catch{return null}}__name(parseHttpUrlRef,"parseHttpUrlRef");function scrubPathsFromMessage(message){return message.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`\\/]+){2,}[\\/]?/g,match=>path.basename(match))}__name(scrubPathsFromMessage,"scrubPathsFromMessage");function formatCauseChain(err){const parts=[];let cause=err instanceof Error?err.cause:void 0;for(let depth=0;cause!=null&&depth<4;depth++){const code=cause.code;const message=cause instanceof Error?cause.message:typeof cause==="string"?cause:void 0;if(typeof code==="string"&&message&&!message.includes(code)){parts.push(`${code}: ${message}`)}else if(message){parts.push(message)}else if(typeof code==="string"){parts.push(code)}cause=cause instanceof Error?cause.cause:void 0}return parts.length>0?scrubPathsFromMessage(parts.join("; ")):void 0}__name(formatCauseChain,"formatCauseChain");function detectConfiguredProxy(undici){for(const key of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY","all_proxy","ALL_PROXY"]){if(process.env[key])return true}try{return undici.getGlobalDispatcher()instanceof undici.EnvHttpProxyAgent}catch{return false}}__name(detectConfiguredProxy,"detectConfiguredProxy");async function downloadMediaUrl(params){const{url,downloadsDir,maxBytes,signal,resolveTimeoutMs=RESOLVE_TIMEOUT_MS,headerTimeoutMs=HEADER_TIMEOUT_MS,idleTimeoutMs=IDLE_TIMEOUT_MS}=params;const resolveTarget=params.resolveTarget??(target=>resolveNetworkTarget(target,"public",signal));if(isPrivateHost(url)){throw new OmniDownloadError(`URL host is not publicly routable (refused for safety): ${new URL(url).hostname}`)}let parsed;try{parsed=new URL(url)}catch{throw new OmniDownloadError("URL media ref is not a valid URL (refused).")}if(parsed.protocol!=="https:"){throw new OmniDownloadError(`URL media must be https (refused for safety): ${parsed.protocol}//${parsed.hostname}`)}if(parsed.username||parsed.password){throw new OmniDownloadError(`URL media must not embed credentials (refused for safety): ${parsed.hostname}`)}const runtime=detectRuntime();if(runtime!=="node"){throw new OmniDownloadError(`URL media requires the Node runtime to verify the connection target (refused for safety on ${runtime}): use a local file path instead of a URL, or run under Node.`)}const undici=await loadUndici();const proxied=params.detectProxy?params.detectProxy():detectConfiguredProxy(undici);if(proxied){throw new OmniDownloadError(`URL media fetching is not supported behind a proxy yet (refused): the connection pinning that enforces SSRF protection cannot be applied through a proxy. Download the file manually and use a local path instead.`)}try{await prepareOmniDownloadsDir(downloadsDir)}catch(err){throw new OmniDownloadError(`Could not prepare the downloads directory for URL media: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}const partPath=path.join(downloadsDir,`${randomBytes(8).toString("hex")}.part`);let currentUrl=url;let dispatcher;try{for(let redirects=0;;redirects++){let target;const resolveAbort=new AbortController;const resolveTimer=setTimeout(()=>resolveAbort.abort(new Error("resolve timeout")),resolveTimeoutMs);try{const pending=resolveTarget(currentUrl);pending.catch(()=>{});target=await Promise.race([pending,new Promise((_,reject)=>{resolveAbort.signal.addEventListener("abort",()=>reject(resolveAbort.signal.reason),{once:true})})])}catch(err){if(signal?.aborted)throw err;if(resolveAbort.signal.aborted){throw new OmniDownloadError(`Download timed out resolving ${new URL(currentUrl).hostname} (${resolveTimeoutMs/1e3}s)`)}const text=err instanceof Error?err.message:String(err);const reason=/blocked address/i.test(text)?"resolved to a non-public address":/did not resolve/i.test(text)?"did not resolve":"could not be verified";throw new OmniDownloadError(`URL host ${reason} (refused for safety): ${new URL(currentUrl).hostname}`,{cause:err})}finally{clearTimeout(resolveTimer)}if(!target.lookup){throw new OmniDownloadError(`URL host cannot be safely bound to a verified address (refused for safety): ${new URL(currentUrl).hostname}`)}const fetchFn=params.fetchFn??undici.fetch;const previousDispatcher=dispatcher;dispatcher=new undici.Agent({connect:{lookup:target.lookup}});await previousDispatcher?.close().catch(()=>{});const headerAbort=new AbortController;const headerTimer=setTimeout(()=>headerAbort.abort(new Error("header timeout")),headerTimeoutMs);const combined=AbortSignal.any(signal?[signal,headerAbort.signal]:[headerAbort.signal]);let res;try{res=await fetchFn(currentUrl,{redirect:"manual",signal:combined,dispatcher})}catch(err){if(signal?.aborted)throw err;if(headerAbort.signal.aborted){throw new OmniDownloadError(`Download timed out waiting for response headers from ${new URL(currentUrl).hostname} (${headerTimeoutMs/1e3}s)`)}const detail=err instanceof Error?scrubPathsFromMessage(err.message):String(err);const causeDetail=formatCauseChain(err);throw new OmniDownloadError(`Download request failed for ${new URL(currentUrl).hostname}: ${detail}${causeDetail?` (${causeDetail})`:""}`,{cause:err})}finally{clearTimeout(headerTimer)}if(res.status>=300&&res.status<400){await res.body?.cancel().catch(()=>{});const location=res.headers.get("location");if(!location||redirects>=MAX_REDIRECTS){throw new OmniDownloadError(`Too many or invalid redirects downloading from ${new URL(currentUrl).hostname}`)}let redirectUrl;try{redirectUrl=new URL(location,currentUrl).toString()}catch{throw new OmniDownloadError(`Redirect with a malformed Location header from ${new URL(currentUrl).hostname}`)}if(!isPermittedRedirect(currentUrl,redirectUrl)){throw new OmniDownloadError(`Cross-origin redirect refused: ${new URL(currentUrl).hostname} \u2192 ${new URL(redirectUrl).hostname}`)}currentUrl=redirectUrl;continue}if(!res.ok){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download failed: HTTP ${res.status} from ${new URL(currentUrl).hostname}`)}const contentLength=Number(res.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>maxBytes){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download exceeds the omni media limit: Content-Length ${contentLength} > ${maxBytes} bytes.`)}if(!res.body){throw new OmniDownloadError("Download response had no body.")}let written=0;const idleAbort=new AbortController;let idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);const streamSignal=AbortSignal.any(signal?[signal,idleAbort.signal]:[idleAbort.signal]);try{const source=Readable.fromWeb(res.body,{signal:streamSignal});const counter=__name(async function*(src){for await(const chunk of src){clearTimeout(idleTimer);idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);written+=chunk.length;if(written>maxBytes){throw new OmniDownloadError(`Download exceeds the omni media limit: >${maxBytes} bytes received.`)}yield chunk}},"counter");const destination=createWriteStream(partPath,{mode:384});await once(destination,"open");await pipeline(source,counter,destination)}catch(err){if(signal?.aborted)throw err;if(err instanceof OmniDownloadError)throw err;if(idleAbort.signal.aborted){throw new OmniDownloadError(`Download stalled from ${new URL(currentUrl).hostname}: no data for ${idleTimeoutMs/1e3}s`)}throw new OmniDownloadError(`Download interrupted from ${new URL(currentUrl).hostname}: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}finally{clearTimeout(idleTimer)}debugLogger.debug(`downloaded ${written} bytes from ${new URL(currentUrl).hostname}`);return{partPath}}}catch(err){await fs.rm(partPath,{force:true});throw err}finally{await dispatcher?.close().catch(()=>{})}}__name(downloadMediaUrl,"downloadMediaUrl");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import fs2 from"node:fs/promises";import path2 from"node:path";var debugLogger2=createDebugLogger("omni:tool-result");var MAX_UPLOADS_PER_TOOL_RESULT=8;var MAX_UPLOAD_BYTES_PER_TOOL_RESULT=128*1024*1024;async function boundDeclinedInlinePart(part,bytes,signal){const inline=part.inlineData;if(!inline?.data)return part;const inlineByteCeiling=getMaxInlineMediaBytes();let boundedPart=part;if(sniffBoundableImageMime(bytes.subarray(0,12))){try{const view=await boundImageBuffer(bytes,`tool-result media (${inline.mimeType??"unknown"})`,signal,inlineByteCeiling);if(view){boundedPart={inlineData:{...inline,data:view.bytes.toString("base64"),mimeType:view.mimeType}}}}catch(error){if(!(error instanceof ImageViewError)){throw error}debugLogger2.debug(`tool-result media kept inline could not be bounded: ${error.message}`)}}return clampInlineMediaPart(boundedPart,inlineByteCeiling,TOOL_RESULT_MEDIA_REMEDY)}__name(boundDeclinedInlinePart,"boundDeclinedInlinePart");async function processToolResultOmniMedia(responseParts,config,signal){if(!isOmniDeliveryActive(config))return responseParts;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};let changed=false;let uploadsRemaining=MAX_UPLOADS_PER_TOOL_RESULT;let uploadBytesRemaining=MAX_UPLOAD_BYTES_PER_TOOL_RESULT;const keepInline=__name(async(part,bytes)=>{const kept=await boundDeclinedInlinePart(part,bytes,signal);if(kept!==part)changed=true;return[kept]},"keepInline");const convertPart=__name(async part=>{const inline=part.inlineData;if(!inline?.data||!inline.mimeType)return[part];const top=inline.mimeType.split("/")[0];if(top!=="image"&&top!=="audio"&&top!=="video")return[part];const bytes=Buffer.from(inline.data,"base64");const sniffed=sniffMediaType(bytes.subarray(0,4096));if(!sniffed)return keepInline(part,bytes);if(!modalities[sniffed.modality]){return keepInline(part,bytes)}if(uploadsRemaining<=0||bytes.length>uploadBytesRemaining){debugLogger2.debug(`tool-result media budget exhausted; keeping part inline (${bytes.length} bytes)`);return keepInline(part,bytes)}const store=new OmniObjectStore(config.storage.getQwenDir());let tempPath;const displayName=inline.displayName??`tool-media.${top}`;try{const stagingDir=await prepareOmniDownloadsDir(path2.join(store.getOmniRootDir(),"downloads"));tempPath=path2.join(stagingDir,`${randomBytes2(8).toString("hex")}.part`);await fs2.writeFile(tempPath,bytes,{mode:384});const delivery=await processMediaForOmniDelivery(tempPath,config,{expectedModality:sniffed.modality,signal,displayName,origin:"tool"});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);uploadsRemaining-=delivery.additionalMedia?.filter(e=>!e.omission).length??0;const handleParts=delivery.resourceId?[{text:formatResourceHandleText(displayName,delivery.resourceId)}]:[];if(delivery.omission){changed=true;return[...handleParts,{text:formatOmissionText(displayName,delivery.omission.reason)},...additionalParts,...transcriptParts]}if(!delivery.fileUri&&transcriptParts.length>0){changed=true;return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},...additionalParts,...transcriptParts]:[...handleParts,...additionalParts,...transcriptParts]}changed=true;uploadsRemaining--;uploadBytesRemaining-=bytes.length;const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},fileDataPart,...additionalParts,...transcriptParts]:[...handleParts,fileDataPart,...additionalParts,...transcriptParts]}catch(err){if(signal.aborted)throw err;if(err instanceof OmniTransportGuardError){changed=true;return[...err.sessionResourceId?[{text:formatResourceHandleText(displayName,err.sessionResourceId)}]:[],{text:`[Tool media part withheld by the omni transport guard: ${err.message}]`}]}debugLogger2.debug(`tool-result media upload failed, keeping inline: ${err instanceof Error?err.message:String(err)}`);return keepInline(part,bytes)}finally{if(tempPath!==void 0){await fs2.rm(tempPath,{force:true}).catch(()=>{})}}},"convertPart");const result=[];for(const part of responseParts){const nested=part.functionResponse?.parts;if(Array.isArray(nested)&&nested.length>0){const convertedNested=[];let nestedChanged=false;for(const nestedPart of nested){const converted=await convertPart(nestedPart);if(converted.length!==1||converted[0]!==nestedPart){nestedChanged=true}convertedNested.push(...converted)}if(nestedChanged){result.push({...part,functionResponse:{...part.functionResponse,parts:convertedNested}});changed=true}else{result.push(part)}continue}result.push(...await convertPart(part))}return changed?result:responseParts}__name(processToolResultOmniMedia,"processToolResultOmniMedia");init_esbuild_shims();import fs3 from"node:fs/promises";import path3 from"node:path";var debugLogger3=createDebugLogger("omni:export");function textOfPart(part){if(typeof part==="string")return part;if(typeof part==="object"&&part!==null&&"text"in part){const text=part.text;return typeof text==="string"?text:void 0}return void 0}__name(textOfPart,"textOfPart");function functionResponseOfPart(part){if(typeof part!=="object"||part===null)return void 0;const response=part.functionResponse;if(typeof response!=="object"||response===null)return void 0;const{id,parts}=response;return{id,...Array.isArray(parts)?{parts}:{}}}__name(functionResponseOfPart,"functionResponseOfPart");function isThoughtPart(part){return typeof part==="object"&&part!==null&&part.thought===true}__name(isThoughtPart,"isThoughtPart");function functionCallOfPart(part){if(typeof part!=="object"||part===null)return void 0;const fc=part.functionCall;if(typeof fc!=="object"||fc===null)return void 0;const{id,name,args}=fc;if(typeof name!=="string")return void 0;const cleanArgs=typeof args==="object"&&args!==null?{...args}:void 0;return{...typeof id==="string"?{callId:id}:{},name,...cleanArgs?{args:cleanArgs}:{}}}__name(functionCallOfPart,"functionCallOfPart");function stripSystemReminders(text){return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"")}__name(stripSystemReminders,"stripSystemReminders");function mediaFor(turn,name){let media=turn.media.get(name);if(!media){media={name,disclosures:[],transcripts:[]};turn.media.set(name,media)}return media}__name(mediaFor,"mediaFor");function consumeAnnotationPart(turn,text,isHarnessAnnotation){if(text.startsWith(OMNI_RESOURCE_HANDLE_TEXT_PREFIX)){const resourceId=parseResourceHandleText(text);if(resourceId){const body=text.slice(OMNI_RESOURCE_HANDLE_TEXT_PREFIX.length);const name=unescapeAnnotationName(body.slice(0,body.length-resourceId.length-1));mediaFor(turn,name).resourceId=resourceId;return true}return false}if(text.startsWith(OMNI_RESOURCE_PATH_TEXT_PREFIX)){if(!isHarnessAnnotation)return false;const filePath=parseResourcePathText(text);if(filePath){mediaFor(turn,filePath.split(/[\\/]/).pop()??filePath);return true}return false}for(const[prefix,apply]of[[OMNI_DISCLOSURE_TEXT_PREFIX,(m,payload)=>{m.disclosures.push(payload)}],[OMNI_OMISSION_TEXT_PREFIX,(m,payload)=>{m.omitted=payload}],[OMNI_TRANSCRIPT_TEXT_PREFIX,(m,payload)=>{m.transcripts.push(payload)}]]){if(!text.startsWith(prefix))continue;const split=splitAnnotationBody(text.slice(prefix.length));if(!split)return false;apply(mediaFor(turn,split.name),split.payload);return true}return false}__name(consumeAnnotationPart,"consumeAnnotationPart");function consumeRecordParts(turn,record,collectProse){const parts=(record.message?.parts??[]).flatMap(part=>[part,...functionResponseOfPart(part)?.parts??[]]);for(const part of parts){const raw=textOfPart(part);if(raw===void 0)continue;const withoutReminders=stripSystemReminders(raw);const forAnnotation=withoutReminders.replace(/^\s+/,"");if(consumeAnnotationPart(turn,forAnnotation,isHarnessAnnotationPart(part)))continue;const prose=withoutReminders.trim();if(!prose)continue;if(collectProse)turn.requestTexts.push(prose)}}__name(consumeRecordParts,"consumeRecordParts");function finishTurn(turn,sessionId){return{kind:"turn",sessionId,turnIndex:turn.turnIndex,...turn.timestamp!==void 0?{timestamp:turn.timestamp}:{},request:{text:turn.requestTexts.join("\n"),media:[...turn.media.values()],...turn.recall!==void 0?{recall:turn.recall}:{}},response:{text:turn.responseTexts.join("\n"),toolCalls:turn.toolCalls}}}__name(finishTurn,"finishTurn");function activeChainRecords(records){const byUuid=new Map;for(const record of records){if(typeof record.uuid==="string")byUuid.set(record.uuid,record)}if(byUuid.size===0)return records;let leaf;for(let i=records.length-1;i>=0;i--){if(typeof records[i].uuid==="string"){leaf=records[i];break}}if(!leaf)return records;const active=new Set;let current=leaf;while(current?.uuid&&!active.has(current.uuid)){active.add(current.uuid);current=typeof current.parentUuid==="string"?byUuid.get(current.parentUuid):void 0}return records.filter(r=>typeof r.uuid!=="string"||active.has(r.uuid))}__name(activeChainRecords,"activeChainRecords");function buildTurnRecords(transcriptLines){const turns=[];let sessionId="";let current;for(const record of activeChainRecords(transcriptLines)){if(typeof record.sessionId==="string"&&sessionId===""){sessionId=record.sessionId}if(record.type==="user"&&record.subtype===void 0){if(current)turns.push(finishTurn(current,sessionId));current={turnIndex:turns.length,...record.timestamp!==void 0?{timestamp:record.timestamp}:{},requestTexts:[],media:new Map,responseTexts:[],toolCalls:[]};consumeRecordParts(current,record,true);continue}if(!current)continue;if(record.type==="system"&&record.subtype==="omni_recall"){current.recall=record.systemPayload;continue}if(record.type==="tool_result"){consumeRecordParts(current,record,false);continue}if(record.type==="assistant"){for(const part of record.message?.parts??[]){if(isThoughtPart(part))continue;const text=textOfPart(part);if(text!==void 0&&text.trim()){current.responseTexts.push(text);continue}const call=functionCallOfPart(part);if(call)current.toolCalls.push(call)}}}if(current)turns.push(finishTurn(current,sessionId));return turns}__name(buildTurnRecords,"buildTurnRecords");async function readSnapshotRaw(omniRootDir){const filePath=path3.join(omniRootDir,"memory.json");let raw;try{raw=await fs3.readFile(filePath,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||[parsed.files,parsed.versions,parsed.executions,parsed.entries].some(c=>typeof c!=="object"||c===null||Array.isArray(c))){throw new Error("unexpected snapshot shape")}return parsed}catch(err){debugLogger3.debug(`trajectory export: memory unreadable, exporting transcript only: ${err instanceof Error?err.message:err}`);return void 0}}__name(readSnapshotRaw,"readSnapshotRaw");function buildMemoryRecords(snapshot){const files=[];const executions=[];for(const version of Object.values(snapshot.versions)){try{const file=snapshot.files[version.fileId];if(!file)continue;files.push({kind:"file",fileId:version.fileId,fileVersionId:version.fileVersionId,rootFileId:file.rootFileId,sha256:version.sha256,mediaType:version.mediaType,origin:file.origin,sizeBytes:version.sizeBytes,mimeType:version.mimeType,source:version.source,...version.producedByExecutionId!==void 0?{producedByExecutionId:version.producedByExecutionId}:{},...version.parentVersionId!==void 0?{parentVersionId:version.parentVersionId}:{},createdAt:version.createdAt})}catch{}}for(const execution of Object.values(snapshot.executions)){try{const outputs=execution.outputRefs.flatMap(entryId=>{const entry=snapshot.entries[entryId];if(!entry)return[];return[{kind:entry.kind,...entry.role!==void 0?{role:entry.role}:{},...entry.artifactRef?.managedId?.startsWith("sha256/")?{sha256:entry.artifactRef.managedId.slice("sha256/".length)}:{},...entry.artifactRef?.mimeType!==void 0?{mimeType:entry.artifactRef.mimeType}:{},...entry.artifactRef?.sizeBytes!==void 0?{sizeBytes:entry.artifactRef.sizeBytes}:{},...entry.disclosure!==void 0?{disclosure:entry.disclosure}:{}}]});executions.push({kind:"execution",executionId:execution.executionId,invocationId:execution.invocationId,executionOrigin:execution.executionOrigin,toolName:execution.toolName,...execution.toolVersion!==void 0?{toolVersion:execution.toolVersion}:{},finalArguments:execution.finalArguments,omniConfigHash:execution.omniConfigHash,sourceVersionId:execution.sourceVersionId,rootFileId:execution.rootFileId,startedAt:execution.startedAt,completedAt:execution.completedAt,...execution.reusedExecutionId!==void 0?{reusedExecutionId:execution.reusedExecutionId}:{},outputs})}catch{}}return{files,executions}}__name(buildMemoryRecords,"buildMemoryRecords");function filterToSession(memory,turns,transcriptLines){const callIds=new Set;for(const record of activeChainRecords(transcriptLines)){if(record.type!=="tool_result")continue;for(const part of record.message?.parts??[]){const id=functionResponseOfPart(part)?.id;if(typeof id==="string")callIds.add(id)}}const mediaNames=new Set;for(const turn of turns){for(const call of turn.response.toolCalls){if(call.callId)callIds.add(call.callId)}for(const media of turn.request.media)mediaNames.add(media.name)}const filesByVersion=new Map(memory.files.map(f=>[f.fileVersionId,f]));const versionsByFile=new Map;for(const f of memory.files){const list=versionsByFile.get(f.fileId)??[];list.push(f);versionsByFile.set(f.fileId,list)}const includedFiles=new Set;const includedExecutions=new Set;const includeFile=__name(fileId=>{if(!fileId||includedFiles.has(fileId))return false;if(!versionsByFile.has(fileId))return false;includedFiles.add(fileId);return true},"includeFile");for(const f of memory.files){if(mediaNames.has(f.source.locator))includeFile(f.fileId)}for(const e of memory.executions){if(callIds.has(e.invocationId))includedExecutions.add(e.executionId)}let changed=true;while(changed){changed=false;for(const e of memory.executions){const sourceFile=filesByVersion.get(e.sourceVersionId)?.fileId;if(!includedExecutions.has(e.executionId)){if(sourceFile&&includedFiles.has(sourceFile)){includedExecutions.add(e.executionId);changed=true}else{continue}}if(includeFile(sourceFile))changed=true}for(const f of memory.files){if(includedFiles.has(f.fileId))continue;if(f.producedByExecutionId!==void 0&&includedExecutions.has(f.producedByExecutionId)){includeFile(f.fileId);changed=true}}}return{files:memory.files.filter(f=>includedFiles.has(f.fileId)),executions:memory.executions.filter(e=>includedExecutions.has(e.executionId))}}__name(filterToSession,"filterToSession");async function exportOmniTrajectory(options){const raw=await fs3.readFile(options.transcriptPath,"utf8");const transcriptLines=[];for(const line of raw.split("\n")){if(!line.trim())continue;try{transcriptLines.push(JSON.parse(line))}catch{}}const turns=buildTurnRecords(transcriptLines);const records=[...turns];const snapshot=await readSnapshotRaw(options.omniRootDir);const memoryRecords=snapshot?filterToSession(buildMemoryRecords(snapshot),turns,transcriptLines):{files:[],executions:[]};records.push(...memoryRecords.files.sort((a,b)=>a.fileVersionId.localeCompare(b.fileVersionId)),...memoryRecords.executions.sort((a,b)=>a.executionId.localeCompare(b.executionId)));return records}__name(exportOmniTrajectory,"exportOmniTrajectory");function serializeOmniTrajectory(records){return records.map(r=>JSON.stringify(r)).join("\n")+"\n"}__name(serializeOmniTrajectory,"serializeOmniTrajectory");async function writeOmniTrajectoryJsonl(options){const outPath=path3.resolve(options.outPath);if(outPath===path3.resolve(options.transcriptPath)){throw new Error("trajectory outPath must differ from the transcript path")}const records=await exportOmniTrajectory(options);await fs3.mkdir(path3.dirname(outPath),{recursive:true});await fs3.writeFile(outPath,serializeOmniTrajectory(records),"utf8");return{records:records.length}}__name(writeOmniTrajectoryJsonl,"writeOmniTrajectoryJsonl");var debugLogger4=createDebugLogger("omni");function sanitizeErrorMessage(err,knownPaths=[]){let msg=err instanceof Error?err.message:String(err);for(const known of knownPaths){if(!known)continue;msg=msg.split(known).join(path4.basename(known));const segments=known.split(/[\\/]+/).filter(Boolean);if(/^[A-Za-z]:$/.test(segments[0]??""))segments.shift();if(segments.length>=2){const spelled=segments.map(segment=>segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");msg=msg.replace(new RegExp(`(?:[A-Za-z]:)?[\\\\/]*${spelled}`,"g"),()=>path4.basename(known))}}return msg.replace(/(?:\/[^/\s'"]+)+\/([^/\s'"]+)/g,"$1").replace(/(?:[A-Za-z]:)?(?:\\[^\\\s'"]+)+\\([^\\\s'"]+)/g,"$1")}__name(sanitizeErrorMessage,"sanitizeErrorMessage");function buildAdditionalMediaParts(displayName,additionalMedia){const parts=[];for(const extra of additionalMedia??[]){if(extra.disclosure){parts.push({text:formatDisclosureText(displayName,extra.disclosure)})}if(extra.omission){parts.push({text:formatOmissionText(displayName,extra.omission.reason)})}else{parts.push({fileData:{fileUri:extra.fileUri,mimeType:extra.mimeType,displayName}})}}return parts}__name(buildAdditionalMediaParts,"buildAdditionalMediaParts");function buildTranscriptParts(displayName,transcripts){const parts=[];for(const t of transcripts??[]){if(t.disclosure){parts.push({text:formatDisclosureText(displayName,t.disclosure)})}parts.push({text:formatTranscriptText(displayName,t.text)})}return parts}__name(buildTranscriptParts,"buildTranscriptParts");var OmniDeliveryError=class extends Error{static{__name(this,"OmniDeliveryError")}constructor(message,options){super(message,options);this.name="OmniDeliveryError"}};function evaluateTransportLimits(config,recognized,displayName){try{assertWithinByteLimit(config,recognized.sizeBytes,displayName);assertWithinDurationLimit(config,recognized,displayName);return{estimate:assertWithinTokenLimit(config,recognized,displayName)}}catch(err){if(err instanceof OmniTransportGuardError){return{estimate:estimateRawResourceTokens(recognized),violation:err.message}}throw err}}__name(evaluateTransportLimits,"evaluateTransportLimits");async function processMediaForOmniDelivery(filePath,config,options){const{expectedModality,signal}=options??{};const displayName=options?.displayName??path4.basename(filePath);const[ffmpeg,ffprobe]=await Promise.all([isFfmpegAvailable(),isFfprobeAvailable()]);if(!ffmpeg||!ffprobe){throw new OmniDeliveryError("ffmpeg/ffprobe not available; omni media delivery requires both on PATH.")}await fs4.stat(filePath).catch(err=>{throw new OmniDeliveryError(`Cannot stat media file ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})});let recognized;try{recognized=await recognizeMediaFile(filePath,{expectedModality,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Media recognition failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})}const store=new OmniObjectStore(config.storage.getQwenDir());const uploadConfig=requireEffectiveOmniUploadConfig(config);const cacheScope=createHash("sha256").update(`${uploadConfig.baseUrl}|${uploadConfig.apiKey}`).digest("hex").slice(0,16);const configuredTtl=config.getOmniUploadUrlTtlHours?.();const uploadCache=new OmniUploadCache(store.getOmniRootDir(),configuredTtl===void 0?DEFAULT_UPLOAD_CACHE_TTL_HOURS:configuredTtl,cacheScope);await runStartupRecoveryOnce(store,uploadCache,{quarantineRetentionDays:config.getOmniQuarantineRetentionDays?.(),quarantineMaxBytes:config.getOmniQuarantineMaxBytes?.(),degradationCache:new OmniDegradationCache(store.getOmniRootDir())});const processingConfig=config.getOmniProcessingConfig?.();const conditionContext=processingConfig?{session:buildSessionConditionNamespace(config,processingConfig.limits.reservedOutputTokens)}:void 0;const memoryConfig=config.getOmniMemoryConfig?.();const memoryService=memoryConfig?new MediaMemoryService(store.getOmniRootDir(),{maxInlineTextBytes:memoryConfig.collection.maxInlineTextBytes}):void 0;if(memoryService){void runOmniGcOnce({store,memoryService,registry:config.getOmniMediaResourceRegistry?.(),uploadCache,degradationCache:new OmniDegradationCache(store.getOmniRootDir()),retentionDays:config.getOmniStorageRetentionDays?.()??14,maxTotalBytes:typeof config.getOmniStorageMaxTotalBytes==="function"?effectiveOmniStorageMaxTotalBytes(config):20*1024*1024*1024})}const registry=memoryService?config.getOmniMediaResourceRegistry?.():void 0;const bindSessionResource=__name((item,fileRefOverride)=>registry&&item.memoryBinding?registry.bind({...item.memoryBinding,fileRef:fileRefOverride??item.filePath,mediaType:item.recognized.modality}):void 0,"bindSessionResource");let sourceSha256;let sourceBinding;let sourceFileRef=filePath;if(memoryService){try{sourceSha256=await hashFileSha256(filePath,signal)}catch(err){if(signal?.aborted)throw err;debugLogger4.debug(`omni memory: hashing ${displayName} failed, skipping collection: ${sanitizeErrorMessage(err,[filePath])}`)}if(sourceSha256){const origin=options?.origin??"user";const ephemeralSource=origin==="tool"||options?.sourceUrl!==void 0;sourceFileRef=ephemeralSource?store.objectPathFor(sourceSha256,extensionForMime(recognized.detectedMimeType)):filePath;sourceBinding=await memoryService.recordFileRecognized({fileRef:sourceFileRef,sha256:sourceSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,origin,source:options?.sourceUrl!==void 0?{protocol:"url",locator:options.sourceUrl}:origin==="tool"?{protocol:"managed",locator:`sha256/${sourceSha256}`}:{protocol:"local",locator:displayName},recognition:{ingestionConfigHash:"",detectorVersion:MEDIA_DETECTOR_VERSION,probeStatus:"complete"}})}}let final={filePath,recognized,sha256:sourceSha256,memoryBinding:sourceBinding};const sessionResourceId=bindSessionResource(final,sourceFileRef)?.resourceId;const guardRejection=__name((message,options2)=>{const err=new OmniTransportGuardError(message,options2);if(sessionResourceId!==void 0){err.sessionResourceId=sessionResourceId}return err},"guardRejection");let extraDeliveries=[];const transcripts=[];const collectTranscripts=__name(files=>{for(const file of files){transcripts.push({text:file.text,disclosure:file.disclosure})}},"collectTranscripts");const textOnlyDelivery=__name((recognizedFinal,tokenEstimate2,extras)=>({fileUri:"",mimeType:recognizedFinal.detectedMimeType,sha256:"",recognized:recognizedFinal,tokenEstimate:tokenEstimate2,deduped:false,uploadCacheHit:false,degraded:true,transcripts,resourceId:sessionResourceId,...extras}),"textOnlyDelivery");const policies=processingConfig?.fixedPolicies??[];if(policies.length>0){let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath,recognized,displayName,origin:options?.origin??"user",sha256:sourceSha256},{store,policies,signal,limits:processingConfig?.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Fixed-policy processing failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&transcripts.length>0){return textOnlyDelivery(recognized,evaluateTransportLimits(config,recognized,displayName).estimate)}if(deliveries.length===0){throw new OmniDeliveryError(`Fixed policies produced 0 media deliverables for ${displayName}; exactly one is supported.`)}final=deliveries[0];extraDeliveries=deliveries.slice(1);for(const delivery of deliveries)bindSessionResource(delivery)}const uploadModel=uploadConfig.model;const uploadResource=__name(async(item,estimate)=>{let sha256;try{sha256=item.sha256??await hashFileSha256(item.filePath,signal)}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to hash media file ${displayName}: ${sanitizeErrorMessage(err,[item.filePath])}`,{cause:err})}const cachedUrl=await uploadCache.get(sha256,uploadModel);if(cachedUrl){debugLogger4.debug(`omni upload cache hit: sha256=${sha256.slice(0,12)}\u2026 model=${uploadModel}`);return{fileUri:cachedUrl,sha256,deduped:true,uploadCacheHit:true}}const extension=extensionForMime(item.recognized.detectedMimeType);let objectPath;let deduped;try{const put=await store.putFile(item.filePath,sha256,extension,signal);objectPath=put.objectPath;deduped=put.deduped}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to store media in the omni object store: ${sanitizeErrorMessage(err,[item.filePath,store.getOmniRootDir()])}`,{cause:err})}const uploader=new DashScopeUploader({apiKey:uploadConfig.apiKey,baseUrl:uploadConfig.baseUrl});let fileUri;try{fileUri=await uploader.uploadFile({filePath:objectPath,model:uploadModel,mimeType:item.recognized.detectedMimeType,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(sanitizeErrorMessage(err,[objectPath,store.getOmniRootDir()]),{cause:err})}debugLogger4.debug(`omni ${item.recognized.modality} delivered: sha256=${sha256.slice(0,12)}\u2026 size=${item.recognized.sizeBytes} est=${estimate.estimatedTokenCount}(${estimate.status}) deduped=${deduped} degraded=${item.degraded===true} uri=${fileUri}`);await uploadCache.put(sha256,uploadModel,fileUri);return{fileUri,sha256,deduped,uploadCacheHit:false}},"uploadResource");const processAdditionalMedia=__name(async()=>{if(extraDeliveries.length===0)return void 0;return Promise.all(extraDeliveries.map(async extra=>{const extraGuard=evaluateTransportLimits(config,extra.recognized,displayName);if(extraGuard.violation){debugLogger4.debug(`omni additional ${extra.recognized.modality} explicitly omitted (transport guard): ${extraGuard.violation}`);return{fileUri:"",mimeType:extra.recognized.detectedMimeType,sha256:extra.sha256??"",disclosure:extra.disclosure,omission:{reason:extraGuard.violation}}}const uploaded2=await uploadResource(extra,extraGuard.estimate);return{fileUri:uploaded2.fileUri,mimeType:extra.recognized.detectedMimeType,sha256:uploaded2.sha256,disclosure:extra.disclosure}}))},"processAdditionalMedia");let guard=evaluateTransportLimits(config,final.recognized,displayName);if(guard.violation&&processingConfig){const maxPasses=processingConfig.limits.maxTransportPasses;for(let pass=0;guard.violation&&pass<maxPasses;pass++){const guardPolicies=processingConfig.transportGuardPolicies.filter(p=>p.mediaTypes.includes(final.recognized.modality));if(guardPolicies.length===0)break;let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath:final.filePath,recognized:final.recognized,displayName,origin:options?.origin??"user",sha256:final.sha256},{store,policies:guardPolicies,signal,limits:processingConfig.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding:final.memoryBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw guardRejection(`Transport-guard processing failed for ${displayName}: ${sanitizeErrorMessage(err,[final.filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&fileDeliveries.length>0){return textOnlyDelivery(final.recognized,guard.estimate,{disclosure:final.disclosure,additionalMedia:await processAdditionalMedia()})}if(deliveries.length!==1){throw guardRejection(`Transport-guard policies produced ${deliveries.length} media deliverables for ${displayName}; exactly one is supported.`)}if(deliveries[0].filePath===final.filePath){break}const priorDisclosure=final.disclosure;final=deliveries[0];if(priorDisclosure&&final.disclosure){final={...final,disclosure:`${priorDisclosure}\uFF1B${final.disclosure}`}}else if(priorDisclosure){final={...final,disclosure:priorDisclosure}}bindSessionResource(final);guard=evaluateTransportLimits(config,final.recognized,displayName)}}if(guard.violation){if(!processingConfig){throw guardRejection(guard.violation)}debugLogger4.debug(`omni ${final.recognized.modality} explicitly omitted (transport guard): ${guard.violation}`);return{fileUri:"",mimeType:final.recognized.detectedMimeType,sha256:final.sha256??"",recognized:final.recognized,tokenEstimate:guard.estimate,deduped:false,uploadCacheHit:false,disclosure:final.disclosure,degraded:final.degraded,omission:{reason:guard.violation},transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}const tokenEstimate=guard.estimate;const uploaded=await uploadResource(final,tokenEstimate);return{fileUri:uploaded.fileUri,mimeType:final.recognized.detectedMimeType,sha256:uploaded.sha256,recognized:final.recognized,tokenEstimate,deduped:uploaded.deduped,uploadCacheHit:uploaded.uploadCacheHit,disclosure:final.disclosure,degraded:final.degraded,transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}__name(processMediaForOmniDelivery,"processMediaForOmniDelivery");async function readMediaViaOmniDelivery(params){const{filePath,config,displayName,relativePathForDisplay,expectedModality,signal}=params;try{const delivery=await processMediaForOmniDelivery(filePath,config,{expectedModality,signal});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);const handleParts=(()=>{if(!delivery.resourceId)return[];const binding=config.getOmniMediaResourceRegistry?.()?.resolve(delivery.resourceId);if(binding&&binding.fileRef===filePath&&!/[\r\n]/.test(filePath)){return[harnessPathAnnotationPart(filePath)]}return[{text:formatResourceHandleText(displayName,delivery.resourceId)}]})();if(delivery.omission){const omissionPart={text:formatOmissionText(displayName,delivery.omission.reason)};return{llmContent:transcriptParts.length>0||additionalParts.length>0||handleParts.length>0?[...handleParts,omissionPart,...additionalParts,...transcriptParts]:omissionPart.text,returnDisplay:`Media omitted by the omni transport guard: ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}if(!delivery.fileUri&&transcriptParts.length>0){const disclosureParts=delivery.disclosure?[{text:formatDisclosureText(displayName,delivery.disclosure)}]:[];return{llmContent:[...handleParts,...disclosureParts,...additionalParts,...transcriptParts],returnDisplay:`Read ${delivery.recognized.modality} as transcript (omni policy): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};const parts=[...handleParts];const{width,height}=delivery.recognized.metadata;if(delivery.recognized.modality==="image"&&width!==void 0&&height!==void 0){parts.push({text:delivery.disclosure?`Image ${displayName}: delivered at ${width}x${height} px after degradation. Use zoom_image to inspect details \u2014 it reads the original file.`:`Image ${displayName}: full resolution ${width}x${height} px. Use zoom_image for a closer look at details.`})}if(delivery.disclosure){parts.push({text:formatDisclosureText(displayName,delivery.disclosure)})}parts.push(fileDataPart);parts.push(...additionalParts);parts.push(...transcriptParts);const llmContent=parts.length===1?fileDataPart:parts;return{llmContent,returnDisplay:`Read ${delivery.recognized.modality} file (omni upload): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}catch(err){if(isAbortError(err)||signal?.aborted)throw err;const message=sanitizeErrorMessage(err,[filePath]);return{llmContent:`[Omni media delivery failed for ${displayName}: ${message}]`,returnDisplay:`Failed to deliver media via omni upload: ${relativePathForDisplay}`,error:`Omni media delivery failed: ${displayName}: ${message}`,errorType:"read_content_failure"}}}__name(readMediaViaOmniDelivery,"readMediaViaOmniDelivery");function effectiveMaxDownloadFileBytes(config){const uploadCap=effectiveMaxUploadFileBytes(config);const configured=config.getOmniUrlDownloadMaxFileBytes?.();if(configured!==void 0&&configured>0){return Math.min(configured,uploadCap)}return uploadCap}__name(effectiveMaxDownloadFileBytes,"effectiveMaxDownloadFileBytes");export{OmniDownloadError,parseHttpUrlRef,downloadMediaUrl,exportOmniTrajectory,serializeOmniTrajectory,writeOmniTrajectoryJsonl,sanitizeErrorMessage,buildAdditionalMediaParts,buildTranscriptParts,OmniDeliveryError,processMediaForOmniDelivery,readMediaViaOmniDelivery,effectiveMaxDownloadFileBytes,processToolResultOmniMedia};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{sanitizeFilenameComponent}from"./chunk-LIIMQ4DI.js";import{Storage}from"./chunk-EPODBRBP.js";import{getProjectHash,isSubpath}from"./chunk-OKN3Z5C5.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";function safeTarget(target){if(/^[A-Za-z0-9._-]{55}~[0-9a-f]{8}$/.test(target))return target;const flat=target.replace(/[^A-Za-z0-9._-]/g,"_").replace(/\.\.+/g,"_");const stem=flat.replace(/^[._]+/,"")||"target";if(stem.length<=SAFE_TARGET_MAX)return stem;return`${stem.slice(0,SAFE_TARGET_MAX-9)}~${createHash("sha256").update(stem).digest("hex").slice(0,8)}`}__name(safeTarget,"safeTarget");var SAFE_TARGET_MAX=64;init_esbuild_shims();var MAX_OLD_SPACE_FLAG="--max[-_]old[-_]space[-_]size";var HEAP_TOKEN_RE=new RegExp(`(?:^|\\s)${MAX_OLD_SPACE_FLAG}(?:=(\\d*)|\\s+(\\d+))?(?=\\s|$)`,"g");function heapFlagMb(options){let mb;for(const m of options.matchAll(HEAP_TOKEN_RE)){const value=m[1]||m[2];if(value)mb=Number(value)}return mb}__name(heapFlagMb,"heapFlagMb");function withoutHeapFlag(options){return options.replace(HEAP_TOKEN_RE,"").trim()}__name(withoutHeapFlag,"withoutHeapFlag");function raiseHeap(options,mb){if((heapFlagMb(options)??0)>=mb)return void 0;return`${withoutHeapFlag(options)} --max-old-space-size=${mb}`.trim()}__name(raiseHeap,"raiseHeap");var NPM_ENV_REF_RE=/(?<!\\)(\\*)\$\{([^${}]+)\}/g;function raiseNpmHeap(options,mb){return raiseHeap(options,mb)?.replace(NPM_ENV_REF_RE,(_,esc,name)=>`${esc}${esc}\\\${${name}}`)}__name(raiseNpmHeap,"raiseNpmHeap");var HEAP_BANNER_RE=/^FATAL ERROR: [^\n]*JavaScript heap out of memory/m;function heapBannerIn(raw){return HEAP_BANNER_RE.test(raw)}__name(heapBannerIn,"heapBannerIn");function ranOutOfHeap(r){return r.exitCode!==0&&(r.heapExhausted??heapBannerIn(r.output))}__name(ranOutOfHeap,"ranOutOfHeap");function killedFromOutside(r){return!r.timedOut&&r.spawnError===void 0&&(r.exitCode===137||r.exitCode===null&&r.signal==="SIGKILL")}__name(killedFromOutside,"killedFromOutside");init_esbuild_shims();import{existsSync,readFileSync,readdirSync,realpathSync,statSync}from"node:fs";import{isAbsolute,join,relative}from"node:path";init_esbuild_shims();function stripComments(src){return src.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,m=>m.startsWith("/")?" ":m)}__name(stripComments,"stripComments");function isWorkspaceMember(filePath,workspaceGlobs){return workspaceDirFor(filePath,workspaceGlobs)!==null}__name(isWorkspaceMember,"isWorkspaceMember");function workspaceDirFor(filePath,workspaceGlobs){const norm=filePath.replace(/^\.\//,"");let owner=null;const previous=[];for(const glob of workspaceGlobs){const negated=glob.startsWith("!");const g=glob.replace(/^!/,"").replace(/^\.\//,"").replace(/\/$/,"");let dir=null;if(g.endsWith("/*")){const base=g.slice(0,-2);if(norm.startsWith(`${base}/`)){const seg=norm.slice(base.length+1).split("/")[0];if(seg)dir=`${base}/${seg}`}}else if(norm===g||norm.startsWith(`${g}/`)){dir=g}if(dir===null)continue;if(!negated){if(dir!==owner){previous.push(owner);owner=dir}}else if(dir===owner){owner=previous.pop()??null}}return owner}__name(workspaceDirFor,"workspaceDirFor");function isNegationExcluded(filePath,workspaceGlobs){if(workspaceDirFor(filePath,workspaceGlobs)!==null)return false;const positives=workspaceGlobs.filter(g=>!g.startsWith("!"));return workspaceDirFor(filePath,positives)!==null}__name(isNegationExcluded,"isNegationExcluded");function hasUnmodeledWorkspaceGlob(globs){return globs.some(glob=>{const g=glob.replace(/^!/,"").replace(/^\.\//,"");if(!g.includes("*"))return false;return!/^[^*]+\/\*$/.test(g)})}__name(hasUnmodeledWorkspaceGlob,"hasUnmodeledWorkspaceGlob");function readWorkspaceGlobs(root){try{const pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"));const ws=pkg.workspaces;const globs=Array.isArray(ws)?ws:Array.isArray(ws?.packages)?ws.packages:[];return globs.filter(g=>typeof g==="string")}catch{return[]}}__name(readWorkspaceGlobs,"readWorkspaceGlobs");function readRootPackage(root){let pkg;try{pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"))}catch{return null}if(pkg===null)return null;const scripts=Object.keys(pkg.scripts??{});if(!scripts.includes("build")&&!scripts.includes("test"))return null;const scriptsText={};for(const[k,v]of Object.entries(pkg.scripts??{})){if(typeof v==="string")scriptsText[k]=v}return{dir:".",name:typeof pkg.name==="string"&&pkg.name?pkg.name:"root",scripts,deps:declaredDeps(pkg),scriptsText}}__name(readRootPackage,"readRootPackage");function scriptFansOut(text){return typeof text==="string"&&(/(^|\s)(--workspaces|--?ws)(?=[\s'"`]|$)/.test(text)||/\bpnpm\s+(-r|--recursive)(?=[\s'"`]|$)/.test(text))}__name(scriptFansOut,"scriptFansOut");var COMMAND_SEPARATOR_RE=/[;&|\n]+/;function chainsCommands(text){return text.split(COMMAND_SEPARATOR_RE).filter(c=>c.trim()!=="").length>1}__name(chainsCommands,"chainsCommands");var NODE_VALUE_FLAGS=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--env-file-if-exists","--input-type","--title","--redirect-warnings","--watch-path","--diagnostic-dir","--report-dir","--cpu-prof-dir","--heap-prof-dir","--icu-data-dir","--openssl-config"]);var SCRIPT_RUNNERS=new Set(["node","tsx"]);var NODE_INLINE_FLAGS=new Set(["-e","--eval","-p","--print","-"]);function nodeScripts(text){const files=[];for(const command of text.split(COMMAND_SEPARATOR_RE)){const words=command.trim().split(/\s+/);const runner=words.findIndex(w=>SCRIPT_RUNNERS.has(w));for(let i=runner+1;i>0&&i<words.length;i++){const word=words[i];if(NODE_INLINE_FLAGS.has(word))break;if(word.startsWith("-")){if(NODE_VALUE_FLAGS.has(word))i++;continue}if(/^[\w@./-]+\.[cm]?[jt]s$/.test(word))files.push(word);break}}return files}__name(nodeScripts,"nodeScripts");function childProcessCommands(src){const commands=[];for(const m of stripComments(src).matchAll(/\b(?:exec|execSync|execFile|execFileSync|spawn|spawnSync)\s*\(\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`)/g)){commands.push(m[1].slice(1,-1))}return commands}__name(childProcessCommands,"childProcessCommands");var MAX_HAND_OFF_SCRIPT_BYTES=1024*1024;function rootBuildFanOutScript(root,text){if(typeof text!=="string")return void 0;for(const file of nodeScripts(text)){try{const path=realpathSync(join(root,file));const inRoot=relative(realpathSync(root),path);if(inRoot.startsWith("..")||isAbsolute(inRoot))continue;const stat=statSync(path);if(!stat.isFile()||stat.size>MAX_HAND_OFF_SCRIPT_BYTES)continue;if(childProcessCommands(readFileSync(path,"utf8")).some(scriptFansOut))return file}catch{}}return void 0}__name(rootBuildFanOutScript,"rootBuildFanOutScript");function declaredBuildHeapMb(root){const text=readRootPackage(root)?.scriptsText["build"];if(typeof text!=="string")return void 0;let declared;for(const m of text.matchAll(/\bNODE_OPTIONS=(?:"([^"]*)"|'([^']*)'|(\S*))/g)){const mb=heapFlagMb(m[1]??m[2]??m[3]??"");if(mb!==void 0)declared=Math.max(declared??0,mb)}return declared}__name(declaredBuildHeapMb,"declaredBuildHeapMb");function declaredDeps(pkg){return[...Object.keys(pkg.dependencies??{}),...Object.keys(pkg.devDependencies??{}),...Object.keys(pkg.peerDependencies??{}),...Object.keys(pkg.optionalDependencies??{})]}__name(declaredDeps,"declaredDeps");function workspaceDirCandidates(root,globs){const dirs=new Set;for(const glob of globs){if(glob.startsWith("!"))continue;const g=glob.replace(/^\.\//,"").replace(/\/$/,"");if(g.endsWith("/*")){const base=g.slice(0,-2);let entries;try{entries=readdirSync(join(root,base),{withFileTypes:true}).filter(e=>e.isDirectory()||e.isSymbolicLink()&&existsSync(join(root,base,e.name,"package.json"))).map(e=>e.name)}catch{continue}for(const e of entries)dirs.add(`${base}/${e}`)}else{dirs.add(g)}}return[...dirs].sort()}__name(workspaceDirCandidates,"workspaceDirCandidates");function readWorkspacePackages(root){const globs=readWorkspaceGlobs(root);const packages=[];const skipped=[];for(const dir of workspaceDirCandidates(root,globs)){const manifest=join(root,dir,"package.json");if(!existsSync(manifest))continue;if(workspaceDirFor(`${dir}/package.json`,globs)!==dir){const positives=globs.filter(g=>!g.startsWith("!"));if(workspaceDirFor(`${dir}/package.json`,positives)===dir)continue;skipped.push(dir);continue}let pkg;try{pkg=JSON.parse(readFileSync(manifest,"utf8"))}catch{skipped.push(dir);continue}if(pkg===null||typeof pkg.name!=="string"||!pkg.name){skipped.push(dir);continue}packages.push({dir,name:pkg.name,scripts:Object.keys(pkg.scripts??{}),deps:declaredDeps(pkg)})}packages.sort((a,b)=>a.dir.localeCompare(b.dir));skipped.sort();return{packages,skipped}}__name(readWorkspacePackages,"readWorkspacePackages");function affectedWorkspaces(changedFiles,workspaceGlobs){const dirs=new Set;for(const f of changedFiles){const d=workspaceDirFor(f,workspaceGlobs);if(d)dirs.add(d)}return[...dirs].sort()}__name(affectedWorkspaces,"affectedWorkspaces");function dependencyEdges(packages){const byName=new Map;for(const p of packages){if(p.dir!=="."||!byName.has(p.name))byName.set(p.name,p)}const dependsOn=new Map;for(const p of packages){dependsOn.set(p.dir,p.deps.map(d=>byName.get(d)?.dir).filter(d=>!!d&&d!==p.dir))}return dependsOn}__name(dependencyEdges,"dependencyEdges");function reverseDependencyClosure(affected,packages){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=new Set(affected.filter(a=>byDir.has(a)));let grew=true;while(grew){grew=false;for(const p of packages){if(consumers.has(p.dir))continue;if((dependsOn.get(p.dir)??[]).some(d=>consumers.has(d))){consumers.add(p.dir);grew=true}}}return[...consumers].sort()}__name(reverseDependencyClosure,"reverseDependencyClosure");function buildSetFor(affected,packages,alsoBuild=[]){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=reverseDependencyClosure(affected,packages);const wanted=new Set;const addDeps=__name(dir=>{if(wanted.has(dir))return;wanted.add(dir);for(const d of dependsOn.get(dir)??[])addDeps(d)},"addDeps");for(const c of consumers)addDeps(c);for(const extra of alsoBuild)if(byDir.has(extra))addDeps(extra);const order=[];const seen=new Set;const visit=__name(dir=>{if(seen.has(dir))return;seen.add(dir);for(const d of dependsOn.get(dir)??[]){if(wanted.has(d))visit(d)}order.push(dir)},"visit");for(const dir of alsoBuild.filter(d=>wanted.has(d)).sort())visit(dir);for(const dir of[...wanted].sort())visit(dir);return order}__name(buildSetFor,"buildSetFor");init_esbuild_shims();import{spawnSync as spawnSync2}from"node:child_process";import{accessSync,constants,existsSync as existsSync4,lstatSync as lstatSync3,mkdirSync as mkdirSync2,mkdtempSync,readdirSync as readdirSync3,readFileSync as readFileSync2,realpathSync as realpathSync4,rmSync as rmSync2,statSync as statSync3,symlinkSync,writeFileSync}from"node:fs";import{homedir,tmpdir}from"node:os";import{basename,dirname as dirname3,isAbsolute as isAbsolute3,join as join3,resolve as resolve3,sep as sep2}from"node:path";init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync3,lstatSync as lstatSync2,mkdirSync,readdirSync as readdirSync2,realpathSync as realpathSync3,statSync as statSync2}from"node:fs";import{dirname as dirname2,isAbsolute as isAbsolute2,join as join2,relative as relative2,resolve as resolve2,sep}from"node:path";init_esbuild_shims();import{execFileSync,spawnSync}from"node:child_process";import{existsSync as existsSync2,lstatSync,realpathSync as realpathSync2,rmSync}from"node:fs";import{dirname,resolve}from"node:path";var GIT_TIMEOUT_MS=12e4;function gitOpts(){return{timeout:GIT_TIMEOUT_MS,env:{...sanitizedGitEnv(),GIT_TERMINAL_PROMPT:"0"}}}__name(gitOpts,"gitOpts");var trustedLaunchDir=null;function kernelCwd(){try{const r=spawnSync("/bin/pwd",["-P"],{encoding:"utf8",timeout:5e3,env:sanitizedGitEnv()});if(r.error||r.status!==0||!r.stdout)return null;return r.stdout.replace(/\n$/,"")}catch{return null}}__name(kernelCwd,"kernelCwd");function launchDirRefusal(){const cwd=process.cwd();if(trustedLaunchDir===cwd)return null;if(!insideReviewTmpLexically(cwd)){trustedLaunchDir=cwd;return null}if(process.platform!=="win32"){const kernel=kernelCwd();if(kernel===null){return`the kernel-resolved working directory could not be determined (cwd ${cwd}), so where a command run from here would land is unmeasured`}if(!insideReviewTmpLexically(kernel)){return`the process's working directory was renamed mid-run: the spelling ${cwd} is inside the review temp dir but the kernel reports ${kernel} \u2014 where every command would actually run`}let cachedReal;try{cachedReal=realpathSync2(cwd)}catch{cachedReal=null}if(cachedReal!==kernel){return`the process's working directory spelling ${cwd} resolves to ${cachedReal??"a path that no longer exists"} while the kernel reports ${kernel}: a rename mid-run split them, and every command runs at the kernel's answer`}return untrustedRepositoryFrom(kernel)}return untrustedRepositoryFrom(cwd)}__name(launchDirRefusal,"launchDirRefusal");function assertTrustedLaunchDir(){const refusal=launchDirRefusal();if(refusal!==null){throw new Error(`refusing to run git from this directory: ${refusal}. The command would resolve through that pointer and act on whatever repository it names. Run the review from a checkout outside the review temp dir.`)}}__name(assertTrustedLaunchDir,"assertTrustedLaunchDir");function git(...args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),encoding:"utf8"}).replace(/\r\n/g,"\n").trim()}__name(git,"git");function gitWithEnv(extraEnv,args){assertTrustedLaunchDir();const opts=gitOpts();return execFileSync("git",args,{...opts,env:{...opts.env,...extraEnv},maxBuffer:512*1024*1024,encoding:"utf8"}).replace(/\r\n/g,"\n").trim()}__name(gitWithEnv,"gitWithEnv");function gitWithInput(input,args){return gitWithInputRaw(input,args).replace(/\r\n/g,"\n").trim()}__name(gitWithInput,"gitWithInput");function gitWithInputRaw(input,args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),encoding:"utf8",input,maxBuffer:512*1024*1024})}__name(gitWithInputRaw,"gitWithInputRaw");function gitOpt(...args){return gitProbe(...args).out}__name(gitOpt,"gitOpt");function gitProbe(...args){try{const refusal=launchDirRefusal();if(refusal!==null)return{out:null,status:null,refusal};return{out:execFileSync("git",args,{...gitOpts(),encoding:"utf8",stdio:["ignore","pipe","pipe"]}).replace(/\r\n/g,"\n").trim(),status:0,refusal:null}}catch(err){const status=err.status;return{out:null,status:typeof status==="number"?status:null,refusal:null}}}__name(gitProbe,"gitProbe");function repoRoot(){const first=git("worktree","list","--porcelain").split("\n")[0]??"";if(!first.startsWith("worktree ")){throw new Error(`cannot find the main worktree in: ${first}`)}return first.slice("worktree ".length)}__name(repoRoot,"repoRoot");function refExists(ref){return gitOpt("rev-parse","--verify","--quiet",ref)!==null}__name(refExists,"refExists");function worktreeReleaseResult(existed,stillThere,removeError){const freed=existed&&!stillThere;if(!existed||freed){return{existed,freed,reason:void 0}}return{existed,freed,reason:removeError?removeError instanceof Error?removeError.message:String(removeError):"the path is still there after `git worktree remove --force` and `rm -rf`"}}__name(worktreeReleaseResult,"worktreeReleaseResult");function releaseWorktree(worktreePath2){let redirected;try{redirected=redirectedAncestor(dirname(resolve(worktreePath2)))}catch(err){return worktreeReleaseResult(true,true,err)}if(redirected!==null){return worktreeReleaseResult(true,true,new Error(`refusing to release through a symlink: ${redirected} is a symlink, so the removal would land wherever it points`))}try{if(lstatSync(worktreePath2).isSymbolicLink()){let removeError2;try{rmSync(worktreePath2,{force:true})}catch(e){removeError2=e}const pruned2=gitProbe("worktree","prune");let stillThere2=false;try{lstatSync(worktreePath2);stillThere2=true}catch{}return worktreeReleaseResult(true,stillThere2||pruned2.refusal!==null||pruned2.status===null,removeError2??refusalError(pruned2.refusal)??(pruned2.status===null?couldNotRunError():void 0))}}catch{}const existed=existsSync2(worktreePath2);let removeError;const removed=existed?gitProbe("worktree","remove",worktreePath2,"--force"):null;if(existed){try{rmSync(worktreePath2,{recursive:true,force:true})}catch(e){removeError=e}}const pruned=gitProbe("worktree","prune");const refusal=removed?.refusal??pruned.refusal;const couldNotRun=removed?.status!==0&&pruned.status===null;const stillThere=existsSync2(worktreePath2);return worktreeReleaseResult(existed,stillThere||existed&&couldNotRun,removeError??(couldNotRun?refusalError(refusal)??couldNotRunError():void 0))}__name(releaseWorktree,"releaseWorktree");function couldNotRunError(){return new Error('the `git worktree prune` that frees the registration and the branch could not be run at all (a spawn failure or the timeout kill), so both survive \u2014 the next `git worktree add` over the path will still fail with "missing but already registered". Re-run `qwen review cleanup`.')}__name(couldNotRunError,"couldNotRunError");function refusalError(refusal){if(refusal===null)return void 0;return new Error(`git could not run from this directory \u2014 ${refusal}. The directory is cleared but this worktree's registration and branch were not, so the next \`git worktree add\` over it will still fail. Run \`qwen review cleanup\` from a checkout outside the review temp dir.`)}__name(refusalError,"refusalError");function gitRaw(...args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),maxBuffer:512*1024*1024,stdio:["ignore","pipe","pipe"]})}__name(gitRaw,"gitRaw");function gitRawTolerateDiff(...args){try{return gitRaw(...args)}catch(err){const e=err;if(e.status===1&&e.stdout&&e.stdout.length>0)return e.stdout;throw err}}__name(gitRawTolerateDiff,"gitRawTolerateDiff");init_esbuild_shims();var CONTROL=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;var NEEDS_PRE_ESCAPE=/[\u007f-\u009f\p{Cf}\p{Zl}\p{Zp}]/gu;function inertText(value,maxChars=200){const clipped=value.length>maxChars?value.slice(0,maxChars):value;const rendered=CONTROL.test(clipped)?JSON.stringify(clipped.replace(NEEDS_PRE_ESCAPE,c=>{const hex=c.codePointAt(0).toString(16).padStart(4,"0");return`\\u${hex}`})):clipped;return clipped.length<value.length?`${rendered}\u2026`:rendered}__name(inertText,"inertText");function assertWritableOutPath(out){if(typeof out!=="string"){throw new TypeError(Array.isArray(out)?"--out must be given once, as a file path":"--out must name a file path")}if(out.trim()===""){throw new TypeError("--out must name a file path")}if(/[/\\]$/.test(out.trim())){throw new TypeError(`--out names a directory, not a file: ${out}`)}const resolved=resolve2(out);if(existsSync3(resolved)&&statSync2(resolved).isDirectory()){throw new TypeError(`--out names a directory, not a file: ${out}`)}}__name(assertWritableOutPath,"assertWritableOutPath");var REVIEW_TMP_DIR=join2(".qwen","tmp");var RETIRED_REVIEW_LEASE_DIR=join2(".qwen","review-leases");var REVIEW_TRUST_STATE_DIR="review-state";var REVIEWS_DIR=join2(".qwen","reviews");var REVIEW_CACHE_DIR=join2(".qwen","review-cache");function outermostReviewRepositoryRoot(repositoryRoot){const resolved=resolve2(repositoryRoot);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=(resolved+sep).indexOf(marker);return at<0?resolved:resolved.slice(0,at)}__name(outermostReviewRepositoryRoot,"outermostReviewRepositoryRoot");function canonicalReviewRepositoryRoot(repositoryRoot){let canonical=outermostReviewRepositoryRoot(repositoryRoot);try{canonical=realpathSync3.native(canonical)}catch(error){if(error.code!=="ENOENT")throw error}canonical=outermostReviewRepositoryRoot(canonical);return canonical}__name(canonicalReviewRepositoryRoot,"canonicalReviewRepositoryRoot");function reviewTrustStateDir(repositoryRoot){const digest=getProjectHash(canonicalReviewRepositoryRoot(repositoryRoot));return join2(Storage.getGlobalQwenDir(),REVIEW_TRUST_STATE_DIR,digest)}__name(reviewTrustStateDir,"reviewTrustStateDir");function reviewRepositoryRootForWorktree(worktree){const resolved=resolve2(worktree);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=resolved.indexOf(marker);if(at<0){throw new Error(`cannot place the base-tree trust artifact for ${worktree}: the worktree is not shaped like <root>/.qwen/tmp/<name>, so there is no host-side review directory to key it under`)}return resolved.slice(0,at)}__name(reviewRepositoryRootForWorktree,"reviewRepositoryRootForWorktree");var GENERATED_WORKFLOWS_SUBDIR=join2("workflows","generated");var REVIEW_WORKFLOWS_SUBDIR="review";var REVIEW_WORKFLOW_PREFIX="qwen-review-";var GeneratedWorkflowDirUnavailableError=class extends Error{static{__name(this,"GeneratedWorkflowDirUnavailableError")}};function projectDirFromEnv(env){const projectDir=env["QWEN_CODE_PROJECT_DIR"]?.trim();if(!projectDir){throw new GeneratedWorkflowDirUnavailableError("the CLI did not export QWEN_CODE_PROJECT_DIR, so there is no directory the Workflow tool would load a generated script from. Run this command from inside a qwen session.")}return projectDir}__name(projectDirFromEnv,"projectDirFromEnv");function reviewSessionDirName(session){const digest=createHash2("sha256").update(session).digest("hex").slice(0,8);return`${sanitizeFilenameComponent(session)}-${digest}`}__name(reviewSessionDirName,"reviewSessionDirName");function reviewWorkflowsDir(env=process.env){const session=env["QWEN_CODE_SESSION_ID"]?.trim();return join2(projectDirFromEnv(env),GENERATED_WORKFLOWS_SUBDIR,REVIEW_WORKFLOWS_SUBDIR,session?reviewSessionDirName(session):"no-session")}__name(reviewWorkflowsDir,"reviewWorkflowsDir");function ensureWritableReviewWorkflowsDir(env=process.env){const projectDir=projectDirFromEnv(env);const dir=reviewWorkflowsDir(env);const root=join2(projectDir,GENERATED_WORKFLOWS_SUBDIR);for(const component of[root,join2(root,REVIEW_WORKFLOWS_SUBDIR),dir]){let isLink=false;try{isLink=lstatSync2(component).isSymbolicLink()}catch(err){if(err.code!=="ENOENT")throw err;break}if(isLink){throw new Error(`refusing to write a generated review script through the symlinked directory '${component}' \u2014 it would land outside the generated-workflows root the Workflow loader trusts.`)}}mkdirSync(dir,{recursive:true});const realDir=realpathSync3(dir);const realRoot=realpathSync3(root);if(realDir!==realRoot&&!realDir.startsWith(realRoot+sep)){throw new Error(`refusing to write a generated review script: the canonical session directory '${realDir}' escapes the canonical generated-workflows root '${realRoot}'.`)}return dir}__name(ensureWritableReviewWorkflowsDir,"ensureWritableReviewWorkflowsDir");function reviewWorkflowScriptPath(planPath,script,env=process.env){const resolved=resolve2(planPath);let canonical=resolved;try{canonical=realpathSync3(resolved)}catch{}const digest=createHash2("sha256").update(canonical).digest("hex").slice(0,10);const contentDigest=createHash2("sha256").update(script).digest("hex");return join2(reviewWorkflowsDir(env),`${REVIEW_WORKFLOW_PREFIX}${digest}-${contentDigest}.js`)}__name(reviewWorkflowScriptPath,"reviewWorkflowScriptPath");var LEASE_PREFIX="qwen-review-lease-";var PARSE_ARGS_REPORT=join2(REVIEW_TMP_DIR,"qwen-review-parse-args.json");function lastReviewEffortPath(projectRoot,sessionProjectDir){const owner=sessionProjectDir?.trim()?resolve2(sessionProjectDir):new Storage(projectRoot).getProjectDir();return join2(owner,"review-last-effort")}__name(lastReviewEffortPath,"lastReviewEffortPath");function worktreePath(prNumber){return join2(REVIEW_TMP_DIR,`review-pr-${prNumber}`)}__name(worktreePath,"worktreePath");function probeWorktreePath(worktree){return`${resolve2(worktree)}-probe`}__name(probeWorktreePath,"probeWorktreePath");function baseWorktreePath(worktree){return`${resolve2(worktree)}-base`}__name(baseWorktreePath,"baseWorktreePath");var SCRATCH_INFIX="-scratch-";function scratchWorktreePath(worktree,label){const safe=scratchLabel(label);if(!safe){throw new TypeError(`scratch label ${JSON.stringify(label)} keeps no path-safe character (A-Za-z0-9._-); a tree cannot be named for it`)}return`${resolve2(worktree)}${SCRATCH_INFIX}${safe}`}__name(scratchWorktreePath,"scratchWorktreePath");function scratchWorktreePrefix(worktree){return`${resolve2(worktree)}${SCRATCH_INFIX}`}__name(scratchWorktreePrefix,"scratchWorktreePrefix");function scratchLabel(label){return label.replace(/[^A-Za-z0-9._-]/g,"_").replace(/\.\.+/g,"_").replace(/^[._-]+/,"").slice(0,64)}__name(scratchLabel,"scratchLabel");function reviewBranch(prNumber){return`qwen-review/pr-${prNumber}`}__name(reviewBranch,"reviewBranch");function tmpFile(target,suffix){return join2(REVIEW_TMP_DIR,`qwen-review-${safeTarget(target)}-${suffix}`)}__name(tmpFile,"tmpFile");function tmpPrefix(target){return`qwen-review-${safeTarget(target)}-`}__name(tmpPrefix,"tmpPrefix");function ensureReviewTmpDir(command){for(const dir of[dirname2(REVIEW_TMP_DIR),REVIEW_TMP_DIR]){let isLink=false;try{isLink=lstatSync2(dir).isSymbolicLink()}catch(err){if(err.code!=="ENOENT")throw err;break}if(isLink){throw new Error(`${command}: ${dir} is a symbolic link \u2014 every file this review writes (plan, diff, candidate, stop sidecar, worktree) would land wherever it points, and the plan would be read back from there. Refusing to run; nothing here can tell your own link from a committed one. If it is YOURS \u2014 this directory holds a full worktree per PR, so redirecting it onto other storage is a reasonable thing to have done \u2014 neither ${dirname2(REVIEW_TMP_DIR)} nor ${REVIEW_TMP_DIR} can be one: redirect the checkout itself, or a directory the review never names.`)}}let listing;try{listing=gitRaw("ls-files","-s","-z").toString("utf8")}catch(err){if(insideRepository()){throw new Error(`${command}: could not list the tracked entries under ${REVIEW_TMP_DIR} (${inertText(err.message,2e3)}) \u2014 refusing to run rather than write through a link the listing might have named. Lightweight mode (\`fetch-diff\`) is the one flow that could otherwise proceed without git; every other one needs it for the diff itself.`)}listing=""}const scratch=REVIEW_TMP_DIR.split(sep).join("/").toLowerCase();const planted=listing.split("\0").find(entry=>{const gitlink=entry.startsWith("160000 ");if(!entry.startsWith("120000 ")&&!gitlink)return false;const path=entry.slice(entry.indexOf(" ")+1).toLowerCase();if(path===dirname2(scratch)||path===scratch)return true;if(!path.startsWith(`${scratch}/`))return false;return!gitlink||!isReviewWorktreeName(path.slice(scratch.length+1))});if(planted!==void 0){const path=planted.slice(planted.indexOf(" ")+1);const what=planted.startsWith("160000 ")?"a submodule":"a symbolic link";throw new Error(`${command}: the workspace tracks ${what} at ${inertText(path)} \u2014 on the scratch directory ${REVIEW_TMP_DIR} or a path through it \u2014 and a plain write to that name would follow it out of the tree. Refusing to run; remove it from the index AND the working tree (\`git rm -f -- <path>\`) and retry.`)}const onDisk=roundOwnedLinkOnDisk(command);if(onDisk!==null){throw new Error(`${command}: ${inertText(onDisk)} is a symbolic link on disk, at a name this review writes \u2014 a plain write to it would follow the link out of the tree. Refusing to run; delete the link and retry.`)}mkdirSync(REVIEW_TMP_DIR,{recursive:true})}__name(ensureReviewTmpDir,"ensureReviewTmpDir");function roundOwnedLinkOnDisk(command){const list=__name(dir=>{try{return readdirSync2(dir,{withFileTypes:true})}catch(err){const code=err.code;if(code==="ENOENT"||code==="ENOTDIR")return[];throw new Error(`${command}: could not list ${inertText(dir)} (${inertText(err.message)}) \u2014 refusing to run rather than write through a link the listing might have named.`)}},"list");const walk=__name(dir=>{for(const entry of list(dir)){const path=join2(dir,entry.name);if(entry.isSymbolicLink())return path;if(entry.isDirectory()){const hit=walk(path);if(hit!==null)return hit}}return null},"walk");for(const entry of list(REVIEW_TMP_DIR)){const path=join2(REVIEW_TMP_DIR,entry.name);const name=entry.name.toLowerCase();if(name.startsWith("qwen-review-")){if(entry.isSymbolicLink())return path;if(entry.isDirectory()){const hit=walk(path);if(hit!==null)return hit}}else if(isReviewWorktreeName(name)&&entry.isSymbolicLink()){return path}}return null}__name(roundOwnedLinkOnDisk,"roundOwnedLinkOnDisk");function commandPrefixed(command,message){const prefix=`${command}: `;return message.startsWith(prefix)?message:`${prefix}${message}`}__name(commandPrefixed,"commandPrefixed");function writesIntoReviewTmp(out){const scratch=resolve2(REVIEW_TMP_DIR).toLowerCase();const target=resolve2(out).toLowerCase();return target===scratch||target.startsWith(scratch+sep)}__name(writesIntoReviewTmp,"writesIntoReviewTmp");function isReviewWorktreeName(name){return/^review-pr-\d+(-probe|-base|-scratch-[^/]*)?$/.test(name)}__name(isReviewWorktreeName,"isReviewWorktreeName");function insideRepository(){let dir=resolve2(".");for(;;){if(existsSync3(join2(dir,".git")))return true;const parent=dirname2(dir);if(parent===dir)return false;dir=parent}}__name(insideRepository,"insideRepository");function inertPath(p){return p.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\u2500`]+/gu," ")}__name(inertPath,"inertPath");function canonicalise(abs){const walked=[];let cur=abs;for(;;){try{const real=realpathSync3(cur);return walked.length===0?real:join2(real,...walked.reverse())}catch{const parent=resolve2(cur,"..");if(parent===cur)return abs;walked.push(cur.slice(parent.length).replace(sep==="/"?/^\/+/:/^[\\/]+/,""));cur=parent}}}__name(canonicalise,"canonicalise");function repoRelativeOf(repoRoot2,file,from=process.cwd()){const abs=canonicalise(resolve2(from,file));const rel=relative2(repoRoot2,abs);const escapes=rel===".."||rel.startsWith(".."+sep)||isAbsolute2(rel);return{rel:sep==="/"?rel:rel.split(sep).join("/"),abs,escapes}}__name(repoRelativeOf,"repoRelativeOf");function assertUnredirectedParent(target,what,command){const parent=resolve2(dirname2(target));let real;try{real=realpathSync3(parent)}catch(err){throw new Error(`${command}: cannot resolve the ${what} directory ${inertText(parent)}: `+inertText(err.message))}if(real!==parent){throw new Error(`${command}: the ${what} directory ${inertText(parent)} resolves to ${inertText(real)} \u2014 a symlink in the path would redirect this write outside the tree it names. Refusing.`)}}__name(assertUnredirectedParent,"assertUnredirectedParent");var GIT_ENV_REDIRECTS=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_COMMON_DIR"];var GIT_ENV_CONFIG=["GIT_CONFIG_COUNT","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_PARAMETERS","GIT_DEFAULT_HASH"];var GIT_ENV_EXEC=["GIT_SSH_COMMAND","GIT_SSH","GIT_EXEC_PATH","GIT_TEMPLATE_DIR","GIT_ASKPASS","GIT_PROXY_COMMAND","GIT_EDITOR","GIT_SEQUENCE_EDITOR","GIT_EXTERNAL_DIFF","XDG_CONFIG_HOME"];function mountRootFor(cwd){return mountRootVerdict(cwd).root}__name(mountRootFor,"mountRootFor");function mountNullKind(cwd){return mountRootVerdict(cwd).nullKind??"refused"}__name(mountNullKind,"mountNullKind");function mountRootVerdict(cwd){const resolved=resolve3(cwd);const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;const at=(resolved+sep2).lastIndexOf(marker);if(at<0)return{root:null,nullKind:"outside"};const root=resolved.slice(0,at+marker.length-1);const outermost=outermostReviewTmpRoot(root);const bound=outermost===root?resolve3(root,".."):outermost;try{if(redirectedAncestor(root,bound)!==null){return{root:null,nullKind:"refused"}}const real=realpathSync4(root);if(unmountableRootSpelling(real)){return{root:null,nullKind:"unmountable"}}return{root:real,nullKind:null}}catch{return{root:null,nullKind:"refused"}}}__name(mountRootVerdict,"mountRootVerdict");function unmountableRootSpelling(root){return root.includes(":")||root.startsWith("\\\\")}__name(unmountableRootSpelling,"unmountableRootSpelling");function insideReviewTmpLexically(cwd){const resolved=resolve3(cwd);const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;return(resolved+sep2).lastIndexOf(marker)>=0}__name(insideReviewTmpLexically,"insideReviewTmpLexically");function resolvedGitDir(cwd){return revParse(cwd,"--absolute-git-dir")}__name(resolvedGitDir,"resolvedGitDir");function resolvedCommonDir(cwd){return revParse(cwd,"--path-format=absolute","--git-common-dir")}__name(resolvedCommonDir,"resolvedCommonDir");function revParse(cwd,...flags){const resolved=spawnSync2("git",["-c","core.hooksPath=/dev/null/no-hooks","-c","core.fsmonitor=","rev-parse",...flags],{cwd,encoding:"utf8",timeout:3e4,env:{...sanitizedGitEnv(),LC_ALL:"C"}});const value=resolved.error||resolved.status!==0||!resolved.stdout?null:resolved.stdout.replace(/\n$/,"");return{value:value!==null&&value.includes("\uFFFD")?null:value,notARepository:resolved.status===128&&resolved.stderr.includes("not a git repository")}}__name(revParse,"revParse");function untrustedPointer(dir,gitDir,expectedOwner,root){if(adminEntryInsideReviewTmp(gitDir,root,dir)){return"resolves to an admin entry inside the review temp dir, where the reviewed code can rewrite it"}const common=resolvedCommonDir(dir);if(common.value===null&&!common.notARepository){return"git could not resolve its own common dir from this tree, so whether the pointer names the main repository instead of a linked worktree's admin entry is unknown"}if(common.value!==null&&common.value===gitDir){return"resolves to the repository's own common dir rather than a linked worktree's admin entry, so every command through it acts on the main repository instead of this tree"}let backpointer;try{backpointer=readFileSync2(join3(gitDir,"gitdir"),"utf8").replace(/\n$/,"")}catch{return null}const ownerSpelled=dirname3(resolve3(gitDir,backpointer));let ownerTree;try{ownerTree=realpathSync4(ownerSpelled)}catch{ownerTree=null}const writableRoot=outermostReviewTmpRoot(root);if(ownerSpelled===writableRoot||isSubpath(writableRoot,ownerSpelled)){const redirect=redirectedAncestor(ownerSpelled,writableRoot);if(redirect!==null){return`resolves to a different tree's admin entry \u2014 the owner its gitdir backpointer names resolves through a symlink inside the review temp dir (${redirect}), so the round trip would agree with whatever the link points at`}}let expectedReal;try{expectedReal=realpathSync4(expectedOwner)}catch{return"could not resolve the tree the entry must belong to"}if(ownerTree===null){return"resolves to an admin entry that does not point back at this tree \u2014 the owner its backpointer names cannot be resolved, so the commands this gates would measure whichever repository it does name"}if(ownerTree!==expectedReal){return"resolves to a different tree's admin entry \u2014 its gitdir backpointer names that tree, not this one, so every command through it would measure and mutate the tree it actually belongs to"}return null}__name(untrustedPointer,"untrustedPointer");function untrustedRepositoryFrom(cwd,mountRoot=mountRootFor){const root=mountRoot(cwd);if(root===null){if(mountNullKind(cwd)!=="refused")return null;return`${cwd}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command run from here would land is unmeasured`}if(!existsSync4(cwd)){if(!insideReviewTmpLexically(cwd))return null;return`${cwd}: no directory exists at this spelling inside the review temp dir \u2014 an ancestor was renamed out from under it, so where a command run from here would land is unmeasured`}const target=resolvedGitDir(cwd);if(target.value===null){return target.notARepository?null:`${cwd}: git could not resolve its own git dir, so where a command run from here would land is unmeasured`}const toplevel=revParse(cwd,"--show-toplevel");if(toplevel.value===null){return`${cwd}: git could not resolve its own top-level directory, so where a command run from here would land is unmeasured`}const why=untrustedPointer(cwd,target.value,toplevel.value,root);return why===null?null:`${cwd} ${why}`}__name(untrustedRepositoryFrom,"untrustedRepositoryFrom");function untrustedGitfile(tree,mountRoot=mountRootFor){if(!existsSync4(tree))return null;const root=mountRoot(tree);if(root===null){if(mountNullKind(tree)!=="refused")return null;return`${tree}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command through its .git would land is unmeasured`}const dotGit=join3(tree,".git");let stat;try{stat=lstatSync3(dotGit)}catch{return`${tree} has no .git to resolve`}if(!stat.isFile()){return`${tree}'s .git is not the gitfile the pipeline created, and the tree is inside the review temp dir`}const target=resolvedGitDir(tree);if(target.value===null){return`${tree}: git could not resolve its own git dir`}const why=untrustedPointer(tree,target.value,tree,root);return why===null?null:`${tree} ${why}`}__name(untrustedGitfile,"untrustedGitfile");function adminEntryInsideReviewTmp(gitDir,root,tree){if(root===null)return mountNullKind(tree)==="refused";let real;let realRoot;try{const canonical=realpathSync4.native??realpathSync4;real=canonical(resolve3(gitDir));realRoot=canonical(root)}catch{return true}return isSubpath(outermostReviewTmpRoot(realRoot),real)}__name(adminEntryInsideReviewTmp,"adminEntryInsideReviewTmp");function outermostReviewTmpRoot(root){const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;const at=root.indexOf(marker);return at<0?root:root.slice(0,at+marker.length-1)}__name(outermostReviewTmpRoot,"outermostReviewTmpRoot");function redirectedAncestor(dir,stopAt=process.cwd()){try{const stop=resolve3(stopAt);let stopReal=stop;try{stopReal=realpathSync4(stopAt)}catch{}for(let cur=resolve3(dir);;cur=dirname3(cur)){let isLink;try{isLink=lstatSync3(cur).isSymbolicLink()}catch{isLink=false}if(isLink)return cur;if(cur===stop)return null;try{if(realpathSync4(cur)===stopReal)return null}catch{}if(dirname3(cur)===cur)return null}}catch{return null}}__name(redirectedAncestor,"redirectedAncestor");function sanitizedGitEnv(){const env={...process.env};const drop=new Set([...GIT_ENV_REDIRECTS,...GIT_ENV_CONFIG,...GIT_ENV_EXEC].map(k=>k.toLowerCase()));for(const key of Object.keys(env)){const lower=key.toLowerCase();if(drop.has(lower)||/^git_config_(key|value)_\d+$/.test(lower)){delete env[key]}}env["GIT_NO_REPLACE_OBJECTS"]="1";env["GIT_GRAFT_FILE"]="/dev/null/grafts";return env}__name(sanitizedGitEnv,"sanitizedGitEnv");var MAX_INCLUDE_DEPTH=10;var MAX_INCLUDE_FILES=64;var FILTER_SCREEN_NAMED=12;var SCREEN_KEYS="^filter\\..*\\.(smudge|clean|process)$|^include\\.path$|^includeif\\..*\\.path$";function filterCommandsIn(commonDir,gitDir){const candidates=[join3(commonDir,"config"),join3(gitDir,"config.worktree")];try{for(const entry of readdirSync3(join3(commonDir,"worktrees"))){candidates.push(join3(commonDir,"worktrees",entry,"config.worktree"))}}catch{}const filters=new Set;const unread=new Set;const dangling=new Set;const visited=new Set;const read=__name(file=>{const r=spawnSync2("git",["config","--file",file,"-z","--get-regexp",SCREEN_KEYS],{cwd:commonDir,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error){return{unreadable:r.error.code??r.error.message}}if(r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return{unreadable:`git config exited ${r.status}`}}const records=[];for(const rec of r.stdout.split("\0")){if(!rec)continue;const nl=rec.indexOf("\n");records.push(nl===-1?[rec,""]:[rec.slice(0,nl),rec.slice(nl+1)])}return{records}},"read");const visit=__name((file,depth,via)=>{let real;try{real=realpathSync4.native(file)}catch(e){if(via!==null){const code=e?.code;if(code==="ENOENT"){dangling.add(`${via} -> ${file} (missing \u2014 git ignores it)`)}else{unread.add(`${via} -> ${file} (could not be resolved: ${code??"unknown"} \u2014 not screened)`)}}return}if(visited.has(real))return;if(visited.size>=MAX_INCLUDE_FILES){unread.add(`${via??file} -> ${file} (include fan-out past ${MAX_INCLUDE_FILES} files \u2014 not screened)`);return}visited.add(real);try{if(!statSync3(real).isFile()){unread.add(`${via??file} -> ${file} (not a regular file \u2014 not screened)`);return}accessSync(real,constants.R_OK)}catch{unread.add(`${via??file} -> ${file} (could not be read)`);return}if(depth>MAX_INCLUDE_DEPTH){unread.add(`${via} -> ${file} (nested past git's include limit \u2014 not screened)`);return}const r=read(file);if("unreadable"in r){unread.add(`${file} (could not be read: ${r.unreadable})`);return}for(const[key,value]of r.records){if(key.startsWith("filter.")){filters.add(key);continue}let target;if(value.startsWith("~/")){target=`${process.env["HOME"]||homedir()}${sep2}${value.slice(2)}`}else if(value.startsWith("~")){unread.add(`${key} -> ${value} (another user's home \u2014 not resolved here)`);continue}else{target=isAbsolute3(value)?value:`${dirname3(file)}${sep2}${value}`}visit(target,depth+1,`${key} (in ${file})`)}},"visit");for(const candidate of candidates)visit(candidate,0,null);return{filters:[...filters],unread:[...unread],dangling:[...dangling]}}__name(filterCommandsIn,"filterCommandsIn");function describeFilterScreen(hits){const named=hits.slice(0,FILTER_SCREEN_NAMED);const rest=hits.length-named.length;return rest>0?`${named.join(", ")}, and ${rest} more`:named.join(", ")}__name(describeFilterScreen,"describeFilterScreen");function filterBlankEnv(filterKeys){const names=new Set;for(const key of filterKeys){const m=/^filter\.(.+)\.(?:smudge|clean|process)$/.exec(key);if(m)names.add(m[1])}const env={};let n=0;for(const name of names){for(const[key,value]of[["clean",""],["smudge",""],["process",""],["required","false"]]){env[`GIT_CONFIG_KEY_${n}`]=`filter.${name}.${key}`;env[`GIT_CONFIG_VALUE_${n}`]=value;n++}}if(n>0)env["GIT_CONFIG_COUNT"]=String(n);return env}__name(filterBlankEnv,"filterBlankEnv");var UNRESOLVED_REPO="the repository's git directories could not be resolved (git rev-parse failed) \u2014 not screened";function screenForTree(worktree){const discover=__name(flag=>{const r=spawnSync2("git",["rev-parse","--path-format=absolute",flag],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return null}return r.stdout.endsWith("\n")?r.stdout.slice(0,-1):r.stdout},"discover");const commonDir=discover("--git-common-dir");const gitDir=discover("--git-dir");if(commonDir===null||gitDir===null)return null;return filterCommandsIn(commonDir,gitDir)}__name(screenForTree,"screenForTree");function localFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread,...screen.dangling]}__name(localFilterCommands,"localFilterCommands");function filterScreenForTree(worktree){return screenForTree(worktree)}__name(filterScreenForTree,"filterScreenForTree");function resolvedContentTransformForTree(worktree){const r=spawnSync2("git",["config","--get-regexp","^filter\\..*\\.(smudge|clean|process)$|^core\\.(autocrlf|eol)$"],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.status!==0||typeof r.stdout!=="string")return false;for(const line of r.stdout.split("\n")){const space=line.indexOf(" ");const key=(space===-1?line:line.slice(0,space)).toLowerCase();const value=space===-1?"true":line.slice(space+1).trim().toLowerCase();if(key.startsWith("filter."))return true;if(key==="core.autocrlf"&&(value==="true"||value==="input")){return true}if(key==="core.eol"&&(value==="crlf"||value==="native"&&process.platform==="win32")){return true}}return false}__name(resolvedContentTransformForTree,"resolvedContentTransformForTree");function checkoutFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread]}__name(checkoutFilterCommands,"checkoutFilterCommands");function discardWorktree(cwd,tree){let symlink=false;try{symlink=lstatSync3(tree).isSymbolicLink()}catch{}const ownAdminDir=adminDirOf(tree);let sweep;if(!symlink){sweep=spawnSync2("git",["worktree","remove","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(sweep.status!==0){spawnSync2("git",["worktree","unlock",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});sweep=spawnSync2("git",["worktree","remove","--force","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()})}}rmSync2(tree,{recursive:true,force:true});dropWorktreeRegistration(cwd,tree,ownAdminDir);if(sweep!==void 0&&sweep.status!==0){dropWorktreeRegistration(cwd,tree,null)}return sweep}__name(discardWorktree,"discardWorktree");function dropWorktreeRegistration(cwd,tree,adminDir){if(adminDir!==null){try{rmSync2(adminDir,{recursive:true,force:true})}catch{}return}const common=spawnSync2("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(common.status!==0||typeof common.stdout!=="string")return;const dir=join3(common.stdout.trim(),"worktrees");let ids;try{ids=readdirSync3(dir)}catch{return}const wanted=samePath(tree);const ownId=basename(resolve3(tree));const ownIdPattern=new RegExp(`^${ownId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\d*$`);for(const id of ids){if(!ownIdPattern.test(id))continue;try{const gitdir=readFileSync2(join3(dir,id,"gitdir"),"utf8").trim();const named=dirname3(gitdir);if(samePath(named)!==wanted)continue;if(existsSync4(named))continue;rmSync2(join3(dir,id),{recursive:true,force:true})}catch{}}}__name(dropWorktreeRegistration,"dropWorktreeRegistration");function adminDirOf(tree){try{const pointer=readFileSync2(join3(tree,".git"),"utf8").trim();const match=/^gitdir:\s*(.+)$/.exec(pointer);if(!match)return null;const dir=resolve3(dirname3(resolve3(tree)),match[1].trim());const back=readFileSync2(join3(dir,"gitdir"),"utf8").trim();return samePath(dirname3(back))===samePath(tree)?dir:null}catch{return null}}__name(adminDirOf,"adminDirOf");function samePath(p){const abs=resolve3(p);try{return join3(realpathSync4(dirname3(abs)),basename(abs))}catch{return abs}}__name(samePath,"samePath");var pipelineExcludesFile=null;function pipelineExcludeArgs(){if(pipelineExcludesFile===null){try{const file=join3(mkdtempSync(join3(tmpdir(),"qwen-review-excludes-")),"excludes").split(sep2).join("/");writeFileSync(file,"node_modules/\ndist/\n",{flag:"wx",mode:384});pipelineExcludesFile=file}catch{pipelineExcludesFile=""}}return pipelineExcludesFile===""?[]:["-c",`core.excludesFile=${pipelineExcludesFile}`]}__name(pipelineExcludeArgs,"pipelineExcludeArgs");function inPipelineFootprint(rec){const parts=rec.split("/");for(let i=0;i<parts.length-1;i++){if(parts[i]==="node_modules"||parts[i]==="dist")return true;if(parts[i]===".husky"&&parts[i+1]==="_"&&i+1<parts.length-1)return true}return false}__name(inPipelineFootprint,"inPipelineFootprint");function ignoreSourcesOf(cwd,paths,anchor=[]){const r=spawnSync2("git",[...anchor,...pipelineExcludeArgs(),"check-ignore","-z","-v","--stdin"],{cwd,input:`${paths.join("\0")}\0`,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return null}const fields=r.stdout.split("\0");const rules=new Map;for(let i=0;i+3<fields.length;i+=4){rules.set(fields[i+3],{source:fields[i],pattern:fields[i+2]})}return rules}__name(ignoreSourcesOf,"ignoreSourcesOf");function hidesEverything(pattern){const core=pattern.replace(/^\//,"").replace(/\/$/,"");if(core.length===0)return false;const segments=core.split("/");return core.includes("*")&&segments.every(seg=>/^[*?]+$/.test(seg))}__name(hidesEverything,"hidesEverything");function trackedIgnoreSources(cwd,sources,anchor=[]){const inside=[...sources].filter(s=>s.length>0&&!isAbsolute3(s)&&!s.split("/").some(p=>p===".."));if(inside.length===0)return new Set;const r=spawnSync2("git",[...anchor,"ls-files","-z","--",...inside],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return new Set}return new Set(r.stdout.split("\0").filter(p=>p.length>0))}__name(trackedIgnoreSources,"trackedIgnoreSources");var RESIDUE_PATH_CAP=12;function worktreeResidue(cwd,cap=RESIDUE_PATH_CAP,expectedHeadSha){try{if(!lstatSync3(join3(cwd,".git")).isFile()){return{paths:[],total:0,unmeasured:".git is not a gitfile (a planted repository?) \u2014 a repo stood up at this path answers a clean status for a dirty tree, and the probe cannot tell the two apart"}}}catch{}const root=mountRootFor(cwd);if(root===null){if(mountNullKind(cwd)==="refused"){return{paths:[],total:0,unmeasured:"the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, and the status below would measure whichever repository the pointer here names"}}}else{const target=resolvedGitDir(cwd);let why;if(target.value!==null){why=untrustedPointer(cwd,target.value,cwd,root)}else{why=target.notARepository?null:"git could not resolve its own git dir"}if(why!==null){return{paths:[],total:0,unmeasured:`the .git gitfile ${why} \u2014 the status below would measure whichever repository it names, and refresh that index through whatever filters it configures`}}}const discover=__name(flag=>{const r2=spawnSync2("git",["rev-parse","--path-format=absolute",flag],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(r2.error||r2.status!==0||typeof r2.stdout!=="string"){return null}return r2.stdout.endsWith("\n")?r2.stdout.slice(0,-1):r2.stdout},"discover");const toplevel=discover("--show-toplevel");const gitDir=discover("--git-dir");const commonDir=discover("--git-common-dir");let isWorktree=false;let anchor=[];let filterBlanks={};try{if(toplevel!==null&&gitDir!==null&&commonDir!==null&&realpathSync4(toplevel)===realpathSync4(cwd)){isWorktree=true;if(lstatSync3(cwd).isSymbolicLink()){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${resolve3(cwd)}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}const spelled=resolve3(cwd);const bound=dirname3(commonDir);const redirected=redirectedAncestor(dirname3(spelled),bound);if(redirected!==null){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${redirected}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}let backpointer=null;try{backpointer=readFileSync2(join3(gitDir,"gitdir"),"utf8").trim()}catch{}if(backpointer===null){return{paths:[],total:0,unmeasured:"the .git gitfile names a repository with no admin entry for this tree \u2014 a standalone repository answering for this path, whose index the commands below would measure"}}let pointsBack=false;try{pointsBack=realpathSync4(dirname3(resolve3(gitDir,backpointer)))===realpathSync4(cwd)}catch{}if(!pointsBack){return{paths:[],total:0,unmeasured:"the .git gitfile names an admin entry that does not point back at this tree \u2014 the commands below would measure whichever repository it does name"}}anchor=[`--git-dir=${realpathSync4(gitDir)}`,`--work-tree=${realpathSync4(toplevel)}`];if(expectedHeadSha!==void 0){const head=spawnSync2("git",[...anchor,"rev-parse","HEAD"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});const got=head.error||head.status!==0||typeof head.stdout!=="string"?null:head.stdout.trim();if(got===null||got.toLowerCase()!==expectedHeadSha.toLowerCase()){return{paths:[],total:0,unmeasured:got===null?"the pinned identity could not read its own HEAD \u2014 the commands below would have measured a repository git cannot read":`the pinned identity is checked out at ${got}, not the fetched PR head ${expectedHeadSha} \u2014 the gitfile names a repository answering for this path, and its index is what the commands below would measure`}}}const screen=filterCommandsIn(commonDir,realpathSync4(gitDir));const notReadToTheBottom=[...screen.unread,...screen.dangling];if(notReadToTheBottom.length>0){return{paths:[],total:0,unmeasured:`the residue measurement would run under repo-local config this screen could not read to the bottom: ${describeFilterScreen(notReadToTheBottom)} \u2014 a content filter reached that way would execute on the index refresh, and a filter the screen cannot see it cannot blank; remove the include, or the file it names, if it is not yours`}}filterBlanks=filterBlankEnv(screen.filters)}}catch{isWorktree=false}if(!isWorktree){return{paths:[],total:0,unmeasured:"the path is not a git worktree (repository discovery walks up into the enclosing checkout)"}}const r=spawnSync2("git",[...anchor,...pipelineExcludeArgs(),"-c","core.fsmonitor=","-c","core.hooksPath=/dev/null/no-hooks","status","--porcelain","--untracked-files=all","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:{...sanitizedGitEnv(),...filterBlanks}});if(r.error||r.status!==0||typeof r.stdout!=="string"){const why=r.error?r.error.code??r.error.message:`git status exited ${r.status}`;return{paths:[],total:0,unmeasured:why}}const records=r.stdout.split("\0").filter(rec=>rec.length>0);const paths=[];for(let i=0;i<records.length;i++){const rec=records[i];const status=rec.slice(0,2);paths.push(rec.slice(3));if((status.includes("R")||status.includes("C"))&&i+1<records.length){paths.push(records[++i])}}const others=spawnSync2("git",[...anchor,"-c","core.fsmonitor=","ls-files","--others","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(others.error||others.status!==0||typeof others.stdout!=="string"){const why=others.error?others.error.code??others.error.message:`git ls-files exited ${others.status}`;return{paths:[],total:0,unmeasured:why}}const seen=new Set(paths);const editedFromHead=new Set(paths);const extras=[];for(const rec of others.stdout.split("\0")){if(rec.length===0||seen.has(rec))continue;if(inPipelineFootprint(rec))continue;seen.add(rec);extras.push(rec)}if(extras.length>0){const hiddenBy=ignoreSourcesOf(cwd,extras,anchor);if(hiddenBy===null){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the ignore rules hiding this tree's untracked files could not be attributed, so `git status` cannot be trusted to have seen them"}}const fromTheCommit=trackedIgnoreSources(cwd,new Set([...hiddenBy.values()].map(rule=>rule.source)),anchor);for(const rec of extras){const rule=hiddenBy.get(rec);if(rule!==void 0&&fromTheCommit.has(rule.source)&&!editedFromHead.has(rule.source)&&!hidesEverything(rule.pattern)){continue}paths.push(rec)}}const stage=spawnSync2("git",[...anchor,"-c","core.fsmonitor=","ls-files","-s","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(stage.error||stage.status!==0||typeof stage.stdout!=="string"){const why=stage.error?stage.error.code??stage.error.message:`git ls-files exited ${stage.status}`;return{paths:[],total:0,unmeasured:why}}const blind=stage.stdout.split("\0").filter(rec=>rec.startsWith("160000 ")).map(rec=>rec.slice(rec.indexOf(" ")+1)).filter(gitlink=>{if(gitlink.includes("\uFFFD"))return true;try{return readdirSync3(join3(cwd,gitlink)).length>0}catch(err){return err.code!=="ENOENT"}});if(blind.length>0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"git status cannot see inside the committed submodule path(s) "+blind.join(", ")}}const bits=spawnSync2("git",[...anchor,"-c","core.fsmonitor=","ls-files","-v","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(bits.error||bits.status!==0||typeof bits.stdout!=="string"){const why=bits.error?bits.error.code??bits.error.message:`git ls-files exited ${bits.status}`;return{paths:paths.slice(0,cap),total:paths.length,unmeasured:why}}if(bits.stdout.split("\0").some(rec=>/^[a-zS]/.test(rec))){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the index carries skip-worktree or assume-unchanged bits, so `git status` cannot see edits to the tracked files they cover"}}if(expectedHeadSha===void 0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the caller brought no record of the commit this tree must hold, and a status measured through an unanchored identity would certify whichever index the .git gitfile names \u2014 a forged pair answers clean \u2014 so the measurement is refused rather than certified"}}return{paths:paths.slice(0,cap),total:paths.length}}__name(worktreeResidue,"worktreeResidue");function exposeDependencies(probeTree,dependencyRoot,opts={}){const done={linked:0,failed:0,alreadyPresent:false,selfLinked:0};if(probeTree===dependencyRoot)return done;let members=[];try{const graph=readWorkspacePackages(dependencyRoot);members=[...graph.packages.map(p=>p.dir),...graph.skipped]}catch{}const memberSources=members.map(dir=>({dir,source:containedIn(dependencyRoot,dir)})).filter(m=>{if(m.source===null)return true;try{return realpathSync4(m.source)!==realpathSync4(dependencyRoot)}catch{return true}});let rootNm=null;try{const nm=join3(dependencyRoot,"node_modules");if(lstatSync3(nm).isDirectory())rootNm=realpathSync4(nm)}catch{}const containment={rootNm,selfLinks:new Set(memberSources.flatMap(m=>m.source===null?[]:[m.source]))};farmNodeModules(dependencyRoot,probeTree,done,containment,opts.rebuild===true);const owned=new Set([join3(probeTree,"node_modules")]);for(const{dir,source}of memberSources){const target=containedIn(probeTree,dir);if(!source||!target){if(existsSync4(join3(dependencyRoot,dir)))done.failed++;continue}if(!existsSync4(target))continue;owned.add(join3(target,"node_modules"));try{farmNodeModules(source,target,done,containment,opts.rebuild===true)}catch{done.failed++}}if(opts.rebuild===true){for(const path of[...owned]){try{owned.add(realpathSync4(path))}catch{}}removeUnownedNodeModules(probeTree,owned,done)}return done}__name(exposeDependencies,"exposeDependencies");function removeUnownedNodeModules(tree,owned,done){const inTreeLinks=[];const walk=__name(dir=>{let entries;try{entries=readdirSync3(dir,{withFileTypes:true})}catch{done.failed++;return}for(const entry of entries){const full=join3(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full)){try{rmSync2(full,{recursive:true,force:true})}catch{done.failed++}}continue}if(entry.name===".git")continue;if(entry.isSymbolicLink()){try{const real=realpathSync4(full);const root=realpathSync4(tree);if(!statSync3(full).isDirectory()){}else if(real===root||real.startsWith(root+sep2)){inTreeLinks.push(real)}else{done.failed++}}catch{}continue}if(!entry.isDirectory())continue;walk(full)}},"walk");walk(tree);for(const real of inTreeLinks){if(isOwned(owned,real))continue;if(holdsNodeModules(real,owned))done.failed++}}__name(removeUnownedNodeModules,"removeUnownedNodeModules");function isOwned(owned,path){if(owned.has(path))return true;try{return owned.has(realpathSync4(path))}catch{return false}}__name(isOwned,"isOwned");function holdsNodeModules(dir,owned){let entries;try{entries=readdirSync3(dir,{withFileTypes:true})}catch{return false}for(const entry of entries){const full=join3(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full))return true;continue}if(entry.isSymbolicLink()||!entry.isDirectory())continue;if(entry.name===".git")continue;if(holdsNodeModules(full,owned))return true}return false}__name(holdsNodeModules,"holdsNodeModules");function containedIn(root,dir){try{const base=realpathSync4(resolve3(root));const full=resolve3(base,dir);const real=existsSync4(full)?realpathSync4(full):full;return real===base||real.startsWith(base+sep2)?real:null}catch{return null}}__name(containedIn,"containedIn");var FARM_MARKER=".qwen-review-farm";function farmLinkVerdict(real,sourceNm,containment){if(insideDir(sourceNm,real))return"internal";if(containment.rootNm!==null&&insideDir(containment.rootNm,real)){return"internal"}for(const member of containment.selfLinks){if(insideDir(member,real))return"self"}return null}__name(farmLinkVerdict,"farmLinkVerdict");function insideDir(base,real){return real===base||real.startsWith(base+sep2)}__name(insideDir,"insideDir");function marksOurFarm(target,sourceDir){try{return readFileSync2(join3(target,FARM_MARKER),"utf8").trim()===resolve3(sourceDir)}catch{return false}}__name(marksOurFarm,"marksOurFarm");function farmNodeModules(sourceDir,targetDir,done,containment,rebuild=false){const source=join3(sourceDir,"node_modules");const target=join3(targetDir,"node_modules");if(!existsSync4(source)){if(rebuild){try{lstatSync3(target);rmSync2(target,{recursive:true,force:true})}catch(err){if(err.code!=="ENOENT")done.failed++}}return}try{if(!lstatSync3(source).isDirectory()){done.failed++;return}}catch{done.failed++;return}let sourceNm;try{sourceNm=realpathSync4(source)}catch{done.failed++;return}let targetPresent=true;try{lstatSync3(target)}catch{targetPresent=false}if(targetPresent){if(!rebuild&&marksOurFarm(target,sourceDir)){done.alreadyPresent=true;return}try{rmSync2(target,{recursive:true,force:true})}catch{done.failed++;return}}try{mkdirSync2(target)}catch{done.failed++;return}const linkType=process.platform==="win32"?"junction":"dir";let entries;try{entries=readdirSync3(source,{withFileTypes:true})}catch{done.failed++;return}const before=done.linked;for(const entry of entries){if(entry.name===".vite"||entry.name===".vite-temp")continue;const sourceEntry=join3(source,entry.name);const targetEntry=join3(target,entry.name);let sourceStats;try{sourceStats=lstatSync3(sourceEntry)}catch{done.failed++;continue}if(!sourceStats.isDirectory()&&!sourceStats.isSymbolicLink()){continue}if(sourceStats.isSymbolicLink()){let real;try{real=realpathSync4(sourceEntry)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync3(sourceEntry).isDirectory())continue}catch{done.failed++;continue}}if(entry.name.startsWith("@")){let pkgs;try{mkdirSync2(targetEntry);pkgs=readdirSync3(sourceEntry)}catch{done.failed++;continue}for(const pkg of pkgs){const scopedSource=join3(sourceEntry,pkg);let real;try{real=realpathSync4(scopedSource)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync3(scopedSource).isDirectory())continue}catch{done.failed++;continue}try{symlinkSync(scopedSource,join3(targetEntry,pkg),linkType);done.linked++}catch{done.failed++}}}else{try{symlinkSync(sourceEntry,targetEntry,linkType);done.linked++}catch{done.failed++}}}if(done.linked>before){try{writeFileSync(join3(target,FARM_MARKER),`${resolve3(sourceDir)}
3
+ import{sanitizeFilenameComponent}from"./chunk-LZNBHBAJ.js";import{Storage}from"./chunk-EPODBRBP.js";import{getProjectHash,isSubpath}from"./chunk-OKN3Z5C5.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";function safeTarget(target){if(/^[A-Za-z0-9._-]{55}~[0-9a-f]{8}$/.test(target))return target;const flat=target.replace(/[^A-Za-z0-9._-]/g,"_").replace(/\.\.+/g,"_");const stem=flat.replace(/^[._]+/,"")||"target";if(stem.length<=SAFE_TARGET_MAX)return stem;return`${stem.slice(0,SAFE_TARGET_MAX-9)}~${createHash("sha256").update(stem).digest("hex").slice(0,8)}`}__name(safeTarget,"safeTarget");var SAFE_TARGET_MAX=64;init_esbuild_shims();var MAX_OLD_SPACE_FLAG="--max[-_]old[-_]space[-_]size";var HEAP_TOKEN_RE=new RegExp(`(?:^|\\s)${MAX_OLD_SPACE_FLAG}(?:=(\\d*)|\\s+(\\d+))?(?=\\s|$)`,"g");function heapFlagMb(options){let mb;for(const m of options.matchAll(HEAP_TOKEN_RE)){const value=m[1]||m[2];if(value)mb=Number(value)}return mb}__name(heapFlagMb,"heapFlagMb");function withoutHeapFlag(options){return options.replace(HEAP_TOKEN_RE,"").trim()}__name(withoutHeapFlag,"withoutHeapFlag");function raiseHeap(options,mb){if((heapFlagMb(options)??0)>=mb)return void 0;return`${withoutHeapFlag(options)} --max-old-space-size=${mb}`.trim()}__name(raiseHeap,"raiseHeap");var NPM_ENV_REF_RE=/(?<!\\)(\\*)\$\{([^${}]+)\}/g;function raiseNpmHeap(options,mb){return raiseHeap(options,mb)?.replace(NPM_ENV_REF_RE,(_,esc,name)=>`${esc}${esc}\\\${${name}}`)}__name(raiseNpmHeap,"raiseNpmHeap");var HEAP_BANNER_RE=/^FATAL ERROR: [^\n]*JavaScript heap out of memory/m;function heapBannerIn(raw){return HEAP_BANNER_RE.test(raw)}__name(heapBannerIn,"heapBannerIn");function ranOutOfHeap(r){return r.exitCode!==0&&(r.heapExhausted??heapBannerIn(r.output))}__name(ranOutOfHeap,"ranOutOfHeap");function killedFromOutside(r){return!r.timedOut&&r.spawnError===void 0&&(r.exitCode===137||r.exitCode===null&&r.signal==="SIGKILL")}__name(killedFromOutside,"killedFromOutside");init_esbuild_shims();import{existsSync,readFileSync,readdirSync,realpathSync,statSync}from"node:fs";import{isAbsolute,join,relative}from"node:path";init_esbuild_shims();function stripComments(src){return src.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,m=>m.startsWith("/")?" ":m)}__name(stripComments,"stripComments");function isWorkspaceMember(filePath,workspaceGlobs){return workspaceDirFor(filePath,workspaceGlobs)!==null}__name(isWorkspaceMember,"isWorkspaceMember");function workspaceDirFor(filePath,workspaceGlobs){const norm=filePath.replace(/^\.\//,"");let owner=null;const previous=[];for(const glob of workspaceGlobs){const negated=glob.startsWith("!");const g=glob.replace(/^!/,"").replace(/^\.\//,"").replace(/\/$/,"");let dir=null;if(g.endsWith("/*")){const base=g.slice(0,-2);if(norm.startsWith(`${base}/`)){const seg=norm.slice(base.length+1).split("/")[0];if(seg)dir=`${base}/${seg}`}}else if(norm===g||norm.startsWith(`${g}/`)){dir=g}if(dir===null)continue;if(!negated){if(dir!==owner){previous.push(owner);owner=dir}}else if(dir===owner){owner=previous.pop()??null}}return owner}__name(workspaceDirFor,"workspaceDirFor");function isNegationExcluded(filePath,workspaceGlobs){if(workspaceDirFor(filePath,workspaceGlobs)!==null)return false;const positives=workspaceGlobs.filter(g=>!g.startsWith("!"));return workspaceDirFor(filePath,positives)!==null}__name(isNegationExcluded,"isNegationExcluded");function hasUnmodeledWorkspaceGlob(globs){return globs.some(glob=>{const g=glob.replace(/^!/,"").replace(/^\.\//,"");if(!g.includes("*"))return false;return!/^[^*]+\/\*$/.test(g)})}__name(hasUnmodeledWorkspaceGlob,"hasUnmodeledWorkspaceGlob");function readWorkspaceGlobs(root){try{const pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"));const ws=pkg.workspaces;const globs=Array.isArray(ws)?ws:Array.isArray(ws?.packages)?ws.packages:[];return globs.filter(g=>typeof g==="string")}catch{return[]}}__name(readWorkspaceGlobs,"readWorkspaceGlobs");function readRootPackage(root){let pkg;try{pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"))}catch{return null}if(pkg===null)return null;const scripts=Object.keys(pkg.scripts??{});if(!scripts.includes("build")&&!scripts.includes("test"))return null;const scriptsText={};for(const[k,v]of Object.entries(pkg.scripts??{})){if(typeof v==="string")scriptsText[k]=v}return{dir:".",name:typeof pkg.name==="string"&&pkg.name?pkg.name:"root",scripts,deps:declaredDeps(pkg),scriptsText}}__name(readRootPackage,"readRootPackage");function scriptFansOut(text){return typeof text==="string"&&(/(^|\s)(--workspaces|--?ws)(?=[\s'"`]|$)/.test(text)||/\bpnpm\s+(-r|--recursive)(?=[\s'"`]|$)/.test(text))}__name(scriptFansOut,"scriptFansOut");var COMMAND_SEPARATOR_RE=/[;&|\n]+/;function chainsCommands(text){return text.split(COMMAND_SEPARATOR_RE).filter(c=>c.trim()!=="").length>1}__name(chainsCommands,"chainsCommands");var NODE_VALUE_FLAGS=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--env-file-if-exists","--input-type","--title","--redirect-warnings","--watch-path","--diagnostic-dir","--report-dir","--cpu-prof-dir","--heap-prof-dir","--icu-data-dir","--openssl-config"]);var SCRIPT_RUNNERS=new Set(["node","tsx"]);var NODE_INLINE_FLAGS=new Set(["-e","--eval","-p","--print","-"]);function nodeScripts(text){const files=[];for(const command of text.split(COMMAND_SEPARATOR_RE)){const words=command.trim().split(/\s+/);const runner=words.findIndex(w=>SCRIPT_RUNNERS.has(w));for(let i=runner+1;i>0&&i<words.length;i++){const word=words[i];if(NODE_INLINE_FLAGS.has(word))break;if(word.startsWith("-")){if(NODE_VALUE_FLAGS.has(word))i++;continue}if(/^[\w@./-]+\.[cm]?[jt]s$/.test(word))files.push(word);break}}return files}__name(nodeScripts,"nodeScripts");function childProcessCommands(src){const commands=[];for(const m of stripComments(src).matchAll(/\b(?:exec|execSync|execFile|execFileSync|spawn|spawnSync)\s*\(\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`)/g)){commands.push(m[1].slice(1,-1))}return commands}__name(childProcessCommands,"childProcessCommands");var MAX_HAND_OFF_SCRIPT_BYTES=1024*1024;function rootBuildFanOutScript(root,text){if(typeof text!=="string")return void 0;for(const file of nodeScripts(text)){try{const path=realpathSync(join(root,file));const inRoot=relative(realpathSync(root),path);if(inRoot.startsWith("..")||isAbsolute(inRoot))continue;const stat=statSync(path);if(!stat.isFile()||stat.size>MAX_HAND_OFF_SCRIPT_BYTES)continue;if(childProcessCommands(readFileSync(path,"utf8")).some(scriptFansOut))return file}catch{}}return void 0}__name(rootBuildFanOutScript,"rootBuildFanOutScript");function declaredBuildHeapMb(root){const text=readRootPackage(root)?.scriptsText["build"];if(typeof text!=="string")return void 0;let declared;for(const m of text.matchAll(/\bNODE_OPTIONS=(?:"([^"]*)"|'([^']*)'|(\S*))/g)){const mb=heapFlagMb(m[1]??m[2]??m[3]??"");if(mb!==void 0)declared=Math.max(declared??0,mb)}return declared}__name(declaredBuildHeapMb,"declaredBuildHeapMb");function declaredDeps(pkg){return[...Object.keys(pkg.dependencies??{}),...Object.keys(pkg.devDependencies??{}),...Object.keys(pkg.peerDependencies??{}),...Object.keys(pkg.optionalDependencies??{})]}__name(declaredDeps,"declaredDeps");function workspaceDirCandidates(root,globs){const dirs=new Set;for(const glob of globs){if(glob.startsWith("!"))continue;const g=glob.replace(/^\.\//,"").replace(/\/$/,"");if(g.endsWith("/*")){const base=g.slice(0,-2);let entries;try{entries=readdirSync(join(root,base),{withFileTypes:true}).filter(e=>e.isDirectory()||e.isSymbolicLink()&&existsSync(join(root,base,e.name,"package.json"))).map(e=>e.name)}catch{continue}for(const e of entries)dirs.add(`${base}/${e}`)}else{dirs.add(g)}}return[...dirs].sort()}__name(workspaceDirCandidates,"workspaceDirCandidates");function readWorkspacePackages(root){const globs=readWorkspaceGlobs(root);const packages=[];const skipped=[];for(const dir of workspaceDirCandidates(root,globs)){const manifest=join(root,dir,"package.json");if(!existsSync(manifest))continue;if(workspaceDirFor(`${dir}/package.json`,globs)!==dir){const positives=globs.filter(g=>!g.startsWith("!"));if(workspaceDirFor(`${dir}/package.json`,positives)===dir)continue;skipped.push(dir);continue}let pkg;try{pkg=JSON.parse(readFileSync(manifest,"utf8"))}catch{skipped.push(dir);continue}if(pkg===null||typeof pkg.name!=="string"||!pkg.name){skipped.push(dir);continue}packages.push({dir,name:pkg.name,scripts:Object.keys(pkg.scripts??{}),deps:declaredDeps(pkg)})}packages.sort((a,b)=>a.dir.localeCompare(b.dir));skipped.sort();return{packages,skipped}}__name(readWorkspacePackages,"readWorkspacePackages");function affectedWorkspaces(changedFiles,workspaceGlobs){const dirs=new Set;for(const f of changedFiles){const d=workspaceDirFor(f,workspaceGlobs);if(d)dirs.add(d)}return[...dirs].sort()}__name(affectedWorkspaces,"affectedWorkspaces");function dependencyEdges(packages){const byName=new Map;for(const p of packages){if(p.dir!=="."||!byName.has(p.name))byName.set(p.name,p)}const dependsOn=new Map;for(const p of packages){dependsOn.set(p.dir,p.deps.map(d=>byName.get(d)?.dir).filter(d=>!!d&&d!==p.dir))}return dependsOn}__name(dependencyEdges,"dependencyEdges");function reverseDependencyClosure(affected,packages){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=new Set(affected.filter(a=>byDir.has(a)));let grew=true;while(grew){grew=false;for(const p of packages){if(consumers.has(p.dir))continue;if((dependsOn.get(p.dir)??[]).some(d=>consumers.has(d))){consumers.add(p.dir);grew=true}}}return[...consumers].sort()}__name(reverseDependencyClosure,"reverseDependencyClosure");function buildSetFor(affected,packages,alsoBuild=[]){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=reverseDependencyClosure(affected,packages);const wanted=new Set;const addDeps=__name(dir=>{if(wanted.has(dir))return;wanted.add(dir);for(const d of dependsOn.get(dir)??[])addDeps(d)},"addDeps");for(const c of consumers)addDeps(c);for(const extra of alsoBuild)if(byDir.has(extra))addDeps(extra);const order=[];const seen=new Set;const visit=__name(dir=>{if(seen.has(dir))return;seen.add(dir);for(const d of dependsOn.get(dir)??[]){if(wanted.has(d))visit(d)}order.push(dir)},"visit");for(const dir of alsoBuild.filter(d=>wanted.has(d)).sort())visit(dir);for(const dir of[...wanted].sort())visit(dir);return order}__name(buildSetFor,"buildSetFor");init_esbuild_shims();import{spawnSync as spawnSync2}from"node:child_process";import{accessSync,constants,existsSync as existsSync4,lstatSync as lstatSync3,mkdirSync as mkdirSync2,mkdtempSync,readdirSync as readdirSync3,readFileSync as readFileSync2,realpathSync as realpathSync4,rmSync as rmSync2,statSync as statSync3,symlinkSync,writeFileSync}from"node:fs";import{homedir,tmpdir}from"node:os";import{basename,dirname as dirname3,isAbsolute as isAbsolute3,join as join3,resolve as resolve3,sep as sep2}from"node:path";init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync3,lstatSync as lstatSync2,mkdirSync,readdirSync as readdirSync2,realpathSync as realpathSync3,statSync as statSync2}from"node:fs";import{dirname as dirname2,isAbsolute as isAbsolute2,join as join2,relative as relative2,resolve as resolve2,sep}from"node:path";init_esbuild_shims();import{execFileSync,spawnSync}from"node:child_process";import{existsSync as existsSync2,lstatSync,realpathSync as realpathSync2,rmSync}from"node:fs";import{dirname,resolve}from"node:path";var GIT_TIMEOUT_MS=12e4;function gitOpts(){return{timeout:GIT_TIMEOUT_MS,env:{...sanitizedGitEnv(),GIT_TERMINAL_PROMPT:"0"}}}__name(gitOpts,"gitOpts");var trustedLaunchDir=null;function kernelCwd(){try{const r=spawnSync("/bin/pwd",["-P"],{encoding:"utf8",timeout:5e3,env:sanitizedGitEnv()});if(r.error||r.status!==0||!r.stdout)return null;return r.stdout.replace(/\n$/,"")}catch{return null}}__name(kernelCwd,"kernelCwd");function launchDirRefusal(){const cwd=process.cwd();if(trustedLaunchDir===cwd)return null;if(!insideReviewTmpLexically(cwd)){trustedLaunchDir=cwd;return null}if(process.platform!=="win32"){const kernel=kernelCwd();if(kernel===null){return`the kernel-resolved working directory could not be determined (cwd ${cwd}), so where a command run from here would land is unmeasured`}if(!insideReviewTmpLexically(kernel)){return`the process's working directory was renamed mid-run: the spelling ${cwd} is inside the review temp dir but the kernel reports ${kernel} \u2014 where every command would actually run`}let cachedReal;try{cachedReal=realpathSync2(cwd)}catch{cachedReal=null}if(cachedReal!==kernel){return`the process's working directory spelling ${cwd} resolves to ${cachedReal??"a path that no longer exists"} while the kernel reports ${kernel}: a rename mid-run split them, and every command runs at the kernel's answer`}return untrustedRepositoryFrom(kernel)}return untrustedRepositoryFrom(cwd)}__name(launchDirRefusal,"launchDirRefusal");function assertTrustedLaunchDir(){const refusal=launchDirRefusal();if(refusal!==null){throw new Error(`refusing to run git from this directory: ${refusal}. The command would resolve through that pointer and act on whatever repository it names. Run the review from a checkout outside the review temp dir.`)}}__name(assertTrustedLaunchDir,"assertTrustedLaunchDir");function git(...args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),encoding:"utf8"}).replace(/\r\n/g,"\n").trim()}__name(git,"git");function gitWithEnv(extraEnv,args){assertTrustedLaunchDir();const opts=gitOpts();return execFileSync("git",args,{...opts,env:{...opts.env,...extraEnv},maxBuffer:512*1024*1024,encoding:"utf8"}).replace(/\r\n/g,"\n").trim()}__name(gitWithEnv,"gitWithEnv");function gitWithInput(input,args){return gitWithInputRaw(input,args).replace(/\r\n/g,"\n").trim()}__name(gitWithInput,"gitWithInput");function gitWithInputRaw(input,args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),encoding:"utf8",input,maxBuffer:512*1024*1024})}__name(gitWithInputRaw,"gitWithInputRaw");function gitOpt(...args){return gitProbe(...args).out}__name(gitOpt,"gitOpt");function gitProbe(...args){try{const refusal=launchDirRefusal();if(refusal!==null)return{out:null,status:null,refusal};return{out:execFileSync("git",args,{...gitOpts(),encoding:"utf8",stdio:["ignore","pipe","pipe"]}).replace(/\r\n/g,"\n").trim(),status:0,refusal:null}}catch(err){const status=err.status;return{out:null,status:typeof status==="number"?status:null,refusal:null}}}__name(gitProbe,"gitProbe");function repoRoot(){const first=git("worktree","list","--porcelain").split("\n")[0]??"";if(!first.startsWith("worktree ")){throw new Error(`cannot find the main worktree in: ${first}`)}return first.slice("worktree ".length)}__name(repoRoot,"repoRoot");function refExists(ref){return gitOpt("rev-parse","--verify","--quiet",ref)!==null}__name(refExists,"refExists");function worktreeReleaseResult(existed,stillThere,removeError){const freed=existed&&!stillThere;if(!existed||freed){return{existed,freed,reason:void 0}}return{existed,freed,reason:removeError?removeError instanceof Error?removeError.message:String(removeError):"the path is still there after `git worktree remove --force` and `rm -rf`"}}__name(worktreeReleaseResult,"worktreeReleaseResult");function releaseWorktree(worktreePath2){let redirected;try{redirected=redirectedAncestor(dirname(resolve(worktreePath2)))}catch(err){return worktreeReleaseResult(true,true,err)}if(redirected!==null){return worktreeReleaseResult(true,true,new Error(`refusing to release through a symlink: ${redirected} is a symlink, so the removal would land wherever it points`))}try{if(lstatSync(worktreePath2).isSymbolicLink()){let removeError2;try{rmSync(worktreePath2,{force:true})}catch(e){removeError2=e}const pruned2=gitProbe("worktree","prune");let stillThere2=false;try{lstatSync(worktreePath2);stillThere2=true}catch{}return worktreeReleaseResult(true,stillThere2||pruned2.refusal!==null||pruned2.status===null,removeError2??refusalError(pruned2.refusal)??(pruned2.status===null?couldNotRunError():void 0))}}catch{}const existed=existsSync2(worktreePath2);let removeError;const removed=existed?gitProbe("worktree","remove",worktreePath2,"--force"):null;if(existed){try{rmSync(worktreePath2,{recursive:true,force:true})}catch(e){removeError=e}}const pruned=gitProbe("worktree","prune");const refusal=removed?.refusal??pruned.refusal;const couldNotRun=removed?.status!==0&&pruned.status===null;const stillThere=existsSync2(worktreePath2);return worktreeReleaseResult(existed,stillThere||existed&&couldNotRun,removeError??(couldNotRun?refusalError(refusal)??couldNotRunError():void 0))}__name(releaseWorktree,"releaseWorktree");function couldNotRunError(){return new Error('the `git worktree prune` that frees the registration and the branch could not be run at all (a spawn failure or the timeout kill), so both survive \u2014 the next `git worktree add` over the path will still fail with "missing but already registered". Re-run `qwen review cleanup`.')}__name(couldNotRunError,"couldNotRunError");function refusalError(refusal){if(refusal===null)return void 0;return new Error(`git could not run from this directory \u2014 ${refusal}. The directory is cleared but this worktree's registration and branch were not, so the next \`git worktree add\` over it will still fail. Run \`qwen review cleanup\` from a checkout outside the review temp dir.`)}__name(refusalError,"refusalError");function gitRaw(...args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),maxBuffer:512*1024*1024,stdio:["ignore","pipe","pipe"]})}__name(gitRaw,"gitRaw");function gitRawTolerateDiff(...args){try{return gitRaw(...args)}catch(err){const e=err;if(e.status===1&&e.stdout&&e.stdout.length>0)return e.stdout;throw err}}__name(gitRawTolerateDiff,"gitRawTolerateDiff");init_esbuild_shims();var CONTROL=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;var NEEDS_PRE_ESCAPE=/[\u007f-\u009f\p{Cf}\p{Zl}\p{Zp}]/gu;function inertText(value,maxChars=200){const clipped=value.length>maxChars?value.slice(0,maxChars):value;const rendered=CONTROL.test(clipped)?JSON.stringify(clipped.replace(NEEDS_PRE_ESCAPE,c=>{const hex=c.codePointAt(0).toString(16).padStart(4,"0");return`\\u${hex}`})):clipped;return clipped.length<value.length?`${rendered}\u2026`:rendered}__name(inertText,"inertText");function assertWritableOutPath(out){if(typeof out!=="string"){throw new TypeError(Array.isArray(out)?"--out must be given once, as a file path":"--out must name a file path")}if(out.trim()===""){throw new TypeError("--out must name a file path")}if(/[/\\]$/.test(out.trim())){throw new TypeError(`--out names a directory, not a file: ${out}`)}const resolved=resolve2(out);if(existsSync3(resolved)&&statSync2(resolved).isDirectory()){throw new TypeError(`--out names a directory, not a file: ${out}`)}}__name(assertWritableOutPath,"assertWritableOutPath");var REVIEW_TMP_DIR=join2(".qwen","tmp");var RETIRED_REVIEW_LEASE_DIR=join2(".qwen","review-leases");var REVIEW_TRUST_STATE_DIR="review-state";var REVIEWS_DIR=join2(".qwen","reviews");var REVIEW_CACHE_DIR=join2(".qwen","review-cache");function outermostReviewRepositoryRoot(repositoryRoot){const resolved=resolve2(repositoryRoot);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=(resolved+sep).indexOf(marker);return at<0?resolved:resolved.slice(0,at)}__name(outermostReviewRepositoryRoot,"outermostReviewRepositoryRoot");function canonicalReviewRepositoryRoot(repositoryRoot){let canonical=outermostReviewRepositoryRoot(repositoryRoot);try{canonical=realpathSync3.native(canonical)}catch(error){if(error.code!=="ENOENT")throw error}canonical=outermostReviewRepositoryRoot(canonical);return canonical}__name(canonicalReviewRepositoryRoot,"canonicalReviewRepositoryRoot");function reviewTrustStateDir(repositoryRoot){const digest=getProjectHash(canonicalReviewRepositoryRoot(repositoryRoot));return join2(Storage.getGlobalQwenDir(),REVIEW_TRUST_STATE_DIR,digest)}__name(reviewTrustStateDir,"reviewTrustStateDir");function reviewRepositoryRootForWorktree(worktree){const resolved=resolve2(worktree);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=resolved.indexOf(marker);if(at<0){throw new Error(`cannot place the base-tree trust artifact for ${worktree}: the worktree is not shaped like <root>/.qwen/tmp/<name>, so there is no host-side review directory to key it under`)}return resolved.slice(0,at)}__name(reviewRepositoryRootForWorktree,"reviewRepositoryRootForWorktree");var GENERATED_WORKFLOWS_SUBDIR=join2("workflows","generated");var REVIEW_WORKFLOWS_SUBDIR="review";var REVIEW_WORKFLOW_PREFIX="qwen-review-";var GeneratedWorkflowDirUnavailableError=class extends Error{static{__name(this,"GeneratedWorkflowDirUnavailableError")}};function projectDirFromEnv(env){const projectDir=env["QWEN_CODE_PROJECT_DIR"]?.trim();if(!projectDir){throw new GeneratedWorkflowDirUnavailableError("the CLI did not export QWEN_CODE_PROJECT_DIR, so there is no directory the Workflow tool would load a generated script from. Run this command from inside a qwen session.")}return projectDir}__name(projectDirFromEnv,"projectDirFromEnv");function reviewSessionDirName(session){const digest=createHash2("sha256").update(session).digest("hex").slice(0,8);return`${sanitizeFilenameComponent(session)}-${digest}`}__name(reviewSessionDirName,"reviewSessionDirName");function reviewWorkflowsDir(env=process.env){const session=env["QWEN_CODE_SESSION_ID"]?.trim();return join2(projectDirFromEnv(env),GENERATED_WORKFLOWS_SUBDIR,REVIEW_WORKFLOWS_SUBDIR,session?reviewSessionDirName(session):"no-session")}__name(reviewWorkflowsDir,"reviewWorkflowsDir");function ensureWritableReviewWorkflowsDir(env=process.env){const projectDir=projectDirFromEnv(env);const dir=reviewWorkflowsDir(env);const root=join2(projectDir,GENERATED_WORKFLOWS_SUBDIR);for(const component of[root,join2(root,REVIEW_WORKFLOWS_SUBDIR),dir]){let isLink=false;try{isLink=lstatSync2(component).isSymbolicLink()}catch(err){if(err.code!=="ENOENT")throw err;break}if(isLink){throw new Error(`refusing to write a generated review script through the symlinked directory '${component}' \u2014 it would land outside the generated-workflows root the Workflow loader trusts.`)}}mkdirSync(dir,{recursive:true});const realDir=realpathSync3(dir);const realRoot=realpathSync3(root);if(realDir!==realRoot&&!realDir.startsWith(realRoot+sep)){throw new Error(`refusing to write a generated review script: the canonical session directory '${realDir}' escapes the canonical generated-workflows root '${realRoot}'.`)}return dir}__name(ensureWritableReviewWorkflowsDir,"ensureWritableReviewWorkflowsDir");function reviewWorkflowScriptPath(planPath,script,env=process.env){const resolved=resolve2(planPath);let canonical=resolved;try{canonical=realpathSync3(resolved)}catch{}const digest=createHash2("sha256").update(canonical).digest("hex").slice(0,10);const contentDigest=createHash2("sha256").update(script).digest("hex");return join2(reviewWorkflowsDir(env),`${REVIEW_WORKFLOW_PREFIX}${digest}-${contentDigest}.js`)}__name(reviewWorkflowScriptPath,"reviewWorkflowScriptPath");var LEASE_PREFIX="qwen-review-lease-";var PARSE_ARGS_REPORT=join2(REVIEW_TMP_DIR,"qwen-review-parse-args.json");function lastReviewEffortPath(projectRoot,sessionProjectDir){const owner=sessionProjectDir?.trim()?resolve2(sessionProjectDir):new Storage(projectRoot).getProjectDir();return join2(owner,"review-last-effort")}__name(lastReviewEffortPath,"lastReviewEffortPath");function worktreePath(prNumber){return join2(REVIEW_TMP_DIR,`review-pr-${prNumber}`)}__name(worktreePath,"worktreePath");function probeWorktreePath(worktree){return`${resolve2(worktree)}-probe`}__name(probeWorktreePath,"probeWorktreePath");function baseWorktreePath(worktree){return`${resolve2(worktree)}-base`}__name(baseWorktreePath,"baseWorktreePath");var SCRATCH_INFIX="-scratch-";function scratchWorktreePath(worktree,label){const safe=scratchLabel(label);if(!safe){throw new TypeError(`scratch label ${JSON.stringify(label)} keeps no path-safe character (A-Za-z0-9._-); a tree cannot be named for it`)}return`${resolve2(worktree)}${SCRATCH_INFIX}${safe}`}__name(scratchWorktreePath,"scratchWorktreePath");function scratchWorktreePrefix(worktree){return`${resolve2(worktree)}${SCRATCH_INFIX}`}__name(scratchWorktreePrefix,"scratchWorktreePrefix");function scratchLabel(label){return label.replace(/[^A-Za-z0-9._-]/g,"_").replace(/\.\.+/g,"_").replace(/^[._-]+/,"").slice(0,64)}__name(scratchLabel,"scratchLabel");function reviewBranch(prNumber){return`qwen-review/pr-${prNumber}`}__name(reviewBranch,"reviewBranch");function tmpFile(target,suffix){return join2(REVIEW_TMP_DIR,`qwen-review-${safeTarget(target)}-${suffix}`)}__name(tmpFile,"tmpFile");function tmpPrefix(target){return`qwen-review-${safeTarget(target)}-`}__name(tmpPrefix,"tmpPrefix");function ensureReviewTmpDir(command){for(const dir of[dirname2(REVIEW_TMP_DIR),REVIEW_TMP_DIR]){let isLink=false;try{isLink=lstatSync2(dir).isSymbolicLink()}catch(err){if(err.code!=="ENOENT")throw err;break}if(isLink){throw new Error(`${command}: ${dir} is a symbolic link \u2014 every file this review writes (plan, diff, candidate, stop sidecar, worktree) would land wherever it points, and the plan would be read back from there. Refusing to run; nothing here can tell your own link from a committed one. If it is YOURS \u2014 this directory holds a full worktree per PR, so redirecting it onto other storage is a reasonable thing to have done \u2014 neither ${dirname2(REVIEW_TMP_DIR)} nor ${REVIEW_TMP_DIR} can be one: redirect the checkout itself, or a directory the review never names.`)}}let listing;try{listing=gitRaw("ls-files","-s","-z").toString("utf8")}catch(err){if(insideRepository()){throw new Error(`${command}: could not list the tracked entries under ${REVIEW_TMP_DIR} (${inertText(err.message,2e3)}) \u2014 refusing to run rather than write through a link the listing might have named. Lightweight mode (\`fetch-diff\`) is the one flow that could otherwise proceed without git; every other one needs it for the diff itself.`)}listing=""}const scratch=REVIEW_TMP_DIR.split(sep).join("/").toLowerCase();const planted=listing.split("\0").find(entry=>{const gitlink=entry.startsWith("160000 ");if(!entry.startsWith("120000 ")&&!gitlink)return false;const path=entry.slice(entry.indexOf(" ")+1).toLowerCase();if(path===dirname2(scratch)||path===scratch)return true;if(!path.startsWith(`${scratch}/`))return false;return!gitlink||!isReviewWorktreeName(path.slice(scratch.length+1))});if(planted!==void 0){const path=planted.slice(planted.indexOf(" ")+1);const what=planted.startsWith("160000 ")?"a submodule":"a symbolic link";throw new Error(`${command}: the workspace tracks ${what} at ${inertText(path)} \u2014 on the scratch directory ${REVIEW_TMP_DIR} or a path through it \u2014 and a plain write to that name would follow it out of the tree. Refusing to run; remove it from the index AND the working tree (\`git rm -f -- <path>\`) and retry.`)}const onDisk=roundOwnedLinkOnDisk(command);if(onDisk!==null){throw new Error(`${command}: ${inertText(onDisk)} is a symbolic link on disk, at a name this review writes \u2014 a plain write to it would follow the link out of the tree. Refusing to run; delete the link and retry.`)}mkdirSync(REVIEW_TMP_DIR,{recursive:true})}__name(ensureReviewTmpDir,"ensureReviewTmpDir");function roundOwnedLinkOnDisk(command){const list=__name(dir=>{try{return readdirSync2(dir,{withFileTypes:true})}catch(err){const code=err.code;if(code==="ENOENT"||code==="ENOTDIR")return[];throw new Error(`${command}: could not list ${inertText(dir)} (${inertText(err.message)}) \u2014 refusing to run rather than write through a link the listing might have named.`)}},"list");const walk=__name(dir=>{for(const entry of list(dir)){const path=join2(dir,entry.name);if(entry.isSymbolicLink())return path;if(entry.isDirectory()){const hit=walk(path);if(hit!==null)return hit}}return null},"walk");for(const entry of list(REVIEW_TMP_DIR)){const path=join2(REVIEW_TMP_DIR,entry.name);const name=entry.name.toLowerCase();if(name.startsWith("qwen-review-")){if(entry.isSymbolicLink())return path;if(entry.isDirectory()){const hit=walk(path);if(hit!==null)return hit}}else if(isReviewWorktreeName(name)&&entry.isSymbolicLink()){return path}}return null}__name(roundOwnedLinkOnDisk,"roundOwnedLinkOnDisk");function commandPrefixed(command,message){const prefix=`${command}: `;return message.startsWith(prefix)?message:`${prefix}${message}`}__name(commandPrefixed,"commandPrefixed");function writesIntoReviewTmp(out){const scratch=resolve2(REVIEW_TMP_DIR).toLowerCase();const target=resolve2(out).toLowerCase();return target===scratch||target.startsWith(scratch+sep)}__name(writesIntoReviewTmp,"writesIntoReviewTmp");function isReviewWorktreeName(name){return/^review-pr-\d+(-probe|-base|-scratch-[^/]*)?$/.test(name)}__name(isReviewWorktreeName,"isReviewWorktreeName");function insideRepository(){let dir=resolve2(".");for(;;){if(existsSync3(join2(dir,".git")))return true;const parent=dirname2(dir);if(parent===dir)return false;dir=parent}}__name(insideRepository,"insideRepository");function inertPath(p){return p.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\u2500`]+/gu," ")}__name(inertPath,"inertPath");function canonicalise(abs){const walked=[];let cur=abs;for(;;){try{const real=realpathSync3(cur);return walked.length===0?real:join2(real,...walked.reverse())}catch{const parent=resolve2(cur,"..");if(parent===cur)return abs;walked.push(cur.slice(parent.length).replace(sep==="/"?/^\/+/:/^[\\/]+/,""));cur=parent}}}__name(canonicalise,"canonicalise");function repoRelativeOf(repoRoot2,file,from=process.cwd()){const abs=canonicalise(resolve2(from,file));const rel=relative2(repoRoot2,abs);const escapes=rel===".."||rel.startsWith(".."+sep)||isAbsolute2(rel);return{rel:sep==="/"?rel:rel.split(sep).join("/"),abs,escapes}}__name(repoRelativeOf,"repoRelativeOf");function assertUnredirectedParent(target,what,command){const parent=resolve2(dirname2(target));let real;try{real=realpathSync3(parent)}catch(err){throw new Error(`${command}: cannot resolve the ${what} directory ${inertText(parent)}: `+inertText(err.message))}if(real!==parent){throw new Error(`${command}: the ${what} directory ${inertText(parent)} resolves to ${inertText(real)} \u2014 a symlink in the path would redirect this write outside the tree it names. Refusing.`)}}__name(assertUnredirectedParent,"assertUnredirectedParent");var GIT_ENV_REDIRECTS=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_COMMON_DIR"];var GIT_ENV_CONFIG=["GIT_CONFIG_COUNT","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_PARAMETERS","GIT_DEFAULT_HASH"];var GIT_ENV_EXEC=["GIT_SSH_COMMAND","GIT_SSH","GIT_EXEC_PATH","GIT_TEMPLATE_DIR","GIT_ASKPASS","GIT_PROXY_COMMAND","GIT_EDITOR","GIT_SEQUENCE_EDITOR","GIT_EXTERNAL_DIFF","XDG_CONFIG_HOME"];function mountRootFor(cwd){return mountRootVerdict(cwd).root}__name(mountRootFor,"mountRootFor");function mountNullKind(cwd){return mountRootVerdict(cwd).nullKind??"refused"}__name(mountNullKind,"mountNullKind");function mountRootVerdict(cwd){const resolved=resolve3(cwd);const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;const at=(resolved+sep2).lastIndexOf(marker);if(at<0)return{root:null,nullKind:"outside"};const root=resolved.slice(0,at+marker.length-1);const outermost=outermostReviewTmpRoot(root);const bound=outermost===root?resolve3(root,".."):outermost;try{if(redirectedAncestor(root,bound)!==null){return{root:null,nullKind:"refused"}}const real=realpathSync4(root);if(unmountableRootSpelling(real)){return{root:null,nullKind:"unmountable"}}return{root:real,nullKind:null}}catch{return{root:null,nullKind:"refused"}}}__name(mountRootVerdict,"mountRootVerdict");function unmountableRootSpelling(root){return root.includes(":")||root.startsWith("\\\\")}__name(unmountableRootSpelling,"unmountableRootSpelling");function insideReviewTmpLexically(cwd){const resolved=resolve3(cwd);const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;return(resolved+sep2).lastIndexOf(marker)>=0}__name(insideReviewTmpLexically,"insideReviewTmpLexically");function resolvedGitDir(cwd){return revParse(cwd,"--absolute-git-dir")}__name(resolvedGitDir,"resolvedGitDir");function resolvedCommonDir(cwd){return revParse(cwd,"--path-format=absolute","--git-common-dir")}__name(resolvedCommonDir,"resolvedCommonDir");function revParse(cwd,...flags){const resolved=spawnSync2("git",["-c","core.hooksPath=/dev/null/no-hooks","-c","core.fsmonitor=","rev-parse",...flags],{cwd,encoding:"utf8",timeout:3e4,env:{...sanitizedGitEnv(),LC_ALL:"C"}});const value=resolved.error||resolved.status!==0||!resolved.stdout?null:resolved.stdout.replace(/\n$/,"");return{value:value!==null&&value.includes("\uFFFD")?null:value,notARepository:resolved.status===128&&resolved.stderr.includes("not a git repository")}}__name(revParse,"revParse");function untrustedPointer(dir,gitDir,expectedOwner,root){if(adminEntryInsideReviewTmp(gitDir,root,dir)){return"resolves to an admin entry inside the review temp dir, where the reviewed code can rewrite it"}const common=resolvedCommonDir(dir);if(common.value===null&&!common.notARepository){return"git could not resolve its own common dir from this tree, so whether the pointer names the main repository instead of a linked worktree's admin entry is unknown"}if(common.value!==null&&common.value===gitDir){return"resolves to the repository's own common dir rather than a linked worktree's admin entry, so every command through it acts on the main repository instead of this tree"}let backpointer;try{backpointer=readFileSync2(join3(gitDir,"gitdir"),"utf8").replace(/\n$/,"")}catch{return null}const ownerSpelled=dirname3(resolve3(gitDir,backpointer));let ownerTree;try{ownerTree=realpathSync4(ownerSpelled)}catch{ownerTree=null}const writableRoot=outermostReviewTmpRoot(root);if(ownerSpelled===writableRoot||isSubpath(writableRoot,ownerSpelled)){const redirect=redirectedAncestor(ownerSpelled,writableRoot);if(redirect!==null){return`resolves to a different tree's admin entry \u2014 the owner its gitdir backpointer names resolves through a symlink inside the review temp dir (${redirect}), so the round trip would agree with whatever the link points at`}}let expectedReal;try{expectedReal=realpathSync4(expectedOwner)}catch{return"could not resolve the tree the entry must belong to"}if(ownerTree===null){return"resolves to an admin entry that does not point back at this tree \u2014 the owner its backpointer names cannot be resolved, so the commands this gates would measure whichever repository it does name"}if(ownerTree!==expectedReal){return"resolves to a different tree's admin entry \u2014 its gitdir backpointer names that tree, not this one, so every command through it would measure and mutate the tree it actually belongs to"}return null}__name(untrustedPointer,"untrustedPointer");function untrustedRepositoryFrom(cwd,mountRoot=mountRootFor){const root=mountRoot(cwd);if(root===null){if(mountNullKind(cwd)!=="refused")return null;return`${cwd}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command run from here would land is unmeasured`}if(!existsSync4(cwd)){if(!insideReviewTmpLexically(cwd))return null;return`${cwd}: no directory exists at this spelling inside the review temp dir \u2014 an ancestor was renamed out from under it, so where a command run from here would land is unmeasured`}const target=resolvedGitDir(cwd);if(target.value===null){return target.notARepository?null:`${cwd}: git could not resolve its own git dir, so where a command run from here would land is unmeasured`}const toplevel=revParse(cwd,"--show-toplevel");if(toplevel.value===null){return`${cwd}: git could not resolve its own top-level directory, so where a command run from here would land is unmeasured`}const why=untrustedPointer(cwd,target.value,toplevel.value,root);return why===null?null:`${cwd} ${why}`}__name(untrustedRepositoryFrom,"untrustedRepositoryFrom");function untrustedGitfile(tree,mountRoot=mountRootFor){if(!existsSync4(tree))return null;const root=mountRoot(tree);if(root===null){if(mountNullKind(tree)!=="refused")return null;return`${tree}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command through its .git would land is unmeasured`}const dotGit=join3(tree,".git");let stat;try{stat=lstatSync3(dotGit)}catch{return`${tree} has no .git to resolve`}if(!stat.isFile()){return`${tree}'s .git is not the gitfile the pipeline created, and the tree is inside the review temp dir`}const target=resolvedGitDir(tree);if(target.value===null){return`${tree}: git could not resolve its own git dir`}const why=untrustedPointer(tree,target.value,tree,root);return why===null?null:`${tree} ${why}`}__name(untrustedGitfile,"untrustedGitfile");function adminEntryInsideReviewTmp(gitDir,root,tree){if(root===null)return mountNullKind(tree)==="refused";let real;let realRoot;try{const canonical=realpathSync4.native??realpathSync4;real=canonical(resolve3(gitDir));realRoot=canonical(root)}catch{return true}return isSubpath(outermostReviewTmpRoot(realRoot),real)}__name(adminEntryInsideReviewTmp,"adminEntryInsideReviewTmp");function outermostReviewTmpRoot(root){const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;const at=root.indexOf(marker);return at<0?root:root.slice(0,at+marker.length-1)}__name(outermostReviewTmpRoot,"outermostReviewTmpRoot");function redirectedAncestor(dir,stopAt=process.cwd()){try{const stop=resolve3(stopAt);let stopReal=stop;try{stopReal=realpathSync4(stopAt)}catch{}for(let cur=resolve3(dir);;cur=dirname3(cur)){let isLink;try{isLink=lstatSync3(cur).isSymbolicLink()}catch{isLink=false}if(isLink)return cur;if(cur===stop)return null;try{if(realpathSync4(cur)===stopReal)return null}catch{}if(dirname3(cur)===cur)return null}}catch{return null}}__name(redirectedAncestor,"redirectedAncestor");function sanitizedGitEnv(){const env={...process.env};const drop=new Set([...GIT_ENV_REDIRECTS,...GIT_ENV_CONFIG,...GIT_ENV_EXEC].map(k=>k.toLowerCase()));for(const key of Object.keys(env)){const lower=key.toLowerCase();if(drop.has(lower)||/^git_config_(key|value)_\d+$/.test(lower)){delete env[key]}}env["GIT_NO_REPLACE_OBJECTS"]="1";env["GIT_GRAFT_FILE"]="/dev/null/grafts";return env}__name(sanitizedGitEnv,"sanitizedGitEnv");var MAX_INCLUDE_DEPTH=10;var MAX_INCLUDE_FILES=64;var FILTER_SCREEN_NAMED=12;var SCREEN_KEYS="^filter\\..*\\.(smudge|clean|process)$|^include\\.path$|^includeif\\..*\\.path$";function filterCommandsIn(commonDir,gitDir){const candidates=[join3(commonDir,"config"),join3(gitDir,"config.worktree")];try{for(const entry of readdirSync3(join3(commonDir,"worktrees"))){candidates.push(join3(commonDir,"worktrees",entry,"config.worktree"))}}catch{}const filters=new Set;const unread=new Set;const dangling=new Set;const visited=new Set;const read=__name(file=>{const r=spawnSync2("git",["config","--file",file,"-z","--get-regexp",SCREEN_KEYS],{cwd:commonDir,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error){return{unreadable:r.error.code??r.error.message}}if(r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return{unreadable:`git config exited ${r.status}`}}const records=[];for(const rec of r.stdout.split("\0")){if(!rec)continue;const nl=rec.indexOf("\n");records.push(nl===-1?[rec,""]:[rec.slice(0,nl),rec.slice(nl+1)])}return{records}},"read");const visit=__name((file,depth,via)=>{let real;try{real=realpathSync4.native(file)}catch(e){if(via!==null){const code=e?.code;if(code==="ENOENT"){dangling.add(`${via} -> ${file} (missing \u2014 git ignores it)`)}else{unread.add(`${via} -> ${file} (could not be resolved: ${code??"unknown"} \u2014 not screened)`)}}return}if(visited.has(real))return;if(visited.size>=MAX_INCLUDE_FILES){unread.add(`${via??file} -> ${file} (include fan-out past ${MAX_INCLUDE_FILES} files \u2014 not screened)`);return}visited.add(real);try{if(!statSync3(real).isFile()){unread.add(`${via??file} -> ${file} (not a regular file \u2014 not screened)`);return}accessSync(real,constants.R_OK)}catch{unread.add(`${via??file} -> ${file} (could not be read)`);return}if(depth>MAX_INCLUDE_DEPTH){unread.add(`${via} -> ${file} (nested past git's include limit \u2014 not screened)`);return}const r=read(file);if("unreadable"in r){unread.add(`${file} (could not be read: ${r.unreadable})`);return}for(const[key,value]of r.records){if(key.startsWith("filter.")){filters.add(key);continue}let target;if(value.startsWith("~/")){target=`${process.env["HOME"]||homedir()}${sep2}${value.slice(2)}`}else if(value.startsWith("~")){unread.add(`${key} -> ${value} (another user's home \u2014 not resolved here)`);continue}else{target=isAbsolute3(value)?value:`${dirname3(file)}${sep2}${value}`}visit(target,depth+1,`${key} (in ${file})`)}},"visit");for(const candidate of candidates)visit(candidate,0,null);return{filters:[...filters],unread:[...unread],dangling:[...dangling]}}__name(filterCommandsIn,"filterCommandsIn");function describeFilterScreen(hits){const named=hits.slice(0,FILTER_SCREEN_NAMED);const rest=hits.length-named.length;return rest>0?`${named.join(", ")}, and ${rest} more`:named.join(", ")}__name(describeFilterScreen,"describeFilterScreen");function filterBlankEnv(filterKeys){const names=new Set;for(const key of filterKeys){const m=/^filter\.(.+)\.(?:smudge|clean|process)$/.exec(key);if(m)names.add(m[1])}const env={};let n=0;for(const name of names){for(const[key,value]of[["clean",""],["smudge",""],["process",""],["required","false"]]){env[`GIT_CONFIG_KEY_${n}`]=`filter.${name}.${key}`;env[`GIT_CONFIG_VALUE_${n}`]=value;n++}}if(n>0)env["GIT_CONFIG_COUNT"]=String(n);return env}__name(filterBlankEnv,"filterBlankEnv");var UNRESOLVED_REPO="the repository's git directories could not be resolved (git rev-parse failed) \u2014 not screened";function screenForTree(worktree){const discover=__name(flag=>{const r=spawnSync2("git",["rev-parse","--path-format=absolute",flag],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return null}return r.stdout.endsWith("\n")?r.stdout.slice(0,-1):r.stdout},"discover");const commonDir=discover("--git-common-dir");const gitDir=discover("--git-dir");if(commonDir===null||gitDir===null)return null;return filterCommandsIn(commonDir,gitDir)}__name(screenForTree,"screenForTree");function localFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread,...screen.dangling]}__name(localFilterCommands,"localFilterCommands");function filterScreenForTree(worktree){return screenForTree(worktree)}__name(filterScreenForTree,"filterScreenForTree");function resolvedContentTransformForTree(worktree){const r=spawnSync2("git",["config","--get-regexp","^filter\\..*\\.(smudge|clean|process)$|^core\\.(autocrlf|eol)$"],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.status!==0||typeof r.stdout!=="string")return false;for(const line of r.stdout.split("\n")){const space=line.indexOf(" ");const key=(space===-1?line:line.slice(0,space)).toLowerCase();const value=space===-1?"true":line.slice(space+1).trim().toLowerCase();if(key.startsWith("filter."))return true;if(key==="core.autocrlf"&&(value==="true"||value==="input")){return true}if(key==="core.eol"&&(value==="crlf"||value==="native"&&process.platform==="win32")){return true}}return false}__name(resolvedContentTransformForTree,"resolvedContentTransformForTree");function checkoutFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread]}__name(checkoutFilterCommands,"checkoutFilterCommands");function discardWorktree(cwd,tree){let symlink=false;try{symlink=lstatSync3(tree).isSymbolicLink()}catch{}const ownAdminDir=adminDirOf(tree);let sweep;if(!symlink){sweep=spawnSync2("git",["worktree","remove","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(sweep.status!==0){spawnSync2("git",["worktree","unlock",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});sweep=spawnSync2("git",["worktree","remove","--force","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()})}}rmSync2(tree,{recursive:true,force:true});dropWorktreeRegistration(cwd,tree,ownAdminDir);if(sweep!==void 0&&sweep.status!==0){dropWorktreeRegistration(cwd,tree,null)}return sweep}__name(discardWorktree,"discardWorktree");function dropWorktreeRegistration(cwd,tree,adminDir){if(adminDir!==null){try{rmSync2(adminDir,{recursive:true,force:true})}catch{}return}const common=spawnSync2("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(common.status!==0||typeof common.stdout!=="string")return;const dir=join3(common.stdout.trim(),"worktrees");let ids;try{ids=readdirSync3(dir)}catch{return}const wanted=samePath(tree);const ownId=basename(resolve3(tree));const ownIdPattern=new RegExp(`^${ownId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\d*$`);for(const id of ids){if(!ownIdPattern.test(id))continue;try{const gitdir=readFileSync2(join3(dir,id,"gitdir"),"utf8").trim();const named=dirname3(gitdir);if(samePath(named)!==wanted)continue;if(existsSync4(named))continue;rmSync2(join3(dir,id),{recursive:true,force:true})}catch{}}}__name(dropWorktreeRegistration,"dropWorktreeRegistration");function adminDirOf(tree){try{const pointer=readFileSync2(join3(tree,".git"),"utf8").trim();const match=/^gitdir:\s*(.+)$/.exec(pointer);if(!match)return null;const dir=resolve3(dirname3(resolve3(tree)),match[1].trim());const back=readFileSync2(join3(dir,"gitdir"),"utf8").trim();return samePath(dirname3(back))===samePath(tree)?dir:null}catch{return null}}__name(adminDirOf,"adminDirOf");function samePath(p){const abs=resolve3(p);try{return join3(realpathSync4(dirname3(abs)),basename(abs))}catch{return abs}}__name(samePath,"samePath");var pipelineExcludesFile=null;function pipelineExcludeArgs(){if(pipelineExcludesFile===null){try{const file=join3(mkdtempSync(join3(tmpdir(),"qwen-review-excludes-")),"excludes").split(sep2).join("/");writeFileSync(file,"node_modules/\ndist/\n",{flag:"wx",mode:384});pipelineExcludesFile=file}catch{pipelineExcludesFile=""}}return pipelineExcludesFile===""?[]:["-c",`core.excludesFile=${pipelineExcludesFile}`]}__name(pipelineExcludeArgs,"pipelineExcludeArgs");function inPipelineFootprint(rec){const parts=rec.split("/");for(let i=0;i<parts.length-1;i++){if(parts[i]==="node_modules"||parts[i]==="dist")return true;if(parts[i]===".husky"&&parts[i+1]==="_"&&i+1<parts.length-1)return true}return false}__name(inPipelineFootprint,"inPipelineFootprint");function ignoreSourcesOf(cwd,paths,anchor=[]){const r=spawnSync2("git",[...anchor,...pipelineExcludeArgs(),"check-ignore","-z","-v","--stdin"],{cwd,input:`${paths.join("\0")}\0`,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return null}const fields=r.stdout.split("\0");const rules=new Map;for(let i=0;i+3<fields.length;i+=4){rules.set(fields[i+3],{source:fields[i],pattern:fields[i+2]})}return rules}__name(ignoreSourcesOf,"ignoreSourcesOf");function hidesEverything(pattern){const core=pattern.replace(/^\//,"").replace(/\/$/,"");if(core.length===0)return false;const segments=core.split("/");return core.includes("*")&&segments.every(seg=>/^[*?]+$/.test(seg))}__name(hidesEverything,"hidesEverything");function trackedIgnoreSources(cwd,sources,anchor=[]){const inside=[...sources].filter(s=>s.length>0&&!isAbsolute3(s)&&!s.split("/").some(p=>p===".."));if(inside.length===0)return new Set;const r=spawnSync2("git",[...anchor,"ls-files","-z","--",...inside],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return new Set}return new Set(r.stdout.split("\0").filter(p=>p.length>0))}__name(trackedIgnoreSources,"trackedIgnoreSources");var RESIDUE_PATH_CAP=12;function worktreeResidue(cwd,cap=RESIDUE_PATH_CAP,expectedHeadSha){try{if(!lstatSync3(join3(cwd,".git")).isFile()){return{paths:[],total:0,unmeasured:".git is not a gitfile (a planted repository?) \u2014 a repo stood up at this path answers a clean status for a dirty tree, and the probe cannot tell the two apart"}}}catch{}const root=mountRootFor(cwd);if(root===null){if(mountNullKind(cwd)==="refused"){return{paths:[],total:0,unmeasured:"the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, and the status below would measure whichever repository the pointer here names"}}}else{const target=resolvedGitDir(cwd);let why;if(target.value!==null){why=untrustedPointer(cwd,target.value,cwd,root)}else{why=target.notARepository?null:"git could not resolve its own git dir"}if(why!==null){return{paths:[],total:0,unmeasured:`the .git gitfile ${why} \u2014 the status below would measure whichever repository it names, and refresh that index through whatever filters it configures`}}}const discover=__name(flag=>{const r2=spawnSync2("git",["rev-parse","--path-format=absolute",flag],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(r2.error||r2.status!==0||typeof r2.stdout!=="string"){return null}return r2.stdout.endsWith("\n")?r2.stdout.slice(0,-1):r2.stdout},"discover");const toplevel=discover("--show-toplevel");const gitDir=discover("--git-dir");const commonDir=discover("--git-common-dir");let isWorktree=false;let anchor=[];let filterBlanks={};try{if(toplevel!==null&&gitDir!==null&&commonDir!==null&&realpathSync4(toplevel)===realpathSync4(cwd)){isWorktree=true;if(lstatSync3(cwd).isSymbolicLink()){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${resolve3(cwd)}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}const spelled=resolve3(cwd);const bound=dirname3(commonDir);const redirected=redirectedAncestor(dirname3(spelled),bound);if(redirected!==null){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${redirected}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}let backpointer=null;try{backpointer=readFileSync2(join3(gitDir,"gitdir"),"utf8").trim()}catch{}if(backpointer===null){return{paths:[],total:0,unmeasured:"the .git gitfile names a repository with no admin entry for this tree \u2014 a standalone repository answering for this path, whose index the commands below would measure"}}let pointsBack=false;try{pointsBack=realpathSync4(dirname3(resolve3(gitDir,backpointer)))===realpathSync4(cwd)}catch{}if(!pointsBack){return{paths:[],total:0,unmeasured:"the .git gitfile names an admin entry that does not point back at this tree \u2014 the commands below would measure whichever repository it does name"}}anchor=[`--git-dir=${realpathSync4(gitDir)}`,`--work-tree=${realpathSync4(toplevel)}`];if(expectedHeadSha!==void 0){const head=spawnSync2("git",[...anchor,"rev-parse","HEAD"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});const got=head.error||head.status!==0||typeof head.stdout!=="string"?null:head.stdout.trim();if(got===null||got.toLowerCase()!==expectedHeadSha.toLowerCase()){return{paths:[],total:0,unmeasured:got===null?"the pinned identity could not read its own HEAD \u2014 the commands below would have measured a repository git cannot read":`the pinned identity is checked out at ${got}, not the fetched PR head ${expectedHeadSha} \u2014 the gitfile names a repository answering for this path, and its index is what the commands below would measure`}}}const screen=filterCommandsIn(commonDir,realpathSync4(gitDir));const notReadToTheBottom=[...screen.unread,...screen.dangling];if(notReadToTheBottom.length>0){return{paths:[],total:0,unmeasured:`the residue measurement would run under repo-local config this screen could not read to the bottom: ${describeFilterScreen(notReadToTheBottom)} \u2014 a content filter reached that way would execute on the index refresh, and a filter the screen cannot see it cannot blank; remove the include, or the file it names, if it is not yours`}}filterBlanks=filterBlankEnv(screen.filters)}}catch{isWorktree=false}if(!isWorktree){return{paths:[],total:0,unmeasured:"the path is not a git worktree (repository discovery walks up into the enclosing checkout)"}}const r=spawnSync2("git",[...anchor,...pipelineExcludeArgs(),"-c","core.fsmonitor=","-c","core.hooksPath=/dev/null/no-hooks","status","--porcelain","--untracked-files=all","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:{...sanitizedGitEnv(),...filterBlanks}});if(r.error||r.status!==0||typeof r.stdout!=="string"){const why=r.error?r.error.code??r.error.message:`git status exited ${r.status}`;return{paths:[],total:0,unmeasured:why}}const records=r.stdout.split("\0").filter(rec=>rec.length>0);const paths=[];for(let i=0;i<records.length;i++){const rec=records[i];const status=rec.slice(0,2);paths.push(rec.slice(3));if((status.includes("R")||status.includes("C"))&&i+1<records.length){paths.push(records[++i])}}const others=spawnSync2("git",[...anchor,"-c","core.fsmonitor=","ls-files","--others","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(others.error||others.status!==0||typeof others.stdout!=="string"){const why=others.error?others.error.code??others.error.message:`git ls-files exited ${others.status}`;return{paths:[],total:0,unmeasured:why}}const seen=new Set(paths);const editedFromHead=new Set(paths);const extras=[];for(const rec of others.stdout.split("\0")){if(rec.length===0||seen.has(rec))continue;if(inPipelineFootprint(rec))continue;seen.add(rec);extras.push(rec)}if(extras.length>0){const hiddenBy=ignoreSourcesOf(cwd,extras,anchor);if(hiddenBy===null){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the ignore rules hiding this tree's untracked files could not be attributed, so `git status` cannot be trusted to have seen them"}}const fromTheCommit=trackedIgnoreSources(cwd,new Set([...hiddenBy.values()].map(rule=>rule.source)),anchor);for(const rec of extras){const rule=hiddenBy.get(rec);if(rule!==void 0&&fromTheCommit.has(rule.source)&&!editedFromHead.has(rule.source)&&!hidesEverything(rule.pattern)){continue}paths.push(rec)}}const stage=spawnSync2("git",[...anchor,"-c","core.fsmonitor=","ls-files","-s","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(stage.error||stage.status!==0||typeof stage.stdout!=="string"){const why=stage.error?stage.error.code??stage.error.message:`git ls-files exited ${stage.status}`;return{paths:[],total:0,unmeasured:why}}const blind=stage.stdout.split("\0").filter(rec=>rec.startsWith("160000 ")).map(rec=>rec.slice(rec.indexOf(" ")+1)).filter(gitlink=>{if(gitlink.includes("\uFFFD"))return true;try{return readdirSync3(join3(cwd,gitlink)).length>0}catch(err){return err.code!=="ENOENT"}});if(blind.length>0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"git status cannot see inside the committed submodule path(s) "+blind.join(", ")}}const bits=spawnSync2("git",[...anchor,"-c","core.fsmonitor=","ls-files","-v","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(bits.error||bits.status!==0||typeof bits.stdout!=="string"){const why=bits.error?bits.error.code??bits.error.message:`git ls-files exited ${bits.status}`;return{paths:paths.slice(0,cap),total:paths.length,unmeasured:why}}if(bits.stdout.split("\0").some(rec=>/^[a-zS]/.test(rec))){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the index carries skip-worktree or assume-unchanged bits, so `git status` cannot see edits to the tracked files they cover"}}if(expectedHeadSha===void 0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the caller brought no record of the commit this tree must hold, and a status measured through an unanchored identity would certify whichever index the .git gitfile names \u2014 a forged pair answers clean \u2014 so the measurement is refused rather than certified"}}return{paths:paths.slice(0,cap),total:paths.length}}__name(worktreeResidue,"worktreeResidue");function exposeDependencies(probeTree,dependencyRoot,opts={}){const done={linked:0,failed:0,alreadyPresent:false,selfLinked:0};if(probeTree===dependencyRoot)return done;let members=[];try{const graph=readWorkspacePackages(dependencyRoot);members=[...graph.packages.map(p=>p.dir),...graph.skipped]}catch{}const memberSources=members.map(dir=>({dir,source:containedIn(dependencyRoot,dir)})).filter(m=>{if(m.source===null)return true;try{return realpathSync4(m.source)!==realpathSync4(dependencyRoot)}catch{return true}});let rootNm=null;try{const nm=join3(dependencyRoot,"node_modules");if(lstatSync3(nm).isDirectory())rootNm=realpathSync4(nm)}catch{}const containment={rootNm,selfLinks:new Set(memberSources.flatMap(m=>m.source===null?[]:[m.source]))};farmNodeModules(dependencyRoot,probeTree,done,containment,opts.rebuild===true);const owned=new Set([join3(probeTree,"node_modules")]);for(const{dir,source}of memberSources){const target=containedIn(probeTree,dir);if(!source||!target){if(existsSync4(join3(dependencyRoot,dir)))done.failed++;continue}if(!existsSync4(target))continue;owned.add(join3(target,"node_modules"));try{farmNodeModules(source,target,done,containment,opts.rebuild===true)}catch{done.failed++}}if(opts.rebuild===true){for(const path of[...owned]){try{owned.add(realpathSync4(path))}catch{}}removeUnownedNodeModules(probeTree,owned,done)}return done}__name(exposeDependencies,"exposeDependencies");function removeUnownedNodeModules(tree,owned,done){const inTreeLinks=[];const walk=__name(dir=>{let entries;try{entries=readdirSync3(dir,{withFileTypes:true})}catch{done.failed++;return}for(const entry of entries){const full=join3(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full)){try{rmSync2(full,{recursive:true,force:true})}catch{done.failed++}}continue}if(entry.name===".git")continue;if(entry.isSymbolicLink()){try{const real=realpathSync4(full);const root=realpathSync4(tree);if(!statSync3(full).isDirectory()){}else if(real===root||real.startsWith(root+sep2)){inTreeLinks.push(real)}else{done.failed++}}catch{}continue}if(!entry.isDirectory())continue;walk(full)}},"walk");walk(tree);for(const real of inTreeLinks){if(isOwned(owned,real))continue;if(holdsNodeModules(real,owned))done.failed++}}__name(removeUnownedNodeModules,"removeUnownedNodeModules");function isOwned(owned,path){if(owned.has(path))return true;try{return owned.has(realpathSync4(path))}catch{return false}}__name(isOwned,"isOwned");function holdsNodeModules(dir,owned){let entries;try{entries=readdirSync3(dir,{withFileTypes:true})}catch{return false}for(const entry of entries){const full=join3(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full))return true;continue}if(entry.isSymbolicLink()||!entry.isDirectory())continue;if(entry.name===".git")continue;if(holdsNodeModules(full,owned))return true}return false}__name(holdsNodeModules,"holdsNodeModules");function containedIn(root,dir){try{const base=realpathSync4(resolve3(root));const full=resolve3(base,dir);const real=existsSync4(full)?realpathSync4(full):full;return real===base||real.startsWith(base+sep2)?real:null}catch{return null}}__name(containedIn,"containedIn");var FARM_MARKER=".qwen-review-farm";function farmLinkVerdict(real,sourceNm,containment){if(insideDir(sourceNm,real))return"internal";if(containment.rootNm!==null&&insideDir(containment.rootNm,real)){return"internal"}for(const member of containment.selfLinks){if(insideDir(member,real))return"self"}return null}__name(farmLinkVerdict,"farmLinkVerdict");function insideDir(base,real){return real===base||real.startsWith(base+sep2)}__name(insideDir,"insideDir");function marksOurFarm(target,sourceDir){try{return readFileSync2(join3(target,FARM_MARKER),"utf8").trim()===resolve3(sourceDir)}catch{return false}}__name(marksOurFarm,"marksOurFarm");function farmNodeModules(sourceDir,targetDir,done,containment,rebuild=false){const source=join3(sourceDir,"node_modules");const target=join3(targetDir,"node_modules");if(!existsSync4(source)){if(rebuild){try{lstatSync3(target);rmSync2(target,{recursive:true,force:true})}catch(err){if(err.code!=="ENOENT")done.failed++}}return}try{if(!lstatSync3(source).isDirectory()){done.failed++;return}}catch{done.failed++;return}let sourceNm;try{sourceNm=realpathSync4(source)}catch{done.failed++;return}let targetPresent=true;try{lstatSync3(target)}catch{targetPresent=false}if(targetPresent){if(!rebuild&&marksOurFarm(target,sourceDir)){done.alreadyPresent=true;return}try{rmSync2(target,{recursive:true,force:true})}catch{done.failed++;return}}try{mkdirSync2(target)}catch{done.failed++;return}const linkType=process.platform==="win32"?"junction":"dir";let entries;try{entries=readdirSync3(source,{withFileTypes:true})}catch{done.failed++;return}const before=done.linked;for(const entry of entries){if(entry.name===".vite"||entry.name===".vite-temp")continue;const sourceEntry=join3(source,entry.name);const targetEntry=join3(target,entry.name);let sourceStats;try{sourceStats=lstatSync3(sourceEntry)}catch{done.failed++;continue}if(!sourceStats.isDirectory()&&!sourceStats.isSymbolicLink()){continue}if(sourceStats.isSymbolicLink()){let real;try{real=realpathSync4(sourceEntry)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync3(sourceEntry).isDirectory())continue}catch{done.failed++;continue}}if(entry.name.startsWith("@")){let pkgs;try{mkdirSync2(targetEntry);pkgs=readdirSync3(sourceEntry)}catch{done.failed++;continue}for(const pkg of pkgs){const scopedSource=join3(sourceEntry,pkg);let real;try{real=realpathSync4(scopedSource)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync3(scopedSource).isDirectory())continue}catch{done.failed++;continue}try{symlinkSync(scopedSource,join3(targetEntry,pkg),linkType);done.linked++}catch{done.failed++}}}else{try{symlinkSync(sourceEntry,targetEntry,linkType);done.linked++}catch{done.failed++}}}if(done.linked>before){try{writeFileSync(join3(target,FARM_MARKER),`${resolve3(sourceDir)}
4
4
  `)}catch{}}}__name(farmNodeModules,"farmNodeModules");function worktreeCreateFailureDetail(label,err,sweepStderr){const sweepErr=sweepStderr.trim();return`${label} worktree could not be created: ${err instanceof Error?err.message:String(err)}`+(sweepErr?` (stale-tree sweep also reported: ${sweepErr})`:"")}__name(worktreeCreateFailureDetail,"worktreeCreateFailureDetail");export{safeTarget,raiseHeap,raiseNpmHeap,heapBannerIn,ranOutOfHeap,killedFromOutside,isWorkspaceMember,workspaceDirFor,isNegationExcluded,hasUnmodeledWorkspaceGlob,readWorkspaceGlobs,readRootPackage,scriptFansOut,chainsCommands,rootBuildFanOutScript,declaredBuildHeapMb,readWorkspacePackages,affectedWorkspaces,reverseDependencyClosure,buildSetFor,mountRootFor,untrustedRepositoryFrom,untrustedGitfile,redirectedAncestor,sanitizedGitEnv,describeFilterScreen,filterBlankEnv,localFilterCommands,filterScreenForTree,resolvedContentTransformForTree,checkoutFilterCommands,discardWorktree,RESIDUE_PATH_CAP,worktreeResidue,exposeDependencies,worktreeCreateFailureDetail,GIT_TIMEOUT_MS,git,gitWithEnv,gitWithInput,gitWithInputRaw,gitOpt,gitProbe,repoRoot,refExists,releaseWorktree,gitRaw,gitRawTolerateDiff,CONTROL,inertText,assertWritableOutPath,REVIEW_TMP_DIR,RETIRED_REVIEW_LEASE_DIR,REVIEWS_DIR,REVIEW_CACHE_DIR,reviewTrustStateDir,reviewRepositoryRootForWorktree,ensureWritableReviewWorkflowsDir,reviewWorkflowScriptPath,LEASE_PREFIX,PARSE_ARGS_REPORT,lastReviewEffortPath,worktreePath,probeWorktreePath,baseWorktreePath,scratchWorktreePath,scratchWorktreePrefix,scratchLabel,reviewBranch,tmpFile,tmpPrefix,ensureReviewTmpDir,commandPrefixed,writesIntoReviewTmp,inertPath,repoRelativeOf,assertUnredirectedParent};
5
5
  /**
6
6
  * @license