@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{memoryImportReservation,validateMemoryImportBatchProposal}from"./chunk-NM5TUAPJ.js";import{MEMORY_IMPORT_BUDGET,MemoryImportRequestError,digest,packMemoryImportSections,previewSource}from"./chunk-BCY6VYWQ.js";import{rebuildAutoMemoryIndexAtRoot,tokenizeMemoryRecallTerms,tokenizeMemoryRecallText}from"./chunk-3SQ76U4F.js";import{parseAutoMemoryTopicDocument,resolveTrustedMemoryFile,scanAutoMemorySnapshot}from"./chunk-6RGS6DOB.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{getImportedProjectMemoryRoot,getMemoryRootTrustedAnchor,getUserAutoMemoryRoot}from"./chunk-CQGP2BAW.js";import{Storage}from"./chunk-5VB4YX3Z.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*as fs from"node:fs/promises";import{constants}from"node:fs";import{randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";var MemoryImportNotFoundError=class extends Error{static{__name(this,"MemoryImportNotFoundError")}code="ENOENT"};var ImportBudgetError=class extends Error{static{__name(this,"ImportBudgetError")}};var ImportContextError=class extends Error{static{__name(this,"ImportContextError")}};var heldLocks=new AsyncLocalStorage;var exists=__name(async file=>fs.lstat(file).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error}),"exists");async function privateDirectory(directory,anchor){const relative=path.relative(anchor,directory);if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import path escapes runtime.");let current=anchor;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);await fs.mkdir(current,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Import runtime directory must not be a symlink.")}}__name(privateDirectory,"privateDirectory");async function readJson(file){const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>16*1024*1024)throw new Error("Invalid import state file.");const buffer=Buffer.alloc(stat.size+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>stat.size)throw new Error("Import state exceeds the supported limit.");return JSON.parse(buffer.subarray(0,bytesRead).toString("utf8"))}finally{await handle.close()}}__name(readJson,"readJson");async function writeJson(file,value){heldLocks.getStore()?.throwIfAborted();const tmp=`${file}.${randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value),{mode:384,flag:"wx"});try{heldLocks.getStore()?.throwIfAborted();await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}}__name(writeJson,"writeJson");async function abortable(signal,work){signal.throwIfAborted();let abort;const cancelled=new Promise((_resolve,reject)=>{abort=__name(()=>reject(new Error("Import cancelled.")),"abort");signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work(),cancelled])}finally{signal.removeEventListener("abort",abort)}}__name(abortable,"abortable");function publicTask(task){const{requestDigest:_requestDigest,...result}=task;return structuredClone({...result,usage:task.usage??{modelCalls:0,reservedTokens:0},budget:task.budget??{maxCalls:0,maxReservedTokens:0},result:{sourceSections:task.items.length,newDocuments:task.items.filter(item=>item.status==="added").reduce((n,item)=>n+(item.refs?.length??0),0),duplicateSections:task.items.filter(item=>item.status==="duplicate").length,conflictSections:task.items.filter(item=>item.status==="conflict").length,failedSections:task.items.filter(item=>item.status==="failed").length}})}__name(publicTask,"publicTask");function selectImportContext(existing,sources){const queries=sources.map(source=>({text:source.normalize("NFKC").toLowerCase(),terms:tokenizeMemoryRecallTerms(source)}));const index=existing.map(item=>{const parsed=parseAutoMemoryTopicDocument("existing.md",item.content);if(!parsed)throw new ImportContextError("Existing memory has no bounded metadata index. Repair its native metadata before importing.");const metadata=JSON.stringify({name:parsed.title,description:parsed.description,type:parsed.type,category:parsed.category,keywords:parsed.keywords,usage_scenarios:parsed.usageScenarios});const words=tokenizeMemoryRecallText([parsed.title,...parsed.keywords].join(" "));const anchors=[parsed.title,parsed.description].map(text=>text.normalize("NFKC").toLowerCase().trim()).filter(text=>tokenizeMemoryRecallText(text).length>=2);const body=parsed.body.normalize("NFKC").toLowerCase().trim();const relevant=queries.some(({text,terms})=>{if(anchors.some(anchor=>text.includes(anchor))||body.length>0&&text.includes(body))return true;const shared=words.filter(word=>terms.has(word));return shared.length>=2&&shared.length>=words.length/2});return{ref:item.ref,content:relevant?item.content:metadata,indexOnly:!relevant}});const context=[];let bytes=2;for(const entry of[...index.filter(item=>!item.indexOnly),...index.filter(item=>item.indexOnly)]){const size=Buffer.byteLength(JSON.stringify(entry))+(context.length?1:0);if(bytes+size>MEMORY_IMPORT_BUDGET.contextBytes){if(!entry.indexOnly)throw new ImportContextError("Relevant existing evidence exceeds the 32 KiB import context budget. Select a narrower source group or consolidate existing memory before retrying. No model call was made.");continue}bytes+=size;context.push(entry)}return context}__name(selectImportContext,"selectImportContext");function respectsImportScope(proposal,scope){return scope!=="user"||proposal.documents.every(content=>{const type=parseAutoMemoryTopicDocument("import.md",content)?.type;return type==="user"||type==="feedback"})}__name(respectsImportScope,"respectsImportScope");var MemoryImportService=class{constructor(options){this.options=options;this.owner=digest(path.resolve(options.projectRoot))}static{__name(this,"MemoryImportService")}base=Storage.getRuntimeBaseDir();state=path.join(this.base,"memory-import");owner;workers=new Map;controllers=new Map;async readState(file){const relative=path.relative(this.base,path.dirname(file));if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import state escapes runtime.");let current=this.base;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Invalid import state directory.")}return readJson(file)}taskDir(id){if(!/^[a-f0-9]{64}$/.test(id))throw new MemoryImportRequestError("Invalid import batch ID.");return path.join(this.state,"batches",this.owner,id)}async assertRuntimeOutsideGit(){let current=path.resolve(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a runtime directory outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}await fs.mkdir(this.base,{recursive:true,mode:448});current=await fs.realpath(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a private runtime outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}}async prepare(){this.options.assertActive();await this.assertRuntimeOutsideGit();await privateDirectory(path.join(this.state,"batches",this.owner),this.base)}async locked(directory,run,signal){await privateDirectory(directory,this.base);const ownership=new AbortController;const parent=heldLocks.getStore();const held=parent?AbortSignal.any([parent,ownership.signal]):ownership.signal;const work=signal?AbortSignal.any([signal,held]):held;let release;while(!release){work.throwIfAborted();this.options.assertActive();try{release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,update:1e4,retries:0,onCompromised:__name(()=>{ownership.abort(new Error("Import lock lost."))},"onCompromised")})}catch(error){if(error.code!=="ELOCKED")throw error;await new Promise(resolve=>setTimeout(resolve,250))}}try{work.throwIfAborted();const result=await heldLocks.run(held,()=>run(work));held.throwIfAborted();return result}finally{try{if(!ownership.signal.aborted)await release()}finally{ownership.abort(new Error("Import lock released."))}}}async submit(input,selections,key){this.options.assertActive();const preview=previewSource(input);if(typeof key!=="string"||!/^[\w-]{1,128}$/.test(key)||!Array.isArray(selections)||!selections.length||selections.length>2048)throw new MemoryImportRequestError("Provide an idempotency key and explicit non-empty selection.");const seen=new Set;const selected=selections.map(value=>{if(!value||typeof value!=="object")throw new MemoryImportRequestError("Invalid selection.");const selection=value;const section=preview.sections.find(item=>item.id===selection.id&&item.selectable);if(!section||seen.has(selection.id)||!["project","user"].includes(selection.scope))throw new MemoryImportRequestError("Invalid, duplicate or unavailable section selection.");seen.add(selection.id);return{...section,scope:selection.scope}}).sort((a,b)=>a.id.localeCompare(b.id));const retained=JSON.stringify({sections:selected});if(Buffer.byteLength(retained)>16*1024*1024)throw new MemoryImportRequestError("Selected contextual source exceeds the retained snapshot limit.");const requestDigest=digest(JSON.stringify(selected));const id=digest(`${this.owner}\0${key}`);await this.prepare();const dir=this.taskDir(id);return this.locked(path.join(this.state,"admission",this.owner),async()=>{this.options.assertActive();if(await exists(path.join(dir,"task.json"))){const task2=await this.readState(path.join(dir,"task.json"));if(task2.requestDigest!==requestDigest)throw new MemoryImportRequestError("Idempotency key was already used with a different selection.");this.kick(id);return publicTask(task2)}await privateDirectory(dir,this.base);await writeJson(path.join(dir,"source.json"),{sections:selected});const now=new Date().toISOString();const task={version:1,kind:"task",id,status:"queued",createdAt:now,updatedAt:now,requestDigest,usage:{modelCalls:0,reservedTokens:0},budget:{maxCalls:MEMORY_IMPORT_BUDGET.maxCalls,maxReservedTokens:MEMORY_IMPORT_BUDGET.maxReservedTokens},items:selected.map(section=>({id:section.id,scope:section.scope,status:"pending"}))};await writeJson(path.join(dir,"task.json"),task);this.kick(id);return publicTask(task)})}kick(id){if(this.workers.has(id))return;const worker=heldLocks.exit(()=>this.run(id)).catch(()=>{}).finally(()=>{this.workers.delete(id);this.controllers.delete(id)});this.workers.set(id,worker)}async recover(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return;await this.assertRuntimeOutsideGit();await privateDirectory(root,this.base);for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(()=>void 0);if(task&&(task.status==="running"||task.status==="queued"))this.kick(id)}}async list(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return[];await privateDirectory(root,this.base);const result=[];for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.get(id).catch(()=>void 0);if(task)result.push(task)}return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt))}async get(id){this.options.assertActive();const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(cause=>{if(cause.code==="ENOENT")throw new MemoryImportNotFoundError("Import batch not found.",{cause});throw cause});if(task.status!=="completed"&&await exists(path.join(this.taskDir(id),"cancel.json")))task.status="cancelled";return publicTask(task)}async source(id,sectionId){await this.get(id);const source=await this.readState(path.join(this.taskDir(id),"source.json"));const section=source.sections.find(item=>item.id===sectionId);if(!section)throw new MemoryImportRequestError("Source section not found in this batch.");return section}async cancel(id){this.options.assertActive();this.controllers.get(id)?.abort();const task=await this.get(id);if(task.status==="completed")return task;await writeJson(path.join(this.taskDir(id),"cancel.json"),{cancelled:true});this.controllers.get(id)?.abort();await this.workers.get(id);return this.get(id)}async retry(id){await this.get(id);await this.prepare();await this.workers.get(id);const dir=this.taskDir(id);const result=await this.locked(dir,async()=>{const task=await this.readState(path.join(dir,"task.json"));if(task.status==="completed")return publicTask(task);await fs.rm(path.join(dir,"cancel.json"),{force:true});for(const item of task.items)if(item.status==="failed"){item.status="pending";delete item.reason}task.status="queued";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task);return publicTask(task)});this.kick(id);return result}async idle(id){await this.workers.get(id);return this.get(id)}async run(id){const dir=this.taskDir(id);const controller=new AbortController;this.controllers.set(id,controller);await this.locked(dir,async signal=>{const task=await this.readState(path.join(dir,"task.json"));if(!["queued","running"].includes(task.status))return;const source=await this.readState(path.join(dir,"source.json"));if(!task.usage){task.usage={modelCalls:0,reservedTokens:0};task.budget={maxCalls:0,maxReservedTokens:0}}task.budget??={maxCalls:0,maxReservedTokens:0};task.status="running";await writeJson(path.join(dir,"task.json"),task);for(const section of packMemoryImportSections(source.sections).flat()){const item=task.items.find(item2=>item2.id===section.id);if(item.status!=="pending")continue;if(await exists(path.join(dir,"cancel.json")))controller.abort();if(controller.signal.aborted)break;try{this.options.assertActive();Object.assign(item,await this.importSection(section,id,signal,(before,ledger,proposalSignal)=>this.prepareProposal(section,source,task,before,ledger,proposalSignal),async()=>{if(await exists(path.join(dir,"cancel.json")))controller.abort();controller.signal.throwIfAborted();this.options.assertActive()}))}catch(error){if(controller.signal.aborted)break;item.status="failed";item.reason=error instanceof ImportBudgetError||error instanceof ImportContextError?error.message:"Import could not finish. Existing memories were preserved; retry after resolving runtime, model or storage availability."}task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)}task.status=controller.signal.aborted?"cancelled":task.items.some(item=>item.status==="failed")?"partial":"completed";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)},controller.signal)}async prepareProposal(section,source,task,before,ledger,signal){const dir=this.taskDir(task.id);const journalFile=path.join(dir,"proposals.json");const journals=await exists(journalFile)?await this.readState(journalFile):[];let journal=journals.find(entry=>entry.scope===section.scope&&entry.sections.some(item=>item.id===section.id));if(journal&&!respectsImportScope(journal.proposal.items.find(item=>item.id===section.id),section.scope)){journal.sections=journal.sections.filter(item=>item.id!==section.id);journal.proposal.items=journal.proposal.items.filter(item=>item.id!==section.id);if(!journal.sections.length)journals.splice(journals.indexOf(journal),1);await writeJson(journalFile,journals);journal=void 0}if(!journal){const eligible=source.sections.filter(candidate=>candidate.scope===section.scope&&candidate.groupId===section.groupId&&task.items.some(item=>item.id===candidate.id&&item.status==="pending")&&!ledger[candidate.id]&&!journals.some(entry=>entry.sections.some(item=>item.id===candidate.id)));const batch=packMemoryImportSections(eligible).find(items=>items.some(item=>item.id===section.id));if(!batch)throw new Error("Source batch is unavailable.");const input={scope:section.scope,sources:batch.map(({id,content})=>({id,content})),existing:selectImportContext(before.existing,batch.map(item=>item.content))};const reserved=memoryImportReservation(input);if(task.usage.modelCalls>=Math.min(task.budget.maxCalls,MEMORY_IMPORT_BUDGET.maxCalls)||task.usage.reservedTokens+reserved>Math.min(task.budget.maxReservedTokens,MEMORY_IMPORT_BUDGET.maxReservedTokens))throw new ImportBudgetError("Import budget exhausted. Retry preserves this budget; split remaining sources into an explicitly confirmed new task.");signal.throwIfAborted();task.usage.modelCalls++;task.usage.reservedTokens+=reserved;await writeJson(path.join(dir,"task.json"),task);let proposal;try{proposal=validateMemoryImportBatchProposal(await abortable(signal,()=>this.options.propose(input,signal)),batch.map(item=>item.id));if(proposal.items.some(item=>!respectsImportScope(item,section.scope)))throw new ImportContextError("Model returned project knowledge for user memory. Retry to request a scope-valid response; consumed budget is retained.")}catch(error){if(!signal.aborted){for(const item of task.items)if(batch.some(section2=>section2.id===item.id)){item.status="failed";item.reason="Model batch failed validation or execution; explicit retry retains its consumed budget."}}throw error}signal.throwIfAborted();journal={scope:section.scope,sections:batch.map(item=>({id:item.id,key:item.id})),baseline:before.existing.map(item=>({ref:item.ref,digest:digest(item.content)})),proposal};journals.push(journal);await writeJson(journalFile,journals)}const expected=new Map(journal.baseline.map(item=>[item.ref,item.digest]));for(const record of Object.values(ledger)){if(record.phase==="committed")for(const output of record.outputs){const ref=`${section.scope}:${output.relativePath}`;if(!expected.has(ref))expected.set(ref,output.digest)}}if(expected.size!==before.existing.length||before.existing.some(item=>expected.get(item.ref)!==digest(item.content)))return{decision:"conflict",reason:"Existing memory changed since this batch was consolidated; retained proposals cannot overwrite edits or restore forgotten knowledge.",documents:[]};return journal.proposal.items.find(item=>item.id===section.id)}async snapshot(scope){const snapshot=await scanAutoMemorySnapshot(this.options.projectRoot,{scopes:[scope],trustedProject:true,uncapped:true});if(!snapshot.sourceStatus.complete)throw new Error("Existing memory scan is incomplete.");const existing=[];for(const doc of snapshot.docs)existing.push({ref:`${scope}:${doc.relativePath}`,content:await fs.readFile(doc.filePath,"utf8")});existing.sort((a,b)=>a.ref.localeCompare(b.ref));return{version:digest(JSON.stringify(existing)),existing}}async importSection(section,batchId,signal,propose,assertCommit){const root=section.scope==="user"?getUserAutoMemoryRoot():getImportedProjectMemoryRoot(this.options.projectRoot,true);const scopeState=path.join(this.state,"scopes",digest(root));return this.locked(scopeState,async signal2=>{signal2.throwIfAborted();this.options.assertActive();if(await exists(root)&&(await fs.lstat(root)).isSymbolicLink())throw new ImportContextError("Memory import does not support a symlinked memory root. Use a non-symlink memory root before retrying; existing memories were not changed.");const ledgerPath=path.join(scopeState,"ledger.json");const ledger=await exists(ledgerPath)?await this.readState(ledgerPath):{};const key=section.id;let previous=ledger[key];const discardUnpublishedIntent=__name(async stage2=>{signal2.throwIfAborted();this.options.assertActive();delete ledger[key];await writeJson(ledgerPath,ledger);heldLocks.getStore()?.throwIfAborted();await fs.rm(stage2,{recursive:true,force:true})},"discardUnpublishedIntent");const outcome=__name((status,reason)=>({id:section.id,scope:section.scope,status,...reason?{reason}:{}}),"outcome");if(previous?.phase==="intent"){const stage2=path.join(scopeState,previous.stage);if(await exists(stage2)&&!await exists(path.join(root,"imported",key))&&(await this.snapshot(section.scope)).version!==previous.memoryVersion){await discardUnpublishedIntent(stage2);previous=void 0}}if(previous){const stage2=path.join(scopeState,previous.stage);const destination=path.join(root,"imported",key);if(previous.phase==="intent"&&await exists(stage2)&&!await exists(destination)){for(const output of previous.outputs){const file=path.join(stage2,path.basename(output.relativePath));if(digest(await fs.readFile(file,"utf8"))!==output.digest)throw new Error("Invalid staged import.")}signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage2,destination)}for(const output of previous.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously imported memory was edited or forgotten; it will not be restored.")}previous.phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);if(previous.batchId===batchId)return{...previous.outcome,id:section.id,scope:section.scope};return outcome(previous.outcome.status==="added"?"duplicate":previous.outcome.status,"This source has already been processed.")}const before=await this.snapshot(section.scope);const proposal=await propose(before,ledger,signal2);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version)return outcome("conflict","Existing memory changed during consolidation; preview and retry the source.");await assertCommit();if(proposal.decision==="conflict")return outcome("conflict",proposal.reason);if(proposal.decision!=="new"){const result2=outcome(proposal.decision==="skip"?"skipped":"duplicate",proposal.reason);ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const documents=[];for(const content of new Set(proposal.documents)){const parsed=parseAutoMemoryTopicDocument("import.md",content);if(!parsed)throw new Error("Invalid native memory.");if(section.scope==="user"&&parsed.type!=="user"&&parsed.type!=="feedback")throw new Error("Project knowledge cannot be imported into user memory.");const bodyDigest=digest(parsed.body.trim());for(const[sourceId,record]of Object.entries(ledger)){if(record.outputs.some(output=>output.bodyDigest===bodyDigest)){if(record.phase==="intent"&&!await exists(path.join(root,"imported",sourceId)))continue;for(const output of record.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously edited or forgotten imported knowledge cannot be recreated.")}}}if(before.existing.some(existing=>parseAutoMemoryTopicDocument("existing.md",existing.content)?.body.trim()===parsed.body.trim()))continue;if(!documents.some(existing=>parseAutoMemoryTopicDocument("new.md",existing)?.body.trim()===parsed.body.trim()))documents.push(content)}if(!documents.length){const result2=outcome("duplicate","All proposed knowledge already exists.");ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const stageName=`stage-${key}`;const stage=path.join(scopeState,stageName);if(await exists(stage)){await privateDirectory(stage,this.base);await fs.rm(stage,{recursive:true})}await privateDirectory(stage,this.base);const outputs=[];for(const[index,content]of documents.entries()){const filename=`${index}.md`;await fs.writeFile(path.join(stage,filename),content,{flag:"wx",mode:384});outputs.push({relativePath:`imported/${key}/${filename}`,digest:digest(content),bodyDigest:digest(parseAutoMemoryTopicDocument("import.md",content).body.trim())})}const result={...outcome("added",proposal.reason),refs:outputs.map(output=>`${section.scope}:${output.relativePath}`)};ledger[key]={batchId,phase:"intent",outputs,stage:stageName,memoryVersion:before.version,outcome:result};await writeJson(ledgerPath,ledger);signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version){await discardUnpublishedIntent(stage);return outcome("conflict","Existing memory changed before publication.")}await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage,path.join(root,"imported",key));ledger[key].phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);return result},signal)}};export{MemoryImportNotFoundError,MemoryImportService};
|
|
3
|
+
import{memoryImportReservation,validateMemoryImportBatchProposal}from"./chunk-2GVKPBW5.js";import{MEMORY_IMPORT_BUDGET,MemoryImportRequestError,digest,packMemoryImportSections,previewSource}from"./chunk-QEIX42MZ.js";import{rebuildAutoMemoryIndexAtRoot,tokenizeMemoryRecallTerms,tokenizeMemoryRecallText}from"./chunk-PFKTTUGS.js";import{parseAutoMemoryTopicDocument,resolveTrustedMemoryFile,scanAutoMemorySnapshot}from"./chunk-6RGS6DOB.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{getImportedProjectMemoryRoot,getMemoryRootTrustedAnchor,getUserAutoMemoryRoot}from"./chunk-CQGP2BAW.js";import{Storage}from"./chunk-5VB4YX3Z.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*as fs from"node:fs/promises";import{constants}from"node:fs";import{randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";var MemoryImportNotFoundError=class extends Error{static{__name(this,"MemoryImportNotFoundError")}code="ENOENT"};var ImportBudgetError=class extends Error{static{__name(this,"ImportBudgetError")}};var ImportContextError=class extends Error{static{__name(this,"ImportContextError")}};var heldLocks=new AsyncLocalStorage;var exists=__name(async file=>fs.lstat(file).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error}),"exists");async function privateDirectory(directory,anchor){const relative=path.relative(anchor,directory);if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import path escapes runtime.");let current=anchor;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);await fs.mkdir(current,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Import runtime directory must not be a symlink.")}}__name(privateDirectory,"privateDirectory");async function readJson(file){const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>16*1024*1024)throw new Error("Invalid import state file.");const buffer=Buffer.alloc(stat.size+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>stat.size)throw new Error("Import state exceeds the supported limit.");return JSON.parse(buffer.subarray(0,bytesRead).toString("utf8"))}finally{await handle.close()}}__name(readJson,"readJson");async function writeJson(file,value){heldLocks.getStore()?.throwIfAborted();const tmp=`${file}.${randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value),{mode:384,flag:"wx"});try{heldLocks.getStore()?.throwIfAborted();await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}}__name(writeJson,"writeJson");async function abortable(signal,work){signal.throwIfAborted();let abort;const cancelled=new Promise((_resolve,reject)=>{abort=__name(()=>reject(new Error("Import cancelled.")),"abort");signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work(),cancelled])}finally{signal.removeEventListener("abort",abort)}}__name(abortable,"abortable");function publicTask(task){const{requestDigest:_requestDigest,...result}=task;return structuredClone({...result,usage:task.usage??{modelCalls:0,reservedTokens:0},budget:task.budget??{maxCalls:0,maxReservedTokens:0},result:{sourceSections:task.items.length,newDocuments:task.items.filter(item=>item.status==="added").reduce((n,item)=>n+(item.refs?.length??0),0),duplicateSections:task.items.filter(item=>item.status==="duplicate").length,conflictSections:task.items.filter(item=>item.status==="conflict").length,failedSections:task.items.filter(item=>item.status==="failed").length}})}__name(publicTask,"publicTask");function selectImportContext(existing,sources){const queries=sources.map(source=>({text:source.normalize("NFKC").toLowerCase(),terms:tokenizeMemoryRecallTerms(source)}));const index=existing.map(item=>{const parsed=parseAutoMemoryTopicDocument("existing.md",item.content);if(!parsed)throw new ImportContextError("Existing memory has no bounded metadata index. Repair its native metadata before importing.");const metadata=JSON.stringify({name:parsed.title,description:parsed.description,type:parsed.type,category:parsed.category,keywords:parsed.keywords,usage_scenarios:parsed.usageScenarios});const words=tokenizeMemoryRecallText([parsed.title,...parsed.keywords].join(" "));const anchors=[parsed.title,parsed.description].map(text=>text.normalize("NFKC").toLowerCase().trim()).filter(text=>tokenizeMemoryRecallText(text).length>=2);const body=parsed.body.normalize("NFKC").toLowerCase().trim();const relevant=queries.some(({text,terms})=>{if(anchors.some(anchor=>text.includes(anchor))||body.length>0&&text.includes(body))return true;const shared=words.filter(word=>terms.has(word));return shared.length>=2&&shared.length>=words.length/2});return{ref:item.ref,content:relevant?item.content:metadata,indexOnly:!relevant}});const context=[];let bytes=2;for(const entry of[...index.filter(item=>!item.indexOnly),...index.filter(item=>item.indexOnly)]){const size=Buffer.byteLength(JSON.stringify(entry))+(context.length?1:0);if(bytes+size>MEMORY_IMPORT_BUDGET.contextBytes){if(!entry.indexOnly)throw new ImportContextError("Relevant existing evidence exceeds the 32 KiB import context budget. Select a narrower source group or consolidate existing memory before retrying. No model call was made.");continue}bytes+=size;context.push(entry)}return context}__name(selectImportContext,"selectImportContext");function respectsImportScope(proposal,scope){return scope!=="user"||proposal.documents.every(content=>{const type=parseAutoMemoryTopicDocument("import.md",content)?.type;return type==="user"||type==="feedback"})}__name(respectsImportScope,"respectsImportScope");var MemoryImportService=class{constructor(options){this.options=options;this.owner=digest(path.resolve(options.projectRoot))}static{__name(this,"MemoryImportService")}base=Storage.getRuntimeBaseDir();state=path.join(this.base,"memory-import");owner;workers=new Map;controllers=new Map;async readState(file){const relative=path.relative(this.base,path.dirname(file));if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import state escapes runtime.");let current=this.base;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Invalid import state directory.")}return readJson(file)}taskDir(id){if(!/^[a-f0-9]{64}$/.test(id))throw new MemoryImportRequestError("Invalid import batch ID.");return path.join(this.state,"batches",this.owner,id)}async assertRuntimeOutsideGit(){let current=path.resolve(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a runtime directory outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}await fs.mkdir(this.base,{recursive:true,mode:448});current=await fs.realpath(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a private runtime outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}}async prepare(){this.options.assertActive();await this.assertRuntimeOutsideGit();await privateDirectory(path.join(this.state,"batches",this.owner),this.base)}async locked(directory,run,signal){await privateDirectory(directory,this.base);const ownership=new AbortController;const parent=heldLocks.getStore();const held=parent?AbortSignal.any([parent,ownership.signal]):ownership.signal;const work=signal?AbortSignal.any([signal,held]):held;let release;while(!release){work.throwIfAborted();this.options.assertActive();try{release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,update:1e4,retries:0,onCompromised:__name(()=>{ownership.abort(new Error("Import lock lost."))},"onCompromised")})}catch(error){if(error.code!=="ELOCKED")throw error;await new Promise(resolve=>setTimeout(resolve,250))}}try{work.throwIfAborted();const result=await heldLocks.run(held,()=>run(work));held.throwIfAborted();return result}finally{try{if(!ownership.signal.aborted)await release()}finally{ownership.abort(new Error("Import lock released."))}}}async submit(input,selections,key){this.options.assertActive();const preview=previewSource(input);if(typeof key!=="string"||!/^[\w-]{1,128}$/.test(key)||!Array.isArray(selections)||!selections.length||selections.length>2048)throw new MemoryImportRequestError("Provide an idempotency key and explicit non-empty selection.");const seen=new Set;const selected=selections.map(value=>{if(!value||typeof value!=="object")throw new MemoryImportRequestError("Invalid selection.");const selection=value;const section=preview.sections.find(item=>item.id===selection.id&&item.selectable);if(!section||seen.has(selection.id)||!["project","user"].includes(selection.scope))throw new MemoryImportRequestError("Invalid, duplicate or unavailable section selection.");seen.add(selection.id);return{...section,scope:selection.scope}}).sort((a,b)=>a.id.localeCompare(b.id));const retained=JSON.stringify({sections:selected});if(Buffer.byteLength(retained)>16*1024*1024)throw new MemoryImportRequestError("Selected contextual source exceeds the retained snapshot limit.");const requestDigest=digest(JSON.stringify(selected));const id=digest(`${this.owner}\0${key}`);await this.prepare();const dir=this.taskDir(id);return this.locked(path.join(this.state,"admission",this.owner),async()=>{this.options.assertActive();if(await exists(path.join(dir,"task.json"))){const task2=await this.readState(path.join(dir,"task.json"));if(task2.requestDigest!==requestDigest)throw new MemoryImportRequestError("Idempotency key was already used with a different selection.");this.kick(id);return publicTask(task2)}await privateDirectory(dir,this.base);await writeJson(path.join(dir,"source.json"),{sections:selected});const now=new Date().toISOString();const task={version:1,kind:"task",id,status:"queued",createdAt:now,updatedAt:now,requestDigest,usage:{modelCalls:0,reservedTokens:0},budget:{maxCalls:MEMORY_IMPORT_BUDGET.maxCalls,maxReservedTokens:MEMORY_IMPORT_BUDGET.maxReservedTokens},items:selected.map(section=>({id:section.id,scope:section.scope,status:"pending"}))};await writeJson(path.join(dir,"task.json"),task);this.kick(id);return publicTask(task)})}kick(id){if(this.workers.has(id))return;const worker=heldLocks.exit(()=>this.run(id)).catch(()=>{}).finally(()=>{this.workers.delete(id);this.controllers.delete(id)});this.workers.set(id,worker)}async recover(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return;await this.assertRuntimeOutsideGit();await privateDirectory(root,this.base);for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(()=>void 0);if(task&&(task.status==="running"||task.status==="queued"))this.kick(id)}}async list(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return[];await privateDirectory(root,this.base);const result=[];for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.get(id).catch(()=>void 0);if(task)result.push(task)}return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt))}async get(id){this.options.assertActive();const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(cause=>{if(cause.code==="ENOENT")throw new MemoryImportNotFoundError("Import batch not found.",{cause});throw cause});if(task.status!=="completed"&&await exists(path.join(this.taskDir(id),"cancel.json")))task.status="cancelled";return publicTask(task)}async source(id,sectionId){await this.get(id);const source=await this.readState(path.join(this.taskDir(id),"source.json"));const section=source.sections.find(item=>item.id===sectionId);if(!section)throw new MemoryImportRequestError("Source section not found in this batch.");return section}async cancel(id){this.options.assertActive();this.controllers.get(id)?.abort();const task=await this.get(id);if(task.status==="completed")return task;await writeJson(path.join(this.taskDir(id),"cancel.json"),{cancelled:true});this.controllers.get(id)?.abort();await this.workers.get(id);return this.get(id)}async retry(id){await this.get(id);await this.prepare();await this.workers.get(id);const dir=this.taskDir(id);const result=await this.locked(dir,async()=>{const task=await this.readState(path.join(dir,"task.json"));if(task.status==="completed")return publicTask(task);await fs.rm(path.join(dir,"cancel.json"),{force:true});for(const item of task.items)if(item.status==="failed"){item.status="pending";delete item.reason}task.status="queued";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task);return publicTask(task)});this.kick(id);return result}async idle(id){await this.workers.get(id);return this.get(id)}async run(id){const dir=this.taskDir(id);const controller=new AbortController;this.controllers.set(id,controller);await this.locked(dir,async signal=>{const task=await this.readState(path.join(dir,"task.json"));if(!["queued","running"].includes(task.status))return;const source=await this.readState(path.join(dir,"source.json"));if(!task.usage){task.usage={modelCalls:0,reservedTokens:0};task.budget={maxCalls:0,maxReservedTokens:0}}task.budget??={maxCalls:0,maxReservedTokens:0};task.status="running";await writeJson(path.join(dir,"task.json"),task);for(const section of packMemoryImportSections(source.sections).flat()){const item=task.items.find(item2=>item2.id===section.id);if(item.status!=="pending")continue;if(await exists(path.join(dir,"cancel.json")))controller.abort();if(controller.signal.aborted)break;try{this.options.assertActive();Object.assign(item,await this.importSection(section,id,signal,(before,ledger,proposalSignal)=>this.prepareProposal(section,source,task,before,ledger,proposalSignal),async()=>{if(await exists(path.join(dir,"cancel.json")))controller.abort();controller.signal.throwIfAborted();this.options.assertActive()}))}catch(error){if(controller.signal.aborted)break;item.status="failed";item.reason=error instanceof ImportBudgetError||error instanceof ImportContextError?error.message:"Import could not finish. Existing memories were preserved; retry after resolving runtime, model or storage availability."}task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)}task.status=controller.signal.aborted?"cancelled":task.items.some(item=>item.status==="failed")?"partial":"completed";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)},controller.signal)}async prepareProposal(section,source,task,before,ledger,signal){const dir=this.taskDir(task.id);const journalFile=path.join(dir,"proposals.json");const journals=await exists(journalFile)?await this.readState(journalFile):[];let journal=journals.find(entry=>entry.scope===section.scope&&entry.sections.some(item=>item.id===section.id));if(journal&&!respectsImportScope(journal.proposal.items.find(item=>item.id===section.id),section.scope)){journal.sections=journal.sections.filter(item=>item.id!==section.id);journal.proposal.items=journal.proposal.items.filter(item=>item.id!==section.id);if(!journal.sections.length)journals.splice(journals.indexOf(journal),1);await writeJson(journalFile,journals);journal=void 0}if(!journal){const eligible=source.sections.filter(candidate=>candidate.scope===section.scope&&candidate.groupId===section.groupId&&task.items.some(item=>item.id===candidate.id&&item.status==="pending")&&!ledger[candidate.id]&&!journals.some(entry=>entry.sections.some(item=>item.id===candidate.id)));const batch=packMemoryImportSections(eligible).find(items=>items.some(item=>item.id===section.id));if(!batch)throw new Error("Source batch is unavailable.");const input={scope:section.scope,sources:batch.map(({id,content})=>({id,content})),existing:selectImportContext(before.existing,batch.map(item=>item.content))};const reserved=memoryImportReservation(input);if(task.usage.modelCalls>=Math.min(task.budget.maxCalls,MEMORY_IMPORT_BUDGET.maxCalls)||task.usage.reservedTokens+reserved>Math.min(task.budget.maxReservedTokens,MEMORY_IMPORT_BUDGET.maxReservedTokens))throw new ImportBudgetError("Import budget exhausted. Retry preserves this budget; split remaining sources into an explicitly confirmed new task.");signal.throwIfAborted();task.usage.modelCalls++;task.usage.reservedTokens+=reserved;await writeJson(path.join(dir,"task.json"),task);let proposal;try{proposal=validateMemoryImportBatchProposal(await abortable(signal,()=>this.options.propose(input,signal)),batch.map(item=>item.id));if(proposal.items.some(item=>!respectsImportScope(item,section.scope)))throw new ImportContextError("Model returned project knowledge for user memory. Retry to request a scope-valid response; consumed budget is retained.")}catch(error){if(!signal.aborted){for(const item of task.items)if(batch.some(section2=>section2.id===item.id)){item.status="failed";item.reason="Model batch failed validation or execution; explicit retry retains its consumed budget."}}throw error}signal.throwIfAborted();journal={scope:section.scope,sections:batch.map(item=>({id:item.id,key:item.id})),baseline:before.existing.map(item=>({ref:item.ref,digest:digest(item.content)})),proposal};journals.push(journal);await writeJson(journalFile,journals)}const expected=new Map(journal.baseline.map(item=>[item.ref,item.digest]));for(const record of Object.values(ledger)){if(record.phase==="committed")for(const output of record.outputs){const ref=`${section.scope}:${output.relativePath}`;if(!expected.has(ref))expected.set(ref,output.digest)}}if(expected.size!==before.existing.length||before.existing.some(item=>expected.get(item.ref)!==digest(item.content)))return{decision:"conflict",reason:"Existing memory changed since this batch was consolidated; retained proposals cannot overwrite edits or restore forgotten knowledge.",documents:[]};return journal.proposal.items.find(item=>item.id===section.id)}async snapshot(scope){const snapshot=await scanAutoMemorySnapshot(this.options.projectRoot,{scopes:[scope],trustedProject:true,uncapped:true});if(!snapshot.sourceStatus.complete)throw new Error("Existing memory scan is incomplete.");const existing=[];for(const doc of snapshot.docs)existing.push({ref:`${scope}:${doc.relativePath}`,content:await fs.readFile(doc.filePath,"utf8")});existing.sort((a,b)=>a.ref.localeCompare(b.ref));return{version:digest(JSON.stringify(existing)),existing}}async importSection(section,batchId,signal,propose,assertCommit){const root=section.scope==="user"?getUserAutoMemoryRoot():getImportedProjectMemoryRoot(this.options.projectRoot,true);const scopeState=path.join(this.state,"scopes",digest(root));return this.locked(scopeState,async signal2=>{signal2.throwIfAborted();this.options.assertActive();if(await exists(root)&&(await fs.lstat(root)).isSymbolicLink())throw new ImportContextError("Memory import does not support a symlinked memory root. Use a non-symlink memory root before retrying; existing memories were not changed.");const ledgerPath=path.join(scopeState,"ledger.json");const ledger=await exists(ledgerPath)?await this.readState(ledgerPath):{};const key=section.id;let previous=ledger[key];const discardUnpublishedIntent=__name(async stage2=>{signal2.throwIfAborted();this.options.assertActive();delete ledger[key];await writeJson(ledgerPath,ledger);heldLocks.getStore()?.throwIfAborted();await fs.rm(stage2,{recursive:true,force:true})},"discardUnpublishedIntent");const outcome=__name((status,reason)=>({id:section.id,scope:section.scope,status,...reason?{reason}:{}}),"outcome");if(previous?.phase==="intent"){const stage2=path.join(scopeState,previous.stage);if(await exists(stage2)&&!await exists(path.join(root,"imported",key))&&(await this.snapshot(section.scope)).version!==previous.memoryVersion){await discardUnpublishedIntent(stage2);previous=void 0}}if(previous){const stage2=path.join(scopeState,previous.stage);const destination=path.join(root,"imported",key);if(previous.phase==="intent"&&await exists(stage2)&&!await exists(destination)){for(const output of previous.outputs){const file=path.join(stage2,path.basename(output.relativePath));if(digest(await fs.readFile(file,"utf8"))!==output.digest)throw new Error("Invalid staged import.")}signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage2,destination)}for(const output of previous.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously imported memory was edited or forgotten; it will not be restored.")}previous.phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);if(previous.batchId===batchId)return{...previous.outcome,id:section.id,scope:section.scope};return outcome(previous.outcome.status==="added"?"duplicate":previous.outcome.status,"This source has already been processed.")}const before=await this.snapshot(section.scope);const proposal=await propose(before,ledger,signal2);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version)return outcome("conflict","Existing memory changed during consolidation; preview and retry the source.");await assertCommit();if(proposal.decision==="conflict")return outcome("conflict",proposal.reason);if(proposal.decision!=="new"){const result2=outcome(proposal.decision==="skip"?"skipped":"duplicate",proposal.reason);ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const documents=[];for(const content of new Set(proposal.documents)){const parsed=parseAutoMemoryTopicDocument("import.md",content);if(!parsed)throw new Error("Invalid native memory.");if(section.scope==="user"&&parsed.type!=="user"&&parsed.type!=="feedback")throw new Error("Project knowledge cannot be imported into user memory.");const bodyDigest=digest(parsed.body.trim());for(const[sourceId,record]of Object.entries(ledger)){if(record.outputs.some(output=>output.bodyDigest===bodyDigest)){if(record.phase==="intent"&&!await exists(path.join(root,"imported",sourceId)))continue;for(const output of record.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously edited or forgotten imported knowledge cannot be recreated.")}}}if(before.existing.some(existing=>parseAutoMemoryTopicDocument("existing.md",existing.content)?.body.trim()===parsed.body.trim()))continue;if(!documents.some(existing=>parseAutoMemoryTopicDocument("new.md",existing)?.body.trim()===parsed.body.trim()))documents.push(content)}if(!documents.length){const result2=outcome("duplicate","All proposed knowledge already exists.");ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const stageName=`stage-${key}`;const stage=path.join(scopeState,stageName);if(await exists(stage)){await privateDirectory(stage,this.base);await fs.rm(stage,{recursive:true})}await privateDirectory(stage,this.base);const outputs=[];for(const[index,content]of documents.entries()){const filename=`${index}.md`;await fs.writeFile(path.join(stage,filename),content,{flag:"wx",mode:384});outputs.push({relativePath:`imported/${key}/${filename}`,digest:digest(content),bodyDigest:digest(parseAutoMemoryTopicDocument("import.md",content).body.trim())})}const result={...outcome("added",proposal.reason),refs:outputs.map(output=>`${section.scope}:${output.relativePath}`)};ledger[key]={batchId,phase:"intent",outputs,stage:stageName,memoryVersion:before.version,outcome:result};await writeJson(ledgerPath,ledger);signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version){await discardUnpublishedIntent(stage);return outcome("conflict","Existing memory changed before publication.")}await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage,path.join(root,"imported",key));ledger[key].phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);return result},signal)}};export{MemoryImportNotFoundError,MemoryImportService};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
3
|
import{remarkParse,unified}from"./chunk-AZ3CKMCT.js";import{estimateTextTokens}from"./chunk-RP57XAJ2.js";import{ignoreBrokenPipe}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{homedir}from"node:os";import path2 from"node:path";import*as fs2 from"node:fs/promises";init_esbuild_shims();init_esbuild_shims();var MEMORY_IMPORT_BUDGET={maxCalls:32,maxReservedTokens:512e3,batchSections:8,sourceBytes:65536,contextBytes:32768,outputTokens:8192,promptBytes:32768};function packMemoryImportSections(sections){const groups=new Map;for(const section of[...sections].sort((a,b)=>a.id.localeCompare(b.id))){const key=`${section.scope??""}:${section.groupId}`;const group=groups.get(key)??[];group.push(section);groups.set(key,group)}const batches=[];for(const group of groups.values()){let batch=[];let bytes=0;for(const section of group){const size=Buffer.byteLength(section.content);if(batch.length&&(batch.length===MEMORY_IMPORT_BUDGET.batchSections||bytes+size>MEMORY_IMPORT_BUDGET.sourceBytes)){batches.push(batch);batch=[];bytes=0}batch.push(section);bytes+=size}if(batch.length)batches.push(batch)}return batches}__name(packMemoryImportSections,"packMemoryImportSections");function estimateMemoryImport(sections){const batches=packMemoryImportSections(sections);const modelCalls=batches.length*2;const sourceTokens=sections.reduce((n,section)=>n+estimateTextTokens(section.content),0);const sourceBytes=Buffer.byteLength(JSON.stringify(sections.map(({id,content})=>({id,content}))));const reservedTokens=modelCalls*(MEMORY_IMPORT_BUDGET.contextBytes+MEMORY_IMPORT_BUDGET.promptBytes+MEMORY_IMPORT_BUDGET.outputTokens+1024)+sourceBytes+modelCalls;return{basis:"source-only-with-context-reserve",modelCalls,sourceTokens,maxOutputTokens:modelCalls*MEMORY_IMPORT_BUDGET.outputTokens,reservedTokens,exceedsBudget:modelCalls>MEMORY_IMPORT_BUDGET.maxCalls||reservedTokens>MEMORY_IMPORT_BUDGET.maxReservedTokens,limits:MEMORY_IMPORT_BUDGET}}__name(estimateMemoryImport,"estimateMemoryImport");import{createHash}from"node:crypto";import*as fs from"node:fs/promises";import path from"node:path";import{constants}from"node:fs";var MemoryImportRequestError=class extends Error{static{__name(this,"MemoryImportRequestError")}};var IMPORT_LIMITS={files:256,fileBytes:512*1024,totalBytes:8*1024*1024,sectionBytes:64*1024,headings:4096,markdownLines:16384,inlineMarkers:4096};function digest(value){return createHash("sha256").update(value).digest("hex")}__name(digest,"digest");function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(record,"record");function validSourcePath(value){return value.length<=512&&!/[\\\p{Cc}]/u.test(value)&&!value.startsWith("/")&&!/^[a-z]:/i.test(value)&&value.split("/").every(part=>part!==""&&part!=="."&&part!=="..")&&(/^(?:MEMORY|memory_summary)\.md$/.test(value)||/^rollout_summaries\/[\w.-]+\.md$/.test(value))}__name(validSourcePath,"validSourcePath");function validateSource(value){if(!record(value)||value["version"]!==1||value["source"]!=="codex"||!Array.isArray(value["files"])||value["files"].length===0||value["files"].length>IMPORT_LIMITS.files)throw new MemoryImportRequestError("Invalid version 1 Codex source set.");let bytes=0;const seen=new Set;const files=value["files"].map(file=>{if(!record(file)||typeof file["path"]!=="string"||!validSourcePath(file["path"])||typeof file["content"]!=="string"||file["content"].includes("\0"))throw new MemoryImportRequestError("Invalid Codex Markdown resource. Only memory Markdown and rollout_summaries/*.md are accepted.");const size=Buffer.byteLength(file["content"]);bytes+=size;if(size>IMPORT_LIMITS.fileBytes||bytes>IMPORT_LIMITS.totalBytes||seen.has(file["path"].toLowerCase()))throw new MemoryImportRequestError("Source exceeds limits or contains duplicate paths.");seen.add(file["path"].toLowerCase());return{path:file["path"],content:file["content"]}});if(!files.some(file=>file.path==="MEMORY.md"||file.path==="memory_summary.md"))throw new MemoryImportRequestError("Select the Codex memories folder containing MEMORY.md or memory_summary.md.");return{version:1,source:"codex",files:files.sort((a,b)=>a.path.localeCompare(b.path))}}__name(validateSource,"validateSource");var parser=unified().use(remarkParse);function headingTitle(raw){const atx=raw.match(/^ {0,3}#{1,6}(?:[\t ]+|$)/);if(atx)return raw.slice(atx[0].length).replace(/[\t ]+#+[\t ]*$/,"").trim();return raw.split(/\r\n|[\r\n]/).slice(0,-1).join(" ").trim()}__name(headingTitle,"headingTitle");function scopeFor(content,title,summary){const scopes=[];for(const match of content.matchAll(/(?:^|[\s;(])cwd\s*[=:]\s*(?:`([^`\n]+)`|([^\r\n,;()\s]+))/gim)){if(match[1]!==void 0){scopes.push({value:match[1].trim(),quoted:true,prose:false});continue}const trailing=content.slice(match.index+match[0].length).split(/\r\n|[\r\n]/,1)[0].trim();scopes.push({value:match[2].trim(),quoted:false,prose:/[^\s,;()]/.test(trailing)})}const heading=title.trim();if(/^(?:\/|[A-Za-z]:[\\/])/.test(heading))scopes.push({value:heading.replace(/^`|`$/g,""),quoted:false,prose:false});const strip=__name(value=>value.replace(/[\\/]+$/,"").replace(/[.:!?'"]+$/,""),"strip");const unique=[...new Set(scopes.map(scope=>strip(scope.value)))];if(unique.length===1&&/^(?:\/|[A-Za-z]:[\\/])/.test(unique[0])&&scopes.every(scope=>!scope.prose&&!/[*?{}[\]\p{Cc}]|\bcwd\s*[=:]/u.test(scope.value)&&(scope.quoted||!/\s/.test(scope.value))))return{suggestedScope:"project",sourceProject:unique[0],reason:"Source project hint; explicit target mapping is required."};if(scopes.length)return{suggestedScope:"unassigned",reason:"Ambiguous or unsupported project scope; assign explicitly."};if(summary&&/^(?:user profile|user preferences)$/i.test(title))return{suggestedScope:"user",reason:"Explicit user-level summary section."};return{suggestedScope:"unassigned",reason:"No reliable project scope; assign explicitly."}}__name(scopeFor,"scopeFor");function previewSource(input){const source=validateSource(input);const sections=[];const warnings=[];let headingCount=0;let lineCount=0;let markerCount=0;let expandedBytes=0;const paths=new Set(source.files.map(file=>file.path));const referenced=new Set;for(const file of source.files.filter(f=>!f.path.startsWith("rollout_summaries/"))){for(const match of file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g))referenced.add(match[0])}for(const ref of referenced)if(!paths.has(ref))warnings.push(`Missing referenced Markdown: ${ref}`);for(const file of source.files){if(file.path.startsWith("rollout_summaries/")&&!referenced.has(file.path)){warnings.push(`Unreferenced supporting resource excluded: ${file.path}`);continue}const atxCandidates=file.content.match(/^ {0,3}#{1,6}(?:[\t ]|$)/gm)?.length??0;if(headingCount+atxCandidates>4*IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");for(let i=0;i<file.content.length;i++){const char=file.content[i];if(char==="\n"||char==="\r"&&file.content[i+1]!=="\n")lineCount++;if("*_~[]<>!`&\\".includes(char))markerCount++;if(lineCount>IMPORT_LIMITS.markdownLines||markerCount>IMPORT_LIMITS.inlineMarkers)throw new MemoryImportRequestError("Source exceeds the Markdown complexity limit; split it into smaller source sets before importing.")}const tree=parser.parse(file.content);const headings=tree.children.filter(node=>node.type==="heading").map((node,index,nodes)=>({offset:node.position.start.offset,line:node.position.start.line,depth:node.depth,title:headingTitle(file.content.slice(node.position.start.offset,node.position.end.offset)),preface:file.content.slice(node.position.start.offset,nodes[index+1]?.position.start.offset).trim()}));headingCount+=headings.length;if(headingCount>IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");const scopedDepths=headings.filter(heading=>/^(?:`?\/|`?[A-Za-z]:[\\/])/.test(heading.title)||/\bcwd\s*[=:]/i.test(heading.preface)).map(heading=>heading.depth);const minDepth=headings.length?Math.min(...headings.map(h=>h.depth)):1;const depth=Math.max(file.path==="memory_summary.md"?2:minDepth,...scopedDepths);const boundaries=headings.filter(heading=>heading.depth<=depth);if(!boundaries.length||boundaries[0].offset>0)boundaries.unshift({offset:0,line:1,title:file.path,depth:0,preface:""});for(let i=0;i<boundaries.length;i++){const boundary=boundaries[i];const own=file.content.slice(boundary.offset,boundaries[i+1]?.offset).trim();if(!own||/^v\d+$/.test(own)||own.split(/\r\n|[\r\n]/).every(line=>!line.trim()||/^#{1,6}\s/.test(line)))continue;const ancestors=[];for(const heading of headings){if(heading.offset>=boundary.offset)break;while(ancestors.length&&ancestors.at(-1).depth>=heading.depth)ancestors.pop();ancestors.push(heading)}while(ancestors.length&&ancestors.at(-1).depth>=boundary.depth)ancestors.pop();const parts=[...ancestors.map(heading=>heading.preface),own];expandedBytes+=parts.reduce((bytes,part)=>bytes+Buffer.byteLength(part),0)+2*(parts.length-1);if(expandedBytes>IMPORT_LIMITS.totalBytes)throw new MemoryImportRequestError("Source expanded context exceeds 8 MiB; split shared context and project groups before importing.");const content=parts.join("\n\n");let scope=scopeFor(content,boundary.title,file.path==="memory_summary.md");if(scope.suggestedScope==="unassigned"&&!/\bcwd\s*[=:]/i.test(content)){const parent=ancestors.at(-1);if(parent)scope=scopeFor(content,parent.title,file.path==="memory_summary.md")}const references=[...new Set(Array.from(content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0]))];const selectable=Buffer.byteLength(content)<=IMPORT_LIMITS.sectionBytes;if(!selectable)warnings.push(`${file.path}:${boundary.line}: section exceeds ${IMPORT_LIMITS.sectionBytes} bytes; split it before import.`);const id=digest(`${file.path}\0${content}`);if(sections.some(section=>section.id===id))continue;sections.push({id,groupId:digest(`${scope.suggestedScope}\0${scope.sourceProject??""}`),title:boundary.title,path:file.path,line:boundary.line,content,references,...scope,selectable})}}const groups=new Map;for(const section of sections){const group=groups.get(section.groupId)??{id:section.groupId,scope:section.suggestedScope,sourceProject:section.sourceProject,sectionIds:[]};group.sectionIds.push(section.id);groups.set(group.id,group)}return{version:1,kind:"preview",digest:digest(JSON.stringify(source)),groups:[...groups.values()].map(group=>({...group,estimate:estimateMemoryImport(sections.filter(section=>section.selectable&§ion.groupId===group.id))})),sections,warnings,estimate:estimateMemoryImport(sections.filter(section=>section.selectable))}}__name(previewSource,"previewSource");async function readLocalSource(directory){const root=await fs.realpath(directory);const files=[];const read=__name(async relative=>{const file=path.join(root,relative);const info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>IMPORT_LIMITS.fileBytes)throw new Error("Source must contain regular bounded Markdown files.");const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));try{const opened=await handle.stat();if(!opened.isFile()||opened.size>IMPORT_LIMITS.fileBytes)throw new Error("Source changed while opening.");const buffer=Buffer.alloc(IMPORT_LIMITS.fileBytes+1);let length=0;while(length<buffer.length){const read2=await handle.read(buffer,length,buffer.length-length,null);if(!read2.bytesRead)break;length+=read2.bytesRead}if(length>IMPORT_LIMITS.fileBytes||files.reduce((sum,entry)=>sum+Buffer.byteLength(entry.content),length)>IMPORT_LIMITS.totalBytes)throw new Error("Source exceeds byte limits.");files.push({path:relative,content:buffer.subarray(0,length).toString("utf8")})}finally{await handle.close()}},"read");for(const name of["MEMORY.md","memory_summary.md"]){try{await read(name)}catch(error){if(error.code!=="ENOENT")throw error}}const refs=new Set(files.flatMap(file=>Array.from(file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0])));if(refs.size+files.length>IMPORT_LIMITS.files)throw new Error("Too many referenced source files.");if(refs.size){const dir=await fs.lstat(path.join(root,"rollout_summaries")).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(dir&&(!dir.isDirectory()||dir.isSymbolicLink()))throw new Error("Supporting resource directory must not be a symlink.");if(dir)for(const ref of refs){try{await read(ref)}catch(error){if(error.code!=="ENOENT")throw error}}}return validateSource({version:1,source:"codex",files})}__name(readLocalSource,"readLocalSource");var writeStdoutLineFlushed=__name(message=>new Promise((resolve,reject)=>process.stdout.write(message.endsWith("\n")?message:`${message}
|
|
4
|
-
`,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-
|
|
4
|
+
`,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-HSG47CNJ.js");const service=await createLocalMemoryImportService();let task=await service.submit(source,selection,args["idempotency-key"]);if(args["retry"])task=await service.retry(task.id);task=await service.idle(task.id);await writeStdoutLineFlushed(JSON.stringify(task));if(task.status!=="completed"||task.items.some(item=>item.status==="conflict"))process.exitCode=1},"handler")}).demandCommand(1).version(false),"builder"),handler:__name(()=>{},"handler")};export{MEMORY_IMPORT_BUDGET,packMemoryImportSections,MemoryImportRequestError,digest,previewSource,memoryCommand};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
7
7
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{stripAnsi}from"./chunk-YGLM5XPP.js";import{isBunRuntime}from"./chunk-WGNF7FPC.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{formatMemoryUsage}from"./chunk-NTRFETZB.js";import{sanitizeChildEnv}from"./chunk-C6KSOOGV.js";import{getCurrentAgentId}from"./chunk-GQSVGUOU.js";import{getCachedEncodingForBuffer}from"./chunk-JWTMTDHE.js";import{isBinary}from"./chunk-DBRQGEEI.js";import{getShellConfiguration}from"./chunk-Y2OCBVI6.js";import{createDebugLogger,formatTraceparent,getSessionModel,getSessionModelIdentity,getSessionProjectDir,getTraceContext,isShellTracePropagationEnabled,sessionIdContext}from"./chunk-46KPDLFH.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var WINDOWS_PATH_DELIMITER=";";var cachedWindowsPathFingerprint;var cachedMergedWindowsPath;function mergeWindowsPathValues(env,pathKeys){const mergedEntries=[];const seenEntries=new Set;for(const key of pathKeys){const value=env[key];if(value===void 0){continue}for(const entry of value.split(WINDOWS_PATH_DELIMITER)){if(seenEntries.has(entry)){continue}seenEntries.add(entry);mergedEntries.push(entry)}}return mergedEntries.length>0?mergedEntries.join(WINDOWS_PATH_DELIMITER):void 0}__name(mergeWindowsPathValues,"mergeWindowsPathValues");function getWindowsPathFingerprint(env,pathKeys){return pathKeys.map(key=>`${key}=${env[key]??""}`).join("\0")}__name(getWindowsPathFingerprint,"getWindowsPathFingerprint");function sortPathKeys(pathKeys){return[...pathKeys].sort((left,right)=>{if(left==="PATH"){return-1}if(right==="PATH"){return 1}return left.localeCompare(right)})}__name(sortPathKeys,"sortPathKeys");function normalizePathEnvForWindows(env){if(process.platform!=="win32"){return env}const normalized={...env};const pathKeys=Object.keys(normalized).filter(key=>key.toLowerCase()==="path");if(pathKeys.length===0){return normalized}const orderedPathKeys=sortPathKeys(pathKeys);const fingerprint=getWindowsPathFingerprint(normalized,orderedPathKeys);const canonicalValue=fingerprint===cachedWindowsPathFingerprint?cachedMergedWindowsPath:mergeWindowsPathValues(normalized,orderedPathKeys);if(fingerprint!==cachedWindowsPathFingerprint){cachedWindowsPathFingerprint=fingerprint;cachedMergedWindowsPath=canonicalValue}for(const key of pathKeys){if(key!=="PATH"){delete normalized[key]}}if(canonicalValue!==void 0){normalized["PATH"]=canonicalValue}return normalized}__name(normalizePathEnvForWindows,"normalizePathEnvForWindows");init_esbuild_shims();import{accessSync,closeSync,constants,openSync,readSync,statSync}from"node:fs";var SCRIPT_ENTRY_RE=/\.(?:mjs|cjs|js|mts|cts|ts|tsx|jsx)$/i;var unusableCache=new Map;function isUnusableScriptEntry(path2){const cached=unusableCache.get(path2);if(cached!==void 0)return cached;let unusable;try{if(!statSync(path2).isFile()){unusable=true}else{accessSync(path2,constants.X_OK);const fd=openSync(path2,"r");try{const head=Buffer.alloc(2);const read=readSync(fd,head,0,2,0);const shebang=read===2&&head.toString("utf8")==="#!";unusable=shebang?false:SCRIPT_ENTRY_RE.test(path2)}finally{closeSync(fd)}}}catch{unusable=true}unusableCache.set(path2,unusable);return unusable}__name(isUnusableScriptEntry,"isUnusableScriptEntry");function identityDescribes(identity,model){const head=/^(.*)@[0-9a-f]{8}$/.exec(identity)?.[1]??identity;return head===model}__name(identityDescribes,"identityDescribes");function getShellContextEnvVars(){const env={};const sessionId=sessionIdContext.getStore()??process.env["QWEN_CODE_SESSION_ID"];if(sessionId){env["QWEN_CODE_SESSION_ID"]=sessionId}const projectDir=(sessionId?getSessionProjectDir(sessionId):void 0)??process.env["QWEN_CODE_PROJECT_DIR"];if(projectDir){env["QWEN_CODE_PROJECT_DIR"]=projectDir}const cliEntry=process.env["QWEN_CODE_CLI"];if(cliEntry){env["QWEN_CODE_CLI"]=isUnusableScriptEntry(cliEntry)?"":cliEntry}const model=(sessionId?getSessionModel(sessionId):void 0)??process.env["QWEN_CODE_MODEL"];if(model){env["QWEN_CODE_MODEL"]=model}const globalIdentity=process.env["QWEN_CODE_MODEL_IDENTITY"];const modelIdentity=(sessionId?getSessionModelIdentity(sessionId):void 0)??(globalIdentity&&model&&identityDescribes(globalIdentity,model)?globalIdentity:void 0);env["QWEN_CODE_MODEL_IDENTITY"]=modelIdentity??"";const agentId=getCurrentAgentId();env["QWEN_CODE_AGENT_ID"]=agentId??"";const promptId=promptIdContext.getStore();env["QWEN_CODE_PROMPT_ID"]=promptId??"";if(isShellTracePropagationEnabled()){const ctx=getTraceContext();env["TRACEPARENT"]=ctx?formatTraceparent(ctx):"";env["TRACESTATE"]=""}return env}__name(getShellContextEnvVars,"getShellContextEnvVars");init_esbuild_shims();function getDefaultShellPager(platform=process.platform){return platform==="win32"?void 0:"cat"}__name(getDefaultShellPager,"getDefaultShellPager");function getShellPagerEnv(pager,options={}){const effectivePager=pager??getDefaultShellPager(options.platform);if(!effectivePager){return{PAGER:"",...options.includeGitPager?{GIT_PAGER:""}:{}}}return{PAGER:effectivePager,...options.includeGitPager?{GIT_PAGER:effectivePager}:{}}}__name(getShellPagerEnv,"getShellPagerEnv");init_esbuild_shims();import{isUtf8}from"node:buffer";init_esbuild_shims();var loadPty=__name(async()=>{if(isBunRuntime()){if(process.platform==="win32"){return{impl:null,loadError:"the PTY backend is not yet available under the Bun runtime on Windows; use the Node runtime"}}try{const module=await import("./bun-pty-P5BLNQZZ.js");module.loadAddon();return{impl:{module,name:"qwen-bun-pty"},loadError:null}}catch(error){return{impl:null,loadError:getErrorMessage(error)}}}try{const lydell="@lydell/node-pty";const module=await import(lydell);return{impl:{module,name:"lydell-node-pty"},loadError:null}}catch(lydellError){try{const nodePty="node-pty";const module=await import(nodePty);return{impl:{module,name:"node-pty"},loadError:null}}catch(nodePtyError){return{impl:null,loadError:[lydellError,nodePtyError].map(error=>getErrorMessage(error)).join("; ")}}}},"loadPty");var getPty=__name(async()=>(await loadPty()).impl,"getPty");import{spawn as cpSpawn,spawnSync}from"node:child_process";import{TextDecoder}from"node:util";import os2 from"node:os";import path from"node:path";init_esbuild_shims();var xtermHeadlessModulePromise;function isXtermHeadlessModule(candidate){return candidate!==void 0&&"Terminal"in candidate&&typeof candidate.Terminal==="function"}__name(isXtermHeadlessModule,"isXtermHeadlessModule");function loadXtermHeadless(){xtermHeadlessModulePromise??=import("./xterm-headless-3SGUATG6.js").then(module=>{const imported=module;const candidate=isXtermHeadlessModule(imported)?imported:"default"in imported?imported.default:void 0;if(!isXtermHeadlessModule(candidate)){throw new Error("@xterm/headless module does not match the expected API")}return candidate});return xtermHeadlessModulePromise}__name(loadXtermHeadless,"loadXtermHeadless");init_esbuild_shims();var canMergeAnsiTokens=__name((left,right)=>left.bold===right.bold&&left.italic===right.italic&&left.underline===right.underline&&left.dim===right.dim&&left.inverse===right.inverse&&left.fg===right.fg&&left.bg===right.bg,"canMergeAnsiTokens");var appendAnsiLineTokens=__name((target,source)=>{for(const token of source){const previous=target[target.length-1];if(previous&&canMergeAnsiTokens(previous,token)){previous.text+=token.text}else{target.push({...token})}}},"appendAnsiLineTokens");function serializeTerminalToText(terminal){const buffer=terminal.buffer.active;const lines=[];for(let i=0;i<buffer.length;i++){const line=buffer.getLine(i);const lineContent=line?line.translateToString(true):"";if(line?.isWrapped&&lines.length>0){lines[lines.length-1]+=lineContent;continue}lines.push(lineContent)}return lines.join("\n").trimEnd()}__name(serializeTerminalToText,"serializeTerminalToText");var Cell=class{static{__name(this,"Cell")}cell;x;y;cursorX;cursorY;attributes=0;fg=0;bg=0;fgColorMode=0;bgColorMode=0;constructor(cell,x,y,cursorX,cursorY){this.cell=cell;this.x=x;this.y=y;this.cursorX=cursorX;this.cursorY=cursorY;if(!cell){return}if(cell.isInverse()){this.attributes+=1}if(cell.isBold()){this.attributes+=2}if(cell.isItalic()){this.attributes+=4}if(cell.isUnderline()){this.attributes+=8}if(cell.isDim()){this.attributes+=16}if(cell.isFgRGB()){this.fgColorMode=2}else if(cell.isFgPalette()){this.fgColorMode=1}else{this.fgColorMode=0}if(cell.isBgRGB()){this.bgColorMode=2}else if(cell.isBgPalette()){this.bgColorMode=1}else{this.bgColorMode=0}if(this.fgColorMode===0){this.fg=-1}else{this.fg=cell.getFgColor()}if(this.bgColorMode===0){this.bg=-1}else{this.bg=cell.getBgColor()}}isCursor(){return this.x===this.cursorX&&this.y===this.cursorY}getChars(){return this.cell?.getChars()||" "}isAttribute(attribute){return(this.attributes&attribute)!==0}equals(other){return this.attributes===other.attributes&&this.fg===other.fg&&this.bg===other.bg&&this.fgColorMode===other.fgColorMode&&this.bgColorMode===other.bgColorMode&&this.isCursor()===other.isCursor()}};function serializeTerminalToObject(terminal,scrollOffset=0,options={}){const buffer=terminal.buffer.active;const defaultFg="";const defaultBg="";const clampedOffset=Math.max(0,Math.min(scrollOffset,buffer.viewportY));const startRow=buffer.viewportY-clampedOffset;const cursorX=clampedOffset===0?buffer.cursorX:-1;const cursorY=clampedOffset===0?buffer.cursorY:-1;const result=[];for(let y=0;y<terminal.rows;y++){const line=buffer.getLine(startRow+y);const currentLine=[];if(!line){result.push(currentLine);continue}let lastCell=new Cell(null,-1,-1,cursorX,cursorY);let currentText="";for(let x=0;x<terminal.cols;x++){const cellData=line.getCell(x);const cell=new Cell(cellData||null,x,y,cursorX,cursorY);if(x>0&&!cell.equals(lastCell)){if(currentText){const token={text:currentText,bold:lastCell.isAttribute(2),italic:lastCell.isAttribute(4),underline:lastCell.isAttribute(8),dim:lastCell.isAttribute(16),inverse:lastCell.isAttribute(1)||lastCell.isCursor(),fg:convertColorToHex(lastCell.fg,lastCell.fgColorMode,defaultFg),bg:convertColorToHex(lastCell.bg,lastCell.bgColorMode,defaultBg)};currentLine.push(token)}currentText=""}currentText+=cell.getChars();lastCell=cell}if(currentText){const token={text:currentText,bold:lastCell.isAttribute(2),italic:lastCell.isAttribute(4),underline:lastCell.isAttribute(8),dim:lastCell.isAttribute(16),inverse:lastCell.isAttribute(1)||lastCell.isCursor(),fg:convertColorToHex(lastCell.fg,lastCell.fgColorMode,defaultFg),bg:convertColorToHex(lastCell.bg,lastCell.bgColorMode,defaultBg)};currentLine.push(token)}if(options.unwrapWrappedLines&&line.isWrapped&&result.length>0){appendAnsiLineTokens(result[result.length-1],currentLine)}else{result.push(currentLine)}}return result}__name(serializeTerminalToObject,"serializeTerminalToObject");var ANSI_COLORS=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#000000","#00005f","#000087","#0000af","#0000d7","#0000ff","#005f00","#005f5f","#005f87","#005faf","#005fd7","#005fff","#008700","#00875f","#008787","#0087af","#0087d7","#0087ff","#00af00","#00af5f","#00af87","#00afaf","#00afd7","#00afff","#00d700","#00d75f","#00d787","#00d7af","#00d7d7","#00d7ff","#00ff00","#00ff5f","#00ff87","#00ffaf","#00ffd7","#00ffff","#5f0000","#5f005f","#5f0087","#5f00af","#5f00d7","#5f00ff","#5f5f00","#5f5f5f","#5f5f87","#5f5faf","#5f5fd7","#5f5fff","#5f8700","#5f875f","#5f8787","#5f87af","#5f87d7","#5f87ff","#5faf00","#5faf5f","#5faf87","#5fafaf","#5fafd7","#5fafff","#5fd700","#5fd75f","#5fd787","#5fd7af","#5fd7d7","#5fd7ff","#5fff00","#5fff5f","#5fff87","#5fffaf","#5fffd7","#5fffff","#870000","#87005f","#870087","#8700af","#8700d7","#8700ff","#875f00","#875f5f","#875f87","#875faf","#875fd7","#875fff","#878700","#87875f","#878787","#8787af","#8787d7","#8787ff","#87af00","#87af5f","#87af87","#87afaf","#87afd7","#87afff","#87d700","#87d75f","#87d787","#87d7af","#87d7d7","#87d7ff","#87ff00","#87ff5f","#87ff87","#87ffaf","#87ffd7","#87ffff","#af0000","#af005f","#af0087","#af00af","#af00d7","#af00ff","#af5f00","#af5f5f","#af5f87","#af5faf","#af5fd7","#af5fff","#af8700","#af875f","#af8787","#af87af","#af87d7","#af87ff","#afaf00","#afaf5f","#afaf87","#afafaf","#afafd7","#afafff","#afd700","#afd75f","#afd787","#afd7af","#afd7d7","#afd7ff","#afff00","#afff5f","#afff87","#afffaf","#afffd7","#afffff","#d70000","#d7005f","#d70087","#d700af","#d700d7","#d700ff","#d75f00","#d75f5f","#d75f87","#d75faf","#d75fd7","#d75fff","#d78700","#d7875f","#d78787","#d787af","#d787d7","#d787ff","#d7af00","#d7af5f","#d7af87","#d7afaf","#d7afd7","#d7afff","#d7d700","#d7d75f","#d7d787","#d7d7af","#d7d7d7","#d7d7ff","#d7ff00","#d7ff5f","#d7ff87","#d7ffaf","#d7ffd7","#d7ffff","#ff0000","#ff005f","#ff0087","#ff00af","#ff00d7","#ff00ff","#ff5f00","#ff5f5f","#ff5f87","#ff5faf","#ff5fd7","#ff5fff","#ff8700","#ff875f","#ff8787","#ff87af","#ff87d7","#ff87ff","#ffaf00","#ffaf5f","#ffaf87","#ffafaf","#ffafd7","#ffafff","#ffd700","#ffd75f","#ffd787","#ffd7af","#ffd7d7","#ffd7ff","#ffff00","#ffff5f","#ffff87","#ffffaf","#ffffd7","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a8a8a8","#b2b2b2","#bcbcbc","#c6c6c6","#d0d0d0","#dadada","#e4e4e4","#eeeeee"];function convertColorToHex(color,colorMode,defaultColor){if(colorMode===2){const r=color>>16&255;const g=color>>8&255;const b=color&255;return`#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`}if(colorMode===1){return ANSI_COLORS[color]||defaultColor}return defaultColor}__name(convertColorToHex,"convertColorToHex");init_esbuild_shims();import os from"node:os";var debugLogger=createDebugLogger("CONPTY_HOST");var releasedHosts=new WeakSet;var asPtyObject=__name(ptyProcess=>typeof ptyProcess==="object"&&ptyProcess!==null?ptyProcess:void 0,"asPtyObject");var noteConPtyHostReleased=__name(ptyProcess=>{const key=asPtyObject(ptyProcess);if(key){releasedHosts.add(key)}},"noteConPtyHostReleased");var disposeConoutWorker=__name(ptyProcess=>{if(os.platform()!=="win32"){return}const agent=ptyProcess?._agent;if(!agent){return}try{agent._conoutSocketWorker?.dispose?.()}catch(e){debugLogger.warn(`disposeConoutWorker: conout worker dispose threw: ${e instanceof Error?e.message:String(e)}`)}},"disposeConoutWorker");var releaseConPtyHost=__name(ptyProcess=>{if(os.platform()!=="win32"){return}const key=asPtyObject(ptyProcess);if(!key){return}const agent=ptyProcess?._agent;if(releasedHosts.has(key)){if(agent?._useConptyDll){disposeConoutWorker(ptyProcess)}return}releasedHosts.add(key);const ptyId=agent?._pty;const nativeKill=agent?._ptyNative?.kill;if(!agent){debugLogger.warn("releaseConPtyHost: no node-pty agent; nothing released (see #11303)");return}if(typeof nativeKill==="function"&&typeof ptyId==="number"){try{nativeKill.call(agent._ptyNative,ptyId,agent._useConptyDll??false)}catch(e){debugLogger.warn(`releaseConPtyHost: the native pty kill threw: ${e instanceof Error?e.message:String(e)}`)}}else{debugLogger.warn("releaseConPtyHost: native pty shape changed; skipping the pseudo-console close (see #11303)")}try{agent._conoutSocketWorker?.dispose?.()}catch(e){debugLogger.warn(`releaseConPtyHost: conout worker dispose threw: ${e instanceof Error?e.message:String(e)}`)}},"releaseConPtyHost");var debugLogger2=createDebugLogger("SHELL_EXECUTION");var DEFAULT_MAX_BUFFERED_OUTPUT_BYTES=64*1024*1024;var MAX_BUFFERED_OUTPUT_BYTES_CEILING=256*1024*1024;var SIGKILL_TIMEOUT_MS=200;var POST_EXIT_STREAM_DRAIN_MS=1e3;var MAX_LIVE_TERMINAL_SCROLLBACK_LINES=200;var PROMOTE_DRAIN_TIMEOUT_MS=200;function getShellAbortReasonKind(reason){if(reason!==null&&typeof reason==="object"){try{if(Object.prototype.hasOwnProperty.call(reason,"kind")){const kind=reason.kind;if(kind==="background"||kind==="cancel")return kind}}catch{}}return"cancel"}__name(getShellAbortReasonKind,"getShellAbortReasonKind");var CHCP=`${process.env["SystemRoot"]||"C:\\Windows"}\\System32\\chcp.com`;function applyUtf8Prefix(command,shell){if(os2.platform()!=="win32")return command;switch(shell){case"powershell":return"[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;"+command;case"cmd":return`${CHCP} 65001 >nul 2>nul & ${command}`;case"bash":return command;default:{const _exhaustive=shell;return _exhaustive}}}__name(applyUtf8Prefix,"applyUtf8Prefix");function isSignalTermination(signal){return signal!==null&&signal!==0}__name(isSignalTermination,"isSignalTermination");function launchCommand(input){if(typeof input!=="string"){return{executable:input.executable,args:[...input.args],shell:void 0}}const{executable,argsPrefix,shell}=getShellConfiguration();return{executable,args:[...argsPrefix,applyUtf8Prefix(input,shell)],shell}}__name(launchCommand,"launchCommand");function createPreSpawnAbortedHandle(){return{pid:void 0,result:Promise.resolve({rawOutput:Buffer.alloc(0),output:"",exitCode:null,signal:null,error:null,aborted:true,pid:void 0,executionMethod:"none"})}}__name(createPreSpawnAbortedHandle,"createPreSpawnAbortedHandle");function getMaxBufferedOutputBytes(config){const configured=config.maxBufferedOutputBytes;const floored=typeof configured==="number"&&Number.isFinite(configured)?Math.floor(configured):0;return floored>0?Math.min(floored,MAX_BUFFERED_OUTPUT_BYTES_CEILING):DEFAULT_MAX_BUFFERED_OUTPUT_BYTES}__name(getMaxBufferedOutputBytes,"getMaxBufferedOutputBytes");function decodeBufferedOutput(finalBuffer){const fallbackEncoding=getCachedEncodingForBuffer(finalBuffer);return new TextDecoder(fallbackEncoding).decode(finalBuffer)}__name(decodeBufferedOutput,"decodeBufferedOutput");function decodePreviewTail(buffer){let start=0;while(start<buffer.length&&start<3&&(buffer[start]&192)===128)start++;const aligned=buffer.subarray(start);return decodeBufferedOutput(start>0&&isUtf8(aligned)&&aligned.some(byte=>byte>=194)?aligned:buffer)}__name(decodePreviewTail,"decodePreviewTail");function appendOutputCaptureLimitNotice(output,didExceedLimit,totalBytesReceived,maxBufferedOutputBytes){if(!didExceedLimit){return output}const notice=`[Output exceeded the maximum captured size of ${formatMemoryUsage(maxBufferedOutputBytes)}; captured the first ${formatMemoryUsage(maxBufferedOutputBytes)} of ${formatMemoryUsage(totalBytesReceived)} and discarded the rest to avoid constructing an oversized JavaScript string.]`;return output?`${output}
|
|
3
|
+
import{stripAnsi}from"./chunk-YGLM5XPP.js";import{isBunRuntime}from"./chunk-WGNF7FPC.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{formatMemoryUsage}from"./chunk-NTRFETZB.js";import{sanitizeChildEnv}from"./chunk-C6KSOOGV.js";import{getCurrentAgentId}from"./chunk-KP77CL5U.js";import{getCachedEncodingForBuffer}from"./chunk-JWTMTDHE.js";import{isBinary}from"./chunk-DBRQGEEI.js";import{getShellConfiguration}from"./chunk-Y2OCBVI6.js";import{createDebugLogger,formatTraceparent,getSessionModel,getSessionModelIdentity,getSessionProjectDir,getTraceContext,isShellTracePropagationEnabled,sessionIdContext}from"./chunk-46KPDLFH.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var WINDOWS_PATH_DELIMITER=";";var cachedWindowsPathFingerprint;var cachedMergedWindowsPath;function mergeWindowsPathValues(env,pathKeys){const mergedEntries=[];const seenEntries=new Set;for(const key of pathKeys){const value=env[key];if(value===void 0){continue}for(const entry of value.split(WINDOWS_PATH_DELIMITER)){if(seenEntries.has(entry)){continue}seenEntries.add(entry);mergedEntries.push(entry)}}return mergedEntries.length>0?mergedEntries.join(WINDOWS_PATH_DELIMITER):void 0}__name(mergeWindowsPathValues,"mergeWindowsPathValues");function getWindowsPathFingerprint(env,pathKeys){return pathKeys.map(key=>`${key}=${env[key]??""}`).join("\0")}__name(getWindowsPathFingerprint,"getWindowsPathFingerprint");function sortPathKeys(pathKeys){return[...pathKeys].sort((left,right)=>{if(left==="PATH"){return-1}if(right==="PATH"){return 1}return left.localeCompare(right)})}__name(sortPathKeys,"sortPathKeys");function normalizePathEnvForWindows(env){if(process.platform!=="win32"){return env}const normalized={...env};const pathKeys=Object.keys(normalized).filter(key=>key.toLowerCase()==="path");if(pathKeys.length===0){return normalized}const orderedPathKeys=sortPathKeys(pathKeys);const fingerprint=getWindowsPathFingerprint(normalized,orderedPathKeys);const canonicalValue=fingerprint===cachedWindowsPathFingerprint?cachedMergedWindowsPath:mergeWindowsPathValues(normalized,orderedPathKeys);if(fingerprint!==cachedWindowsPathFingerprint){cachedWindowsPathFingerprint=fingerprint;cachedMergedWindowsPath=canonicalValue}for(const key of pathKeys){if(key!=="PATH"){delete normalized[key]}}if(canonicalValue!==void 0){normalized["PATH"]=canonicalValue}return normalized}__name(normalizePathEnvForWindows,"normalizePathEnvForWindows");init_esbuild_shims();import{accessSync,closeSync,constants,openSync,readSync,statSync}from"node:fs";var SCRIPT_ENTRY_RE=/\.(?:mjs|cjs|js|mts|cts|ts|tsx|jsx)$/i;var unusableCache=new Map;function isUnusableScriptEntry(path2){const cached=unusableCache.get(path2);if(cached!==void 0)return cached;let unusable;try{if(!statSync(path2).isFile()){unusable=true}else{accessSync(path2,constants.X_OK);const fd=openSync(path2,"r");try{const head=Buffer.alloc(2);const read=readSync(fd,head,0,2,0);const shebang=read===2&&head.toString("utf8")==="#!";unusable=shebang?false:SCRIPT_ENTRY_RE.test(path2)}finally{closeSync(fd)}}}catch{unusable=true}unusableCache.set(path2,unusable);return unusable}__name(isUnusableScriptEntry,"isUnusableScriptEntry");function identityDescribes(identity,model){const head=/^(.*)@[0-9a-f]{8}$/.exec(identity)?.[1]??identity;return head===model}__name(identityDescribes,"identityDescribes");function getShellContextEnvVars(){const env={};const sessionId=sessionIdContext.getStore()??process.env["QWEN_CODE_SESSION_ID"];if(sessionId){env["QWEN_CODE_SESSION_ID"]=sessionId}const projectDir=(sessionId?getSessionProjectDir(sessionId):void 0)??process.env["QWEN_CODE_PROJECT_DIR"];if(projectDir){env["QWEN_CODE_PROJECT_DIR"]=projectDir}const cliEntry=process.env["QWEN_CODE_CLI"];if(cliEntry){env["QWEN_CODE_CLI"]=isUnusableScriptEntry(cliEntry)?"":cliEntry}const model=(sessionId?getSessionModel(sessionId):void 0)??process.env["QWEN_CODE_MODEL"];if(model){env["QWEN_CODE_MODEL"]=model}const globalIdentity=process.env["QWEN_CODE_MODEL_IDENTITY"];const modelIdentity=(sessionId?getSessionModelIdentity(sessionId):void 0)??(globalIdentity&&model&&identityDescribes(globalIdentity,model)?globalIdentity:void 0);env["QWEN_CODE_MODEL_IDENTITY"]=modelIdentity??"";const agentId=getCurrentAgentId();env["QWEN_CODE_AGENT_ID"]=agentId??"";const promptId=promptIdContext.getStore();env["QWEN_CODE_PROMPT_ID"]=promptId??"";if(isShellTracePropagationEnabled()){const ctx=getTraceContext();env["TRACEPARENT"]=ctx?formatTraceparent(ctx):"";env["TRACESTATE"]=""}return env}__name(getShellContextEnvVars,"getShellContextEnvVars");init_esbuild_shims();function getDefaultShellPager(platform=process.platform){return platform==="win32"?void 0:"cat"}__name(getDefaultShellPager,"getDefaultShellPager");function getShellPagerEnv(pager,options={}){const effectivePager=pager??getDefaultShellPager(options.platform);if(!effectivePager){return{PAGER:"",...options.includeGitPager?{GIT_PAGER:""}:{}}}return{PAGER:effectivePager,...options.includeGitPager?{GIT_PAGER:effectivePager}:{}}}__name(getShellPagerEnv,"getShellPagerEnv");init_esbuild_shims();import{isUtf8}from"node:buffer";init_esbuild_shims();var loadPty=__name(async()=>{if(isBunRuntime()){if(process.platform==="win32"){return{impl:null,loadError:"the PTY backend is not yet available under the Bun runtime on Windows; use the Node runtime"}}try{const module=await import("./bun-pty-P5BLNQZZ.js");module.loadAddon();return{impl:{module,name:"qwen-bun-pty"},loadError:null}}catch(error){return{impl:null,loadError:getErrorMessage(error)}}}try{const lydell="@lydell/node-pty";const module=await import(lydell);return{impl:{module,name:"lydell-node-pty"},loadError:null}}catch(lydellError){try{const nodePty="node-pty";const module=await import(nodePty);return{impl:{module,name:"node-pty"},loadError:null}}catch(nodePtyError){return{impl:null,loadError:[lydellError,nodePtyError].map(error=>getErrorMessage(error)).join("; ")}}}},"loadPty");var getPty=__name(async()=>(await loadPty()).impl,"getPty");import{spawn as cpSpawn,spawnSync}from"node:child_process";import{TextDecoder}from"node:util";import os2 from"node:os";import path from"node:path";init_esbuild_shims();var xtermHeadlessModulePromise;function isXtermHeadlessModule(candidate){return candidate!==void 0&&"Terminal"in candidate&&typeof candidate.Terminal==="function"}__name(isXtermHeadlessModule,"isXtermHeadlessModule");function loadXtermHeadless(){xtermHeadlessModulePromise??=import("./xterm-headless-3SGUATG6.js").then(module=>{const imported=module;const candidate=isXtermHeadlessModule(imported)?imported:"default"in imported?imported.default:void 0;if(!isXtermHeadlessModule(candidate)){throw new Error("@xterm/headless module does not match the expected API")}return candidate});return xtermHeadlessModulePromise}__name(loadXtermHeadless,"loadXtermHeadless");init_esbuild_shims();var canMergeAnsiTokens=__name((left,right)=>left.bold===right.bold&&left.italic===right.italic&&left.underline===right.underline&&left.dim===right.dim&&left.inverse===right.inverse&&left.fg===right.fg&&left.bg===right.bg,"canMergeAnsiTokens");var appendAnsiLineTokens=__name((target,source)=>{for(const token of source){const previous=target[target.length-1];if(previous&&canMergeAnsiTokens(previous,token)){previous.text+=token.text}else{target.push({...token})}}},"appendAnsiLineTokens");function serializeTerminalToText(terminal){const buffer=terminal.buffer.active;const lines=[];for(let i=0;i<buffer.length;i++){const line=buffer.getLine(i);const lineContent=line?line.translateToString(true):"";if(line?.isWrapped&&lines.length>0){lines[lines.length-1]+=lineContent;continue}lines.push(lineContent)}return lines.join("\n").trimEnd()}__name(serializeTerminalToText,"serializeTerminalToText");var Cell=class{static{__name(this,"Cell")}cell;x;y;cursorX;cursorY;attributes=0;fg=0;bg=0;fgColorMode=0;bgColorMode=0;constructor(cell,x,y,cursorX,cursorY){this.cell=cell;this.x=x;this.y=y;this.cursorX=cursorX;this.cursorY=cursorY;if(!cell){return}if(cell.isInverse()){this.attributes+=1}if(cell.isBold()){this.attributes+=2}if(cell.isItalic()){this.attributes+=4}if(cell.isUnderline()){this.attributes+=8}if(cell.isDim()){this.attributes+=16}if(cell.isFgRGB()){this.fgColorMode=2}else if(cell.isFgPalette()){this.fgColorMode=1}else{this.fgColorMode=0}if(cell.isBgRGB()){this.bgColorMode=2}else if(cell.isBgPalette()){this.bgColorMode=1}else{this.bgColorMode=0}if(this.fgColorMode===0){this.fg=-1}else{this.fg=cell.getFgColor()}if(this.bgColorMode===0){this.bg=-1}else{this.bg=cell.getBgColor()}}isCursor(){return this.x===this.cursorX&&this.y===this.cursorY}getChars(){return this.cell?.getChars()||" "}isAttribute(attribute){return(this.attributes&attribute)!==0}equals(other){return this.attributes===other.attributes&&this.fg===other.fg&&this.bg===other.bg&&this.fgColorMode===other.fgColorMode&&this.bgColorMode===other.bgColorMode&&this.isCursor()===other.isCursor()}};function serializeTerminalToObject(terminal,scrollOffset=0,options={}){const buffer=terminal.buffer.active;const defaultFg="";const defaultBg="";const clampedOffset=Math.max(0,Math.min(scrollOffset,buffer.viewportY));const startRow=buffer.viewportY-clampedOffset;const cursorX=clampedOffset===0?buffer.cursorX:-1;const cursorY=clampedOffset===0?buffer.cursorY:-1;const result=[];for(let y=0;y<terminal.rows;y++){const line=buffer.getLine(startRow+y);const currentLine=[];if(!line){result.push(currentLine);continue}let lastCell=new Cell(null,-1,-1,cursorX,cursorY);let currentText="";for(let x=0;x<terminal.cols;x++){const cellData=line.getCell(x);const cell=new Cell(cellData||null,x,y,cursorX,cursorY);if(x>0&&!cell.equals(lastCell)){if(currentText){const token={text:currentText,bold:lastCell.isAttribute(2),italic:lastCell.isAttribute(4),underline:lastCell.isAttribute(8),dim:lastCell.isAttribute(16),inverse:lastCell.isAttribute(1)||lastCell.isCursor(),fg:convertColorToHex(lastCell.fg,lastCell.fgColorMode,defaultFg),bg:convertColorToHex(lastCell.bg,lastCell.bgColorMode,defaultBg)};currentLine.push(token)}currentText=""}currentText+=cell.getChars();lastCell=cell}if(currentText){const token={text:currentText,bold:lastCell.isAttribute(2),italic:lastCell.isAttribute(4),underline:lastCell.isAttribute(8),dim:lastCell.isAttribute(16),inverse:lastCell.isAttribute(1)||lastCell.isCursor(),fg:convertColorToHex(lastCell.fg,lastCell.fgColorMode,defaultFg),bg:convertColorToHex(lastCell.bg,lastCell.bgColorMode,defaultBg)};currentLine.push(token)}if(options.unwrapWrappedLines&&line.isWrapped&&result.length>0){appendAnsiLineTokens(result[result.length-1],currentLine)}else{result.push(currentLine)}}return result}__name(serializeTerminalToObject,"serializeTerminalToObject");var ANSI_COLORS=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#000000","#00005f","#000087","#0000af","#0000d7","#0000ff","#005f00","#005f5f","#005f87","#005faf","#005fd7","#005fff","#008700","#00875f","#008787","#0087af","#0087d7","#0087ff","#00af00","#00af5f","#00af87","#00afaf","#00afd7","#00afff","#00d700","#00d75f","#00d787","#00d7af","#00d7d7","#00d7ff","#00ff00","#00ff5f","#00ff87","#00ffaf","#00ffd7","#00ffff","#5f0000","#5f005f","#5f0087","#5f00af","#5f00d7","#5f00ff","#5f5f00","#5f5f5f","#5f5f87","#5f5faf","#5f5fd7","#5f5fff","#5f8700","#5f875f","#5f8787","#5f87af","#5f87d7","#5f87ff","#5faf00","#5faf5f","#5faf87","#5fafaf","#5fafd7","#5fafff","#5fd700","#5fd75f","#5fd787","#5fd7af","#5fd7d7","#5fd7ff","#5fff00","#5fff5f","#5fff87","#5fffaf","#5fffd7","#5fffff","#870000","#87005f","#870087","#8700af","#8700d7","#8700ff","#875f00","#875f5f","#875f87","#875faf","#875fd7","#875fff","#878700","#87875f","#878787","#8787af","#8787d7","#8787ff","#87af00","#87af5f","#87af87","#87afaf","#87afd7","#87afff","#87d700","#87d75f","#87d787","#87d7af","#87d7d7","#87d7ff","#87ff00","#87ff5f","#87ff87","#87ffaf","#87ffd7","#87ffff","#af0000","#af005f","#af0087","#af00af","#af00d7","#af00ff","#af5f00","#af5f5f","#af5f87","#af5faf","#af5fd7","#af5fff","#af8700","#af875f","#af8787","#af87af","#af87d7","#af87ff","#afaf00","#afaf5f","#afaf87","#afafaf","#afafd7","#afafff","#afd700","#afd75f","#afd787","#afd7af","#afd7d7","#afd7ff","#afff00","#afff5f","#afff87","#afffaf","#afffd7","#afffff","#d70000","#d7005f","#d70087","#d700af","#d700d7","#d700ff","#d75f00","#d75f5f","#d75f87","#d75faf","#d75fd7","#d75fff","#d78700","#d7875f","#d78787","#d787af","#d787d7","#d787ff","#d7af00","#d7af5f","#d7af87","#d7afaf","#d7afd7","#d7afff","#d7d700","#d7d75f","#d7d787","#d7d7af","#d7d7d7","#d7d7ff","#d7ff00","#d7ff5f","#d7ff87","#d7ffaf","#d7ffd7","#d7ffff","#ff0000","#ff005f","#ff0087","#ff00af","#ff00d7","#ff00ff","#ff5f00","#ff5f5f","#ff5f87","#ff5faf","#ff5fd7","#ff5fff","#ff8700","#ff875f","#ff8787","#ff87af","#ff87d7","#ff87ff","#ffaf00","#ffaf5f","#ffaf87","#ffafaf","#ffafd7","#ffafff","#ffd700","#ffd75f","#ffd787","#ffd7af","#ffd7d7","#ffd7ff","#ffff00","#ffff5f","#ffff87","#ffffaf","#ffffd7","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a8a8a8","#b2b2b2","#bcbcbc","#c6c6c6","#d0d0d0","#dadada","#e4e4e4","#eeeeee"];function convertColorToHex(color,colorMode,defaultColor){if(colorMode===2){const r=color>>16&255;const g=color>>8&255;const b=color&255;return`#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`}if(colorMode===1){return ANSI_COLORS[color]||defaultColor}return defaultColor}__name(convertColorToHex,"convertColorToHex");init_esbuild_shims();import os from"node:os";var debugLogger=createDebugLogger("CONPTY_HOST");var releasedHosts=new WeakSet;var asPtyObject=__name(ptyProcess=>typeof ptyProcess==="object"&&ptyProcess!==null?ptyProcess:void 0,"asPtyObject");var noteConPtyHostReleased=__name(ptyProcess=>{const key=asPtyObject(ptyProcess);if(key){releasedHosts.add(key)}},"noteConPtyHostReleased");var disposeConoutWorker=__name(ptyProcess=>{if(os.platform()!=="win32"){return}const agent=ptyProcess?._agent;if(!agent){return}try{agent._conoutSocketWorker?.dispose?.()}catch(e){debugLogger.warn(`disposeConoutWorker: conout worker dispose threw: ${e instanceof Error?e.message:String(e)}`)}},"disposeConoutWorker");var releaseConPtyHost=__name(ptyProcess=>{if(os.platform()!=="win32"){return}const key=asPtyObject(ptyProcess);if(!key){return}const agent=ptyProcess?._agent;if(releasedHosts.has(key)){if(agent?._useConptyDll){disposeConoutWorker(ptyProcess)}return}releasedHosts.add(key);const ptyId=agent?._pty;const nativeKill=agent?._ptyNative?.kill;if(!agent){debugLogger.warn("releaseConPtyHost: no node-pty agent; nothing released (see #11303)");return}if(typeof nativeKill==="function"&&typeof ptyId==="number"){try{nativeKill.call(agent._ptyNative,ptyId,agent._useConptyDll??false)}catch(e){debugLogger.warn(`releaseConPtyHost: the native pty kill threw: ${e instanceof Error?e.message:String(e)}`)}}else{debugLogger.warn("releaseConPtyHost: native pty shape changed; skipping the pseudo-console close (see #11303)")}try{agent._conoutSocketWorker?.dispose?.()}catch(e){debugLogger.warn(`releaseConPtyHost: conout worker dispose threw: ${e instanceof Error?e.message:String(e)}`)}},"releaseConPtyHost");var debugLogger2=createDebugLogger("SHELL_EXECUTION");var DEFAULT_MAX_BUFFERED_OUTPUT_BYTES=64*1024*1024;var MAX_BUFFERED_OUTPUT_BYTES_CEILING=256*1024*1024;var SIGKILL_TIMEOUT_MS=200;var POST_EXIT_STREAM_DRAIN_MS=1e3;var MAX_LIVE_TERMINAL_SCROLLBACK_LINES=200;var PROMOTE_DRAIN_TIMEOUT_MS=200;function getShellAbortReasonKind(reason){if(reason!==null&&typeof reason==="object"){try{if(Object.prototype.hasOwnProperty.call(reason,"kind")){const kind=reason.kind;if(kind==="background"||kind==="cancel")return kind}}catch{}}return"cancel"}__name(getShellAbortReasonKind,"getShellAbortReasonKind");var CHCP=`${process.env["SystemRoot"]||"C:\\Windows"}\\System32\\chcp.com`;function applyUtf8Prefix(command,shell){if(os2.platform()!=="win32")return command;switch(shell){case"powershell":return"[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;"+command;case"cmd":return`${CHCP} 65001 >nul 2>nul & ${command}`;case"bash":return command;default:{const _exhaustive=shell;return _exhaustive}}}__name(applyUtf8Prefix,"applyUtf8Prefix");function isSignalTermination(signal){return signal!==null&&signal!==0}__name(isSignalTermination,"isSignalTermination");function launchCommand(input){if(typeof input!=="string"){return{executable:input.executable,args:[...input.args],shell:void 0}}const{executable,argsPrefix,shell}=getShellConfiguration();return{executable,args:[...argsPrefix,applyUtf8Prefix(input,shell)],shell}}__name(launchCommand,"launchCommand");function createPreSpawnAbortedHandle(){return{pid:void 0,result:Promise.resolve({rawOutput:Buffer.alloc(0),output:"",exitCode:null,signal:null,error:null,aborted:true,pid:void 0,executionMethod:"none"})}}__name(createPreSpawnAbortedHandle,"createPreSpawnAbortedHandle");function getMaxBufferedOutputBytes(config){const configured=config.maxBufferedOutputBytes;const floored=typeof configured==="number"&&Number.isFinite(configured)?Math.floor(configured):0;return floored>0?Math.min(floored,MAX_BUFFERED_OUTPUT_BYTES_CEILING):DEFAULT_MAX_BUFFERED_OUTPUT_BYTES}__name(getMaxBufferedOutputBytes,"getMaxBufferedOutputBytes");function decodeBufferedOutput(finalBuffer){const fallbackEncoding=getCachedEncodingForBuffer(finalBuffer);return new TextDecoder(fallbackEncoding).decode(finalBuffer)}__name(decodeBufferedOutput,"decodeBufferedOutput");function decodePreviewTail(buffer){let start=0;while(start<buffer.length&&start<3&&(buffer[start]&192)===128)start++;const aligned=buffer.subarray(start);return decodeBufferedOutput(start>0&&isUtf8(aligned)&&aligned.some(byte=>byte>=194)?aligned:buffer)}__name(decodePreviewTail,"decodePreviewTail");function appendOutputCaptureLimitNotice(output,didExceedLimit,totalBytesReceived,maxBufferedOutputBytes){if(!didExceedLimit){return output}const notice=`[Output exceeded the maximum captured size of ${formatMemoryUsage(maxBufferedOutputBytes)}; captured the first ${formatMemoryUsage(maxBufferedOutputBytes)} of ${formatMemoryUsage(totalBytesReceived)} and discarded the rest to avoid constructing an oversized JavaScript string.]`;return output?`${output}
|
|
4
4
|
|
|
5
5
|
${notice}`:notice}__name(appendOutputCaptureLimitNotice,"appendOutputCaptureLimitNotice");var getErrnoCode=__name(error=>{if(!error||typeof error!=="object"||!("code"in error)){return void 0}const code=error.code;return typeof code==="string"?code:void 0},"getErrnoCode");var getErrorMessage2=__name(error=>error instanceof Error?error.message:String(error),"getErrorMessage");var isExpectedPtyReadExitError=__name(error=>{const code=getErrnoCode(error);if(code==="EIO"||code==="EAGAIN"){return true}const message=getErrorMessage2(error);return message.includes("read EIO")||message.includes("EAGAIN")},"isExpectedPtyReadExitError");var isExpectedPtyExitRaceError=__name(error=>{const code=getErrnoCode(error);if(code==="ESRCH"||code==="EBADF"){return true}const message=getErrorMessage2(error);return message.includes("ioctl(2) failed, EBADF")||message.includes("Cannot resize a pty that has already exited")},"isExpectedPtyExitRaceError");var replayTerminalOutput=__name(async(output,cols,rows,Terminal)=>{const replayTerminal=new Terminal({allowProposedApi:true,cols,rows,scrollback:1e4,convertEol:true,logLevel:"off"});try{await new Promise(resolve=>{replayTerminal.write(output,()=>resolve())});return serializeTerminalToText(replayTerminal)}finally{replayTerminal.dispose()}},"replayTerminalOutput");var getLastNonEmptyAnsiLineIndex=__name(output=>{for(let i=output.length-1;i>=0;i--){const line=output[i];if(line.map(segment=>segment.text).join("").trim().length>0){return i}}return-1},"getLastNonEmptyAnsiLineIndex");var trimTrailingEmptyAnsiLines=__name(output=>output.slice(0,getLastNonEmptyAnsiLineIndex(output)+1),"trimTrailingEmptyAnsiLines");var areAnsiOutputsEqual=__name((left,right)=>{if(!left||left.length!==right.length){return false}return left.every((leftLine,lineIndex)=>{const rightLine=right[lineIndex];if(leftLine.length!==rightLine.length){return false}return leftLine.every((leftToken,tokenIndex)=>{const rightToken=rightLine[tokenIndex];return leftToken.text===rightToken.text&&leftToken.bold===rightToken.bold&&leftToken.italic===rightToken.italic&&leftToken.underline===rightToken.underline&&leftToken.dim===rightToken.dim&&leftToken.inverse===rightToken.inverse&&leftToken.fg===rightToken.fg&&leftToken.bg===rightToken.bg})})},"areAnsiOutputsEqual");var createPlainAnsiLine=__name(text=>[{text,bold:false,italic:false,underline:false,dim:false,inverse:false,fg:"",bg:""}],"createPlainAnsiLine");var serializePlainViewportToAnsiOutput=__name((terminal,unwrapWrappedLines=false)=>{const buffer=terminal.buffer.active;const lines=[];for(let y=0;y<terminal.rows;y++){const line=buffer.getLine(buffer.viewportY+y);const lineContent=line?line.translateToString(true):"";if(unwrapWrappedLines&&line?.isWrapped&&lines.length>0){lines[lines.length-1][0].text+=lineContent}else{lines.push(createPlainAnsiLine(lineContent))}}return lines},"serializePlainViewportToAnsiOutput");var WINDOWS_TASKKILL=`${process.env["SystemRoot"]||"C:\\Windows"}\\System32\\taskkill.exe`;var WINDOWS_TASKKILL_OPTIONS={windowsHide:true};var windowsKillPid=__name((pid,tree)=>{try{const args=tree?["/f","/t","/pid",pid.toString()]:["/f","/pid",pid.toString()];const killer=cpSpawn(WINDOWS_TASKKILL,args,WINDOWS_TASKKILL_OPTIONS);killer.on("error",e=>{debugLogger2.warn(`windowsKillPid: taskkill failed to launch for pid ${pid}: ${e.message}`)});killer.on("exit",(code,signal)=>{if(code!==0||signal){debugLogger2.warn(`windowsKillPid: taskkill exited non-zero for pid ${pid}: ${signal?`signal ${signal}`:`exit ${code}`}`)}})}catch(e){debugLogger2.warn(`windowsKillPid: taskkill spawn threw for pid ${pid}: ${e instanceof Error?e.message:String(e)}`)}},"windowsKillPid");var windowsStrategy={killPty:__name((pid,pty)=>{try{spawnSync(WINDOWS_TASKKILL,["/f","/t","/pid",pid.toString()],WINDOWS_TASKKILL_OPTIONS)}catch{}try{pty.ptyProcess.kill()}catch{}noteConPtyHostReleased(pty.ptyProcess)},"killPty"),killChildProcesses:__name(pids=>{if(pids.size>0){try{const args=["/f","/t"];for(const pid of pids){args.push("/pid",pid.toString())}spawnSync(WINDOWS_TASKKILL,args,WINDOWS_TASKKILL_OPTIONS)}catch{}}},"killChildProcesses")};var posixStrategy={killPty:__name((pid,_pty)=>{process.kill(-pid,"SIGKILL")},"killPty"),killChildProcesses:__name(pids=>{for(const pid of pids){try{process.kill(-pid,"SIGKILL")}catch{}}},"killChildProcesses")};var getCleanupStrategy=__name(()=>os2.platform()==="win32"?windowsStrategy:posixStrategy,"getCleanupStrategy");var ShellExecutionService=class _ShellExecutionService{static{__name(this,"ShellExecutionService")}static activePtys=new Map;static activeChildProcesses=new Set;static cleanup(){const strategy=getCleanupStrategy();for(const[pid,pty]of this.activePtys){try{strategy.killPty(pid,pty)}catch{}try{pty.headlessTerminal.dispose()}catch{}}strategy.killChildProcesses(this.activeChildProcesses)}static{process.on("exit",()=>{_ShellExecutionService.cleanup()})}static async execute(commandToExecute,cwd,onOutputEvent,abortSignal,shouldUseNodePty,shellExecutionConfig,options={}){return this.executeInternal(commandToExecute,cwd,onOutputEvent,abortSignal,shouldUseNodePty,shellExecutionConfig,options)}static async executeLaunch(launch,onOutputEvent,abortSignal,shouldUseNodePty,shellExecutionConfig,options={}){const snapshot={executable:launch.executable,args:[...launch.args],cwd:launch.cwd,env:{...launch.env},stdin:Buffer.isBuffer(launch.stdin)?Buffer.from(launch.stdin):launch.stdin,inheritStdin:launch.inheritStdin};if(!path.isAbsolute(snapshot.executable)||!path.isAbsolute(snapshot.cwd)){throw new Error("Process executable and cwd must be absolute.")}if([snapshot.executable,snapshot.cwd,...snapshot.args,...Object.values(snapshot.env)].some(value=>value.includes("\0"))||Object.keys(snapshot.env).some(key=>!key||key.includes("=")||key.includes("\0"))){throw new Error("Invalid process launch argument or environment.")}if(snapshot.stdin!==void 0&&snapshot.inheritStdin){throw new Error("Process stdin cannot be both piped and inherited.")}if(shouldUseNodePty&&(snapshot.stdin!==void 0||snapshot.inheritStdin)){throw new Error("Process stdin requires pipe execution.")}if(shouldUseNodePty&&!snapshot.env["TERM"]){throw new Error("PTY launch requires an explicit TERM environment value.")}if(shouldUseNodePty&&os2.platform()!=="win32"&&snapshot.env["PWD"]!==snapshot.cwd){throw new Error("PTY launch requires PWD to match cwd.")}return this.executeInternal(snapshot,snapshot.cwd,onOutputEvent,abortSignal,shouldUseNodePty,shellExecutionConfig,options)}static async executeInternal(commandToExecute,cwd,onOutputEvent,abortSignal,shouldUseNodePty,shellExecutionConfig,options){if(abortSignal.aborted){return createPreSpawnAbortedHandle()}if(shouldUseNodePty){let removeAbortListener;const ptyResult=Promise.resolve(getPty()).then(value=>({kind:"resolved",value}),error=>({kind:"rejected",error}));const aborted=new Promise(resolve=>{const onAbort=__name(()=>resolve({kind:"aborted"}),"onAbort");abortSignal.addEventListener("abort",onAbort,{once:true});removeAbortListener=__name(()=>abortSignal.removeEventListener("abort",onAbort),"removeAbortListener");if(abortSignal.aborted)onAbort()});const ptyOutcome=await Promise.race([ptyResult,aborted]);removeAbortListener?.();if(ptyOutcome.kind==="aborted"){return createPreSpawnAbortedHandle()}if(ptyOutcome.kind==="rejected"){throw ptyOutcome.error}if(abortSignal.aborted){return createPreSpawnAbortedHandle()}const ptyInfo=ptyOutcome.value;if(ptyInfo){try{const{Terminal}=await loadXtermHeadless();if(abortSignal.aborted){return createPreSpawnAbortedHandle()}return this.executeWithPty(commandToExecute,cwd,onOutputEvent,abortSignal,shellExecutionConfig,ptyInfo,Terminal,options.postPromote)}catch(_e){}}}if(abortSignal.aborted)return createPreSpawnAbortedHandle();return this.childProcessFallback(commandToExecute,cwd,onOutputEvent,abortSignal,options.streamStdout??false,options.streamRawOutput??false,getMaxBufferedOutputBytes(shellExecutionConfig),shellExecutionConfig.pager,options.postPromote,shellExecutionConfig.streamBufferedOutput,options.rawCapture)}static childProcessFallback(commandToExecute,cwd,onOutputEvent,abortSignal,streamStdout,streamRawOutput,maxBufferedOutputBytes,pager,postPromote,streamBufferedOutput=false,rawCapture){try{const isWindows=os2.platform()==="win32";const launch=typeof commandToExecute==="string"?void 0:commandToExecute;const{executable,args:shellArgs,shell}=launchCommand(commandToExecute);const child=cpSpawn(executable,shellArgs,{cwd,stdio:[launch?.inheritStdin?"inherit":launch?.stdin===void 0?"ignore":"pipe","pipe","pipe"],windowsVerbatimArguments:isWindows&&shell==="cmd",detached:!isWindows,windowsHide:isWindows,env:launch?{...launch.env}:{...normalizePathEnvForWindows(sanitizeChildEnv(process.env)),QWEN_CODE:"1",TERM:"xterm-256color",...getShellPagerEnv(pager,{includeGitPager:false,platform:os2.platform()}),...getShellContextEnvVars()}});const result=new Promise(resolve=>{let stdoutDecoder=null;let stderrDecoder=null;let stdout="";let stderr="";let stdoutPreview="";let stderrPreview="";const outputChunks=[];const sniffChunks=[];let error=null;let stdinError=null;let exited=false;let settled=false;let recordedExit=null;let drainTimer=null;let remainingDrainMs=POST_EXIT_STREAM_DRAIN_MS;let drainStartedAt=0;let stdoutHeld=false;let pendingCaptureWrites=0;let stdoutEnded=false;let stderrEnded=false;let stdoutWrite=Promise.resolve();let stderrWrite=Promise.resolve();const pauseDrain=__name(()=>{if(!drainTimer)return;clearTimeout(drainTimer);drainTimer=null;remainingDrainMs-=performance.now()-drainStartedAt},"pauseDrain");const resumeDrain=__name(()=>{if(!recordedExit||drainTimer||settled||pendingCaptureWrites){return}if(remainingDrainMs<=0){stdoutHeld=!stdoutEnded;void handleExit(recordedExit.code,recordedExit.signal);return}drainStartedAt=performance.now();drainTimer=setTimeout(()=>{drainTimer=null;stdoutHeld=!stdoutEnded;const recorded=recordedExit;if(recorded)void handleExit(recorded.code,recorded.signal)},remainingDrainMs);drainTimer.unref?.()},"resumeDrain");let isStreamingRawContent=true;const MAX_SNIFF_SIZE=4096;let sniffedBytes=0;let capturedOutputBytes=0;let totalOutputBytes=0;let outputCaptureLimitExceeded=false;let outputCaptureLimitWarningEmitted=false;const previewHeadBytes=rawCapture?Math.floor(maxBufferedOutputBytes/2):maxBufferedOutputBytes;const stderrTailBytes=rawCapture?Math.min(8192,Math.floor(maxBufferedOutputBytes/8)):0;const createTail=__name(capacity=>{const bytes=Buffer.alloc(capacity);let length=0;let position=0;return{add(data){if(bytes.length===0)return;if(data.length>=bytes.length){data.copy(bytes,0,data.length-bytes.length);length=bytes.length;position=0;return}const first=Math.min(data.length,bytes.length-position);data.copy(bytes,position,0,first);data.copy(bytes,0,first);position=(position+data.length)%bytes.length;length=Math.min(bytes.length,length+data.length)},read(){if(length===0)return Buffer.alloc(0);if(length<bytes.length)return bytes.subarray(0,length);return Buffer.concat([bytes.subarray(position),bytes.subarray(0,position)])}}},"createTail");let previewTail=rawCapture?createTail(maxBufferedOutputBytes-previewHeadBytes):null;let stderrTail=null;const retainedTail=__name(()=>previewTail?.read()??Buffer.alloc(0),"retainedTail");const completePreviewBytes=__name(()=>maxBufferedOutputBytes-(stderrTail?stderrTailBytes:0),"completePreviewBytes");const markOutputCaptureLimitExceeded=__name(()=>{if(rawCapture&&totalOutputBytes<=completePreviewBytes())return;outputCaptureLimitExceeded=true;if(outputCaptureLimitWarningEmitted){return}outputCaptureLimitWarningEmitted=true;debugLogger2.warn(`Shell output ${rawCapture?"preview":"capture"} exceeded ${rawCapture?completePreviewBytes():maxBufferedOutputBytes} bytes. Total bytes: ${totalOutputBytes}. ${rawCapture?"Truncating the preview.":"Discarding excess."}`)},"markOutputCaptureLimitExceeded");const captureOutputData=__name(data=>{if(capturedOutputBytes>=previewHeadBytes){markOutputCaptureLimitExceeded();return null}const remainingBytes=previewHeadBytes-capturedOutputBytes;const captured=data.length>remainingBytes?data.subarray(0,remainingBytes):data;if(captured.length>0){outputChunks.push(captured);capturedOutputBytes+=captured.length}if(captured.length<data.length){markOutputCaptureLimitExceeded()}return captured.length>0?captured:null},"captureOutputData");const handleOutput=__name((data,stream)=>{totalOutputBytes+=data.length;if(stream==="stderr"&&stderrTailBytes>0&&!stderrTail){const previous=retainedTail();previewTail=createTail(maxBufferedOutputBytes-previewHeadBytes-stderrTailBytes);previewTail.add(previous);stderrTail=createTail(stderrTailBytes)}previewTail?.add(data);if(stream==="stderr")stderrTail?.add(data);const capturedData=captureOutputData(data);if(streamRawOutput){onOutputEvent({type:"raw_data",chunk:Buffer.from(data),stream});return}if(!stdoutDecoder||!stderrDecoder){const encoding=getCachedEncodingForBuffer(data);try{stdoutDecoder=new TextDecoder(encoding);stderrDecoder=new TextDecoder(encoding)}catch{stdoutDecoder=new TextDecoder("utf-8");stderrDecoder=new TextDecoder("utf-8")}}if(isStreamingRawContent&&sniffedBytes<MAX_SNIFF_SIZE){const sniffSlice=data.subarray(0,Math.min(data.length,MAX_SNIFF_SIZE-sniffedBytes));if(sniffSlice.length>0){sniffChunks.push(sniffSlice);sniffedBytes+=sniffSlice.length}const sniffBuffer=Buffer.concat(sniffChunks);if(isBinary(sniffBuffer)){isStreamingRawContent=false;if(streamStdout){onOutputEvent({type:"binary_detected"});sniffChunks.length=0}}else if(streamStdout&&sniffedBytes>=MAX_SNIFF_SIZE){sniffChunks.length=0}}if(!isStreamingRawContent){return}const decoder=stream==="stdout"?stdoutDecoder:stderrDecoder;if(streamStdout){const decodedChunk2=decoder.decode(data,{stream:true});onOutputEvent({type:"data",chunk:decodedChunk2,stream});return}if(!capturedData){return}const decodedChunk=decoder.decode(capturedData,{stream:true});if(stream==="stdout"){stdout+=decodedChunk}else{stderr+=decodedChunk}if(streamBufferedOutput){if(stream==="stdout"){stdoutPreview=(stdoutPreview+decodedChunk.slice(-65536)).slice(-65536)}else{stderrPreview=(stderrPreview+decodedChunk.slice(-65536)).slice(-65536)}const separator=stdoutPreview.endsWith("\n")?"":"\n";const snapshot=stdoutPreview+(stderrPreview?(stdoutPreview?separator:"")+stderrPreview:"");onOutputEvent({type:"data",chunk:stripAnsi(snapshot).slice(-65536)})}},"handleOutput");const handleExit=__name(async(code,signal)=>{if(settled)return;settled=true;if(drainTimer){clearTimeout(drainTimer);drainTimer=null}if(rawCapture){await Promise.all([stdoutWrite,stderrWrite]);const finished=await Promise.allSettled([rawCapture.finish("stdout",stdoutEnded),rawCapture.finish("stderr",stderrEnded)]);for(const result2 of finished){if(result2.status==="rejected"){debugLogger2.warn("Shell raw capture finish failed",result2.reason)}}}const{finalBuffer}=cleanup();const separator=stdout.endsWith("\n")?"":"\n";const combinedOutput=stdout+(stderr?(stdout?separator:"")+stderr:"");const finalStrippedOutput=stripAnsi(combinedOutput).trim();const stderrPreview2=stderrTail?.read()??Buffer.alloc(0);const tailPreview=retainedTail();const tailText=rawCapture?stripAnsi(decodePreviewTail(tailPreview)).trim():"";const stderrText=stderrPreview2.length?stripAnsi(decodePreviewTail(stderrPreview2)).trim():"";const boundedOutput=rawCapture&&isStreamingRawContent&&totalOutputBytes>previewHeadBytes?totalOutputBytes<=completePreviewBytes()?stripAnsi(decodeBufferedOutput(Buffer.concat([finalBuffer,tailPreview.subarray(-(totalOutputBytes-capturedOutputBytes))]))).trim():`${finalStrippedOutput}
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{captureEnvironmentBeforeLoad,publishPendingCompileCache,resetEnvironmentSnapshotForTesting}from"./chunk-PKK2D2W4.js";import{DEFAULT_EXCLUDED_ENV_VARS,HOME_ENV_BOOTSTRAP_KEYS,PROJECT_ENV_HARDCODED_EXCLUSIONS,VERIFY_PR_COORDINATE_ENV,isHardcodedProjectEnvExclusion,isLoaderEnvKey,isPrivateProvenanceEnvKey,keepsEmptyHomeEnvValue,reportRejectedLoaderKeys,resetLoaderKeyRejectionReportingForTesting}from"./chunk-AJTR5LAF.js";import{isWorkspaceTrusted}from"./chunk-T4P4FF3I.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{require_main}from"./chunk-HW7ZRPZU.js";import{PRIVATE_RELAUNCH_ENV_PROVENANCE}from"./chunk-3ITJ3AIN.js";import{writeStderrLineSafe}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{QWEN_DIR}from"./chunk-2ZK2FGZQ.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();var dotenv=__toESM(require_main(),1);import*as fs from"node:fs";import*as path from"node:path";import*as os from"node:os";var SETTINGS_DIRECTORY_NAME=QWEN_DIR;var RELOAD_EXCLUDED_KEYS=new Set([...PROJECT_ENV_HARDCODED_EXCLUSIONS,"LD_LIBRARY_PATH","DYLD_LIBRARY_PATH","ENV","PATH","HOME"]);var RELOAD_EXCLUDED_KEYS_CASEFOLDED=new Set([...RELOAD_EXCLUDED_KEYS].map(key=>key.toLowerCase()));function isReloadExcludedKey(key){return RELOAD_EXCLUDED_KEYS_CASEFOLDED.has(key.toLowerCase())||isHardcodedProjectEnvExclusion(key)}__name(isReloadExcludedKey,"isReloadExcludedKey");var dotEnvSourcedKeys=new Set;var settingsEnvSourcedKeys=new Set;var inheritedDotEnvKeys=new Set;var inheritedSettingsEnvKeys=new Set;var inheritedProvenance=process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];if(inheritedProvenance){const sources=JSON.parse(inheritedProvenance);if(!sources||typeof sources!=="object"||!("dotEnv"in sources)||!("settingsEnv"in sources)||!Array.isArray(sources.dotEnv)||!Array.isArray(sources.settingsEnv)||!sources.dotEnv.every(key=>typeof key==="string")||!sources.settingsEnv.every(key=>typeof key==="string")){throw new Error("Invalid inherited environment provenance.")}for(const key of sources.dotEnv)inheritedDotEnvKeys.add(key);for(const key of sources.settingsEnv)inheritedSettingsEnvKeys.add(key);Object.assign(process.env,getRelaunchEnvProvenance())}var DOCUMENTED_MODEL_ENV_KEYS=["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_MODEL","QWEN_MODEL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","GEMINI_API_KEY","GEMINI_MODEL","GOOGLE_API_KEY","GOOGLE_MODEL"];var requestTimeEnvKeys=new Set;function rememberRequestTimeEnvKeys(settings){requestTimeEnvKeys.clear();for(const key of DOCUMENTED_MODEL_ENV_KEYS)requestTimeEnvKeys.add(key);for(const models of Object.values(settings.modelProviders??{})){if(!Array.isArray(models))continue;for(const model of models){const envKey=model?.envKey;if(typeof envKey==="string"&&envKey&&!isHardcodedProjectEnvExclusion(envKey)&&!isLoaderEnvKey(envKey)){requestTimeEnvKeys.add(envKey)}}}}__name(rememberRequestTimeEnvKeys,"rememberRequestTimeEnvKeys");function hasLoadedEnvironmentValues(){for(const keys of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of keys){if(!requestTimeEnvKeys.has(key))return true}}return false}__name(hasLoadedEnvironmentValues,"hasLoadedEnvironmentValues");function getRelaunchEnvProvenance(){return{[PRIVATE_RELAUNCH_ENV_PROVENANCE]:JSON.stringify({dotEnv:[...new Set([...inheritedDotEnvKeys,...dotEnvSourcedKeys])],settingsEnv:[...new Set([...inheritedSettingsEnvKeys,...settingsEnvSourcedKeys])]})}}__name(getRelaunchEnvProvenance,"getRelaunchEnvProvenance");var lastReloadSnapshot=new Map;var lastReloadSnapshotSeeded=false;function getUserLevelEnvPaths(){const homeDir=os.homedir();const globalQwenDir=Storage.getGlobalQwenDir();const paths=new Set([path.normalize(path.join(homeDir,".env")),path.normalize(path.join(globalQwenDir,".env"))]);const legacyQwenEnv=path.normalize(path.join(homeDir,QWEN_DIR,".env"));paths.add(legacyQwenEnv);return paths}__name(getUserLevelEnvPaths,"getUserLevelEnvPaths");var homeEnvBootstrapped=false;function preResolveHomeEnvOverrides(){if(homeEnvBootstrapped){return}homeEnvBootstrapped=true;if(HOME_ENV_BOOTSTRAP_KEYS.every(key=>process.env[key])){return}const initialQwenHome=process.env["QWEN_HOME"];const initialQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(initialQwenDir,".env")];if(!initialQwenHome){candidates.push(path.join(path.dirname(initialQwenDir),".env"))}for(const candidate of candidates){readHomeEnvInto(candidate)}const discoveredQwenHome=process.env["QWEN_HOME"];if(discoveredQwenHome&&discoveredQwenHome!==initialQwenHome){const discoveredDir=Storage.getGlobalQwenDir();if(discoveredDir!==initialQwenDir){readHomeEnvInto(path.join(discoveredDir,".env"))}}}__name(preResolveHomeEnvOverrides,"preResolveHomeEnvOverrides");function readHomeEnvInto(file){if(!fs.existsSync(file)){return}try{const parsed=dotenv.parse(fs.readFileSync(file,"utf-8"));for(const key of HOME_ENV_BOOTSTRAP_KEYS){if((parsed[key]||keepsEmptyHomeEnvValue(key)&&parsed[key]!==void 0)&&!Object.hasOwn(process.env,key)){process.env[key]=parsed[key]}}}catch(_e){}}__name(readHomeEnvInto,"readHomeEnvInto");function resetHomeEnvBootstrapForTesting(){homeEnvBootstrapped=false}__name(resetHomeEnvBootstrapForTesting,"resetHomeEnvBootstrapForTesting");function resetEnvironmentTrackingForTesting(){resetLoaderKeyRejectionReportingForTesting();resetEnvironmentSnapshotForTesting();dotEnvSourcedKeys.clear();settingsEnvSourcedKeys.clear();inheritedDotEnvKeys.clear();inheritedSettingsEnvKeys.clear();requestTimeEnvKeys.clear();delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];lastReloadSnapshot.clear();lastReloadSnapshotSeeded=false}__name(resetEnvironmentTrackingForTesting,"resetEnvironmentTrackingForTesting");function isFileSourcedEnvKey(key){const sources=[dotEnvSourcedKeys,settingsEnvSourcedKeys,inheritedDotEnvKeys,inheritedSettingsEnvKeys];if(sources.some(keys=>keys.has(key))){return true}if(process.platform!=="win32")return false;const lower=key.toLowerCase();for(const keys of sources){for(const tracked of keys){if(tracked.toLowerCase()===lower)return true}}return false}__name(isFileSourcedEnvKey,"isFileSourcedEnvKey");function getHomeEnvFallbackVars(onReadError){const globalQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(globalQwenDir,".env")];if(!process.env["QWEN_HOME"]){candidates.push(path.join(path.dirname(globalQwenDir),".env"))}const result={};for(const candidate of candidates){if(!fs.existsSync(candidate)){continue}try{const parsed=dotenv.parse(fs.readFileSync(candidate,"utf-8"));for(const key in parsed){if(Object.hasOwn(parsed,key)&&!Object.hasOwn(process.env,key)){result[key]??=parsed[key]}}}catch(e){onReadError?.(`Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`)}}return result}__name(getHomeEnvFallbackVars,"getHomeEnvFallbackVars");function findEnvFiles(settings,startDir,userLevelPaths=getUserLevelEnvPaths(),workspaceTrusted){const homeDir=os.homedir();let realStartDir=path.resolve(startDir);try{realStartDir=fs.realpathSync(realStartDir)}catch{}const globalQwenDir=Storage.getGlobalQwenDir();const legacyQwenDir=path.normalize(path.join(homeDir,QWEN_DIR));const hasCustomConfigDir=path.normalize(globalQwenDir)!==legacyQwenDir;const found=[];const seen=new Set;const workspaceIsTrusted=workspaceTrusted??isWorkspaceTrusted(settings,void 0,realStartDir).isTrusted===true;const canUseEnvFile=__name(filePath=>{const normalized=path.normalize(filePath);if(userLevelPaths.has(normalized))return true;if(!workspaceIsTrusted)return false;const dirPath=path.dirname(normalized);const workspaceDir=path.basename(dirPath)===SETTINGS_DIRECTORY_NAME?path.dirname(dirPath):dirPath;if(workspaceDir===realStartDir)return true;return isWorkspaceTrusted(settings,void 0,workspaceDir).isTrusted!==false},"canUseEnvFile");const pushCandidate=__name(filePath=>{const normalized=path.normalize(filePath);if(!seen.has(normalized)&&fs.existsSync(filePath)&&canUseEnvFile(filePath)){seen.add(normalized);found.push(filePath);return true}return false},"pushCandidate");const pushHomeCandidates=__name(()=>{const candidates=[path.join(globalQwenDir,".env")];if(hasCustomConfigDir){candidates.push(path.join(legacyQwenDir,".env"))}candidates.push(path.join(homeDir,".env"));for(const candidate of candidates){pushCandidate(candidate)}},"pushHomeCandidates");if(path.resolve(startDir)===path.resolve(homeDir)){pushHomeCandidates();return found}let currentDir=realStartDir;let visitedHomeDir=false;while(true){if(currentDir===homeDir){visitedHomeDir=true;pushHomeCandidates();return found}else{const geminiEnvPath=path.join(currentDir,QWEN_DIR,".env");if(pushCandidate(geminiEnvPath)){pushHomeCandidates();return found}const envPath=path.join(currentDir,".env");if(pushCandidate(envPath)){pushHomeCandidates();return found}}const parentDir=path.dirname(currentDir);if(parentDir===currentDir||!parentDir){if(!visitedHomeDir){pushHomeCandidates()}return found}currentDir=parentDir}}__name(findEnvFiles,"findEnvFiles");function setUpCloudShellEnvironment(envFilePath){if(envFilePath&&fs.existsSync(envFilePath)){const envFileContent=fs.readFileSync(envFilePath);const parsedEnv=dotenv.parse(envFileContent);if(parsedEnv["GOOGLE_CLOUD_PROJECT"]){process.env["GOOGLE_CLOUD_PROJECT"]=parsedEnv["GOOGLE_CLOUD_PROJECT"]}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}__name(setUpCloudShellEnvironment,"setUpCloudShellEnvironment");function setUpCloudShellEnvironmentInEnv(env,envFiles){for(const envFile of envFiles){if(envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"]){env["GOOGLE_CLOUD_PROJECT"]=envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"];return}}env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}__name(setUpCloudShellEnvironmentInEnv,"setUpCloudShellEnvironmentInEnv");function readProjectEnvFiles(settings,startDir,workspaceTrusted){const userLevelPaths=getUserLevelEnvPaths();let workspaceRoot=path.resolve(startDir);try{workspaceRoot=fs.realpathSync(workspaceRoot)}catch{}const isInsideWorkspace=__name(filePath=>{let resolved;try{resolved=fs.realpathSync(filePath)}catch{return false}return isWithinRoot(resolved,workspaceRoot)},"isInsideWorkspace");const files={};for(const file of findEnvFiles(settings,startDir,userLevelPaths,workspaceTrusted)){if(userLevelPaths.has(path.normalize(file)))continue;if(!isInsideWorkspace(file))continue;try{files[file]=dotenv.parse(fs.readFileSync(file,"utf-8"))}catch{files[file]=null}}return files}__name(readProjectEnvFiles,"readProjectEnvFiles");function parseEnvFiles(envFilePaths,userLevelPaths){const files=[];const readFailures=[];for(const envFilePath of envFilePaths){try{const envFileContent=fs.readFileSync(envFilePath,"utf-8");const parsedEnv=dotenv.parse(envFileContent);const normalizedEnvFilePath=path.normalize(envFilePath);const isHomeScopedEnvFile=userLevelPaths.has(normalizedEnvFilePath);const isQwenScopedEnvFile=isHomeScopedEnvFile||path.basename(path.dirname(normalizedEnvFilePath))===QWEN_DIR;files.push({path:envFilePath,parsedEnv,isHomeScopedEnvFile,isQwenScopedEnvFile})}catch(err){readFailures.push({path:envFilePath,error:getErrorMessage(err)})}}return{files,readFailed:readFailures.length>0,readFailures}}__name(parseEnvFiles,"parseEnvFiles");function canApplyParsedEnvKey(envFile,key,excludedVars,options={}){if(!Object.hasOwn(envFile.parsedEnv,key))return false;if(isLoaderEnvKey(key))return false;if(isPrivateProvenanceEnvKey(key))return false;if(options.reload&&isReloadExcludedKey(key))return false;if(!envFile.isHomeScopedEnvFile&&isHardcodedProjectEnvExclusion(key)){return false}return envFile.isQwenScopedEnvFile||!excludedVars.includes(key)}__name(canApplyParsedEnvKey,"canApplyParsedEnvKey");function isEffectivelyUnset(env,key){const existingValue=env[key];return!Object.hasOwn(env,key)||existingValue===""}__name(isEffectivelyUnset,"isEffectivelyUnset");function setRuntimeEnvIfUnset(env,key,value){if(isEffectivelyUnset(env,key)){env[key]=value}}__name(setRuntimeEnvIfUnset,"setRuntimeEnvIfUnset");function reportRejectedSettingsEnv(env,startDir){const source=`settings.env (${startDir})`;reportRejectedLoaderKeys(source,Object.keys(env));if(Object.entries(env).some(([key,value])=>key.toUpperCase()==="QWEN_AGENT_EXECUTION_BACKEND"&&typeof value==="string"&&value.trim()!=="")){writeStderrLineSafe(`qwen: ${source} cannot set QWEN_AGENT_EXECUTION_BACKEND; ignored. Export it in the launch environment instead.`)}for(const[setting,key]of Object.entries(VERIFY_PR_COORDINATE_ENV)){const entry=Object.entries(env).find(([candidate,value])=>candidate.toUpperCase()===key&&typeof value==="string"&&value.trim()!=="");if(!entry)continue;writeStderrLineSafe(`qwen: ${source} cannot set ${entry[0]}; ignored. Set verifyPr.${setting} at user scope in settings.json, or export it in the launch environment.`)}}__name(reportRejectedSettingsEnv,"reportRejectedSettingsEnv");function buildRuntimeEnvironment(settings,startDir=process.cwd(),baseEnv=process.env,workspaceTrusted){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);const effectiveEnv={...baseEnv};if(baseEnv["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(effectiveEnv,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}setRuntimeEnvIfUnset(effectiveEnv,key,envFile.parsedEnv[key])}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(excludedVars.includes(key))continue;if(typeof value!=="string")continue;setRuntimeEnvIfUnset(effectiveEnv,key,value)}reportRejectedSettingsEnv(settings.env,startDir)}const overlayKeys=Object.keys(effectiveEnv).filter(key=>effectiveEnv[key]!==baseEnv[key]).sort();return{effectiveEnv:Object.freeze({...effectiveEnv}),overlayKeys:Object.freeze(overlayKeys),envFilePaths:Object.freeze([...envFilePaths]),envFileReadFailed:parsedEnvFiles.readFailed,envFileReadFailures:Object.freeze([...parsedEnvFiles.readFailures])}}__name(buildRuntimeEnvironment,"buildRuntimeEnvironment");function loadEnvironment(settings,startDir=process.cwd()){captureEnvironmentBeforeLoad();rememberRequestTimeEnvKeys(settings);const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars))continue;const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue===""&&!keepsEmptyHomeEnvValue(key);if(isEffectivelyUnset2){process.env[key]=envFile.parsedEnv[key];dotEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key)){continue}if(isReloadExcludedKey(key)){continue}if(isHardcodedProjectEnvExclusion(key)){continue}const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2&&typeof value==="string"){process.env[key]=value;settingsEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&typeof value==="string"&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,value)}}reportRejectedSettingsEnv(settings.env,startDir)}lastReloadSnapshotSeeded=true;Object.assign(process.env,getRelaunchEnvProvenance());publishPendingCompileCache()}__name(loadEnvironment,"loadEnvironment");function reloadEnvironment(settings,workspaceCwd,workspaceTrusted,options={}){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,workspaceCwd,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(parsedEnvFiles.readFailed&&options.failClosedOnEnvFileReadError){return{updatedKeys:[],removedKeys:[],envFileReadFailed:true}}if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}const dotEnvReadFailed=parsedEnvFiles.readFailed;const newDotEnvKeys=new Map;const newSettingsEnvKeys=new Map;for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}if(!newDotEnvKeys.has(key)){newDotEnvKeys.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(typeof value!=="string")continue;const dotEnvValue=newDotEnvKeys.get(key);if(dotEnvValue!==void 0&&dotEnvValue!=="")continue;if(dotEnvReadFailed&&lastReloadSnapshot.has(key))continue;newSettingsEnvKeys.set(key,value)}reportRejectedSettingsEnv(settings.env,workspaceCwd)}const allNewKeys=new Set([...newDotEnvKeys.keys(),...newSettingsEnvKeys.keys()]);const updatedKeys=[];const removedKeys=[];if(!dotEnvReadFailed){const previouslyKnown=new Set([...lastReloadSnapshot.keys(),...dotEnvSourcedKeys,...settingsEnvSourcedKeys]);for(const key of previouslyKnown){if(!allNewKeys.has(key)&&!isReloadExcludedKey(key)){delete process.env[key];inheritedDotEnvKeys.delete(key);inheritedSettingsEnvKeys.delete(key);removedKeys.push(key)}}}for(const[key,value]of newDotEnvKeys){if(value===""&&newSettingsEnvKeys.has(key))continue;if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}for(const[key,value]of newSettingsEnvKeys){if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}if(!dotEnvReadFailed){for(const sources of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of sources){if(!isReloadExcludedKey(key))sources.delete(key)}}lastReloadSnapshot.clear();for(const[key,value]of newDotEnvKeys){lastReloadSnapshot.set(key,value)}for(const[key,value]of newSettingsEnvKeys){lastReloadSnapshot.set(key,value)}}for(const key of newDotEnvKeys.keys()){dotEnvSourcedKeys.add(key)}for(const key of newSettingsEnvKeys.keys()){settingsEnvSourcedKeys.add(key)}Object.assign(process.env,getRelaunchEnvProvenance());return{updatedKeys,removedKeys,...dotEnvReadFailed?{envFileReadFailed:true}:{}}}__name(reloadEnvironment,"reloadEnvironment");export{SETTINGS_DIRECTORY_NAME,hasLoadedEnvironmentValues,getRelaunchEnvProvenance,preResolveHomeEnvOverrides,resetHomeEnvBootstrapForTesting,resetEnvironmentTrackingForTesting,isFileSourcedEnvKey,getHomeEnvFallbackVars,findEnvFiles,setUpCloudShellEnvironment,readProjectEnvFiles,buildRuntimeEnvironment,loadEnvironment,reloadEnvironment};
|
|
3
|
+
import{captureEnvironmentBeforeLoad,publishPendingCompileCache,resetEnvironmentSnapshotForTesting}from"./chunk-PKK2D2W4.js";import{DEFAULT_EXCLUDED_ENV_VARS,HOME_ENV_BOOTSTRAP_KEYS,PROJECT_ENV_HARDCODED_EXCLUSIONS,VERIFY_PR_COORDINATE_ENV,isHardcodedProjectEnvExclusion,isLoaderEnvKey,isPrivateProvenanceEnvKey,keepsEmptyHomeEnvValue,reportRejectedLoaderKeys,resetLoaderKeyRejectionReportingForTesting}from"./chunk-AJTR5LAF.js";import{isWorkspaceTrusted}from"./chunk-WZTO3EYG.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{require_main}from"./chunk-HW7ZRPZU.js";import{PRIVATE_RELAUNCH_ENV_PROVENANCE}from"./chunk-3ITJ3AIN.js";import{writeStderrLineSafe}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{QWEN_DIR}from"./chunk-2ZK2FGZQ.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();var dotenv=__toESM(require_main(),1);import*as fs from"node:fs";import*as path from"node:path";import*as os from"node:os";var SETTINGS_DIRECTORY_NAME=QWEN_DIR;var RELOAD_EXCLUDED_KEYS=new Set([...PROJECT_ENV_HARDCODED_EXCLUSIONS,"LD_LIBRARY_PATH","DYLD_LIBRARY_PATH","ENV","PATH","HOME"]);var RELOAD_EXCLUDED_KEYS_CASEFOLDED=new Set([...RELOAD_EXCLUDED_KEYS].map(key=>key.toLowerCase()));function isReloadExcludedKey(key){return RELOAD_EXCLUDED_KEYS_CASEFOLDED.has(key.toLowerCase())||isHardcodedProjectEnvExclusion(key)}__name(isReloadExcludedKey,"isReloadExcludedKey");var dotEnvSourcedKeys=new Set;var settingsEnvSourcedKeys=new Set;var inheritedDotEnvKeys=new Set;var inheritedSettingsEnvKeys=new Set;var inheritedProvenance=process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];if(inheritedProvenance){const sources=JSON.parse(inheritedProvenance);if(!sources||typeof sources!=="object"||!("dotEnv"in sources)||!("settingsEnv"in sources)||!Array.isArray(sources.dotEnv)||!Array.isArray(sources.settingsEnv)||!sources.dotEnv.every(key=>typeof key==="string")||!sources.settingsEnv.every(key=>typeof key==="string")){throw new Error("Invalid inherited environment provenance.")}for(const key of sources.dotEnv)inheritedDotEnvKeys.add(key);for(const key of sources.settingsEnv)inheritedSettingsEnvKeys.add(key);Object.assign(process.env,getRelaunchEnvProvenance())}var DOCUMENTED_MODEL_ENV_KEYS=["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_MODEL","QWEN_MODEL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","GEMINI_API_KEY","GEMINI_MODEL","GOOGLE_API_KEY","GOOGLE_MODEL"];var requestTimeEnvKeys=new Set;function rememberRequestTimeEnvKeys(settings){requestTimeEnvKeys.clear();for(const key of DOCUMENTED_MODEL_ENV_KEYS)requestTimeEnvKeys.add(key);for(const models of Object.values(settings.modelProviders??{})){if(!Array.isArray(models))continue;for(const model of models){const envKey=model?.envKey;if(typeof envKey==="string"&&envKey&&!isHardcodedProjectEnvExclusion(envKey)&&!isLoaderEnvKey(envKey)){requestTimeEnvKeys.add(envKey)}}}}__name(rememberRequestTimeEnvKeys,"rememberRequestTimeEnvKeys");function hasLoadedEnvironmentValues(){for(const keys of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of keys){if(!requestTimeEnvKeys.has(key))return true}}return false}__name(hasLoadedEnvironmentValues,"hasLoadedEnvironmentValues");function getRelaunchEnvProvenance(){return{[PRIVATE_RELAUNCH_ENV_PROVENANCE]:JSON.stringify({dotEnv:[...new Set([...inheritedDotEnvKeys,...dotEnvSourcedKeys])],settingsEnv:[...new Set([...inheritedSettingsEnvKeys,...settingsEnvSourcedKeys])]})}}__name(getRelaunchEnvProvenance,"getRelaunchEnvProvenance");var lastReloadSnapshot=new Map;var lastReloadSnapshotSeeded=false;function getUserLevelEnvPaths(){const homeDir=os.homedir();const globalQwenDir=Storage.getGlobalQwenDir();const paths=new Set([path.normalize(path.join(homeDir,".env")),path.normalize(path.join(globalQwenDir,".env"))]);const legacyQwenEnv=path.normalize(path.join(homeDir,QWEN_DIR,".env"));paths.add(legacyQwenEnv);return paths}__name(getUserLevelEnvPaths,"getUserLevelEnvPaths");var homeEnvBootstrapped=false;function preResolveHomeEnvOverrides(){if(homeEnvBootstrapped){return}homeEnvBootstrapped=true;if(HOME_ENV_BOOTSTRAP_KEYS.every(key=>process.env[key])){return}const initialQwenHome=process.env["QWEN_HOME"];const initialQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(initialQwenDir,".env")];if(!initialQwenHome){candidates.push(path.join(path.dirname(initialQwenDir),".env"))}for(const candidate of candidates){readHomeEnvInto(candidate)}const discoveredQwenHome=process.env["QWEN_HOME"];if(discoveredQwenHome&&discoveredQwenHome!==initialQwenHome){const discoveredDir=Storage.getGlobalQwenDir();if(discoveredDir!==initialQwenDir){readHomeEnvInto(path.join(discoveredDir,".env"))}}}__name(preResolveHomeEnvOverrides,"preResolveHomeEnvOverrides");function readHomeEnvInto(file){if(!fs.existsSync(file)){return}try{const parsed=dotenv.parse(fs.readFileSync(file,"utf-8"));for(const key of HOME_ENV_BOOTSTRAP_KEYS){if((parsed[key]||keepsEmptyHomeEnvValue(key)&&parsed[key]!==void 0)&&!Object.hasOwn(process.env,key)){process.env[key]=parsed[key]}}}catch(_e){}}__name(readHomeEnvInto,"readHomeEnvInto");function resetHomeEnvBootstrapForTesting(){homeEnvBootstrapped=false}__name(resetHomeEnvBootstrapForTesting,"resetHomeEnvBootstrapForTesting");function resetEnvironmentTrackingForTesting(){resetLoaderKeyRejectionReportingForTesting();resetEnvironmentSnapshotForTesting();dotEnvSourcedKeys.clear();settingsEnvSourcedKeys.clear();inheritedDotEnvKeys.clear();inheritedSettingsEnvKeys.clear();requestTimeEnvKeys.clear();delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];lastReloadSnapshot.clear();lastReloadSnapshotSeeded=false}__name(resetEnvironmentTrackingForTesting,"resetEnvironmentTrackingForTesting");function isFileSourcedEnvKey(key){const sources=[dotEnvSourcedKeys,settingsEnvSourcedKeys,inheritedDotEnvKeys,inheritedSettingsEnvKeys];if(sources.some(keys=>keys.has(key))){return true}if(process.platform!=="win32")return false;const lower=key.toLowerCase();for(const keys of sources){for(const tracked of keys){if(tracked.toLowerCase()===lower)return true}}return false}__name(isFileSourcedEnvKey,"isFileSourcedEnvKey");function getHomeEnvFallbackVars(onReadError){const globalQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(globalQwenDir,".env")];if(!process.env["QWEN_HOME"]){candidates.push(path.join(path.dirname(globalQwenDir),".env"))}const result={};for(const candidate of candidates){if(!fs.existsSync(candidate)){continue}try{const parsed=dotenv.parse(fs.readFileSync(candidate,"utf-8"));for(const key in parsed){if(Object.hasOwn(parsed,key)&&!Object.hasOwn(process.env,key)){result[key]??=parsed[key]}}}catch(e){onReadError?.(`Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`)}}return result}__name(getHomeEnvFallbackVars,"getHomeEnvFallbackVars");function findEnvFiles(settings,startDir,userLevelPaths=getUserLevelEnvPaths(),workspaceTrusted){const homeDir=os.homedir();let realStartDir=path.resolve(startDir);try{realStartDir=fs.realpathSync(realStartDir)}catch{}const globalQwenDir=Storage.getGlobalQwenDir();const legacyQwenDir=path.normalize(path.join(homeDir,QWEN_DIR));const hasCustomConfigDir=path.normalize(globalQwenDir)!==legacyQwenDir;const found=[];const seen=new Set;const workspaceIsTrusted=workspaceTrusted??isWorkspaceTrusted(settings,void 0,realStartDir).isTrusted===true;const canUseEnvFile=__name(filePath=>{const normalized=path.normalize(filePath);if(userLevelPaths.has(normalized))return true;if(!workspaceIsTrusted)return false;const dirPath=path.dirname(normalized);const workspaceDir=path.basename(dirPath)===SETTINGS_DIRECTORY_NAME?path.dirname(dirPath):dirPath;if(workspaceDir===realStartDir)return true;return isWorkspaceTrusted(settings,void 0,workspaceDir).isTrusted!==false},"canUseEnvFile");const pushCandidate=__name(filePath=>{const normalized=path.normalize(filePath);if(!seen.has(normalized)&&fs.existsSync(filePath)&&canUseEnvFile(filePath)){seen.add(normalized);found.push(filePath);return true}return false},"pushCandidate");const pushHomeCandidates=__name(()=>{const candidates=[path.join(globalQwenDir,".env")];if(hasCustomConfigDir){candidates.push(path.join(legacyQwenDir,".env"))}candidates.push(path.join(homeDir,".env"));for(const candidate of candidates){pushCandidate(candidate)}},"pushHomeCandidates");if(path.resolve(startDir)===path.resolve(homeDir)){pushHomeCandidates();return found}let currentDir=realStartDir;let visitedHomeDir=false;while(true){if(currentDir===homeDir){visitedHomeDir=true;pushHomeCandidates();return found}else{const geminiEnvPath=path.join(currentDir,QWEN_DIR,".env");if(pushCandidate(geminiEnvPath)){pushHomeCandidates();return found}const envPath=path.join(currentDir,".env");if(pushCandidate(envPath)){pushHomeCandidates();return found}}const parentDir=path.dirname(currentDir);if(parentDir===currentDir||!parentDir){if(!visitedHomeDir){pushHomeCandidates()}return found}currentDir=parentDir}}__name(findEnvFiles,"findEnvFiles");function setUpCloudShellEnvironment(envFilePath){if(envFilePath&&fs.existsSync(envFilePath)){const envFileContent=fs.readFileSync(envFilePath);const parsedEnv=dotenv.parse(envFileContent);if(parsedEnv["GOOGLE_CLOUD_PROJECT"]){process.env["GOOGLE_CLOUD_PROJECT"]=parsedEnv["GOOGLE_CLOUD_PROJECT"]}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}__name(setUpCloudShellEnvironment,"setUpCloudShellEnvironment");function setUpCloudShellEnvironmentInEnv(env,envFiles){for(const envFile of envFiles){if(envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"]){env["GOOGLE_CLOUD_PROJECT"]=envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"];return}}env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}__name(setUpCloudShellEnvironmentInEnv,"setUpCloudShellEnvironmentInEnv");function readProjectEnvFiles(settings,startDir,workspaceTrusted){const userLevelPaths=getUserLevelEnvPaths();let workspaceRoot=path.resolve(startDir);try{workspaceRoot=fs.realpathSync(workspaceRoot)}catch{}const isInsideWorkspace=__name(filePath=>{let resolved;try{resolved=fs.realpathSync(filePath)}catch{return false}return isWithinRoot(resolved,workspaceRoot)},"isInsideWorkspace");const files={};for(const file of findEnvFiles(settings,startDir,userLevelPaths,workspaceTrusted)){if(userLevelPaths.has(path.normalize(file)))continue;if(!isInsideWorkspace(file))continue;try{files[file]=dotenv.parse(fs.readFileSync(file,"utf-8"))}catch{files[file]=null}}return files}__name(readProjectEnvFiles,"readProjectEnvFiles");function parseEnvFiles(envFilePaths,userLevelPaths){const files=[];const readFailures=[];for(const envFilePath of envFilePaths){try{const envFileContent=fs.readFileSync(envFilePath,"utf-8");const parsedEnv=dotenv.parse(envFileContent);const normalizedEnvFilePath=path.normalize(envFilePath);const isHomeScopedEnvFile=userLevelPaths.has(normalizedEnvFilePath);const isQwenScopedEnvFile=isHomeScopedEnvFile||path.basename(path.dirname(normalizedEnvFilePath))===QWEN_DIR;files.push({path:envFilePath,parsedEnv,isHomeScopedEnvFile,isQwenScopedEnvFile})}catch(err){readFailures.push({path:envFilePath,error:getErrorMessage(err)})}}return{files,readFailed:readFailures.length>0,readFailures}}__name(parseEnvFiles,"parseEnvFiles");function canApplyParsedEnvKey(envFile,key,excludedVars,options={}){if(!Object.hasOwn(envFile.parsedEnv,key))return false;if(isLoaderEnvKey(key))return false;if(isPrivateProvenanceEnvKey(key))return false;if(options.reload&&isReloadExcludedKey(key))return false;if(!envFile.isHomeScopedEnvFile&&isHardcodedProjectEnvExclusion(key)){return false}return envFile.isQwenScopedEnvFile||!excludedVars.includes(key)}__name(canApplyParsedEnvKey,"canApplyParsedEnvKey");function isEffectivelyUnset(env,key){const existingValue=env[key];return!Object.hasOwn(env,key)||existingValue===""}__name(isEffectivelyUnset,"isEffectivelyUnset");function setRuntimeEnvIfUnset(env,key,value){if(isEffectivelyUnset(env,key)){env[key]=value}}__name(setRuntimeEnvIfUnset,"setRuntimeEnvIfUnset");function reportRejectedSettingsEnv(env,startDir){const source=`settings.env (${startDir})`;reportRejectedLoaderKeys(source,Object.keys(env));if(Object.entries(env).some(([key,value])=>key.toUpperCase()==="QWEN_AGENT_EXECUTION_BACKEND"&&typeof value==="string"&&value.trim()!=="")){writeStderrLineSafe(`qwen: ${source} cannot set QWEN_AGENT_EXECUTION_BACKEND; ignored. Export it in the launch environment instead.`)}for(const[setting,key]of Object.entries(VERIFY_PR_COORDINATE_ENV)){const entry=Object.entries(env).find(([candidate,value])=>candidate.toUpperCase()===key&&typeof value==="string"&&value.trim()!=="");if(!entry)continue;writeStderrLineSafe(`qwen: ${source} cannot set ${entry[0]}; ignored. Set verifyPr.${setting} at user scope in settings.json, or export it in the launch environment.`)}}__name(reportRejectedSettingsEnv,"reportRejectedSettingsEnv");function buildRuntimeEnvironment(settings,startDir=process.cwd(),baseEnv=process.env,workspaceTrusted){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);const effectiveEnv={...baseEnv};if(baseEnv["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(effectiveEnv,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}setRuntimeEnvIfUnset(effectiveEnv,key,envFile.parsedEnv[key])}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(excludedVars.includes(key))continue;if(typeof value!=="string")continue;setRuntimeEnvIfUnset(effectiveEnv,key,value)}reportRejectedSettingsEnv(settings.env,startDir)}const overlayKeys=Object.keys(effectiveEnv).filter(key=>effectiveEnv[key]!==baseEnv[key]).sort();return{effectiveEnv:Object.freeze({...effectiveEnv}),overlayKeys:Object.freeze(overlayKeys),envFilePaths:Object.freeze([...envFilePaths]),envFileReadFailed:parsedEnvFiles.readFailed,envFileReadFailures:Object.freeze([...parsedEnvFiles.readFailures])}}__name(buildRuntimeEnvironment,"buildRuntimeEnvironment");function loadEnvironment(settings,startDir=process.cwd()){captureEnvironmentBeforeLoad();rememberRequestTimeEnvKeys(settings);const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars))continue;const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue===""&&!keepsEmptyHomeEnvValue(key);if(isEffectivelyUnset2){process.env[key]=envFile.parsedEnv[key];dotEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key)){continue}if(isReloadExcludedKey(key)){continue}if(isHardcodedProjectEnvExclusion(key)){continue}const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2&&typeof value==="string"){process.env[key]=value;settingsEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&typeof value==="string"&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,value)}}reportRejectedSettingsEnv(settings.env,startDir)}lastReloadSnapshotSeeded=true;Object.assign(process.env,getRelaunchEnvProvenance());publishPendingCompileCache()}__name(loadEnvironment,"loadEnvironment");function reloadEnvironment(settings,workspaceCwd,workspaceTrusted,options={}){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,workspaceCwd,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(parsedEnvFiles.readFailed&&options.failClosedOnEnvFileReadError){return{updatedKeys:[],removedKeys:[],envFileReadFailed:true}}if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}const dotEnvReadFailed=parsedEnvFiles.readFailed;const newDotEnvKeys=new Map;const newSettingsEnvKeys=new Map;for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}if(!newDotEnvKeys.has(key)){newDotEnvKeys.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(typeof value!=="string")continue;const dotEnvValue=newDotEnvKeys.get(key);if(dotEnvValue!==void 0&&dotEnvValue!=="")continue;if(dotEnvReadFailed&&lastReloadSnapshot.has(key))continue;newSettingsEnvKeys.set(key,value)}reportRejectedSettingsEnv(settings.env,workspaceCwd)}const allNewKeys=new Set([...newDotEnvKeys.keys(),...newSettingsEnvKeys.keys()]);const updatedKeys=[];const removedKeys=[];if(!dotEnvReadFailed){const previouslyKnown=new Set([...lastReloadSnapshot.keys(),...dotEnvSourcedKeys,...settingsEnvSourcedKeys]);for(const key of previouslyKnown){if(!allNewKeys.has(key)&&!isReloadExcludedKey(key)){delete process.env[key];inheritedDotEnvKeys.delete(key);inheritedSettingsEnvKeys.delete(key);removedKeys.push(key)}}}for(const[key,value]of newDotEnvKeys){if(value===""&&newSettingsEnvKeys.has(key))continue;if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}for(const[key,value]of newSettingsEnvKeys){if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}if(!dotEnvReadFailed){for(const sources of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of sources){if(!isReloadExcludedKey(key))sources.delete(key)}}lastReloadSnapshot.clear();for(const[key,value]of newDotEnvKeys){lastReloadSnapshot.set(key,value)}for(const[key,value]of newSettingsEnvKeys){lastReloadSnapshot.set(key,value)}}for(const key of newDotEnvKeys.keys()){dotEnvSourcedKeys.add(key)}for(const key of newSettingsEnvKeys.keys()){settingsEnvSourcedKeys.add(key)}Object.assign(process.env,getRelaunchEnvProvenance());return{updatedKeys,removedKeys,...dotEnvReadFailed?{envFileReadFailed:true}:{}}}__name(reloadEnvironment,"reloadEnvironment");export{SETTINGS_DIRECTORY_NAME,hasLoadedEnvironmentValues,getRelaunchEnvProvenance,preResolveHomeEnvOverrides,resetHomeEnvBootstrapForTesting,resetEnvironmentTrackingForTesting,isFileSourcedEnvKey,getHomeEnvFallbackVars,findEnvFiles,setUpCloudShellEnvironment,readProjectEnvFiles,buildRuntimeEnvironment,loadEnvironment,reloadEnvironment};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{GIT_COMMIT_INFO}from"./chunk-
|
|
3
|
+
import{GIT_COMMIT_INFO}from"./chunk-MQWKOOSR.js";import{formatAuxModelSelectorForDisplay}from"./chunk-L42NTHIT.js";import{getCliVersion}from"./chunk-D3YOXHQF.js";import{IdeClient}from"./chunk-PFKTTUGS.js";import{formatMemoryUsage}from"./chunk-NTRFETZB.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();function formatExecutionSandbox(config){const policy=config?.getShellExecutionSandbox?.();if(!policy)return void 0;const effective=policy.effectiveBackend??"unresolved";const enforcement=policy.enforcement?` (${policy.enforcement}${policy.landlockAbi?`, ABI ${policy.landlockAbi}`:""})`:"";return`tools / ${policy.requestedBackend??"auto"} \u2192 ${effective}${enforcement} / ${policy.filesystem} / command network: ${policy.network}`}__name(formatExecutionSandbox,"formatExecutionSandbox");import process from"node:process";import os from"node:os";import{execFile}from"node:child_process";var debugLogger=createDebugLogger("STATUS");var VERSION_PROBE_TIMEOUT_MS=5e3;function probeVersion(binary){return new Promise(resolve=>{execFile(binary,["--version"],{timeout:VERSION_PROBE_TIMEOUT_MS,encoding:"utf-8"},(err,stdout)=>{if(err){resolve("unknown");return}resolve(typeof stdout==="string"?stdout.trim():"unknown")})})}__name(probeVersion,"probeVersion");async function getNpmVersion(){return probeVersion("npm")}__name(getNpmVersion,"getNpmVersion");async function getGitVersion(){return probeVersion("git")}__name(getGitVersion,"getGitVersion");async function getIdeClientName(context){if(!context.services.config?.getIdeMode()){return""}try{const ideClient=await IdeClient.getInstance();return ideClient?.getDetectedIdeDisplayName()??""}catch{return""}}__name(getIdeClientName,"getIdeClientName");function getSandboxEnv(stripPrefix=false){const sandbox=process.env["SANDBOX"];if(!sandbox||sandbox==="sandbox-exec"){if(sandbox==="sandbox-exec"){const profile=process.env["SEATBELT_PROFILE"]||"unknown";return`sandbox-exec (${profile})`}return"no sandbox"}if(stripPrefix){return sandbox.replace(/^qwen-(?:code-)?/,"")}return sandbox}__name(getSandboxEnv,"getSandboxEnv");async function getSystemInfo(context){const osPlatform=process.platform;const osArch=process.arch;const osRelease=os.release();const nodeVersion=process.version;const executionSandbox=formatExecutionSandbox(context.services.config);const npmVersion=executionSandbox?"not probed (tool execution sandbox active)":await getNpmVersion();const sandboxEnv=executionSandbox??getSandboxEnv();const modelVersion=context.services.config?.getModel()||"Unknown";const cliVersion=await getCliVersion();const selectedAuthType=context.services.config?.getAuthType()||"";const ideClient=await getIdeClientName(context);const sessionId=context.services.config?.getSessionId()||"unknown";const proxy=context.services.config?.getProxy();return{cliVersion,osPlatform,osArch,osRelease,nodeVersion,npmVersion,sandboxEnv,modelVersion,selectedAuthType,ideClient,sessionId,proxy}}__name(getSystemInfo,"getSystemInfo");async function getExtendedSystemInfo(context){const baseInfo=await getSystemInfo(context);const memoryUsage=formatMemoryUsage(process.memoryUsage().rss);const sandboxEnv=formatExecutionSandbox(context.services.config)??getSandboxEnv(true);const contentGeneratorConfig=baseInfo.selectedAuthType==="openai"||baseInfo.selectedAuthType==="openai-responses"||baseInfo.selectedAuthType==="anthropic"?context.services.config?.getContentGeneratorConfig():void 0;const baseUrl=contentGeneratorConfig?.baseUrl;const apiKeyEnvKey=contentGeneratorConfig?.apiKeyEnvKey;const gitCommit=GIT_COMMIT_INFO&&!["N/A"].includes(GIT_COMMIT_INFO)?GIT_COMMIT_INFO:void 0;const fastModelSetting=context.services.settings?.merged?.fastModel||void 0;const fastModel=fastModelSetting?formatAuxModelSelectorForDisplay(fastModelSetting):void 0;const lspStatus=getLspStatus(context);return{...baseInfo,sandboxEnv,memoryUsage,baseUrl,apiKeyEnvKey,gitCommit,fastModel,lspStatus}}__name(getExtendedSystemInfo,"getExtendedSystemInfo");function getLspStatus(context){try{const snapshot=context.services.config?.getLspStatusSnapshot?.();if(!snapshot){return void 0}if(context.services.config?.getDebugMode?.()){debugLogger.debug("LSP status snapshot for /status:",snapshot)}return formatLspStatusSnapshot(snapshot)}catch(error){if(context.services.config?.getDebugMode?.()){debugLogger.debug("Unable to read LSP status snapshot for /status:",error)}return void 0}}__name(getLspStatus,"getLspStatus");function formatLspStatusSnapshot(snapshot){if(!snapshot.enabled){return"disabled"}if(snapshot.initializationError){return`enabled, initialization failed: ${snapshot.initializationError}`}if(snapshot.statusUnavailable){return"enabled, status unavailable"}if(snapshot.configuredServers===0){return"enabled, no servers configured"}const details=[snapshot.failedServers>0?`${snapshot.failedServers} failed`:"",snapshot.inProgressServers>0?`${snapshot.inProgressServers} starting`:"",snapshot.notStartedServers>0?`${snapshot.notStartedServers} not started`:""].filter(Boolean);const detailText=details.length>0?` (${details.join(", ")})`:"";return`enabled, ${snapshot.readyServers}/${snapshot.configuredServers} ready${detailText}`}__name(formatLspStatusSnapshot,"formatLspStatusSnapshot");export{formatExecutionSandbox,getNpmVersion,getGitVersion,getExtendedSystemInfo};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|