@hostclubeos/miraos 0.0.1-beta → 0.0.5-beta
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/bundled/app-store-compliance/SKILL.md +58 -0
- package/bundled/bug-hunter/NOTICE +17 -0
- package/bundled/bug-hunter/SKILL.md +65 -0
- package/bundled/superpowers/NOTICE +11 -0
- package/bundled/superpowers/SKILL.md +43 -0
- package/bundled/superpowers/references/brainstorming/SKILL.md +316 -0
- package/bundled/superpowers/references/brainstorming/builder-check-prompt.md +23 -0
- package/bundled/superpowers/references/brainstorming/scripts/frame-template.html +213 -0
- package/bundled/superpowers/references/brainstorming/scripts/helper.js +167 -0
- package/bundled/superpowers/references/brainstorming/scripts/server.cjs +723 -0
- package/bundled/superpowers/references/brainstorming/scripts/start-server.sh +216 -0
- package/bundled/superpowers/references/brainstorming/scripts/stop-server.sh +120 -0
- package/bundled/superpowers/references/brainstorming/visual-companion.md +299 -0
- package/bundled/superpowers/references/diagnosing-superpowers/SKILL.md +120 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/analyst-common.md +38 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/cost-and-time.md +28 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/plan-adherence.md +29 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/quality-evidence.md +26 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/repeated-work.md +30 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/request-conflicts.md +20 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/scrub-audit.md +33 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/scrub.md +29 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/similar-session.md +38 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/skill-timeline.md +30 -0
- package/bundled/superpowers/references/diagnosing-superpowers/prompts/stumbles.md +28 -0
- package/bundled/superpowers/references/diagnosing-superpowers/references/context-safety.md +22 -0
- package/bundled/superpowers/references/diagnosing-superpowers/references/github-issues.md +47 -0
- package/bundled/superpowers/references/diagnosing-superpowers/references/redaction-policy.md +34 -0
- package/bundled/superpowers/references/diagnosing-superpowers/references/session-discovery.md +31 -0
- package/bundled/superpowers/references/diagnosing-superpowers/templates/bundle-README.md +77 -0
- package/bundled/superpowers/references/diagnosing-superpowers/templates/case.md +64 -0
- package/bundled/superpowers/references/diagnosing-superpowers/templates/issue.md +70 -0
- package/bundled/superpowers/references/diagnosing-superpowers/templates/report.md +82 -0
- package/bundled/superpowers/references/dispatching-parallel-agents/SKILL.md +167 -0
- package/bundled/superpowers/references/executing-plans/SKILL.md +323 -0
- package/bundled/superpowers/references/executing-plans/scripts/task-done +55 -0
- package/bundled/superpowers/references/executing-plans/scripts/task-start +32 -0
- package/bundled/superpowers/references/finishing-a-development-branch/SKILL.md +225 -0
- package/bundled/superpowers/references/receiving-code-review/SKILL.md +205 -0
- package/bundled/superpowers/references/requesting-code-review/SKILL.md +95 -0
- package/bundled/superpowers/references/requesting-code-review/code-reviewer.md +198 -0
- package/bundled/superpowers/references/subagent-driven-development/SKILL.md +339 -0
- package/bundled/superpowers/references/subagent-driven-development/implementer-prompt.md +154 -0
- package/bundled/superpowers/references/subagent-driven-development/re-review-prompt.md +116 -0
- package/bundled/superpowers/references/subagent-driven-development/references/batching.md +11 -0
- package/bundled/superpowers/references/subagent-driven-development/references/cannot-verify.md +10 -0
- package/bundled/superpowers/references/subagent-driven-development/references/final-review.md +49 -0
- package/bundled/superpowers/references/subagent-driven-development/references/fix-loop.md +77 -0
- package/bundled/superpowers/references/subagent-driven-development/references/handling-reports.md +15 -0
- package/bundled/superpowers/references/subagent-driven-development/references/preflight.md +26 -0
- package/bundled/superpowers/references/subagent-driven-development/references/resuming.md +12 -0
- package/bundled/superpowers/references/subagent-driven-development/scripts/review-package +64 -0
- package/bundled/superpowers/references/subagent-driven-development/scripts/sdd-repo +54 -0
- package/bundled/superpowers/references/subagent-driven-development/scripts/sdd-workspace +110 -0
- package/bundled/superpowers/references/subagent-driven-development/scripts/task-brief +108 -0
- package/bundled/superpowers/references/subagent-driven-development/task-reviewer-prompt.md +209 -0
- package/bundled/superpowers/references/systematic-debugging/SKILL.md +283 -0
- package/bundled/superpowers/references/systematic-debugging/condition-based-waiting-example.ts +159 -0
- package/bundled/superpowers/references/systematic-debugging/condition-based-waiting.md +115 -0
- package/bundled/superpowers/references/systematic-debugging/defense-in-depth.md +122 -0
- package/bundled/superpowers/references/systematic-debugging/find-polluter.sh +72 -0
- package/bundled/superpowers/references/systematic-debugging/root-cause-tracing.md +169 -0
- package/bundled/superpowers/references/test-driven-development/SKILL.md +330 -0
- package/bundled/superpowers/references/test-driven-development/writing-good-tests.md +198 -0
- package/bundled/superpowers/references/using-git-worktrees/SKILL.md +167 -0
- package/bundled/superpowers/references/using-superpowers/SKILL.md +65 -0
- package/bundled/superpowers/references/using-superpowers/references/antigravity-tools.md +23 -0
- package/bundled/superpowers/references/using-superpowers/references/claude-code-tools.md +29 -0
- package/bundled/superpowers/references/using-superpowers/references/codex-tools.md +108 -0
- package/bundled/superpowers/references/using-superpowers/references/gemini-tools.md +63 -0
- package/bundled/superpowers/references/using-superpowers/references/hermes-tools.md +56 -0
- package/bundled/superpowers/references/using-superpowers/references/muse-tools.md +35 -0
- package/bundled/superpowers/references/using-superpowers/references/pi-tools.md +16 -0
- package/bundled/superpowers/references/verification-before-completion/SKILL.md +120 -0
- package/bundled/superpowers/references/writing-plans/SKILL.md +204 -0
- package/bundled/superpowers/references/writing-skills/SKILL.md +399 -0
- package/bundled/superpowers/references/writing-skills/references/CLAUDE_MD_TESTING.md +189 -0
- package/bundled/superpowers/references/writing-skills/references/anthropic-best-practices.md +1150 -0
- package/bundled/superpowers/references/writing-skills/references/bulletproofing.md +80 -0
- package/bundled/superpowers/references/writing-skills/references/discovery.md +201 -0
- package/bundled/superpowers/references/writing-skills/references/flowcharts.md +37 -0
- package/bundled/superpowers/references/writing-skills/references/graphviz-conventions.dot +172 -0
- package/bundled/superpowers/references/writing-skills/references/persuasion-principles.md +187 -0
- package/bundled/superpowers/references/writing-skills/references/testing-skills-with-subagents.md +384 -0
- package/bundled/superpowers/references/writing-skills/render-graphs.js +169 -0
- package/bundled/swarm/SKILL.md +47 -0
- package/chunks/{MaxSizedBox-4XZJGJCR.js → MaxSizedBox-CBUPHLMW.js} +1 -1
- package/chunks/{StandaloneSessionPicker-YUWFI6WT.js → StandaloneSessionPicker-EXZJQKTK.js} +1 -1
- package/chunks/{acp-subagent-executor-7BGJRBWA.js → acp-subagent-executor-BMIXP52W.js} +1 -1
- package/chunks/{acpAgent-DO3DYSKS.js → acpAgent-UHWDA3W7.js} +3 -3
- package/chunks/{advisor-ZMSGPCRF.js → advisor-5RUG3VFZ.js} +1 -1
- package/chunks/{agent-ZMZLTEBG.js → agent-SGQ7AEZI.js} +1 -1
- package/chunks/{agent-headless-5COOZKMA.js → agent-headless-ZGCZ2DA7.js} +1 -1
- package/chunks/{agent-host-client-L2ROWXVT.js → agent-host-client-HY5GPSHM.js} +1 -1
- package/chunks/{agent-host-connections-A4UGANXV.js → agent-host-connections-KGTBS37X.js} +1 -1
- package/chunks/{autofix-pr-N3M7IGHT.js → autofix-pr-E62FC67X.js} +1 -1
- package/chunks/{autofix-pr-VWZPABZQ.js → autofix-pr-TRI4NMYI.js} +1 -1
- package/chunks/{batch-RTO7FWGG.js → batch-OUC6FGCQ.js} +1 -1
- package/chunks/{bridge-ZZ2GF4DM.js → bridge-FLEIBB5V.js} +1 -1
- package/chunks/{bwrap-execution-6NIUP47A.js → bwrap-execution-VLHJWP4O.js} +1 -1
- package/chunks/{channel-settings-store-Y5HXLPQF.js → channel-settings-store-QG6HREVH.js} +1 -1
- package/chunks/{chunk-FXFSZ7QF.js → chunk-23543L6E.js} +1 -1
- package/chunks/{chunk-NM5TUAPJ.js → chunk-2GVKPBW5.js} +1 -1
- package/chunks/{chunk-DPKN7TSL.js → chunk-2QYFSBJY.js} +1 -1
- package/chunks/{chunk-NMB6IBA7.js → chunk-2TDRP3IX.js} +1 -1
- package/chunks/{chunk-ZE5YXIAJ.js → chunk-2VW4HXVF.js} +1 -1
- package/chunks/{chunk-FQXNP7EE.js → chunk-2ZWVSKPK.js} +1 -1
- package/chunks/{chunk-SBFKWNC3.js → chunk-3GJ56V2J.js} +1 -1
- package/chunks/{chunk-7JU5ZJJ7.js → chunk-3KFLO5W3.js} +1 -1
- package/chunks/{chunk-P4ZCOMZS.js → chunk-3MBYQYPC.js} +1 -1
- package/chunks/{chunk-FHGGT7VE.js → chunk-4346FNTB.js} +1 -1
- package/chunks/{chunk-IKQHFQ74.js → chunk-4GNHXVJZ.js} +1 -1
- package/chunks/{chunk-2FD2BYUZ.js → chunk-4IVYVCCU.js} +3 -3
- package/chunks/{chunk-ZEIWENJU.js → chunk-4KIFAVR2.js} +1 -1
- package/chunks/{chunk-YSWDQYJU.js → chunk-4MGTY3CJ.js} +1 -1
- package/chunks/{chunk-3LS3HVJA.js → chunk-4WYKHP7Q.js} +1 -1
- package/chunks/{chunk-MWGGXT4P.js → chunk-56PVVXUG.js} +1 -1
- package/chunks/{chunk-J4KLD52D.js → chunk-62DMHXLL.js} +1 -1
- package/chunks/{chunk-TALEJQWF.js → chunk-66DZADDA.js} +1 -1
- package/chunks/{chunk-GOEBFMO2.js → chunk-6RDYPRV6.js} +1 -1
- package/chunks/{chunk-5HNCGRMZ.js → chunk-724YPZRX.js} +1 -1
- package/chunks/{chunk-HA6K73R7.js → chunk-744QTJR2.js} +2 -2
- package/chunks/{chunk-SCQWVHLA.js → chunk-7F5IYTVE.js} +1 -1
- package/chunks/{chunk-TDM5PKRC.js → chunk-7VP4KALB.js} +1 -1
- package/chunks/{chunk-QWOBTVIO.js → chunk-7W5DOBKY.js} +1 -1
- package/chunks/{chunk-UL5A63VS.js → chunk-AE6E2YKY.js} +1 -1
- package/chunks/{chunk-J2DA7XAM.js → chunk-AIAYQAPA.js} +1 -1
- package/chunks/{chunk-3XFUS57Z.js → chunk-AIGBQN6R.js} +1 -1
- package/chunks/{chunk-BVYNPYGP.js → chunk-AJ75BPTA.js} +6 -1
- package/chunks/{chunk-LEZ3AZJI.js → chunk-ATVRF62A.js} +1 -1
- package/chunks/{chunk-DW4HTZVZ.js → chunk-BX3KM7OK.js} +1 -1
- package/chunks/{chunk-4UVQYN33.js → chunk-CUY6CVSL.js} +1 -1
- package/chunks/{chunk-RRXNG7AI.js → chunk-D3QZNIFB.js} +6 -6
- package/chunks/{chunk-5PZ4EFXH.js → chunk-D3YOXHQF.js} +1 -1
- package/chunks/{chunk-L66KXTVG.js → chunk-DABLVQXV.js} +1 -1
- package/chunks/{chunk-6AA5DYMC.js → chunk-DMM5LJWL.js} +2 -2
- package/chunks/{chunk-TWCQNRBQ.js → chunk-DNYXZVBT.js} +1 -1
- package/chunks/{chunk-HCIFQTQ4.js → chunk-E6LRCLLE.js} +2 -2
- package/chunks/{chunk-L44CUCID.js → chunk-EF3HUB7S.js} +1 -1
- package/chunks/{chunk-WQEJL3HN.js → chunk-EW3EVEYN.js} +1 -1
- package/chunks/{chunk-RMATGKAM.js → chunk-FC7SJIAS.js} +1 -1
- package/chunks/{chunk-4NQCOITC.js → chunk-FK5L2WVV.js} +1 -1
- package/chunks/{chunk-EMRZ722U.js → chunk-FRADUGRC.js} +1 -1
- package/chunks/{chunk-T2O3JMRH.js → chunk-FS67DOZQ.js} +1 -1
- package/chunks/{chunk-27MEJGPT.js → chunk-FXANOHXI.js} +5 -5
- package/chunks/{chunk-VCLKQDTV.js → chunk-GLQWA4W2.js} +1 -1
- package/chunks/{chunk-STPD3MIX.js → chunk-GOZ5FAUV.js} +1 -1
- package/chunks/{chunk-POX6TDCX.js → chunk-GTQULDIL.js} +1 -1
- package/chunks/{chunk-SR6MFJYO.js → chunk-GY4ID3EB.js} +1 -1
- package/chunks/{chunk-IJDGB3GP.js → chunk-H65ZVST6.js} +1 -1
- package/chunks/{chunk-6MWOHNU7.js → chunk-HASJX2YS.js} +1 -1
- package/chunks/{chunk-TJVI2L24.js → chunk-HSN5QUS7.js} +1 -1
- package/chunks/{chunk-7A42KF7G.js → chunk-HZ4L4MDM.js} +1 -1
- package/chunks/{chunk-WXVU3W2Q.js → chunk-IC42HQCH.js} +1 -1
- package/chunks/{chunk-NSA4ZO4V.js → chunk-IF3SWUYT.js} +1 -1
- package/chunks/{chunk-AGVUBA2V.js → chunk-J773THNP.js} +1 -1
- package/chunks/{chunk-ETYFIFMT.js → chunk-JDHMSERR.js} +1 -1
- package/chunks/{chunk-GNJTCOX3.js → chunk-JIQVUYBI.js} +1 -1
- package/chunks/{chunk-F5LMCQ2K.js → chunk-JJDF5FHA.js} +1 -1
- package/chunks/{chunk-TSI3G7JM.js → chunk-JQOLNQQN.js} +1 -1
- package/chunks/{chunk-ERUWCPGL.js → chunk-JQYPRANX.js} +1 -1
- package/chunks/{chunk-IW5GJAOR.js → chunk-K7KY7FIB.js} +1 -1
- package/chunks/{chunk-P2CUOX2Q.js → chunk-K7VOBDFT.js} +1 -1
- package/chunks/{chunk-SNGI5OD7.js → chunk-KK6SQPYG.js} +1 -1
- package/chunks/{chunk-HVAOQB42.js → chunk-KNW2OD46.js} +1 -1
- package/chunks/{chunk-GQSVGUOU.js → chunk-KP77CL5U.js} +1 -1
- package/chunks/{chunk-G6EIN5FW.js → chunk-KYK53GFP.js} +1 -1
- package/chunks/{chunk-432LPP2J.js → chunk-MQWKOOSR.js} +1 -1
- package/chunks/{chunk-XMIUDKGO.js → chunk-MUS4ADP7.js} +2 -2
- package/chunks/{chunk-IVHSWYWP.js → chunk-MYS5NQXO.js} +1 -1
- package/chunks/{chunk-FCOVJQX7.js → chunk-N4RIISOE.js} +1 -1
- package/chunks/{chunk-FCB7X7TI.js → chunk-NCBA52SB.js} +1 -1
- package/chunks/{chunk-GNV3UOVR.js → chunk-NGH27AWP.js} +1 -1
- package/chunks/{chunk-YM7CPT6W.js → chunk-NKWATWMD.js} +2 -2
- package/chunks/{chunk-R4HUU27E.js → chunk-NVD63O5H.js} +1 -1
- package/chunks/{chunk-WNT3ND65.js → chunk-NYM67KKZ.js} +2 -2
- package/chunks/{chunk-F6MHDBMX.js → chunk-O6Z3KO6R.js} +1 -1
- package/chunks/{chunk-RPMW55YH.js → chunk-OV2J3OED.js} +1 -1
- package/chunks/{chunk-RGOWOT3Z.js → chunk-P42MFWO2.js} +1 -1
- package/chunks/{chunk-XREDCQA5.js → chunk-P5543CFV.js} +1 -1
- package/chunks/{chunk-RHFRL6CB.js → chunk-PFECH6U6.js} +1 -1
- package/chunks/{chunk-3SQ76U4F.js → chunk-PFKTTUGS.js} +6 -6
- package/chunks/{chunk-XU5D2FKZ.js → chunk-PGKFDR73.js} +1 -1
- package/chunks/{chunk-LTUKVA3O.js → chunk-PQOQONLN.js} +1 -1
- package/chunks/{chunk-E7PL6EYK.js → chunk-PVHBBTAU.js} +1 -1
- package/chunks/{chunk-SKLO2WHR.js → chunk-PXBJPUGN.js} +1 -1
- package/chunks/{chunk-BCY6VYWQ.js → chunk-QEIX42MZ.js} +1 -1
- package/chunks/{chunk-MEUP65FI.js → chunk-QTCO5I4C.js} +1 -1
- package/chunks/{chunk-3KM4JL4Y.js → chunk-RBA3TP7L.js} +1 -1
- package/chunks/{chunk-R3H2AN4X.js → chunk-RKFNQQNA.js} +1 -1
- package/chunks/{chunk-RBYRJBQV.js → chunk-RNPVWQ3V.js} +1 -1
- package/chunks/{chunk-G7KBHT53.js → chunk-RRMTSVGU.js} +1 -1
- package/chunks/{chunk-W5YMSMZG.js → chunk-RWFOQXPU.js} +1 -1
- package/chunks/{chunk-R32F7IAM.js → chunk-SCHCTQCG.js} +1 -1
- package/chunks/{chunk-MC47YWMG.js → chunk-SHKSVOTG.js} +1 -1
- package/chunks/{chunk-YPG2SMZS.js → chunk-SK3QOQR4.js} +1 -1
- package/chunks/{chunk-5SFSOCHV.js → chunk-T3A53XMM.js} +1 -1
- package/chunks/{chunk-3SCCBDDE.js → chunk-T5PDEAU5.js} +1 -1
- package/chunks/{chunk-PIHZPQYO.js → chunk-T5XGTSQU.js} +1 -1
- package/chunks/{chunk-J4SZAKAX.js → chunk-TFITRCIC.js} +1 -1
- package/chunks/{chunk-THO23XWK.js → chunk-TLZM3DMY.js} +1 -1
- package/chunks/{chunk-Y6PDX4C4.js → chunk-TU5QHOJC.js} +1 -1
- package/chunks/{chunk-FFE5LIA6.js → chunk-TWJ4XBED.js} +1 -1
- package/chunks/{chunk-K6I2EP3G.js → chunk-UNJYVYTC.js} +1 -1
- package/chunks/{chunk-KSWZ6FTA.js → chunk-UOYXBAN7.js} +1 -1
- package/chunks/{chunk-GGXMABF2.js → chunk-USR2Y7B3.js} +1 -1
- package/chunks/{chunk-6O6IED5M.js → chunk-UWMLSAQY.js} +1 -1
- package/chunks/{chunk-OGPOUNG7.js → chunk-V5Z6OEKJ.js} +1 -1
- package/chunks/{chunk-MWMYT4PK.js → chunk-VBJV7T47.js} +1 -1
- package/chunks/{chunk-BAHNLZJQ.js → chunk-VF2UWWI2.js} +1 -1
- package/chunks/{chunk-MVF4MYTY.js → chunk-VJUTDS6C.js} +1 -1
- package/chunks/{chunk-A42T2FGM.js → chunk-W2ZVZ6LS.js} +1 -1
- package/chunks/{chunk-V6ZOOFZ3.js → chunk-W6IOHGWW.js} +1 -1
- package/chunks/{chunk-I5FHTXDB.js → chunk-WC72OWF2.js} +2 -2
- package/chunks/{chunk-XW5ZOTPK.js → chunk-WJLHLFIR.js} +1 -1
- package/chunks/{chunk-T4P4FF3I.js → chunk-WZTO3EYG.js} +1 -1
- package/chunks/{chunk-IUUWYEF5.js → chunk-XZNF4YNN.js} +1 -1
- package/chunks/{chunk-N7OJZ7AS.js → chunk-YN6WXB6B.js} +1 -1
- package/chunks/{chunk-PJUXHD2F.js → chunk-YVN32EUM.js} +1 -1
- package/chunks/{chunk-B7XMOQLO.js → chunk-Z4JY3HGO.js} +1 -1
- package/chunks/{chunk-AIIV662S.js → chunk-ZOWMHZWO.js} +1 -1
- package/chunks/{codex-subagent-executor-AR4Q5IHV.js → codex-subagent-executor-UCDGQFTR.js} +1 -1
- package/chunks/{config-utils-5S5PZQ5S.js → config-utils-Z6F4DVLG.js} +1 -1
- package/chunks/{contextCommand-YEZP3P4L.js → contextCommand-HMVZT56Y.js} +1 -1
- package/chunks/{core-runtime-LISS3YR4.js → core-runtime-AV7CJXOL.js} +1 -1
- package/chunks/{create-sub-session-FCB4YENT.js → create-sub-session-NNKVHZKT.js} +1 -1
- package/chunks/{cron-create-E2PZGYSL.js → cron-create-HWZDFVPA.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-23KFZWC5.js → daemon-git-worktree-guard-Q3C45X7T.js} +1 -1
- package/chunks/{daemon-status-provider-KU7B5BBQ.js → daemon-status-provider-F6KB2LNG.js} +1 -1
- package/chunks/{daemon-trust-policy-FL3DDA6T.js → daemon-trust-policy-6D4KJANB.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-FCCK3YHW.js → daemon-trust-policy-monitor-BZ46W4IA.js} +1 -1
- package/chunks/{deferred-core-runtime-BCJU6YQI.js → deferred-core-runtime-YC5XIWEI.js} +1 -1
- package/chunks/{display-image-ZHNLZCK7.js → display-image-LAGHQ4RY.js} +1 -1
- package/chunks/{edit-SXQ5HK4W.js → edit-LOWDEKPX.js} +1 -1
- package/chunks/{enterPlanMode-NX6SOALP.js → enterPlanMode-NGSATDRH.js} +1 -1
- package/chunks/{environment-GFCR2C43.js → environment-CVIB5DW4.js} +1 -1
- package/chunks/{errors-WZJPHSEP.js → errors-USKSVZFO.js} +1 -1
- package/chunks/{execute-sandbox-VZ4OKFCC.js → execute-sandbox-KNRRYQ52.js} +1 -1
- package/chunks/{execution-sandbox-config-XQNSHI7G.js → execution-sandbox-config-XBW3PXDA.js} +1 -1
- package/chunks/{execution-tool-XPHUDQJ4.js → execution-tool-QSJLRU5N.js} +1 -1
- package/chunks/{execution-worker-6RXFIQH4.js → execution-worker-TQEIC4AJ.js} +1 -1
- package/chunks/{exitPlanMode-LP3D7M5M.js → exitPlanMode-AW2HOTIK.js} +1 -1
- package/chunks/{fast-path-2D5QZRQW.js → fast-path-DWPD5EGQ.js} +1 -1
- package/chunks/{glob-JFH2DTI7.js → glob-7U6FQSWZ.js} +1 -1
- package/chunks/{goal-tools-UL3O364Y.js → goal-tools-5ZB6GPCJ.js} +1 -1
- package/chunks/{handleAutoUpdate-MYD2LZXQ.js → handleAutoUpdate-MLUFTWFP.js} +1 -1
- package/chunks/{i18n-LDINZEX3.js → i18n-QAPQLOC3.js} +1 -1
- package/chunks/{initializer-LLXI4EVO.js → initializer-B27IZ7K4.js} +1 -1
- package/chunks/{installationInfo-4FS5ROEO.js → installationInfo-SAMHABWV.js} +1 -1
- package/chunks/{interactive-mod-session-UFB2CURW.js → interactive-mod-session-7LQ5CYUR.js} +1 -1
- package/chunks/{landlock-execution-3T5Y3SFY.js → landlock-execution-2BJ56FDV.js} +1 -1
- package/chunks/{list-45PFXWOV.js → list-TDMJQDQO.js} +1 -1
- package/chunks/{llm-VIFUT34L.js → llm-RBI7KXDE.js} +4 -4
- package/chunks/{loadedSettingsAdapter-3MNB7PHB.js → loadedSettingsAdapter-ZQK5KMEW.js} +1 -1
- package/chunks/{local-TBDN3BOU.js → local-HSG47CNJ.js} +1 -1
- package/chunks/{local-execution-environment-PNRU2WTJ.js → local-execution-environment-WJVCE26F.js} +1 -1
- package/chunks/{loggingContentGenerator-JA22TIC4.js → loggingContentGenerator-ALSG42YA.js} +1 -1
- package/chunks/{loop-wakeup-BXKFVB7H.js → loop-wakeup-LFU4LDJM.js} +1 -1
- package/chunks/{manage-memory-BMKA64KG.js → manage-memory-FBL6CHX2.js} +1 -1
- package/chunks/{managed-execution-engine-PVXRANOE.js → managed-execution-engine-FX7FDAWW.js} +1 -1
- package/chunks/{managed-local-serve-H5BEBXVR.js → managed-local-serve-YE4JDFNP.js} +1 -1
- package/chunks/{managed-npm-update-JGC5W6SL.js → managed-npm-update-2MKV7UOI.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-KCUQIRVR.js → managed-runtime-attestation-worker-DBAHM5MN.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-HCN3NINM.js → managed-runtime-bootstrap-SHEXUEZN.js} +1 -1
- package/chunks/{managed-runtime-session-worker-G4TB3S5M.js → managed-runtime-session-worker-YN4KML7A.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-4WSWY2MH.js → managed-runtime-ssh-worker-BZNJV7IB.js} +1 -1
- package/chunks/{managed-session-authority-H5USCQ6W.js → managed-session-authority-MFEINLXC.js} +1 -1
- package/chunks/{mcp-WXNSQID6.js → mcp-TS5PX5FY.js} +1 -1
- package/chunks/{memory-E5SQH3NJ.js → memory-JTDN5AEA.js} +1 -1
- package/chunks/{model-call-collection-PULBNXXQ.js → model-call-collection-TNBMD3YL.js} +1 -1
- package/chunks/{model-configuration-SJEIOQGZ.js → model-configuration-6KTQQTMO.js} +1 -1
- package/chunks/{modelConfigUtils-WJ27GPGB.js → modelConfigUtils-LCZZ3EQU.js} +1 -1
- package/chunks/{monitor-N25QQU7J.js → monitor-KCCNIKLE.js} +1 -1
- package/chunks/{nonInteractiveCli-E6RLP7AG.js → nonInteractiveCli-BXHX6EIU.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-Z5JBEIAW.js → nonInteractiveToolExecutor-R5CTTWKD.js} +1 -1
- package/chunks/{notebook-edit-WVLO2EUN.js → notebook-edit-KIWE2XOA.js} +1 -1
- package/chunks/{omni-RKVYBBQI.js → omni-IFTMWBMU.js} +1 -1
- package/chunks/{openaiContentGenerator-2G2XB3DF.js → openaiContentGenerator-XP3VPU6C.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-344BTMHF.js → openaiResponsesContentGenerator-ZJ6C22EA.js} +1 -1
- package/chunks/{pidfile-KS6QFQIJ.js → pidfile-42P24JIA.js} +1 -1
- package/chunks/{processUtils-U45GFMXN.js → processUtils-I2XOO5U2.js} +1 -1
- package/chunks/{prompt-terminal-ledger-HAK6RGOC.js → prompt-terminal-ledger-7EW46VQ4.js} +1 -1
- package/chunks/{reactive-degrade-S7C6GXHH.js → reactive-degrade-O4JO7MOX.js} +1 -1
- package/chunks/{read-file-RG5ZNNCH.js → read-file-VGC4O7F2.js} +1 -1
- package/chunks/{record-source-6J47E2DW.js → record-source-VX26ZO6I.js} +1 -1
- package/chunks/{request-shutdown-SCU5TN5V.js → request-shutdown-P7227UEF.js} +1 -1
- package/chunks/{resumeHistoryUtils-CDDEU4RO.js → resumeHistoryUtils-QMVIHQRW.js} +1 -1
- package/chunks/{review-H6FLIVJV.js → review-PC4IDLCG.js} +1 -1
- package/chunks/{ripGrep-XEDOYGPA.js → ripGrep-JY4PZABK.js} +1 -1
- package/chunks/{run-qwen-serve-ODBFOM6H.js → run-qwen-serve-XRWVWOZK.js} +1 -1
- package/chunks/{runtime-SCINDTK2.js → runtime-OL7B72CH.js} +1 -1
- package/chunks/{runtime-shell-policy-77EFLSNG.js → runtime-shell-policy-TXAWAOBK.js} +1 -1
- package/chunks/{sandboxConfig-WE7GXTES.js → sandboxConfig-EJTMWZHD.js} +1 -1
- package/chunks/{scheduled-tasks-4HL6GKQ4.js → scheduled-tasks-XQSZWZXG.js} +1 -1
- package/chunks/{scheduler-ETHKOB4B.js → scheduler-3TIRZEVB.js} +1 -1
- package/chunks/{search-memory-R4O5AIEV.js → search-memory-P5KOTUVV.js} +1 -1
- package/chunks/{send-message-SBQSBXDW.js → send-message-KFSKFXLX.js} +1 -1
- package/chunks/{serve-TRAGNNK6.js → serve-JCUT4WK7.js} +1 -1
- package/chunks/{server-BXVHT3XW.js → server-HMTRZJF7.js} +3 -3
- package/chunks/{session-A6NV4RLU.js → session-RGLZU6KY.js} +1 -1
- package/chunks/{session-attachments-root-WU56VFQN.js → session-attachments-root-O3YQ7HWD.js} +1 -1
- package/chunks/{session-execution-engine-selector-MG2ZDK25.js → session-execution-engine-selector-LZBHS3UO.js} +1 -1
- package/chunks/{session-pr-refresh-HQOHASVU.js → session-pr-refresh-L5Z5WCXS.js} +1 -1
- package/chunks/{sessionService-XBFZRVW6.js → sessionService-MMPZUN5X.js} +1 -1
- package/chunks/{settings-HDG72SDU.js → settings-7PYHXPN4.js} +1 -1
- package/chunks/{shell-VNVPTXQO.js → shell-E6QLKRVU.js} +1 -1
- package/chunks/{skill-4VDNIMOV.js → skill-55IZUUM5.js} +1 -1
- package/chunks/{skill-settings-VKC2ATCK.js → skill-settings-A2M5BPH7.js} +1 -1
- package/chunks/{spawnChannel-RB5Q6Z4U.js → spawnChannel-KWU26CB7.js} +1 -1
- package/chunks/{standalone-update-QDH63IIS.js → standalone-update-32WYZ3BJ.js} +1 -1
- package/chunks/{start-opentui-ui-VULNQJ3L.js → start-opentui-ui-YNTPK7LX.js} +2 -2
- package/chunks/{startInteractiveUI-XZATGHLR.js → startInteractiveUI-MWA2VYTJ.js} +2 -2
- package/chunks/{task-create-ODLLJ5EF.js → task-create-67YBESBR.js} +1 -1
- package/chunks/{task-update-ZNWF5QPF.js → task-update-DLBXOE5R.js} +1 -1
- package/chunks/{team-create-CUJXJ2ZS.js → team-create-ARICYIQB.js} +1 -1
- package/chunks/{team-plan-approval-36LS5SZD.js → team-plan-approval-JPRE6Q3R.js} +1 -1
- package/chunks/{terminal-image-renderer-FYGH5GYJ.js → terminal-image-renderer-HVIZ2VNE.js} +1 -1
- package/chunks/{theme-manager-AMNU6BMN.js → theme-manager-UEPLIBUP.js} +1 -1
- package/chunks/{tool-call-E635LKSC.js → tool-call-EFJKXI3Z.js} +1 -1
- package/chunks/{tool-result-media-USCQTGHC.js → tool-result-media-LMIYNXSD.js} +1 -1
- package/chunks/{tool-search-FNTAT2ZW.js → tool-search-D7HQTRQG.js} +1 -1
- package/chunks/{total-session-admission-6P5YNVII.js → total-session-admission-67QMR44O.js} +1 -1
- package/chunks/{trustedFolders-7SPIYZSS.js → trustedFolders-HARYVS3F.js} +1 -1
- package/chunks/{update-relaunch-ZYID7ZKA.js → update-relaunch-NVNPOK5J.js} +1 -1
- package/chunks/{updateCheck-A3JUVWQV.js → updateCheck-7NMXUCTN.js} +1 -1
- package/chunks/{upload-config-DT3IQPC7.js → upload-config-W2SICJ32.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-OS64SJOW.js → useAutoAcceptIndicator-ELMIP4TJ.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-SJLXPGT4.js → validateNonInterActiveAuth-3433WFLE.js} +1 -1
- package/chunks/{version-CD2O2AJ7.js → version-XCFKTEY3.js} +1 -1
- package/chunks/{web-fetch-CQZMLBDV.js → web-fetch-537RS6IX.js} +1 -1
- package/chunks/{web-search-47YZU3PO.js → web-search-O27MYFSW.js} +1 -1
- package/chunks/{workflow-ROHRWGL5.js → workflow-6QF4RMYM.js} +1 -1
- package/chunks/{workflow-ancestor-trust-YSFNC6J5.js → workflow-ancestor-trust-CABLU3VV.js} +1 -1
- package/chunks/{workspace-agents-P4T5564B.js → workspace-agents-5WP3PY7W.js} +1 -1
- package/chunks/{workspace-providers-status-GZOJR5XX.js → workspace-providers-status-7G2EJJEO.js} +1 -1
- package/chunks/{workspace-recovery-worker-C4KTT7J5.js → workspace-recovery-worker-ICCIDEWU.js} +1 -1
- package/chunks/{workspace-registration-store-2WDVL42M.js → workspace-registration-store-WHXMNQQQ.js} +1 -1
- package/chunks/{workspace-registry-2V2LYFXO.js → workspace-registry-NXBODLYH.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-7OH4M6FV.js → workspace-runtime-coordinator-CJXS273B.js} +1 -1
- package/chunks/{workspace-service-353F3S2A.js → workspace-service-HUDE2RXN.js} +1 -1
- package/chunks/{workspace-skills-status-A5FRCJJF.js → workspace-skills-status-FJC6U62F.js} +1 -1
- package/chunks/{workspace-trust-reconciler-N4AKVBD4.js → workspace-trust-reconciler-ZIQ3A5ZB.js} +1 -1
- package/chunks/{write-file-XOIVQYGC.js → write-file-652YGG7I.js} +1 -1
- package/chunks/{zoom-image-ACTDUJ4C.js → zoom-image-YEH4O74G.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/package.json +2 -2
- package/web-shell/assets/{PierreFilePreview-DR46bTX6.js → PierreFilePreview-DEhWK46v.js} +1 -1
- package/web-shell/assets/{SpreadsheetPreview-zgxr-aKy.js → SpreadsheetPreview-C-GgIuPX.js} +1 -1
- package/web-shell/assets/{WorkspaceFileBrowser-BEoibHvP.js → WorkspaceFileBrowser-64vDYikf.js} +1 -1
- package/web-shell/assets/{abnfDiagram-VCTEODGH-Cba-rfLM.js → abnfDiagram-VCTEODGH-C2WWURam.js} +1 -1
- package/web-shell/assets/{agents-route-DexLhLcH.js → agents-route-j5ba59xn.js} +1 -1
- package/web-shell/assets/{arc-BLxikpdy.js → arc-Bkr_-GVn.js} +1 -1
- package/web-shell/assets/{architectureDiagram-5GKGNRK7-BMaIAoGQ.js → architectureDiagram-5GKGNRK7-D_v_wDDW.js} +1 -1
- package/web-shell/assets/{blockDiagram-NRAW4CY4-CGSbuIDn.js → blockDiagram-NRAW4CY4-Csxc3YNo.js} +1 -1
- package/web-shell/assets/{c4Diagram-UCG6FXSJ-DVwZ8MO2.js → c4Diagram-UCG6FXSJ-PXryoJCB.js} +1 -1
- package/web-shell/assets/channel-6Pj4KPAs.js +1 -0
- package/web-shell/assets/{chunk-2Q5K7J3B-BzKDWtZ3.js → chunk-2Q5K7J3B-DwK5UBHI.js} +1 -1
- package/web-shell/assets/{chunk-5VM5RSS4-C8SFBHFV.js → chunk-5VM5RSS4-BC1hvD6_.js} +1 -1
- package/web-shell/assets/{chunk-F27PBJKO-D8brpDvU.js → chunk-F27PBJKO-iFe0IxfJ.js} +1 -1
- package/web-shell/assets/{chunk-G27WJ6UU-Cilx_eO_.js → chunk-G27WJ6UU-ROSuKRxI.js} +1 -1
- package/web-shell/assets/{chunk-JWPE2WC7-CeplW23S.js → chunk-JWPE2WC7-CYHS6PxA.js} +1 -1
- package/web-shell/assets/{chunk-LCL6LL3I-BUO5XSSe.js → chunk-LCL6LL3I-D5bFMqCy.js} +1 -1
- package/web-shell/assets/{chunk-POPQ4Y6H-DPo869nv.js → chunk-POPQ4Y6H-BJh77MGv.js} +1 -1
- package/web-shell/assets/{chunk-SVP7TREG-DhfIj0Jt.js → chunk-SVP7TREG-Cs81aYft.js} +1 -1
- package/web-shell/assets/{chunk-XXDRQBXY-B72Tsbdi.js → chunk-XXDRQBXY-DqDbN44E.js} +1 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-BaTUuuB8.js +1 -0
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-BaTUuuB8.js +1 -0
- package/web-shell/assets/{cose-bilkent-JH36ORCC-8EANR5K4.js → cose-bilkent-JH36ORCC-DhjrwADJ.js} +1 -1
- package/web-shell/assets/{cynefin-OW5HDTMX-Cj3uoFr9.js → cynefin-OW5HDTMX-Dh7t-_3M.js} +1 -1
- package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-CHwRYcv9.js → cynefinDiagram-5FMLGOSQ-5J4kto0C.js} +1 -1
- package/web-shell/assets/{dagre-3AP2YEHR-B50MDk4E.js → dagre-3AP2YEHR-28AdbIcl.js} +1 -1
- package/web-shell/assets/{diagram-S7CK7UJ4-Fbk8W4Ks.js → diagram-S7CK7UJ4-DmksuoIf.js} +1 -1
- package/web-shell/assets/{diagram-UQ7AKVKN-CNeEtpni.js → diagram-UQ7AKVKN-DUjgQ8Fg.js} +1 -1
- package/web-shell/assets/{diagram-VSXAHHWV-CYXiWI4p.js → diagram-VSXAHHWV-DUe_FpG-.js} +1 -1
- package/web-shell/assets/{diagram-VX7I27RA-CF7R7hGA.js → diagram-VX7I27RA-CJJ70teK.js} +1 -1
- package/web-shell/assets/{diagram-Z3DM3KII-DZzHpEub.js → diagram-Z3DM3KII-BgABlJO4.js} +1 -1
- package/web-shell/assets/{docx-preview-CjpeB47y.js → docx-preview-BMBWboRx.js} +1 -1
- package/web-shell/assets/{ebnfDiagram-PWID7BFC-CtH0z2j9.js → ebnfDiagram-PWID7BFC-B3nK_Lh7.js} +1 -1
- package/web-shell/assets/{erDiagram-SSCWMZ5O-D51BQ445.js → erDiagram-SSCWMZ5O-DCTdCWlu.js} +1 -1
- package/web-shell/assets/{flowDiagram-A5DVABFB-B1-3lJwP.js → flowDiagram-A5DVABFB-CPxk2UUl.js} +1 -1
- package/web-shell/assets/{ganttDiagram-EL5Y4UJY-iMw3jNW5.js → ganttDiagram-EL5Y4UJY-WZzMAKht.js} +1 -1
- package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-D_KI4JVS.js → gitGraphDiagram-WWUBYQGX-DKcO5ugU.js} +1 -1
- package/web-shell/assets/{index-D1oIEFvH.js → index-CkRLMu1y.js} +6 -6
- package/web-shell/assets/{index-iouf3mnZ.js → index-Dbm3-Fps.js} +1 -1
- package/web-shell/assets/{infoDiagram-RXCK75RN-CwG9MQQq.js → infoDiagram-RXCK75RN-CJX5DzdL.js} +1 -1
- package/web-shell/assets/{ishikawaDiagram-5VMMS53U-C99w6R-O.js → ishikawaDiagram-5VMMS53U-fF0Id5B6.js} +1 -1
- package/web-shell/assets/{journeyDiagram-EYS64GPL--T5XVhJh.js → journeyDiagram-EYS64GPL-BOAezBVe.js} +1 -1
- package/web-shell/assets/{kanban-definition-3QL26DDD-Cs-rGYgZ.js → kanban-definition-3QL26DDD-DdNBof9J.js} +1 -1
- package/web-shell/assets/{layout-BHU2s0xS.js → layout-CXX3l5w0.js} +1 -1
- package/web-shell/assets/{linear-DbLtsa7_.js → linear-Dnaccp-S.js} +1 -1
- package/web-shell/assets/{mermaid.core-CTBkTEXb.js → mermaid.core-BzdC3B6T.js} +6 -6
- package/web-shell/assets/{mindmap-definition-FBJOCRG2-RWLGqkYd.js → mindmap-definition-FBJOCRG2-D-gMUzLw.js} +1 -1
- package/web-shell/assets/{pegDiagram-XKGWAZYB-DIQRWxNr.js → pegDiagram-XKGWAZYB-B9n1WVZq.js} +1 -1
- package/web-shell/assets/{pieDiagram-E7YTZNPT-Dg9VHqU0.js → pieDiagram-E7YTZNPT-ok49U0zT.js} +1 -1
- package/web-shell/assets/{quadrantDiagram-AXDQQJYC-BFeuB7Iq.js → quadrantDiagram-AXDQQJYC-DJKha-v3.js} +1 -1
- package/web-shell/assets/{railroadDiagram-O6MQD6OU-DbO9AYto.js → railroadDiagram-O6MQD6OU-DjL4pl7y.js} +1 -1
- package/web-shell/assets/{requirementDiagram-EFPCY7ZU-ClpOYbUE.js → requirementDiagram-EFPCY7ZU-BpmmRw3A.js} +1 -1
- package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CaHmNc0O.js → sankeyDiagram-P5KCCOFB-KpteHB8X.js} +1 -1
- package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-4r32bqWv.js → sequenceDiagram-WJ2MYXX4-COMghCpA.js} +1 -1
- package/web-shell/assets/{sizeCapture-X5ZJPWSS-CGXqc7rW.js → sizeCapture-X5ZJPWSS-5fEwJD-n.js} +1 -1
- package/web-shell/assets/{stateDiagram-HBIQ2CUA-DuAO60my.js → stateDiagram-HBIQ2CUA-CnC7oXvs.js} +1 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-V_cfZFBL.js +1 -0
- package/web-shell/assets/{swimlanes-XN3QIQJK-DUQMHZRn.js → swimlanes-XN3QIQJK-bVlhZdve.js} +1 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-25wVg0WL.js +8 -0
- package/web-shell/assets/{timeline-definition-24CTP7MA-DNCSPOxv.js → timeline-definition-24CTP7MA-CBvYgMu5.js} +1 -1
- package/web-shell/assets/{vennDiagram-4TSXK5OY-Bxh1Z0T6.js → vennDiagram-4TSXK5OY-CUTYvV1j.js} +1 -1
- package/web-shell/assets/{wardleyDiagram-VM6X3IG4-D6fuN1bA.js → wardleyDiagram-VM6X3IG4-Djl4gxCB.js} +1 -1
- package/web-shell/assets/{xychartDiagram-S5SC5T6Z-DkwTa8kZ.js → xychartDiagram-S5SC5T6Z-BcJZtI2X.js} +1 -1
- package/web-shell/index.html +1 -1
- package/web-shell/sw.js +1 -1
- package/web-shell/assets/channel-CvkbH6SO.js +0 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-DuyseBqE.js +0 -1
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-DuyseBqE.js +0 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BjIYif-p.js +0 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DZB3DqrF.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{msSinceLastInteraction}from"./chunk-UGLQO5K7.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{DEFAULT_OPENAI_LOG_RETENTION_DAYS}from"./chunk-R4HUU27E.js";import{resolveOpenAILogDir}from"./chunk-MSAAQ2I7.js";import{FILE_HISTORY_DIR,getSubagentsRootDir}from"./chunk-3SQ76U4F.js";import{createDebugLogger,sessionIdContext}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat as stat3}from"node:fs/promises";import{createHash}from"node:crypto";import{join as join2}from"node:path";init_esbuild_shims();import{opendir,readdir,stat,rm,rmdir,unlink}from"node:fs/promises";import{join}from"node:path";var DEBUG_LOG_FILE_SUFFIX=".txt";var debugLogger=createDebugLogger("HOUSEKEEPING");var MS_PER_DAY=24*60*60*1e3;var MS_PER_HOUR=60*60*1e3;var MIN_DATE_MS=-864e13;var SWEEP_CONCURRENCY=20;function getCutoffDate(cleanupPeriodDays){const periodMs=cleanupPeriodDays>0?cleanupPeriodDays*MS_PER_DAY:MS_PER_HOUR;return new Date(Math.max(Date.now()-periodMs,MIN_DATE_MS))}__name(getCutoffDate,"getCutoffDate");async function sweepOldSessionDirs(root,opts){const result={removed:0,errors:0};const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const sessionDirs=entries.filter(e=>e.isDirectory()&&!excludes.has(e.name)).map(e=>join(root,e.name));for(let i=0;i<sessionDirs.length;i+=SWEEP_CONCURRENCY){const batch=sessionDirs.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async dir=>{try{const s=await stat(dir);if(s.mtime<opts.cutoffDate){await rm(dir,{recursive:true,force:true});result.removed++}}catch(err){result.errors++;debugLogger.error(`failed to sweep ${dir}`,err)}}))}if(opts.removeEmptyRoot!==false){await rmdir(root).catch(()=>{})}return result}__name(sweepOldSessionDirs,"sweepOldSessionDirs");async function cleanupOldFileHistoryBackups(opts){return sweepOldSessionDirs(join(Storage.getGlobalQwenDir(),FILE_HISTORY_DIR),opts)}__name(cleanupOldFileHistoryBackups,"cleanupOldFileHistoryBackups");async function cleanupOldSubagentTranscripts(opts){return sweepOldSessionDirs(opts.subagentsRoot,{...opts,removeEmptyRoot:false})}__name(cleanupOldSubagentTranscripts,"cleanupOldSubagentTranscripts");var OPENAI_LOG_FILE_PATTERN=/^openai-(\d{4}-\d{2}-\d{2})T\d{2}-\d{2}-\d{2}\.\d{3}Z-[a-f0-9]{8}(?:-[a-zA-Z0-9._](?:[a-zA-Z0-9._-]*[a-zA-Z0-9._])?)?\.json$/;async function cleanupOldOpenAILogs(opts){const result={removed:0,errors:0,completed:true};if(opts.signal?.aborted){result.completed=false;return result}let dir;try{dir=await opendir(opts.logDir)}catch(e){if(isENOENT(e))return result;debugLogger.error("opendir failed",e);throw e}const cutoffDay=opts.cutoffDate.toISOString().slice(0,10);let batch=[];for await(const entry of dir){if(opts.signal?.aborted){result.completed=false;break}const filenameDate=entry.isFile()?OPENAI_LOG_FILE_PATTERN.exec(entry.name)?.[1]:void 0;if(!filenameDate)continue;const filePath=join(opts.logDir,entry.name);batch.push((async()=>{try{let shouldRemove;if(filenameDate!==cutoffDay){shouldRemove=filenameDate<cutoffDay}else{const s=await stat(filePath);shouldRemove=s.mtime<opts.cutoffDate}if(shouldRemove){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}})());if(batch.length===SWEEP_CONCURRENCY){await Promise.all(batch);batch=[]}}await Promise.all(batch);return result}__name(cleanupOldOpenAILogs,"cleanupOldOpenAILogs");function isENOENT(e){return e?.code==="ENOENT"}__name(isENOENT,"isENOENT");async function cleanupOldDebugLogs(opts){const result={removed:0,errors:0};const root=Storage.getGlobalDebugDir();const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const logFiles=entries.flatMap(entry=>{if(!entry.isFile()||!entry.name.endsWith(DEBUG_LOG_FILE_SUFFIX)){return[]}const sessionId=entry.name.slice(0,-DEBUG_LOG_FILE_SUFFIX.length);if(!opts.isValidSessionId(sessionId)||excludes.has(sessionId)){return[]}return[join(root,entry.name)]});for(let i=0;i<logFiles.length;i+=SWEEP_CONCURRENCY){const batch=logFiles.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async filePath=>{try{const s=await stat(filePath);if(s.mtime<opts.cutoffDate){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}}))}return result}__name(cleanupOldDebugLogs,"cleanupOldDebugLogs");init_esbuild_shims();import{mkdir,open,stat as stat2,unlink as unlink2,writeFile}from"node:fs/promises";import{dirname}from"node:path";var debugLogger2=createDebugLogger("HOUSEKEEPING");var ONE_DAY_MS=24*60*60*1e3;var STALE_LOCK_MS=60*60*1e3;async function runThrottledOnce(opts,task){const minIntervalMs=opts.minIntervalMs??ONE_DAY_MS;const staleLockMs=opts.staleLockMs??STALE_LOCK_MS;await mkdir(dirname(opts.lockPath),{mode:448}).catch(()=>{});const firstFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(firstFreshForMs!==void 0){return{status:"fresh",retryAfterMs:firstFreshForMs}}let acquired=await tryAcquire(opts.lockPath);if(!acquired){try{const s=await stat2(opts.lockPath);if(Date.now()-s.mtimeMs>staleLockMs){await unlink2(opts.lockPath).catch(()=>{});acquired=await tryAcquire(opts.lockPath)}}catch{acquired=await tryAcquire(opts.lockPath)}if(!acquired){debugLogger2.debug(`${opts.name}: skipping, lock held`);return{status:"locked"}}}try{const secondFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(secondFreshForMs!==void 0){return{status:"fresh",retryAfterMs:secondFreshForMs}}let taskCompleted=false;try{taskCompleted=await task()!==false}finally{if(taskCompleted){try{await writeFile(opts.markerPath,new Date().toISOString())}catch(err){debugLogger2.debug(`${opts.name}: marker write failed (cleanup succeeded)`,err)}}}return{status:taskCompleted?"completed":"incomplete"}}finally{await unlink2(opts.lockPath).catch(()=>{debugLogger2.debug(`${opts.name}: lock unlink failed (harmless)`)})}}__name(runThrottledOnce,"runThrottledOnce");async function markerFreshForMs(markerPath,minIntervalMs,name){try{const s=await stat2(markerPath);const age=Date.now()-s.mtimeMs;if(age<minIntervalMs){debugLogger2.debug(`${name}: skipping, ran ${age}ms ago`);return minIntervalMs-age}}catch{}return void 0}__name(markerFreshForMs,"markerFreshForMs");async function tryAcquire(lockPath){try{const fh=await open(lockPath,"wx");await fh.close();return true}catch(e){if(e?.code==="EEXIST"){return false}throw e}}__name(tryAcquire,"tryAcquire");var debugLogger3=createDebugLogger("HOUSEKEEPING");var STARTUP_DELAY_MS=10*60*1e3;var RECURRING_INTERVAL_MS=24*60*60*1e3;var RECENT_INTERACTION_MS=60*1e3;var CATCHUP_THRESHOLD_MS=7*24*60*60*1e3;var STARTUP_DELAY_CATCHUP_MS=60*1e3;var NON_INTERACTIVE_LOCK_RETRY_MS=60*1e3;var NON_INTERACTIVE_FAILURE_RETRY_MS=10*60*1e3;var NON_INTERACTIVE_STOP_GRACE_MS=250;var FILE_HISTORY_MARKER=".file-history-cleanup";var SUBAGENT_MARKER=".subagent-cleanup";var OPENAI_LOGS_MARKER=".openai-logs-cleanup";var DEBUG_LOGS_MARKER=".debug-logs-cleanup";var PSEUDO_DEBUG_SESSION_STEMS=new Set(["transcript-replay","workspace-mcp-discovery"]);var started=false;var nonInteractiveJobs=new Map;var nonInteractiveQueue=[];var activeNonInteractiveJob;var activeNonInteractiveAbortController;var nonInteractiveWorker;var nonInteractiveStopping=false;var nonInteractiveStopPromise;function startBackgroundHousekeeping(config,settings){if(started)return;started=true;void scheduleFirstPass(config,settings).catch(err=>{started=false;debugLogger3.error("scheduleFirstPass failed; chain will retry on next start",err)})}__name(startBackgroundHousekeeping,"startBackgroundHousekeeping");async function scheduleFirstPass(config,settings){const delay=await getFirstPassDelay(config,settings);debugLogger3.debug(`first pass in ${delay/1e3}s`);setTimeout(()=>scheduleNextPass(config,settings),delay).unref()}__name(scheduleFirstPass,"scheduleFirstPass");async function getFirstPassDelay(config,settings){const qwenDir=Storage.getGlobalQwenDir();const markerPaths=[join2(qwenDir,FILE_HISTORY_MARKER),getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir())];const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){markerPaths.push(getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}const catchUpStates=await Promise.all(markerPaths.map(needsCatchUp));return catchUpStates.some(Boolean)?STARTUP_DELAY_CATCHUP_MS:STARTUP_DELAY_MS}__name(getFirstPassDelay,"getFirstPassDelay");async function needsCatchUp(markerPath){try{const s=await stat3(markerPath);return Date.now()-s.mtimeMs>CATCHUP_THRESHOLD_MS}catch{return true}}__name(needsCatchUp,"needsCatchUp");function getSubagentMarkerPath(qwenDir,projectDir){const projectKey=createHash("sha256").update(projectDir).digest("hex").slice(0,16);return join2(qwenDir,`${SUBAGENT_MARKER}-${projectKey}`)}__name(getSubagentMarkerPath,"getSubagentMarkerPath");function getOpenAILogsMarkerPath(qwenDir,logDir){const logDirKey=createHash("sha256").update(logDir).digest("hex").slice(0,16);return join2(qwenDir,`${OPENAI_LOGS_MARKER}-${logDirKey}`)}__name(getOpenAILogsMarkerPath,"getOpenAILogsMarkerPath");function getDebugLogsMarkerPath(qwenDir,debugDir){const debugDirKey=createHash("sha256").update(debugDir).digest("hex").slice(0,16);return join2(qwenDir,`${DEBUG_LOGS_MARKER}-${debugDirKey}`)}__name(getDebugLogsMarkerPath,"getDebugLogsMarkerPath");function getOpenAILogCleanupTarget(config,settings){try{const customLogDir=config.getContentGeneratorConfig?.()?.openAILoggingDir??config.getModelsConfig?.()?.getGenerationConfig?.().openAILoggingDir??settings.merged.model?.openAILoggingDir;const systemRetention=settings.system?.settings.model?.openAILogRetentionDays;const workspaceRetention=settings.isTrusted?settings.workspace?.settings.model?.openAILogRetentionDays:void 0;if(customLogDir&&workspaceRetention!==void 0&&systemRetention===void 0){debugLogger3.error("workspace-scoped openAILogRetentionDays is unsafe with a custom openAILoggingDir; skipping cleanup");return void 0}const retentionDays=customLogDir?systemRetention??settings.user?.settings.model?.openAILogRetentionDays??settings.systemDefaults?.settings.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS:settings.merged.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS;return{logDir:resolveOpenAILogDir(customLogDir,config.getWorkingDir()),retentionDays}}catch(err){debugLogger3.error("failed to resolve OpenAI log cleanup target; skipping",err);return void 0}}__name(getOpenAILogCleanupTarget,"getOpenAILogCleanupTarget");function startNonInteractiveOpenAILogHousekeeping(config,settings){if(nonInteractiveStopping)return;sessionIdContext.exit(()=>{try{const target=getOpenAILogCleanupTarget(config,settings);if(!target||nonInteractiveJobs.has(target.logDir))return;const markerPath=getOpenAILogsMarkerPath(Storage.getGlobalQwenDir(),target.logDir);const job={target,markerPath,queued:false};nonInteractiveJobs.set(target.logDir,job);enqueueNonInteractiveJob(job)}catch(err){debugLogger3.error("failed to start non-interactive OpenAI log cleanup; skipping",err)}})}__name(startNonInteractiveOpenAILogHousekeeping,"startNonInteractiveOpenAILogHousekeeping");function stopNonInteractiveOpenAILogHousekeeping(){if(nonInteractiveStopPromise)return nonInteractiveStopPromise;nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer){clearTimeout(job.timer);job.timer=void 0}job.queued=false}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();nonInteractiveStopPromise=waitForNonInteractiveWorkerToStop();return nonInteractiveStopPromise}__name(stopNonInteractiveOpenAILogHousekeeping,"stopNonInteractiveOpenAILogHousekeeping");function enqueueNonInteractiveJob(job){if(nonInteractiveStopping||job.queued||activeNonInteractiveJob===job){return}job.queued=true;nonInteractiveQueue.push(job);startNonInteractiveWorker()}__name(enqueueNonInteractiveJob,"enqueueNonInteractiveJob");function startNonInteractiveWorker(){if(nonInteractiveWorker||nonInteractiveStopping)return;nonInteractiveWorker=drainNonInteractiveQueue().catch(err=>{debugLogger3.error("non-interactive OpenAI log worker failed",err)}).finally(()=>{nonInteractiveWorker=void 0;if(nonInteractiveQueue.length>0&&!nonInteractiveStopping){startNonInteractiveWorker()}})}__name(startNonInteractiveWorker,"startNonInteractiveWorker");async function drainNonInteractiveQueue(){while(!nonInteractiveStopping){const job=nonInteractiveQueue.shift();if(!job)return;job.queued=false;activeNonInteractiveJob=job;const abortController=new AbortController;activeNonInteractiveAbortController=abortController;try{const result=await runOpenAILogCleanup(job.target,job.markerPath,abortController.signal);if(nonInteractiveStopping)continue;switch(result.status){case"completed":scheduleNonInteractiveJob(job,RECURRING_INTERVAL_MS);break;case"fresh":scheduleNonInteractiveJob(job,Math.min(RECURRING_INTERVAL_MS,Math.max(NON_INTERACTIVE_LOCK_RETRY_MS,result.retryAfterMs)));break;case"locked":scheduleNonInteractiveJob(job,NON_INTERACTIVE_LOCK_RETRY_MS);break;case"incomplete":break;default:break}}catch(err){debugLogger3.error(`non-interactive OpenAI log cleanup failed for ${job.target.logDir}`,err);if(!nonInteractiveStopping){scheduleNonInteractiveJob(job,NON_INTERACTIVE_FAILURE_RETRY_MS)}}finally{activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0}}}__name(drainNonInteractiveQueue,"drainNonInteractiveQueue");async function runOpenAILogCleanup(target,markerPath,signal){return runThrottledOnce({name:"openai-logs-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldOpenAILogs({logDir:target.logDir,cutoffDate:getCutoffDate(target.retentionDays),signal});debugLogger3.debug(`openai-logs: removed=${r.removed} errors=${r.errors} completed=${r.completed}`);return r.completed?void 0:false})}__name(runOpenAILogCleanup,"runOpenAILogCleanup");function scheduleNonInteractiveJob(job,delayMs){if(nonInteractiveStopping)return;job.timer=setTimeout(()=>{job.timer=void 0;enqueueNonInteractiveJob(job)},delayMs);job.timer.unref()}__name(scheduleNonInteractiveJob,"scheduleNonInteractiveJob");async function waitForNonInteractiveWorkerToStop(){const worker=nonInteractiveWorker;if(!worker){nonInteractiveJobs.clear();return}let timeout;try{await Promise.race([worker,new Promise(resolve=>{timeout=setTimeout(resolve,NON_INTERACTIVE_STOP_GRACE_MS)})])}finally{if(timeout)clearTimeout(timeout);nonInteractiveJobs.clear()}}__name(waitForNonInteractiveWorkerToStop,"waitForNonInteractiveWorkerToStop");async function runPass(config,settings){if(msSinceLastInteraction()<RECENT_INTERACTION_MS){debugLogger3.debug("user active, deferring 10 min");setTimeout(()=>scheduleNextPass(config,settings),STARTUP_DELAY_MS).unref();return}try{await runHousekeeping(config,settings)}catch(err){debugLogger3.error("housekeeping pass failed; will retry next cycle",err)}setTimeout(()=>scheduleNextPass(config,settings),RECURRING_INTERVAL_MS).unref()}__name(runPass,"runPass");function scheduleNextPass(config,settings){void runPass(config,settings).catch(err=>{debugLogger3.error("runPass rejected unexpectedly",err)})}__name(scheduleNextPass,"scheduleNextPass");async function runHousekeeping(config,settings){const days=settings.merged.general?.cleanupPeriodDays??30;const cutoff=getCutoffDate(days);const currentSessionId=config.getSessionId();const qwenDir=Storage.getGlobalQwenDir();await runThrottledOnce({name:"file-history-cleanup",markerPath:join2(qwenDir,FILE_HISTORY_MARKER),lockPath:join2(qwenDir,FILE_HISTORY_MARKER+".lock")},async()=>{const r=await cleanupOldFileHistoryBackups({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId])});debugLogger3.debug(`file-history: removed=${r.removed} errors=${r.errors}`)});const debugLogsMarkerPath=getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir());await runThrottledOnce({name:"debug-logs-cleanup",markerPath:debugLogsMarkerPath,lockPath:debugLogsMarkerPath+".lock"},async()=>{const r=await cleanupOldDebugLogs({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),isValidSessionId:__name(v=>isValidSessionId(v)||PSEUDO_DEBUG_SESSION_STEMS.has(v),"isValidSessionId")});debugLogger3.debug(`debug-logs: removed=${r.removed} errors=${r.errors}`)});const projectDir=config.storage?.getProjectDir?.();if(projectDir){const markerPath=getSubagentMarkerPath(qwenDir,projectDir);await runThrottledOnce({name:"subagent-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldSubagentTranscripts({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),subagentsRoot:getSubagentsRootDir(projectDir)});debugLogger3.debug(`subagents: removed=${r.removed} errors=${r.errors}`)})}const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){await runOpenAILogCleanup(openaiTarget,getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}}__name(runHousekeeping,"runHousekeeping");function _resetForTesting(){started=false}__name(_resetForTesting,"_resetForTesting");async function _resetNonInteractiveForTesting(){nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer)clearTimeout(job.timer)}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();await nonInteractiveWorker;nonInteractiveJobs.clear();activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0;nonInteractiveWorker=void 0;nonInteractiveStopping=false;nonInteractiveStopPromise=void 0}__name(_resetNonInteractiveForTesting,"_resetNonInteractiveForTesting");var _needsCatchUpForTesting=needsCatchUp;var _getFirstPassDelayForTesting=getFirstPassDelay;var _runHousekeepingForTesting=runHousekeeping;var _runPassForTesting=runPass;var _FILE_HISTORY_MARKER_FOR_TESTING=FILE_HISTORY_MARKER;var _getDebugLogsMarkerPathForTesting=getDebugLogsMarkerPath;var _getSubagentMarkerPathForTesting=getSubagentMarkerPath;var _getOpenAILogsMarkerPathForTesting=getOpenAILogsMarkerPath;export{startBackgroundHousekeeping,startNonInteractiveOpenAILogHousekeeping,stopNonInteractiveOpenAILogHousekeeping,_resetForTesting,_resetNonInteractiveForTesting,_needsCatchUpForTesting,_getFirstPassDelayForTesting,_runHousekeepingForTesting,_runPassForTesting,_FILE_HISTORY_MARKER_FOR_TESTING,_getDebugLogsMarkerPathForTesting,_getSubagentMarkerPathForTesting,_getOpenAILogsMarkerPathForTesting};
|
|
3
|
+
import{msSinceLastInteraction}from"./chunk-UGLQO5K7.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{DEFAULT_OPENAI_LOG_RETENTION_DAYS}from"./chunk-NVD63O5H.js";import{resolveOpenAILogDir}from"./chunk-MSAAQ2I7.js";import{FILE_HISTORY_DIR,getSubagentsRootDir}from"./chunk-PFKTTUGS.js";import{createDebugLogger,sessionIdContext}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat as stat3}from"node:fs/promises";import{createHash}from"node:crypto";import{join as join2}from"node:path";init_esbuild_shims();import{opendir,readdir,stat,rm,rmdir,unlink}from"node:fs/promises";import{join}from"node:path";var DEBUG_LOG_FILE_SUFFIX=".txt";var debugLogger=createDebugLogger("HOUSEKEEPING");var MS_PER_DAY=24*60*60*1e3;var MS_PER_HOUR=60*60*1e3;var MIN_DATE_MS=-864e13;var SWEEP_CONCURRENCY=20;function getCutoffDate(cleanupPeriodDays){const periodMs=cleanupPeriodDays>0?cleanupPeriodDays*MS_PER_DAY:MS_PER_HOUR;return new Date(Math.max(Date.now()-periodMs,MIN_DATE_MS))}__name(getCutoffDate,"getCutoffDate");async function sweepOldSessionDirs(root,opts){const result={removed:0,errors:0};const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const sessionDirs=entries.filter(e=>e.isDirectory()&&!excludes.has(e.name)).map(e=>join(root,e.name));for(let i=0;i<sessionDirs.length;i+=SWEEP_CONCURRENCY){const batch=sessionDirs.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async dir=>{try{const s=await stat(dir);if(s.mtime<opts.cutoffDate){await rm(dir,{recursive:true,force:true});result.removed++}}catch(err){result.errors++;debugLogger.error(`failed to sweep ${dir}`,err)}}))}if(opts.removeEmptyRoot!==false){await rmdir(root).catch(()=>{})}return result}__name(sweepOldSessionDirs,"sweepOldSessionDirs");async function cleanupOldFileHistoryBackups(opts){return sweepOldSessionDirs(join(Storage.getGlobalQwenDir(),FILE_HISTORY_DIR),opts)}__name(cleanupOldFileHistoryBackups,"cleanupOldFileHistoryBackups");async function cleanupOldSubagentTranscripts(opts){return sweepOldSessionDirs(opts.subagentsRoot,{...opts,removeEmptyRoot:false})}__name(cleanupOldSubagentTranscripts,"cleanupOldSubagentTranscripts");var OPENAI_LOG_FILE_PATTERN=/^openai-(\d{4}-\d{2}-\d{2})T\d{2}-\d{2}-\d{2}\.\d{3}Z-[a-f0-9]{8}(?:-[a-zA-Z0-9._](?:[a-zA-Z0-9._-]*[a-zA-Z0-9._])?)?\.json$/;async function cleanupOldOpenAILogs(opts){const result={removed:0,errors:0,completed:true};if(opts.signal?.aborted){result.completed=false;return result}let dir;try{dir=await opendir(opts.logDir)}catch(e){if(isENOENT(e))return result;debugLogger.error("opendir failed",e);throw e}const cutoffDay=opts.cutoffDate.toISOString().slice(0,10);let batch=[];for await(const entry of dir){if(opts.signal?.aborted){result.completed=false;break}const filenameDate=entry.isFile()?OPENAI_LOG_FILE_PATTERN.exec(entry.name)?.[1]:void 0;if(!filenameDate)continue;const filePath=join(opts.logDir,entry.name);batch.push((async()=>{try{let shouldRemove;if(filenameDate!==cutoffDay){shouldRemove=filenameDate<cutoffDay}else{const s=await stat(filePath);shouldRemove=s.mtime<opts.cutoffDate}if(shouldRemove){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}})());if(batch.length===SWEEP_CONCURRENCY){await Promise.all(batch);batch=[]}}await Promise.all(batch);return result}__name(cleanupOldOpenAILogs,"cleanupOldOpenAILogs");function isENOENT(e){return e?.code==="ENOENT"}__name(isENOENT,"isENOENT");async function cleanupOldDebugLogs(opts){const result={removed:0,errors:0};const root=Storage.getGlobalDebugDir();const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const logFiles=entries.flatMap(entry=>{if(!entry.isFile()||!entry.name.endsWith(DEBUG_LOG_FILE_SUFFIX)){return[]}const sessionId=entry.name.slice(0,-DEBUG_LOG_FILE_SUFFIX.length);if(!opts.isValidSessionId(sessionId)||excludes.has(sessionId)){return[]}return[join(root,entry.name)]});for(let i=0;i<logFiles.length;i+=SWEEP_CONCURRENCY){const batch=logFiles.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async filePath=>{try{const s=await stat(filePath);if(s.mtime<opts.cutoffDate){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}}))}return result}__name(cleanupOldDebugLogs,"cleanupOldDebugLogs");init_esbuild_shims();import{mkdir,open,stat as stat2,unlink as unlink2,writeFile}from"node:fs/promises";import{dirname}from"node:path";var debugLogger2=createDebugLogger("HOUSEKEEPING");var ONE_DAY_MS=24*60*60*1e3;var STALE_LOCK_MS=60*60*1e3;async function runThrottledOnce(opts,task){const minIntervalMs=opts.minIntervalMs??ONE_DAY_MS;const staleLockMs=opts.staleLockMs??STALE_LOCK_MS;await mkdir(dirname(opts.lockPath),{mode:448}).catch(()=>{});const firstFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(firstFreshForMs!==void 0){return{status:"fresh",retryAfterMs:firstFreshForMs}}let acquired=await tryAcquire(opts.lockPath);if(!acquired){try{const s=await stat2(opts.lockPath);if(Date.now()-s.mtimeMs>staleLockMs){await unlink2(opts.lockPath).catch(()=>{});acquired=await tryAcquire(opts.lockPath)}}catch{acquired=await tryAcquire(opts.lockPath)}if(!acquired){debugLogger2.debug(`${opts.name}: skipping, lock held`);return{status:"locked"}}}try{const secondFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(secondFreshForMs!==void 0){return{status:"fresh",retryAfterMs:secondFreshForMs}}let taskCompleted=false;try{taskCompleted=await task()!==false}finally{if(taskCompleted){try{await writeFile(opts.markerPath,new Date().toISOString())}catch(err){debugLogger2.debug(`${opts.name}: marker write failed (cleanup succeeded)`,err)}}}return{status:taskCompleted?"completed":"incomplete"}}finally{await unlink2(opts.lockPath).catch(()=>{debugLogger2.debug(`${opts.name}: lock unlink failed (harmless)`)})}}__name(runThrottledOnce,"runThrottledOnce");async function markerFreshForMs(markerPath,minIntervalMs,name){try{const s=await stat2(markerPath);const age=Date.now()-s.mtimeMs;if(age<minIntervalMs){debugLogger2.debug(`${name}: skipping, ran ${age}ms ago`);return minIntervalMs-age}}catch{}return void 0}__name(markerFreshForMs,"markerFreshForMs");async function tryAcquire(lockPath){try{const fh=await open(lockPath,"wx");await fh.close();return true}catch(e){if(e?.code==="EEXIST"){return false}throw e}}__name(tryAcquire,"tryAcquire");var debugLogger3=createDebugLogger("HOUSEKEEPING");var STARTUP_DELAY_MS=10*60*1e3;var RECURRING_INTERVAL_MS=24*60*60*1e3;var RECENT_INTERACTION_MS=60*1e3;var CATCHUP_THRESHOLD_MS=7*24*60*60*1e3;var STARTUP_DELAY_CATCHUP_MS=60*1e3;var NON_INTERACTIVE_LOCK_RETRY_MS=60*1e3;var NON_INTERACTIVE_FAILURE_RETRY_MS=10*60*1e3;var NON_INTERACTIVE_STOP_GRACE_MS=250;var FILE_HISTORY_MARKER=".file-history-cleanup";var SUBAGENT_MARKER=".subagent-cleanup";var OPENAI_LOGS_MARKER=".openai-logs-cleanup";var DEBUG_LOGS_MARKER=".debug-logs-cleanup";var PSEUDO_DEBUG_SESSION_STEMS=new Set(["transcript-replay","workspace-mcp-discovery"]);var started=false;var nonInteractiveJobs=new Map;var nonInteractiveQueue=[];var activeNonInteractiveJob;var activeNonInteractiveAbortController;var nonInteractiveWorker;var nonInteractiveStopping=false;var nonInteractiveStopPromise;function startBackgroundHousekeeping(config,settings){if(started)return;started=true;void scheduleFirstPass(config,settings).catch(err=>{started=false;debugLogger3.error("scheduleFirstPass failed; chain will retry on next start",err)})}__name(startBackgroundHousekeeping,"startBackgroundHousekeeping");async function scheduleFirstPass(config,settings){const delay=await getFirstPassDelay(config,settings);debugLogger3.debug(`first pass in ${delay/1e3}s`);setTimeout(()=>scheduleNextPass(config,settings),delay).unref()}__name(scheduleFirstPass,"scheduleFirstPass");async function getFirstPassDelay(config,settings){const qwenDir=Storage.getGlobalQwenDir();const markerPaths=[join2(qwenDir,FILE_HISTORY_MARKER),getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir())];const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){markerPaths.push(getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}const catchUpStates=await Promise.all(markerPaths.map(needsCatchUp));return catchUpStates.some(Boolean)?STARTUP_DELAY_CATCHUP_MS:STARTUP_DELAY_MS}__name(getFirstPassDelay,"getFirstPassDelay");async function needsCatchUp(markerPath){try{const s=await stat3(markerPath);return Date.now()-s.mtimeMs>CATCHUP_THRESHOLD_MS}catch{return true}}__name(needsCatchUp,"needsCatchUp");function getSubagentMarkerPath(qwenDir,projectDir){const projectKey=createHash("sha256").update(projectDir).digest("hex").slice(0,16);return join2(qwenDir,`${SUBAGENT_MARKER}-${projectKey}`)}__name(getSubagentMarkerPath,"getSubagentMarkerPath");function getOpenAILogsMarkerPath(qwenDir,logDir){const logDirKey=createHash("sha256").update(logDir).digest("hex").slice(0,16);return join2(qwenDir,`${OPENAI_LOGS_MARKER}-${logDirKey}`)}__name(getOpenAILogsMarkerPath,"getOpenAILogsMarkerPath");function getDebugLogsMarkerPath(qwenDir,debugDir){const debugDirKey=createHash("sha256").update(debugDir).digest("hex").slice(0,16);return join2(qwenDir,`${DEBUG_LOGS_MARKER}-${debugDirKey}`)}__name(getDebugLogsMarkerPath,"getDebugLogsMarkerPath");function getOpenAILogCleanupTarget(config,settings){try{const customLogDir=config.getContentGeneratorConfig?.()?.openAILoggingDir??config.getModelsConfig?.()?.getGenerationConfig?.().openAILoggingDir??settings.merged.model?.openAILoggingDir;const systemRetention=settings.system?.settings.model?.openAILogRetentionDays;const workspaceRetention=settings.isTrusted?settings.workspace?.settings.model?.openAILogRetentionDays:void 0;if(customLogDir&&workspaceRetention!==void 0&&systemRetention===void 0){debugLogger3.error("workspace-scoped openAILogRetentionDays is unsafe with a custom openAILoggingDir; skipping cleanup");return void 0}const retentionDays=customLogDir?systemRetention??settings.user?.settings.model?.openAILogRetentionDays??settings.systemDefaults?.settings.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS:settings.merged.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS;return{logDir:resolveOpenAILogDir(customLogDir,config.getWorkingDir()),retentionDays}}catch(err){debugLogger3.error("failed to resolve OpenAI log cleanup target; skipping",err);return void 0}}__name(getOpenAILogCleanupTarget,"getOpenAILogCleanupTarget");function startNonInteractiveOpenAILogHousekeeping(config,settings){if(nonInteractiveStopping)return;sessionIdContext.exit(()=>{try{const target=getOpenAILogCleanupTarget(config,settings);if(!target||nonInteractiveJobs.has(target.logDir))return;const markerPath=getOpenAILogsMarkerPath(Storage.getGlobalQwenDir(),target.logDir);const job={target,markerPath,queued:false};nonInteractiveJobs.set(target.logDir,job);enqueueNonInteractiveJob(job)}catch(err){debugLogger3.error("failed to start non-interactive OpenAI log cleanup; skipping",err)}})}__name(startNonInteractiveOpenAILogHousekeeping,"startNonInteractiveOpenAILogHousekeeping");function stopNonInteractiveOpenAILogHousekeeping(){if(nonInteractiveStopPromise)return nonInteractiveStopPromise;nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer){clearTimeout(job.timer);job.timer=void 0}job.queued=false}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();nonInteractiveStopPromise=waitForNonInteractiveWorkerToStop();return nonInteractiveStopPromise}__name(stopNonInteractiveOpenAILogHousekeeping,"stopNonInteractiveOpenAILogHousekeeping");function enqueueNonInteractiveJob(job){if(nonInteractiveStopping||job.queued||activeNonInteractiveJob===job){return}job.queued=true;nonInteractiveQueue.push(job);startNonInteractiveWorker()}__name(enqueueNonInteractiveJob,"enqueueNonInteractiveJob");function startNonInteractiveWorker(){if(nonInteractiveWorker||nonInteractiveStopping)return;nonInteractiveWorker=drainNonInteractiveQueue().catch(err=>{debugLogger3.error("non-interactive OpenAI log worker failed",err)}).finally(()=>{nonInteractiveWorker=void 0;if(nonInteractiveQueue.length>0&&!nonInteractiveStopping){startNonInteractiveWorker()}})}__name(startNonInteractiveWorker,"startNonInteractiveWorker");async function drainNonInteractiveQueue(){while(!nonInteractiveStopping){const job=nonInteractiveQueue.shift();if(!job)return;job.queued=false;activeNonInteractiveJob=job;const abortController=new AbortController;activeNonInteractiveAbortController=abortController;try{const result=await runOpenAILogCleanup(job.target,job.markerPath,abortController.signal);if(nonInteractiveStopping)continue;switch(result.status){case"completed":scheduleNonInteractiveJob(job,RECURRING_INTERVAL_MS);break;case"fresh":scheduleNonInteractiveJob(job,Math.min(RECURRING_INTERVAL_MS,Math.max(NON_INTERACTIVE_LOCK_RETRY_MS,result.retryAfterMs)));break;case"locked":scheduleNonInteractiveJob(job,NON_INTERACTIVE_LOCK_RETRY_MS);break;case"incomplete":break;default:break}}catch(err){debugLogger3.error(`non-interactive OpenAI log cleanup failed for ${job.target.logDir}`,err);if(!nonInteractiveStopping){scheduleNonInteractiveJob(job,NON_INTERACTIVE_FAILURE_RETRY_MS)}}finally{activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0}}}__name(drainNonInteractiveQueue,"drainNonInteractiveQueue");async function runOpenAILogCleanup(target,markerPath,signal){return runThrottledOnce({name:"openai-logs-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldOpenAILogs({logDir:target.logDir,cutoffDate:getCutoffDate(target.retentionDays),signal});debugLogger3.debug(`openai-logs: removed=${r.removed} errors=${r.errors} completed=${r.completed}`);return r.completed?void 0:false})}__name(runOpenAILogCleanup,"runOpenAILogCleanup");function scheduleNonInteractiveJob(job,delayMs){if(nonInteractiveStopping)return;job.timer=setTimeout(()=>{job.timer=void 0;enqueueNonInteractiveJob(job)},delayMs);job.timer.unref()}__name(scheduleNonInteractiveJob,"scheduleNonInteractiveJob");async function waitForNonInteractiveWorkerToStop(){const worker=nonInteractiveWorker;if(!worker){nonInteractiveJobs.clear();return}let timeout;try{await Promise.race([worker,new Promise(resolve=>{timeout=setTimeout(resolve,NON_INTERACTIVE_STOP_GRACE_MS)})])}finally{if(timeout)clearTimeout(timeout);nonInteractiveJobs.clear()}}__name(waitForNonInteractiveWorkerToStop,"waitForNonInteractiveWorkerToStop");async function runPass(config,settings){if(msSinceLastInteraction()<RECENT_INTERACTION_MS){debugLogger3.debug("user active, deferring 10 min");setTimeout(()=>scheduleNextPass(config,settings),STARTUP_DELAY_MS).unref();return}try{await runHousekeeping(config,settings)}catch(err){debugLogger3.error("housekeeping pass failed; will retry next cycle",err)}setTimeout(()=>scheduleNextPass(config,settings),RECURRING_INTERVAL_MS).unref()}__name(runPass,"runPass");function scheduleNextPass(config,settings){void runPass(config,settings).catch(err=>{debugLogger3.error("runPass rejected unexpectedly",err)})}__name(scheduleNextPass,"scheduleNextPass");async function runHousekeeping(config,settings){const days=settings.merged.general?.cleanupPeriodDays??30;const cutoff=getCutoffDate(days);const currentSessionId=config.getSessionId();const qwenDir=Storage.getGlobalQwenDir();await runThrottledOnce({name:"file-history-cleanup",markerPath:join2(qwenDir,FILE_HISTORY_MARKER),lockPath:join2(qwenDir,FILE_HISTORY_MARKER+".lock")},async()=>{const r=await cleanupOldFileHistoryBackups({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId])});debugLogger3.debug(`file-history: removed=${r.removed} errors=${r.errors}`)});const debugLogsMarkerPath=getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir());await runThrottledOnce({name:"debug-logs-cleanup",markerPath:debugLogsMarkerPath,lockPath:debugLogsMarkerPath+".lock"},async()=>{const r=await cleanupOldDebugLogs({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),isValidSessionId:__name(v=>isValidSessionId(v)||PSEUDO_DEBUG_SESSION_STEMS.has(v),"isValidSessionId")});debugLogger3.debug(`debug-logs: removed=${r.removed} errors=${r.errors}`)});const projectDir=config.storage?.getProjectDir?.();if(projectDir){const markerPath=getSubagentMarkerPath(qwenDir,projectDir);await runThrottledOnce({name:"subagent-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldSubagentTranscripts({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),subagentsRoot:getSubagentsRootDir(projectDir)});debugLogger3.debug(`subagents: removed=${r.removed} errors=${r.errors}`)})}const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){await runOpenAILogCleanup(openaiTarget,getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}}__name(runHousekeeping,"runHousekeeping");function _resetForTesting(){started=false}__name(_resetForTesting,"_resetForTesting");async function _resetNonInteractiveForTesting(){nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer)clearTimeout(job.timer)}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();await nonInteractiveWorker;nonInteractiveJobs.clear();activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0;nonInteractiveWorker=void 0;nonInteractiveStopping=false;nonInteractiveStopPromise=void 0}__name(_resetNonInteractiveForTesting,"_resetNonInteractiveForTesting");var _needsCatchUpForTesting=needsCatchUp;var _getFirstPassDelayForTesting=getFirstPassDelay;var _runHousekeepingForTesting=runHousekeeping;var _runPassForTesting=runPass;var _FILE_HISTORY_MARKER_FOR_TESTING=FILE_HISTORY_MARKER;var _getDebugLogsMarkerPathForTesting=getDebugLogsMarkerPath;var _getSubagentMarkerPathForTesting=getSubagentMarkerPath;var _getOpenAILogsMarkerPathForTesting=getOpenAILogsMarkerPath;export{startBackgroundHousekeeping,startNonInteractiveOpenAILogHousekeeping,stopNonInteractiveOpenAILogHousekeeping,_resetForTesting,_resetNonInteractiveForTesting,_needsCatchUpForTesting,_getFirstPassDelayForTesting,_runHousekeepingForTesting,_runPassForTesting,_FILE_HISTORY_MARKER_FOR_TESTING,_getDebugLogsMarkerPathForTesting,_getSubagentMarkerPathForTesting,_getOpenAILogsMarkerPathForTesting};
|
|
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{OPEN_TUI_RENDERER_VALUE,TUI_RENDERER_ENV_VAR,TUI_RENDERER_STRICT_ENV_VAR}from"./chunk-2HLVSWM6.js";import{isGitRepository}from"./chunk-744VRMDB.js";import{NPM_RUNTIME_CONTEXT}from"./chunk-3ITJ3AIN.js";import{createDebugLogger}from"./chunk-46KPDLFH.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 path from"node:path";import*as childProcess from"node:child_process";import{promisify}from"node:util";init_esbuild_shims();import{accessSync,constants,readFileSync,realpathSync,statSync}from"node:fs";import{createRequire}from"node:module";import{basename,dirname,isAbsolute,join}from"node:path";var BUN_PACKAGES={"darwin-arm64":"@oven/bun-darwin-aarch64","darwin-x64":"@oven/bun-darwin-x64","linux-arm64":"@oven/bun-linux-aarch64","linux-x64":"@oven/bun-linux-x64"};function executableFile(file){const realPath=realpathSync(file);if(!statSync(realPath).isFile())throw new Error("Expected an executable file");accessSync(realPath,constants.X_OK);return realPath}__name(executableFile,"executableFile");function npmPackageRoot(script){const root=dirname(realpathSync(script));const manifest=JSON.parse(readFileSync(join(root,"package.json"),"utf8"));if(basename(script)!=="cli.js"||manifest.name!=="@qwen-code/qwen-code"||manifest.bin?.qwen!=="cli-entry.js"||basename(dirname(root))!=="@qwen-code"||basename(dirname(dirname(root)))!=="node_modules"){throw new Error("The running CLI is not a published npm installation")}return root}__name(npmPackageRoot,"npmPackageRoot");function npmNodeAtBoot(){if(!process.versions["bun"])return process.execPath;try{const context=JSON.parse(process.env[NPM_RUNTIME_CONTEXT]??"");if(!context||typeof context!=="object")return process.execPath;const entry=context;if(typeof entry["node"]!=="string"||typeof entry["bun"]!=="string"||typeof entry["cli"]!=="string"||!isAbsolute(entry["node"])||entry["cli"]!==realpathSync(process.argv[1])||entry["bun"]!==realpathSync(process.execPath)){return process.execPath}npmPackageRoot(entry["cli"]);return entry["node"]}catch{return process.execPath}}__name(npmNodeAtBoot,"npmNodeAtBoot");var npmNodePath=npmNodeAtBoot();function getNpmNodePath(){return npmNodePath}__name(getNpmNodePath,"getNpmNodePath");function selectNpmBunHandoff({interactive,screenReader,protocolMode,sandbox,env=process.env,script=process.argv[1],platform=process.platform,arch=process.arch,versions=process.versions,execArgv=process.execArgv,glibc}){if(env[TUI_RENDERER_ENV_VAR]?.trim().toLowerCase()!==OPEN_TUI_RENDERER_VALUE||!interactive||screenReader||protocolMode||sandbox||env["SANDBOX"]||versions.bun){return void 0}const unavailable=__name(reason=>{if(["1","true"].includes(env[TUI_RENDERER_STRICT_ENV_VAR]?.trim().toLowerCase()??"")){throw new Error(`OpenTUI npm Bun handoff unavailable: ${reason}`)}return void 0},"unavailable");const name=BUN_PACKAGES[`${platform}-${arch}`];const supportedLibc=platform!=="linux"||(glibc??Boolean(process.report?.getReport()?.header?.glibcVersionRuntime));if(!name||!supportedLibc||env["OPENTUI_LIBC"]==="musl"){return unavailable("only macOS and glibc Linux arm64/x64 are supported")}if(env["QWEN_CODE_NO_RELAUNCH"]){return unavailable("QWEN_CODE_NO_RELAUNCH disables runtime handoff")}if(execArgv.some(arg=>arg!=="--expose-gc")||env["NODE_OPTIONS"]?.trim()||env["BUN_OPTIONS"]?.trim()){return unavailable("inherited runtime flags prevent Bun handoff")}if(!script)return void 0;let root;try{root=npmPackageRoot(script)}catch{return void 0}try{const manifest=JSON.parse(readFileSync(join(root,"package.json"),"utf8"));const version=manifest.optionalDependencies?.[name];if(!version||!/^\d+\.\d+\.\d+$/.test(version)){throw new Error(`no exact optional dependency pin for ${name}`)}const dependencyManifest=createRequire(join(root,"package.json")).resolve(`${name}/package.json`);const dependencyRoot=dirname(realpathSync(dependencyManifest));const installed=JSON.parse(readFileSync(dependencyManifest,"utf8"));const ownedDependency=[join(root,"node_modules",name),join(dirname(dirname(root)),name)].some(candidate=>{try{return realpathSync(candidate)===dependencyRoot}catch{return false}});if(installed.name!==name||installed.version!==version||!ownedDependency){throw new Error(`${name} does not match this installation's pinned runtime`)}const command=executableFile(join(dependencyRoot,"bin","bun"));return{interpreter:{command,runtime:"bun"},childEnv:{[NPM_RUNTIME_CONTEXT]:JSON.stringify({node:executableFile(process.execPath),bun:command,cli:realpathSync(script)})}}}catch(error){return unavailable(`install the published optional dependency ${name}; ${error instanceof Error?error.message:String(error)}`)}}__name(selectNpmBunHandoff,"selectNpmBunHandoff");var PackageManager=(PackageManager2=>{PackageManager2["NPM"]="npm";PackageManager2["YARN"]="yarn";PackageManager2["PNPM"]="pnpm";PackageManager2["PNPX"]="pnpx";PackageManager2["BUN"]="bun";PackageManager2["BUNX"]="bunx";PackageManager2["HOMEBREW"]="homebrew";PackageManager2["STANDALONE"]="standalone";PackageManager2["NPX"]="npx";PackageManager2["UNKNOWN"]="unknown";return PackageManager2})(PackageManager||{});function getNpmCliPath(nodePath=getNpmNodePath(),platform=process.platform){if(platform==="win32"){return path.win32.join(path.win32.dirname(nodePath),"node_modules","npm","bin","npm-cli.js")}const npmCliJs=path.posix.join(path.posix.dirname(nodePath),"..","lib","node_modules","npm","bin","npm-cli.js");const adjacentNpm=path.posix.join(path.posix.dirname(nodePath),"npm");try{const resolved=fs.realpathSync(adjacentNpm);if(resolved.endsWith(".js"))return resolved;return npmCliJs}catch{return npmCliJs}}__name(getNpmCliPath,"getNpmCliPath");var debugLogger=createDebugLogger("INSTALLATION_INFO");var STANDALONE_UNIX_INSTALLER="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.sh";var STANDALONE_WINDOWS_INSTALLER="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.ps1";var STANDALONE_UPDATE_PREFIX="Standalone install detected. Please rerun the standalone installer to update: ";function getStandaloneInstallerUrl(){return process.platform==="win32"?STANDALONE_WINDOWS_INSTALLER:STANDALONE_UNIX_INSTALLER}__name(getStandaloneInstallerUrl,"getStandaloneInstallerUrl");function resolveUpdateCommand(updateCommand,latestVersion){const isNightly=latestVersion.includes("nightly");return updateCommand.replace("@latest",isNightly?"@nightly":`@${latestVersion}`)}__name(resolveUpdateCommand,"resolveUpdateCommand");function formatUpdateInstructions(installationInfo,latestVersion){const lines=[];if(installationInfo.updateMessage&&!installationInfo.updateCommand){lines.push(...formatUpdateMessage(installationInfo.updateMessage,latestVersion))}if(installationInfo.updateCommand){const updateCmd=resolveUpdateCommand(installationInfo.updateCommand,latestVersion);lines.push("Run the following to update:",` ${updateCmd}`)}else if(!installationInfo.updateMessage){lines.push("Manual update required. Please reinstall Qwen Code.")}return lines}__name(formatUpdateInstructions,"formatUpdateInstructions");function formatUpdateMessage(updateMessage,latestVersion){const message=resolveUpdateCommand(updateMessage,latestVersion);const sudoPrefix="Update requires sudo. Please run: ";if(message.startsWith(sudoPrefix)){return["Update requires sudo. Please run:",` ${message.slice(sudoPrefix.length)}`]}if(message.startsWith(STANDALONE_UPDATE_PREFIX)){return[STANDALONE_UPDATE_PREFIX.trimEnd(),` ${message.slice(STANDALONE_UPDATE_PREFIX.length)}`]}return[message]}__name(formatUpdateMessage,"formatUpdateMessage");var execFileAsync=promisify(childProcess.execFile);var HOMEBREW_INFO_TIMEOUT_MS=5e3;async function getHomebrewLatestVersion(formula="qwen-code",run=execFileAsync){try{const{stdout}=await run("brew",["info","--json=v2","--formula",formula],{encoding:"utf8",timeout:HOMEBREW_INFO_TIMEOUT_MS});const parsed=JSON.parse(String(stdout));const stable=parsed.formulae?.[0]?.versions?.stable;return typeof stable==="string"&&stable.length>0?stable:null}catch(error){debugLogger.warn("Failed to query Homebrew formula version:",error);return null}}__name(getHomebrewLatestVersion,"getHomebrewLatestVersion");function getInstallationInfo(projectRoot,isAutoUpdateEnabled){const cliPath=process.argv[1];if(!cliPath){return{packageManager:"unknown",isGlobal:false}}try{const realPath=fs.realpathSync(cliPath).replace(/\\/g,"/");const normalizedProjectRoot=projectRoot?.replace(/\\/g,"/");const isGit=isGitRepository(process.cwd());if(isGit&&normalizedProjectRoot&&isSamePathOrInside(realPath,normalizedProjectRoot)&&!realPath.includes("/node_modules/")){return{packageManager:"unknown",isGlobal:false,updateMessage:'Running from a local git clone. Please update with "git pull".'}}if(realPath.includes("/.npm/_npx")||realPath.includes("/npm/_npx")){return{packageManager:"npx",isGlobal:false,updateMessage:"Running via npx, update not applicable."}}if(realPath.includes("/.pnpm/_pnpx")){return{packageManager:"pnpx",isGlobal:false,updateMessage:"Running via pnpx, update not applicable."}}const standaloneInfo=getStandaloneInstallInfo(realPath,isAutoUpdateEnabled);if(standaloneInfo){return standaloneInfo}if(process.platform==="darwin"){try{childProcess.execSync('brew list -1 | grep -q "^qwen-code$"',{stdio:"ignore"});return{packageManager:"homebrew",isGlobal:true,updateMessage:'Installed via Homebrew. Please update with "brew upgrade".'}}catch(_error){}}if(realPath.includes("/.pnpm/global")){const updateCommand2="pnpm add -g miraos@latest";return{packageManager:"pnpm",isGlobal:true,updateCommand:updateCommand2,updateMessage:isAutoUpdateEnabled?"Installed with pnpm. Attempting to automatically update now...":`Please run ${updateCommand2} to update`}}if(realPath.includes("/.yarn/global")){const updateCommand2="yarn global add miraos@latest";return{packageManager:"yarn",isGlobal:true,updateCommand:updateCommand2,updateMessage:isAutoUpdateEnabled?"Installed with yarn. Attempting to automatically update now...":`Please run ${updateCommand2} to update`}}if(realPath.includes("/.bun/install/cache")){return{packageManager:"bunx",isGlobal:false,updateMessage:"Running via bunx, update not applicable."}}if(realPath.includes("/.bun/bin")){const updateCommand2="bun add -g miraos@latest";return{packageManager:"bun",isGlobal:true,updateCommand:updateCommand2,updateMessage:isAutoUpdateEnabled?"Installed with bun. Attempting to automatically update now...":`Please run ${updateCommand2} to update`}}if(normalizedProjectRoot&&isSamePathOrInside(realPath,`${normalizedProjectRoot}/node_modules`)){let pm="npm";if(fs.existsSync(path.join(projectRoot,"yarn.lock"))){pm="yarn"}else if(fs.existsSync(path.join(projectRoot,"pnpm-lock.yaml"))){pm="pnpm"}else if(fs.existsSync(path.join(projectRoot,"bun.lockb"))){pm="bun"}return{packageManager:pm,isGlobal:false,updateMessage:"Locally installed. Please update via your project's package.json."}}const npmPackageDir=path.dirname(path.dirname(realPath));let npmPrefixWritable=false;try{fs.accessSync(npmPackageDir,fs.constants.W_OK);npmPrefixWritable=true}catch{}if(!npmPrefixWritable){return{packageManager:"npm",isGlobal:true,updateMessage:"Update requires sudo. Please run: sudo npm install -g miraos@latest"}}const updateCommand="npm install -g miraos@latest";return{packageManager:"npm",isGlobal:true,updateCommand,updateMessage:isAutoUpdateEnabled?"Installed with npm. Attempting to automatically update now...":`Please run ${updateCommand} to update`}}catch(error){debugLogger.error("Failed to detect installation info:",error);return{packageManager:"unknown",isGlobal:false}}}__name(getInstallationInfo,"getInstallationInfo");function stripTrailingSlashes(value){return value.replace(/\/+$/,"")||"/"}__name(stripTrailingSlashes,"stripTrailingSlashes");function isSamePathOrInside(candidate,parent){const normalizedCandidate=stripTrailingSlashes(candidate);const normalizedParent=stripTrailingSlashes(parent);if(normalizedParent==="/"){return normalizedCandidate==="/"||normalizedCandidate.startsWith("/")}return normalizedCandidate===normalizedParent||normalizedCandidate.startsWith(`${normalizedParent}/`)}__name(isSamePathOrInside,"isSamePathOrInside");function getStandaloneInstallInfo(realPath,isAutoUpdateEnabled){const installDir=standaloneInstallDirForCliPath(realPath);if(!installDir||!isStandaloneInstallDir(installDir)){return null}const installerUrl=getStandaloneInstallerUrl();const updateCommand=process.platform==="win32"?`powershell -ExecutionPolicy Bypass -c "irm ${installerUrl} | iex"`:`curl -fsSL ${installerUrl} | bash`;return{packageManager:"standalone",isGlobal:true,isStandalone:true,standaloneDir:installDir,updateMessage:isAutoUpdateEnabled?"Standalone install detected. Attempting to automatically update now...":`${STANDALONE_UPDATE_PREFIX}${updateCommand}`}}__name(getStandaloneInstallInfo,"getStandaloneInstallInfo");function standaloneInstallDirForCliPath(realPath){const normalized=realPath.replace(/\\/g,"/");const suffix="/lib/cli.js";if(!normalized.endsWith(suffix)){return null}return realPath.slice(0,-suffix.length)}__name(standaloneInstallDirForCliPath,"standaloneInstallDirForCliPath");function isStandaloneInstallDir(installDir){try{const manifestPath=path.join(installDir,"manifest.json");if(!fs.existsSync(manifestPath)){return false}const manifest=JSON.parse(fs.readFileSync(manifestPath,"utf8"));if(manifest.name!=="@qwen-code/qwen-code"||typeof manifest.target!=="string"||!isStandaloneTargetForCurrentPlatform(manifest.target)){return false}const runtime=manifest.runtime==="bun"?"bun":"node";return hasStandaloneLauncherLayout(installDir,manifest.target,runtime)||hasStandaloneArchiveLayout(installDir,manifest.target,runtime)}catch(err){debugLogger.error("Standalone detection failed:",installDir,err);return false}}__name(isStandaloneInstallDir,"isStandaloneInstallDir");function standaloneRuntimePaths(installDir,target,runtime){const isWindowsTarget=target.startsWith("win");return{launcher:isWindowsTarget?path.join(installDir,"bin","qwen.cmd"):path.join(installDir,"bin","qwen"),interpreter:isWindowsTarget?path.join(installDir,runtime,`${runtime}.exe`):path.join(installDir,runtime,"bin",runtime),entryPoint:path.join(installDir,"lib","cli-entry.js")}}__name(standaloneRuntimePaths,"standaloneRuntimePaths");function hasStandaloneLauncherLayout(installDir,target,runtime){const{launcher,interpreter}=standaloneRuntimePaths(installDir,target,runtime);return fs.existsSync(launcher)&&fs.existsSync(interpreter)&&isStandaloneRuntimeFile(launcher)&&isStandaloneRuntimeFile(interpreter)}__name(hasStandaloneLauncherLayout,"hasStandaloneLauncherLayout");function hasStandaloneArchiveLayout(installDir,target,runtime){const{entryPoint,interpreter}=standaloneRuntimePaths(installDir,target,runtime);return fs.existsSync(entryPoint)&&fs.existsSync(interpreter)&&isStandaloneRuntimeFile(interpreter)}__name(hasStandaloneArchiveLayout,"hasStandaloneArchiveLayout");function isStandaloneTargetForCurrentPlatform(target){switch(process.platform){case"darwin":return/^darwin-(arm64|x64)$/.test(target);case"linux":return/^linux-(arm64|x64)$/.test(target);case"win32":return/^win-(arm64|x64)$/.test(target);default:return false}}__name(isStandaloneTargetForCurrentPlatform,"isStandaloneTargetForCurrentPlatform");function isStandaloneRuntimeFile(filePath){const stats=fs.lstatSync(filePath);if(!stats.isFile()||stats.isSymbolicLink()){return false}return process.platform==="win32"||(stats.mode&73)!==0}__name(isStandaloneRuntimeFile,"isStandaloneRuntimeFile");export{getNpmNodePath,selectNpmBunHandoff,PackageManager,getNpmCliPath,resolveUpdateCommand,formatUpdateInstructions,getHomebrewLatestVersion,getInstallationInfo,standaloneRuntimePaths,hasStandaloneArchiveLayout};
|
|
3
|
+
import{OPEN_TUI_RENDERER_VALUE,TUI_RENDERER_ENV_VAR,TUI_RENDERER_STRICT_ENV_VAR}from"./chunk-2HLVSWM6.js";import{isGitRepository}from"./chunk-744VRMDB.js";import{NPM_RUNTIME_CONTEXT}from"./chunk-3ITJ3AIN.js";import{createDebugLogger}from"./chunk-46KPDLFH.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 path from"node:path";import*as childProcess from"node:child_process";import{promisify}from"node:util";init_esbuild_shims();import{accessSync,constants,readFileSync,realpathSync,statSync}from"node:fs";import{createRequire}from"node:module";import{basename,dirname,isAbsolute,join}from"node:path";var BUN_PACKAGES={"darwin-arm64":"@oven/bun-darwin-aarch64","darwin-x64":"@oven/bun-darwin-x64","linux-arm64":"@oven/bun-linux-aarch64","linux-x64":"@oven/bun-linux-x64"};function executableFile(file){const realPath=realpathSync(file);if(!statSync(realPath).isFile())throw new Error("Expected an executable file");accessSync(realPath,constants.X_OK);return realPath}__name(executableFile,"executableFile");function npmPackageRoot(script){const root=dirname(realpathSync(script));const manifest=JSON.parse(readFileSync(join(root,"package.json"),"utf8"));if(basename(script)!=="cli.js"||manifest.name!=="@qwen-code/qwen-code"||manifest.bin?.qwen!=="cli-entry.js"||basename(dirname(root))!=="@qwen-code"||basename(dirname(dirname(root)))!=="node_modules"){throw new Error("The running CLI is not a published npm installation")}return root}__name(npmPackageRoot,"npmPackageRoot");function npmNodeAtBoot(){if(!process.versions["bun"])return process.execPath;try{const context=JSON.parse(process.env[NPM_RUNTIME_CONTEXT]??"");if(!context||typeof context!=="object")return process.execPath;const entry=context;if(typeof entry["node"]!=="string"||typeof entry["bun"]!=="string"||typeof entry["cli"]!=="string"||!isAbsolute(entry["node"])||entry["cli"]!==realpathSync(process.argv[1])||entry["bun"]!==realpathSync(process.execPath)){return process.execPath}npmPackageRoot(entry["cli"]);return entry["node"]}catch{return process.execPath}}__name(npmNodeAtBoot,"npmNodeAtBoot");var npmNodePath=npmNodeAtBoot();function getNpmNodePath(){return npmNodePath}__name(getNpmNodePath,"getNpmNodePath");function selectNpmBunHandoff({interactive,screenReader,protocolMode,sandbox,env=process.env,script=process.argv[1],platform=process.platform,arch=process.arch,versions=process.versions,execArgv=process.execArgv,glibc}){if(env[TUI_RENDERER_ENV_VAR]?.trim().toLowerCase()!==OPEN_TUI_RENDERER_VALUE||!interactive||screenReader||protocolMode||sandbox||env["SANDBOX"]||versions.bun){return void 0}const unavailable=__name(reason=>{if(["1","true"].includes(env[TUI_RENDERER_STRICT_ENV_VAR]?.trim().toLowerCase()??"")){throw new Error(`OpenTUI npm Bun handoff unavailable: ${reason}`)}return void 0},"unavailable");const name=BUN_PACKAGES[`${platform}-${arch}`];const supportedLibc=platform!=="linux"||(glibc??Boolean(process.report?.getReport()?.header?.glibcVersionRuntime));if(!name||!supportedLibc||env["OPENTUI_LIBC"]==="musl"){return unavailable("only macOS and glibc Linux arm64/x64 are supported")}if(env["QWEN_CODE_NO_RELAUNCH"]){return unavailable("QWEN_CODE_NO_RELAUNCH disables runtime handoff")}if(execArgv.some(arg=>arg!=="--expose-gc")||env["NODE_OPTIONS"]?.trim()||env["BUN_OPTIONS"]?.trim()){return unavailable("inherited runtime flags prevent Bun handoff")}if(!script)return void 0;let root;try{root=npmPackageRoot(script)}catch{return void 0}try{const manifest=JSON.parse(readFileSync(join(root,"package.json"),"utf8"));const version=manifest.optionalDependencies?.[name];if(!version||!/^\d+\.\d+\.\d+$/.test(version)){throw new Error(`no exact optional dependency pin for ${name}`)}const dependencyManifest=createRequire(join(root,"package.json")).resolve(`${name}/package.json`);const dependencyRoot=dirname(realpathSync(dependencyManifest));const installed=JSON.parse(readFileSync(dependencyManifest,"utf8"));const ownedDependency=[join(root,"node_modules",name),join(dirname(dirname(root)),name)].some(candidate=>{try{return realpathSync(candidate)===dependencyRoot}catch{return false}});if(installed.name!==name||installed.version!==version||!ownedDependency){throw new Error(`${name} does not match this installation's pinned runtime`)}const command=executableFile(join(dependencyRoot,"bin","bun"));return{interpreter:{command,runtime:"bun"},childEnv:{[NPM_RUNTIME_CONTEXT]:JSON.stringify({node:executableFile(process.execPath),bun:command,cli:realpathSync(script)})}}}catch(error){return unavailable(`install the published optional dependency ${name}; ${error instanceof Error?error.message:String(error)}`)}}__name(selectNpmBunHandoff,"selectNpmBunHandoff");var PackageManager=(PackageManager2=>{PackageManager2["NPM"]="npm";PackageManager2["YARN"]="yarn";PackageManager2["PNPM"]="pnpm";PackageManager2["PNPX"]="pnpx";PackageManager2["BUN"]="bun";PackageManager2["BUNX"]="bunx";PackageManager2["HOMEBREW"]="homebrew";PackageManager2["STANDALONE"]="standalone";PackageManager2["NPX"]="npx";PackageManager2["UNKNOWN"]="unknown";return PackageManager2})(PackageManager||{});function getNpmCliPath(nodePath=getNpmNodePath(),platform=process.platform){if(platform==="win32"){return path.win32.join(path.win32.dirname(nodePath),"node_modules","npm","bin","npm-cli.js")}const npmCliJs=path.posix.join(path.posix.dirname(nodePath),"..","lib","node_modules","npm","bin","npm-cli.js");const adjacentNpm=path.posix.join(path.posix.dirname(nodePath),"npm");try{const resolved=fs.realpathSync(adjacentNpm);if(resolved.endsWith(".js"))return resolved;return npmCliJs}catch{return npmCliJs}}__name(getNpmCliPath,"getNpmCliPath");var debugLogger=createDebugLogger("INSTALLATION_INFO");var STANDALONE_UNIX_INSTALLER="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.sh";var STANDALONE_WINDOWS_INSTALLER="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.ps1";var STANDALONE_UPDATE_PREFIX="Standalone install detected. Please rerun the standalone installer to update: ";function getStandaloneInstallerUrl(){return process.platform==="win32"?STANDALONE_WINDOWS_INSTALLER:STANDALONE_UNIX_INSTALLER}__name(getStandaloneInstallerUrl,"getStandaloneInstallerUrl");function resolveUpdateCommand(updateCommand,latestVersion){const isNightly=latestVersion.includes("nightly");return updateCommand.replace("@latest",isNightly?"@nightly":`@${latestVersion}`)}__name(resolveUpdateCommand,"resolveUpdateCommand");function formatUpdateInstructions(installationInfo,latestVersion){const lines=[];if(installationInfo.updateMessage&&!installationInfo.updateCommand){lines.push(...formatUpdateMessage(installationInfo.updateMessage,latestVersion))}if(installationInfo.updateCommand){const updateCmd=resolveUpdateCommand(installationInfo.updateCommand,latestVersion);lines.push("Run the following to update:",` ${updateCmd}`)}else if(!installationInfo.updateMessage){lines.push("Manual update required. Please reinstall Qwen Code.")}return lines}__name(formatUpdateInstructions,"formatUpdateInstructions");function formatUpdateMessage(updateMessage,latestVersion){const message=resolveUpdateCommand(updateMessage,latestVersion);const sudoPrefix="Update requires sudo. Please run: ";if(message.startsWith(sudoPrefix)){return["Update requires sudo. Please run:",` ${message.slice(sudoPrefix.length)}`]}if(message.startsWith(STANDALONE_UPDATE_PREFIX)){return[STANDALONE_UPDATE_PREFIX.trimEnd(),` ${message.slice(STANDALONE_UPDATE_PREFIX.length)}`]}return[message]}__name(formatUpdateMessage,"formatUpdateMessage");var execFileAsync=promisify(childProcess.execFile);var HOMEBREW_INFO_TIMEOUT_MS=5e3;async function getHomebrewLatestVersion(formula="qwen-code",run=execFileAsync){try{const{stdout}=await run("brew",["info","--json=v2","--formula",formula],{encoding:"utf8",timeout:HOMEBREW_INFO_TIMEOUT_MS});const parsed=JSON.parse(String(stdout));const stable=parsed.formulae?.[0]?.versions?.stable;return typeof stable==="string"&&stable.length>0?stable:null}catch(error){debugLogger.warn("Failed to query Homebrew formula version:",error);return null}}__name(getHomebrewLatestVersion,"getHomebrewLatestVersion");function getInstallationInfo(projectRoot,isAutoUpdateEnabled){const cliPath=process.argv[1];if(!cliPath){return{packageManager:"unknown",isGlobal:false}}try{const realPath=fs.realpathSync(cliPath).replace(/\\/g,"/");const normalizedProjectRoot=projectRoot?.replace(/\\/g,"/");const isGit=isGitRepository(process.cwd());if(isGit&&normalizedProjectRoot&&isSamePathOrInside(realPath,normalizedProjectRoot)&&!realPath.includes("/node_modules/")){return{packageManager:"unknown",isGlobal:false,updateMessage:'Running from a local git clone. Please update with "git pull".'}}if(realPath.includes("/.npm/_npx")||realPath.includes("/npm/_npx")){return{packageManager:"npx",isGlobal:false,updateMessage:"Running via npx, update not applicable."}}if(realPath.includes("/.pnpm/_pnpx")){return{packageManager:"pnpx",isGlobal:false,updateMessage:"Running via pnpx, update not applicable."}}const standaloneInfo=getStandaloneInstallInfo(realPath,isAutoUpdateEnabled);if(standaloneInfo){return standaloneInfo}if(process.platform==="darwin"){try{childProcess.execSync('brew list -1 | grep -q "^qwen-code$"',{stdio:"ignore"});return{packageManager:"homebrew",isGlobal:true,updateMessage:'Installed via Homebrew. Please update with "brew upgrade".'}}catch(_error){}}if(realPath.includes("/.pnpm/global")){const updateCommand2="pnpm add -g @hostclubeos/miraos@latest";return{packageManager:"pnpm",isGlobal:true,updateCommand:updateCommand2,updateMessage:isAutoUpdateEnabled?"Installed with pnpm. Attempting to automatically update now...":`Please run ${updateCommand2} to update`}}if(realPath.includes("/.yarn/global")){const updateCommand2="yarn global add @hostclubeos/miraos@latest";return{packageManager:"yarn",isGlobal:true,updateCommand:updateCommand2,updateMessage:isAutoUpdateEnabled?"Installed with yarn. Attempting to automatically update now...":`Please run ${updateCommand2} to update`}}if(realPath.includes("/.bun/install/cache")){return{packageManager:"bunx",isGlobal:false,updateMessage:"Running via bunx, update not applicable."}}if(realPath.includes("/.bun/bin")){const updateCommand2="bun add -g @hostclubeos/miraos@latest";return{packageManager:"bun",isGlobal:true,updateCommand:updateCommand2,updateMessage:isAutoUpdateEnabled?"Installed with bun. Attempting to automatically update now...":`Please run ${updateCommand2} to update`}}if(normalizedProjectRoot&&isSamePathOrInside(realPath,`${normalizedProjectRoot}/node_modules`)){let pm="npm";if(fs.existsSync(path.join(projectRoot,"yarn.lock"))){pm="yarn"}else if(fs.existsSync(path.join(projectRoot,"pnpm-lock.yaml"))){pm="pnpm"}else if(fs.existsSync(path.join(projectRoot,"bun.lockb"))){pm="bun"}return{packageManager:pm,isGlobal:false,updateMessage:"Locally installed. Please update via your project's package.json."}}const npmPackageDir=path.dirname(path.dirname(realPath));let npmPrefixWritable=false;try{fs.accessSync(npmPackageDir,fs.constants.W_OK);npmPrefixWritable=true}catch{}if(!npmPrefixWritable){return{packageManager:"npm",isGlobal:true,updateMessage:"Update requires sudo. Please run: sudo npm install -g @hostclubeos/miraos@latest"}}const updateCommand="npm install -g @hostclubeos/miraos@latest";return{packageManager:"npm",isGlobal:true,updateCommand,updateMessage:isAutoUpdateEnabled?"Installed with npm. Attempting to automatically update now...":`Please run ${updateCommand} to update`}}catch(error){debugLogger.error("Failed to detect installation info:",error);return{packageManager:"unknown",isGlobal:false}}}__name(getInstallationInfo,"getInstallationInfo");function stripTrailingSlashes(value){return value.replace(/\/+$/,"")||"/"}__name(stripTrailingSlashes,"stripTrailingSlashes");function isSamePathOrInside(candidate,parent){const normalizedCandidate=stripTrailingSlashes(candidate);const normalizedParent=stripTrailingSlashes(parent);if(normalizedParent==="/"){return normalizedCandidate==="/"||normalizedCandidate.startsWith("/")}return normalizedCandidate===normalizedParent||normalizedCandidate.startsWith(`${normalizedParent}/`)}__name(isSamePathOrInside,"isSamePathOrInside");function getStandaloneInstallInfo(realPath,isAutoUpdateEnabled){const installDir=standaloneInstallDirForCliPath(realPath);if(!installDir||!isStandaloneInstallDir(installDir)){return null}const installerUrl=getStandaloneInstallerUrl();const updateCommand=process.platform==="win32"?`powershell -ExecutionPolicy Bypass -c "irm ${installerUrl} | iex"`:`curl -fsSL ${installerUrl} | bash`;return{packageManager:"standalone",isGlobal:true,isStandalone:true,standaloneDir:installDir,updateMessage:isAutoUpdateEnabled?"Standalone install detected. Attempting to automatically update now...":`${STANDALONE_UPDATE_PREFIX}${updateCommand}`}}__name(getStandaloneInstallInfo,"getStandaloneInstallInfo");function standaloneInstallDirForCliPath(realPath){const normalized=realPath.replace(/\\/g,"/");const suffix="/lib/cli.js";if(!normalized.endsWith(suffix)){return null}return realPath.slice(0,-suffix.length)}__name(standaloneInstallDirForCliPath,"standaloneInstallDirForCliPath");function isStandaloneInstallDir(installDir){try{const manifestPath=path.join(installDir,"manifest.json");if(!fs.existsSync(manifestPath)){return false}const manifest=JSON.parse(fs.readFileSync(manifestPath,"utf8"));if(manifest.name!=="@qwen-code/qwen-code"||typeof manifest.target!=="string"||!isStandaloneTargetForCurrentPlatform(manifest.target)){return false}const runtime=manifest.runtime==="bun"?"bun":"node";return hasStandaloneLauncherLayout(installDir,manifest.target,runtime)||hasStandaloneArchiveLayout(installDir,manifest.target,runtime)}catch(err){debugLogger.error("Standalone detection failed:",installDir,err);return false}}__name(isStandaloneInstallDir,"isStandaloneInstallDir");function standaloneRuntimePaths(installDir,target,runtime){const isWindowsTarget=target.startsWith("win");return{launcher:isWindowsTarget?path.join(installDir,"bin","qwen.cmd"):path.join(installDir,"bin","qwen"),interpreter:isWindowsTarget?path.join(installDir,runtime,`${runtime}.exe`):path.join(installDir,runtime,"bin",runtime),entryPoint:path.join(installDir,"lib","cli-entry.js")}}__name(standaloneRuntimePaths,"standaloneRuntimePaths");function hasStandaloneLauncherLayout(installDir,target,runtime){const{launcher,interpreter}=standaloneRuntimePaths(installDir,target,runtime);return fs.existsSync(launcher)&&fs.existsSync(interpreter)&&isStandaloneRuntimeFile(launcher)&&isStandaloneRuntimeFile(interpreter)}__name(hasStandaloneLauncherLayout,"hasStandaloneLauncherLayout");function hasStandaloneArchiveLayout(installDir,target,runtime){const{entryPoint,interpreter}=standaloneRuntimePaths(installDir,target,runtime);return fs.existsSync(entryPoint)&&fs.existsSync(interpreter)&&isStandaloneRuntimeFile(interpreter)}__name(hasStandaloneArchiveLayout,"hasStandaloneArchiveLayout");function isStandaloneTargetForCurrentPlatform(target){switch(process.platform){case"darwin":return/^darwin-(arm64|x64)$/.test(target);case"linux":return/^linux-(arm64|x64)$/.test(target);case"win32":return/^win-(arm64|x64)$/.test(target);default:return false}}__name(isStandaloneTargetForCurrentPlatform,"isStandaloneTargetForCurrentPlatform");function isStandaloneRuntimeFile(filePath){const stats=fs.lstatSync(filePath);if(!stats.isFile()||stats.isSymbolicLink()){return false}return process.platform==="win32"||(stats.mode&73)!==0}__name(isStandaloneRuntimeFile,"isStandaloneRuntimeFile");export{getNpmNodePath,selectNpmBunHandoff,PackageManager,getNpmCliPath,resolveUpdateCommand,formatUpdateInstructions,getHomebrewLatestVersion,getInstallationInfo,standaloneRuntimePaths,hasStandaloneArchiveLayout};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{MAX_WORKSPACE_PATH_LENGTH,canonicalizeWorkspace}from"./chunk-L5UULTGF.js";import{getGlobalQwenDirLite}from"./chunk-ERGT5BD3.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{isUnverifiableIdentityError,openNoFollow}from"./chunk-PSKT6KWO.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{createHash}from"node:crypto";import*as fs from"node:fs/promises";import*as os from"node:os";import*as path from"node:path";init_esbuild_shims();var MAX_REGISTERED_WORKSPACES=256;var MAX_CONFIGURED_REGISTERED_WORKSPACES=256;var QWEN_SERVE_MAX_WORKSPACES_ENV="QWEN_SERVE_MAX_WORKSPACES";function resolveMaxRegisteredWorkspaces(configured,env){const raw=env[QWEN_SERVE_MAX_WORKSPACES_ENV];const value=configured??(raw===void 0?MAX_REGISTERED_WORKSPACES:/^\d+$/.test(raw.trim())?Number(raw.trim()):Number.NaN);if(!Number.isSafeInteger(value)||value<1||value>MAX_CONFIGURED_REGISTERED_WORKSPACES){const source=configured===void 0?`${QWEN_SERVE_MAX_WORKSPACES_ENV}=${JSON.stringify(raw)}`:`maxRegisteredWorkspaces option ${String(configured)}`;throw new TypeError(`Invalid ${source}: must be an integer from 1 to ${MAX_CONFIGURED_REGISTERED_WORKSPACES}.`)}return value}__name(resolveMaxRegisteredWorkspaces,"resolveMaxRegisteredWorkspaces");var DuplicateWorkspaceInputError=class extends Error{static{__name(this,"DuplicateWorkspaceInputError")}constructor(workspace){super(`Duplicate --workspace value resolves to ${JSON.stringify(workspace)}. Pass distinct --workspace values.`);this.name="DuplicateWorkspaceInputError"}};var NestedWorkspaceInputError=class extends Error{static{__name(this,"NestedWorkspaceInputError")}constructor(parent,child){super(`Nested --workspace values are not supported yet: ${JSON.stringify(child)} is inside ${JSON.stringify(parent)}. Pass non-nested --workspace values.`);this.name="NestedWorkspaceInputError"}};var MissingWorkspaceInputError=class extends Error{static{__name(this,"MissingWorkspaceInputError")}constructor(){super("--workspace requires a value.");this.name="MissingWorkspaceInputError"}};function normalizeWorkspaceInputs(workspace){if(Array.isArray(workspace)){if(workspace.length===0){throw new MissingWorkspaceInputError}return workspace.map(value=>String(value))}if(workspace===void 0)return[process.cwd()];return[String(workspace)]}__name(normalizeWorkspaceInputs,"normalizeWorkspaceInputs");function isNestedWorkspace(parent,child){return parent!==child&&isWithinRoot(child,parent)}__name(isNestedWorkspace,"isNestedWorkspace");function rejectDuplicateOrNestedWorkspaceInputs(workspaces){if(workspaces.length<=1)return;let canonicalWorkspaces;try{canonicalWorkspaces=workspaces.map(workspace=>canonicalizeWorkspace(workspace))}catch{return}const seen=new Set;for(const workspace of canonicalWorkspaces){if(seen.has(workspace)){throw new DuplicateWorkspaceInputError(workspace)}seen.add(workspace)}for(let i=0;i<canonicalWorkspaces.length;i++){for(let j=i+1;j<canonicalWorkspaces.length;j++){const first=canonicalWorkspaces[i];const second=canonicalWorkspaces[j];if(isNestedWorkspace(first,second)){throw new NestedWorkspaceInputError(first,second)}if(isNestedWorkspace(second,first)){throw new NestedWorkspaceInputError(second,first)}}}}__name(rejectDuplicateOrNestedWorkspaceInputs,"rejectDuplicateOrNestedWorkspaceInputs");function resolveWorkspaceInputs(workspace){const workspaces=normalizeWorkspaceInputs(workspace);rejectDuplicateOrNestedWorkspaceInputs(workspaces);return workspaces}__name(resolveWorkspaceInputs,"resolveWorkspaceInputs");var SCHEMA_VERSION=1;var MAX_SECONDARY_WORKSPACES=MAX_CONFIGURED_REGISTERED_WORKSPACES-1;var MAX_STORE_BYTES=8*1024*1024;var MAX_WORKSPACE_DISPLAY_NAME_LENGTH=256;var LOCK_OPTIONS={realpath:false,stale:1e4,update:2e3,retries:{retries:120,minTimeout:10,maxTimeout:100,factor:1.2,randomize:true}};var WorkspaceDisplayNameValidationError=class extends Error{static{__name(this,"WorkspaceDisplayNameValidationError")}constructor(message){super(message);this.name="WorkspaceDisplayNameValidationError"}};function containsDisplayNameControlCharacter(value){for(const character of value){const codePoint=character.codePointAt(0);if(codePoint<=31||codePoint===127)return true}return false}__name(containsDisplayNameControlCharacter,"containsDisplayNameControlCharacter");function normalizeWorkspaceDisplayName(value){if(typeof value!=="string"){throw new WorkspaceDisplayNameValidationError("Workspace display name must be a string")}const trimmed=value.trim();if(trimmed.length>MAX_WORKSPACE_DISPLAY_NAME_LENGTH){throw new WorkspaceDisplayNameValidationError(`Workspace display name exceeds ${MAX_WORKSPACE_DISPLAY_NAME_LENGTH} characters`)}if(containsDisplayNameControlCharacter(trimmed)){throw new WorkspaceDisplayNameValidationError("Workspace display name contains control characters")}return trimmed.length===0?void 0:trimmed}__name(normalizeWorkspaceDisplayName,"normalizeWorkspaceDisplayName");var WorkspaceRegistrationStoreError=class extends Error{static{__name(this,"WorkspaceRegistrationStoreError")}constructor(message){super(message);this.name="WorkspaceRegistrationStoreError"}};var WorkspaceRegistrationStoreLimitError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreLimitError")}};var WorkspaceRegistrationStoreTooLargeError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreTooLargeError")}};var WorkspaceRegistrationStoreCommittedError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreCommittedError")}};var WorkspaceOrderValidationError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceOrderValidationError")}};function normalizeWorkspaceOrder(value){if(!Array.isArray(value)||value.length>MAX_CONFIGURED_REGISTERED_WORKSPACES){throw new WorkspaceOrderValidationError("Workspace order must be an array of at most 256 paths")}const seen=new Set;return Array.from(value,(entry,index)=>{let cwd;try{cwd=validateWorkspacePath(entry,`workspaceOrder[${index}]`)}catch(err){throw new WorkspaceOrderValidationError(err.message)}const key=normalizedScopePath(cwd);if(seen.has(key)){throw new WorkspaceOrderValidationError("Workspace order contains duplicate paths")}seen.add(key);return cwd})}__name(normalizeWorkspaceOrder,"normalizeWorkspaceOrder");function normalizedScopePath(primaryWorkspace){return os.platform()==="win32"?primaryWorkspace.toLowerCase():primaryWorkspace}__name(normalizedScopePath,"normalizedScopePath");function workspaceRegistrationScopeHash(primaryWorkspace){return createHash("sha256").update(normalizedScopePath(primaryWorkspace)).digest("hex")}__name(workspaceRegistrationScopeHash,"workspaceRegistrationScopeHash");function workspaceRegistrationId(workspace){return createHash("sha256").update(workspace).digest("hex").slice(0,16)}__name(workspaceRegistrationId,"workspaceRegistrationId");function getWorkspaceRegistrationStorePath(primaryWorkspace,qwenHome=getGlobalQwenDirLite()){return path.join(qwenHome,"daemon","workspaces",`${workspaceRegistrationScopeHash(primaryWorkspace)}.json`)}__name(getWorkspaceRegistrationStorePath,"getWorkspaceRegistrationStorePath");function emptySnapshot(primaryWorkspace){return{schemaVersion:SCHEMA_VERSION,primaryWorkspace,workspaces:[]}}__name(emptySnapshot,"emptySnapshot");function validateWorkspacePath(value,label){if(typeof value!=="string"||!path.isAbsolute(value)){throw new WorkspaceRegistrationStoreError(`${label} must be an absolute path`)}if(value.includes("\0")||value.length>MAX_WORKSPACE_PATH_LENGTH){throw new WorkspaceRegistrationStoreError(`${label} is invalid`)}return value}__name(validateWorkspacePath,"validateWorkspacePath");function validateStoredDisplayName(value,label){let displayName;try{displayName=normalizeWorkspaceDisplayName(value)}catch(err){throw new WorkspaceRegistrationStoreError(`${label} is invalid: ${err instanceof Error?err.message:String(err)}`)}if(displayName===void 0){throw new WorkspaceRegistrationStoreError(`${label} must not be empty`)}return displayName}__name(validateStoredDisplayName,"validateStoredDisplayName");function setSnapshotDisplayName(snapshot,registrationId,displayName){if(displayName===void 0){if(!snapshot.displayNames||!Object.hasOwn(snapshot.displayNames,registrationId)){return false}delete snapshot.displayNames[registrationId];if(Object.keys(snapshot.displayNames).length===0){delete snapshot.displayNames}return true}if(snapshot.displayNames?.[registrationId]===displayName)return false;snapshot.displayNames??={};snapshot.displayNames[registrationId]=displayName;return true}__name(setSnapshotDisplayName,"setSnapshotDisplayName");function parseSnapshot(raw,primaryWorkspace){let value;try{value=JSON.parse(raw)}catch{throw new WorkspaceRegistrationStoreError("Workspace registration store contains malformed JSON")}if(typeof value!=="object"||value===null||Array.isArray(value)){throw new WorkspaceRegistrationStoreError("Workspace registration store root must be an object")}const record=value;if(record["schemaVersion"]!==SCHEMA_VERSION){throw new WorkspaceRegistrationStoreError(`Unsupported workspace registration schema ${String(record["schemaVersion"])}`)}const storedPrimary=validateWorkspacePath(record["primaryWorkspace"],"primaryWorkspace");if(normalizedScopePath(storedPrimary)!==normalizedScopePath(primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Workspace registration store primary does not match this daemon")}if(!Array.isArray(record["workspaces"])){throw new WorkspaceRegistrationStoreError("Workspace registration store workspaces must be an array")}if(record["workspaces"].length>MAX_SECONDARY_WORKSPACES){throw new WorkspaceRegistrationStoreError(`Workspace registration store exceeds ${MAX_SECONDARY_WORKSPACES} entries`)}const seen=new Set;const workspaces=record["workspaces"].map((entry,index)=>{const workspace=validateWorkspacePath(entry,`workspaces[${index}]`);const normalizedWorkspace=normalizedScopePath(workspace);if(normalizedWorkspace===normalizedScopePath(primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Primary workspace cannot be stored as a secondary registration")}if(seen.has(normalizedWorkspace)){throw new WorkspaceRegistrationStoreError("Workspace registration store contains duplicate paths")}seen.add(normalizedWorkspace);return workspace});const rawDisplayNames=record["displayNames"];let displayNames;if(rawDisplayNames!==void 0){if(typeof rawDisplayNames!=="object"||rawDisplayNames===null||Array.isArray(rawDisplayNames)){throw new WorkspaceRegistrationStoreError("Workspace registration store displayNames must be an object")}const registrationIds=new Set(workspaces.map(workspaceRegistrationId));for(const[registrationId,value2]of Object.entries(rawDisplayNames)){if(!registrationIds.has(registrationId)){throw new WorkspaceRegistrationStoreError(`Workspace registration store displayNames contains unknown registration id ${JSON.stringify(registrationId)}`)}displayNames??={};displayNames[registrationId]=validateStoredDisplayName(value2,`displayNames[${JSON.stringify(registrationId)}]`)}}return{schemaVersion:SCHEMA_VERSION,primaryWorkspace,workspaces,...displayNames?{displayNames}:{},...record["workspaceOrder"]!==void 0?{workspaceOrder:normalizeWorkspaceOrder(record["workspaceOrder"])}:{}}}__name(parseSnapshot,"parseSnapshot");var updateChains=new Map;async function withInProcessLock(filePath,work){const previous=updateChains.get(filePath)??Promise.resolve();const next=previous.then(work,work);const settled=next.catch(()=>void 0).finally(()=>{if(updateChains.get(filePath)===settled)updateChains.delete(filePath)});updateChains.set(filePath,settled);return next}__name(withInProcessLock,"withInProcessLock");function compromisedLockError(){return new WorkspaceRegistrationStoreError("Workspace registration store lock was compromised")}__name(compromisedLockError,"compromisedLockError");async function acquireFileLock(filePath){await fs.mkdir(path.dirname(filePath),{recursive:true,mode:448});let compromised=false;const release=await import_proper_lockfile.default.lock(filePath,{...LOCK_OPTIONS,onCompromised:__name(()=>{compromised=true},"onCompromised")});return{assertOwned:__name(()=>{if(compromised)throw compromisedLockError()},"assertOwned"),release:__name(async()=>{try{await release()}catch(err){if(!compromised)throw err}if(compromised)throw compromisedLockError()},"release")}}__name(acquireFileLock,"acquireFileLock");var WorkspaceRegistrationStore=class{constructor(primaryWorkspace,qwenHome){this.primaryWorkspace=primaryWorkspace;validateWorkspacePath(primaryWorkspace,"primaryWorkspace");this.filePath=getWorkspaceRegistrationStorePath(primaryWorkspace,qwenHome)}static{__name(this,"WorkspaceRegistrationStore")}filePath;async read(){try{const entry=await fs.lstat(this.filePath);if(entry.isSymbolicLink()||!entry.isFile()){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}}catch(err){if(err.code==="ENOENT"){return emptySnapshot(this.primaryWorkspace)}throw err}let file;try{file=await openNoFollow(this.filePath)}catch(err){if(err.code==="ENOENT"){return emptySnapshot(this.primaryWorkspace)}if(isUnverifiableIdentityError(err)){throw new WorkspaceRegistrationStoreError("Workspace registration store identity could not be verified")}if(err.code==="ELOOP"){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}throw err}try{const stat=await file.stat();if(!stat.isFile()){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}if(stat.size>MAX_STORE_BYTES){throw new WorkspaceRegistrationStoreTooLargeError(`Workspace registration store exceeds ${MAX_STORE_BYTES} bytes`)}let buffer=Buffer.alloc(Math.max(1,Math.min(stat.size+1,MAX_STORE_BYTES+1)));let totalBytesRead=0;for(;;){if(totalBytesRead===buffer.length){if(totalBytesRead>MAX_STORE_BYTES)break;const grown=Buffer.alloc(Math.min(MAX_STORE_BYTES+1,Math.max(buffer.length*2,totalBytesRead+1)));buffer.copy(grown,0,0,totalBytesRead);buffer=grown}const{bytesRead}=await file.read(buffer,totalBytesRead,buffer.length-totalBytesRead,totalBytesRead);if(bytesRead===0)break;totalBytesRead+=bytesRead}if(totalBytesRead>MAX_STORE_BYTES){throw new WorkspaceRegistrationStoreTooLargeError(`Workspace registration store exceeds ${MAX_STORE_BYTES} bytes`)}return parseSnapshot(buffer.toString("utf8",0,totalBytesRead),this.primaryWorkspace)}finally{await file.close()}}async add(workspace,displayName,maxRegisteredWorkspaces=MAX_REGISTERED_WORKSPACES){const maxSecondaries=resolveMaxRegisteredWorkspaces(maxRegisteredWorkspaces,{})-1;validateWorkspacePath(workspace,"workspace");const normalizedDisplayName=displayName===void 0?void 0:normalizeWorkspaceDisplayName(displayName);if(normalizedScopePath(workspace)===normalizedScopePath(this.primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Primary workspace cannot be stored as a secondary registration")}return this.update(snapshot=>{const normalizedWorkspace=normalizedScopePath(workspace);if(snapshot.workspaces.some(stored=>normalizedScopePath(stored)===normalizedWorkspace)){return false}if(snapshot.workspaces.length>=maxSecondaries){throw new WorkspaceRegistrationStoreLimitError(`Workspace registration store limit of ${maxSecondaries} reached`)}snapshot.workspaces.push(workspace);if(normalizedDisplayName!==void 0){snapshot.displayNames??={};snapshot.displayNames[workspaceRegistrationId(workspace)]=normalizedDisplayName}return true})}async removeById(id){return await this.removeByIds([id])>0}async setDisplayNameByIds(ids,displayName){const normalizedDisplayName=displayName===void 0?void 0:normalizeWorkspaceDisplayName(displayName);const requested=new Set(ids);if(requested.size===0)return 0;let matched=0;await this.update(snapshot=>{let changed=false;for(const workspace of snapshot.workspaces){const registrationId=workspaceRegistrationId(workspace);if(!requested.has(registrationId))continue;matched++;changed=setSnapshotDisplayName(snapshot,registrationId,normalizedDisplayName)||changed}return changed});return matched}async removeByIds(ids){const requested=new Set(ids);if(requested.size===0)return 0;let removed=0;await this.update(snapshot=>{const removedIds=new Set;const retained=snapshot.workspaces.filter(workspace=>{const registrationId=workspaceRegistrationId(workspace);if(!requested.has(registrationId))return true;removed++;removedIds.add(registrationId);return false});if(removed===0)return false;snapshot.workspaces.splice(0,snapshot.workspaces.length,...retained);for(const registrationId of removedIds){setSnapshotDisplayName(snapshot,registrationId,void 0)}return true});return removed}async setWorkspaceOrder(cwds){const order=normalizeWorkspaceOrder(cwds);await this.update(snapshot=>{if(JSON.stringify(snapshot.workspaceOrder)===JSON.stringify(order))return false;snapshot.workspaceOrder=order;return true})}async update(mutate){const{atomicWriteFile}=await import("./deferred-core-runtime-BCJU6YQI.js");return withInProcessLock(this.filePath,async()=>{const lock=await acquireFileLock(this.filePath);let committed=false;let changed=false;let workError;try{const snapshot=await this.read();lock.assertOwned();changed=mutate(snapshot);if(changed){const serialized=`${JSON.stringify(snapshot,null,2)}
|
|
3
|
+
import{MAX_WORKSPACE_PATH_LENGTH,canonicalizeWorkspace}from"./chunk-L5UULTGF.js";import{getGlobalQwenDirLite}from"./chunk-ERGT5BD3.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{isUnverifiableIdentityError,openNoFollow}from"./chunk-PSKT6KWO.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{createHash}from"node:crypto";import*as fs from"node:fs/promises";import*as os from"node:os";import*as path from"node:path";init_esbuild_shims();var MAX_REGISTERED_WORKSPACES=256;var MAX_CONFIGURED_REGISTERED_WORKSPACES=256;var QWEN_SERVE_MAX_WORKSPACES_ENV="QWEN_SERVE_MAX_WORKSPACES";function resolveMaxRegisteredWorkspaces(configured,env){const raw=env[QWEN_SERVE_MAX_WORKSPACES_ENV];const value=configured??(raw===void 0?MAX_REGISTERED_WORKSPACES:/^\d+$/.test(raw.trim())?Number(raw.trim()):Number.NaN);if(!Number.isSafeInteger(value)||value<1||value>MAX_CONFIGURED_REGISTERED_WORKSPACES){const source=configured===void 0?`${QWEN_SERVE_MAX_WORKSPACES_ENV}=${JSON.stringify(raw)}`:`maxRegisteredWorkspaces option ${String(configured)}`;throw new TypeError(`Invalid ${source}: must be an integer from 1 to ${MAX_CONFIGURED_REGISTERED_WORKSPACES}.`)}return value}__name(resolveMaxRegisteredWorkspaces,"resolveMaxRegisteredWorkspaces");var DuplicateWorkspaceInputError=class extends Error{static{__name(this,"DuplicateWorkspaceInputError")}constructor(workspace){super(`Duplicate --workspace value resolves to ${JSON.stringify(workspace)}. Pass distinct --workspace values.`);this.name="DuplicateWorkspaceInputError"}};var NestedWorkspaceInputError=class extends Error{static{__name(this,"NestedWorkspaceInputError")}constructor(parent,child){super(`Nested --workspace values are not supported yet: ${JSON.stringify(child)} is inside ${JSON.stringify(parent)}. Pass non-nested --workspace values.`);this.name="NestedWorkspaceInputError"}};var MissingWorkspaceInputError=class extends Error{static{__name(this,"MissingWorkspaceInputError")}constructor(){super("--workspace requires a value.");this.name="MissingWorkspaceInputError"}};function normalizeWorkspaceInputs(workspace){if(Array.isArray(workspace)){if(workspace.length===0){throw new MissingWorkspaceInputError}return workspace.map(value=>String(value))}if(workspace===void 0)return[process.cwd()];return[String(workspace)]}__name(normalizeWorkspaceInputs,"normalizeWorkspaceInputs");function isNestedWorkspace(parent,child){return parent!==child&&isWithinRoot(child,parent)}__name(isNestedWorkspace,"isNestedWorkspace");function rejectDuplicateOrNestedWorkspaceInputs(workspaces){if(workspaces.length<=1)return;let canonicalWorkspaces;try{canonicalWorkspaces=workspaces.map(workspace=>canonicalizeWorkspace(workspace))}catch{return}const seen=new Set;for(const workspace of canonicalWorkspaces){if(seen.has(workspace)){throw new DuplicateWorkspaceInputError(workspace)}seen.add(workspace)}for(let i=0;i<canonicalWorkspaces.length;i++){for(let j=i+1;j<canonicalWorkspaces.length;j++){const first=canonicalWorkspaces[i];const second=canonicalWorkspaces[j];if(isNestedWorkspace(first,second)){throw new NestedWorkspaceInputError(first,second)}if(isNestedWorkspace(second,first)){throw new NestedWorkspaceInputError(second,first)}}}}__name(rejectDuplicateOrNestedWorkspaceInputs,"rejectDuplicateOrNestedWorkspaceInputs");function resolveWorkspaceInputs(workspace){const workspaces=normalizeWorkspaceInputs(workspace);rejectDuplicateOrNestedWorkspaceInputs(workspaces);return workspaces}__name(resolveWorkspaceInputs,"resolveWorkspaceInputs");var SCHEMA_VERSION=1;var MAX_SECONDARY_WORKSPACES=MAX_CONFIGURED_REGISTERED_WORKSPACES-1;var MAX_STORE_BYTES=8*1024*1024;var MAX_WORKSPACE_DISPLAY_NAME_LENGTH=256;var LOCK_OPTIONS={realpath:false,stale:1e4,update:2e3,retries:{retries:120,minTimeout:10,maxTimeout:100,factor:1.2,randomize:true}};var WorkspaceDisplayNameValidationError=class extends Error{static{__name(this,"WorkspaceDisplayNameValidationError")}constructor(message){super(message);this.name="WorkspaceDisplayNameValidationError"}};function containsDisplayNameControlCharacter(value){for(const character of value){const codePoint=character.codePointAt(0);if(codePoint<=31||codePoint===127)return true}return false}__name(containsDisplayNameControlCharacter,"containsDisplayNameControlCharacter");function normalizeWorkspaceDisplayName(value){if(typeof value!=="string"){throw new WorkspaceDisplayNameValidationError("Workspace display name must be a string")}const trimmed=value.trim();if(trimmed.length>MAX_WORKSPACE_DISPLAY_NAME_LENGTH){throw new WorkspaceDisplayNameValidationError(`Workspace display name exceeds ${MAX_WORKSPACE_DISPLAY_NAME_LENGTH} characters`)}if(containsDisplayNameControlCharacter(trimmed)){throw new WorkspaceDisplayNameValidationError("Workspace display name contains control characters")}return trimmed.length===0?void 0:trimmed}__name(normalizeWorkspaceDisplayName,"normalizeWorkspaceDisplayName");var WorkspaceRegistrationStoreError=class extends Error{static{__name(this,"WorkspaceRegistrationStoreError")}constructor(message){super(message);this.name="WorkspaceRegistrationStoreError"}};var WorkspaceRegistrationStoreLimitError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreLimitError")}};var WorkspaceRegistrationStoreTooLargeError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreTooLargeError")}};var WorkspaceRegistrationStoreCommittedError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceRegistrationStoreCommittedError")}};var WorkspaceOrderValidationError=class extends WorkspaceRegistrationStoreError{static{__name(this,"WorkspaceOrderValidationError")}};function normalizeWorkspaceOrder(value){if(!Array.isArray(value)||value.length>MAX_CONFIGURED_REGISTERED_WORKSPACES){throw new WorkspaceOrderValidationError("Workspace order must be an array of at most 256 paths")}const seen=new Set;return Array.from(value,(entry,index)=>{let cwd;try{cwd=validateWorkspacePath(entry,`workspaceOrder[${index}]`)}catch(err){throw new WorkspaceOrderValidationError(err.message)}const key=normalizedScopePath(cwd);if(seen.has(key)){throw new WorkspaceOrderValidationError("Workspace order contains duplicate paths")}seen.add(key);return cwd})}__name(normalizeWorkspaceOrder,"normalizeWorkspaceOrder");function normalizedScopePath(primaryWorkspace){return os.platform()==="win32"?primaryWorkspace.toLowerCase():primaryWorkspace}__name(normalizedScopePath,"normalizedScopePath");function workspaceRegistrationScopeHash(primaryWorkspace){return createHash("sha256").update(normalizedScopePath(primaryWorkspace)).digest("hex")}__name(workspaceRegistrationScopeHash,"workspaceRegistrationScopeHash");function workspaceRegistrationId(workspace){return createHash("sha256").update(workspace).digest("hex").slice(0,16)}__name(workspaceRegistrationId,"workspaceRegistrationId");function getWorkspaceRegistrationStorePath(primaryWorkspace,qwenHome=getGlobalQwenDirLite()){return path.join(qwenHome,"daemon","workspaces",`${workspaceRegistrationScopeHash(primaryWorkspace)}.json`)}__name(getWorkspaceRegistrationStorePath,"getWorkspaceRegistrationStorePath");function emptySnapshot(primaryWorkspace){return{schemaVersion:SCHEMA_VERSION,primaryWorkspace,workspaces:[]}}__name(emptySnapshot,"emptySnapshot");function validateWorkspacePath(value,label){if(typeof value!=="string"||!path.isAbsolute(value)){throw new WorkspaceRegistrationStoreError(`${label} must be an absolute path`)}if(value.includes("\0")||value.length>MAX_WORKSPACE_PATH_LENGTH){throw new WorkspaceRegistrationStoreError(`${label} is invalid`)}return value}__name(validateWorkspacePath,"validateWorkspacePath");function validateStoredDisplayName(value,label){let displayName;try{displayName=normalizeWorkspaceDisplayName(value)}catch(err){throw new WorkspaceRegistrationStoreError(`${label} is invalid: ${err instanceof Error?err.message:String(err)}`)}if(displayName===void 0){throw new WorkspaceRegistrationStoreError(`${label} must not be empty`)}return displayName}__name(validateStoredDisplayName,"validateStoredDisplayName");function setSnapshotDisplayName(snapshot,registrationId,displayName){if(displayName===void 0){if(!snapshot.displayNames||!Object.hasOwn(snapshot.displayNames,registrationId)){return false}delete snapshot.displayNames[registrationId];if(Object.keys(snapshot.displayNames).length===0){delete snapshot.displayNames}return true}if(snapshot.displayNames?.[registrationId]===displayName)return false;snapshot.displayNames??={};snapshot.displayNames[registrationId]=displayName;return true}__name(setSnapshotDisplayName,"setSnapshotDisplayName");function parseSnapshot(raw,primaryWorkspace){let value;try{value=JSON.parse(raw)}catch{throw new WorkspaceRegistrationStoreError("Workspace registration store contains malformed JSON")}if(typeof value!=="object"||value===null||Array.isArray(value)){throw new WorkspaceRegistrationStoreError("Workspace registration store root must be an object")}const record=value;if(record["schemaVersion"]!==SCHEMA_VERSION){throw new WorkspaceRegistrationStoreError(`Unsupported workspace registration schema ${String(record["schemaVersion"])}`)}const storedPrimary=validateWorkspacePath(record["primaryWorkspace"],"primaryWorkspace");if(normalizedScopePath(storedPrimary)!==normalizedScopePath(primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Workspace registration store primary does not match this daemon")}if(!Array.isArray(record["workspaces"])){throw new WorkspaceRegistrationStoreError("Workspace registration store workspaces must be an array")}if(record["workspaces"].length>MAX_SECONDARY_WORKSPACES){throw new WorkspaceRegistrationStoreError(`Workspace registration store exceeds ${MAX_SECONDARY_WORKSPACES} entries`)}const seen=new Set;const workspaces=record["workspaces"].map((entry,index)=>{const workspace=validateWorkspacePath(entry,`workspaces[${index}]`);const normalizedWorkspace=normalizedScopePath(workspace);if(normalizedWorkspace===normalizedScopePath(primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Primary workspace cannot be stored as a secondary registration")}if(seen.has(normalizedWorkspace)){throw new WorkspaceRegistrationStoreError("Workspace registration store contains duplicate paths")}seen.add(normalizedWorkspace);return workspace});const rawDisplayNames=record["displayNames"];let displayNames;if(rawDisplayNames!==void 0){if(typeof rawDisplayNames!=="object"||rawDisplayNames===null||Array.isArray(rawDisplayNames)){throw new WorkspaceRegistrationStoreError("Workspace registration store displayNames must be an object")}const registrationIds=new Set(workspaces.map(workspaceRegistrationId));for(const[registrationId,value2]of Object.entries(rawDisplayNames)){if(!registrationIds.has(registrationId)){throw new WorkspaceRegistrationStoreError(`Workspace registration store displayNames contains unknown registration id ${JSON.stringify(registrationId)}`)}displayNames??={};displayNames[registrationId]=validateStoredDisplayName(value2,`displayNames[${JSON.stringify(registrationId)}]`)}}return{schemaVersion:SCHEMA_VERSION,primaryWorkspace,workspaces,...displayNames?{displayNames}:{},...record["workspaceOrder"]!==void 0?{workspaceOrder:normalizeWorkspaceOrder(record["workspaceOrder"])}:{}}}__name(parseSnapshot,"parseSnapshot");var updateChains=new Map;async function withInProcessLock(filePath,work){const previous=updateChains.get(filePath)??Promise.resolve();const next=previous.then(work,work);const settled=next.catch(()=>void 0).finally(()=>{if(updateChains.get(filePath)===settled)updateChains.delete(filePath)});updateChains.set(filePath,settled);return next}__name(withInProcessLock,"withInProcessLock");function compromisedLockError(){return new WorkspaceRegistrationStoreError("Workspace registration store lock was compromised")}__name(compromisedLockError,"compromisedLockError");async function acquireFileLock(filePath){await fs.mkdir(path.dirname(filePath),{recursive:true,mode:448});let compromised=false;const release=await import_proper_lockfile.default.lock(filePath,{...LOCK_OPTIONS,onCompromised:__name(()=>{compromised=true},"onCompromised")});return{assertOwned:__name(()=>{if(compromised)throw compromisedLockError()},"assertOwned"),release:__name(async()=>{try{await release()}catch(err){if(!compromised)throw err}if(compromised)throw compromisedLockError()},"release")}}__name(acquireFileLock,"acquireFileLock");var WorkspaceRegistrationStore=class{constructor(primaryWorkspace,qwenHome){this.primaryWorkspace=primaryWorkspace;validateWorkspacePath(primaryWorkspace,"primaryWorkspace");this.filePath=getWorkspaceRegistrationStorePath(primaryWorkspace,qwenHome)}static{__name(this,"WorkspaceRegistrationStore")}filePath;async read(){try{const entry=await fs.lstat(this.filePath);if(entry.isSymbolicLink()||!entry.isFile()){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}}catch(err){if(err.code==="ENOENT"){return emptySnapshot(this.primaryWorkspace)}throw err}let file;try{file=await openNoFollow(this.filePath)}catch(err){if(err.code==="ENOENT"){return emptySnapshot(this.primaryWorkspace)}if(isUnverifiableIdentityError(err)){throw new WorkspaceRegistrationStoreError("Workspace registration store identity could not be verified")}if(err.code==="ELOOP"){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}throw err}try{const stat=await file.stat();if(!stat.isFile()){throw new WorkspaceRegistrationStoreError("Workspace registration store must be a regular file")}if(stat.size>MAX_STORE_BYTES){throw new WorkspaceRegistrationStoreTooLargeError(`Workspace registration store exceeds ${MAX_STORE_BYTES} bytes`)}let buffer=Buffer.alloc(Math.max(1,Math.min(stat.size+1,MAX_STORE_BYTES+1)));let totalBytesRead=0;for(;;){if(totalBytesRead===buffer.length){if(totalBytesRead>MAX_STORE_BYTES)break;const grown=Buffer.alloc(Math.min(MAX_STORE_BYTES+1,Math.max(buffer.length*2,totalBytesRead+1)));buffer.copy(grown,0,0,totalBytesRead);buffer=grown}const{bytesRead}=await file.read(buffer,totalBytesRead,buffer.length-totalBytesRead,totalBytesRead);if(bytesRead===0)break;totalBytesRead+=bytesRead}if(totalBytesRead>MAX_STORE_BYTES){throw new WorkspaceRegistrationStoreTooLargeError(`Workspace registration store exceeds ${MAX_STORE_BYTES} bytes`)}return parseSnapshot(buffer.toString("utf8",0,totalBytesRead),this.primaryWorkspace)}finally{await file.close()}}async add(workspace,displayName,maxRegisteredWorkspaces=MAX_REGISTERED_WORKSPACES){const maxSecondaries=resolveMaxRegisteredWorkspaces(maxRegisteredWorkspaces,{})-1;validateWorkspacePath(workspace,"workspace");const normalizedDisplayName=displayName===void 0?void 0:normalizeWorkspaceDisplayName(displayName);if(normalizedScopePath(workspace)===normalizedScopePath(this.primaryWorkspace)){throw new WorkspaceRegistrationStoreError("Primary workspace cannot be stored as a secondary registration")}return this.update(snapshot=>{const normalizedWorkspace=normalizedScopePath(workspace);if(snapshot.workspaces.some(stored=>normalizedScopePath(stored)===normalizedWorkspace)){return false}if(snapshot.workspaces.length>=maxSecondaries){throw new WorkspaceRegistrationStoreLimitError(`Workspace registration store limit of ${maxSecondaries} reached`)}snapshot.workspaces.push(workspace);if(normalizedDisplayName!==void 0){snapshot.displayNames??={};snapshot.displayNames[workspaceRegistrationId(workspace)]=normalizedDisplayName}return true})}async removeById(id){return await this.removeByIds([id])>0}async setDisplayNameByIds(ids,displayName){const normalizedDisplayName=displayName===void 0?void 0:normalizeWorkspaceDisplayName(displayName);const requested=new Set(ids);if(requested.size===0)return 0;let matched=0;await this.update(snapshot=>{let changed=false;for(const workspace of snapshot.workspaces){const registrationId=workspaceRegistrationId(workspace);if(!requested.has(registrationId))continue;matched++;changed=setSnapshotDisplayName(snapshot,registrationId,normalizedDisplayName)||changed}return changed});return matched}async removeByIds(ids){const requested=new Set(ids);if(requested.size===0)return 0;let removed=0;await this.update(snapshot=>{const removedIds=new Set;const retained=snapshot.workspaces.filter(workspace=>{const registrationId=workspaceRegistrationId(workspace);if(!requested.has(registrationId))return true;removed++;removedIds.add(registrationId);return false});if(removed===0)return false;snapshot.workspaces.splice(0,snapshot.workspaces.length,...retained);for(const registrationId of removedIds){setSnapshotDisplayName(snapshot,registrationId,void 0)}return true});return removed}async setWorkspaceOrder(cwds){const order=normalizeWorkspaceOrder(cwds);await this.update(snapshot=>{if(JSON.stringify(snapshot.workspaceOrder)===JSON.stringify(order))return false;snapshot.workspaceOrder=order;return true})}async update(mutate){const{atomicWriteFile}=await import("./deferred-core-runtime-YC5XIWEI.js");return withInProcessLock(this.filePath,async()=>{const lock=await acquireFileLock(this.filePath);let committed=false;let changed=false;let workError;try{const snapshot=await this.read();lock.assertOwned();changed=mutate(snapshot);if(changed){const serialized=`${JSON.stringify(snapshot,null,2)}
|
|
4
4
|
`;if(Buffer.byteLength(serialized,"utf8")>MAX_STORE_BYTES){throw new WorkspaceRegistrationStoreTooLargeError(`Workspace registration store exceeds ${MAX_STORE_BYTES} bytes`)}lock.assertOwned();await atomicWriteFile(this.filePath,serialized,{mode:384,forceMode:true,noFollow:true});committed=true}}catch(err){workError=err}let releaseError;try{await lock.release()}catch(err){releaseError=committed?new WorkspaceRegistrationStoreCommittedError(`Workspace registration update committed but lock release failed: ${err instanceof Error?err.message:String(err)}`):err}if(workError instanceof Error&&releaseError!==void 0&&workError.cause===void 0){workError.cause=releaseError}if(workError!==void 0)throw workError;if(releaseError!==void 0)throw releaseError;return changed})}};export{MAX_REGISTERED_WORKSPACES,resolveMaxRegisteredWorkspaces,resolveWorkspaceInputs,MAX_WORKSPACE_DISPLAY_NAME_LENGTH,WorkspaceDisplayNameValidationError,normalizeWorkspaceDisplayName,WorkspaceRegistrationStoreError,WorkspaceRegistrationStoreLimitError,WorkspaceRegistrationStoreTooLargeError,WorkspaceRegistrationStoreCommittedError,WorkspaceOrderValidationError,normalizeWorkspaceOrder,workspaceRegistrationScopeHash,workspaceRegistrationId,getWorkspaceRegistrationStorePath,WorkspaceRegistrationStore};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{clipToWidth,cpLen,cpSlice,getCachedStringWidth,sanitizeTerminalLine}from"./chunk-64CA3W6G.js";import{normalizeProjectRoot}from"./chunk-JDZ3UHK5.js";import{readProjectEnvFiles}from"./chunk-
|
|
3
|
+
import{clipToWidth,cpLen,cpSlice,getCachedStringWidth,sanitizeTerminalLine}from"./chunk-64CA3W6G.js";import{normalizeProjectRoot}from"./chunk-JDZ3UHK5.js";import{readProjectEnvFiles}from"./chunk-RBA3TP7L.js";import{require_strip_json_comments}from"./chunk-EKRCICRK.js";import{resolveEnvVarsInObject}from"./chunk-HW7ZRPZU.js";import{atomicWriteFile}from"./chunk-2GF3E5MI.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{HookEventName}from"./chunk-4WFJ5OPA.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as crypto from"node:crypto";import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var HOOK_APPROVALS_FILENAME="hookApprovals.json";function getHookApprovalsPath(){if(process.env["QWEN_CODE_HOOK_APPROVALS_PATH"]){return process.env["QWEN_CODE_HOOK_APPROVALS_PATH"]}return path.join(Storage.getGlobalQwenDir(),HOOK_APPROVALS_FILENAME)}__name(getHookApprovalsPath,"getHookApprovalsPath");function getProjectHooksRoot(settings){return path.dirname(path.dirname(settings.workspace.path))}__name(getProjectHooksRoot,"getProjectHooksRoot");function getProjectHooksForApproval(settings){const resolved=settings.getProjectHooks();if(!isRecord(resolved)||summarizeProjectHooks(resolved).length===0){return void 0}const hooks=settings.workspace.originalSettings.hooks;if(!isRecord(hooks))return void 0;const root=getProjectHooksRoot(settings);return{root,hooks,resolved,env:{files:readProjectEnvFiles(settings.merged,root),settings:settings.workspace.originalSettings.env??null}}}__name(getProjectHooksForApproval,"getProjectHooksForApproval");function getProjectHooksForApprovalFromRawWorkspace(settings){const hooks=settings.workspace.originalSettings.hooks;if(!isRecord(hooks))return void 0;const resolved=resolveEnvVarsInObject(hooks);if(summarizeProjectHooks(resolved,hooks).length===0)return void 0;const root=getProjectHooksRoot(settings);return{root,hooks,resolved,env:{files:readProjectEnvFiles(settings.merged,root,true),settings:settings.workspace.originalSettings.env??null}}}__name(getProjectHooksForApprovalFromRawWorkspace,"getProjectHooksForApprovalFromRawWorkspace");function getSeparatedHookSettings(settings){const projectHooks=structuredClone(settings.getProjectHooks());const projectHooksApproval=getProjectHooksForApproval(settings);return{systemHooks:settings.getSystemHooks(),userHooks:settings.getUserHooks(),projectHooks,projectHooksDisplayOnly:structuredClone(settings.workspace?.originalSettings?.hooks),...projectHooksApproval?{projectHooksApproval}:{}}}__name(getSeparatedHookSettings,"getSeparatedHookSettings");function hashProjectHooks(approval){const stable=JSON.stringify({hooks:approval.hooks,env:approval.env},(_key,value)=>{if(value&&typeof value==="object"&&!Array.isArray(value)){const obj=value;const sorted=Object.create(null);for(const k of Object.keys(obj).sort()){sorted[k]=obj[k]}return sorted}return value});return crypto.createHash("sha256").update(stable).digest("hex")}__name(hashProjectHooks,"hashProjectHooks");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function displayText(value,max=200){const text=sanitizeTerminalLine(String(value??"")).replace(new RegExp("\\p{Cf}","gu"),"");const length=cpLen(text);return length>max?`${cpSlice(text,0,max)}\u2026 [${length} chars, full value in .qwen/settings.json]`:text}__name(displayText,"displayText");function envList(value){if(!isRecord(value))return keyList(value);return Object.entries(value).map(([k,v])=>`${displayText(k)}=${displayText(v,80)}`).join(", ")}__name(envList,"envList");function keyList(value){if(Array.isArray(value))return value.map(v=>displayText(v)).join(", ");if(isRecord(value))return Object.keys(value).map(k=>displayText(k)).join(", ");return void 0}__name(keyList,"keyList");function describeHook(hook,raw,matcher){const details=[];const add=__name((label,value)=>{if(value)details.push(`${label}: ${value}`)},"add");let head;switch(hook["type"]){case"command":head=displayText(raw["command"]);if(typeof raw["command"]==="string"&&/\$\{?\w/.test(raw["command"])){details.push("resolves ${VAR} from the environment (project .env/settings.env or shell)")}add("env",envList(raw["env"]));if(raw["shell"])add("shell",displayText(raw["shell"]));if(hook["async"]===true)details.push("async");break;case"http":head=`http ${displayText(raw["url"])}`;add("headers",keyList(raw["headers"]));add("allowedEnvVars",keyList(raw["allowedEnvVars"]));break;default:head=`prompt "${displayText(raw["prompt"])}"`;if(raw["model"])add("model",displayText(raw["model"],80))}if(raw["type"]!==hook["type"])add("type",displayText(raw["type"]));if(matcher)add("matcher",displayText(matcher,80));return details.length>0?`${head} [${details.join("; ")}]`:head}__name(describeHook,"describeHook");var HOOK_EVENTS=new Set(Object.values(HookEventName));var REQUIRED_FIELD={command:"command",http:"url",prompt:"prompt"};function isRunnableHook(hook){if(!isRecord(hook)||typeof hook["type"]!=="string")return false;const field=REQUIRED_FIELD[hook["type"]];return field!==void 0&&Boolean(hook[field])}__name(isRunnableHook,"isRunnableHook");function entry(value,key){if(Array.isArray(value)&&typeof key==="number")return value[key];return isRecord(value)?value[key]:void 0}__name(entry,"entry");function summarizeProjectHooks(resolved,raw=resolved){const lines=[];for(const[event,definitions]of Object.entries(resolved)){if(!HOOK_EVENTS.has(event)||!Array.isArray(definitions))continue;definitions.forEach((definition,i)=>{if(!isRecord(definition)||!Array.isArray(definition["hooks"]))return;const rawDefinition=entry(entry(raw,event),i);definition["hooks"].forEach((hook,j)=>{if(!isRunnableHook(hook))return;const rawHook=entry(entry(rawDefinition,"hooks"),j);const rawMatcher=entry(rawDefinition,"matcher");lines.push(`${displayText(event,24)} ${describeHook(hook,isRecord(rawHook)?rawHook:hook,rawMatcher??definition["matcher"])}`)})})}return lines}__name(summarizeProjectHooks,"summarizeProjectHooks");function fitHookLines(lines,maxRows){const rows=Math.max(1,Math.floor(maxRows));if(lines.length<=rows)return lines;const shown=Math.max(0,rows-1);return[...lines.slice(0,shown),`\u2026 and ${lines.length-shown} more (see .qwen/settings.json)`]}__name(fitHookLines,"fitHookLines");function fitHookLine(line,width){if(getCachedStringWidth(line)<=width)return line;const total=cpLen(line);const marker=`\u2026 [+${total} chars]`;const kept=clipToWidth(line,width-getCachedStringWidth(marker));return`${kept}\u2026 [+${total-cpLen(kept)} chars]`}__name(fitHookLine,"fitHookLine");var LoadedHookApprovals=class{constructor(file,errors){this.file=file;this.errors=errors}static{__name(this,"LoadedHookApprovals")}getState(approval){const record=this.file.config[normalizeProjectRoot(approval.root)];if(!isRecord(record)||record["hash"]!==hashProjectHooks(approval)){return"pending"}const status=record["status"];return status==="approved"||status==="rejected"?status:"pending"}async setState(approval,status){const{config,errors}=readHookApprovals(this.file.path);if(errors.length>0){throw new Error(`${errors[0].message} (${this.file.path})`)}Object.defineProperty(config,normalizeProjectRoot(approval.root),{value:{hash:hashProjectHooks(approval),status},enumerable:true,configurable:true,writable:true});fs.mkdirSync(path.dirname(this.file.path),{recursive:true});await atomicWriteFile(this.file.path,JSON.stringify(config,null,2),{mode:384,forceMode:true});this.file.config=config}};var warnedErrors=new Set;function readHookApprovals(filePath){const errors=[];let config=Object.create(null);try{if(fs.existsSync(filePath)){const parsed=JSON.parse((0,import_strip_json_comments.default)(fs.readFileSync(filePath,"utf-8")));if(isRecord(parsed)){config=Object.assign(Object.create(null),parsed)}else{errors.push({message:"Hook approvals file is not a valid JSON object.",path:filePath})}}}catch(error){errors.push({message:getErrorMessage(error),path:filePath})}return{config,errors}}__name(readHookApprovals,"readHookApprovals");function loadHookApprovals(){const filePath=getHookApprovalsPath();const{config,errors}=readHookApprovals(filePath);for(const error of errors){if(warnedErrors.has(error.message))continue;warnedErrors.add(error.message);writeStderrLine(`Warning: hook approvals file error: ${error.message}`)}return new LoadedHookApprovals({path:filePath,config},errors)}__name(loadHookApprovals,"loadHookApprovals");function getProjectHooksApprovalState(approval){return approval?loadHookApprovals().getState(approval):void 0}__name(getProjectHooksApprovalState,"getProjectHooksApprovalState");function applyProjectHooksApproval(config,approval){const state=getProjectHooksApprovalState(approval);const trusted=config.isExplicitlyTrustedFolder?.()===true;config.setProjectHooksPendingApproval(state!==void 0&&state!=="approved"&&!(trusted&&state!=="rejected"),state==="rejected");return state}__name(applyProjectHooksApproval,"applyProjectHooksApproval");function getProjectHooksHeadlessWarning(state){return state==="rejected"?`Project hooks in .qwen/settings.json were not loaded: they were rejected for this folder and are not asked about again until they change (decisions are kept in ${getHookApprovalsPath()}).`:"Project hooks in .qwen/settings.json were not loaded: they are not approved for this folder. Run qwen interactively here to review them."}__name(getProjectHooksHeadlessWarning,"getProjectHooksHeadlessWarning");export{getProjectHooksForApproval,getProjectHooksForApprovalFromRawWorkspace,getSeparatedHookSettings,hashProjectHooks,summarizeProjectHooks,fitHookLines,fitHookLine,loadHookApprovals,getProjectHooksApprovalState,applyProjectHooksApproval,getProjectHooksHeadlessWarning};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{extensionToOutputString,getExtensionManager}from"./chunk-
|
|
3
|
+
import{extensionToOutputString,getExtensionManager}from"./chunk-SCHCTQCG.js";import{getErrorMessage}from"./chunk-4KIFAVR2.js";import{loadSettings}from"./chunk-23543L6E.js";import{initializeI18n,resolveLanguageSetting,t}from"./chunk-FK5L2WVV.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function handleList(){try{const settings=loadSettings();await initializeI18n(resolveLanguageSetting(settings.merged.general?.language));const extensionManager=await getExtensionManager();const extensions=extensionManager.getLoadedExtensions();if(!extensions||extensions.length===0){writeStdoutLine(t("No extensions installed."));return}writeStdoutLine(extensions.map((extension,_)=>extensionToOutputString(extension,extensionManager,process.cwd())).join("\n\n"))}catch(error){writeStderrLine(getErrorMessage(error));process.exit(1)}}__name(handleList,"handleList");var listCommand={command:"list",describe:t("Lists installed extensions."),builder:__name(yargs=>yargs,"builder"),handler:__name(async()=>{await handleList()},"handler")};export{handleList,listCommand};
|
|
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{cancelTask,checkReadiness,cleanTask,collectTask,listTasks,retryTask,runPlan}from"./chunk-TJT2PKMI.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{loadSettings}from"./chunk-
|
|
3
|
+
import{cancelTask,checkReadiness,cleanTask,collectTask,listTasks,retryTask,runPlan}from"./chunk-TJT2PKMI.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{loadSettings}from"./chunk-23543L6E.js";import{collectProviderModelsForProtocol,getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-56PVVXUG.js";import{normalizeProxyUrl}from"./chunk-PFKTTUGS.js";import{isTlsVerificationDisabled}from"./chunk-E5XJBLSO.js";import{ignoreBrokenPipe,writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();async function resolveProxy(cliProxy,settingsProxy){const proxyUrl=resolveProxyUrl(cliProxy,settingsProxy);if(proxyUrl){const{EnvHttpProxyAgent,setGlobalDispatcher}=await loadUndici();setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}))}return proxyUrl}__name(resolveProxy,"resolveProxy");function resolveProxyUrl(cliProxy,settingsProxy){return normalizeProxyUrl(cliProxy||settingsProxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"])}__name(resolveProxyUrl,"resolveProxyUrl");var DEFAULT_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1";function resolveEndpoint(env=process.env,options={}){let settings=options.settings??loadSettings().merged;const batch=settings.batch;if(batch?.model||batch?.authType||batch?.baseUrl){if(!batch.model?.trim()){throw new Error("Set batch.model to a modelProviders model ID.")}if(batch.authType&&batch.authType!=="openai"){throw new Error('batch.authType must be "openai" for DashScope Batch.')}const matches=collectProviderModelsForProtocol(settings.modelProviders,settings.providerProtocol,"openai").filter(provider2=>provider2.id===batch.model&&(!batch.baseUrl||provider2.baseUrl===batch.baseUrl));if(matches.length!==1){throw new Error("batch.model must match exactly one chat-completions modelProviders entry; use batch.baseUrl to disambiguate duplicate IDs.")}const provider=matches[0];if(!provider.baseUrl||!provider.envKey||!env[provider.envKey]){throw new Error("The Batch provider needs baseUrl and an envKey with a non-empty value in settings.env or the environment.")}settings={...settings,model:{name:provider.id,baseUrl:provider.baseUrl},modelProviders:{openai:[provider]},security:{auth:{selectedType:"openai"}}};env={[provider.envKey]:env[provider.envKey]}}const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);if(selectedAuthType!=="openai"){throw new Error(`qwen batch needs an API key (auth type "openai") for a DashScope endpoint; current auth type is "${selectedAuthType??"none"}".`)}const{apiKey,baseUrl,model,warnings,authType,generationConfig}=resolveCliGenerationConfig({argv:{},settings,selectedAuthType,env});if(authType!=="openai"){throw new Error(`qwen batch needs a model on the OpenAI-compatible chat-completions wire; "${model||"the configured model"}" resolves to auth type "${authType??"none"}".`)}if(!apiKey){throw new Error("No API key found: set OPENAI_API_KEY or security.auth.apiKey.")}const warn=options.warn??(message=>writeStderrLine(`warning: ${message}`));for(const warning of warnings??[]){warn(warning)}return{apiKey,baseUrl:(baseUrl||DEFAULT_BASE_URL).replace(/\/+$/,""),model,generationConfig}}__name(resolveEndpoint,"resolveEndpoint");async function prepareEndpoint(env=process.env,cliOptions={}){if(cliOptions.insecure)process.env["QWEN_TLS_INSECURE"]="1";if(isTlsVerificationDisabled()&&process.env["NODE_TLS_REJECT_UNAUTHORIZED"]!=="0"){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0";writeStderrLine("WARNING: TLS certificate verification is disabled (--insecure / QWEN_TLS_INSECURE); connections made by this command are vulnerable to man-in-the-middle attacks.")}await resolveProxy(cliOptions.proxy,loadSettings().merged.proxy);return resolveEndpoint(env)}__name(prepareEndpoint,"prepareEndpoint");var cliOptionsOf=__name(argv=>({proxy:argv["proxy"],insecure:argv["insecure"]}),"cliOptionsOf");async function run(fn){try{await fn()}catch(error){writeStderrLine(error instanceof Error?error.message:String(error));process.exitCode=1}await Promise.all([process.stdout,process.stderr].map(stream=>new Promise(resolve=>stream.write("",()=>resolve()))))}__name(run,"run");var LOCK_WAIT_MS=15e3;var workflowDeps=__name(ep=>({ep,cwd:process.cwd(),env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS}),"workflowDeps");var runWorkflowCommand={command:"run <plan>",describe:"Run an agent-prepared batch plan: assemble requests, submit, record the task",builder:__name(yargs=>yargs.positional("plan",{describe:"Plan JSON (usually written by the /batch-api skill): shared rules + source/target items",type:"string",demandOption:true}).option("dry-run",{describe:"Assemble and show items, frozen settings and the estimate without uploading; prints a snapshot digest",type:"boolean",default:false}).option("expect",{describe:"Submit only if the batch still matches this snapshot digest from --dry-run",type:"string"}).check(argv=>argv["dry-run"]&&argv["expect"]!==void 0?"--dry-run and --expect cannot be combined":true),"builder"),handler:__name(argv=>run(async()=>{await runPlan(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["plan"],{dryRun:argv["dry-run"],expect:argv["expect"]})}),"handler")};var collectWorkflowCommand={command:"collect <task-id>",describe:"Collect a workflow task: reconcile, download, validate, and deliver results",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id printed by `qwen batch run`",type:"string",demandOption:true}).option("wait",{describe:"Poll (over HTTP, holding no lock) until the batch settles, then collect",type:"boolean",default:false}).option("timeout",{describe:"Seconds to wait with --wait before giving up (default: none)",type:"number"}).check(argv=>argv["timeout"]===void 0||Number.isFinite(argv["timeout"])&&argv["timeout"]>0?true:"--timeout must be a positive number of seconds"),"builder"),handler:__name(argv=>run(async()=>{await collectTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{wait:argv["wait"],timeoutSeconds:argv["timeout"]})}),"handler")};var retryWorkflowCommand={command:"retry <task-id>",describe:"Resubmit only the failed items of a workflow task",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("max-output-tokens",{describe:"Output limit for the new attempt; required to resend items that were truncated",type:"number"}).check(argv=>argv["max-output-tokens"]===void 0||Number.isInteger(argv["max-output-tokens"])&&argv["max-output-tokens"]>0?true:"--max-output-tokens must be a positive integer"),"builder"),handler:__name(argv=>run(async()=>{await retryTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{maxOutputTokens:argv["max-output-tokens"]})}),"handler")};var cleanWorkflowCommand={command:"clean <task-id>",describe:"Delete a workflow task's local record (cancels nothing; refuses while a batch may be running)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("force",{describe:"Delete even if a batch may still be running or uncollected (it is not cancelled)",type:"boolean",default:false}),"builder"),handler:__name(argv=>run(async()=>{await cleanTask({env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS},argv["task-id"],{force:argv["force"]})}),"handler")};var checkWorkflowCommand={command:"check",describe:"Verify credentials and the Batch route, and show the settings a run would freeze (no billed request)",builder:__name(yargs=>yargs,"builder"),handler:__name(argv=>run(async()=>{await checkReadiness(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))))}),"handler")};var cancelWorkflowCommand={command:"cancel <task-id>",describe:"Cancel a workflow task's active batch (already-completed requests are still billed)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}),"builder"),handler:__name(argv=>run(async()=>{await cancelTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"])}),"handler")};var listWorkflowCommand={command:"list",describe:"List all recorded workflow tasks with their project",builder:__name(yargs=>yargs,"builder"),handler:__name(()=>run(async()=>{ignoreBrokenPipe();await listTasks({env:process.env,out:writeStdoutLine,err:writeStderrLine})}),"handler")};var batchCommand={command:"batch",describe:"Run many independent requests through the DashScope Batch API",builder:__name(yargs=>yargs.command(runWorkflowCommand).command(collectWorkflowCommand).command(retryWorkflowCommand).command(cancelWorkflowCommand).command(listWorkflowCommand).command(checkWorkflowCommand).command(cleanWorkflowCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{resolveProxy,resolveProxyUrl,resolveEndpoint,prepareEndpoint,listWorkflowCommand,batchCommand};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|