@qwen-code/qwen-code 0.25.2-preview.1 → 0.25.2
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.
- package/chunks/{MaxSizedBox-CF4NN4Y7.js → MaxSizedBox-CGJP7S5S.js} +1 -1
- package/chunks/{StandaloneSessionPicker-Q23KTB6U.js → StandaloneSessionPicker-H6NONKPP.js} +1 -1
- package/chunks/{acp-subagent-executor-LXOLDTFY.js → acp-subagent-executor-7OCKCTA5.js} +1 -1
- package/chunks/{acpAgent-QRKZVQAG.js → acpAgent-VCKTBLFO.js} +3 -3
- package/chunks/{advisor-VZZJU7BR.js → advisor-UQJ45FLG.js} +1 -1
- package/chunks/{agent-LP66VBC4.js → agent-KMSCVRSG.js} +1 -1
- package/chunks/{agent-headless-W5P4KPX4.js → agent-headless-3FWQ5QNO.js} +1 -1
- package/chunks/{agent-host-client-OW4HBXRL.js → agent-host-client-PXIIFCCS.js} +1 -1
- package/chunks/{agent-host-connections-D7IC6WWL.js → agent-host-connections-QUYGQNJX.js} +1 -1
- package/chunks/{anthropicContentGenerator-6I25Q3Y6.js → anthropicContentGenerator-MDETV5LU.js} +1 -1
- package/chunks/{batch-7E5KJ625.js → batch-RQO2HWFV.js} +1 -1
- package/chunks/{bridge-BITC2AVN.js → bridge-OA3GEU2I.js} +1 -1
- package/chunks/{channel-settings-store-VAVG6ONF.js → channel-settings-store-YN23NP2H.js} +1 -1
- package/chunks/{chunk-4NCTKE4Z.js → chunk-2PQ5ZRTI.js} +1 -1
- package/chunks/{chunk-OJHTHXBC.js → chunk-32UFT5HU.js} +1 -1
- package/chunks/{chunk-2HJZ3OYW.js → chunk-3C34EMBZ.js} +1 -1
- package/chunks/{chunk-UXFLNZNB.js → chunk-3FPPMGVC.js} +1 -1
- package/chunks/{chunk-74YXI5IJ.js → chunk-445NIH5T.js} +1 -1
- package/chunks/{chunk-MXXYBMBZ.js → chunk-45EKBDFD.js} +1 -1
- package/chunks/{chunk-JV5FCFG4.js → chunk-4WFWZWR3.js} +1 -1
- package/chunks/{chunk-AAOAX46J.js → chunk-56NX3ASC.js} +1 -1
- package/chunks/{chunk-IBS4PHD2.js → chunk-5FY6TL3Z.js} +1 -1
- package/chunks/{chunk-UGI3XPRM.js → chunk-5GJPVNHI.js} +1 -1
- package/chunks/{chunk-7BZGY7AH.js → chunk-5XAVUYY6.js} +6 -6
- package/chunks/{chunk-V3WNU4F5.js → chunk-655XEN5H.js} +1 -1
- package/chunks/{chunk-APX7ODYT.js → chunk-6PHAGUA6.js} +1 -1
- package/chunks/{chunk-CD6C4OHZ.js → chunk-7YX6LW5H.js} +1 -1
- package/chunks/{chunk-C2NFZSGI.js → chunk-AAVRYR5T.js} +1 -1
- package/chunks/{chunk-EO35BRIG.js → chunk-ANUAITTH.js} +1 -1
- package/chunks/{chunk-CNQ6AOFN.js → chunk-AZ5GFEKG.js} +1 -1
- package/chunks/{chunk-KAEW65QP.js → chunk-B5XDGUAK.js} +1 -1
- package/chunks/{chunk-X6QHNKUW.js → chunk-BCNBZOGV.js} +1 -1
- package/chunks/{chunk-W5DIWPQB.js → chunk-BDXWLZJD.js} +1 -1
- package/chunks/{chunk-ZASVUARY.js → chunk-BPX4A433.js} +1 -1
- package/chunks/{chunk-CDSI44GJ.js → chunk-BUI6W6CU.js} +1 -1
- package/chunks/{chunk-ZEYCGUHI.js → chunk-BVARURDD.js} +1 -1
- package/chunks/{chunk-PZ5UPKIG.js → chunk-BW5CHWEJ.js} +2 -2
- package/chunks/{chunk-7TUP75C2.js → chunk-C4DSH4A3.js} +1 -1
- package/chunks/{chunk-R4KMBENY.js → chunk-CCBWBPJL.js} +1 -1
- package/chunks/{chunk-TU6DWKVI.js → chunk-CKJ3OUIV.js} +2 -2
- package/chunks/{chunk-SG5P4CK4.js → chunk-CRZ7QRFB.js} +1 -1
- package/chunks/{chunk-UYFL7K4Z.js → chunk-CTEBIP2S.js} +1 -1
- package/chunks/{chunk-WSIDVWGO.js → chunk-DBOWUORN.js} +1 -1
- package/chunks/{chunk-NAHKSVYI.js → chunk-DPBXGGQX.js} +1 -1
- package/chunks/{chunk-BMOJDKDZ.js → chunk-DSSSLNXD.js} +3 -3
- package/chunks/{chunk-FP2RLPWJ.js → chunk-EKGFFEH4.js} +1 -1
- package/chunks/{chunk-L7W3J427.js → chunk-EMEQR2LX.js} +1 -1
- package/chunks/{chunk-YRYMLJAC.js → chunk-ENUYA7BO.js} +1 -1
- package/chunks/{chunk-4CWBH6LP.js → chunk-EORORGZC.js} +1 -1
- package/chunks/{chunk-RBH3BOVF.js → chunk-EUK64V6Z.js} +1 -1
- package/chunks/{chunk-AII4DN7M.js → chunk-FBV4LUUL.js} +1 -1
- package/chunks/{chunk-YVEPPENZ.js → chunk-FFLFTXO7.js} +1 -1
- package/chunks/{chunk-2HSFO66N.js → chunk-FHXH3GSI.js} +1 -1
- package/chunks/{chunk-RH6PMH32.js → chunk-FVBDVZD7.js} +1 -1
- package/chunks/{chunk-Y2HLDUZG.js → chunk-I2D2ZUKF.js} +1 -1
- package/chunks/{chunk-6PUZWUMQ.js → chunk-I3FZ733S.js} +1 -1
- package/chunks/{chunk-GG7RNHZW.js → chunk-IFAUFERF.js} +5 -5
- package/chunks/{chunk-JQ7BCB3L.js → chunk-IYFUH3JB.js} +1 -1
- package/chunks/{chunk-VAMQAYF3.js → chunk-JB5I5QAD.js} +1 -1
- package/chunks/{chunk-Z3UZTCKY.js → chunk-JD3QDS7D.js} +1 -1
- package/chunks/{chunk-TFVPY43T.js → chunk-JG2UNQOW.js} +1 -1
- package/chunks/{chunk-E4MRBL4O.js → chunk-JSXHTTFE.js} +1 -1
- package/chunks/{chunk-QTYA6TES.js → chunk-LJLS3MDJ.js} +1 -1
- package/chunks/{chunk-RZISIEQL.js → chunk-MEIW5WVJ.js} +1 -1
- package/chunks/{chunk-ZD4U3GR4.js → chunk-MGL36H3B.js} +1 -1
- package/chunks/{chunk-HXA3X4PB.js → chunk-MJUFVFH3.js} +1 -1
- package/chunks/{chunk-SYIDPXVT.js → chunk-MSR6LYHS.js} +1 -1
- package/chunks/{chunk-4MJ67O5W.js → chunk-MTXJRB7G.js} +2 -2
- package/chunks/{chunk-F5P3BWS7.js → chunk-MXFBSMIM.js} +1 -1
- package/chunks/{chunk-W6TNBCKX.js → chunk-MYHJ4WUH.js} +1 -1
- package/chunks/{chunk-CWU5NJOB.js → chunk-NHXKNS7F.js} +1 -1
- package/chunks/{chunk-6OIJIF6G.js → chunk-NT74NPQT.js} +1 -1
- package/chunks/{chunk-O47FCWNF.js → chunk-NWXW4UNC.js} +1 -1
- package/chunks/{chunk-JASL4RZR.js → chunk-O77LM4EW.js} +1 -1
- package/chunks/{chunk-ZDNTENP2.js → chunk-OB7T2MDO.js} +1 -1
- package/chunks/{chunk-L7WFW57T.js → chunk-PODFLAH7.js} +1 -1
- package/chunks/{chunk-R3ZMQ7WR.js → chunk-Q2G675WT.js} +1 -1
- package/chunks/{chunk-H3QROVUO.js → chunk-QT27SK62.js} +1 -1
- package/chunks/{chunk-UELAXFT7.js → chunk-QZPNBV4F.js} +1 -1
- package/chunks/{chunk-B3L4LODR.js → chunk-RV54BGL2.js} +1 -1
- package/chunks/{chunk-KLXL3FSI.js → chunk-SFETIBPP.js} +1 -1
- package/chunks/{chunk-F3YGAXZ5.js → chunk-SGKINIQB.js} +1 -1
- package/chunks/{chunk-MBPT3YYO.js → chunk-SHJNP7OV.js} +1 -1
- package/chunks/{chunk-U3YSYIQE.js → chunk-SPFRORFN.js} +1 -1
- package/chunks/{chunk-S3B4TZVJ.js → chunk-SPLINFM7.js} +1 -1
- package/chunks/{chunk-ORIS5AVH.js → chunk-SYO5FPHL.js} +1 -1
- package/chunks/{chunk-AGHGPOH6.js → chunk-TEE4MM5S.js} +1 -1
- package/chunks/{chunk-WHF3HYZI.js → chunk-TPZTO4K3.js} +1 -1
- package/chunks/{chunk-KJO757RN.js → chunk-UY2CSL5W.js} +1 -1
- package/chunks/{chunk-VCTZRPKP.js → chunk-W7QYXFWW.js} +1 -1
- package/chunks/{chunk-T3ECMT6I.js → chunk-WQOZJ6V7.js} +2 -2
- package/chunks/{chunk-INEI2ZW2.js → chunk-WZK7RC36.js} +1 -1
- package/chunks/{chunk-Y5JLH3SN.js → chunk-X22435IN.js} +4 -4
- package/chunks/{chunk-WHNAY3QQ.js → chunk-X2KF6AUQ.js} +1 -1
- package/chunks/{chunk-MUEIZGTI.js → chunk-YHPHQX6M.js} +1 -1
- package/chunks/{chunk-5OOO3YIH.js → chunk-YL7QMYOX.js} +1 -1
- package/chunks/{chunk-43E3XC2W.js → chunk-YQEOEO5V.js} +1 -1
- package/chunks/{chunk-624P32LD.js → chunk-YZ374XTK.js} +1 -1
- package/chunks/{codex-subagent-executor-2MPLWNLD.js → codex-subagent-executor-MC3QB2AN.js} +1 -1
- package/chunks/{config-utils-MJEEBLQW.js → config-utils-FYT7PUIC.js} +1 -1
- package/chunks/{contextCommand-BP566QVE.js → contextCommand-DXMSMSR7.js} +1 -1
- package/chunks/{core-runtime-BOAIFYAZ.js → core-runtime-ZLB6QZ3Z.js} +1 -1
- package/chunks/{create-sub-session-HJVK7AXV.js → create-sub-session-YUI3G5AF.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-KA2Y6FHL.js → daemon-git-worktree-guard-5PYZMC6T.js} +1 -1
- package/chunks/{daemon-status-provider-JGR5JT2T.js → daemon-status-provider-GC567FVE.js} +1 -1
- package/chunks/{daemon-trust-policy-EP4DHXOW.js → daemon-trust-policy-LLD2UMPF.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-W3VZRKOK.js → daemon-trust-policy-monitor-MRMB2CRJ.js} +1 -1
- package/chunks/{deferred-core-runtime-Q3JH7XDL.js → deferred-core-runtime-4HLTINJ6.js} +1 -1
- package/chunks/{edit-S7DCBMAL.js → edit-CZ6FEXDU.js} +1 -1
- package/chunks/{enterPlanMode-UX7B6KWX.js → enterPlanMode-O3CJ3I2J.js} +1 -1
- package/chunks/{environment-ZBW6HDG3.js → environment-OJWH4FYL.js} +1 -1
- package/chunks/{errors-7ZRLUHEB.js → errors-NWKSQVL3.js} +1 -1
- package/chunks/{execution-tool-R244Q3GW.js → execution-tool-7UCADALN.js} +1 -1
- package/chunks/{execution-worker-JR44JTC4.js → execution-worker-LWHQMPBV.js} +1 -1
- package/chunks/{exitPlanMode-2PTTZXGO.js → exitPlanMode-JDM6ZZWI.js} +1 -1
- package/chunks/{fast-path-NQQ42XUR.js → fast-path-4WHPMNMD.js} +1 -1
- package/chunks/{glob-4JP6RQNK.js → glob-LAU4YJ6J.js} +1 -1
- package/chunks/{goal-tools-MO7NIH7B.js → goal-tools-AF2FQO3H.js} +1 -1
- package/chunks/{handleAutoUpdate-STUVMCIU.js → handleAutoUpdate-WBWK4775.js} +1 -1
- package/chunks/{i18n-UTIILRKE.js → i18n-O4Q2KHOA.js} +1 -1
- package/chunks/{initializer-YI2WT6LZ.js → initializer-2AH3EKBL.js} +1 -1
- package/chunks/{installationInfo-PW2JHHJV.js → installationInfo-77WYXG4W.js} +1 -1
- package/chunks/{list-SAOL2OZI.js → list-RAU3ZJQS.js} +1 -1
- package/chunks/{llm-LMY62H6Z.js → llm-MJMQ34KB.js} +4 -4
- package/chunks/{llm-content-generator-6RPOZ2YR.js → llm-content-generator-MJPR2TWC.js} +1 -1
- package/chunks/{loadedSettingsAdapter-RNXWDDE2.js → loadedSettingsAdapter-WRWWNGHZ.js} +1 -1
- package/chunks/{local-execution-environment-GIWY2LO6.js → local-execution-environment-VVJ7OYBT.js} +1 -1
- package/chunks/{loggingContentGenerator-AOKEDXK6.js → loggingContentGenerator-722BJL7T.js} +1 -1
- package/chunks/{manage-memory-WKPWLYDD.js → manage-memory-GN56UQHG.js} +1 -1
- package/chunks/{managed-npm-update-LFFWFATA.js → managed-npm-update-5VE662JS.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-IV6ZNIAK.js → managed-runtime-attestation-worker-ASGGZMFM.js} +1 -1
- package/chunks/{managed-runtime-session-worker-3NU4FOXD.js → managed-runtime-session-worker-YUSO7WFB.js} +1 -1
- package/chunks/{mcp-RDDGN4JK.js → mcp-6D236MEH.js} +1 -1
- package/chunks/{model-call-collection-JARTJD6S.js → model-call-collection-UAE2W6VV.js} +1 -1
- package/chunks/{model-configuration-7H6PEOLY.js → model-configuration-VHPSBCQI.js} +1 -1
- package/chunks/{modelConfigUtils-Q63ZZTXY.js → modelConfigUtils-XKDXYQRJ.js} +1 -1
- package/chunks/{monitor-HLO366TQ.js → monitor-JIKXBXDK.js} +1 -1
- package/chunks/{nonInteractiveCli-JO5EG6OK.js → nonInteractiveCli-IXTK5V4Q.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-T7AKBX25.js → nonInteractiveToolExecutor-3MSROJV5.js} +1 -1
- package/chunks/{notebook-edit-XKULPMG7.js → notebook-edit-VDWBIBMG.js} +1 -1
- package/chunks/{omni-H3GFC6KR.js → omni-MEUE65XC.js} +1 -1
- package/chunks/{openaiContentGenerator-RT4S6OYR.js → openaiContentGenerator-KNZTYVNK.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-JD4ZBCAL.js → openaiResponsesContentGenerator-G7GRJXES.js} +1 -1
- package/chunks/{pidfile-JXCPPGC6.js → pidfile-HMEKKPWO.js} +1 -1
- package/chunks/{processUtils-FF7LHGHW.js → processUtils-KHWNT3KU.js} +1 -1
- package/chunks/{prompt-terminal-ledger-VLIEJ5BB.js → prompt-terminal-ledger-EY72RU3D.js} +1 -1
- package/chunks/{qwenContentGenerator-6SGQI4ES.js → qwenContentGenerator-A7WREYLV.js} +1 -1
- package/chunks/{reactive-degrade-2UJPX4AU.js → reactive-degrade-O6WBGQ5X.js} +1 -1
- package/chunks/{read-file-27DWTM5N.js → read-file-A4MQWC6T.js} +1 -1
- package/chunks/{resumeHistoryUtils-KRF2LD7T.js → resumeHistoryUtils-KNUVMH5J.js} +1 -1
- package/chunks/{review-IPFFTVGV.js → review-OC76PLQ4.js} +1 -1
- package/chunks/{ripGrep-75QL35XD.js → ripGrep-JR6DHTIW.js} +1 -1
- package/chunks/{run-qwen-serve-WW74NSUL.js → run-qwen-serve-NFPGPJJ2.js} +2 -2
- package/chunks/{runtime-Z2NIOF6Y.js → runtime-BPHFAZOP.js} +1 -1
- package/chunks/{sandboxConfig-WMQAKX7Q.js → sandboxConfig-KXTV3QBG.js} +1 -1
- package/chunks/{scheduled-tasks-LMJJ5ZM7.js → scheduled-tasks-2GNFZH4N.js} +1 -1
- package/chunks/{scheduler-KHWWXW6H.js → scheduler-CKLZCETX.js} +1 -1
- package/chunks/{search-memory-WEO3M674.js → search-memory-ICNU2EJA.js} +1 -1
- package/chunks/{send-message-E2EVXDU4.js → send-message-T32PFXX5.js} +1 -1
- package/chunks/{serve-E7ZGE7PD.js → serve-O7XBFM36.js} +1 -1
- package/chunks/{server-SSHP5IO4.js → server-7H2EGX7C.js} +3 -3
- package/chunks/{session-UWUQU3NV.js → session-SO4TKKO3.js} +1 -1
- package/chunks/{session-attachments-root-I35OUD7P.js → session-attachments-root-QPBJB3Y2.js} +1 -1
- package/chunks/{session-execution-engine-selector-S7HXLYKG.js → session-execution-engine-selector-73JQ7AG6.js} +1 -1
- package/chunks/{session-pr-refresh-34FLQB2Z.js → session-pr-refresh-XPDBRBQV.js} +1 -1
- package/chunks/{sessionService-BBC2563F.js → sessionService-DDLWVLNC.js} +1 -1
- package/chunks/{settings-BXCTAYMU.js → settings-TUEKBNAX.js} +1 -1
- package/chunks/{shell-ORZNRZKX.js → shell-SXSN7UYK.js} +1 -1
- package/chunks/{skill-3MJ6V2VQ.js → skill-XAYT7HGV.js} +1 -1
- package/chunks/{skill-settings-A7TTYJGH.js → skill-settings-X3O75XUN.js} +1 -1
- package/chunks/{spawnChannel-UPHPUPIJ.js → spawnChannel-3523LPUW.js} +1 -1
- package/chunks/{standalone-update-GGHQ54QB.js → standalone-update-T7AUODLV.js} +1 -1
- package/chunks/{start-opentui-ui-O6WMWLGS.js → start-opentui-ui-IKBADQQS.js} +1 -1
- package/chunks/{startInteractiveUI-N3ZPR2FK.js → startInteractiveUI-PV2JETB4.js} +1 -1
- package/chunks/{team-create-EYLFAQVU.js → team-create-ZKTBFE7Z.js} +1 -1
- package/chunks/{team-plan-approval-2WFSX4XE.js → team-plan-approval-SCTAN2HM.js} +1 -1
- package/chunks/{terminal-image-renderer-A5HEJZTW.js → terminal-image-renderer-EDBYTK3B.js} +1 -1
- package/chunks/{theme-manager-TQHNJSKQ.js → theme-manager-ZLXHLO2Y.js} +1 -1
- package/chunks/{tool-call-UBLAA45C.js → tool-call-ULUE3W3P.js} +1 -1
- package/chunks/{tool-result-media-53AD3EHK.js → tool-result-media-VXS7QTX7.js} +1 -1
- package/chunks/{tool-search-D6PSBDDZ.js → tool-search-VWM6VCVU.js} +1 -1
- package/chunks/{total-session-admission-CUMMWSM2.js → total-session-admission-FZDBG232.js} +1 -1
- package/chunks/{trustedFolders-TERXKVJ6.js → trustedFolders-VIPEDZNB.js} +1 -1
- package/chunks/{update-relaunch-PXCI66U2.js → update-relaunch-N6TNUHQE.js} +1 -1
- package/chunks/{updateCheck-2P4ANPL7.js → updateCheck-367IR3FW.js} +1 -1
- package/chunks/{upload-config-G2WZG4DM.js → upload-config-5W4WTLML.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-H7I7JP34.js → useAutoAcceptIndicator-SGT7EBCJ.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-VLRV5LCK.js → validateNonInterActiveAuth-7WEBPZ4S.js} +1 -1
- package/chunks/{version-AOKDKXXZ.js → version-3OKRQ6LC.js} +1 -1
- package/chunks/{web-fetch-OUJS56AV.js → web-fetch-BV7BK5NT.js} +1 -1
- package/chunks/{web-search-3S4ZIGLP.js → web-search-DFQ74G7V.js} +1 -1
- package/chunks/{workflow-6W4WB4L5.js → workflow-EXSCHLQK.js} +1 -1
- package/chunks/{workspace-agents-7GB2RLY5.js → workspace-agents-HPOPFXKJ.js} +1 -1
- package/chunks/{workspace-providers-status-OMD57CUW.js → workspace-providers-status-UQCSR2PB.js} +1 -1
- package/chunks/{workspace-registration-store-WKLFVMQ2.js → workspace-registration-store-Q5U4WD5M.js} +1 -1
- package/chunks/{workspace-registry-6WJOPYIS.js → workspace-registry-I2O2LXTZ.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-XG7G7DG3.js → workspace-runtime-coordinator-MVVDZYYX.js} +1 -1
- package/chunks/{workspace-service-YLX46RJM.js → workspace-service-CFJ2EUB7.js} +1 -1
- package/chunks/{workspace-skills-status-JZZR7QHN.js → workspace-skills-status-LLNIK3NS.js} +1 -1
- package/chunks/{workspace-trust-reconciler-AO3I5KYO.js → workspace-trust-reconciler-VLGJXLCZ.js} +1 -1
- package/chunks/{write-file-MGYLC32T.js → write-file-RG7HHIYP.js} +1 -1
- package/chunks/{zoom-image-TZ527ASZ.js → zoom-image-AKW6CA4K.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/package.json +3 -3
- package/web-shell/assets/{PierreFilePreview-Cq9imG0c.js → PierreFilePreview-Cij36lF-.js} +1 -1
- package/web-shell/assets/{SpreadsheetPreview-Blho0kkO.js → SpreadsheetPreview-kDlHrK21.js} +1 -1
- package/web-shell/assets/{WorkspaceFileBrowser-DjeX-ArR.js → WorkspaceFileBrowser-DBXW9l-s.js} +1 -1
- package/web-shell/assets/{abnfDiagram-VCTEODGH-mEfLgGao.js → abnfDiagram-VCTEODGH-DBrfOx4O.js} +1 -1
- package/web-shell/assets/{agents-route-Bg4_tLdL.js → agents-route-6E_3XRjk.js} +1 -1
- package/web-shell/assets/{arc-DEVpMJqB.js → arc-RwrvKU6y.js} +1 -1
- package/web-shell/assets/{architectureDiagram-5GKGNRK7-CGhqKvd1.js → architectureDiagram-5GKGNRK7-B2_hfNn6.js} +1 -1
- package/web-shell/assets/{blockDiagram-NRAW4CY4-DxpWdCdl.js → blockDiagram-NRAW4CY4-C755qTFO.js} +1 -1
- package/web-shell/assets/{c4Diagram-UCG6FXSJ-CE1W0_yu.js → c4Diagram-UCG6FXSJ-CARC2uHQ.js} +1 -1
- package/web-shell/assets/channel-U9JRrjem.js +1 -0
- package/web-shell/assets/{chunk-2Q5K7J3B-ibHTXjoH.js → chunk-2Q5K7J3B-BS1ldEp9.js} +1 -1
- package/web-shell/assets/{chunk-5VM5RSS4-BEZ2-gCE.js → chunk-5VM5RSS4-DckOEd3N.js} +1 -1
- package/web-shell/assets/{chunk-F27PBJKO-CKyPZ7Jh.js → chunk-F27PBJKO-fZstOLLL.js} +1 -1
- package/web-shell/assets/{chunk-G27WJ6UU-WHNRb7iQ.js → chunk-G27WJ6UU-Bf4QkrJ7.js} +1 -1
- package/web-shell/assets/{chunk-JWPE2WC7-Dm4G-fLP.js → chunk-JWPE2WC7-uBW51XO_.js} +1 -1
- package/web-shell/assets/{chunk-LCL6LL3I-BvTm39E-.js → chunk-LCL6LL3I-D2MYZdE_.js} +1 -1
- package/web-shell/assets/{chunk-POPQ4Y6H-C0zAbzIo.js → chunk-POPQ4Y6H-CzTHTST7.js} +1 -1
- package/web-shell/assets/{chunk-SVP7TREG-B36K-VPq.js → chunk-SVP7TREG-fL48tjL5.js} +1 -1
- package/web-shell/assets/{chunk-XXDRQBXY-D1opdtZ1.js → chunk-XXDRQBXY-R1jjDz-e.js} +1 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-r255RW6f.js +1 -0
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-r255RW6f.js +1 -0
- package/web-shell/assets/{cose-bilkent-JH36ORCC-S_IO4ZW5.js → cose-bilkent-JH36ORCC-DTK6Alrt.js} +1 -1
- package/web-shell/assets/{cynefin-OW5HDTMX-CGUKfurr.js → cynefin-OW5HDTMX-C1JYDjN4.js} +1 -1
- package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-BqUpO_VD.js → cynefinDiagram-5FMLGOSQ-C3bR18IM.js} +1 -1
- package/web-shell/assets/{dagre-3AP2YEHR-CiKqZpUi.js → dagre-3AP2YEHR-D4oUlW7g.js} +1 -1
- package/web-shell/assets/{diagram-S7CK7UJ4-B3CQED4o.js → diagram-S7CK7UJ4-m-a-vk_2.js} +1 -1
- package/web-shell/assets/{diagram-UQ7AKVKN-BewunX5H.js → diagram-UQ7AKVKN-CVGSVvpJ.js} +1 -1
- package/web-shell/assets/{diagram-VSXAHHWV-C5j1hiVn.js → diagram-VSXAHHWV-DcLovKfd.js} +1 -1
- package/web-shell/assets/{diagram-VX7I27RA-CWDIIA61.js → diagram-VX7I27RA-DAwY09qQ.js} +1 -1
- package/web-shell/assets/{diagram-Z3DM3KII-COa1V8UD.js → diagram-Z3DM3KII-D4BWV8Yb.js} +1 -1
- package/web-shell/assets/{ebnfDiagram-PWID7BFC-CP33EIO8.js → ebnfDiagram-PWID7BFC-AhqQLlAR.js} +1 -1
- package/web-shell/assets/{erDiagram-SSCWMZ5O-V2pL2JAp.js → erDiagram-SSCWMZ5O-DcIpsPuK.js} +1 -1
- package/web-shell/assets/{flowDiagram-A5DVABFB-CF-YQlR_.js → flowDiagram-A5DVABFB-Cdu3v56D.js} +1 -1
- package/web-shell/assets/{ganttDiagram-EL5Y4UJY-TXUid-Q2.js → ganttDiagram-EL5Y4UJY-D8o98Muo.js} +1 -1
- package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-QNcIYsgn.js → gitGraphDiagram-WWUBYQGX-fIAd56jC.js} +1 -1
- package/web-shell/assets/{index-CKa6aZMZ.js → index-CJmvuO8Q.js} +1 -1
- package/web-shell/assets/{index-N9F4X44H.js → index-DSh5Yfsf.js} +5 -5
- package/web-shell/assets/{infoDiagram-RXCK75RN-Dn1biwuc.js → infoDiagram-RXCK75RN-dPnP0Koe.js} +1 -1
- package/web-shell/assets/{ishikawaDiagram-5VMMS53U-iBYO7WCt.js → ishikawaDiagram-5VMMS53U-f9Oq8YH7.js} +1 -1
- package/web-shell/assets/{journeyDiagram-EYS64GPL-D98LzO4k.js → journeyDiagram-EYS64GPL-CqwSlUQ1.js} +1 -1
- package/web-shell/assets/{kanban-definition-3QL26DDD-lQMIgDSM.js → kanban-definition-3QL26DDD-Bh_KTp2S.js} +1 -1
- package/web-shell/assets/{layout-BgOy6tFo.js → layout-0e-hGnuM.js} +1 -1
- package/web-shell/assets/{linear-En8RXsBs.js → linear-BtxWFISv.js} +1 -1
- package/web-shell/assets/{mermaid.core-BneKXyZr.js → mermaid.core-Dik4l-jM.js} +6 -6
- package/web-shell/assets/{mindmap-definition-FBJOCRG2-NkP_9BC4.js → mindmap-definition-FBJOCRG2-B7gext3e.js} +1 -1
- package/web-shell/assets/{pegDiagram-XKGWAZYB-B0ie-nkt.js → pegDiagram-XKGWAZYB-BfyKzGY0.js} +1 -1
- package/web-shell/assets/{pieDiagram-E7YTZNPT-Qa86cFZc.js → pieDiagram-E7YTZNPT-vfeVyHgh.js} +1 -1
- package/web-shell/assets/{quadrantDiagram-AXDQQJYC-CkjUzR0e.js → quadrantDiagram-AXDQQJYC-DGAZmngq.js} +1 -1
- package/web-shell/assets/{railroadDiagram-O6MQD6OU-mN7KpgJG.js → railroadDiagram-O6MQD6OU-Dgxiy8W5.js} +1 -1
- package/web-shell/assets/{requirementDiagram-EFPCY7ZU-Bmn2z6x2.js → requirementDiagram-EFPCY7ZU-D7TFokdR.js} +1 -1
- package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CYWnwpoW.js → sankeyDiagram-P5KCCOFB-BZU_UYd-.js} +1 -1
- package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BFyWlR1P.js → sequenceDiagram-WJ2MYXX4-Bz94qtvq.js} +1 -1
- package/web-shell/assets/{sizeCapture-X5ZJPWSS-BwCPrn2w.js → sizeCapture-X5ZJPWSS-DVlzIShY.js} +1 -1
- package/web-shell/assets/{stateDiagram-HBIQ2CUA-oqL3E0Ws.js → stateDiagram-HBIQ2CUA-CE9Il33j.js} +1 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BVL1rIGD.js +1 -0
- package/web-shell/assets/{swimlanes-XN3QIQJK-C3FAVL8g.js → swimlanes-XN3QIQJK-Cr2CyF9L.js} +1 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-BeWJAUmf.js +8 -0
- package/web-shell/assets/{timeline-definition-24CTP7MA-BdwxFsPJ.js → timeline-definition-24CTP7MA-DWbRlUDe.js} +1 -1
- package/web-shell/assets/{vennDiagram-4TSXK5OY-j_G2AbSj.js → vennDiagram-4TSXK5OY-Bp5BiaRL.js} +1 -1
- package/web-shell/assets/{wardleyDiagram-VM6X3IG4-Dy_fHHBq.js → wardleyDiagram-VM6X3IG4-DoQIUrT8.js} +1 -1
- package/web-shell/assets/{xychartDiagram-S5SC5T6Z-CnLgG50x.js → xychartDiagram-S5SC5T6Z-BTO308Vv.js} +1 -1
- package/web-shell/index.html +1 -1
- package/web-shell/sw.js +1 -1
- package/web-shell/assets/channel-CHCXOu89.js +0 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-DXIqcod_.js +0 -1
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-DXIqcod_.js +0 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-Cmho6gw2.js +0 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-D9Sfkn7b.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{sanitizeFilenameComponent}from"./chunk-GG7RNHZW.js";import{writeStderrLineSafe}from"./chunk-SLPJ4OII.js";import{createDebugLogger}from"./chunk-JAUJI56S.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{execFileSync as execFileSync2}from"node:child_process";import{randomBytes}from"node:crypto";import{existsSync as existsSync5,lstatSync as lstatSync4,mkdirSync as mkdirSync3,readFileSync as readFileSync3,readdirSync as readdirSync4,renameSync,rmdirSync,rmSync as rmSync3,writeFileSync as writeFileSync2}from"node:fs";import{basename as basename2,dirname as dirname4,isAbsolute as isAbsolute3,join as join4,relative as relative2,resolve as resolve4}from"node:path";init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync4,lstatSync as lstatSync3,mkdirSync as mkdirSync2,readdirSync as readdirSync3,realpathSync as realpathSync3,statSync as statSync2}from"node:fs";import{dirname as dirname3,isAbsolute as isAbsolute2,join as join3,relative,resolve as resolve3,sep as sep2}from"node:path";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();import{execFileSync,spawnSync as spawnSync2}from"node:child_process";init_esbuild_shims();import{spawnSync}from"node:child_process";import{accessSync,constants,existsSync as existsSync2,lstatSync,mkdirSync,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,realpathSync,rmSync,statSync,symlinkSync,writeFileSync}from"node:fs";import{homedir,tmpdir}from"node:os";import{basename,dirname,isAbsolute,join as join2,resolve,sep}from"node:path";init_esbuild_shims();import{existsSync,readFileSync,readdirSync}from"node:fs";import{join}from"node:path";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(?=\s|$)|--?ws(?=\s|$))/.test(text)}__name(scriptFansOut,"scriptFansOut");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(packages.map(p=>[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");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=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=(resolved+sep).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?resolve(root,".."):outermost;try{if(redirectedAncestor(root,bound)!==null){return{root:null,nullKind:"refused"}}const real=realpathSync(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=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;return(resolved+sep).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=spawnSync("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(join2(gitDir,"gitdir"),"utf8").replace(/\n$/,"")}catch{return null}const ownerSpelled=dirname(resolve(gitDir,backpointer));let ownerTree;try{ownerTree=realpathSync(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=realpathSync(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(!existsSync2(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(!existsSync2(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=join2(tree,".git");let stat;try{stat=lstatSync(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=realpathSync.native??realpathSync;real=canonical(resolve(gitDir));realRoot=canonical(root)}catch{return true}return isSubpath(outermostReviewTmpRoot(realRoot),real)}__name(adminEntryInsideReviewTmp,"adminEntryInsideReviewTmp");function outermostReviewTmpRoot(root){const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;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=resolve(stopAt);let stopReal=stop;try{stopReal=realpathSync(stopAt)}catch{}for(let cur=resolve(dir);;cur=dirname(cur)){let isLink;try{isLink=lstatSync(cur).isSymbolicLink()}catch{isLink=false}if(isLink)return cur;if(cur===stop)return null;try{if(realpathSync(cur)===stopReal)return null}catch{}if(dirname(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";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=[join2(commonDir,"config"),join2(gitDir,"config.worktree")];try{for(const entry of readdirSync2(join2(commonDir,"worktrees"))){candidates.push(join2(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=spawnSync("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=realpathSync.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(!statSync(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()}${sep}${value.slice(2)}`}else if(value.startsWith("~")){unread.add(`${key} -> ${value} (another user's home \u2014 not resolved here)`);continue}else{target=isAbsolute(value)?value:`${dirname(file)}${sep}${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=spawnSync("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=spawnSync("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=lstatSync(tree).isSymbolicLink()}catch{}const ownAdminDir=adminDirOf(tree);let sweep;if(!symlink){sweep=spawnSync("git",["worktree","remove","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(sweep.status!==0){spawnSync("git",["worktree","unlock",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});sweep=spawnSync("git",["worktree","remove","--force","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()})}}rmSync(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{rmSync(adminDir,{recursive:true,force:true})}catch{}return}const common=spawnSync("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=join2(common.stdout.trim(),"worktrees");let ids;try{ids=readdirSync2(dir)}catch{return}const wanted=samePath(tree);const ownId=basename(resolve(tree));const ownIdPattern=new RegExp(`^${ownId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\d*$`);for(const id of ids){if(!ownIdPattern.test(id))continue;try{const gitdir=readFileSync2(join2(dir,id,"gitdir"),"utf8").trim();const named=dirname(gitdir);if(samePath(named)!==wanted)continue;if(existsSync2(named))continue;rmSync(join2(dir,id),{recursive:true,force:true})}catch{}}}__name(dropWorktreeRegistration,"dropWorktreeRegistration");function adminDirOf(tree){try{const pointer=readFileSync2(join2(tree,".git"),"utf8").trim();const match=/^gitdir:\s*(.+)$/.exec(pointer);if(!match)return null;const dir=resolve(dirname(resolve(tree)),match[1].trim());const back=readFileSync2(join2(dir,"gitdir"),"utf8").trim();return samePath(dirname(back))===samePath(tree)?dir:null}catch{return null}}__name(adminDirOf,"adminDirOf");function samePath(p){const abs=resolve(p);try{return join2(realpathSync(dirname(abs)),basename(abs))}catch{return abs}}__name(samePath,"samePath");var pipelineExcludesFile=null;function pipelineExcludeArgs(){if(pipelineExcludesFile===null){try{const file=join2(mkdtempSync(join2(tmpdir(),"qwen-review-excludes-")),"excludes").split(sep).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=spawnSync("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&&!isAbsolute(s)&&!s.split("/").some(p=>p===".."));if(inside.length===0)return new Set;const r=spawnSync("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(!lstatSync(join2(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=spawnSync("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&&realpathSync(toplevel)===realpathSync(cwd)){isWorktree=true;if(lstatSync(cwd).isSymbolicLink()){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${resolve(cwd)}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}const spelled=resolve(cwd);const bound=dirname(commonDir);const redirected=redirectedAncestor(dirname(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(join2(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=realpathSync(dirname(resolve(gitDir,backpointer)))===realpathSync(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=${realpathSync(gitDir)}`,`--work-tree=${realpathSync(toplevel)}`];if(expectedHeadSha!==void 0){const head=spawnSync("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,realpathSync(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=spawnSync("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=spawnSync("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=spawnSync("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 readdirSync2(join2(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=spawnSync("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 realpathSync(m.source)!==realpathSync(dependencyRoot)}catch{return true}});let rootNm=null;try{const nm=join2(dependencyRoot,"node_modules");if(lstatSync(nm).isDirectory())rootNm=realpathSync(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([join2(probeTree,"node_modules")]);for(const{dir,source}of memberSources){const target=containedIn(probeTree,dir);if(!source||!target){if(existsSync2(join2(dependencyRoot,dir)))done.failed++;continue}if(!existsSync2(target))continue;owned.add(join2(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(realpathSync(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=readdirSync2(dir,{withFileTypes:true})}catch{done.failed++;return}for(const entry of entries){const full=join2(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full)){try{rmSync(full,{recursive:true,force:true})}catch{done.failed++}}continue}if(entry.name===".git")continue;if(entry.isSymbolicLink()){try{const real=realpathSync(full);const root=realpathSync(tree);if(!statSync(full).isDirectory()){}else if(real===root||real.startsWith(root+sep)){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(realpathSync(path))}catch{return false}}__name(isOwned,"isOwned");function holdsNodeModules(dir,owned){let entries;try{entries=readdirSync2(dir,{withFileTypes:true})}catch{return false}for(const entry of entries){const full=join2(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=realpathSync(resolve(root));const full=resolve(base,dir);const real=existsSync2(full)?realpathSync(full):full;return real===base||real.startsWith(base+sep)?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+sep)}__name(insideDir,"insideDir");function marksOurFarm(target,sourceDir){try{return readFileSync2(join2(target,FARM_MARKER),"utf8").trim()===resolve(sourceDir)}catch{return false}}__name(marksOurFarm,"marksOurFarm");function farmNodeModules(sourceDir,targetDir,done,containment,rebuild=false){const source=join2(sourceDir,"node_modules");const target=join2(targetDir,"node_modules");if(!existsSync2(source)){if(rebuild){try{lstatSync(target);rmSync(target,{recursive:true,force:true})}catch(err){if(err.code!=="ENOENT")done.failed++}}return}try{if(!lstatSync(source).isDirectory()){done.failed++;return}}catch{done.failed++;return}let sourceNm;try{sourceNm=realpathSync(source)}catch{done.failed++;return}let targetPresent=true;try{lstatSync(target)}catch{targetPresent=false}if(targetPresent){if(!rebuild&&marksOurFarm(target,sourceDir)){done.alreadyPresent=true;return}try{rmSync(target,{recursive:true,force:true})}catch{done.failed++;return}}try{mkdirSync(target)}catch{done.failed++;return}const linkType=process.platform==="win32"?"junction":"dir";let entries;try{entries=readdirSync2(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=join2(source,entry.name);const targetEntry=join2(target,entry.name);let sourceStats;try{sourceStats=lstatSync(sourceEntry)}catch{done.failed++;continue}if(!sourceStats.isDirectory()&&!sourceStats.isSymbolicLink()){continue}if(sourceStats.isSymbolicLink()){let real;try{real=realpathSync(sourceEntry)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync(sourceEntry).isDirectory())continue}catch{done.failed++;continue}}if(entry.name.startsWith("@")){let pkgs;try{mkdirSync(targetEntry);pkgs=readdirSync2(sourceEntry)}catch{done.failed++;continue}for(const pkg of pkgs){const scopedSource=join2(sourceEntry,pkg);let real;try{real=realpathSync(scopedSource)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync(scopedSource).isDirectory())continue}catch{done.failed++;continue}try{symlinkSync(scopedSource,join2(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(join2(target,FARM_MARKER),`${resolve(sourceDir)}
|
|
3
|
+
import{sanitizeFilenameComponent}from"./chunk-IFAUFERF.js";import{writeStderrLineSafe}from"./chunk-SLPJ4OII.js";import{createDebugLogger}from"./chunk-JAUJI56S.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{execFileSync as execFileSync2}from"node:child_process";import{randomBytes}from"node:crypto";import{existsSync as existsSync5,lstatSync as lstatSync4,mkdirSync as mkdirSync3,readFileSync as readFileSync3,readdirSync as readdirSync4,renameSync,rmdirSync,rmSync as rmSync3,writeFileSync as writeFileSync2}from"node:fs";import{basename as basename2,dirname as dirname4,isAbsolute as isAbsolute3,join as join4,relative as relative2,resolve as resolve4}from"node:path";init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync4,lstatSync as lstatSync3,mkdirSync as mkdirSync2,readdirSync as readdirSync3,realpathSync as realpathSync3,statSync as statSync2}from"node:fs";import{dirname as dirname3,isAbsolute as isAbsolute2,join as join3,relative,resolve as resolve3,sep as sep2}from"node:path";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();import{execFileSync,spawnSync as spawnSync2}from"node:child_process";init_esbuild_shims();import{spawnSync}from"node:child_process";import{accessSync,constants,existsSync as existsSync2,lstatSync,mkdirSync,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,realpathSync,rmSync,statSync,symlinkSync,writeFileSync}from"node:fs";import{homedir,tmpdir}from"node:os";import{basename,dirname,isAbsolute,join as join2,resolve,sep}from"node:path";init_esbuild_shims();import{existsSync,readFileSync,readdirSync}from"node:fs";import{join}from"node:path";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(?=\s|$)|--?ws(?=\s|$))/.test(text)}__name(scriptFansOut,"scriptFansOut");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(packages.map(p=>[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");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=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=(resolved+sep).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?resolve(root,".."):outermost;try{if(redirectedAncestor(root,bound)!==null){return{root:null,nullKind:"refused"}}const real=realpathSync(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=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;return(resolved+sep).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=spawnSync("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(join2(gitDir,"gitdir"),"utf8").replace(/\n$/,"")}catch{return null}const ownerSpelled=dirname(resolve(gitDir,backpointer));let ownerTree;try{ownerTree=realpathSync(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=realpathSync(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(!existsSync2(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(!existsSync2(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=join2(tree,".git");let stat;try{stat=lstatSync(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=realpathSync.native??realpathSync;real=canonical(resolve(gitDir));realRoot=canonical(root)}catch{return true}return isSubpath(outermostReviewTmpRoot(realRoot),real)}__name(adminEntryInsideReviewTmp,"adminEntryInsideReviewTmp");function outermostReviewTmpRoot(root){const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;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=resolve(stopAt);let stopReal=stop;try{stopReal=realpathSync(stopAt)}catch{}for(let cur=resolve(dir);;cur=dirname(cur)){let isLink;try{isLink=lstatSync(cur).isSymbolicLink()}catch{isLink=false}if(isLink)return cur;if(cur===stop)return null;try{if(realpathSync(cur)===stopReal)return null}catch{}if(dirname(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";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=[join2(commonDir,"config"),join2(gitDir,"config.worktree")];try{for(const entry of readdirSync2(join2(commonDir,"worktrees"))){candidates.push(join2(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=spawnSync("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=realpathSync.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(!statSync(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()}${sep}${value.slice(2)}`}else if(value.startsWith("~")){unread.add(`${key} -> ${value} (another user's home \u2014 not resolved here)`);continue}else{target=isAbsolute(value)?value:`${dirname(file)}${sep}${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=spawnSync("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=spawnSync("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=lstatSync(tree).isSymbolicLink()}catch{}const ownAdminDir=adminDirOf(tree);let sweep;if(!symlink){sweep=spawnSync("git",["worktree","remove","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(sweep.status!==0){spawnSync("git",["worktree","unlock",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});sweep=spawnSync("git",["worktree","remove","--force","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()})}}rmSync(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{rmSync(adminDir,{recursive:true,force:true})}catch{}return}const common=spawnSync("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=join2(common.stdout.trim(),"worktrees");let ids;try{ids=readdirSync2(dir)}catch{return}const wanted=samePath(tree);const ownId=basename(resolve(tree));const ownIdPattern=new RegExp(`^${ownId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\d*$`);for(const id of ids){if(!ownIdPattern.test(id))continue;try{const gitdir=readFileSync2(join2(dir,id,"gitdir"),"utf8").trim();const named=dirname(gitdir);if(samePath(named)!==wanted)continue;if(existsSync2(named))continue;rmSync(join2(dir,id),{recursive:true,force:true})}catch{}}}__name(dropWorktreeRegistration,"dropWorktreeRegistration");function adminDirOf(tree){try{const pointer=readFileSync2(join2(tree,".git"),"utf8").trim();const match=/^gitdir:\s*(.+)$/.exec(pointer);if(!match)return null;const dir=resolve(dirname(resolve(tree)),match[1].trim());const back=readFileSync2(join2(dir,"gitdir"),"utf8").trim();return samePath(dirname(back))===samePath(tree)?dir:null}catch{return null}}__name(adminDirOf,"adminDirOf");function samePath(p){const abs=resolve(p);try{return join2(realpathSync(dirname(abs)),basename(abs))}catch{return abs}}__name(samePath,"samePath");var pipelineExcludesFile=null;function pipelineExcludeArgs(){if(pipelineExcludesFile===null){try{const file=join2(mkdtempSync(join2(tmpdir(),"qwen-review-excludes-")),"excludes").split(sep).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=spawnSync("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&&!isAbsolute(s)&&!s.split("/").some(p=>p===".."));if(inside.length===0)return new Set;const r=spawnSync("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(!lstatSync(join2(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=spawnSync("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&&realpathSync(toplevel)===realpathSync(cwd)){isWorktree=true;if(lstatSync(cwd).isSymbolicLink()){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${resolve(cwd)}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}const spelled=resolve(cwd);const bound=dirname(commonDir);const redirected=redirectedAncestor(dirname(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(join2(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=realpathSync(dirname(resolve(gitDir,backpointer)))===realpathSync(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=${realpathSync(gitDir)}`,`--work-tree=${realpathSync(toplevel)}`];if(expectedHeadSha!==void 0){const head=spawnSync("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,realpathSync(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=spawnSync("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=spawnSync("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=spawnSync("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 readdirSync2(join2(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=spawnSync("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 realpathSync(m.source)!==realpathSync(dependencyRoot)}catch{return true}});let rootNm=null;try{const nm=join2(dependencyRoot,"node_modules");if(lstatSync(nm).isDirectory())rootNm=realpathSync(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([join2(probeTree,"node_modules")]);for(const{dir,source}of memberSources){const target=containedIn(probeTree,dir);if(!source||!target){if(existsSync2(join2(dependencyRoot,dir)))done.failed++;continue}if(!existsSync2(target))continue;owned.add(join2(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(realpathSync(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=readdirSync2(dir,{withFileTypes:true})}catch{done.failed++;return}for(const entry of entries){const full=join2(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full)){try{rmSync(full,{recursive:true,force:true})}catch{done.failed++}}continue}if(entry.name===".git")continue;if(entry.isSymbolicLink()){try{const real=realpathSync(full);const root=realpathSync(tree);if(!statSync(full).isDirectory()){}else if(real===root||real.startsWith(root+sep)){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(realpathSync(path))}catch{return false}}__name(isOwned,"isOwned");function holdsNodeModules(dir,owned){let entries;try{entries=readdirSync2(dir,{withFileTypes:true})}catch{return false}for(const entry of entries){const full=join2(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=realpathSync(resolve(root));const full=resolve(base,dir);const real=existsSync2(full)?realpathSync(full):full;return real===base||real.startsWith(base+sep)?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+sep)}__name(insideDir,"insideDir");function marksOurFarm(target,sourceDir){try{return readFileSync2(join2(target,FARM_MARKER),"utf8").trim()===resolve(sourceDir)}catch{return false}}__name(marksOurFarm,"marksOurFarm");function farmNodeModules(sourceDir,targetDir,done,containment,rebuild=false){const source=join2(sourceDir,"node_modules");const target=join2(targetDir,"node_modules");if(!existsSync2(source)){if(rebuild){try{lstatSync(target);rmSync(target,{recursive:true,force:true})}catch(err){if(err.code!=="ENOENT")done.failed++}}return}try{if(!lstatSync(source).isDirectory()){done.failed++;return}}catch{done.failed++;return}let sourceNm;try{sourceNm=realpathSync(source)}catch{done.failed++;return}let targetPresent=true;try{lstatSync(target)}catch{targetPresent=false}if(targetPresent){if(!rebuild&&marksOurFarm(target,sourceDir)){done.alreadyPresent=true;return}try{rmSync(target,{recursive:true,force:true})}catch{done.failed++;return}}try{mkdirSync(target)}catch{done.failed++;return}const linkType=process.platform==="win32"?"junction":"dir";let entries;try{entries=readdirSync2(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=join2(source,entry.name);const targetEntry=join2(target,entry.name);let sourceStats;try{sourceStats=lstatSync(sourceEntry)}catch{done.failed++;continue}if(!sourceStats.isDirectory()&&!sourceStats.isSymbolicLink()){continue}if(sourceStats.isSymbolicLink()){let real;try{real=realpathSync(sourceEntry)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync(sourceEntry).isDirectory())continue}catch{done.failed++;continue}}if(entry.name.startsWith("@")){let pkgs;try{mkdirSync(targetEntry);pkgs=readdirSync2(sourceEntry)}catch{done.failed++;continue}for(const pkg of pkgs){const scopedSource=join2(sourceEntry,pkg);let real;try{real=realpathSync(scopedSource)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync(scopedSource).isDirectory())continue}catch{done.failed++;continue}try{symlinkSync(scopedSource,join2(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(join2(target,FARM_MARKER),`${resolve(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");import{existsSync as existsSync3,lstatSync as lstatSync2,realpathSync as realpathSync2,rmSync as rmSync2}from"node:fs";import{dirname as dirname2,resolve as resolve2}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=spawnSync2("/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 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(dirname2(resolve2(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(lstatSync2(worktreePath2).isSymbolicLink()){let removeError2;try{rmSync2(worktreePath2,{force:true})}catch(e){removeError2=e}const pruned2=gitProbe("worktree","prune");let stillThere2=false;try{lstatSync2(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=existsSync3(worktreePath2);let removeError;const removed=existed?gitProbe("worktree","remove",worktreePath2,"--force"):null;if(existed){try{rmSync2(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=existsSync3(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=resolve3(out);if(existsSync4(resolved)&&statSync2(resolved).isDirectory()){throw new TypeError(`--out names a directory, not a file: ${out}`)}}__name(assertWritableOutPath,"assertWritableOutPath");var REVIEW_TMP_DIR=join3(".qwen","tmp");var RETIRED_REVIEW_LEASE_DIR=join3(".qwen","review-leases");var REVIEW_TRUST_STATE_DIR="review-state";var REVIEWS_DIR=join3(".qwen","reviews");var REVIEW_CACHE_DIR=join3(".qwen","review-cache");function outermostReviewRepositoryRoot(repositoryRoot){const resolved=resolve3(repositoryRoot);const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;const at=(resolved+sep2).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 join3(Storage.getGlobalQwenDir(),REVIEW_TRUST_STATE_DIR,digest)}__name(reviewTrustStateDir,"reviewTrustStateDir");function reviewRepositoryRootForWorktree(worktree){const resolved=resolve3(worktree);const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;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=join3("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 join3(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=join3(projectDir,GENERATED_WORKFLOWS_SUBDIR);for(const component of[root,join3(root,REVIEW_WORKFLOWS_SUBDIR),dir]){let isLink=false;try{isLink=lstatSync3(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.`)}}mkdirSync2(dir,{recursive:true});const realDir=realpathSync3(dir);const realRoot=realpathSync3(root);if(realDir!==realRoot&&!realDir.startsWith(realRoot+sep2)){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=resolve3(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 join3(reviewWorkflowsDir(env),`${REVIEW_WORKFLOW_PREFIX}${digest}-${contentDigest}.js`)}__name(reviewWorkflowScriptPath,"reviewWorkflowScriptPath");var LEASE_PREFIX="qwen-review-lease-";var PARSE_ARGS_REPORT=join3(REVIEW_TMP_DIR,"qwen-review-parse-args.json");function lastReviewEffortPath(projectRoot,sessionProjectDir){const owner=sessionProjectDir?.trim()?resolve3(sessionProjectDir):new Storage(projectRoot).getProjectDir();return join3(owner,"review-last-effort")}__name(lastReviewEffortPath,"lastReviewEffortPath");function worktreePath(prNumber){return join3(REVIEW_TMP_DIR,`review-pr-${prNumber}`)}__name(worktreePath,"worktreePath");function probeWorktreePath(worktree){return`${resolve3(worktree)}-probe`}__name(probeWorktreePath,"probeWorktreePath");function baseWorktreePath(worktree){return`${resolve3(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`${resolve3(worktree)}${SCRATCH_INFIX}${safe}`}__name(scratchWorktreePath,"scratchWorktreePath");function scratchWorktreePrefix(worktree){return`${resolve3(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 join3(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[dirname3(REVIEW_TMP_DIR),REVIEW_TMP_DIR]){let isLink=false;try{isLink=lstatSync3(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 ${dirname3(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(sep2).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===dirname3(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.`)}mkdirSync2(REVIEW_TMP_DIR,{recursive:true})}__name(ensureReviewTmpDir,"ensureReviewTmpDir");function roundOwnedLinkOnDisk(command){const list=__name(dir=>{try{return readdirSync3(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=join3(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=join3(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=resolve3(REVIEW_TMP_DIR).toLowerCase();const target=resolve3(out).toLowerCase();return target===scratch||target.startsWith(scratch+sep2)}__name(writesIntoReviewTmp,"writesIntoReviewTmp");function isReviewWorktreeName(name){return/^review-pr-\d+(-probe|-base|-scratch-[^/]*)?$/.test(name)}__name(isReviewWorktreeName,"isReviewWorktreeName");function insideRepository(){let dir=resolve3(".");for(;;){if(existsSync4(join3(dir,".git")))return true;const parent=dirname3(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:join3(real,...walked.reverse())}catch{const parent=resolve3(cur,"..");if(parent===cur)return abs;walked.push(cur.slice(parent.length).replace(sep2==="/"?/^\/+/:/^[\\/]+/,""));cur=parent}}}__name(canonicalise,"canonicalise");function repoRelativeOf(repoRoot,file,from=process.cwd()){const abs=canonicalise(resolve3(from,file));const rel=relative(repoRoot,abs);const escapes=rel===".."||rel.startsWith(".."+sep2)||isAbsolute2(rel);return{rel:sep2==="/"?rel:rel.split(sep2).join("/"),abs,escapes}}__name(repoRelativeOf,"repoRelativeOf");function assertUnredirectedParent(target,what,command){const parent=resolve3(dirname3(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_TIMEOUT_MS2=12e4;var debugLogger=createDebugLogger("REVIEW_WORKTREE_LEASE");function gitOptions(timeout){return{stdio:"ignore",timeout,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}}__name(gitOptions,"gitOptions");function validTarget(target){return/^pr-\d+$/.test(target)}__name(validTarget,"validTarget");function isReviewLeaseFile(fileName){if(!fileName.startsWith(LEASE_PREFIX)||!fileName.endsWith(".json")){return false}const target=fileName.slice(LEASE_PREFIX.length,fileName.length-".json".length);return validTarget(target)}__name(isReviewLeaseFile,"isReviewLeaseFile");function leaseDirectory(repositoryRoot){return reviewTrustStateDir(repositoryRoot)}__name(leaseDirectory,"leaseDirectory");function legacyLeasePath(repositoryRoot,target){return join4(repositoryRoot,REVIEW_TMP_DIR,`${LEASE_PREFIX}${target}.json`)}__name(legacyLeasePath,"legacyLeasePath");function leasePath(repositoryRoot,target){return join4(leaseDirectory(repositoryRoot),`${LEASE_PREFIX}${target}.json`)}__name(leasePath,"leasePath");function clearReviewWorktreeLease(repositoryRoot,target){if(!validTarget(target))return;const root=resolve4(repositoryRoot);rmSync3(leasePath(root,target),{force:true});reclaimBaseTreeTrust(root,target);const legacy=legacyLeasePath(root,target);try{rmSync3(legacy,{force:true,recursive:true})}catch(error){writeStderrLineSafe(`warning: could not remove the pre-move review lease at ${legacy} (${error.code??error}); the trusted lease for ${target} is released, but a build from before the lease move will keep seeing this one until it is deleted by hand.`)}}__name(clearReviewWorktreeLease,"clearReviewWorktreeLease");function clearReviewWorktreeLeaseIfOwned(repositoryRoot,target,owner){const lease=readReviewWorktreeLease(repositoryRoot,target);if(!lease||lease.sessionId!==owner.sessionId||lease.promptId!==owner.promptId){return}clearReviewWorktreeLease(repositoryRoot,target)}__name(clearReviewWorktreeLeaseIfOwned,"clearReviewWorktreeLeaseIfOwned");function mintIdentity(){return Math.floor(Date.now()/1e3)*2**20+randomBytes(3).readUIntBE(0,3)%2**20}__name(mintIdentity,"mintIdentity");function recordReviewWorktreeLeaseMergeBase(repositoryRoot,target,mergeBaseSha,sessionId,options={}){if(!validTarget(target)||!mergeBaseSha)return;const stale=options.stale===true;const root=resolve4(repositoryRoot);const path=leasePath(root,target);const existing=readLease(path);if(!existing)return;if(sessionId!==void 0&&existing.sessionId!==sessionId)return;if(existing.mergeBaseSha===mergeBaseSha&&existing.mergeBaseStale===true===stale){return}const previous=existing.mergeBaseSha??existing.priorMergeBaseSha;const next={...existing,mergeBaseSha,mergeBaseStale:stale,priorMergeBaseSha:mergeBaseSha,priorMergeBaseStale:stale,priorMergeBaseCurrent:true,identity:previous===void 0||previous===mergeBaseSha?existing.identity??mintIdentity():mintIdentity()};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
|
|
5
5
|
`)}catch(error){debugLogger.debug(`Failed to record the merge base in ${path}:`,error)}}__name(recordReviewWorktreeLeaseMergeBase,"recordReviewWorktreeLeaseMergeBase");function atomicWriteLease(path,data){const tmp=`${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{writeFileSync2(tmp,data,{encoding:"utf8",flag:"wx"});renameSync(tmp,path)}catch(error){try{rmSync3(tmp,{force:true})}catch{}throw error}}__name(atomicWriteLease,"atomicWriteLease");function reclaimBaseTreeTrust(root,target){const dir=join4(leaseDirectory(root),"base-tree",target);let entries;try{entries=readdirSync4(dir)}catch(error){if(error.code!=="ENOENT"){debugLogger.debug(`Failed to reclaim base-tree trust state for ${target}:`,error)}return}for(const name of entries){if(name.endsWith(".lock"))continue;try{rmSync3(join4(dir,name),{recursive:true,force:true})}catch(error){debugLogger.debug(`Failed to reclaim base-tree trust state ${name} for ${target}:`,error)}}try{rmdirSync(dir)}catch{}}__name(reclaimBaseTreeTrust,"reclaimBaseTreeTrust");function restoreReviewWorktreeLeaseMergeBase(repositoryRoot,target,sessionId){if(!validTarget(target)||!sessionId)return;const path=leasePath(resolve4(repositoryRoot),target);const existing=readLease(path);if(!existing||existing.sessionId!==sessionId)return;if(existing.mergeBaseSha!==void 0)return;if(existing.priorMergeBaseResumable!==true)return;const next={...existing,mergeBaseSha:existing.priorMergeBaseSha,mergeBaseStale:existing.priorMergeBaseStale===true,priorMergeBaseCurrent:true};try{atomicWriteLease(path,`${JSON.stringify(next,null,2)}
|
|
6
6
|
`)}catch(error){debugLogger.debug(`Failed to restore the merge base in ${path}:`,error)}}__name(restoreReviewWorktreeLeaseMergeBase,"restoreReviewWorktreeLeaseMergeBase");function createReviewWorktreeLease(params){if(!params.sessionId||!params.promptId||!validTarget(params.target)){return}const repositoryRoot=resolve4(params.repositoryRoot);const path=leasePath(repositoryRoot,params.target);const leaseFor=__name((identity,prior)=>{const lease={sessionId:params.sessionId,promptId:params.promptId,target:params.target,repositoryRoot,worktreePath:resolve4(repositoryRoot,params.worktreePath),branch:params.branch,identity,...prior===void 0?{}:{priorMergeBaseSha:prior.sha,priorMergeBaseStale:prior.stale,priorMergeBaseResumable:prior.resumable}};return`${JSON.stringify(lease,null,2)}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{registerCleanup}from"./chunk-
|
|
3
|
+
import{registerCleanup}from"./chunk-SPFRORFN.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var MAX_PROFILES=5;var RATE_LIMIT_MS=3e4;var MIN_FREE_BYTES_AFTER_WRITE=256*1024*1024;var DEFAULT_SAMPLING_INTERVAL_US=1e3;var ESTIMATED_PROFILE_BYTES=10*1024*1024;var state="idle";var session=null;var initialized=false;var signalHandlerRegistered=false;var lastWriteByDir=new Map;function initCpuProfiler(){if(initialized)return;initialized=true;registerSignalHandler();registerCleanup(async()=>{if(state==="recording"){const result=await stopCpuProfile();if(result.ok){process.stderr.write(`[cpu-profiler] Profile written: ${result.filePath}
|
|
4
4
|
`)}}});const enabled=process.env["QWEN_CODE_CPU_PROFILE"]==="1";if(!enabled)return;void startCpuProfile().then(result=>{if(!result.ok){process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}
|
|
5
5
|
`)}})}__name(initCpuProfiler,"initCpuProfiler");async function startCpuProfile(opts){if(state!=="idle"){return{ok:false,error:state==="recording"?"CPU profiling is already in progress.":"CPU profiler is currently stopping. Please wait a moment and try again."}}state="recording";try{const inspectorSession=await getOrCreateSession();await inspectorSession.post("Profiler.enable");await inspectorSession.post("Profiler.setSamplingInterval",{interval:opts?.samplingInterval??DEFAULT_SAMPLING_INTERVAL_US});await inspectorSession.post("Profiler.start");return{ok:true}}catch(error){state="idle";disconnectSession();return{ok:false,error:formatError(error)}}}__name(startCpuProfile,"startCpuProfile");async function stopCpuProfile(options){if(state!=="recording"){return{ok:false,error:state==="idle"?"CPU profiler is not recording.":"CPU profiler is already stopping."}}const outputDir=options?.outputDir??defaultOutputDir();const now=options?.now??new Date;const rateLimitMs=options?.rateLimitMs??RATE_LIMIT_MS;const maxProfiles=options?.maxProfiles??MAX_PROFILES;try{enforceRateLimit(outputDir,now,rateLimitMs)}catch(error){state="idle";if(session){session.post("Profiler.stop").catch(()=>{});session.post("Profiler.disable").catch(()=>{})}disconnectSession();return{ok:false,error:formatError(error)}}state="stopping";try{if(!session){throw new Error("Inspector session lost unexpectedly during Profiler.stop; the profile data could not be retrieved.")}const result=await session.post("Profiler.stop");if(!result.profile){throw new Error("V8 Profiler.stop returned an empty profile; recording may have been interrupted.")}await session.post("Profiler.disable");fs.mkdirSync(outputDir,{recursive:true,mode:448});try{fs.chmodSync(outputDir,448)}catch{}checkDiskSpace(outputDir);const filePath=path.join(outputDir,`qwen-code-cpu-${process.pid}-${formatTimestamp(now)}.cpuprofile`);try{fs.writeFileSync(filePath,JSON.stringify(result.profile),{mode:384})}catch(writeError){try{fs.rmSync(filePath,{force:true})}catch{}throw writeError}recordWrite(outputDir,now);cleanupOldProfiles(outputDir,maxProfiles);state="idle";return{ok:true,filePath}}catch(error){state="idle";disconnectSession();return{ok:false,error:formatError(error)}}}__name(stopCpuProfile,"stopCpuProfile");function isCpuProfileRecording(){return state==="recording"}__name(isCpuProfileRecording,"isCpuProfileRecording");function registerSignalHandler(){if(signalHandlerRegistered)return;if(process.platform==="win32")return;signalHandlerRegistered=true;process.on("SIGUSR1",handleSigusr1)}__name(registerSignalHandler,"registerSignalHandler");function defaultOutputDir(){return path.join(os.homedir(),".qwen","cpu-profiles")}__name(defaultOutputDir,"defaultOutputDir");function formatTimestamp(now){return now.toISOString().replace(/[:.]/g,"-")}__name(formatTimestamp,"formatTimestamp");function formatError(error){return error instanceof Error?error.message:String(error)}__name(formatError,"formatError");var sessionFactory=null;async function getOrCreateSession(){if(session)return session;if(sessionFactory){session=await sessionFactory();return session}const inspectorModule=await import("node:inspector/promises");const newSession=new inspectorModule.Session;newSession.connect();session=newSession;return session}__name(getOrCreateSession,"getOrCreateSession");function disconnectSession(){if(session){try{session.disconnect()}catch{}session=null}}__name(disconnectSession,"disconnectSession");function handleSigusr1(){if(state==="idle"){void startCpuProfile().then(result=>{if(result.ok){process.stderr.write(`[cpu-profiler] Recording started (PID ${process.pid}). Send SIGUSR1 again to stop.
|
|
6
6
|
`)}else{process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";import{join}from"node:path";var cleanupFunctions=[];var exitCleanupPromise;function registerCleanup(fn,options={}){if(options.first)cleanupFunctions.unshift(fn);else cleanupFunctions.push(fn);return()=>{const index=cleanupFunctions.indexOf(fn);if(index!==-1)cleanupFunctions.splice(index,1)}}__name(registerCleanup,"registerCleanup");var PER_CLEANUP_TIMEOUT_MS=2e3;var OVERALL_CLEANUP_TIMEOUT_MS=5e3;function withTimeout(promise,ms){return new Promise(resolve=>{const timer=setTimeout(()=>resolve(void 0),ms);timer.unref?.();promise.then(value=>{clearTimeout(timer);resolve(value)},()=>{clearTimeout(timer);resolve(void 0)})})}__name(withTimeout,"withTimeout");function runExitCleanup(options={}){if(exitCleanupPromise)return exitCleanupPromise;const cleanup=runExitCleanupPass(options).finally(()=>{if(exitCleanupPromise===cleanup)exitCleanupPromise=void 0});exitCleanupPromise=cleanup;return cleanup}__name(runExitCleanup,"runExitCleanup");async function runExitCleanupPass(options){const perFn=options._testPerFnTimeoutMs??PER_CLEANUP_TIMEOUT_MS;const overall=options._testOverallTimeoutMs??OVERALL_CLEANUP_TIMEOUT_MS;const drain=(async()=>{for(const fn of cleanupFunctions){try{await withTimeout(Promise.resolve().then(fn),perFn)}catch(_){}}})();let wallClockTimer;const wallClock=new Promise(resolve=>{wallClockTimer=setTimeout(()=>resolve(),overall);wallClockTimer.unref?.()});try{await Promise.race([drain,wallClock])}finally{if(wallClockTimer)clearTimeout(wallClockTimer);cleanupFunctions.length=0}}__name(runExitCleanupPass,"runExitCleanupPass");async function cleanupCheckpoints(){const{Storage}=await import("./deferred-core-runtime-
|
|
3
|
+
import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";import{join}from"node:path";var cleanupFunctions=[];var exitCleanupPromise;function registerCleanup(fn,options={}){if(options.first)cleanupFunctions.unshift(fn);else cleanupFunctions.push(fn);return()=>{const index=cleanupFunctions.indexOf(fn);if(index!==-1)cleanupFunctions.splice(index,1)}}__name(registerCleanup,"registerCleanup");var PER_CLEANUP_TIMEOUT_MS=2e3;var OVERALL_CLEANUP_TIMEOUT_MS=5e3;function withTimeout(promise,ms){return new Promise(resolve=>{const timer=setTimeout(()=>resolve(void 0),ms);timer.unref?.();promise.then(value=>{clearTimeout(timer);resolve(value)},()=>{clearTimeout(timer);resolve(void 0)})})}__name(withTimeout,"withTimeout");function runExitCleanup(options={}){if(exitCleanupPromise)return exitCleanupPromise;const cleanup=runExitCleanupPass(options).finally(()=>{if(exitCleanupPromise===cleanup)exitCleanupPromise=void 0});exitCleanupPromise=cleanup;return cleanup}__name(runExitCleanup,"runExitCleanup");async function runExitCleanupPass(options){const perFn=options._testPerFnTimeoutMs??PER_CLEANUP_TIMEOUT_MS;const overall=options._testOverallTimeoutMs??OVERALL_CLEANUP_TIMEOUT_MS;const drain=(async()=>{for(const fn of cleanupFunctions){try{await withTimeout(Promise.resolve().then(fn),perFn)}catch(_){}}})();let wallClockTimer;const wallClock=new Promise(resolve=>{wallClockTimer=setTimeout(()=>resolve(),overall);wallClockTimer.unref?.()});try{await Promise.race([drain,wallClock])}finally{if(wallClockTimer)clearTimeout(wallClockTimer);cleanupFunctions.length=0}}__name(runExitCleanupPass,"runExitCleanupPass");async function cleanupCheckpoints(){const{Storage}=await import("./deferred-core-runtime-4HLTINJ6.js");const storage=new Storage(process.cwd());const tempDir=storage.getProjectTempDir();const checkpointsDir=join(tempDir,"checkpoints");try{await fs.rm(checkpointsDir,{recursive:true,force:true})}catch{}}__name(cleanupCheckpoints,"cleanupCheckpoints");export{registerCleanup,runExitCleanup,cleanupCheckpoints};
|
|
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{JsonOutputAdapter}from"./chunk-AGHGPOH6.js";import{normalizePartList}from"./chunk-HIO3M52C.js";import{settleChatRecording,subscribeToHeadlessChatRecordingFailures}from"./chunk-ULEYDXOX.js";import{StreamJsonOutputAdapter}from"./chunk-JQ7BCB3L.js";import{handleAtCommand}from"./chunk-TU6DWKVI.js";import{buildInitialSystemReminders,buildSystemMessage,computeUsageFromMetrics,createAgentToolProgressHandler,createToolProgressHandler,extractPartsFromUserMessage,handleSlashCommand,insertAfterFunctionResponses,isSlashCommand}from"./chunk-BMOJDKDZ.js";import{formatDuration}from"./chunk-PBC5IFGO.js";import{RunBudgetEnforcer,flushOutput}from"./chunk-Y5JLH3SN.js";import{sanitizeTerminalText}from"./chunk-MOH67CDU.js";import{cleanupReviewWorktreeLeases}from"./chunk-F3YGAXZ5.js";import{AlreadyReportedError,handleBudgetExceededError,handleCancellationError,handleError,handleMaxTurnsExceededError,handleToolError}from"./chunk-AII4DN7M.js";import{isInlineModelOverrideAllowed}from"./chunk-GT4TCQ3R.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{buildGoalContinuationParts,buildSessionRecoveryPlanFromApiHistory,detectAutonomousSentinel,detectLoopSentinel}from"./chunk-B3L4LODR.js";import{restoreWorktreeContext}from"./chunk-XIB6LAXR.js";import{MOD_END_TIMEOUT_MS,MOD_MAX_BYTES,executeToolCall,record,validateResult}from"./chunk-6OIJIF6G.js";import{GoalPersistenceUnavailableError,PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE,createDuplicateProviderToolCallResponse,finalizeToolResponses,findPlanModeEntryBatchBoundaryIndex,findRepeatedDuplicateProviderToolCall,getCachedToolCallFingerprint,getLastApiPromptCancellation,goalToolResultProvenance,isReplayOfHandledToolCall,isToolCallConcurrencySafe,markDuplicateProviderToolCallResponseSent,parseAndFormatApiError,partitionByConcurrencySafety,recordHandledToolCall}from"./chunk-GG7RNHZW.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{external_exports}from"./chunk-TWP72VRH.js";import{openNoFollow}from"./chunk-QXQGUM3Y.js";import{GOAL_PAUSE_REASON_HEADLESS_RUN_ENDED,GOAL_PAUSE_REASON_USER_INTERRUPT,addAgentOutputMessageAttributes,goalPauseReasonForHeadlessFailure,goalPauseReasonForRunBudget}from"./chunk-YPIUTOL3.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,hasImageParts,runVisionBridge,shouldRunVisionBridge,splitImageParts,uiTelemetryService}from"./chunk-KBPIYGHG.js";import{clampInlineMediaPart}from"./chunk-P3RLMP7L.js";import{endInteractionSpan,getActiveInteractionSpan,isTelemetrySdkInitialized,shutdownTelemetry}from"./chunk-AWTUIQ7W.js";import{registerCleanup}from"./chunk-U3YSYIQE.js";import{stripAnsiAndControl}from"./chunk-4YLXNRRH.js";import{isSystemReminderContent}from"./chunk-65UCR6OZ.js";import{ToolNames,canonicalToolName}from"./chunk-2UNFJQ2D.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{FatalInputError,getErrorType}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import{promises as fs}from"node:fs";import path from"node:path";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);var name=external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/);var dependency=external_exports.union([external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:@[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/),external_exports.object({name,marketplace:name.optional(),version:external_exports.string().optional()}).strict()]);function parseModDependencies(value){const parsed=external_exports.array(dependency).safeParse(value===void 0?[]:value);if(!parsed.success)throw new Error("Invalid Mod dependencies declaration.");return parsed.data.map(item=>{if(typeof item==="string"){const[name2,marketplace]=item.split("@");return{name:name2,marketplace}}if(item.version!==void 0&&!(0,import_semver.validRange)(item.version)){throw new Error(`Invalid Mod dependency version range for ${item.name}.`)}return item})}__name(parseModDependencies,"parseModDependencies");function resolveModDependency(plugins,plugin,dependency2){const marketplace=dependency2.marketplace??plugin.marketplace;const local=plugins.filter(item=>item.name===dependency2.name&&!item.marketplace);const matches=local.length?local:plugins.filter(item=>item.name===dependency2.name&&item.marketplace===marketplace);if(matches.length!==1){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} must identify one installed, enabled plugin.`)}const target=matches[0];if(target.marketplace&&dependency2.version&&!(0,import_semver.satisfies)(target.version,dependency2.version)){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} has an incompatible installed version.`)}return target}__name(resolveModDependency,"resolveModDependency");function orderModPlugins(plugins){const edges=plugins.map(()=>new Set);const incoming=plugins.map(()=>0);for(const[index,plugin]of plugins.entries()){for(const dependency2 of plugin.dependencies){const targetIndex=plugins.indexOf(resolveModDependency(plugins,plugin,dependency2));if(!edges[index].has(targetIndex)){edges[index].add(targetIndex);incoming[targetIndex]++}}}const ordered=[];const remaining=new Set(plugins.map((_,index)=>index));while(remaining.size){const next=[...remaining].find(index=>incoming[index]===0);if(next===void 0)throw new Error("Mod dependency cycle: activation refused.");remaining.delete(next);ordered.push(plugins[next]);for(const target of edges[next])incoming[target]--}return ordered}__name(orderModPlugins,"orderModPlugins");function isContainedFile(root,file){const relative=path.relative(root,file);return Boolean(relative)&&!path.isAbsolute(relative)&&relative!==".."&&!relative.startsWith(`..${path.sep}`)}__name(isContainedFile,"isContainedFile");async function readModFile(root,file){if(!isContainedFile(root,file)){throw new Error("Mod file must stay inside the installed extension.")}let current=root;for(const part of path.relative(root,file).split(path.sep)){current=path.join(current,part);const stat=await fs.lstat(current);if(stat.isSymbolicLink()){throw new Error("Mod files cannot be symbolic links.")}if(current===file&&!stat.isFile()){throw Object.assign(new Error("Mod input must be a regular file."),{code:stat.isDirectory()?"EISDIR":void 0})}}const entry=await fs.realpath(file);if(!isContainedFile(root,entry)){throw new Error("Mod file must stay inside the installed extension.")}const handle=await openNoFollow(entry);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>MOD_MAX_BYTES){throw new Error("Mod file exceeds the 256 KiB regular-file limit.")}const buffer=Buffer.alloc(MOD_MAX_BYTES+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>MOD_MAX_BYTES)throw new Error("Mod file is too large.");return{entry,source:buffer.subarray(0,bytesRead).toString("utf8")}}finally{await handle.close()}}__name(readModFile,"readModFile");async function readManifest(root,relative){try{if(path.isAbsolute(relative)){throw new Error("Mod manifest path must be relative to the extension.")}const value=JSON.parse((await readModFile(root,path.resolve(root,relative))).source);if(!value||typeof value!=="object"||Array.isArray(value)){throw new Error("Mod manifest must be a JSON object.")}return value}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(readManifest,"readManifest");async function loadModSource(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");if(typeof qwen?.["hooks"]==="string"&&(path.isAbsolute(qwen["hooks"])||!isContainedFile(root,path.resolve(root,qwen["hooks"])))){return void 0}const claude=await readManifest(root,".claude-plugin/plugin.json");const hooksPath=typeof qwen?.["hooks"]==="string"?qwen["hooks"]:typeof claude?.["hooks"]==="string"?claude["hooks"]:"hooks/hooks.json";if(path.isAbsolute(hooksPath)||!isContainedFile(root,path.resolve(root,hooksPath))){return void 0}const hooks=await readManifest(root,hooksPath);if(!hooks||!Object.hasOwn(hooks,"modules"))return void 0;const modules=hooks["modules"];if(!Array.isArray(modules)||modules.length!==1||typeof modules[0]!=="string"||path.isAbsolute(modules[0])||!/\.(?:[cm]?js|[cm]?ts)$/.test(modules[0])){throw new Error("Mods require one relative JavaScript or TypeScript module.")}const manifest={...claude,...qwen};const entry=path.resolve(root,path.dirname(hooksPath),modules[0]);return{root,...await readModFile(root,entry),userConfig:manifest["userConfig"],dependencies:parseModDependencies(manifest["dependencies"])}}__name(loadModSource,"loadModSource");async function loadModDependencies(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");const claude=await readManifest(root,".claude-plugin/plugin.json");return parseModDependencies({...claude,...qwen}["dependencies"])}__name(loadModDependencies,"loadModDependencies");init_esbuild_shims();var option=external_exports.union([external_exports.string(),external_exports.number().finite(),external_exports.boolean(),external_exports.array(external_exports.string())]);var field=external_exports.object({type:external_exports.enum(["string","number","boolean","directory","file"]),title:external_exports.string(),description:external_exports.string(),required:external_exports.boolean().optional(),default:option.optional(),multiple:external_exports.boolean().optional(),sensitive:external_exports.boolean().optional(),min:external_exports.number().finite().optional(),max:external_exports.number().finite().optional(),options:external_exports.array(external_exports.string().min(1).max(64)).nonempty().optional()}).strict().refine(value=>{if(!value.options)return true;return value.type==="string"&&!value.multiple&&!value.sensitive&&value.options.every(item=>item.trim()===item&&!/[\p{Cc}\p{Cf}]/u.test(item))&&new Set(value.options.map(item=>item.toLowerCase())).size===value.options.length&&(value.default===void 0?value.required===true:value.options.includes(value.default))});var schema=external_exports.record(external_exports.string().regex(/^[A-Za-z_]\w*$/),field);var storedOptions=external_exports.record(option);function*pluginConfigurations(scopes,name2,marketplace){const keys=marketplace?[`${name2}@${marketplace}`]:[name2,`${name2}@inline`];for(const scope of scopes){if(scope===void 0)continue;if(!scope||typeof scope!=="object"||Array.isArray(scope)){throw new Error("Invalid Mod pluginConfigs settings.")}for(const key of keys){if(!Object.hasOwn(scope,key))continue;const config=scope[key];if(!config||typeof config!=="object"||Array.isArray(config)){throw new Error("Invalid Mod pluginConfigs entry.")}yield config}}}__name(pluginConfigurations,"pluginConfigurations");function resolveModToolDialect(scopes,name2,marketplace){let dialect="native";for(const config of pluginConfigurations(scopes,name2,marketplace)){const value=config["toolDialect"];if(value===void 0)continue;if(value!=="native"&&value!=="claude")throw new Error("Invalid Mod toolDialect: expected native or claude.");dialect=value}return dialect}__name(resolveModToolDialect,"resolveModToolDialect");function resolveModOptions(declaration,scopes,name2,marketplace){const parsed=schema.safeParse(declaration===void 0?{}:declaration);if(!parsed.success)throw new Error("Invalid Mod userConfig declaration.");const fields=Object.entries(parsed.data);if(!fields.length)return{};if(fields.some(([,value])=>value.sensitive)){throw new Error("Sensitive Mod userConfig is not supported yet.")}let stored={};for(const config of pluginConfigurations(scopes,name2,marketplace)){const options=config["options"];if(options===void 0)continue;const values=storedOptions.safeParse(options);if(!values.success)throw new Error(`Invalid Mod configured option: ${String(values.error.issues[0]?.path[0]??"").slice(0,64)}.`);stored={...stored,...values.data}}const result=Object.fromEntries(fields.filter(([,config])=>config.default!==void 0||!config.required).map(([key,config])=>[key,config.default??""]));for(const[key,value]of Object.entries(stored)){const choices=Object.hasOwn(parsed.data,key)?parsed.data[key].options:void 0;if(!choices||choices.includes(value))Object.defineProperty(result,key,{value,enumerable:true,writable:true,configurable:true})}for(const[key,config]of fields){const value=Object.hasOwn(result,key)?result[key]:void 0;if(value===void 0||value===""){if(config.required)throw new Error(`Missing required Mod option: ${key}.`)}else{const valid=config.type==="number"?typeof value==="number"&&(config.min===void 0||value>=config.min)&&(config.max===void 0||value<=config.max):config.type==="boolean"?typeof value==="boolean":typeof value==="string"||config.type==="string"&&config.multiple&&Array.isArray(value);if(!valid)throw new Error(`Invalid Mod option: ${key}.`)}}if(Buffer.byteLength(JSON.stringify(result))>MOD_MAX_BYTES){throw new Error("Mod options exceed the 256 KiB limit.")}return result}__name(resolveModOptions,"resolveModOptions");init_esbuild_shims();import{Worker}from"node:worker_threads";import{existsSync}from"node:fs";import path2 from"node:path";import{createRequire}from"node:module";import{pathToFileURL}from"node:url";function workerEntry(){if(import.meta.url.endsWith(".ts")){return new URL(`data:text/javascript,${encodeURIComponent(`import { register } from ${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("tsx/esm/api")).href)}; register(); await import(${JSON.stringify(new URL("./mod-worker.ts",import.meta.url).href)});`)}`)}const sibling=new URL("./mod-worker.js",import.meta.url);return existsSync(sibling)?sibling:path2.join(resolveBundleDir(import.meta.url),"mod-worker.js")}__name(workerEntry,"workerEntry");var ModRuntime=class _ModRuntime{constructor(log,resolveTool){this.log=log;this.resolveTool=resolveTool;this.worker=new Worker(workerEntry(),{stdout:true,stderr:true,workerData:this.cancelled.buffer});this.worker.stdout.resume();this.worker.stderr.resume();this.worker.on("message",reply=>{if(reply.type==="host-call")this.executeHost(reply);else if(reply.type==="host-cancel"){for(const id of reply.ids)this.tool?.operations.get(id)?.controller.abort()}else if(reply.type==="check-result")this.tool?.checks.get(reply.id)?.(reply);else if(reply.type==="log"){if(this.failure)return;try{this.log({text:reply.text,to:reply.to},reply.plugin)}catch(error){this.fail(error instanceof Error?error:new Error(String(error)));void this.worker.terminate()}}else this.pending?.(reply)});this.worker.on("error",error=>this.fail(error));this.worker.on("exit",code=>this.fail(new Error(`Mod worker exited (${code}).`)))}static{__name(this,"ModRuntime")}worker;failure;pending;commands=[];tools=false;sequence=0;tool;cancelled=new Int32Array(new SharedArrayBuffer(4));static async create(source,cwd,log,signal,options={}){return _ModRuntime.createGroup([{id:"mod",name:"mod",source,options}],cwd,log,signal)}static async createGroup(plugins,cwd,log,signal,resolveTool){if(plugins.length>32||new Set(plugins.map(p=>p.id)).size!==plugins.length)throw new Error("Invalid Mod plugin group.");const runtime=new _ModRuntime(log,plugins.some(plugin=>plugin.toolDialect==="claude")?resolveTool:void 0);try{const result=await runtime.request({type:"load",plugins,cwd},signal,6e4);if(!record(result)||typeof result["tools"]!=="boolean")throw new Error("Invalid Mod declarations.");const commands=result["commands"];if(!Array.isArray(commands)||commands.length>64||commands.some(command=>!command||!plugins.some(plugin=>plugin.id===command.plugin)||typeof command.name!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(command.name)||typeof command.description!=="string"||command.argumentHint!==void 0&&typeof command.argumentHint!=="string"))throw new Error("Invalid Mod command declarations.");runtime.commands=commands;runtime.tools=result["tools"];return runtime}catch(error){await runtime.dispose();throw error}}getCommands(plugin="mod"){return this.commands.filter(command=>command.plugin===plugin).map(({plugin:_plugin,...command})=>command)}get hasToolHooks(){return this.tools}async builtinTool(name2){if(!this.resolveTool)return void 0;let builtin=false;switch(name2){case ToolNames.SHELL:builtin=await this.resolveTool(name2)instanceof(await import("./shell-ORZNRZKX.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-S7DCBMAL.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-MGYLC32T.js")).WriteFileTool;break;default:return void 0}return builtin?name2:void 0}async runTool(input,next,signal){if(this.tool||this.pending)throw new Error("A Mod dispatch is already running.");const owner={next,controller:new AbortController,operations:new Map,checks:new Map,tail:Promise.resolve()};this.tool=owner;try{const builtinTool=await this.builtinTool(input.tool);const result=await this.request({type:"tool",input,builtinTool},AbortSignal.any([signal,owner.controller.signal]));validateResult("tool.call",result);return result}finally{owner.controller.abort();await Promise.allSettled([...owner.operations.values()].map(operation=>operation.task));this.tool=void 0}}executeHost(reply){const owner=this.tool;if(!owner||owner.operations.size>=32||owner.operations.has(reply.id)){this.fail(new Error("Invalid Mod host operation."));return}const controller=new AbortController;const signal=AbortSignal.any([owner.controller.signal,controller.signal]);const task=owner.tail.then(async()=>{signal.throwIfAborted();const result=await owner.next(reply.input,signal,async(input,verdict,checkSignal)=>{const active=AbortSignal.any([signal,checkSignal]);active.throwIfAborted();const id=++this.sequence;let abort=__name(()=>{},"abort");try{return await new Promise((resolve,reject)=>{abort=__name(()=>reject(new Error("Mod permission check cancelled.")),"abort");owner.checks.set(id,response=>{if(response.error!==void 0)reject(new Error(response.error));else{try{validateResult("tool.check",response.result);resolve({...response.result,ceiling:input.ceiling})}catch(error){reject(error)}}});active.addEventListener("abort",abort,{once:true});this.post({type:"tool-check",id,operation:reply.id,input,verdict})})}finally{active.removeEventListener("abort",abort);owner.checks.delete(id)}});signal.throwIfAborted();this.post({type:"host-result",id:reply.id,result})}).catch(error=>{if(!this.failure)this.post({type:"host-result",id:reply.id,error:String(error).slice(0,4e3)})}).finally(()=>{owner.operations.delete(reply.id)});owner.operations.set(reply.id,{controller,task});owner.tail=task}post(request){if(Buffer.byteLength(JSON.stringify(request))>MOD_MAX_BYTES+8192)throw new Error("Mod host message is too large.");this.worker.postMessage(request)}async runCommand(command,args,signal){if(!this.commands.some(item=>item.name===command))throw new Error("Unknown Mod command.");const result=await this.request({type:"command",command,args},signal);if(!result||typeof result!=="object"||Array.isArray(result)||Object.keys(result).some(key=>key!=="text")||"text"in result&&typeof result.text!=="string"){throw new Error("Invalid Mod command result.")}return"text"in result?result.text:""}async end(sessionId,reason,signal){await this.request({type:"end",sessionId,reason},signal,MOD_END_TIMEOUT_MS)}async dispose(){this.fail(new Error("Mod runtime is closed."));await this.worker.terminate();await Promise.allSettled([...this.tool?.operations.values()??[]].map(operation=>operation.task))}fail(error){this.failure??=error;this.tool?.controller.abort();this.pending?.({type:"error",message:this.failure.message})}async request(request,signal,timeoutMs=6e4){signal.throwIfAborted();if(this.failure)throw this.failure;if(this.pending)throw new Error("A Mod dispatch is already running.");if(Buffer.byteLength(JSON.stringify(request))>(request.type==="load"?32:1)*MOD_MAX_BYTES+8192)throw new Error("Mod request is too large.");let timer;const cleanup=new AbortController;let aborted=false;const onAbort=__name(()=>{aborted=true;Atomics.store(this.cancelled,0,1);this.tool?.controller.abort()},"onAbort");Atomics.store(this.cancelled,0,0);try{return await new Promise((resolve,reject)=>{this.pending=reply=>{if(aborted)reject(new Error("Mod dispatch cancelled."));else if(reply.type==="error")reject(new Error(reply.message));else if(reply.type==="result"){try{if(Buffer.byteLength(reply.json)>MOD_MAX_BYTES)throw new Error("Mod reply is too large.");resolve(JSON.parse(reply.json))}catch(error){reject(error)}}};signal.addEventListener("abort",onAbort,{once:true});timer=setTimeout(()=>{this.fail(new Error(aborted?"Mod dispatch cancelled.":"Mod dispatch timed out."));void this.worker.terminate()},timeoutMs+250);signal.addEventListener("abort",()=>{if(timer)clearTimeout(timer);timer=setTimeout(()=>{this.fail(new Error("Mod dispatch cancelled."));void this.worker.terminate()},250)},{once:true,signal:cleanup.signal});this.worker.postMessage(request)})}finally{cleanup.abort();if(timer)clearTimeout(timer);signal.removeEventListener("abort",onAbort);this.pending=void 0}}};var logger=createDebugLogger("MODS");var ModSession=class _ModSession{constructor(config,adapter,optionScopes=[]){this.config=config;this.adapter=adapter;this.optionScopes=optionScopes;this.sessionId=config.getSessionId();this.unregisterCleanup=registerCleanup(()=>{this.unregisterCleanup=()=>{};return this.close()})}static{__name(this,"ModSession")}mods=[];runtime;toolQueue=Promise.resolve();lifetime=new AbortController;initialization;closing;logsReady=false;pendingLogs=[];sessionId;unregisterCleanup;static create(config,settings,adapter){return settings.merged.experimental?.mods?new _ModSession(config,adapter,[settings.systemDefaults.settings.pluginConfigs,settings.user.settings.pluginConfigs,settings.system.settings.pluginConfigs]):void 0}allowed(){return!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&this.config.isTrustedFolder()&&!this.config.getDisableAllHooks()&&!this.config.getBareMode()&&!this.config.isSafeMode()&&!this.config.getExecutionEnvironment()&&!this.config.getExecutionEnvironmentFactory()&&!this.config.getHookSystem()?.isManaged()&&!this.config.getSandbox()&&!this.config.isSessionAgentSession()}async initialize(signal){if(this.closing)throw new Error("Mod session is closed.");if(!this.allowed()){if(this.mods.length){await this.close();throw new Error("Mods are no longer permitted in this session.")}return}this.initialization??=this.load(AbortSignal.any([signal,this.lifetime.signal]));await this.initialization}async load(signal){try{const candidates=[];for(const extension of this.config.getExtensions().filter(item=>item.isActive&&item.format!=="agent-plugins-v1")){signal.throwIfAborted();try{const source=await loadModSource(extension.path);const marketplace=extension.installMetadata?.marketplaceConfig?.name;candidates.push({extension,name:extension.name,version:extension.version,marketplace,source,dependencies:source?.dependencies??[],toolDialect:source?resolveModToolDialect(this.optionScopes,extension.name,marketplace):void 0,options:source?resolveModOptions(source.userConfig,this.optionScopes,extension.name,marketplace):{}})}catch(error){throw new Error(`Mod ${extension.name}: ${error instanceof Error?error.message:String(error)}`)}}const pending=candidates.filter(item=>item.source);const reachable=new Set;while(pending.length){signal.throwIfAborted();const plugin=pending.shift();if(reachable.has(plugin))continue;reachable.add(plugin);if(!plugin.source){try{plugin.dependencies=await loadModDependencies(plugin.extension.path)}catch(error){throw new Error(`Mod dependency ${plugin.name}: ${error instanceof Error?error.message:String(error)}`)}}for(const dependency2 of plugin.dependencies){pending.push(resolveModDependency(candidates,plugin,dependency2))}}const selected=candidates.filter(item=>reachable.has(item));orderModPlugins(selected);const mods=selected.filter(item=>item.source).map(plugin=>({...plugin,dependencies:plugin.dependencies.filter(dependency2=>resolveModDependency(selected,plugin,dependency2).source)}));const ordered=orderModPlugins(mods);if(ordered.length){this.runtime=await ModRuntime.createGroup(ordered.map(({extension,source,options,toolDialect})=>({id:extension.id,name:extension.name,source:{root:source.root,entry:source.entry,source:source.source},options,toolDialect})),this.config.getTargetDir(),(entry,plugin)=>{this.pendingLogs.push({...entry,plugin});if(this.logsReady)this.flushLogs()},signal,name2=>this.config.getToolRegistry().ensureTool(name2));this.mods.push(...ordered.map(({extension})=>({id:extension.id,name:extension.name})))}}catch(error){await this.runtime?.dispose();this.mods.length=0;throw error}}async loadCommands(signal){await this.initialize(signal);return this.mods.flatMap(mod=>this.runtime.getCommands(mod.id).map(command=>({name:command.name,description:command.description,kind:"file",source:"plugin-command",extensionName:mod.name,supportedModes:["non_interactive"],argumentHint:command.argumentHint,modelInvocable:false,action:__name(async(_context,args)=>{if(!this.allowed()||!this.active()||this.closing){await this.runtime.dispose();throw new Error(`Mod ${mod.name} is disabled or its middleware chain changed.`)}return{type:"message",messageType:"info",content:await this.runtime.runCommand(command.name,args,signal)}},"action")})))}async syncSession(reason){const current=this.config.getSessionId();if(current===this.sessionId)return;await this.end(reason);this.sessionId=current}get hasToolHooks(){return this.runtime?.hasToolHooks===true}toolCall(onRepeat){if(!this.hasToolHooks)return void 0;return(input,next,signal)=>{const active=AbortSignal.any([signal,this.lifetime.signal]);const assertAllowed=__name(()=>{active.throwIfAborted();if(!this.allowed()||!this.active()||this.closing)throw new Error("Mod tool middleware is disabled or its chain changed.")},"assertAllowed");const task=this.toolQueue.then(async()=>{assertAllowed();let attempts=0;return this.runtime.runTool(input,async(changed,hostSignal,check)=>{assertAllowed();if(attempts++)onRepeat();active.throwIfAborted();return next(changed,hostSignal,async(question,verdict,checkSignal)=>{assertAllowed();return check(question,verdict,checkSignal)})},active)});this.toolQueue=task.catch(()=>{});return task}}flushLogs(){this.logsReady=true;for(const entry of this.pendingLogs.splice(0)){logger.debug(`[${entry.plugin}] ${entry.text}`);if(entry.to==="debug")continue;const text=stripAnsiAndControl(entry.text);if(this.config.getOutputFormat()==="text"){process.stderr.write(`[Mod ${entry.plugin}] ${text}
|
|
3
|
+
import{JsonOutputAdapter}from"./chunk-TEE4MM5S.js";import{normalizePartList}from"./chunk-HIO3M52C.js";import{settleChatRecording,subscribeToHeadlessChatRecordingFailures}from"./chunk-ULEYDXOX.js";import{StreamJsonOutputAdapter}from"./chunk-IYFUH3JB.js";import{handleAtCommand}from"./chunk-CKJ3OUIV.js";import{buildInitialSystemReminders,buildSystemMessage,computeUsageFromMetrics,createAgentToolProgressHandler,createToolProgressHandler,extractPartsFromUserMessage,handleSlashCommand,insertAfterFunctionResponses,isSlashCommand}from"./chunk-DSSSLNXD.js";import{formatDuration}from"./chunk-PBC5IFGO.js";import{RunBudgetEnforcer,flushOutput}from"./chunk-X22435IN.js";import{sanitizeTerminalText}from"./chunk-MOH67CDU.js";import{cleanupReviewWorktreeLeases}from"./chunk-SGKINIQB.js";import{AlreadyReportedError,handleBudgetExceededError,handleCancellationError,handleError,handleMaxTurnsExceededError,handleToolError}from"./chunk-FBV4LUUL.js";import{isInlineModelOverrideAllowed}from"./chunk-GT4TCQ3R.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{buildGoalContinuationParts,buildSessionRecoveryPlanFromApiHistory,detectAutonomousSentinel,detectLoopSentinel}from"./chunk-RV54BGL2.js";import{restoreWorktreeContext}from"./chunk-XIB6LAXR.js";import{MOD_END_TIMEOUT_MS,MOD_MAX_BYTES,executeToolCall,record,validateResult}from"./chunk-NT74NPQT.js";import{GoalPersistenceUnavailableError,PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE,createDuplicateProviderToolCallResponse,finalizeToolResponses,findPlanModeEntryBatchBoundaryIndex,findRepeatedDuplicateProviderToolCall,getCachedToolCallFingerprint,getLastApiPromptCancellation,goalToolResultProvenance,isReplayOfHandledToolCall,isToolCallConcurrencySafe,markDuplicateProviderToolCallResponseSent,parseAndFormatApiError,partitionByConcurrencySafety,recordHandledToolCall}from"./chunk-IFAUFERF.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{external_exports}from"./chunk-TWP72VRH.js";import{openNoFollow}from"./chunk-QXQGUM3Y.js";import{GOAL_PAUSE_REASON_HEADLESS_RUN_ENDED,GOAL_PAUSE_REASON_USER_INTERRUPT,addAgentOutputMessageAttributes,goalPauseReasonForHeadlessFailure,goalPauseReasonForRunBudget}from"./chunk-YPIUTOL3.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,hasImageParts,runVisionBridge,shouldRunVisionBridge,splitImageParts,uiTelemetryService}from"./chunk-KBPIYGHG.js";import{clampInlineMediaPart}from"./chunk-P3RLMP7L.js";import{endInteractionSpan,getActiveInteractionSpan,isTelemetrySdkInitialized,shutdownTelemetry}from"./chunk-AWTUIQ7W.js";import{registerCleanup}from"./chunk-SPFRORFN.js";import{stripAnsiAndControl}from"./chunk-4YLXNRRH.js";import{isSystemReminderContent}from"./chunk-65UCR6OZ.js";import{ToolNames,canonicalToolName}from"./chunk-2UNFJQ2D.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{FatalInputError,getErrorType}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import{promises as fs}from"node:fs";import path from"node:path";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);var name=external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/);var dependency=external_exports.union([external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:@[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/),external_exports.object({name,marketplace:name.optional(),version:external_exports.string().optional()}).strict()]);function parseModDependencies(value){const parsed=external_exports.array(dependency).safeParse(value===void 0?[]:value);if(!parsed.success)throw new Error("Invalid Mod dependencies declaration.");return parsed.data.map(item=>{if(typeof item==="string"){const[name2,marketplace]=item.split("@");return{name:name2,marketplace}}if(item.version!==void 0&&!(0,import_semver.validRange)(item.version)){throw new Error(`Invalid Mod dependency version range for ${item.name}.`)}return item})}__name(parseModDependencies,"parseModDependencies");function resolveModDependency(plugins,plugin,dependency2){const marketplace=dependency2.marketplace??plugin.marketplace;const local=plugins.filter(item=>item.name===dependency2.name&&!item.marketplace);const matches=local.length?local:plugins.filter(item=>item.name===dependency2.name&&item.marketplace===marketplace);if(matches.length!==1){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} must identify one installed, enabled plugin.`)}const target=matches[0];if(target.marketplace&&dependency2.version&&!(0,import_semver.satisfies)(target.version,dependency2.version)){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} has an incompatible installed version.`)}return target}__name(resolveModDependency,"resolveModDependency");function orderModPlugins(plugins){const edges=plugins.map(()=>new Set);const incoming=plugins.map(()=>0);for(const[index,plugin]of plugins.entries()){for(const dependency2 of plugin.dependencies){const targetIndex=plugins.indexOf(resolveModDependency(plugins,plugin,dependency2));if(!edges[index].has(targetIndex)){edges[index].add(targetIndex);incoming[targetIndex]++}}}const ordered=[];const remaining=new Set(plugins.map((_,index)=>index));while(remaining.size){const next=[...remaining].find(index=>incoming[index]===0);if(next===void 0)throw new Error("Mod dependency cycle: activation refused.");remaining.delete(next);ordered.push(plugins[next]);for(const target of edges[next])incoming[target]--}return ordered}__name(orderModPlugins,"orderModPlugins");function isContainedFile(root,file){const relative=path.relative(root,file);return Boolean(relative)&&!path.isAbsolute(relative)&&relative!==".."&&!relative.startsWith(`..${path.sep}`)}__name(isContainedFile,"isContainedFile");async function readModFile(root,file){if(!isContainedFile(root,file)){throw new Error("Mod file must stay inside the installed extension.")}let current=root;for(const part of path.relative(root,file).split(path.sep)){current=path.join(current,part);const stat=await fs.lstat(current);if(stat.isSymbolicLink()){throw new Error("Mod files cannot be symbolic links.")}if(current===file&&!stat.isFile()){throw Object.assign(new Error("Mod input must be a regular file."),{code:stat.isDirectory()?"EISDIR":void 0})}}const entry=await fs.realpath(file);if(!isContainedFile(root,entry)){throw new Error("Mod file must stay inside the installed extension.")}const handle=await openNoFollow(entry);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>MOD_MAX_BYTES){throw new Error("Mod file exceeds the 256 KiB regular-file limit.")}const buffer=Buffer.alloc(MOD_MAX_BYTES+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>MOD_MAX_BYTES)throw new Error("Mod file is too large.");return{entry,source:buffer.subarray(0,bytesRead).toString("utf8")}}finally{await handle.close()}}__name(readModFile,"readModFile");async function readManifest(root,relative){try{if(path.isAbsolute(relative)){throw new Error("Mod manifest path must be relative to the extension.")}const value=JSON.parse((await readModFile(root,path.resolve(root,relative))).source);if(!value||typeof value!=="object"||Array.isArray(value)){throw new Error("Mod manifest must be a JSON object.")}return value}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(readManifest,"readManifest");async function loadModSource(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");if(typeof qwen?.["hooks"]==="string"&&(path.isAbsolute(qwen["hooks"])||!isContainedFile(root,path.resolve(root,qwen["hooks"])))){return void 0}const claude=await readManifest(root,".claude-plugin/plugin.json");const hooksPath=typeof qwen?.["hooks"]==="string"?qwen["hooks"]:typeof claude?.["hooks"]==="string"?claude["hooks"]:"hooks/hooks.json";if(path.isAbsolute(hooksPath)||!isContainedFile(root,path.resolve(root,hooksPath))){return void 0}const hooks=await readManifest(root,hooksPath);if(!hooks||!Object.hasOwn(hooks,"modules"))return void 0;const modules=hooks["modules"];if(!Array.isArray(modules)||modules.length!==1||typeof modules[0]!=="string"||path.isAbsolute(modules[0])||!/\.(?:[cm]?js|[cm]?ts)$/.test(modules[0])){throw new Error("Mods require one relative JavaScript or TypeScript module.")}const manifest={...claude,...qwen};const entry=path.resolve(root,path.dirname(hooksPath),modules[0]);return{root,...await readModFile(root,entry),userConfig:manifest["userConfig"],dependencies:parseModDependencies(manifest["dependencies"])}}__name(loadModSource,"loadModSource");async function loadModDependencies(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");const claude=await readManifest(root,".claude-plugin/plugin.json");return parseModDependencies({...claude,...qwen}["dependencies"])}__name(loadModDependencies,"loadModDependencies");init_esbuild_shims();var option=external_exports.union([external_exports.string(),external_exports.number().finite(),external_exports.boolean(),external_exports.array(external_exports.string())]);var field=external_exports.object({type:external_exports.enum(["string","number","boolean","directory","file"]),title:external_exports.string(),description:external_exports.string(),required:external_exports.boolean().optional(),default:option.optional(),multiple:external_exports.boolean().optional(),sensitive:external_exports.boolean().optional(),min:external_exports.number().finite().optional(),max:external_exports.number().finite().optional(),options:external_exports.array(external_exports.string().min(1).max(64)).nonempty().optional()}).strict().refine(value=>{if(!value.options)return true;return value.type==="string"&&!value.multiple&&!value.sensitive&&value.options.every(item=>item.trim()===item&&!/[\p{Cc}\p{Cf}]/u.test(item))&&new Set(value.options.map(item=>item.toLowerCase())).size===value.options.length&&(value.default===void 0?value.required===true:value.options.includes(value.default))});var schema=external_exports.record(external_exports.string().regex(/^[A-Za-z_]\w*$/),field);var storedOptions=external_exports.record(option);function*pluginConfigurations(scopes,name2,marketplace){const keys=marketplace?[`${name2}@${marketplace}`]:[name2,`${name2}@inline`];for(const scope of scopes){if(scope===void 0)continue;if(!scope||typeof scope!=="object"||Array.isArray(scope)){throw new Error("Invalid Mod pluginConfigs settings.")}for(const key of keys){if(!Object.hasOwn(scope,key))continue;const config=scope[key];if(!config||typeof config!=="object"||Array.isArray(config)){throw new Error("Invalid Mod pluginConfigs entry.")}yield config}}}__name(pluginConfigurations,"pluginConfigurations");function resolveModToolDialect(scopes,name2,marketplace){let dialect="native";for(const config of pluginConfigurations(scopes,name2,marketplace)){const value=config["toolDialect"];if(value===void 0)continue;if(value!=="native"&&value!=="claude")throw new Error("Invalid Mod toolDialect: expected native or claude.");dialect=value}return dialect}__name(resolveModToolDialect,"resolveModToolDialect");function resolveModOptions(declaration,scopes,name2,marketplace){const parsed=schema.safeParse(declaration===void 0?{}:declaration);if(!parsed.success)throw new Error("Invalid Mod userConfig declaration.");const fields=Object.entries(parsed.data);if(!fields.length)return{};if(fields.some(([,value])=>value.sensitive)){throw new Error("Sensitive Mod userConfig is not supported yet.")}let stored={};for(const config of pluginConfigurations(scopes,name2,marketplace)){const options=config["options"];if(options===void 0)continue;const values=storedOptions.safeParse(options);if(!values.success)throw new Error(`Invalid Mod configured option: ${String(values.error.issues[0]?.path[0]??"").slice(0,64)}.`);stored={...stored,...values.data}}const result=Object.fromEntries(fields.filter(([,config])=>config.default!==void 0||!config.required).map(([key,config])=>[key,config.default??""]));for(const[key,value]of Object.entries(stored)){const choices=Object.hasOwn(parsed.data,key)?parsed.data[key].options:void 0;if(!choices||choices.includes(value))Object.defineProperty(result,key,{value,enumerable:true,writable:true,configurable:true})}for(const[key,config]of fields){const value=Object.hasOwn(result,key)?result[key]:void 0;if(value===void 0||value===""){if(config.required)throw new Error(`Missing required Mod option: ${key}.`)}else{const valid=config.type==="number"?typeof value==="number"&&(config.min===void 0||value>=config.min)&&(config.max===void 0||value<=config.max):config.type==="boolean"?typeof value==="boolean":typeof value==="string"||config.type==="string"&&config.multiple&&Array.isArray(value);if(!valid)throw new Error(`Invalid Mod option: ${key}.`)}}if(Buffer.byteLength(JSON.stringify(result))>MOD_MAX_BYTES){throw new Error("Mod options exceed the 256 KiB limit.")}return result}__name(resolveModOptions,"resolveModOptions");init_esbuild_shims();import{Worker}from"node:worker_threads";import{existsSync}from"node:fs";import path2 from"node:path";import{createRequire}from"node:module";import{pathToFileURL}from"node:url";function workerEntry(){if(import.meta.url.endsWith(".ts")){return new URL(`data:text/javascript,${encodeURIComponent(`import { register } from ${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("tsx/esm/api")).href)}; register(); await import(${JSON.stringify(new URL("./mod-worker.ts",import.meta.url).href)});`)}`)}const sibling=new URL("./mod-worker.js",import.meta.url);return existsSync(sibling)?sibling:path2.join(resolveBundleDir(import.meta.url),"mod-worker.js")}__name(workerEntry,"workerEntry");var ModRuntime=class _ModRuntime{constructor(log,resolveTool){this.log=log;this.resolveTool=resolveTool;this.worker=new Worker(workerEntry(),{stdout:true,stderr:true,workerData:this.cancelled.buffer});this.worker.stdout.resume();this.worker.stderr.resume();this.worker.on("message",reply=>{if(reply.type==="host-call")this.executeHost(reply);else if(reply.type==="host-cancel"){for(const id of reply.ids)this.tool?.operations.get(id)?.controller.abort()}else if(reply.type==="check-result")this.tool?.checks.get(reply.id)?.(reply);else if(reply.type==="log"){if(this.failure)return;try{this.log({text:reply.text,to:reply.to},reply.plugin)}catch(error){this.fail(error instanceof Error?error:new Error(String(error)));void this.worker.terminate()}}else this.pending?.(reply)});this.worker.on("error",error=>this.fail(error));this.worker.on("exit",code=>this.fail(new Error(`Mod worker exited (${code}).`)))}static{__name(this,"ModRuntime")}worker;failure;pending;commands=[];tools=false;sequence=0;tool;cancelled=new Int32Array(new SharedArrayBuffer(4));static async create(source,cwd,log,signal,options={}){return _ModRuntime.createGroup([{id:"mod",name:"mod",source,options}],cwd,log,signal)}static async createGroup(plugins,cwd,log,signal,resolveTool){if(plugins.length>32||new Set(plugins.map(p=>p.id)).size!==plugins.length)throw new Error("Invalid Mod plugin group.");const runtime=new _ModRuntime(log,plugins.some(plugin=>plugin.toolDialect==="claude")?resolveTool:void 0);try{const result=await runtime.request({type:"load",plugins,cwd},signal,6e4);if(!record(result)||typeof result["tools"]!=="boolean")throw new Error("Invalid Mod declarations.");const commands=result["commands"];if(!Array.isArray(commands)||commands.length>64||commands.some(command=>!command||!plugins.some(plugin=>plugin.id===command.plugin)||typeof command.name!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(command.name)||typeof command.description!=="string"||command.argumentHint!==void 0&&typeof command.argumentHint!=="string"))throw new Error("Invalid Mod command declarations.");runtime.commands=commands;runtime.tools=result["tools"];return runtime}catch(error){await runtime.dispose();throw error}}getCommands(plugin="mod"){return this.commands.filter(command=>command.plugin===plugin).map(({plugin:_plugin,...command})=>command)}get hasToolHooks(){return this.tools}async builtinTool(name2){if(!this.resolveTool)return void 0;let builtin=false;switch(name2){case ToolNames.SHELL:builtin=await this.resolveTool(name2)instanceof(await import("./shell-SXSN7UYK.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-CZ6FEXDU.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-RG7HHIYP.js")).WriteFileTool;break;default:return void 0}return builtin?name2:void 0}async runTool(input,next,signal){if(this.tool||this.pending)throw new Error("A Mod dispatch is already running.");const owner={next,controller:new AbortController,operations:new Map,checks:new Map,tail:Promise.resolve()};this.tool=owner;try{const builtinTool=await this.builtinTool(input.tool);const result=await this.request({type:"tool",input,builtinTool},AbortSignal.any([signal,owner.controller.signal]));validateResult("tool.call",result);return result}finally{owner.controller.abort();await Promise.allSettled([...owner.operations.values()].map(operation=>operation.task));this.tool=void 0}}executeHost(reply){const owner=this.tool;if(!owner||owner.operations.size>=32||owner.operations.has(reply.id)){this.fail(new Error("Invalid Mod host operation."));return}const controller=new AbortController;const signal=AbortSignal.any([owner.controller.signal,controller.signal]);const task=owner.tail.then(async()=>{signal.throwIfAborted();const result=await owner.next(reply.input,signal,async(input,verdict,checkSignal)=>{const active=AbortSignal.any([signal,checkSignal]);active.throwIfAborted();const id=++this.sequence;let abort=__name(()=>{},"abort");try{return await new Promise((resolve,reject)=>{abort=__name(()=>reject(new Error("Mod permission check cancelled.")),"abort");owner.checks.set(id,response=>{if(response.error!==void 0)reject(new Error(response.error));else{try{validateResult("tool.check",response.result);resolve({...response.result,ceiling:input.ceiling})}catch(error){reject(error)}}});active.addEventListener("abort",abort,{once:true});this.post({type:"tool-check",id,operation:reply.id,input,verdict})})}finally{active.removeEventListener("abort",abort);owner.checks.delete(id)}});signal.throwIfAborted();this.post({type:"host-result",id:reply.id,result})}).catch(error=>{if(!this.failure)this.post({type:"host-result",id:reply.id,error:String(error).slice(0,4e3)})}).finally(()=>{owner.operations.delete(reply.id)});owner.operations.set(reply.id,{controller,task});owner.tail=task}post(request){if(Buffer.byteLength(JSON.stringify(request))>MOD_MAX_BYTES+8192)throw new Error("Mod host message is too large.");this.worker.postMessage(request)}async runCommand(command,args,signal){if(!this.commands.some(item=>item.name===command))throw new Error("Unknown Mod command.");const result=await this.request({type:"command",command,args},signal);if(!result||typeof result!=="object"||Array.isArray(result)||Object.keys(result).some(key=>key!=="text")||"text"in result&&typeof result.text!=="string"){throw new Error("Invalid Mod command result.")}return"text"in result?result.text:""}async end(sessionId,reason,signal){await this.request({type:"end",sessionId,reason},signal,MOD_END_TIMEOUT_MS)}async dispose(){this.fail(new Error("Mod runtime is closed."));await this.worker.terminate();await Promise.allSettled([...this.tool?.operations.values()??[]].map(operation=>operation.task))}fail(error){this.failure??=error;this.tool?.controller.abort();this.pending?.({type:"error",message:this.failure.message})}async request(request,signal,timeoutMs=6e4){signal.throwIfAborted();if(this.failure)throw this.failure;if(this.pending)throw new Error("A Mod dispatch is already running.");if(Buffer.byteLength(JSON.stringify(request))>(request.type==="load"?32:1)*MOD_MAX_BYTES+8192)throw new Error("Mod request is too large.");let timer;const cleanup=new AbortController;let aborted=false;const onAbort=__name(()=>{aborted=true;Atomics.store(this.cancelled,0,1);this.tool?.controller.abort()},"onAbort");Atomics.store(this.cancelled,0,0);try{return await new Promise((resolve,reject)=>{this.pending=reply=>{if(aborted)reject(new Error("Mod dispatch cancelled."));else if(reply.type==="error")reject(new Error(reply.message));else if(reply.type==="result"){try{if(Buffer.byteLength(reply.json)>MOD_MAX_BYTES)throw new Error("Mod reply is too large.");resolve(JSON.parse(reply.json))}catch(error){reject(error)}}};signal.addEventListener("abort",onAbort,{once:true});timer=setTimeout(()=>{this.fail(new Error(aborted?"Mod dispatch cancelled.":"Mod dispatch timed out."));void this.worker.terminate()},timeoutMs+250);signal.addEventListener("abort",()=>{if(timer)clearTimeout(timer);timer=setTimeout(()=>{this.fail(new Error("Mod dispatch cancelled."));void this.worker.terminate()},250)},{once:true,signal:cleanup.signal});this.worker.postMessage(request)})}finally{cleanup.abort();if(timer)clearTimeout(timer);signal.removeEventListener("abort",onAbort);this.pending=void 0}}};var logger=createDebugLogger("MODS");var ModSession=class _ModSession{constructor(config,adapter,optionScopes=[]){this.config=config;this.adapter=adapter;this.optionScopes=optionScopes;this.sessionId=config.getSessionId();this.unregisterCleanup=registerCleanup(()=>{this.unregisterCleanup=()=>{};return this.close()})}static{__name(this,"ModSession")}mods=[];runtime;toolQueue=Promise.resolve();lifetime=new AbortController;initialization;closing;logsReady=false;pendingLogs=[];sessionId;unregisterCleanup;static create(config,settings,adapter){return settings.merged.experimental?.mods?new _ModSession(config,adapter,[settings.systemDefaults.settings.pluginConfigs,settings.user.settings.pluginConfigs,settings.system.settings.pluginConfigs]):void 0}allowed(){return!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&this.config.isTrustedFolder()&&!this.config.getDisableAllHooks()&&!this.config.getBareMode()&&!this.config.isSafeMode()&&!this.config.getExecutionEnvironment()&&!this.config.getExecutionEnvironmentFactory()&&!this.config.getHookSystem()?.isManaged()&&!this.config.getSandbox()&&!this.config.isSessionAgentSession()}async initialize(signal){if(this.closing)throw new Error("Mod session is closed.");if(!this.allowed()){if(this.mods.length){await this.close();throw new Error("Mods are no longer permitted in this session.")}return}this.initialization??=this.load(AbortSignal.any([signal,this.lifetime.signal]));await this.initialization}async load(signal){try{const candidates=[];for(const extension of this.config.getExtensions().filter(item=>item.isActive&&item.format!=="agent-plugins-v1")){signal.throwIfAborted();try{const source=await loadModSource(extension.path);const marketplace=extension.installMetadata?.marketplaceConfig?.name;candidates.push({extension,name:extension.name,version:extension.version,marketplace,source,dependencies:source?.dependencies??[],toolDialect:source?resolveModToolDialect(this.optionScopes,extension.name,marketplace):void 0,options:source?resolveModOptions(source.userConfig,this.optionScopes,extension.name,marketplace):{}})}catch(error){throw new Error(`Mod ${extension.name}: ${error instanceof Error?error.message:String(error)}`)}}const pending=candidates.filter(item=>item.source);const reachable=new Set;while(pending.length){signal.throwIfAborted();const plugin=pending.shift();if(reachable.has(plugin))continue;reachable.add(plugin);if(!plugin.source){try{plugin.dependencies=await loadModDependencies(plugin.extension.path)}catch(error){throw new Error(`Mod dependency ${plugin.name}: ${error instanceof Error?error.message:String(error)}`)}}for(const dependency2 of plugin.dependencies){pending.push(resolveModDependency(candidates,plugin,dependency2))}}const selected=candidates.filter(item=>reachable.has(item));orderModPlugins(selected);const mods=selected.filter(item=>item.source).map(plugin=>({...plugin,dependencies:plugin.dependencies.filter(dependency2=>resolveModDependency(selected,plugin,dependency2).source)}));const ordered=orderModPlugins(mods);if(ordered.length){this.runtime=await ModRuntime.createGroup(ordered.map(({extension,source,options,toolDialect})=>({id:extension.id,name:extension.name,source:{root:source.root,entry:source.entry,source:source.source},options,toolDialect})),this.config.getTargetDir(),(entry,plugin)=>{this.pendingLogs.push({...entry,plugin});if(this.logsReady)this.flushLogs()},signal,name2=>this.config.getToolRegistry().ensureTool(name2));this.mods.push(...ordered.map(({extension})=>({id:extension.id,name:extension.name})))}}catch(error){await this.runtime?.dispose();this.mods.length=0;throw error}}async loadCommands(signal){await this.initialize(signal);return this.mods.flatMap(mod=>this.runtime.getCommands(mod.id).map(command=>({name:command.name,description:command.description,kind:"file",source:"plugin-command",extensionName:mod.name,supportedModes:["non_interactive"],argumentHint:command.argumentHint,modelInvocable:false,action:__name(async(_context,args)=>{if(!this.allowed()||!this.active()||this.closing){await this.runtime.dispose();throw new Error(`Mod ${mod.name} is disabled or its middleware chain changed.`)}return{type:"message",messageType:"info",content:await this.runtime.runCommand(command.name,args,signal)}},"action")})))}async syncSession(reason){const current=this.config.getSessionId();if(current===this.sessionId)return;await this.end(reason);this.sessionId=current}get hasToolHooks(){return this.runtime?.hasToolHooks===true}toolCall(onRepeat){if(!this.hasToolHooks)return void 0;return(input,next,signal)=>{const active=AbortSignal.any([signal,this.lifetime.signal]);const assertAllowed=__name(()=>{active.throwIfAborted();if(!this.allowed()||!this.active()||this.closing)throw new Error("Mod tool middleware is disabled or its chain changed.")},"assertAllowed");const task=this.toolQueue.then(async()=>{assertAllowed();let attempts=0;return this.runtime.runTool(input,async(changed,hostSignal,check)=>{assertAllowed();if(attempts++)onRepeat();active.throwIfAborted();return next(changed,hostSignal,async(question,verdict,checkSignal)=>{assertAllowed();return check(question,verdict,checkSignal)})},active)});this.toolQueue=task.catch(()=>{});return task}}flushLogs(){this.logsReady=true;for(const entry of this.pendingLogs.splice(0)){logger.debug(`[${entry.plugin}] ${entry.text}`);if(entry.to==="debug")continue;const text=stripAnsiAndControl(entry.text);if(this.config.getOutputFormat()==="text"){process.stderr.write(`[Mod ${entry.plugin}] ${text}
|
|
4
4
|
`)}else{this.adapter.emitSystemMessage("ui_log",{plugin:entry.plugin,text})}}}async flushOutput(){const signal=AbortSignal.timeout(1500);await Promise.allSettled([flushOutput(process.stdout,signal),flushOutput(process.stderr,signal)])}active(){const extensions=this.config.getExtensions();return this.mods.every(mod=>extensions.some(extension=>extension.id===mod.id&&extension.isActive))}async end(reason){await this.toolQueue;if(!this.allowed()||!this.active())return;try{await this.runtime?.end(this.sessionId,reason,AbortSignal.timeout(MOD_END_TIMEOUT_MS))}catch(error){logger.warn(`Mod session.end: ${String(error)}`)}}close(){this.closing??=(async()=>{this.unregisterCleanup();this.lifetime.abort();await this.initialization?.catch(()=>{});try{await this.end("other")}finally{this.lifetime.abort();await this.runtime?.dispose();await this.flushOutput()}})();return this.closing}};var debugLogger=createDebugLogger("NON_INTERACTIVE_CLI");var TurnInterruptedError=class extends Error{static{__name(this,"TurnInterruptedError")}constructor(){super("Operation cancelled.");this.name="TurnInterruptedError"}};var restoredBackgroundAgentSessions=new WeakMap;var STRUCTURED_SHUTDOWN_HOLDBACK_MS=500;function isHeadlessLoopSentinel(prompt){return detectLoopSentinel(prompt)!==null||detectAutonomousSentinel(prompt)!==null}__name(isHeadlessLoopSentinel,"isHeadlessLoopSentinel");var SUPPRESSED_OUTPUT_SUCCESS="Skipped: this turn's structured_output contract took precedence as the terminal output.";var SUPPRESSED_OUTPUT_RETRY=`${SUPPRESSED_OUTPUT_SUCCESS} Re-issue this call in a separate turn if needed.`;function suppressedOutputBody(structuredCaptured){return structuredCaptured?SUPPRESSED_OUTPUT_SUCCESS:SUPPRESSED_OUTPUT_RETRY}__name(suppressedOutputBody,"suppressedOutputBody");var LOOP_TYPE_LABELS={["consecutive_identical_tool_calls"]:"the model repeated the same tool call with identical arguments",["chanting_identical_sentences"]:"the model repeated the same sentence in its output or reasoning",["repetitive_thoughts"]:"the model repeated the same reasoning thought",["read_file_loop"]:"the model spent too many consecutive calls reading files without making progress",["action_stagnation"]:"the model kept calling the same tool without making progress",["shell_command_stagnation"]:"the model repeated similar shell inspection commands without making progress",["global_tool_call_duplicate"]:"the model repeated the same tool call across the turn, even when not back-to-back",["alternating_tool_call_pattern"]:"the model alternated between the same two tool calls in a repeating pattern",["turn_tool_call_cap"]:"the turn reached the per-turn tool-call limit",["invalid_tool_params_stagnation"]:"the model repeatedly sent invalid tool parameters without correcting them",["repeated_tool_execution_failure"]:"the same tool execution failure continued after a corrective reminder"};function formatLoopDetectedMessage(loopType){const reason=loopType?LOOP_TYPE_LABELS[loopType]:void 0;const detail=reason?` (${loopType}: ${reason})`:"";const isAlwaysOn=loopType==="consecutive_identical_tool_calls"||loopType==="shell_command_stagnation"||loopType==="global_tool_call_duplicate"||loopType==="invalid_tool_params_stagnation"||loopType==="repeated_tool_execution_failure";const hint=loopType==="turn_tool_call_cap"?" A per-turn tool-call cap was reached. The default is adaptive (allows up to 1000 diverse calls, halting only on repeated calls); an explicitly set `model.maxToolCallsPerTurn` is a hard cap. If the model was repeating the same call, investigate the repetition; otherwise unset the value to use the adaptive default, or raise it (set 0 to disable).":isAlwaysOn?" This is an always-on guard and cannot be disabled via `model.skipLoopDetection`.":" Set the `model.skipLoopDetection` setting to true to disable.";return`Loop detection halted the run${detail}.${hint}`}__name(formatLoopDetectedMessage,"formatLoopDetectedMessage");function sameGoalPermit(left,right){return left?.goalId===right.goalId&&left.revision===right.revision&&left.turnId===right.turnId}__name(sameGoalPermit,"sameGoalPermit");function formatGoalState(snapshot,operation){const goal=snapshot.goal;if(!goal){return operation==="clear"?"Goal cleared.":"No Goal is set."}const status=goal.status==="usage_limited"?"usage limited":goal.status;const summary=`Goal ${status}: ${goal.objective}`;const usage=[];if(goal.turnCount>0){const turns=goal.turnBudget??goal.turnCount;usage.push(`${goal.turnCount}${goal.turnBudget===void 0?"":` of ${goal.turnBudget}`} ${turns===1?"turn":"turns"}`)}if(goal.activeTimeMs>0&&goal.activeTimeBudgetMs!==void 0){usage.push(`${formatDuration(goal.activeTimeMs,{hideTrailingZeros:true})} of ${formatDuration(goal.activeTimeBudgetMs,{hideTrailingZeros:true})} active`)}if(goal.tokensUsed>0){const used=goal.tokensUsed.toLocaleString("en-US");usage.push(goal.tokenBudget===void 0?`${used} tokens`:`${used} of ${goal.tokenBudget.toLocaleString("en-US")} tokens`)}const lines=[summary];if(usage.length>0)lines.push(`Usage: ${usage.join(" \xB7 ")}`);if(goal.status!=="active"&&goal.lastReason){lines.push(`Reason: ${sanitizeTerminalText(goal.lastReason)}`)}return lines.join("\n")}__name(formatGoalState,"formatGoalState");async function claimUserGoalTurn(runtime,turnKey,signal){const immediate=runtime.permitForTurn(turnKey)??runtime.beginTurn(turnKey);if(immediate||runtime.getSnapshot().goal?.status!=="active"){return immediate}return new Promise((resolve,reject)=>{let settled=false;let unsubscribe=__name(()=>{},"unsubscribe");const finish=__name((permit,error)=>{if(settled)return;settled=true;unsubscribe();signal.removeEventListener("abort",onAbort);if(error!==void 0)reject(error);else resolve(permit)},"finish");const inspect=__name(()=>{try{const permit=runtime.permitForTurn(turnKey);if(permit||runtime.getSnapshot().goal?.status!=="active"){finish(permit)}}catch(error){finish(void 0,error)}},"inspect");const onAbort=__name(()=>finish(void 0),"onAbort");unsubscribe=runtime.subscribe(inspect);signal.addEventListener("abort",onAbort,{once:true});if(signal.aborted)onAbort();else inspect()})}__name(claimUserGoalTurn,"claimUserGoalTurn");function skipHeadlessLoopSentinel(scheduler,job){if(!isHeadlessLoopSentinel(job.prompt)){return false}if(job.recurring&&!job.durable){debugLogger.debug("skipHeadlessLoopSentinel: cleaning up recurring session loop.md cron in headless mode",{jobId:job.id});void scheduler.delete(job.id).catch(()=>{})}return true}__name(skipHeadlessLoopSentinel,"skipHeadlessLoopSentinel");function emitLoopDetectedMessage(config,loopType){const message=formatLoopDetectedMessage(loopType);if(config.getOutputFormat()!=="text"){return message}process.stderr.write(`${message}
|
|
5
5
|
`);return message}__name(emitLoopDetectedMessage,"emitLoopDetectedMessage");async function emitNonInteractiveFinalMessage(params){const{message,isError,adapter,config}=params;adapter.startAssistantMessage();adapter.processEvent({type:"content",value:message});adapter.finalizeAssistantMessage();const metrics=uiTelemetryService.getMetrics();const usage=computeUsageFromMetrics(metrics);const outputFormat=config.getOutputFormat();const stats=outputFormat==="json"?uiTelemetryService.getMetrics():void 0;await params.beforeEmit();adapter.emitResult({isError,durationMs:Date.now()-params.startTimeMs,apiDurationMs:0,numTurns:0,errorMessage:isError?message:void 0,usage,stats,summary:message})}__name(emitNonInteractiveFinalMessage,"emitNonInteractiveFinalMessage");function partitionHeadlessToolCalls(requests,config){let skillBefore=false;return partitionByConcurrencySafety(requests,request=>{const executionRequest=getHeadlessExecutionRequest(request,config);const canonicalName=canonicalToolName(executionRequest.name);const kind=config.getToolRegistry().getTool(canonicalName)?.kind;const inputMayChange=kind==="execute"&&(skillBefore||!config.getDisableAllHooks()&&(config.hasHooksForEvent("PreToolUse")||config.hasHooksForEvent("PermissionRequest")));skillBefore||=canonicalName===ToolNames.SKILL;return!inputMayChange&&isToolCallConcurrencySafe(executionRequest.name,kind,executionRequest.args)})}__name(partitionHeadlessToolCalls,"partitionHeadlessToolCalls");function getHeadlessExecutionRequest(request,config){if(canonicalToolName(request.name)!==ToolNames.TOOL_CALL){return request}const targetName=request.args["name"];let targetArgs=request.args["arguments"];if(typeof targetArgs==="string"){try{targetArgs=JSON.parse(targetArgs)}catch{return request}}if(typeof targetName!=="string"||typeof targetArgs!=="object"||targetArgs===null||Array.isArray(targetArgs)){return request}const registry=config.getToolRegistry();const target=registry.getTool(canonicalToolName(targetName));if(!target||!registry.isDeferredAndHidden(target.name)){return request}return{...request,name:target.name,args:targetArgs}}__name(getHeadlessExecutionRequest,"getHeadlessExecutionRequest");async function runNonInteractive(config,settings,input,prompt_id,options={}){return promptIdContext.run(prompt_id,async()=>{let adapter;const outputFormat=config.getOutputFormat();if(options.adapter){adapter=options.adapter}else if(outputFormat==="stream-json"){adapter=new StreamJsonOutputAdapter(config,config.getIncludePartialMessages())}else{adapter=new JsonOutputAdapter(config)}const ownsAdapter=options.adapter===void 0;const modSession=options.modSession??ModSession.create(config,settings,adapter);const ownsModSession=options.modSession===void 0;const unsubscribeRecordingFailure=ownsAdapter?subscribeToHeadlessChatRecordingFailures(config,adapter):void 0;let chatRecordingSettlement;const settleBeforeTerminalOutput=__name(()=>{chatRecordingSettlement??=(async()=>{if(ownsModSession)await modSession?.close();modSession?.flushLogs();await settleChatRecording(config,{finalize:ownsAdapter})})();return chatRecordingSettlement},"settleBeforeTerminalOutput");const emitResult=__name(async result=>{await settleBeforeTerminalOutput();adapter.emitResult(result);options.onResultEmitted?.();await modSession?.flushOutput()},"emitResult");const sessionId=config.getSessionId();const permissionMode=config.getApprovalMode();const cleanupReviewWorktrees=__name(gitTimeout=>{if(config.getShellExecutionSandbox?.())return;cleanupReviewWorktreeLeases({sessionId,promptId:prompt_id,repositoryRoot:config.getProjectRoot(),gitTimeout})},"cleanupReviewWorktrees");const unregisterReviewWorktreeCleanup=registerCleanup(()=>cleanupReviewWorktrees(1e3));let turnCount=0;let limitedTurnCount=0;let totalApiDurationMs=0;const startTime=Date.now();let activeInteractionPromptId=prompt_id;let activeInteractionOwner;const selectActiveInteraction=__name((promptId,startsInteraction=false)=>{if(startsInteraction||activeInteractionPromptId!==promptId){activeInteractionOwner=void 0}activeInteractionPromptId=promptId},"selectActiveInteraction");const captureActiveInteractionOwner=__name(()=>{activeInteractionOwner??=getActiveInteractionSpan(activeInteractionPromptId);return activeInteractionOwner},"captureActiveInteractionOwner");const endActiveInteraction=__name((status,metadata={})=>{const owner=captureActiveInteractionOwner();if(!owner||getActiveInteractionSpan(activeInteractionPromptId)!==owner){return}endInteractionSpan(status,{promptId:activeInteractionPromptId,...metadata})},"endActiveInteraction");const llmClient=config.getLlmClient();const abortController=options.abortController??new AbortController;const queuedGoalTurns=[];let activeGoalTurn;let goalRuntimeUnsubscribe;const emitGoalSnapshot=__name(snapshot=>{adapter.processEvent({type:"goal_state",value:snapshot})},"emitGoalSnapshot");const observeGoalRuntime=__name(runtime=>{goalRuntimeUnsubscribe??=runtime.subscribe(emitGoalSnapshot)},"observeGoalRuntime");const enforceSessionTurnLimit=__name(async isRuntimeGoalTurn=>{if(isRuntimeGoalTurn)return;limitedTurnCount++;const maxSessionTurns=config.getMaxSessionTurns();if(maxSessionTurns>=0&&limitedTurnCount>maxSessionTurns){await failClosedActiveGoalTurn("Headless Goal stopped after the session turn limit");await settleBeforeTerminalOutput();await handleMaxTurnsExceededError(config)}},"enforceSessionTurnLimit");let goalHostUnbind;const goalHost={startGoalTurn:__name(async input2=>{if(queuedGoalTurns.some(({permit:permit2})=>permit2.turnId===input2.permit.turnId)){return}const{permit,...continuation}=input2;queuedGoalTurns.push({permit:{...permit},turnKey:`goal-runtime:${permit.turnId}`,controller:new AbortController,origin:"runtime",...continuation})},"startGoalTurn"),preemptGoalTurn:__name(reason=>{for(const turn of queuedGoalTurns.splice(0)){turn.controller.abort(reason)}activeGoalTurn?.controller.abort(reason)},"preemptGoalTurn")};const bindGoalHost=__name(()=>{goalHostUnbind??=config.bindGoalTurnHost(goalHost)},"bindGoalHost");const markGoalTurnDelivered=__name(turn=>{try{config.getGoalRuntime().markTurnDelivered(turn.turnKey)}catch{}},"markGoalTurnDelivered");let settlingGoalTurn;let goalTurnSettlement;const failClosedActiveGoalTurn=__name((reason,pauseReason)=>{const turn=activeGoalTurn;if(!turn)return Promise.resolve();if(settlingGoalTurn===turn&&goalTurnSettlement){return goalTurnSettlement}settlingGoalTurn=turn;goalTurnSettlement=(async()=>{if(!turn.controller.signal.aborted){turn.controller.abort(reason)}try{const runtime=await config.getGoalRuntimeReady();if(!sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){return}if(runtime.getSnapshot().goal?.status==="active"){try{await runtime.dispatch({action:"pause",expectedGoalId:turn.permit.goalId,expectedRevision:turn.permit.revision,reason:pauseReason??goalPauseReasonForHeadlessFailure(reason)})}catch(error){debugLogger.warn("Failed to pause terminal headless Goal",error)}}try{await config.getChatRecordingService?.()?.flush()}catch(error){debugLogger.warn("Failed to flush terminal headless Goal",error)}if(sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){await runtime.finishTurn(turn.permit)}}catch(error){debugLogger.warn("Failed to close terminal headless Goal",error)}finally{if(activeGoalTurn===turn){activeGoalTurn=void 0}if(settlingGoalTurn===turn){settlingGoalTurn=void 0;goalTurnSettlement=void 0}}})();return goalTurnSettlement},"failClosedActiveGoalTurn");const finishGoalTurn=__name(async turn=>{const runtime=await config.getGoalRuntimeReady();if(!sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){return}let abortSettlement;const pauseOnAbort=__name(()=>{const exceeded=budgetEnforcer.getExceeded();abortSettlement??=runtime.dispatch({action:"pause",expectedGoalId:turn.permit.goalId,expectedRevision:turn.permit.revision,reason:exceeded?goalPauseReasonForRunBudget(exceeded.kind):GOAL_PAUSE_REASON_USER_INTERRUPT}).then(()=>void 0).catch(error=>{debugLogger.warn("Failed to pause aborted headless Goal",error)})},"pauseOnAbort");abortController.signal.addEventListener("abort",pauseOnAbort,{once:true});if(abortController.signal.aborted)pauseOnAbort();try{if(!abortController.signal.aborted){await runtime.finishTurn(turn.permit)}}finally{abortController.signal.removeEventListener("abort",pauseOnAbort);await abortSettlement}},"finishGoalTurn");const budgetEnforcer=new RunBudgetEnforcer({maxWallTimeSeconds:config.getMaxWallTimeSeconds(),maxToolCalls:config.getMaxToolCalls()},abortController);const stampBudgetAbort=__name(()=>{const exceeded=budgetEnforcer.getExceeded();if(!exceeded)return;endActiveInteraction("error",{errorMessage:exceeded.message,errorType:"run_budget_exceeded"})},"stampBudgetAbort");abortController.signal.addEventListener("abort",stampBudgetAbort,{once:true});budgetEnforcer.start();const routeAbort=__name(async()=>{const exceeded=budgetEnforcer.getExceeded();endActiveInteraction(exceeded?"error":"cancelled",{...exceeded?{errorMessage:exceeded.message,errorType:"run_budget_exceeded"}:{}});await failClosedActiveGoalTurn(exceeded?.message??"Headless Goal execution was cancelled",exceeded?goalPauseReasonForRunBudget(exceeded.kind):GOAL_PAUSE_REASON_USER_INTERRUPT);await settleBeforeTerminalOutput();if(exceeded){await handleBudgetExceededError(config,exceeded);throw new Error(exceeded.message)}if(options.recoverableCancellation===true&&abortController.signal.reason instanceof TurnInterruptedError){throw abortController.signal.reason}await handleCancellationError(config);throw new Error("Operation cancelled.")},"routeAbort");const localQueue=[];const sdkOnlyMonitorQueue=[];const isCancelledMonitorEvent=__name(item=>Boolean(item.monitorId&&item.sdkNotification?.status==="running"&&config.getMonitorRegistry().get(item.monitorId)?.status==="cancelled"),"isCancelledMonitorEvent");const emitNotificationToSdk=__name(item=>{if(item.sendMessageType!=="notification")return;adapter.emitUserMessage([{text:item.displayText}]);if(item.sdkNotification){adapter.emitSystemMessage("task_notification",item.sdkNotification)}},"emitNotificationToSdk");const flushQueuedNotificationsToSdk=__name(queue=>{while(queue.length>0){const item=queue.shift();if(!isCancelledMonitorEvent(item)){emitNotificationToSdk(item)}}},"flushQueuedNotificationsToSdk");let captureMonitorTurnsInLocalQueue=true;let oneShotMonitorsFinalized=false;const finalizeOneShotMonitors=__name(()=>{if(options.captureMonitorNotifications===false||oneShotMonitorsFinalized)return;oneShotMonitorsFinalized=true;captureMonitorTurnsInLocalQueue=false;config.getMonitorRegistry().abortAll();flushQueuedNotificationsToSdk(sdkOnlyMonitorQueue)},"finalizeOneShotMonitors");let pipeBroken=false;let workflowApprovalChannelRegistered=false;const stdoutErrorHandler=__name(err=>{if(err.code==="EPIPE"&&!pipeBroken){pipeBroken=true;process.stdout.destroy()}},"stdoutErrorHandler");const shutdownHandler=__name(()=>{debugLogger.debug("[runNonInteractive] Shutdown signal received");abortController.abort()},"shutdownHandler");const pendingTeammateMessages=[];let boundManager=null;let approvalListener=null;const detachFromManager=__name(m=>{m.setLeaderMessageCallback(null);if(approvalListener){m.getEventEmitter().off("teammate_approval_request",approvalListener);approvalListener=null}},"detachFromManager");const onTeamManagerChangeHandler=__name(manager=>{if(boundManager&&boundManager!==manager){detachFromManager(boundManager)}boundManager=manager;if(manager){manager.setLeaderMessageCallback(formatted=>{pendingTeammateMessages.push(formatted)});if(options.controlService){approvalListener=__name(event=>{options.controlService.permission.handleTeammateApproval(event).catch(err=>{debugLogger.warn("Teammate approval handling failed:",err)})},"approvalListener")}else{approvalListener=__name(event=>{const mode=config.getApprovalMode();const confirmationDetails=event.confirmationDetails;const requiresExplicitHostApproval=confirmationDetails?.type!=="plan"&&confirmationDetails!==void 0&&"hideAlwaysAllow"in confirmationDetails&&confirmationDetails.hideAlwaysAllow===true;if(mode==="yolo"&&!requiresExplicitHostApproval){event.respond("proceed_once").catch(err=>{debugLogger.warn("Teammate approval ProceedOnce failed:",err)});return}const reason=requiresExplicitHostApproval?mode==="yolo"?`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": this request requires an explicit interactive approval surface and cannot be bypassed by YOLO mode.`:`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": this request requires an explicit interactive approval surface, which is unavailable in non-stream-json mode with the current approval mode (${mode}). Use --input-format stream-json --output-format stream-json to review it.`:`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": current approval mode (${mode}) cannot prompt in non-stream-json mode. Use --yolo or stream-json to allow teammate tool calls.`;process.stderr.write(`[team] ${reason}
|
|
6
6
|
`);pendingTeammateMessages.push(`<team_notice>
|