@hostclubeos/miraos 0.0.4-beta → 0.0.6-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.
Files changed (113) hide show
  1. package/bundled/bug-hunter/SKILL.md +7 -0
  2. package/chunks/{acpAgent-F4OT4AQQ.js → acpAgent-OGBFWA5R.js} +2 -2
  3. package/chunks/{chunk-BX3KM7OK.js → chunk-2PB6TEZU.js} +1 -1
  4. package/chunks/{chunk-7LXU4NUI.js → chunk-34YXJ3CX.js} +1 -1
  5. package/chunks/{chunk-WDLXS4A3.js → chunk-3GA3NTAV.js} +3 -3
  6. package/chunks/{chunk-4TJKJ2LG.js → chunk-5JKJSIIP.js} +1 -1
  7. package/chunks/{chunk-FUIRLSNA.js → chunk-7JT2V4AW.js} +1 -1
  8. package/chunks/{chunk-C24YTZET.js → chunk-BB2C4HKQ.js} +1 -1
  9. package/chunks/{chunk-AXBNQS6C.js → chunk-F2XELUO3.js} +1 -1
  10. package/chunks/{chunk-BZMSTSKY.js → chunk-GPI53DWB.js} +1 -1
  11. package/chunks/{chunk-AYU4PDSQ.js → chunk-HHSHBOT7.js} +2 -2
  12. package/chunks/{chunk-TIWH3MUJ.js → chunk-HMID4D72.js} +1 -1
  13. package/chunks/{chunk-JM46SKXF.js → chunk-IC2WDA6V.js} +1 -1
  14. package/chunks/{chunk-HPGUQCRQ.js → chunk-JRPR5IME.js} +1 -1
  15. package/chunks/{chunk-ECNTMKHI.js → chunk-ORVQPZMQ.js} +1 -1
  16. package/chunks/{chunk-5SJFYZQJ.js → chunk-RGVXNWZA.js} +1 -1
  17. package/chunks/{chunk-LISKSG7B.js → chunk-SHLTP6ZB.js} +1 -1
  18. package/chunks/{chunk-D3QZNIFB.js → chunk-SOCXRMZM.js} +4 -4
  19. package/chunks/{chunk-PUPIORBU.js → chunk-TI7J4HX2.js} +1 -1
  20. package/chunks/{chunk-CKBEAZAV.js → chunk-VGPV5AVJ.js} +1 -1
  21. package/chunks/{chunk-33G7MOU6.js → chunk-Y3BCVTFB.js} +1 -1
  22. package/chunks/{chunk-4XV2522J.js → chunk-YVORE4W4.js} +1 -1
  23. package/chunks/{daemon-status-provider-NBPLE4JN.js → daemon-status-provider-FCQ4YYAY.js} +1 -1
  24. package/chunks/{fast-path-66F2TWKE.js → fast-path-ZBD7IYQM.js} +1 -1
  25. package/chunks/{llm-LZ3HARC2.js → llm-DQNQEAFW.js} +3 -3
  26. package/chunks/{local-6KBSW7N2.js → local-ZRC4XZCJ.js} +1 -1
  27. package/chunks/{managed-local-serve-2N3IAB3D.js → managed-local-serve-B2KOLPB5.js} +1 -1
  28. package/chunks/{managed-runtime-bootstrap-M4P43K7W.js → managed-runtime-bootstrap-MREL5UC2.js} +1 -1
  29. package/chunks/{managed-runtime-ssh-worker-WWZ7SJ7U.js → managed-runtime-ssh-worker-GUKAZFAJ.js} +1 -1
  30. package/chunks/{memory-D62BXIJW.js → memory-ZYPCFYPF.js} +1 -1
  31. package/chunks/{nonInteractiveCli-Z4A7THMG.js → nonInteractiveCli-JG6PKBAD.js} +1 -1
  32. package/chunks/{review-LM7KW6Y5.js → review-N3VFZQMI.js} +1 -1
  33. package/chunks/{run-qwen-serve-77UZS4JA.js → run-qwen-serve-4MZRQFXK.js} +1 -1
  34. package/chunks/{serve-RHO7RZ45.js → serve-EQN6QAXF.js} +1 -1
  35. package/chunks/{server-5HEOZG3T.js → server-CCEHAI25.js} +1 -1
  36. package/chunks/{session-RT7VH6GE.js → session-HNUJSV5A.js} +1 -1
  37. package/chunks/{start-opentui-ui-I2XXWTJS.js → start-opentui-ui-6MCAEWAW.js} +1 -1
  38. package/chunks/{startInteractiveUI-774LJIJD.js → startInteractiveUI-657JWOTK.js} +1 -1
  39. package/chunks/{validateNonInterActiveAuth-633WYCVH.js → validateNonInterActiveAuth-CP5WFNAE.js} +1 -1
  40. package/chunks/{version-77KBVA2F.js → version-SIM74L5K.js} +1 -1
  41. package/cli.js +1 -1
  42. package/export-transcript-document.js +1 -1
  43. package/package.json +3 -3
  44. package/web-shell/assets/{PierreFilePreview-DEhWK46v.js → PierreFilePreview-Dkt6iPte.js} +1 -1
  45. package/web-shell/assets/SpreadsheetPreview-I4yiL7q3.js +1 -0
  46. package/web-shell/assets/{WorkspaceFileBrowser-64vDYikf.js → WorkspaceFileBrowser-Du9bMpNo.js} +1 -1
  47. package/web-shell/assets/{abnfDiagram-VCTEODGH-C2WWURam.js → abnfDiagram-VCTEODGH-CGY1lCxS.js} +1 -1
  48. package/web-shell/assets/{agents-route-j5ba59xn.js → agents-route-kcQ3YUNc.js} +1 -1
  49. package/web-shell/assets/{arc-Bkr_-GVn.js → arc-BUMNyJDV.js} +1 -1
  50. package/web-shell/assets/{architectureDiagram-5GKGNRK7-D_v_wDDW.js → architectureDiagram-5GKGNRK7-CEfXhEKD.js} +1 -1
  51. package/web-shell/assets/{blockDiagram-NRAW4CY4-Csxc3YNo.js → blockDiagram-NRAW4CY4-BH8hjvlX.js} +1 -1
  52. package/web-shell/assets/{c4Diagram-UCG6FXSJ-PXryoJCB.js → c4Diagram-UCG6FXSJ-Dfl946ex.js} +1 -1
  53. package/web-shell/assets/channel-CoZByzPk.js +1 -0
  54. package/web-shell/assets/{chunk-2Q5K7J3B-DwK5UBHI.js → chunk-2Q5K7J3B-CBvGm-pD.js} +1 -1
  55. package/web-shell/assets/{chunk-5VM5RSS4-BC1hvD6_.js → chunk-5VM5RSS4-k06tGOfl.js} +1 -1
  56. package/web-shell/assets/{chunk-F27PBJKO-iFe0IxfJ.js → chunk-F27PBJKO-Dv4S4vSq.js} +1 -1
  57. package/web-shell/assets/{chunk-G27WJ6UU-ROSuKRxI.js → chunk-G27WJ6UU-7LY0yu3f.js} +1 -1
  58. package/web-shell/assets/{chunk-JWPE2WC7-CYHS6PxA.js → chunk-JWPE2WC7-B-CgVEuJ.js} +1 -1
  59. package/web-shell/assets/{chunk-LCL6LL3I-D5bFMqCy.js → chunk-LCL6LL3I-D0TrWx1f.js} +1 -1
  60. package/web-shell/assets/{chunk-POPQ4Y6H-BJh77MGv.js → chunk-POPQ4Y6H-B97ZANlR.js} +1 -1
  61. package/web-shell/assets/{chunk-SVP7TREG-Cs81aYft.js → chunk-SVP7TREG-2CO_3G76.js} +1 -1
  62. package/web-shell/assets/{chunk-XXDRQBXY-DqDbN44E.js → chunk-XXDRQBXY-CFbSHjzz.js} +1 -1
  63. package/web-shell/assets/classDiagram-DTDB5LWJ-BgKRvG5r.js +1 -0
  64. package/web-shell/assets/classDiagram-v2-JRS7N3AN-BgKRvG5r.js +1 -0
  65. package/web-shell/assets/{cose-bilkent-JH36ORCC-DhjrwADJ.js → cose-bilkent-JH36ORCC-K-uc8eFw.js} +1 -1
  66. package/web-shell/assets/{cynefin-OW5HDTMX-Dh7t-_3M.js → cynefin-OW5HDTMX-Cb0lt2G3.js} +1 -1
  67. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-5J4kto0C.js → cynefinDiagram-5FMLGOSQ-DWkqpFuH.js} +1 -1
  68. package/web-shell/assets/{dagre-3AP2YEHR-28AdbIcl.js → dagre-3AP2YEHR-Cs8gu3Q4.js} +1 -1
  69. package/web-shell/assets/{diagram-S7CK7UJ4-DmksuoIf.js → diagram-S7CK7UJ4-DlMLXUgK.js} +1 -1
  70. package/web-shell/assets/{diagram-UQ7AKVKN-DUjgQ8Fg.js → diagram-UQ7AKVKN-68PPYL92.js} +1 -1
  71. package/web-shell/assets/{diagram-VSXAHHWV-DUe_FpG-.js → diagram-VSXAHHWV-CxIdRSbx.js} +1 -1
  72. package/web-shell/assets/{diagram-VX7I27RA-CJJ70teK.js → diagram-VX7I27RA-G3C0kWVW.js} +1 -1
  73. package/web-shell/assets/{diagram-Z3DM3KII-BgABlJO4.js → diagram-Z3DM3KII-CwEuAgyS.js} +1 -1
  74. package/web-shell/assets/{docx-preview-BMBWboRx.js → docx-preview-3XzkP9iR.js} +1 -1
  75. package/web-shell/assets/{ebnfDiagram-PWID7BFC-B3nK_Lh7.js → ebnfDiagram-PWID7BFC-DLeMX1Ka.js} +1 -1
  76. package/web-shell/assets/{erDiagram-SSCWMZ5O-DCTdCWlu.js → erDiagram-SSCWMZ5O-CoQLSOGk.js} +1 -1
  77. package/web-shell/assets/{flowDiagram-A5DVABFB-CPxk2UUl.js → flowDiagram-A5DVABFB-BXUV-Qml.js} +1 -1
  78. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-WZzMAKht.js → ganttDiagram-EL5Y4UJY-sWi6Lowi.js} +1 -1
  79. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-DKcO5ugU.js → gitGraphDiagram-WWUBYQGX-Dsh4-kB4.js} +1 -1
  80. package/web-shell/assets/{index-CkRLMu1y.js → index-CrSq-SfJ.js} +6 -6
  81. package/web-shell/assets/{index-Dbm3-Fps.js → index-DjwWlZt0.js} +1 -1
  82. package/web-shell/assets/{infoDiagram-RXCK75RN-CJX5DzdL.js → infoDiagram-RXCK75RN-JZ6nFIgB.js} +1 -1
  83. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-fF0Id5B6.js → ishikawaDiagram-5VMMS53U-qJj-sQFs.js} +1 -1
  84. package/web-shell/assets/{journeyDiagram-EYS64GPL-BOAezBVe.js → journeyDiagram-EYS64GPL-Ck0jv8SO.js} +1 -1
  85. package/web-shell/assets/{kanban-definition-3QL26DDD-DdNBof9J.js → kanban-definition-3QL26DDD-Ck6_Ydmt.js} +1 -1
  86. package/web-shell/assets/{layout-CXX3l5w0.js → layout-yLaSulE8.js} +1 -1
  87. package/web-shell/assets/{linear-Dnaccp-S.js → linear-CXw5rE6U.js} +1 -1
  88. package/web-shell/assets/{mermaid.core-BzdC3B6T.js → mermaid.core-6WQsyLcq.js} +6 -6
  89. package/web-shell/assets/{mindmap-definition-FBJOCRG2-D-gMUzLw.js → mindmap-definition-FBJOCRG2-BDAmAz8h.js} +1 -1
  90. package/web-shell/assets/{pegDiagram-XKGWAZYB-B9n1WVZq.js → pegDiagram-XKGWAZYB-Rvn5mpol.js} +1 -1
  91. package/web-shell/assets/{pieDiagram-E7YTZNPT-ok49U0zT.js → pieDiagram-E7YTZNPT-DHw4avFL.js} +1 -1
  92. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-DJKha-v3.js → quadrantDiagram-AXDQQJYC-vch6jDK-.js} +1 -1
  93. package/web-shell/assets/{railroadDiagram-O6MQD6OU-DjL4pl7y.js → railroadDiagram-O6MQD6OU-DfVCzYpO.js} +1 -1
  94. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-BpmmRw3A.js → requirementDiagram-EFPCY7ZU-BQAnwpSv.js} +1 -1
  95. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-KpteHB8X.js → sankeyDiagram-P5KCCOFB-fJuxdbbi.js} +1 -1
  96. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-COMghCpA.js → sequenceDiagram-WJ2MYXX4-B3TtvHJp.js} +1 -1
  97. package/web-shell/assets/{sizeCapture-X5ZJPWSS-5fEwJD-n.js → sizeCapture-X5ZJPWSS-DlJmbcZd.js} +1 -1
  98. package/web-shell/assets/{stateDiagram-HBIQ2CUA-CnC7oXvs.js → stateDiagram-HBIQ2CUA--0kiPvGS.js} +1 -1
  99. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-Dw-ppcvp.js +1 -0
  100. package/web-shell/assets/{swimlanes-XN3QIQJK-bVlhZdve.js → swimlanes-XN3QIQJK-CAytfKbo.js} +1 -1
  101. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-B36XZQuh.js +8 -0
  102. package/web-shell/assets/{timeline-definition-24CTP7MA-CBvYgMu5.js → timeline-definition-24CTP7MA-C-BUmwu6.js} +1 -1
  103. package/web-shell/assets/{vennDiagram-4TSXK5OY-CUTYvV1j.js → vennDiagram-4TSXK5OY-W_dgEGv2.js} +1 -1
  104. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-Djl4gxCB.js → wardleyDiagram-VM6X3IG4-ikAv1QJ9.js} +1 -1
  105. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-BcJZtI2X.js → xychartDiagram-S5SC5T6Z-BmY9Ily6.js} +1 -1
  106. package/web-shell/index.html +1 -1
  107. package/web-shell/sw.js +1 -1
  108. package/web-shell/assets/SpreadsheetPreview-C-GgIuPX.js +0 -1
  109. package/web-shell/assets/channel-6Pj4KPAs.js +0 -1
  110. package/web-shell/assets/classDiagram-DTDB5LWJ-BaTUuuB8.js +0 -1
  111. package/web-shell/assets/classDiagram-v2-JRS7N3AN-BaTUuuB8.js +0 -1
  112. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-V_cfZFBL.js +0 -1
  113. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-25wVg0WL.js +0 -8
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
3
  import{HEADLESS_YOLO_NO_SANDBOX_WARNING}from"./chunk-Z57KDB5F.js";import{listExplicitCandidates}from"./chunk-EIVJHHRA.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,DEFAULT_RING_MAX_BYTES,DEFAULT_RING_SIZE,JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeMaxRingBytes}from"./chunk-OFWAMIMB.js";import{JOURNAL_GROWTH_POOL_FRACTION,MAX_JOURNAL_GROWTH_POOL_MB,MIN_MEMORY_BUDGET_MB,isValidMemoryBudgetMb,memoryBudgetRangeError}from"./chunk-2QYDBHYZ.js";import{normalizeServeChannelSelection}from"./chunk-KOJ7WZ63.js";import{EXTERNAL_TOOL_GUARD_TOKEN_ENV}from"./chunk-NIEO2TBE.js";import{loadSettings}from"./chunk-23543L6E.js";import{MCP_BUDGET_WARN_FRACTION}from"./chunk-PFKTTUGS.js";import{openBrowserSecurely,shouldLaunchBrowser}from"./chunk-UJSVTVKB.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{MEMORY_PROJECT_SCOPES}from"./chunk-PWOQASXT.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var SEGMENT=/^[A-Za-z0-9_-]{1,256}$/;function parseJoinLink(link){let url;try{url=new URL(link.trim())}catch{throw new Error("--join expects the link shown by the coordinator.")}const marker=url.pathname.lastIndexOf("/join/");const[workspaceId,...rest]=marker>=0?url.pathname.slice(marker+"/join/".length).split("/"):[];if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.search||url.hash||!workspaceId||rest.some(Boolean)||!SEGMENT.test(workspaceId)){throw new Error("--join expects a link like https://host:4170/join/<workspace>.")}const base=url.pathname.slice(0,marker).replace(/\/+$/,"");return{serverUrl:`${url.origin}${base}`,workspaceId}}__name(parseJoinLink,"parseJoinLink");function blockForever(){return new Promise(()=>{})}__name(blockForever,"blockForever");var DEFAULT_SERVE_HOSTNAME="127.0.0.1";function validateManagedLocalFlags(args){const supported=new Set(["--managed","--managed-data-dir","--port","--hostname","--open","--no-open","--open-with-auth","--no-open-with-auth","--web","--require-auth","--http-bridge"]);const unsupported=args.find(arg=>arg.startsWith("--")&&!supported.has(arg.split("=")[0]));if(unsupported){throw new Error(`${unsupported.split("=")[0]} is not supported with --managed. Use --port, --managed-data-dir, and --open.`)}}__name(validateManagedLocalFlags,"validateManagedLocalFlags");function validateManagedWebFlags(args){const supported=new Set(["--managed-web-config","--hostname","--port","--allow-origin","--token","--require-auth"]);const unsupported=args.find(arg=>arg.startsWith("--")&&!supported.has(arg.split("=")[0]));if(unsupported){throw new Error(`${unsupported.split("=")[0]} is not supported with --managed-web-config. Only hostname, port, allow-origin and browser authentication options are supported.`)}}__name(validateManagedWebFlags,"validateManagedWebFlags");async function startLocalControl(handle,address){await handle.runtimeReady;if(!handle.webShellMounted){throw new Error("Local Control requires the Web Shell.")}const service=handle.getLocalControl();if(!service){throw new Error("Local Control is unavailable on this daemon.")}let status;try{status=await service.enable(address?{address,allowExplicitAddress:true}:{})}catch(err){if(err instanceof Error&&err.code==="ambiguous_lan_interface"){throw new Error(`${err.message}. Pass --local-control-address <ip>.`)}if(err instanceof Error&&err.code==="no_lan_interface"){throw new Error(`${err.message} If this host's usable address is outside private/link-local space, or sits on a VPN/tunnel interface, name it: --local-control-address <ip>.`)}if(err instanceof Error&&err.code==="unknown_lan_interface"){const candidates=listExplicitCandidates();throw new Error(`${err.message}${candidates.length?` This host currently has: ${candidates.map(c=>`${c.interfaceName} (${c.address})`).join(", ")}.`:""}`)}throw err}if(!status.url){throw new Error("Local Control did not return a pairing URL.")}const{default:qrcode}=await import("./main-5IVKRF6Q.js");qrcode.setErrorLevel("Q");writeStdoutLine("\nLocal Control is on. Scan this QR code from the same network:");writeStdoutLine(`
4
- ${status.interfaceName}: ${status.url}`);qrcode.generate(status.url,{small:true},code=>{writeStdoutLine(code.trimEnd())});writeStdoutLine("\nKeep this terminal open. "+(status.sleepInhibited?"Sleep is inhibited while this session is active. ":"Sleep inhibition is unavailable here, so the host may sleep. ")+(status.encrypted?"Traffic is encrypted.":"Traffic is unencrypted \u2014 use it only on a network you trust.")+" Turn Local Control off from the Web Shell Settings card, or press Ctrl+C to exit the daemon.")}__name(startLocalControl,"startLocalControl");async function maybeOpenWebShellBrowser(handle,open,manualFallbackWhenIneligible=false){if(!open||!handle.webShellMounted)return;const shouldLaunch=shouldLaunchBrowser();if(!shouldLaunch&&!manualFallbackWhenIneligible)return;try{await handle.runtimeReady}catch(runtimeErr){writeStderrLine(`qwen serve: Web Shell runtime not ready; skipping --open: ${runtimeErr instanceof Error?runtimeErr.message:String(runtimeErr)}`);return}let target;try{target=new URL(handle.url);if(target.hostname==="0.0.0.0"||target.hostname==="[::]"){target.hostname="127.0.0.1"}if(handle.resolvedToken){target.hash=`token=${encodeURIComponent(handle.resolvedToken)}`}if(!shouldLaunch){writeStderrLine(`Browser launch is not available in this environment. Please open this URL manually: ${target.toString()}`);return}if(handle.resolvedToken){writeStderrLine("qwen serve: --open passes the token in the browser launch command (visible via `ps` / /proc); on a multi-user host open the URL manually instead.")}await openBrowserSecurely(target.toString())}catch(browserErr){const manualUrl=manualFallbackWhenIneligible&&target?`. Please open this URL manually: ${target.toString()}`:"";writeStderrLine(`qwen serve: failed to open browser: ${browserErr instanceof Error?browserErr.message:String(browserErr)}${manualUrl}`)}}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function primaryWorkspaceArg(workspace){return Array.isArray(workspace)?workspace[0]:workspace}__name(primaryWorkspaceArg,"primaryWorkspaceArg");var serveCommand={command:"serve",describe:"Run Qwen Code as a local HTTP daemon (Stage 1 experimental: --http-bridge)",builder:__name(yargs=>yargs.option("port",{type:"number",default:4170,description:"TCP port to bind (use 0 for an OS-assigned ephemeral port)"}).option("hostname",{type:"string",default:DEFAULT_SERVE_HOSTNAME,description:"Interface to bind. Loopback (127.0.0.0/8, localhost, ::1, [::1]) is auth-free; anything else requires a token (one is generated and printed when neither --token nor QWEN_SERVER_TOKEN supplies one). A localhost bind that resolves off-loopback never generates, and still refuses when no token source resolved; an empty value is rejected as operator error."}).option("profile",{choices:["default","hosted-harness"],default:"default",description:"Deployment profile. hosted-harness enables the private no-tool Managed Session API on loopback."}).option("hosted-harness-capability-digest",{type:"string",description:"SHA-256 capability digest for the private Hosted Harness profile. Falls back to QWEN_HOSTED_HARNESS_CAPABILITY_DIGEST."}).option("managed",{type:"boolean",default:false,description:"Start the daemon and Managed Agent with shared WebShell and embedded storage; downloads the server on first use and requires Java 21."}).option("managed-data-dir",{type:"string",requiresArg:true,description:"Private persistent data directory for --managed; defaults to <Qwen home>/managed-local."}).option("managed-web-config",{type:"string",requiresArg:true,description:"Run only the authenticated Managed Web gateway using a JSON file with apiUrl, tenantId, actorId and signingKeyFile. Requires a non-empty independent browser token via QWEN_SERVER_TOKEN or --token."}).option("token",{type:"string",description:"Bearer token required on every request. Falls back to the QWEN_SERVER_TOKEN env var; a non-loopback bind with neither generates an ephemeral token at startup, while loopback keeps the trusted tokenless mode unless --require-auth is set."}).option("max-sessions",{type:"number",description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable. Defaults to 32, or to the serve.maxSessions setting (user, system, and system-defaults scopes only); the flag wins when passed."}).option("max-total-sessions",{type:"number",description:"Non-negative integer cap on concurrent live sessions across all workspace runtimes. Set to 0 to disable."}).option("max-pending-prompts-per-session",{type:"number",default:5,description:"Per-session cap on accepted prompts waiting or running. New prompts beyond this return 503. Set to 0 to disable."}).option("workspace",{type:"string",array:true,requiresArg:true,description:"Absolute workspace path to register with this daemon. POST /session requests with a mismatched cwd return 400 workspace_mismatch. Defaults to process.cwd() when omitted. Repeat to register isolated workspace runtimes; the first is primary."}).option("conversations-dir",{type:"string",requiresArg:true,description:"Absolute working-directory root shared by standalone and Live Conversations. Overrides QWEN_CONVERSATIONS_DIR; defaults to ~/Documents/Qwen Code/Conversations."}).option("memory-project-scope",{type:"string",choices:MEMORY_PROJECT_SCOPES,description:'Choose how project memory is partitioned. Defaults to "workspace" so each daemon workspace stays isolated; "git-root" preserves the legacy shared scope. Overrides QWEN_CODE_MEMORY_PROJECT_SCOPE when provided.'}).option("max-connections",{type:"number",default:256,description:"Listener-level TCP connection cap (server.maxConnections). Bounds raw sockets \u2014 slow/phantom SSE clients get rejected at accept time once full. Set to 0 to disable."}).option("require-auth",{type:"boolean",default:false,description:"Refuse to start without a bearer token, even on loopback. Hardens the loopback developer default for shared dev hosts / CI runners / multi-tenant workstations where any local user can hit 127.0.0.1. Requires --token, QWEN_SERVER_TOKEN, or --open-with-auth (which installs its own generated loopback token); on non-loopback binds the generated ephemeral token also satisfies it, so the no-configured-secret fail-fast is loopback-only. /health also requires Authorization when enabled (no loopback exemption \u2014 k8s/Compose probes must pass the bearer too)."}).option("enable-session-shell",{type:"boolean",default:false,description:"Enable direct POST /session/:id/shell execution. Available with bearer auth or trusted loopback; each call still requires a session-bound client id."}).option("tls-cert",{type:"string",description:"Path to a PEM certificate file. Serve over HTTPS instead of HTTP. Required for secure-context browser APIs (voice input/getUserMedia, WebRTC) when accessed over a LAN IP. Must be used together with --tls-key. Generate a local cert with mkcert."}).option("tls-key",{type:"string",description:"Path to a PEM private key file. Must be used together with --tls-cert."}).option("experimental-lsp",{type:"boolean",default:false,description:"Forward the experimental LSP opt-in to spawned agent sessions."}).option("restore-ask-user-question",{type:"boolean",default:false,description:"On session load/resume, re-hang a trailing unanswered ask_user_question instead of synthesizing a failed tool result."}).option("channel",{type:"string",array:true,description:"Experimental: start a daemon-managed channel worker for the named channel. Repeat to select multiple channels, or use --channel all."}).option("web",{type:"boolean",default:true,description:"Serve the Web Shell UI at the daemon root path. Use --no-web for an API-only daemon."}).option("open",{type:"boolean",default:false,description:"Open the Web Shell in a browser once the daemon is listening. With a token configured, the launch URL (token included) is handed to the browser launcher and is visible in the process list, so prefer opening the URL manually on multi-user hosts. No-op with --no-web, when the UI assets are absent, or in headless/CI/SSH environments."}).option("open-with-auth",{type:"boolean",default:false,description:"Open the Web Shell with bearer authentication on loopback. Reuse --token or QWEN_SERVER_TOKEN, or generate a temporary 256-bit token and deliver it in the URL fragment. In headless environments, print the fragment URL for manual opening."}).option("token-qr",{type:"boolean",description:"Print the token-bearing QR even when stdout is captured (not an interactive terminal) and the bearer is an operator-supplied (stable) token, which is withheld by default to keep stable credentials out of collected logs. Enable only when the log pipeline is as trusted as the daemon host. Can also be set via the serve.tokenQr setting (user, system, and system-defaults scopes only); the flag wins when passed. --no-token-qr suppresses the startup quickstart token QR for that run on every quickstart path \u2014 interactive terminal and generated token included. It does not govern the Local Control pairing QR, which --local-control prints by design."}).option("local-control",{type:"boolean",default:false,description:"Share the Web Shell on the local IPv4 network with its own revocable pairing token, terminal QR code, and best-effort sleep inhibition. Ctrl+C turns it off by ending the whole daemon; the Web Shell Settings card turns it off while the daemon keeps running."}).option("local-control-address",{type:"string",description:"Which local IPv4 address to share when the host is on more than one network. Only needed if --local-control reports an ambiguous choice. Naming an address outside RFC 1918/3927 space, or one on a VPN/tunnel interface (e.g. phone and laptop on the same corporate VPN), is accepted as an explicit opt-in; out-of-private-space picks are logged with a warning."}).option("join",{type:"string",description:"Join another Qwen Code as a runtime, with the one-line link it shows under Agent \u2192 Runtime \u2192 Add runtime."}).option("agent-host-server",{type:"string",description:"Register this daemon as an Agent Host with a primary Qwen daemon."}).option("agent-host-workspace-id",{type:"string",description:"Control-plane workspace id printed by the primary daemon."}).option("agent-host-name",{type:"string",description:"Display name advertised for this Agent Host."}).option("agent-host-allow-http",{type:"boolean",default:false,description:"Allow unencrypted Agent Host HTTP connections outside loopback (trusted demo networks only)."}).check(argv=>{if(Array.isArray(argv["conversations-dir"])){throw new Error("pass --conversations-dir once.")}normalizeMaxRingBytes(argv["event-ring-max-bytes"]);if(argv["local-control"]===true&&argv["web"]===false){throw new Error("Local Control requires the Web Shell.")}if(argv["local-control"]===true&&argv.hostname!==DEFAULT_SERVE_HOSTNAME){throw new Error(`Local Control requires --hostname ${DEFAULT_SERVE_HOSTNAME}.`)}if(argv["local-control"]!==true&&argv["local-control-address"]!==void 0){throw new Error("--local-control-address requires --local-control.")}if(argv["local-control-address"]===""){throw new Error("--local-control-address must not be empty.")}if(Boolean(argv["agent-host-server"])!==Boolean(argv["agent-host-workspace-id"])){throw new Error("--agent-host-server and --agent-host-workspace-id must be used together.")}if(argv["agent-host-name"]===""){throw new Error("--agent-host-name must not be empty.")}if(argv["join"]!==void 0){if(argv["agent-host-server"]||argv["agent-host-workspace-id"]){throw new Error("--join already names the coordinator and workspace; drop --agent-host-server and --agent-host-workspace-id.")}parseJoinLink(argv["join"])}return true}).option("event-ring-size",{type:"number",default:DEFAULT_RING_SIZE,description:"Per-session SSE replay ring depth. Sets the replay backlog available to `GET /session/:id/events` reconnects that send a `Last-Event-ID: N` header. Larger = more reconnect headroom at the cost of a few hundred KB extra RAM per session. Must be a positive finite integer."}).option("event-ring-max-bytes",{type:"number",nargs:1,default:DEFAULT_RING_MAX_BYTES,description:"Per-session retained SSE replay ring byte cap, including the latest full commands snapshot. Must be a positive safe integer up to 256 MiB; no unlimited sentinel."}).option("compacted-replay-max-bytes",{type:"number",default:DEFAULT_COMPACTED_REPLAY_MAX_BYTES,description:"Per-session in-memory compacted replay snapshot byte cap for `POST /session/:id/load` late attaches. Larger = more recent history in load snapshots at higher heap cost. Must be a positive safe integer no larger than 256 MiB."}).option("max-journal-events",{type:"number",nargs:1,description:"Per-session baseline cap on replay entries retained in the in-flight live journal (current unfinished turn). Compatible text/thought chunks share bounded entries. When exceeded, the daemon first tries adaptive growth (see --max-journal-bytes); without granted headroom the oldest entries are dropped. Pinning this flag (or --max-journal-bytes) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_EVENTS+" when unset. Must be a positive safe integer."}).option("max-journal-bytes",{type:"number",nargs:1,description:"Per-session baseline source-event byte cap on the in-flight live journal. When a turn outgrows it, adaptive growth raises the session's caps (per-session hard cap "+JOURNAL_GROWTH_HARD_CAP_BYTES/(1024*1024)+" MiB) within a growth pool derived from the daemon memory budget (see --memory-budget-mb); without granted headroom the oldest entries are dropped whole (at least one is always kept), so the retained tail can be much smaller than the cap. Pinning this flag (or --max-journal-events) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_BYTES+" bytes when unset. Must be a positive safe integer."}).option("http-bridge",{type:"boolean",default:true,description:"HTTP bridge mode: attempt to preheat the primary `qwen --acp` child; trusted secondaries start one on demand. Stage 2 native in-process mode is not yet implemented; this flag will become opt-in then."}).option("memory-budget-mb",{type:"number",description:"Total memory budget in MB for the daemon process tree. When unset, derived as 50% of cgroup-constrained or host memory, and capped at the resolved available memory either way. In `admit` and `enforce` modes it determines managed ACP child capacity; `enforce` also applies the modeled per-child old-space ceiling. It also sizes one daemon-wide pool of "+JOURNAL_GROWTH_POOL_FRACTION*100+"% of the effective budget (capped at "+MAX_JOURNAL_GROWTH_POOL_MB+" MB; 0, growth disabled, when the effective budget falls below the "+MIN_MEMORY_BUDGET_MB+" MB minimum; see --max-journal-bytes). Reported under `limits.memory` in daemon status, alongside a modeled per-child partition under `limits.memory.childHeap`. Must be an integer in [1024, 1048576]."}).option("memory-pressure-mode",{choices:["off","observe"],default:"observe",description:"Whether the daemon derives a memory-pressure level from its own RSS and V8 heap. `observe` (default) reports the level in daemon status and raises a status issue when it leaves normal. `off` still reports the underlying figures but raises no issue, so the overall status rollup is unchanged \u2014 use it while calibrating, or if you alert on the top-level status. Nothing remediates in either mode."}).option("child-heap-mode",{choices:["off","observe","admit","enforce"],default:"observe",description:"Whether the daemon models a per-child heap partition of the memory budget. `observe` (default) reports the partition it would apply \u2014 `limits.memory.childHeap.perChildCeilingMb` and `maxConcurrentChildren` \u2014 and counts spawns that would have exceeded it. Nothing is applied: no child is sized from the budget and no spawn is refused. `off` models nothing. Note a refusal count of 0 does NOT mean the partition would be safe to apply; children still run on the much larger host-derived ceiling, so a workload needing more old space than the modeled ceiling looks healthy here. `admit` rejects starts past the modeled process limit but keeps the existing child heap arguments. Experimental `enforce` also applies the fixed modeled old-space ceiling to each managed child; it does not cap total process RSS."}).option("mcp-client-budget",{type:"number",description:"Cap on live MCP clients spawned inside the ACP child for the bound workspace. Positive integer. Combine with --mcp-budget-mode to control behavior at the cap. When unset, mode defaults to off (no accounting-driven enforcement, but GET /workspace/mcp still reports `clientCount`). Distinct from claude-code MCP_SERVER_CONNECTION_BATCH_SIZE which gates startup concurrency, not the total client count."}).option("mcp-budget-mode",{choices:["enforce","warn","off"],description:'How --mcp-client-budget is enforced. `warn` (default when budget set): no refusal, snapshot surfaces warning at >=75% of budget. `enforce`: connects past the cap are refused (`disabledReason: "budget"`, deterministic by mcpServers declaration order). `off`: pure observability. Boot rejects `enforce` without a budget.'}).option("allow-origin",{type:"string",array:true,description:"Cross-origin allowlist for browser clients. Accepts `*`, a canonical origin, or a loopback port wildcard like `http://127.0.0.1:*` (requires a bearer token)."}).option("allow-private-auth-base-url",{type:"boolean",default:false,description:"Allow /workspace/auth/provider to install localhost/private-network baseUrl values. Use only for local development with trusted clients."}).option("prompt-deadline-ms",{type:"number",description:"Server-side wallclock cap on POST /session/:id/prompt (ms). Falls back to QWEN_SERVE_PROMPT_DEADLINE_MS. Positive integer."}).option("experimental-paired-engines",{type:"boolean",default:false,description:"Experimental: build workspace runtimes, other than the private Conversations one, with paired Legacy and Managed engines. No Managed engine is available yet, so sessions run on Legacy with a durable owner."}).option("experimental-managed-agents",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-worker",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-auto-local",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-url",{type:"string",requiresArg:true,description:"Reserved experimental Runtime URL; not implemented and rejects startup."}).option("experimental-managed-runtime-token",{type:"string",requiresArg:true,description:"Reserved experimental Runtime credential; not implemented and rejects startup."}).option("managed-runtime-broker-url",{type:"string",requiresArg:true,description:"Private Broker URL for --profile hosted-harness; required together with token for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_URL."}).option("managed-runtime-broker-token",{type:"string",requiresArg:true,description:"Private Broker credential for --profile hosted-harness; required together with URL for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_TOKEN; prefer the variable, since this option puts the credential in the process list."}).option("writer-idle-timeout-ms",{type:"number",description:"Per-SSE-connection idle deadline (ms). Falls back to QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS. Positive integer."}).option("channel-idle-timeout-ms",{type:"number",description:"Compatibility auto-reap delay for an idle workspace ACP child. 0 or unset = reap after work drains; keepalive windows may extend it (default)."}).option("initialize-timeout-ms",{type:"number",description:"ACP child request timeout, including the initialize handshake (ms). Default: 10000 (10 s)."}).option("session-restore-timeout-ms",{type:"number",description:"ACP session load/resume timeout (ms). Default: 60000. An explicit --initialize-timeout-ms can raise (but never lower) this default."}).option("session-reap-interval-ms",{type:"number",description:"Session reaper scan interval (ms). 0 = disabled. Default: 60000."}).option("session-idle-timeout-ms",{type:"number",description:"Idle timeout before a disconnected session is reaped (ms). 0 = disabled. Default: 1800000 (30 min)."}).option("session-prompt-settled-close-grace-ms",{type:"number",description:"Grace period after a prompt settles before an otherwise-idle session may be auto-closed (ms). Poll-based SSE clients use this window to reconnect without triggering a session rebuild. 0 = disabled (immediate close). Default: 0."}).option("permission-response-timeout-ms",{type:"number",description:"Wall-clock timeout for a human permission / ask_user_question response in daemon (ACP) mode (ms). 0 or unset = disabled (wait indefinitely). Default: 0."}).option("external-tool-guard-mode",{choices:["off","required"],default:"off",description:"Managed ACP pre-execution policy mode. Default off preserves current CLI and daemon behavior. Required fails startup unless a compatible loopback provider is available."}).option("external-tool-guard-endpoint",{type:"string",description:"Origin-only loopback HTTP(S) endpoint for required external tool guarding, for example http://127.0.0.1:8787."}).option("external-tool-guard-timeout-ms",{type:"number",description:"Per-handshake/prepare external tool guard timeout in milliseconds. Default: 3000."}).option("rate-limit",{type:"boolean",description:"Enable per-tier HTTP rate limiting. Tiers: prompt (10/min), mutation (30/min), read (120/min). Health, heartbeat, SSE, and /acp are exempt."}).option("rate-limit-prompt",{type:"number",description:"Max prompt requests per window per client (default 10). Requires --rate-limit."}).option("rate-limit-mutation",{type:"number",description:"Max mutation requests per window per client (default 30). Requires --rate-limit."}).option("rate-limit-read",{type:"number",description:"Max read requests per window per client (default 120). Requires --rate-limit."}).option("rate-limit-window-ms",{type:"number",description:"Rate limit window duration in ms (default 60000). Requires --rate-limit."}),"builder"),handler:__name(async argv=>{if(argv["managed-web-config"]!==void 0){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedWebFlags(process.argv.slice(serveIndex+1));if(argv.managed||argv.profile!=="default"||!argv.web||argv.workspace!==void 0||argv["conversations-dir"]!==void 0){throw new Error("--managed-web-config cannot be combined with daemon execution or Managed local mode.")}const{runManagedWebServe}=await import("./managed-web-serve-34XXVQ7Z.js");const handle=await runManagedWebServe({configFile:argv["managed-web-config"],hostname:argv.hostname,port:argv.port,token:argv.token,allowOrigins:argv["allow-origin"]});writeStdoutLine(`Managed WebShell: ${handle.url}`);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv.managed){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedLocalFlags(process.argv.slice(serveIndex+1));if(argv.hostname!==DEFAULT_SERVE_HOSTNAME||argv.profile!=="default"||!argv.web||argv.workspace!==void 0||argv["conversations-dir"]!==void 0||argv.token!==void 0||argv["tls-cert"]||argv["tls-key"]||argv["local-control"]||argv.join||argv["agent-host-server"]||argv.channel!==void 0||argv["experimental-paired-engines"]||argv["experimental-managed-agents"]||argv["experimental-managed-runtime-worker"]||argv["experimental-managed-runtime-auto-local"]||argv["experimental-managed-runtime-url"]!==void 0||argv["managed-runtime-broker-url"]!==void 0||argv["managed-runtime-broker-token"]!==void 0||argv["allow-origin"]?.length||argv["enable-session-shell"]||!argv["http-bridge"]){throw new Error("--managed uses its own loopback services, persistent credentials, and application-owned Workspaces. Use --port, --managed-data-dir, and --open; other deployment, workspace-import, or execution modes cannot be combined.")}const{runManagedLocalServe}=await import("./managed-local-serve-2N3IAB3D.js");const handle=await runManagedLocalServe({port:argv.port,dataDirectory:argv["managed-data-dir"]});await maybeOpenWebShellBrowser(handle,argv.open||argv["open-with-auth"],argv["open-with-auth"]);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv["managed-data-dir"]!==void 0){writeStderrLine("qwen serve: --managed-data-dir requires --managed.");process.exit(1)}const managedRuntimeBrokerUrl=argv["managed-runtime-broker-url"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];const managedRuntimeBrokerToken=argv["managed-runtime-broker-token"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];const agentHostEnrollmentToken=process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"]?.trim();delete process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"];if(!argv["http-bridge"]){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(argv.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}if(argv["managed-runtime-broker-token"]!==void 0){writeStderrLine("qwen serve: --managed-runtime-broker-token is visible in the process command line; prefer the QWEN_MANAGED_RUNTIME_BROKER_TOKEN env var.")}let channelSelection;try{channelSelection=normalizeServeChannelSelection(argv.channel)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}const mcpClientBudget=argv["mcp-client-budget"];const mcpBudgetMode=argv["mcp-budget-mode"];if(mcpClientBudget!==void 0){if(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0){writeStderrLine("qwen serve: --mcp-client-budget must be a positive integer.");process.exit(1)}}if(mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){writeStderrLine("qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N.");process.exit(1)}const resolvedMcpMode=mcpBudgetMode??(mcpClientBudget!==void 0?"warn":"off");const memoryBudgetMb=argv["memory-budget-mb"];if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){writeStderrLine(memoryBudgetRangeError());process.exit(1)}const maxPendingPromptsPerSession=argv["max-pending-prompts-per-session"];if(maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){writeStderrLine("qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited).");process.exit(1)}if(mcpClientBudget!==void 0){writeStderrLine(`qwen serve: --mcp-client-budget=${mcpClientBudget} mode=${resolvedMcpMode}`+(resolvedMcpMode==="enforce"?" (servers past the cap will be refused at discovery)":resolvedMcpMode==="warn"?` (warnings at >=${Math.ceil(mcpClientBudget*MCP_BUDGET_WARN_FRACTION)}, no refusal)`:""))}try{const loaded=loadSettings(primaryWorkspaceArg(argv.workspace)??process.cwd());const merged=loaded.merged;const approvalMode=merged.tools?.approvalMode;const sandbox=merged.tools?.sandbox;const sandboxEnv=process.env["SANDBOX"];const suppress=process.env["QWEN_CODE_SUPPRESS_YOLO_WARNING"];const suppressed=suppress==="1"||suppress==="true";if(approvalMode==="yolo"&&!sandbox&&!sandboxEnv&&!suppressed){writeStderrLine(HEADLESS_YOLO_NO_SANDBOX_WARNING)}}catch{}const rateLimit=argv["rate-limit"]??(process.env["QWEN_SERVE_RATE_LIMIT"]==="1"||process.env["QWEN_SERVE_RATE_LIMIT"]==="true");let rateLimitPrompt;let rateLimitMutation;let rateLimitRead;let rateLimitWindowMs;if(rateLimit){const envInt=__name(key=>{const raw=process.env[key];if(raw===void 0||raw==="")return void 0;return parsePositiveIntegerEnv(raw,Number.NaN)},"envInt");rateLimitPrompt=argv["rate-limit-prompt"]??envInt("QWEN_SERVE_RATE_LIMIT_PROMPT");rateLimitMutation=argv["rate-limit-mutation"]??envInt("QWEN_SERVE_RATE_LIMIT_MUTATION");rateLimitRead=argv["rate-limit-read"]??envInt("QWEN_SERVE_RATE_LIMIT_READ");rateLimitWindowMs=argv["rate-limit-window-ms"]??envInt("QWEN_SERVE_RATE_LIMIT_WINDOW_MS");for(const[name,value]of[["--rate-limit-prompt",rateLimitPrompt],["--rate-limit-mutation",rateLimitMutation],["--rate-limit-read",rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){writeStderrLine(`qwen serve: ${name} must be a positive integer.`);process.exit(1)}}if(rateLimitWindowMs!==void 0&&(!Number.isFinite(rateLimitWindowMs)||!Number.isInteger(rateLimitWindowMs)||rateLimitWindowMs<1e3)){writeStderrLine("qwen serve: --rate-limit-window-ms must be an integer >= 1000.");process.exit(1)}}const externalToolGuardToken=process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV]??"";delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];const openWithAuth=argv["open-with-auth"];const open=argv.open||openWithAuth;const{runQwenServe}=await import("./run-qwen-serve-77UZS4JA.js");try{const serveOptions={port:argv.port,hostname:argv.hostname,profile:argv.profile,token:argv.token,mode:"http-bridge",maxSessions:argv["max-sessions"],...argv["max-total-sessions"]!==void 0?{maxTotalSessions:argv["max-total-sessions"]}:{},maxPendingPromptsPerSession,maxConnections:argv["max-connections"],eventRingSize:argv["event-ring-size"],eventRingMaxBytes:argv["event-ring-max-bytes"],compactedReplayMaxBytes:argv["compacted-replay-max-bytes"],...argv["max-journal-events"]!==void 0?{maxJournalEvents:argv["max-journal-events"]}:{},...argv["max-journal-bytes"]!==void 0?{maxJournalBytes:argv["max-journal-bytes"]}:{},workspace:argv.workspace,...argv["conversations-dir"]!==void 0?{conversationsDir:argv["conversations-dir"]}:{},...argv["memory-project-scope"]!==void 0?{memoryProjectScope:argv["memory-project-scope"]}:{},requireAuth:argv["require-auth"],enableSessionShell:argv["enable-session-shell"],serveWebShell:argv.web,...argv["token-qr"]!==void 0?{tokenQr:argv["token-qr"]}:{},...argv["tls-cert"]!==void 0?{tlsCert:argv["tls-cert"]}:{},...argv["tls-key"]!==void 0?{tlsKey:argv["tls-key"]}:{},allowPrivateAuthBaseUrl:argv["allow-private-auth-base-url"],mcpClientBudget,mcpBudgetMode:resolvedMcpMode,...memoryBudgetMb!==void 0?{memoryBudgetMb}:{},memoryPressureMode:argv["memory-pressure-mode"],childHeapMode:argv["child-heap-mode"],...argv["allow-origin"]&&argv["allow-origin"].length>0?{allowOrigins:argv["allow-origin"]}:{},...argv["prompt-deadline-ms"]!==void 0?{promptDeadlineMs:argv["prompt-deadline-ms"]}:{},...argv["experimental-paired-engines"]?{experimentalPairedEngines:true}:{},...argv["experimental-managed-agents"]?{experimentalManagedAgents:true}:{},...argv["experimental-managed-runtime-auto-local"]?{experimentalManagedRuntimeAutoLocal:true}:{},...argv["experimental-managed-runtime-worker"]?{experimentalManagedRuntimeWorker:true}:{},...argv["experimental-managed-runtime-url"]!==void 0?{experimentalManagedRuntimeUrl:argv["experimental-managed-runtime-url"]}:{},...argv["experimental-managed-runtime-token"]!==void 0?{experimentalManagedRuntimeToken:argv["experimental-managed-runtime-token"]}:{},...managedRuntimeBrokerUrl!==void 0?{managedRuntimeBrokerUrl}:{},...managedRuntimeBrokerToken!==void 0?{managedRuntimeBrokerToken}:{},...argv["hosted-harness-capability-digest"]!==void 0?{hostedHarnessCapabilityDigest:argv["hosted-harness-capability-digest"]}:{},...argv["writer-idle-timeout-ms"]!==void 0?{writerIdleTimeoutMs:argv["writer-idle-timeout-ms"]}:{},...argv["channel-idle-timeout-ms"]!==void 0?{channelIdleTimeoutMs:argv["channel-idle-timeout-ms"]}:{},...argv["initialize-timeout-ms"]!==void 0?{initializeTimeoutMs:argv["initialize-timeout-ms"]}:{},...argv["session-restore-timeout-ms"]!==void 0?{sessionRestoreTimeoutMs:argv["session-restore-timeout-ms"]}:{},...argv["session-reap-interval-ms"]!==void 0?{sessionReapIntervalMs:argv["session-reap-interval-ms"]}:{},...argv["session-idle-timeout-ms"]!==void 0?{sessionIdleTimeoutMs:argv["session-idle-timeout-ms"]}:{},...argv["session-prompt-settled-close-grace-ms"]!==void 0?{sessionPromptSettledCloseGraceMs:argv["session-prompt-settled-close-grace-ms"]}:{},...argv["permission-response-timeout-ms"]!==void 0?{permissionResponseTimeoutMs:argv["permission-response-timeout-ms"]}:{},...argv["external-tool-guard-mode"]==="required"?{externalToolGuard:{mode:"required",endpoint:argv["external-tool-guard-endpoint"]??"",token:externalToolGuardToken,...argv["external-tool-guard-timeout-ms"]!==void 0?{timeoutMs:argv["external-tool-guard-timeout-ms"]}:{}}}:{},...rateLimit?{rateLimit:true}:{},...rateLimitPrompt!==void 0?{rateLimitPrompt}:{},...rateLimitMutation!==void 0?{rateLimitMutation}:{},...rateLimitRead!==void 0?{rateLimitRead}:{},...rateLimitWindowMs!==void 0?{rateLimitWindowMs}:{},...argv.experimentalLsp===true?{experimentalLsp:true}:{},...argv.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},...channelSelection!==void 0?{channelSelection}:{}};if(openWithAuth){const{applyOpenWithAuth}=await import("./open-with-auth-Z6WKB2OO.js");applyOpenWithAuth(serveOptions)}const handle=await runQwenServe(serveOptions,{updateRestartArgv:process.argv.slice(2)});const joined=argv["join"]?parseJoinLink(argv["join"]):void 0;const hostTarget=joined?{...joined,token:agentHostEnrollmentToken}:argv["agent-host-server"]&&argv["agent-host-workspace-id"]?{serverUrl:argv["agent-host-server"],workspaceId:argv["agent-host-workspace-id"],token:agentHostEnrollmentToken}:void 0;if(hostTarget){try{await handle.runtimeReady;const runtime=handle.getPrimaryWorkspaceRuntime();if(!runtime?.trusted||!runtime.generationGuard||runtime.generationGuard.closed){throw new Error("Agent Host join requires a trusted active workspace.")}const{startAgentHostConnection}=await import("./agent-host-client-HY5GPSHM.js");await startAgentHostConnection({bridge:runtime.bridge,serverUrl:hostTarget.serverUrl,workspaceId:hostTarget.workspaceId,workspaceCwd:runtime.workspaceCwd,allowHttp:argv["agent-host-allow-http"]===true,generationGuard:runtime.generationGuard,...hostTarget.token?{enrollmentToken:hostTarget.token}:{},...argv["agent-host-name"]?{name:argv["agent-host-name"]}:{}})}catch(error){await handle.close().catch(()=>void 0);throw error}}if(argv["local-control"]){try{await startLocalControl(handle,argv["local-control-address"])}catch(err){await handle.close().catch(()=>void 0);throw err}}await maybeOpenWebShellBrowser(handle,open,openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await blockForever()},"handler")};export{parseJoinLink,validateManagedLocalFlags,validateManagedWebFlags,maybeOpenWebShellBrowser,serveCommand};
4
+ ${status.interfaceName}: ${status.url}`);qrcode.generate(status.url,{small:true},code=>{writeStdoutLine(code.trimEnd())});writeStdoutLine("\nKeep this terminal open. "+(status.sleepInhibited?"Sleep is inhibited while this session is active. ":"Sleep inhibition is unavailable here, so the host may sleep. ")+(status.encrypted?"Traffic is encrypted.":"Traffic is unencrypted \u2014 use it only on a network you trust.")+" Turn Local Control off from the Web Shell Settings card, or press Ctrl+C to exit the daemon.")}__name(startLocalControl,"startLocalControl");async function maybeOpenWebShellBrowser(handle,open,manualFallbackWhenIneligible=false){if(!open||!handle.webShellMounted)return;const shouldLaunch=shouldLaunchBrowser();if(!shouldLaunch&&!manualFallbackWhenIneligible)return;try{await handle.runtimeReady}catch(runtimeErr){writeStderrLine(`qwen serve: Web Shell runtime not ready; skipping --open: ${runtimeErr instanceof Error?runtimeErr.message:String(runtimeErr)}`);return}let target;try{target=new URL(handle.url);if(target.hostname==="0.0.0.0"||target.hostname==="[::]"){target.hostname="127.0.0.1"}if(handle.resolvedToken){target.hash=`token=${encodeURIComponent(handle.resolvedToken)}`}if(!shouldLaunch){writeStderrLine(`Browser launch is not available in this environment. Please open this URL manually: ${target.toString()}`);return}if(handle.resolvedToken){writeStderrLine("qwen serve: --open passes the token in the browser launch command (visible via `ps` / /proc); on a multi-user host open the URL manually instead.")}await openBrowserSecurely(target.toString())}catch(browserErr){const manualUrl=manualFallbackWhenIneligible&&target?`. Please open this URL manually: ${target.toString()}`:"";writeStderrLine(`qwen serve: failed to open browser: ${browserErr instanceof Error?browserErr.message:String(browserErr)}${manualUrl}`)}}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function primaryWorkspaceArg(workspace){return Array.isArray(workspace)?workspace[0]:workspace}__name(primaryWorkspaceArg,"primaryWorkspaceArg");var serveCommand={command:"serve",describe:"Run Qwen Code as a local HTTP daemon (Stage 1 experimental: --http-bridge)",builder:__name(yargs=>yargs.option("port",{type:"number",default:4170,description:"TCP port to bind (use 0 for an OS-assigned ephemeral port)"}).option("hostname",{type:"string",default:DEFAULT_SERVE_HOSTNAME,description:"Interface to bind. Loopback (127.0.0.0/8, localhost, ::1, [::1]) is auth-free; anything else requires a token (one is generated and printed when neither --token nor QWEN_SERVER_TOKEN supplies one). A localhost bind that resolves off-loopback never generates, and still refuses when no token source resolved; an empty value is rejected as operator error."}).option("profile",{choices:["default","hosted-harness"],default:"default",description:"Deployment profile. hosted-harness enables the private no-tool Managed Session API on loopback."}).option("hosted-harness-capability-digest",{type:"string",description:"SHA-256 capability digest for the private Hosted Harness profile. Falls back to QWEN_HOSTED_HARNESS_CAPABILITY_DIGEST."}).option("managed",{type:"boolean",default:false,description:"Start the daemon and Managed Agent with shared WebShell and embedded storage; downloads the server on first use and requires Java 21."}).option("managed-data-dir",{type:"string",requiresArg:true,description:"Private persistent data directory for --managed; defaults to <Qwen home>/managed-local."}).option("managed-web-config",{type:"string",requiresArg:true,description:"Run only the authenticated Managed Web gateway using a JSON file with apiUrl, tenantId, actorId and signingKeyFile. Requires a non-empty independent browser token via QWEN_SERVER_TOKEN or --token."}).option("token",{type:"string",description:"Bearer token required on every request. Falls back to the QWEN_SERVER_TOKEN env var; a non-loopback bind with neither generates an ephemeral token at startup, while loopback keeps the trusted tokenless mode unless --require-auth is set."}).option("max-sessions",{type:"number",description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable. Defaults to 32, or to the serve.maxSessions setting (user, system, and system-defaults scopes only); the flag wins when passed."}).option("max-total-sessions",{type:"number",description:"Non-negative integer cap on concurrent live sessions across all workspace runtimes. Set to 0 to disable."}).option("max-pending-prompts-per-session",{type:"number",default:5,description:"Per-session cap on accepted prompts waiting or running. New prompts beyond this return 503. Set to 0 to disable."}).option("workspace",{type:"string",array:true,requiresArg:true,description:"Absolute workspace path to register with this daemon. POST /session requests with a mismatched cwd return 400 workspace_mismatch. Defaults to process.cwd() when omitted. Repeat to register isolated workspace runtimes; the first is primary."}).option("conversations-dir",{type:"string",requiresArg:true,description:"Absolute working-directory root shared by standalone and Live Conversations. Overrides QWEN_CONVERSATIONS_DIR; defaults to ~/Documents/Qwen Code/Conversations."}).option("memory-project-scope",{type:"string",choices:MEMORY_PROJECT_SCOPES,description:'Choose how project memory is partitioned. Defaults to "workspace" so each daemon workspace stays isolated; "git-root" preserves the legacy shared scope. Overrides QWEN_CODE_MEMORY_PROJECT_SCOPE when provided.'}).option("max-connections",{type:"number",default:256,description:"Listener-level TCP connection cap (server.maxConnections). Bounds raw sockets \u2014 slow/phantom SSE clients get rejected at accept time once full. Set to 0 to disable."}).option("require-auth",{type:"boolean",default:false,description:"Refuse to start without a bearer token, even on loopback. Hardens the loopback developer default for shared dev hosts / CI runners / multi-tenant workstations where any local user can hit 127.0.0.1. Requires --token, QWEN_SERVER_TOKEN, or --open-with-auth (which installs its own generated loopback token); on non-loopback binds the generated ephemeral token also satisfies it, so the no-configured-secret fail-fast is loopback-only. /health also requires Authorization when enabled (no loopback exemption \u2014 k8s/Compose probes must pass the bearer too)."}).option("enable-session-shell",{type:"boolean",default:false,description:"Enable direct POST /session/:id/shell execution. Available with bearer auth or trusted loopback; each call still requires a session-bound client id."}).option("tls-cert",{type:"string",description:"Path to a PEM certificate file. Serve over HTTPS instead of HTTP. Required for secure-context browser APIs (voice input/getUserMedia, WebRTC) when accessed over a LAN IP. Must be used together with --tls-key. Generate a local cert with mkcert."}).option("tls-key",{type:"string",description:"Path to a PEM private key file. Must be used together with --tls-cert."}).option("experimental-lsp",{type:"boolean",default:false,description:"Forward the experimental LSP opt-in to spawned agent sessions."}).option("restore-ask-user-question",{type:"boolean",default:false,description:"On session load/resume, re-hang a trailing unanswered ask_user_question instead of synthesizing a failed tool result."}).option("channel",{type:"string",array:true,description:"Experimental: start a daemon-managed channel worker for the named channel. Repeat to select multiple channels, or use --channel all."}).option("web",{type:"boolean",default:true,description:"Serve the Web Shell UI at the daemon root path. Use --no-web for an API-only daemon."}).option("open",{type:"boolean",default:false,description:"Open the Web Shell in a browser once the daemon is listening. With a token configured, the launch URL (token included) is handed to the browser launcher and is visible in the process list, so prefer opening the URL manually on multi-user hosts. No-op with --no-web, when the UI assets are absent, or in headless/CI/SSH environments."}).option("open-with-auth",{type:"boolean",default:false,description:"Open the Web Shell with bearer authentication on loopback. Reuse --token or QWEN_SERVER_TOKEN, or generate a temporary 256-bit token and deliver it in the URL fragment. In headless environments, print the fragment URL for manual opening."}).option("token-qr",{type:"boolean",description:"Print the token-bearing QR even when stdout is captured (not an interactive terminal) and the bearer is an operator-supplied (stable) token, which is withheld by default to keep stable credentials out of collected logs. Enable only when the log pipeline is as trusted as the daemon host. Can also be set via the serve.tokenQr setting (user, system, and system-defaults scopes only); the flag wins when passed. --no-token-qr suppresses the startup quickstart token QR for that run on every quickstart path \u2014 interactive terminal and generated token included. It does not govern the Local Control pairing QR, which --local-control prints by design."}).option("local-control",{type:"boolean",default:false,description:"Share the Web Shell on the local IPv4 network with its own revocable pairing token, terminal QR code, and best-effort sleep inhibition. Ctrl+C turns it off by ending the whole daemon; the Web Shell Settings card turns it off while the daemon keeps running."}).option("local-control-address",{type:"string",description:"Which local IPv4 address to share when the host is on more than one network. Only needed if --local-control reports an ambiguous choice. Naming an address outside RFC 1918/3927 space, or one on a VPN/tunnel interface (e.g. phone and laptop on the same corporate VPN), is accepted as an explicit opt-in; out-of-private-space picks are logged with a warning."}).option("join",{type:"string",description:"Join another Qwen Code as a runtime, with the one-line link it shows under Agent \u2192 Runtime \u2192 Add runtime."}).option("agent-host-server",{type:"string",description:"Register this daemon as an Agent Host with a primary Qwen daemon."}).option("agent-host-workspace-id",{type:"string",description:"Control-plane workspace id printed by the primary daemon."}).option("agent-host-name",{type:"string",description:"Display name advertised for this Agent Host."}).option("agent-host-allow-http",{type:"boolean",default:false,description:"Allow unencrypted Agent Host HTTP connections outside loopback (trusted demo networks only)."}).check(argv=>{if(Array.isArray(argv["conversations-dir"])){throw new Error("pass --conversations-dir once.")}normalizeMaxRingBytes(argv["event-ring-max-bytes"]);if(argv["local-control"]===true&&argv["web"]===false){throw new Error("Local Control requires the Web Shell.")}if(argv["local-control"]===true&&argv.hostname!==DEFAULT_SERVE_HOSTNAME){throw new Error(`Local Control requires --hostname ${DEFAULT_SERVE_HOSTNAME}.`)}if(argv["local-control"]!==true&&argv["local-control-address"]!==void 0){throw new Error("--local-control-address requires --local-control.")}if(argv["local-control-address"]===""){throw new Error("--local-control-address must not be empty.")}if(Boolean(argv["agent-host-server"])!==Boolean(argv["agent-host-workspace-id"])){throw new Error("--agent-host-server and --agent-host-workspace-id must be used together.")}if(argv["agent-host-name"]===""){throw new Error("--agent-host-name must not be empty.")}if(argv["join"]!==void 0){if(argv["agent-host-server"]||argv["agent-host-workspace-id"]){throw new Error("--join already names the coordinator and workspace; drop --agent-host-server and --agent-host-workspace-id.")}parseJoinLink(argv["join"])}return true}).option("event-ring-size",{type:"number",default:DEFAULT_RING_SIZE,description:"Per-session SSE replay ring depth. Sets the replay backlog available to `GET /session/:id/events` reconnects that send a `Last-Event-ID: N` header. Larger = more reconnect headroom at the cost of a few hundred KB extra RAM per session. Must be a positive finite integer."}).option("event-ring-max-bytes",{type:"number",nargs:1,default:DEFAULT_RING_MAX_BYTES,description:"Per-session retained SSE replay ring byte cap, including the latest full commands snapshot. Must be a positive safe integer up to 256 MiB; no unlimited sentinel."}).option("compacted-replay-max-bytes",{type:"number",default:DEFAULT_COMPACTED_REPLAY_MAX_BYTES,description:"Per-session in-memory compacted replay snapshot byte cap for `POST /session/:id/load` late attaches. Larger = more recent history in load snapshots at higher heap cost. Must be a positive safe integer no larger than 256 MiB."}).option("max-journal-events",{type:"number",nargs:1,description:"Per-session baseline cap on replay entries retained in the in-flight live journal (current unfinished turn). Compatible text/thought chunks share bounded entries. When exceeded, the daemon first tries adaptive growth (see --max-journal-bytes); without granted headroom the oldest entries are dropped. Pinning this flag (or --max-journal-bytes) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_EVENTS+" when unset. Must be a positive safe integer."}).option("max-journal-bytes",{type:"number",nargs:1,description:"Per-session baseline source-event byte cap on the in-flight live journal. When a turn outgrows it, adaptive growth raises the session's caps (per-session hard cap "+JOURNAL_GROWTH_HARD_CAP_BYTES/(1024*1024)+" MiB) within a growth pool derived from the daemon memory budget (see --memory-budget-mb); without granted headroom the oldest entries are dropped whole (at least one is always kept), so the retained tail can be much smaller than the cap. Pinning this flag (or --max-journal-events) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_BYTES+" bytes when unset. Must be a positive safe integer."}).option("http-bridge",{type:"boolean",default:true,description:"HTTP bridge mode: attempt to preheat the primary `qwen --acp` child; trusted secondaries start one on demand. Stage 2 native in-process mode is not yet implemented; this flag will become opt-in then."}).option("memory-budget-mb",{type:"number",description:"Total memory budget in MB for the daemon process tree. When unset, derived as 50% of cgroup-constrained or host memory, and capped at the resolved available memory either way. In `admit` and `enforce` modes it determines managed ACP child capacity; `enforce` also applies the modeled per-child old-space ceiling. It also sizes one daemon-wide pool of "+JOURNAL_GROWTH_POOL_FRACTION*100+"% of the effective budget (capped at "+MAX_JOURNAL_GROWTH_POOL_MB+" MB; 0, growth disabled, when the effective budget falls below the "+MIN_MEMORY_BUDGET_MB+" MB minimum; see --max-journal-bytes). Reported under `limits.memory` in daemon status, alongside a modeled per-child partition under `limits.memory.childHeap`. Must be an integer in [1024, 1048576]."}).option("memory-pressure-mode",{choices:["off","observe"],default:"observe",description:"Whether the daemon derives a memory-pressure level from its own RSS and V8 heap. `observe` (default) reports the level in daemon status and raises a status issue when it leaves normal. `off` still reports the underlying figures but raises no issue, so the overall status rollup is unchanged \u2014 use it while calibrating, or if you alert on the top-level status. Nothing remediates in either mode."}).option("child-heap-mode",{choices:["off","observe","admit","enforce"],default:"observe",description:"Whether the daemon models a per-child heap partition of the memory budget. `observe` (default) reports the partition it would apply \u2014 `limits.memory.childHeap.perChildCeilingMb` and `maxConcurrentChildren` \u2014 and counts spawns that would have exceeded it. Nothing is applied: no child is sized from the budget and no spawn is refused. `off` models nothing. Note a refusal count of 0 does NOT mean the partition would be safe to apply; children still run on the much larger host-derived ceiling, so a workload needing more old space than the modeled ceiling looks healthy here. `admit` rejects starts past the modeled process limit but keeps the existing child heap arguments. Experimental `enforce` also applies the fixed modeled old-space ceiling to each managed child; it does not cap total process RSS."}).option("mcp-client-budget",{type:"number",description:"Cap on live MCP clients spawned inside the ACP child for the bound workspace. Positive integer. Combine with --mcp-budget-mode to control behavior at the cap. When unset, mode defaults to off (no accounting-driven enforcement, but GET /workspace/mcp still reports `clientCount`). Distinct from claude-code MCP_SERVER_CONNECTION_BATCH_SIZE which gates startup concurrency, not the total client count."}).option("mcp-budget-mode",{choices:["enforce","warn","off"],description:'How --mcp-client-budget is enforced. `warn` (default when budget set): no refusal, snapshot surfaces warning at >=75% of budget. `enforce`: connects past the cap are refused (`disabledReason: "budget"`, deterministic by mcpServers declaration order). `off`: pure observability. Boot rejects `enforce` without a budget.'}).option("allow-origin",{type:"string",array:true,description:"Cross-origin allowlist for browser clients. Accepts `*`, a canonical origin, or a loopback port wildcard like `http://127.0.0.1:*` (requires a bearer token)."}).option("allow-private-auth-base-url",{type:"boolean",default:false,description:"Allow /workspace/auth/provider to install localhost/private-network baseUrl values. Use only for local development with trusted clients."}).option("prompt-deadline-ms",{type:"number",description:"Server-side wallclock cap on POST /session/:id/prompt (ms). Falls back to QWEN_SERVE_PROMPT_DEADLINE_MS. Positive integer."}).option("experimental-paired-engines",{type:"boolean",default:false,description:"Experimental: build workspace runtimes, other than the private Conversations one, with paired Legacy and Managed engines. No Managed engine is available yet, so sessions run on Legacy with a durable owner."}).option("experimental-managed-agents",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-worker",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-auto-local",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-url",{type:"string",requiresArg:true,description:"Reserved experimental Runtime URL; not implemented and rejects startup."}).option("experimental-managed-runtime-token",{type:"string",requiresArg:true,description:"Reserved experimental Runtime credential; not implemented and rejects startup."}).option("managed-runtime-broker-url",{type:"string",requiresArg:true,description:"Private Broker URL for --profile hosted-harness; required together with token for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_URL."}).option("managed-runtime-broker-token",{type:"string",requiresArg:true,description:"Private Broker credential for --profile hosted-harness; required together with URL for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_TOKEN; prefer the variable, since this option puts the credential in the process list."}).option("writer-idle-timeout-ms",{type:"number",description:"Per-SSE-connection idle deadline (ms). Falls back to QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS. Positive integer."}).option("channel-idle-timeout-ms",{type:"number",description:"Compatibility auto-reap delay for an idle workspace ACP child. 0 or unset = reap after work drains; keepalive windows may extend it (default)."}).option("initialize-timeout-ms",{type:"number",description:"ACP child request timeout, including the initialize handshake (ms). Default: 10000 (10 s)."}).option("session-restore-timeout-ms",{type:"number",description:"ACP session load/resume timeout (ms). Default: 60000. An explicit --initialize-timeout-ms can raise (but never lower) this default."}).option("session-reap-interval-ms",{type:"number",description:"Session reaper scan interval (ms). 0 = disabled. Default: 60000."}).option("session-idle-timeout-ms",{type:"number",description:"Idle timeout before a disconnected session is reaped (ms). 0 = disabled. Default: 1800000 (30 min)."}).option("session-prompt-settled-close-grace-ms",{type:"number",description:"Grace period after a prompt settles before an otherwise-idle session may be auto-closed (ms). Poll-based SSE clients use this window to reconnect without triggering a session rebuild. 0 = disabled (immediate close). Default: 0."}).option("permission-response-timeout-ms",{type:"number",description:"Wall-clock timeout for a human permission / ask_user_question response in daemon (ACP) mode (ms). 0 or unset = disabled (wait indefinitely). Default: 0."}).option("external-tool-guard-mode",{choices:["off","required"],default:"off",description:"Managed ACP pre-execution policy mode. Default off preserves current CLI and daemon behavior. Required fails startup unless a compatible loopback provider is available."}).option("external-tool-guard-endpoint",{type:"string",description:"Origin-only loopback HTTP(S) endpoint for required external tool guarding, for example http://127.0.0.1:8787."}).option("external-tool-guard-timeout-ms",{type:"number",description:"Per-handshake/prepare external tool guard timeout in milliseconds. Default: 3000."}).option("rate-limit",{type:"boolean",description:"Enable per-tier HTTP rate limiting. Tiers: prompt (10/min), mutation (30/min), read (120/min). Health, heartbeat, SSE, and /acp are exempt."}).option("rate-limit-prompt",{type:"number",description:"Max prompt requests per window per client (default 10). Requires --rate-limit."}).option("rate-limit-mutation",{type:"number",description:"Max mutation requests per window per client (default 30). Requires --rate-limit."}).option("rate-limit-read",{type:"number",description:"Max read requests per window per client (default 120). Requires --rate-limit."}).option("rate-limit-window-ms",{type:"number",description:"Rate limit window duration in ms (default 60000). Requires --rate-limit."}),"builder"),handler:__name(async argv=>{if(argv["managed-web-config"]!==void 0){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedWebFlags(process.argv.slice(serveIndex+1));if(argv.managed||argv.profile!=="default"||!argv.web||argv.workspace!==void 0||argv["conversations-dir"]!==void 0){throw new Error("--managed-web-config cannot be combined with daemon execution or Managed local mode.")}const{runManagedWebServe}=await import("./managed-web-serve-34XXVQ7Z.js");const handle=await runManagedWebServe({configFile:argv["managed-web-config"],hostname:argv.hostname,port:argv.port,token:argv.token,allowOrigins:argv["allow-origin"]});writeStdoutLine(`Managed WebShell: ${handle.url}`);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv.managed){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedLocalFlags(process.argv.slice(serveIndex+1));if(argv.hostname!==DEFAULT_SERVE_HOSTNAME||argv.profile!=="default"||!argv.web||argv.workspace!==void 0||argv["conversations-dir"]!==void 0||argv.token!==void 0||argv["tls-cert"]||argv["tls-key"]||argv["local-control"]||argv.join||argv["agent-host-server"]||argv.channel!==void 0||argv["experimental-paired-engines"]||argv["experimental-managed-agents"]||argv["experimental-managed-runtime-worker"]||argv["experimental-managed-runtime-auto-local"]||argv["experimental-managed-runtime-url"]!==void 0||argv["managed-runtime-broker-url"]!==void 0||argv["managed-runtime-broker-token"]!==void 0||argv["allow-origin"]?.length||argv["enable-session-shell"]||!argv["http-bridge"]){throw new Error("--managed uses its own loopback services, persistent credentials, and application-owned Workspaces. Use --port, --managed-data-dir, and --open; other deployment, workspace-import, or execution modes cannot be combined.")}const{runManagedLocalServe}=await import("./managed-local-serve-B2KOLPB5.js");const handle=await runManagedLocalServe({port:argv.port,dataDirectory:argv["managed-data-dir"]});await maybeOpenWebShellBrowser(handle,argv.open||argv["open-with-auth"],argv["open-with-auth"]);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv["managed-data-dir"]!==void 0){writeStderrLine("qwen serve: --managed-data-dir requires --managed.");process.exit(1)}const managedRuntimeBrokerUrl=argv["managed-runtime-broker-url"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];const managedRuntimeBrokerToken=argv["managed-runtime-broker-token"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];const agentHostEnrollmentToken=process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"]?.trim();delete process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"];if(!argv["http-bridge"]){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(argv.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}if(argv["managed-runtime-broker-token"]!==void 0){writeStderrLine("qwen serve: --managed-runtime-broker-token is visible in the process command line; prefer the QWEN_MANAGED_RUNTIME_BROKER_TOKEN env var.")}let channelSelection;try{channelSelection=normalizeServeChannelSelection(argv.channel)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}const mcpClientBudget=argv["mcp-client-budget"];const mcpBudgetMode=argv["mcp-budget-mode"];if(mcpClientBudget!==void 0){if(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0){writeStderrLine("qwen serve: --mcp-client-budget must be a positive integer.");process.exit(1)}}if(mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){writeStderrLine("qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N.");process.exit(1)}const resolvedMcpMode=mcpBudgetMode??(mcpClientBudget!==void 0?"warn":"off");const memoryBudgetMb=argv["memory-budget-mb"];if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){writeStderrLine(memoryBudgetRangeError());process.exit(1)}const maxPendingPromptsPerSession=argv["max-pending-prompts-per-session"];if(maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){writeStderrLine("qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited).");process.exit(1)}if(mcpClientBudget!==void 0){writeStderrLine(`qwen serve: --mcp-client-budget=${mcpClientBudget} mode=${resolvedMcpMode}`+(resolvedMcpMode==="enforce"?" (servers past the cap will be refused at discovery)":resolvedMcpMode==="warn"?` (warnings at >=${Math.ceil(mcpClientBudget*MCP_BUDGET_WARN_FRACTION)}, no refusal)`:""))}try{const loaded=loadSettings(primaryWorkspaceArg(argv.workspace)??process.cwd());const merged=loaded.merged;const approvalMode=merged.tools?.approvalMode;const sandbox=merged.tools?.sandbox;const sandboxEnv=process.env["SANDBOX"];const suppress=process.env["QWEN_CODE_SUPPRESS_YOLO_WARNING"];const suppressed=suppress==="1"||suppress==="true";if(approvalMode==="yolo"&&!sandbox&&!sandboxEnv&&!suppressed){writeStderrLine(HEADLESS_YOLO_NO_SANDBOX_WARNING)}}catch{}const rateLimit=argv["rate-limit"]??(process.env["QWEN_SERVE_RATE_LIMIT"]==="1"||process.env["QWEN_SERVE_RATE_LIMIT"]==="true");let rateLimitPrompt;let rateLimitMutation;let rateLimitRead;let rateLimitWindowMs;if(rateLimit){const envInt=__name(key=>{const raw=process.env[key];if(raw===void 0||raw==="")return void 0;return parsePositiveIntegerEnv(raw,Number.NaN)},"envInt");rateLimitPrompt=argv["rate-limit-prompt"]??envInt("QWEN_SERVE_RATE_LIMIT_PROMPT");rateLimitMutation=argv["rate-limit-mutation"]??envInt("QWEN_SERVE_RATE_LIMIT_MUTATION");rateLimitRead=argv["rate-limit-read"]??envInt("QWEN_SERVE_RATE_LIMIT_READ");rateLimitWindowMs=argv["rate-limit-window-ms"]??envInt("QWEN_SERVE_RATE_LIMIT_WINDOW_MS");for(const[name,value]of[["--rate-limit-prompt",rateLimitPrompt],["--rate-limit-mutation",rateLimitMutation],["--rate-limit-read",rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){writeStderrLine(`qwen serve: ${name} must be a positive integer.`);process.exit(1)}}if(rateLimitWindowMs!==void 0&&(!Number.isFinite(rateLimitWindowMs)||!Number.isInteger(rateLimitWindowMs)||rateLimitWindowMs<1e3)){writeStderrLine("qwen serve: --rate-limit-window-ms must be an integer >= 1000.");process.exit(1)}}const externalToolGuardToken=process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV]??"";delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];const openWithAuth=argv["open-with-auth"];const open=argv.open||openWithAuth;const{runQwenServe}=await import("./run-qwen-serve-4MZRQFXK.js");try{const serveOptions={port:argv.port,hostname:argv.hostname,profile:argv.profile,token:argv.token,mode:"http-bridge",maxSessions:argv["max-sessions"],...argv["max-total-sessions"]!==void 0?{maxTotalSessions:argv["max-total-sessions"]}:{},maxPendingPromptsPerSession,maxConnections:argv["max-connections"],eventRingSize:argv["event-ring-size"],eventRingMaxBytes:argv["event-ring-max-bytes"],compactedReplayMaxBytes:argv["compacted-replay-max-bytes"],...argv["max-journal-events"]!==void 0?{maxJournalEvents:argv["max-journal-events"]}:{},...argv["max-journal-bytes"]!==void 0?{maxJournalBytes:argv["max-journal-bytes"]}:{},workspace:argv.workspace,...argv["conversations-dir"]!==void 0?{conversationsDir:argv["conversations-dir"]}:{},...argv["memory-project-scope"]!==void 0?{memoryProjectScope:argv["memory-project-scope"]}:{},requireAuth:argv["require-auth"],enableSessionShell:argv["enable-session-shell"],serveWebShell:argv.web,...argv["token-qr"]!==void 0?{tokenQr:argv["token-qr"]}:{},...argv["tls-cert"]!==void 0?{tlsCert:argv["tls-cert"]}:{},...argv["tls-key"]!==void 0?{tlsKey:argv["tls-key"]}:{},allowPrivateAuthBaseUrl:argv["allow-private-auth-base-url"],mcpClientBudget,mcpBudgetMode:resolvedMcpMode,...memoryBudgetMb!==void 0?{memoryBudgetMb}:{},memoryPressureMode:argv["memory-pressure-mode"],childHeapMode:argv["child-heap-mode"],...argv["allow-origin"]&&argv["allow-origin"].length>0?{allowOrigins:argv["allow-origin"]}:{},...argv["prompt-deadline-ms"]!==void 0?{promptDeadlineMs:argv["prompt-deadline-ms"]}:{},...argv["experimental-paired-engines"]?{experimentalPairedEngines:true}:{},...argv["experimental-managed-agents"]?{experimentalManagedAgents:true}:{},...argv["experimental-managed-runtime-auto-local"]?{experimentalManagedRuntimeAutoLocal:true}:{},...argv["experimental-managed-runtime-worker"]?{experimentalManagedRuntimeWorker:true}:{},...argv["experimental-managed-runtime-url"]!==void 0?{experimentalManagedRuntimeUrl:argv["experimental-managed-runtime-url"]}:{},...argv["experimental-managed-runtime-token"]!==void 0?{experimentalManagedRuntimeToken:argv["experimental-managed-runtime-token"]}:{},...managedRuntimeBrokerUrl!==void 0?{managedRuntimeBrokerUrl}:{},...managedRuntimeBrokerToken!==void 0?{managedRuntimeBrokerToken}:{},...argv["hosted-harness-capability-digest"]!==void 0?{hostedHarnessCapabilityDigest:argv["hosted-harness-capability-digest"]}:{},...argv["writer-idle-timeout-ms"]!==void 0?{writerIdleTimeoutMs:argv["writer-idle-timeout-ms"]}:{},...argv["channel-idle-timeout-ms"]!==void 0?{channelIdleTimeoutMs:argv["channel-idle-timeout-ms"]}:{},...argv["initialize-timeout-ms"]!==void 0?{initializeTimeoutMs:argv["initialize-timeout-ms"]}:{},...argv["session-restore-timeout-ms"]!==void 0?{sessionRestoreTimeoutMs:argv["session-restore-timeout-ms"]}:{},...argv["session-reap-interval-ms"]!==void 0?{sessionReapIntervalMs:argv["session-reap-interval-ms"]}:{},...argv["session-idle-timeout-ms"]!==void 0?{sessionIdleTimeoutMs:argv["session-idle-timeout-ms"]}:{},...argv["session-prompt-settled-close-grace-ms"]!==void 0?{sessionPromptSettledCloseGraceMs:argv["session-prompt-settled-close-grace-ms"]}:{},...argv["permission-response-timeout-ms"]!==void 0?{permissionResponseTimeoutMs:argv["permission-response-timeout-ms"]}:{},...argv["external-tool-guard-mode"]==="required"?{externalToolGuard:{mode:"required",endpoint:argv["external-tool-guard-endpoint"]??"",token:externalToolGuardToken,...argv["external-tool-guard-timeout-ms"]!==void 0?{timeoutMs:argv["external-tool-guard-timeout-ms"]}:{}}}:{},...rateLimit?{rateLimit:true}:{},...rateLimitPrompt!==void 0?{rateLimitPrompt}:{},...rateLimitMutation!==void 0?{rateLimitMutation}:{},...rateLimitRead!==void 0?{rateLimitRead}:{},...rateLimitWindowMs!==void 0?{rateLimitWindowMs}:{},...argv.experimentalLsp===true?{experimentalLsp:true}:{},...argv.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},...channelSelection!==void 0?{channelSelection}:{}};if(openWithAuth){const{applyOpenWithAuth}=await import("./open-with-auth-Z6WKB2OO.js");applyOpenWithAuth(serveOptions)}const handle=await runQwenServe(serveOptions,{updateRestartArgv:process.argv.slice(2)});const joined=argv["join"]?parseJoinLink(argv["join"]):void 0;const hostTarget=joined?{...joined,token:agentHostEnrollmentToken}:argv["agent-host-server"]&&argv["agent-host-workspace-id"]?{serverUrl:argv["agent-host-server"],workspaceId:argv["agent-host-workspace-id"],token:agentHostEnrollmentToken}:void 0;if(hostTarget){try{await handle.runtimeReady;const runtime=handle.getPrimaryWorkspaceRuntime();if(!runtime?.trusted||!runtime.generationGuard||runtime.generationGuard.closed){throw new Error("Agent Host join requires a trusted active workspace.")}const{startAgentHostConnection}=await import("./agent-host-client-HY5GPSHM.js");await startAgentHostConnection({bridge:runtime.bridge,serverUrl:hostTarget.serverUrl,workspaceId:hostTarget.workspaceId,workspaceCwd:runtime.workspaceCwd,allowHttp:argv["agent-host-allow-http"]===true,generationGuard:runtime.generationGuard,...hostTarget.token?{enrollmentToken:hostTarget.token}:{},...argv["agent-host-name"]?{name:argv["agent-host-name"]}:{}})}catch(error){await handle.close().catch(()=>void 0);throw error}}if(argv["local-control"]){try{await startLocalControl(handle,argv["local-control-address"])}catch(err){await handle.close().catch(()=>void 0);throw err}}await maybeOpenWebShellBrowser(handle,open,openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await blockForever()},"handler")};export{parseJoinLink,validateManagedLocalFlags,validateManagedWebFlags,maybeOpenWebShellBrowser,serveCommand};
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{createManagedContextAttestationResponse,isManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{getCliVersion}from"./chunk-4XV2522J.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync,spawn}from"node:child_process";import{createHash as createHash3,createHmac,randomUUID}from"node:crypto";import{constants as constants3,promises as fs3}from"node:fs";import path3 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";import{constants,promises as fs}from"node:fs";import path from"node:path";var MAX_WORKSPACE_UPLOAD_BYTES=8*1024*1024;var WorkspaceFileError=class extends Error{constructor(code){super("Workspace file request is unavailable.");this.code=code}static{__name(this,"WorkspaceFileError")}};function refuse(code="unavailable"){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse,"refuse");function workspaceFilePath(value){if(value===".")return".";if(typeof value!=="string"||value.length>1024||/[\\\p{Cc}\p{Cs}]/u.test(value)||value.split("/").some(part=>!part||part==="."||part===".."||part===".git"||part===".qwen-child-workspaces"||part.startsWith(".qwen-managed-")))refuse("invalid_path");return value}__name(workspaceFilePath,"workspaceFilePath");function sessionWorkspaceFileScope(value,cwdRelative){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const scope=value;const keys=["sessionId","contextDigest","worktreeId","worktreeRevision","cwdRelative","worktreeRootIdentity"];if(Object.keys(scope).length!==keys.length||keys.some(key=>!(key in scope))||typeof scope["sessionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(scope["sessionId"])||typeof scope["contextDigest"]!=="string"||!/^sha256:[a-f0-9]{64}$/.test(scope["contextDigest"])||typeof scope["worktreeId"]!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(scope["worktreeId"])||!Number.isSafeInteger(scope["worktreeRevision"])||Number(scope["worktreeRevision"])<1||typeof cwdRelative!=="string"||scope["cwdRelative"]!==cwdRelative)refuse("invalid_request");const prefix=`.qwen-managed-worktrees/${scope["worktreeId"]}`;if(cwdRelative!==prefix&&!cwdRelative.startsWith(`${prefix}/`))refuse("invalid_path");workspaceFilePath(cwdRelative.slice(prefix.length+1)||".");const identity=scope["worktreeRootIdentity"];if(!identity||typeof identity!=="object"||Array.isArray(identity))refuse("invalid_request");const fields=identity;if(Object.keys(fields).length!==2||!["device","inode"].every(key=>typeof fields[key]==="string"&&/^\d+$/.test(fields[key])))refuse("invalid_request");return scope}__name(sessionWorkspaceFileScope,"sessionWorkspaceFileScope");function signature(stat){return[stat.dev,stat.ino,stat.birthtimeNs,stat.size,stat.mtimeNs,stat.ctimeNs].join(":")}__name(signature,"signature");async function workspaceFileDirectories(root,cwdRelative,expected,sessionScope){const scope=sessionWorkspaceFileScope(sessionScope,cwdRelative);const cwd=scope?.cwdRelative??workspaceFilePath(cwdRelative);const worktreeRoot=scope?path.join(root,".qwen-managed-worktrees",scope.worktreeId):void 0;const anchors=new Map;async function directory(relative){const segments=relative==="."?[]:relative.split("/");let current=root;for(const segment of["",...segments]){if(segment)current=path.join(current,segment);const stat=await fs.lstat(current,{bigint:true});if(!stat.isDirectory()||await fs.realpath(current)!==current)refuse();if(current===root&&(String(stat.dev)!==expected.device||String(stat.ino)!==expected.inode))refuse();if(scope&&current===worktreeRoot&&(String(stat.dev)!==scope.worktreeRootIdentity.device||String(stat.ino)!==scope.worktreeRootIdentity.inode))refuse("changed");const prior=anchors.get(current);const identity=[stat.dev,stat.ino,stat.birthtimeNs].join(":");if(prior&&prior!==identity)refuse("changed");anchors.set(current,identity)}return current}__name(directory,"directory");async function verify(){for(const[name,identity]of anchors){const stat=await fs.lstat(name,{bigint:true});if(!stat.isDirectory()||await fs.realpath(name)!==name||[stat.dev,stat.ino,stat.birthtimeNs].join(":")!==identity)refuse("changed")}}__name(verify,"verify");const base=await directory(cwd);const rooted=__name(relative=>cwd==="."?relative:relative==="."?cwd:`${cwd}/${relative}`,"rooted");return{base,directory:__name(relative=>directory(rooted(relative)),"directory"),verify}}__name(workspaceFileDirectories,"workspaceFileDirectories");async function readWorkspaceFiles(root,cwdRelative,value,expected,sessionScope){if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const request=value;if(request["protocolVersion"]!==1)refuse("unsupported");const{base,directory,verify}=await workspaceFileDirectories(root,cwdRelative,expected,sessionScope);if(request["operation"]==="read"){const relative2=workspaceFilePath(request["path"]);if(relative2===".")refuse("invalid_path");const parent=path.posix.dirname(relative2);await directory(parent);const filename=path.join(base,relative2);const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(!before.isFile()||before.size===0n||before.size>24n*1024n)refuse("unsupported_content");const bytes=Buffer.alloc(24*1024+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}if(BigInt(size)!==before.size||signature(before)!==signature(await handle.stat({bigint:true}))||signature(before)!==signature(await fs.lstat(filename,{bigint:true})))refuse("changed");let text2;try{text2=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(bytes.subarray(0,size))}catch{return refuse("unsupported_content")}if(!text2||text2.includes("\0"))refuse("unsupported_content");await verify();const result={protocolVersion:1,path:relative2,name:path.posix.basename(relative2),mimeType:"text/plain",text:text2,byteLength:size,sha256:createHash("sha256").update(bytes.subarray(0,size)).digest("hex")};if(Buffer.byteLength(JSON.stringify(result))>48*1024)refuse("too_large");return result}finally{await handle.close()}}if(request["operation"]!=="query")refuse("invalid_request");const relative=workspaceFilePath(request["directory"]??".");const query=request["query"]??"";if(typeof query!=="string"||query.length>256||/[\p{Cc}\p{Cs}]/u.test(query))refuse("invalid_request");const entries=[];let scanned=0;let truncated=false;const deadline=Date.now()+2e3;const queue=[{relative,depth:0}];while(queue.length){const next=queue.shift();const dir=await directory(next.relative);const stream=await fs.opendir(dir);for await(const entry of stream){if(++scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}const name=next.relative==="."?entry.name:`${next.relative}/${entry.name}`;try{workspaceFilePath(name)}catch{continue}if(!entry.isFile()&&!entry.isDirectory())continue;if(query&&entry.isDirectory()){if(next.depth<32)queue.push({relative:name,depth:next.depth+1});else truncated=true}if(query&&(entry.isDirectory()||!name.toLowerCase().includes(query.toLowerCase())))continue;const item={path:name,name:entry.name,kind:entry.isDirectory()?"directory":"file"};if(Buffer.byteLength(JSON.stringify([...entries,item]))>24*1024){truncated=true;break}entries.push(item)}if(scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}}await verify();return{protocolVersion:1,directory:relative,entries,truncated,maxUploadBytes:MAX_WORKSPACE_UPLOAD_BYTES}}__name(readWorkspaceFiles,"readWorkspaceFiles");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{constants as constants2,promises as fs2}from"node:fs";import path2 from"node:path";function refuse2(code){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse2,"refuse");function failed(metadata,error){return workspaceUploadResult(metadata,"failed",error instanceof WorkspaceFileError?error.code:error.code==="EEXIST"?"ssh_runtime_file_exists":"ssh_runtime_file_unavailable")}__name(failed,"failed");function workspaceUploadRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))refuse2("invalid_request");const request=value;if(request["protocolVersion"]!==1||!["upload","upload-status"].includes(String(request["operation"]))||typeof request["uploadId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(request["uploadId"])||!Number.isSafeInteger(request["sizeBytes"])||Number(request["sizeBytes"])<0||Number(request["sizeBytes"])>MAX_WORKSPACE_UPLOAD_BYTES||typeof request["sha256"]!=="string"||!/^[0-9a-f]{64}$/.test(request["sha256"]))refuse2("invalid_request");const relative=workspaceFilePath(request["path"]);if(relative===".")refuse2("invalid_path");const metadata={uploadId:request["uploadId"],path:relative,sizeBytes:Number(request["sizeBytes"]),sha256:request["sha256"]};if(request["operation"]==="upload-status"){if(request["data"]!==void 0)refuse2("invalid_request");return{metadata}}const data=request["data"];if(typeof data!=="string"||data.length!==Math.ceil(metadata.sizeBytes/3)*4)refuse2("invalid_content");const bytes=Buffer.from(data,"base64");if(bytes.length!==metadata.sizeBytes||bytes.toString("base64")!==data||createHash2("sha256").update(bytes).digest("hex")!==metadata.sha256)refuse2("invalid_content");return{metadata,bytes}}__name(workspaceUploadRequest,"workspaceUploadRequest");function workspaceUploadResult(metadata,state,code){return{protocolVersion:1,...metadata,state,...code===void 0?{}:{code}}}__name(workspaceUploadResult,"workspaceUploadResult");function temporaryPath(directory,metadata){return path2.join(directory,`.qwen-managed-upload-${metadata.uploadId}.tmp`)}__name(temporaryPath,"temporaryPath");async function removeTemporary(temporary){try{await fs2.unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}}__name(removeTemporary,"removeTemporary");async function syncDirectory(directory){const handle=await fs2.open(directory,"r");try{await handle.sync()}finally{await handle.close()}}__name(syncDirectory,"syncDirectory");async function writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope){let directories;let parent;try{await verifyStorage();directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);parent=await directories.directory(path2.posix.dirname(metadata.path))}catch(error){return failed(metadata,error)}const destination=path2.join(directories.base,metadata.path);const temporary=temporaryPath(parent,metadata);let ownsTemporary=false;let result;try{const handle=await fs2.open(temporary,"wx",384);ownsTemporary=true;try{await handle.writeFile(bytes);await handle.sync()}finally{await handle.close()}await directories.verify();await verifyStorage();await fs2.link(temporary,destination);await directories.verify();await verifyStorage();result=workspaceUploadResult(metadata,"completed")}catch(error){result=failed(metadata,error)}finally{if(ownsTemporary){await directories.verify();await removeTemporary(temporary);await syncDirectory(parent)}}return result}__name(writeWorkspaceUpload,"writeWorkspaceUpload");async function inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope){await verifyStorage();const directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);const parent=await directories.directory(path2.posix.dirname(metadata.path));const destination=path2.join(directories.base,metadata.path);let completed=false;try{const handle=await fs2.open(destination,constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(before.isFile()&&before.size===BigInt(metadata.sizeBytes)){const bytes=Buffer.alloc(metadata.sizeBytes+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}const after=await handle.stat({bigint:true});const current=await fs2.lstat(destination,{bigint:true});completed=size===metadata.sizeBytes&&before.dev===current.dev&&before.ino===current.ino&&before.mtimeNs===after.mtimeNs&&before.ctimeNs===after.ctimeNs&&before.size===after.size&&after.ctimeNs===current.ctimeNs&&createHash2("sha256").update(bytes.subarray(0,size)).digest("hex")===metadata.sha256}}finally{await handle.close()}}catch(error){if(!["ENOENT","ELOOP"].includes(error.code??""))throw error}await directories.verify();await verifyStorage();await removeTemporary(temporaryPath(parent,metadata));await syncDirectory(parent);return workspaceUploadResult(metadata,completed?"completed":"failed",completed?void 0:"ssh_runtime_file_upload_incomplete")}__name(inspectWorkspaceUpload,"inspectWorkspaceUpload");var MARKER=".qwen-managed-storage.json";var MAX_BYTES=64*1024;var MAX_UPLOAD_REQUEST_BYTES=12*1024*1024;var ID=/^[a-zA-Z0-9_.:-]{1,512}$/;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var hostId;var SSH_RETIRE_PATH="/internal/managed-runtime/v3/retire";var SshBootstrapError=class extends Error{constructor(code,message,retryable=false){super(message);this.code=code;this.retryable=retryable}static{__name(this,"SshBootstrapError")}};function refuse3(message){throw new SshBootstrapError("ssh_runtime_identity_conflict",message)}__name(refuse3,"refuse");function object(value){if(!value||typeof value!=="object"||Array.isArray(value))return refuse3("Runtime bootstrap document is invalid.");return value}__name(object,"object");function text(value){if(typeof value!=="string"||!value||value.includes("\0"))return refuse3("Runtime bootstrap text is invalid.");return value}__name(text,"text");function absolute(value){const directory=text(value);if(!path3.isAbsolute(directory)||path3.resolve(directory)!==directory)return refuse3("Runtime path must be absolute and normalized.");return directory}__name(absolute,"absolute");function within(root,candidate){const relative=path3.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path3.sep}`)&&!path3.isAbsolute(relative)}__name(within,"within");function exact(value,fields){if(Object.keys(value).length!==fields.length||fields.some(field=>!(field in value)))refuse3("Runtime bootstrap document has unexpected fields.")}__name(exact,"exact");async function readSshPrivateJson(file){const stat=await fs3.lstat(file);if(!stat.isFile()||stat.size>MAX_BYTES||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state file is not owner-private.");return JSON.parse(await fs3.readFile(file,"utf8"))}__name(readSshPrivateJson,"readSshPrivateJson");async function syncParentDirectory(file){const directory=await fs3.open(path3.dirname(file),"r");try{await directory.sync()}finally{await directory.close()}}__name(syncParentDirectory,"syncParentDirectory");async function writeSshPrivateJson(file,value){if(!await createSshPrivateJson(file,value)&&!isDeepStrictEqual(await readSshPrivateJson(file),value))refuse3("Runtime state conflicts with an earlier operation.")}__name(writeSshPrivateJson,"writeSshPrivateJson");async function createSshPrivateJson(file,value){const temporary=path3.join(path3.dirname(file),`.${path3.basename(file)}.${randomUUID()}.tmp`);const handle=await fs3.open(temporary,"wx",384);let created=true;try{try{await handle.writeFile(JSON.stringify(value),"utf8");await handle.sync()}finally{await handle.close()}try{await fs3.link(temporary,file)}catch(error){if(error.code!=="EEXIST")throw error;created=false}}finally{await fs3.unlink(temporary)}await syncParentDirectory(file);return created}__name(createSshPrivateJson,"createSshPrivateJson");async function privateDirectory(directory){const created=await fs3.mkdir(directory,{recursive:true,mode:448});const stat=await fs3.lstat(directory);if(!stat.isDirectory()||await fs3.realpath(directory)!==directory||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state directory must be canonical and owner-private.");for(let current=directory;;current=path3.dirname(current)){await syncParentDirectory(current);if(created===void 0||current===created)break}}__name(privateDirectory,"privateDirectory");function identityDocument(value){const identity=object(value);exact(identity,["root","hostId","device","inode","birthTime"]);absolute(identity["root"]);if(!/^[0-9a-f]{64}$/.test(text(identity["hostId"]))||!/^\d+$/.test(text(identity["device"]))||!/^\d+$/.test(text(identity["inode"]))||!Number.isFinite(Date.parse(text(identity["birthTime"]))))refuse3("Storage identity is invalid.");return identity}__name(identityDocument,"identityDocument");function markerDocument(value,identity){const marker=object(value);exact(marker,["version","tenantId","storageId","root","hostId","device","inode","birthTime","registrationId"]);if(marker["version"]!==2||!UUID.test(text(marker["registrationId"]))||!ID.test(text(marker["tenantId"]))||!ID.test(text(marker["storageId"]))||Object.entries(identity).some(([key,item])=>marker[key]!==item))refuse3("Storage marker does not bind the registered identity.");return marker}__name(markerDocument,"markerDocument");async function readMachineIdentity(){try{if(process.platform==="linux")return(await fs3.readFile("/etc/machine-id","utf8")).trim();return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(execFileSync("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:MAX_BYTES}))?.[1]}catch{return void 0}}__name(readMachineIdentity,"readMachineIdentity");async function inspectSshStorage(root){if(!["linux","darwin"].includes(process.platform))throw new SshBootstrapError("ssh_runtime_platform_unsupported","Runtime requires Linux or macOS.");if(absolute(root)!==await fs3.realpath(root))refuse3("Storage root is not canonical.");const stat=await fs3.lstat(root,{bigint:true});if(!stat.isDirectory()||stat.birthtimeNs<=0n)refuse3("Storage directory has no independent birth identity.");await fs3.access(root,constants3.R_OK|constants3.W_OK|constants3.X_OK);const machine=hostId?void 0:await readMachineIdentity();if(!hostId){if(!machine||machine.length>256)refuse3("Stable host identity is unavailable.");hostId=createHmac("sha256",machine).update("Qwen-Code/verified-workspace/v2").digest("hex")}const seconds=stat.birthtimeNs/1000000000n;const nanos=(stat.birthtimeNs%1000000000n).toString().padStart(9,"0");const fraction=nanos==="000000000"?"":`.${nanos.endsWith("000000")?nanos.slice(0,3):nanos.endsWith("000")?nanos.slice(0,6):nanos}`;return{root,hostId,device:BigInt.asUintN(64,stat.dev).toString(),inode:BigInt.asUintN(64,stat.ino).toString(),birthTime:new Date(Number(seconds)*1e3).toISOString().replace(/\.000Z$/,`${fraction}Z`)}}__name(inspectSshStorage,"inspectSshStorage");async function verifySshStorage(identity,marker){if(!isDeepStrictEqual(await inspectSshStorage(identity.root),identity))refuse3("Registered storage identity changed.");if(marker&&!isDeepStrictEqual(await readSshPrivateJson(path3.join(identity.root,MARKER)),marker))refuse3("Registered storage marker changed.")}__name(verifySshStorage,"verifySshStorage");function resourceDirectory(stateDirectory,resourceId){if(!UUID.test(resourceId))refuse3("Runtime resource identity is invalid.");return path3.join(stateDirectory,"resources",resourceId)}__name(resourceDirectory,"resourceDirectory");async function readSshRuntimeRecord(directory){const value=object(await readSshPrivateJson(path3.join(directory,"intent.json")));exact(value,["version","nodeId","stateDirectory","resourceId","bindingId","bindingGeneration","boot","identity","marker","workerEntry","expectedQwenVersion"]);const identity=identityDocument(value["identity"]);const boot=parseManagedContextBoot(value["boot"]);const marker=markerDocument(value["marker"],identity);if(value["version"]!==1||!ID.test(text(value["nodeId"]))||!ID.test(text(value["bindingId"]))||!Number.isSafeInteger(value["bindingGeneration"])||Number(value["bindingGeneration"])<=0||boot.isolationClass!=="session"||boot.mountRoot!==identity.root||boot.tenantId!==marker.tenantId||boot.storageId!==marker.storageId||resourceDirectory(absolute(value["stateDirectory"]),text(value["resourceId"]))!==directory)refuse3("Runtime intent identity is invalid.");absolute(value["workerEntry"]);text(value["expectedQwenVersion"]);return value}__name(readSshRuntimeRecord,"readSshRuntimeRecord");function sshCleanProof(record,retirementId,retiredAt){return{version:record.boot.managedExtensions?2:1,...record.boot.managedExtensions?{executionMode:record.boot.managedExtensions.mode,scope:record.boot.managedExtensions.mode==="linux-cgroup"?"process_tree":"process_group"}:{},resourceId:record.resourceId,bindingId:record.bindingId,bindingGeneration:record.bindingGeneration,provisionRequestId:record.boot.provisionRequestId,runtimeInstanceId:record.boot.runtimeInstanceId,runtimeIncarnation:record.boot.runtimeIncarnation,leaseId:record.boot.leaseId,epoch:record.boot.epoch,retirementId,retiredAt}}__name(sshCleanProof,"sshCleanProof");function alive(pid){try{process.kill(pid,0);return true}catch(error){if(error.code==="ESRCH")return false;throw new SshBootstrapError("ssh_runtime_stop_unverified","Original process liveness is unverified.")}}__name(alive,"alive");async function optionalJson(file){try{return await readSshPrivateJson(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(optionalJson,"optionalJson");async function observe(record){await verifySshStorage(record.identity,record.marker);const directory=resourceDirectory(record.stateDirectory,record.resourceId);const pidRecord=await optionalJson(path3.join(directory,"pid.json"));const pid=pidRecord===void 0?null:object(pidRecord)["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Runtime process record is invalid.");const result={resourceId:record.resourceId,state:"INTENT",pid,ready:null};const claim=await optionalJson(path3.join(directory,"launch.claim"));if(claim===void 0){for(const file of["pid.json","ready.json","clean.json","stdout.log","stderr.log","launch-failed.json"]){try{await fs3.lstat(path3.join(directory,file))}catch(error){if(error.code==="ENOENT")continue;throw error}refuse3("Runtime launch claim is missing from an existing resource.")}return result}const claimedRetirement=object(claim)["retirementId"];const neverStarted=typeof claimedRetirement==="string"&&UUID.test(claimedRetirement);if(!isDeepStrictEqual(claim,neverStarted?{provisionRequestId:record.boot.provisionRequestId,retirementId:claimedRetirement}:{provisionRequestId:record.boot.provisionRequestId}))refuse3("Runtime launch claim conflicts.");if(neverStarted&&pid!==null)refuse3("A retired launch claim cannot own a worker process.");const failed2=await optionalJson(path3.join(directory,"launch-failed.json"));if(failed2!==void 0&&(!isDeepStrictEqual(failed2,{provisionRequestId:record.boot.provisionRequestId})||pid!==null||await optionalJson(path3.join(directory,"ready.json"))!==void 0))refuse3("Runtime failed-launch evidence conflicts.");const clean=await optionalJson(path3.join(directory,"clean.json"));if(clean!==void 0){const proof=object(clean);const retiredAt=text(proof["retiredAt"]);const stop=object(await readSshPrivateJson(path3.join(directory,"stop.json")));if(!Number.isFinite(Date.parse(retiredAt))||!isDeepStrictEqual(clean,sshCleanProof(record,text(stop["retirementId"]),retiredAt)))refuse3("Runtime clean proof conflicts.");if((neverStarted||failed2!==void 0)&&pid===null&&(failed2!==void 0||claimedRetirement===stop["retirementId"])||pid!==null&&!alive(Number(pid)))return{...result,state:"RETIRED",cleanProof:clean};return{...result,state:"BLOCKED"}}if(failed2!==void 0)return{...result,state:"FAILED"};if(neverStarted&&pid===null)return result;if(pid===null||!alive(Number(pid)))return{...result,state:"BLOCKED"};const ready=await optionalJson(path3.join(directory,"ready.json"));if(ready===void 0)return{...result,state:"STARTING"};const value=object(ready);if(!isManagedContextReady(value,record.boot))refuse3("Runtime ready identity conflicts.");return{...result,state:"READY",ready:value}}__name(observe,"observe");async function attest(record,ready){const expected=createManagedContextAttestationResponse(record.boot);const{runtimeInstanceId:_runtime,runtimeIncarnation:_incarnation,leaseId:_lease,epoch:_epoch,...request}=expected;const response=await fetch(`${ready.url}/internal/managed-runtime/v3/attest`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify(request),redirect:"error",signal:AbortSignal.timeout(5e3)});if(!response.ok||!isDeepStrictEqual(await response.json(),expected))refuse3("Original Runtime attestation failed.")}__name(attest,"attest");function sshRuntimeHeaders(boot){return{Authorization:`Bearer ${boot.token}`,"Cache-Control":"no-store","Content-Type":"application/json","X-Qwen-Managed-Lease-Id":boot.leaseId,"X-Qwen-Managed-Lease-Epoch":String(boot.epoch)}}__name(sshRuntimeHeaders,"sshRuntimeHeaders");async function ensure(request,nodeId,stateDirectory){const resourceId=text(request["resourceId"]);const expectedQwenVersion=text(request["expectedQwenVersion"]);if(expectedQwenVersion!==await getCliVersion()){throw new SshBootstrapError("ssh_runtime_version_conflict","Pinned Qwen version does not match this installation.")}const directory=resourceDirectory(stateDirectory,resourceId);const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity,marker);await privateDirectory(directory);const record={version:1,nodeId,stateDirectory,resourceId,bindingId:request["bindingId"],bindingGeneration:request["bindingGeneration"],boot:request["boot"],identity,marker,workerEntry:absolute(request["workerEntry"]),expectedQwenVersion};await writeSshPrivateJson(path3.join(directory,"intent.json"),record);const saved=await readSshRuntimeRecord(directory);if(typeof request["launch"]!=="boolean")refuse3("Runtime launch phase is required.");if(!request["launch"])return observe(saved);if(await optionalJson(path3.join(directory,"stop.json"))!==void 0)return observe(saved);const original=await observe(saved);if(original["state"]!=="INTENT")return original;if(!await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:saved.boot.provisionRequestId}))return observe(saved);let spawned=false;try{const output=await fs3.open(path3.join(directory,"stdout.log"),"ax",384);try{const errors=await fs3.open(path3.join(directory,"stderr.log"),"ax",384);try{const env={};for(const key of["PATH","HOME","USER","LOGNAME","SHELL","LANG","LC_ALL","TMPDIR","TMP","TEMP","TZ"]){if(process.env[key]!==void 0)env[key]=process.env[key]}const child=spawn(process.execPath,[saved.workerEntry,"managed-runtime-bootstrap-worker",directory],{cwd:path3.dirname(saved.workerEntry),detached:true,stdio:["ignore",output.fd,errors.fd],env});await new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",reject)});spawned=true;child.unref();await writeSshPrivateJson(path3.join(directory,"pid.json"),{pid:child.pid})}finally{await errors.close()}}finally{await output.close()}}catch{if(!spawned){await writeSshPrivateJson(path3.join(directory,"launch-failed.json"),{provisionRequestId:saved.boot.provisionRequestId});return observe(saved)}}for(let attempt=0;attempt<100;attempt++){const observed=await observe(saved);if(observed["state"]!=="STARTING"&&!(observed["state"]==="BLOCKED"&&observed["pid"]===null))return observed;await new Promise(resolve=>setTimeout(resolve,50))}return observe(saved)}__name(ensure,"ensure");async function workspaceUpload(request,expected,verifyStorage,sessionScope){const{metadata,bytes}=workspaceUploadRequest(request["files"]);const root=absolute(request["root"]);const cwd=sessionScope?.cwdRelative??workspaceFilePath(request["cwdRelative"]);const target={nodeId:request["nodeId"],root,cwd,expected,identity:request["identity"]??null,marker:request["marker"]??null,...sessionScope?{sessionFileScope:sessionScope}:{},...metadata};const canonical=__name(value=>value&&typeof value==="object"&&!Array.isArray(value)?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,item])=>[key,canonical(item)])):value,"canonical");const requestDigest=createHash3("sha256").update(JSON.stringify(canonical(target))).digest("hex");const stateDirectory=absolute(request["stateDirectory"]);await privateDirectory(stateDirectory);const directory=path3.join(stateDirectory,"workspace-uploads",metadata.uploadId);await privateDirectory(directory);const claimPath=path3.join(directory,"claim.json");const receiptPath=path3.join(directory,"receipt.json");let claim=await optionalJson(claimPath);let started=false;if(claim===void 0){if(await optionalJson(receiptPath)!==void 0)refuse3("Workspace upload claim is unavailable.");const proposed={version:1,target,requestDigest,pid:bytes===void 0?null:process.pid};started=await createSshPrivateJson(claimPath,proposed);claim=started?proposed:await readSshPrivateJson(claimPath)}const saved=object(claim);exact(saved,["version","target","requestDigest","pid"]);if(saved["version"]!==1||saved["requestDigest"]!==requestDigest||!isDeepStrictEqual(saved["target"],target))throw new WorkspaceFileError("ssh_runtime_file_upload_conflict");const pid=saved["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Workspace upload process identity is invalid.");const receipt=await optionalJson(receiptPath);if(receipt!==void 0){const result2=object(receipt);if(!["completed","failed"].includes(String(result2["state"]))||result2["state"]==="failed"&&typeof result2["code"]!=="string"||!isDeepStrictEqual(receipt,workspaceUploadResult(metadata,result2["state"],result2["code"])))refuse3("Workspace upload receipt is invalid.");return receipt}let result;if(pid===null){result=workspaceUploadResult(metadata,"failed","ssh_runtime_file_upload_not_started")}else if(started&&bytes!==void 0){result=await writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope)}else{let live=true;try{live=alive(Number(pid))}catch{}if(live)return workspaceUploadResult(metadata,"pending");result=await inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope)}await writeSshPrivateJson(receiptPath,result);return result}__name(workspaceUpload,"workspaceUpload");async function executeSshBootstrap(value){const request=object(value);if(request["protocolVersion"]!==1||!ID.test(text(request["nodeId"])))refuse3("Runtime bootstrap protocol is invalid.");const nodeId=text(request["nodeId"]);const stateDirectory=absolute(request["stateDirectory"]);const operation=text(request["operation"]);if(operation==="probe"||operation==="ensure"){if(Number(process.versions.node.split(".")[0])<22){throw new SshBootstrapError("ssh_runtime_node_unsupported","Runtime requires Node.js 22 or later.")}}if(operation==="probe"){const root=absolute(request["root"]);const roots=request["allowedRoots"];if(!Array.isArray(roots)||roots.length===0||!roots.some(candidate=>within(absolute(candidate),root)))refuse3("Directory is outside the configured roots.");if(within(root,stateDirectory)||within(stateDirectory,root))refuse3("Runtime state and Workspace roots must not overlap.");if(request["files"]!==void 0){const fileOperation=object(request["files"])["operation"];const uploading=["upload","upload-status"].includes(String(fileOperation));const identity2=request["identity"]===void 0?void 0:identityDocument(request["identity"]);const marker=identity2?markerDocument(request["marker"],identity2):void 0;if(identity2&&identity2.root!==root)refuse3("Storage root conflicts.");if(identity2&&!uploading)await verifySshStorage(identity2,marker);const expected=identity2??object(request["localRootIdentity"]);try{if(request["sessionFileScope"]!==void 0&&identity2)refuse3("Session file scopes require local storage.");const sessionScope=sessionWorkspaceFileScope(request["sessionFileScope"],request["cwdRelative"]);const fileIdentity={device:text(expected.device),inode:text(expected.inode)};const files=uploading?await workspaceUpload(request,fileIdentity,async()=>{if(identity2)await verifySshStorage(identity2,marker)},sessionScope):await readWorkspaceFiles(root,text(request["cwdRelative"]),request["files"],fileIdentity,sessionScope);if(identity2&&!uploading)await verifySshStorage(identity2,marker);return{qwenVersion:await getCliVersion(),files}}catch(error){if(error instanceof WorkspaceFileError)throw new SshBootstrapError(error.code,error.message);throw error}}const identity=await inspectSshStorage(root);if(request["cwdRelative"]!==void 0){const relative=text(request["cwdRelative"]);const cwd=path3.resolve(root,relative);if(path3.isAbsolute(relative)||!within(root,cwd)||cwd!==await fs3.realpath(cwd)||!(await fs3.stat(cwd)).isDirectory())refuse3("Working directory is unavailable.");await fs3.access(cwd,constants3.R_OK|constants3.W_OK|constants3.X_OK)}return{platform:process.platform,nodeVersion:process.version,qwenVersion:await getCliVersion(),identity,marker:await optionalJson(path3.join(root,MARKER))??null}}if(operation==="register-storage"){const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity);await writeSshPrivateJson(path3.join(identity.root,MARKER),marker);await verifySshStorage(identity,marker);return{identity,marker}}await privateDirectory(stateDirectory);if(operation==="ensure")return ensure(request,nodeId,stateDirectory);const directory=resourceDirectory(stateDirectory,text(request["resourceId"]));const record=await readSshRuntimeRecord(directory);if(record.nodeId!==nodeId||record.stateDirectory!==stateDirectory)refuse3("Runtime node identity conflicts.");let observed=await observe(record);if(operation==="observe")return observed;if(operation!=="stop")refuse3("Runtime bootstrap operation is unsupported.");const retirementId=text(request["retirementId"]);if(!UUID.test(retirementId))refuse3("Runtime retirement identity is invalid.");if(observed["state"]==="INTENT"){await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:record.boot.provisionRequestId,retirementId});observed=await observe(record)}const claim=object(await readSshPrivateJson(path3.join(directory,"launch.claim")));if(claim["retirementId"]!==void 0&&claim["retirementId"]!==retirementId)refuse3("Runtime retirement identity conflicts.");if(observed["state"]==="RETIRED"){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});return observed}if(observed["state"]==="FAILED"||claim["retirementId"]===retirementId){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});await verifySshStorage(record.identity,record.marker);await writeSshPrivateJson(path3.join(directory,"clean.json"),sshCleanProof(record,retirementId,new Date().toISOString()));return observe(record)}if(observed["state"]==="STARTING"||observed["state"]==="BLOCKED"&&observed["pid"]===null)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime startup has not completed.",true);if(observed["state"]!=="READY")throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime is not reachable for clean retirement.");await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});const ready=observed["ready"];try{await attest(record,ready);const response=await fetch(`${ready.url}${SSH_RETIRE_PATH}`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify({protocolVersion:1,resourceId:record.resourceId,retirementId}),redirect:"error",signal:AbortSignal.timeout(15e3)});if(!response.ok)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement is not proven.",true);await response.arrayBuffer()}catch(error){if(error instanceof SshBootstrapError)throw error;if((await observe(record))["state"]!=="RETIRED")throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement response is unavailable.",true)}for(let attempt=0;attempt<100;attempt++){const result=await observe(record);if(result["state"]==="RETIRED")return result;await new Promise(resolve=>setTimeout(resolve,50))}throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime process has not exited.",true)}__name(executeSshBootstrap,"executeSshBootstrap");async function runManagedRuntimeBootstrap(help=false,workspaceFileUpload=false){if(help){process.stdout.write(`${JSON.stringify({protocolVersion:1,capabilities:{workspaceFiles:1,workspaceFileUpload:1}})}
3
+ import{createManagedContextAttestationResponse,isManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{getCliVersion}from"./chunk-YVORE4W4.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync,spawn}from"node:child_process";import{createHash as createHash3,createHmac,randomUUID}from"node:crypto";import{constants as constants3,promises as fs3}from"node:fs";import path3 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";import{constants,promises as fs}from"node:fs";import path from"node:path";var MAX_WORKSPACE_UPLOAD_BYTES=8*1024*1024;var WorkspaceFileError=class extends Error{constructor(code){super("Workspace file request is unavailable.");this.code=code}static{__name(this,"WorkspaceFileError")}};function refuse(code="unavailable"){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse,"refuse");function workspaceFilePath(value){if(value===".")return".";if(typeof value!=="string"||value.length>1024||/[\\\p{Cc}\p{Cs}]/u.test(value)||value.split("/").some(part=>!part||part==="."||part===".."||part===".git"||part===".qwen-child-workspaces"||part.startsWith(".qwen-managed-")))refuse("invalid_path");return value}__name(workspaceFilePath,"workspaceFilePath");function sessionWorkspaceFileScope(value,cwdRelative){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const scope=value;const keys=["sessionId","contextDigest","worktreeId","worktreeRevision","cwdRelative","worktreeRootIdentity"];if(Object.keys(scope).length!==keys.length||keys.some(key=>!(key in scope))||typeof scope["sessionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(scope["sessionId"])||typeof scope["contextDigest"]!=="string"||!/^sha256:[a-f0-9]{64}$/.test(scope["contextDigest"])||typeof scope["worktreeId"]!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(scope["worktreeId"])||!Number.isSafeInteger(scope["worktreeRevision"])||Number(scope["worktreeRevision"])<1||typeof cwdRelative!=="string"||scope["cwdRelative"]!==cwdRelative)refuse("invalid_request");const prefix=`.qwen-managed-worktrees/${scope["worktreeId"]}`;if(cwdRelative!==prefix&&!cwdRelative.startsWith(`${prefix}/`))refuse("invalid_path");workspaceFilePath(cwdRelative.slice(prefix.length+1)||".");const identity=scope["worktreeRootIdentity"];if(!identity||typeof identity!=="object"||Array.isArray(identity))refuse("invalid_request");const fields=identity;if(Object.keys(fields).length!==2||!["device","inode"].every(key=>typeof fields[key]==="string"&&/^\d+$/.test(fields[key])))refuse("invalid_request");return scope}__name(sessionWorkspaceFileScope,"sessionWorkspaceFileScope");function signature(stat){return[stat.dev,stat.ino,stat.birthtimeNs,stat.size,stat.mtimeNs,stat.ctimeNs].join(":")}__name(signature,"signature");async function workspaceFileDirectories(root,cwdRelative,expected,sessionScope){const scope=sessionWorkspaceFileScope(sessionScope,cwdRelative);const cwd=scope?.cwdRelative??workspaceFilePath(cwdRelative);const worktreeRoot=scope?path.join(root,".qwen-managed-worktrees",scope.worktreeId):void 0;const anchors=new Map;async function directory(relative){const segments=relative==="."?[]:relative.split("/");let current=root;for(const segment of["",...segments]){if(segment)current=path.join(current,segment);const stat=await fs.lstat(current,{bigint:true});if(!stat.isDirectory()||await fs.realpath(current)!==current)refuse();if(current===root&&(String(stat.dev)!==expected.device||String(stat.ino)!==expected.inode))refuse();if(scope&&current===worktreeRoot&&(String(stat.dev)!==scope.worktreeRootIdentity.device||String(stat.ino)!==scope.worktreeRootIdentity.inode))refuse("changed");const prior=anchors.get(current);const identity=[stat.dev,stat.ino,stat.birthtimeNs].join(":");if(prior&&prior!==identity)refuse("changed");anchors.set(current,identity)}return current}__name(directory,"directory");async function verify(){for(const[name,identity]of anchors){const stat=await fs.lstat(name,{bigint:true});if(!stat.isDirectory()||await fs.realpath(name)!==name||[stat.dev,stat.ino,stat.birthtimeNs].join(":")!==identity)refuse("changed")}}__name(verify,"verify");const base=await directory(cwd);const rooted=__name(relative=>cwd==="."?relative:relative==="."?cwd:`${cwd}/${relative}`,"rooted");return{base,directory:__name(relative=>directory(rooted(relative)),"directory"),verify}}__name(workspaceFileDirectories,"workspaceFileDirectories");async function readWorkspaceFiles(root,cwdRelative,value,expected,sessionScope){if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const request=value;if(request["protocolVersion"]!==1)refuse("unsupported");const{base,directory,verify}=await workspaceFileDirectories(root,cwdRelative,expected,sessionScope);if(request["operation"]==="read"){const relative2=workspaceFilePath(request["path"]);if(relative2===".")refuse("invalid_path");const parent=path.posix.dirname(relative2);await directory(parent);const filename=path.join(base,relative2);const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(!before.isFile()||before.size===0n||before.size>24n*1024n)refuse("unsupported_content");const bytes=Buffer.alloc(24*1024+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}if(BigInt(size)!==before.size||signature(before)!==signature(await handle.stat({bigint:true}))||signature(before)!==signature(await fs.lstat(filename,{bigint:true})))refuse("changed");let text2;try{text2=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(bytes.subarray(0,size))}catch{return refuse("unsupported_content")}if(!text2||text2.includes("\0"))refuse("unsupported_content");await verify();const result={protocolVersion:1,path:relative2,name:path.posix.basename(relative2),mimeType:"text/plain",text:text2,byteLength:size,sha256:createHash("sha256").update(bytes.subarray(0,size)).digest("hex")};if(Buffer.byteLength(JSON.stringify(result))>48*1024)refuse("too_large");return result}finally{await handle.close()}}if(request["operation"]!=="query")refuse("invalid_request");const relative=workspaceFilePath(request["directory"]??".");const query=request["query"]??"";if(typeof query!=="string"||query.length>256||/[\p{Cc}\p{Cs}]/u.test(query))refuse("invalid_request");const entries=[];let scanned=0;let truncated=false;const deadline=Date.now()+2e3;const queue=[{relative,depth:0}];while(queue.length){const next=queue.shift();const dir=await directory(next.relative);const stream=await fs.opendir(dir);for await(const entry of stream){if(++scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}const name=next.relative==="."?entry.name:`${next.relative}/${entry.name}`;try{workspaceFilePath(name)}catch{continue}if(!entry.isFile()&&!entry.isDirectory())continue;if(query&&entry.isDirectory()){if(next.depth<32)queue.push({relative:name,depth:next.depth+1});else truncated=true}if(query&&(entry.isDirectory()||!name.toLowerCase().includes(query.toLowerCase())))continue;const item={path:name,name:entry.name,kind:entry.isDirectory()?"directory":"file"};if(Buffer.byteLength(JSON.stringify([...entries,item]))>24*1024){truncated=true;break}entries.push(item)}if(scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}}await verify();return{protocolVersion:1,directory:relative,entries,truncated,maxUploadBytes:MAX_WORKSPACE_UPLOAD_BYTES}}__name(readWorkspaceFiles,"readWorkspaceFiles");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{constants as constants2,promises as fs2}from"node:fs";import path2 from"node:path";function refuse2(code){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse2,"refuse");function failed(metadata,error){return workspaceUploadResult(metadata,"failed",error instanceof WorkspaceFileError?error.code:error.code==="EEXIST"?"ssh_runtime_file_exists":"ssh_runtime_file_unavailable")}__name(failed,"failed");function workspaceUploadRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))refuse2("invalid_request");const request=value;if(request["protocolVersion"]!==1||!["upload","upload-status"].includes(String(request["operation"]))||typeof request["uploadId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(request["uploadId"])||!Number.isSafeInteger(request["sizeBytes"])||Number(request["sizeBytes"])<0||Number(request["sizeBytes"])>MAX_WORKSPACE_UPLOAD_BYTES||typeof request["sha256"]!=="string"||!/^[0-9a-f]{64}$/.test(request["sha256"]))refuse2("invalid_request");const relative=workspaceFilePath(request["path"]);if(relative===".")refuse2("invalid_path");const metadata={uploadId:request["uploadId"],path:relative,sizeBytes:Number(request["sizeBytes"]),sha256:request["sha256"]};if(request["operation"]==="upload-status"){if(request["data"]!==void 0)refuse2("invalid_request");return{metadata}}const data=request["data"];if(typeof data!=="string"||data.length!==Math.ceil(metadata.sizeBytes/3)*4)refuse2("invalid_content");const bytes=Buffer.from(data,"base64");if(bytes.length!==metadata.sizeBytes||bytes.toString("base64")!==data||createHash2("sha256").update(bytes).digest("hex")!==metadata.sha256)refuse2("invalid_content");return{metadata,bytes}}__name(workspaceUploadRequest,"workspaceUploadRequest");function workspaceUploadResult(metadata,state,code){return{protocolVersion:1,...metadata,state,...code===void 0?{}:{code}}}__name(workspaceUploadResult,"workspaceUploadResult");function temporaryPath(directory,metadata){return path2.join(directory,`.qwen-managed-upload-${metadata.uploadId}.tmp`)}__name(temporaryPath,"temporaryPath");async function removeTemporary(temporary){try{await fs2.unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}}__name(removeTemporary,"removeTemporary");async function syncDirectory(directory){const handle=await fs2.open(directory,"r");try{await handle.sync()}finally{await handle.close()}}__name(syncDirectory,"syncDirectory");async function writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope){let directories;let parent;try{await verifyStorage();directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);parent=await directories.directory(path2.posix.dirname(metadata.path))}catch(error){return failed(metadata,error)}const destination=path2.join(directories.base,metadata.path);const temporary=temporaryPath(parent,metadata);let ownsTemporary=false;let result;try{const handle=await fs2.open(temporary,"wx",384);ownsTemporary=true;try{await handle.writeFile(bytes);await handle.sync()}finally{await handle.close()}await directories.verify();await verifyStorage();await fs2.link(temporary,destination);await directories.verify();await verifyStorage();result=workspaceUploadResult(metadata,"completed")}catch(error){result=failed(metadata,error)}finally{if(ownsTemporary){await directories.verify();await removeTemporary(temporary);await syncDirectory(parent)}}return result}__name(writeWorkspaceUpload,"writeWorkspaceUpload");async function inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope){await verifyStorage();const directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);const parent=await directories.directory(path2.posix.dirname(metadata.path));const destination=path2.join(directories.base,metadata.path);let completed=false;try{const handle=await fs2.open(destination,constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(before.isFile()&&before.size===BigInt(metadata.sizeBytes)){const bytes=Buffer.alloc(metadata.sizeBytes+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}const after=await handle.stat({bigint:true});const current=await fs2.lstat(destination,{bigint:true});completed=size===metadata.sizeBytes&&before.dev===current.dev&&before.ino===current.ino&&before.mtimeNs===after.mtimeNs&&before.ctimeNs===after.ctimeNs&&before.size===after.size&&after.ctimeNs===current.ctimeNs&&createHash2("sha256").update(bytes.subarray(0,size)).digest("hex")===metadata.sha256}}finally{await handle.close()}}catch(error){if(!["ENOENT","ELOOP"].includes(error.code??""))throw error}await directories.verify();await verifyStorage();await removeTemporary(temporaryPath(parent,metadata));await syncDirectory(parent);return workspaceUploadResult(metadata,completed?"completed":"failed",completed?void 0:"ssh_runtime_file_upload_incomplete")}__name(inspectWorkspaceUpload,"inspectWorkspaceUpload");var MARKER=".qwen-managed-storage.json";var MAX_BYTES=64*1024;var MAX_UPLOAD_REQUEST_BYTES=12*1024*1024;var ID=/^[a-zA-Z0-9_.:-]{1,512}$/;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var hostId;var SSH_RETIRE_PATH="/internal/managed-runtime/v3/retire";var SshBootstrapError=class extends Error{constructor(code,message,retryable=false){super(message);this.code=code;this.retryable=retryable}static{__name(this,"SshBootstrapError")}};function refuse3(message){throw new SshBootstrapError("ssh_runtime_identity_conflict",message)}__name(refuse3,"refuse");function object(value){if(!value||typeof value!=="object"||Array.isArray(value))return refuse3("Runtime bootstrap document is invalid.");return value}__name(object,"object");function text(value){if(typeof value!=="string"||!value||value.includes("\0"))return refuse3("Runtime bootstrap text is invalid.");return value}__name(text,"text");function absolute(value){const directory=text(value);if(!path3.isAbsolute(directory)||path3.resolve(directory)!==directory)return refuse3("Runtime path must be absolute and normalized.");return directory}__name(absolute,"absolute");function within(root,candidate){const relative=path3.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path3.sep}`)&&!path3.isAbsolute(relative)}__name(within,"within");function exact(value,fields){if(Object.keys(value).length!==fields.length||fields.some(field=>!(field in value)))refuse3("Runtime bootstrap document has unexpected fields.")}__name(exact,"exact");async function readSshPrivateJson(file){const stat=await fs3.lstat(file);if(!stat.isFile()||stat.size>MAX_BYTES||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state file is not owner-private.");return JSON.parse(await fs3.readFile(file,"utf8"))}__name(readSshPrivateJson,"readSshPrivateJson");async function syncParentDirectory(file){const directory=await fs3.open(path3.dirname(file),"r");try{await directory.sync()}finally{await directory.close()}}__name(syncParentDirectory,"syncParentDirectory");async function writeSshPrivateJson(file,value){if(!await createSshPrivateJson(file,value)&&!isDeepStrictEqual(await readSshPrivateJson(file),value))refuse3("Runtime state conflicts with an earlier operation.")}__name(writeSshPrivateJson,"writeSshPrivateJson");async function createSshPrivateJson(file,value){const temporary=path3.join(path3.dirname(file),`.${path3.basename(file)}.${randomUUID()}.tmp`);const handle=await fs3.open(temporary,"wx",384);let created=true;try{try{await handle.writeFile(JSON.stringify(value),"utf8");await handle.sync()}finally{await handle.close()}try{await fs3.link(temporary,file)}catch(error){if(error.code!=="EEXIST")throw error;created=false}}finally{await fs3.unlink(temporary)}await syncParentDirectory(file);return created}__name(createSshPrivateJson,"createSshPrivateJson");async function privateDirectory(directory){const created=await fs3.mkdir(directory,{recursive:true,mode:448});const stat=await fs3.lstat(directory);if(!stat.isDirectory()||await fs3.realpath(directory)!==directory||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state directory must be canonical and owner-private.");for(let current=directory;;current=path3.dirname(current)){await syncParentDirectory(current);if(created===void 0||current===created)break}}__name(privateDirectory,"privateDirectory");function identityDocument(value){const identity=object(value);exact(identity,["root","hostId","device","inode","birthTime"]);absolute(identity["root"]);if(!/^[0-9a-f]{64}$/.test(text(identity["hostId"]))||!/^\d+$/.test(text(identity["device"]))||!/^\d+$/.test(text(identity["inode"]))||!Number.isFinite(Date.parse(text(identity["birthTime"]))))refuse3("Storage identity is invalid.");return identity}__name(identityDocument,"identityDocument");function markerDocument(value,identity){const marker=object(value);exact(marker,["version","tenantId","storageId","root","hostId","device","inode","birthTime","registrationId"]);if(marker["version"]!==2||!UUID.test(text(marker["registrationId"]))||!ID.test(text(marker["tenantId"]))||!ID.test(text(marker["storageId"]))||Object.entries(identity).some(([key,item])=>marker[key]!==item))refuse3("Storage marker does not bind the registered identity.");return marker}__name(markerDocument,"markerDocument");async function readMachineIdentity(){try{if(process.platform==="linux")return(await fs3.readFile("/etc/machine-id","utf8")).trim();return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(execFileSync("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:MAX_BYTES}))?.[1]}catch{return void 0}}__name(readMachineIdentity,"readMachineIdentity");async function inspectSshStorage(root){if(!["linux","darwin"].includes(process.platform))throw new SshBootstrapError("ssh_runtime_platform_unsupported","Runtime requires Linux or macOS.");if(absolute(root)!==await fs3.realpath(root))refuse3("Storage root is not canonical.");const stat=await fs3.lstat(root,{bigint:true});if(!stat.isDirectory()||stat.birthtimeNs<=0n)refuse3("Storage directory has no independent birth identity.");await fs3.access(root,constants3.R_OK|constants3.W_OK|constants3.X_OK);const machine=hostId?void 0:await readMachineIdentity();if(!hostId){if(!machine||machine.length>256)refuse3("Stable host identity is unavailable.");hostId=createHmac("sha256",machine).update("Qwen-Code/verified-workspace/v2").digest("hex")}const seconds=stat.birthtimeNs/1000000000n;const nanos=(stat.birthtimeNs%1000000000n).toString().padStart(9,"0");const fraction=nanos==="000000000"?"":`.${nanos.endsWith("000000")?nanos.slice(0,3):nanos.endsWith("000")?nanos.slice(0,6):nanos}`;return{root,hostId,device:BigInt.asUintN(64,stat.dev).toString(),inode:BigInt.asUintN(64,stat.ino).toString(),birthTime:new Date(Number(seconds)*1e3).toISOString().replace(/\.000Z$/,`${fraction}Z`)}}__name(inspectSshStorage,"inspectSshStorage");async function verifySshStorage(identity,marker){if(!isDeepStrictEqual(await inspectSshStorage(identity.root),identity))refuse3("Registered storage identity changed.");if(marker&&!isDeepStrictEqual(await readSshPrivateJson(path3.join(identity.root,MARKER)),marker))refuse3("Registered storage marker changed.")}__name(verifySshStorage,"verifySshStorage");function resourceDirectory(stateDirectory,resourceId){if(!UUID.test(resourceId))refuse3("Runtime resource identity is invalid.");return path3.join(stateDirectory,"resources",resourceId)}__name(resourceDirectory,"resourceDirectory");async function readSshRuntimeRecord(directory){const value=object(await readSshPrivateJson(path3.join(directory,"intent.json")));exact(value,["version","nodeId","stateDirectory","resourceId","bindingId","bindingGeneration","boot","identity","marker","workerEntry","expectedQwenVersion"]);const identity=identityDocument(value["identity"]);const boot=parseManagedContextBoot(value["boot"]);const marker=markerDocument(value["marker"],identity);if(value["version"]!==1||!ID.test(text(value["nodeId"]))||!ID.test(text(value["bindingId"]))||!Number.isSafeInteger(value["bindingGeneration"])||Number(value["bindingGeneration"])<=0||boot.isolationClass!=="session"||boot.mountRoot!==identity.root||boot.tenantId!==marker.tenantId||boot.storageId!==marker.storageId||resourceDirectory(absolute(value["stateDirectory"]),text(value["resourceId"]))!==directory)refuse3("Runtime intent identity is invalid.");absolute(value["workerEntry"]);text(value["expectedQwenVersion"]);return value}__name(readSshRuntimeRecord,"readSshRuntimeRecord");function sshCleanProof(record,retirementId,retiredAt){return{version:record.boot.managedExtensions?2:1,...record.boot.managedExtensions?{executionMode:record.boot.managedExtensions.mode,scope:record.boot.managedExtensions.mode==="linux-cgroup"?"process_tree":"process_group"}:{},resourceId:record.resourceId,bindingId:record.bindingId,bindingGeneration:record.bindingGeneration,provisionRequestId:record.boot.provisionRequestId,runtimeInstanceId:record.boot.runtimeInstanceId,runtimeIncarnation:record.boot.runtimeIncarnation,leaseId:record.boot.leaseId,epoch:record.boot.epoch,retirementId,retiredAt}}__name(sshCleanProof,"sshCleanProof");function alive(pid){try{process.kill(pid,0);return true}catch(error){if(error.code==="ESRCH")return false;throw new SshBootstrapError("ssh_runtime_stop_unverified","Original process liveness is unverified.")}}__name(alive,"alive");async function optionalJson(file){try{return await readSshPrivateJson(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(optionalJson,"optionalJson");async function observe(record){await verifySshStorage(record.identity,record.marker);const directory=resourceDirectory(record.stateDirectory,record.resourceId);const pidRecord=await optionalJson(path3.join(directory,"pid.json"));const pid=pidRecord===void 0?null:object(pidRecord)["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Runtime process record is invalid.");const result={resourceId:record.resourceId,state:"INTENT",pid,ready:null};const claim=await optionalJson(path3.join(directory,"launch.claim"));if(claim===void 0){for(const file of["pid.json","ready.json","clean.json","stdout.log","stderr.log","launch-failed.json"]){try{await fs3.lstat(path3.join(directory,file))}catch(error){if(error.code==="ENOENT")continue;throw error}refuse3("Runtime launch claim is missing from an existing resource.")}return result}const claimedRetirement=object(claim)["retirementId"];const neverStarted=typeof claimedRetirement==="string"&&UUID.test(claimedRetirement);if(!isDeepStrictEqual(claim,neverStarted?{provisionRequestId:record.boot.provisionRequestId,retirementId:claimedRetirement}:{provisionRequestId:record.boot.provisionRequestId}))refuse3("Runtime launch claim conflicts.");if(neverStarted&&pid!==null)refuse3("A retired launch claim cannot own a worker process.");const failed2=await optionalJson(path3.join(directory,"launch-failed.json"));if(failed2!==void 0&&(!isDeepStrictEqual(failed2,{provisionRequestId:record.boot.provisionRequestId})||pid!==null||await optionalJson(path3.join(directory,"ready.json"))!==void 0))refuse3("Runtime failed-launch evidence conflicts.");const clean=await optionalJson(path3.join(directory,"clean.json"));if(clean!==void 0){const proof=object(clean);const retiredAt=text(proof["retiredAt"]);const stop=object(await readSshPrivateJson(path3.join(directory,"stop.json")));if(!Number.isFinite(Date.parse(retiredAt))||!isDeepStrictEqual(clean,sshCleanProof(record,text(stop["retirementId"]),retiredAt)))refuse3("Runtime clean proof conflicts.");if((neverStarted||failed2!==void 0)&&pid===null&&(failed2!==void 0||claimedRetirement===stop["retirementId"])||pid!==null&&!alive(Number(pid)))return{...result,state:"RETIRED",cleanProof:clean};return{...result,state:"BLOCKED"}}if(failed2!==void 0)return{...result,state:"FAILED"};if(neverStarted&&pid===null)return result;if(pid===null||!alive(Number(pid)))return{...result,state:"BLOCKED"};const ready=await optionalJson(path3.join(directory,"ready.json"));if(ready===void 0)return{...result,state:"STARTING"};const value=object(ready);if(!isManagedContextReady(value,record.boot))refuse3("Runtime ready identity conflicts.");return{...result,state:"READY",ready:value}}__name(observe,"observe");async function attest(record,ready){const expected=createManagedContextAttestationResponse(record.boot);const{runtimeInstanceId:_runtime,runtimeIncarnation:_incarnation,leaseId:_lease,epoch:_epoch,...request}=expected;const response=await fetch(`${ready.url}/internal/managed-runtime/v3/attest`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify(request),redirect:"error",signal:AbortSignal.timeout(5e3)});if(!response.ok||!isDeepStrictEqual(await response.json(),expected))refuse3("Original Runtime attestation failed.")}__name(attest,"attest");function sshRuntimeHeaders(boot){return{Authorization:`Bearer ${boot.token}`,"Cache-Control":"no-store","Content-Type":"application/json","X-Qwen-Managed-Lease-Id":boot.leaseId,"X-Qwen-Managed-Lease-Epoch":String(boot.epoch)}}__name(sshRuntimeHeaders,"sshRuntimeHeaders");async function ensure(request,nodeId,stateDirectory){const resourceId=text(request["resourceId"]);const expectedQwenVersion=text(request["expectedQwenVersion"]);if(expectedQwenVersion!==await getCliVersion()){throw new SshBootstrapError("ssh_runtime_version_conflict","Pinned Qwen version does not match this installation.")}const directory=resourceDirectory(stateDirectory,resourceId);const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity,marker);await privateDirectory(directory);const record={version:1,nodeId,stateDirectory,resourceId,bindingId:request["bindingId"],bindingGeneration:request["bindingGeneration"],boot:request["boot"],identity,marker,workerEntry:absolute(request["workerEntry"]),expectedQwenVersion};await writeSshPrivateJson(path3.join(directory,"intent.json"),record);const saved=await readSshRuntimeRecord(directory);if(typeof request["launch"]!=="boolean")refuse3("Runtime launch phase is required.");if(!request["launch"])return observe(saved);if(await optionalJson(path3.join(directory,"stop.json"))!==void 0)return observe(saved);const original=await observe(saved);if(original["state"]!=="INTENT")return original;if(!await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:saved.boot.provisionRequestId}))return observe(saved);let spawned=false;try{const output=await fs3.open(path3.join(directory,"stdout.log"),"ax",384);try{const errors=await fs3.open(path3.join(directory,"stderr.log"),"ax",384);try{const env={};for(const key of["PATH","HOME","USER","LOGNAME","SHELL","LANG","LC_ALL","TMPDIR","TMP","TEMP","TZ"]){if(process.env[key]!==void 0)env[key]=process.env[key]}const child=spawn(process.execPath,[saved.workerEntry,"managed-runtime-bootstrap-worker",directory],{cwd:path3.dirname(saved.workerEntry),detached:true,stdio:["ignore",output.fd,errors.fd],env});await new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",reject)});spawned=true;child.unref();await writeSshPrivateJson(path3.join(directory,"pid.json"),{pid:child.pid})}finally{await errors.close()}}finally{await output.close()}}catch{if(!spawned){await writeSshPrivateJson(path3.join(directory,"launch-failed.json"),{provisionRequestId:saved.boot.provisionRequestId});return observe(saved)}}for(let attempt=0;attempt<100;attempt++){const observed=await observe(saved);if(observed["state"]!=="STARTING"&&!(observed["state"]==="BLOCKED"&&observed["pid"]===null))return observed;await new Promise(resolve=>setTimeout(resolve,50))}return observe(saved)}__name(ensure,"ensure");async function workspaceUpload(request,expected,verifyStorage,sessionScope){const{metadata,bytes}=workspaceUploadRequest(request["files"]);const root=absolute(request["root"]);const cwd=sessionScope?.cwdRelative??workspaceFilePath(request["cwdRelative"]);const target={nodeId:request["nodeId"],root,cwd,expected,identity:request["identity"]??null,marker:request["marker"]??null,...sessionScope?{sessionFileScope:sessionScope}:{},...metadata};const canonical=__name(value=>value&&typeof value==="object"&&!Array.isArray(value)?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,item])=>[key,canonical(item)])):value,"canonical");const requestDigest=createHash3("sha256").update(JSON.stringify(canonical(target))).digest("hex");const stateDirectory=absolute(request["stateDirectory"]);await privateDirectory(stateDirectory);const directory=path3.join(stateDirectory,"workspace-uploads",metadata.uploadId);await privateDirectory(directory);const claimPath=path3.join(directory,"claim.json");const receiptPath=path3.join(directory,"receipt.json");let claim=await optionalJson(claimPath);let started=false;if(claim===void 0){if(await optionalJson(receiptPath)!==void 0)refuse3("Workspace upload claim is unavailable.");const proposed={version:1,target,requestDigest,pid:bytes===void 0?null:process.pid};started=await createSshPrivateJson(claimPath,proposed);claim=started?proposed:await readSshPrivateJson(claimPath)}const saved=object(claim);exact(saved,["version","target","requestDigest","pid"]);if(saved["version"]!==1||saved["requestDigest"]!==requestDigest||!isDeepStrictEqual(saved["target"],target))throw new WorkspaceFileError("ssh_runtime_file_upload_conflict");const pid=saved["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Workspace upload process identity is invalid.");const receipt=await optionalJson(receiptPath);if(receipt!==void 0){const result2=object(receipt);if(!["completed","failed"].includes(String(result2["state"]))||result2["state"]==="failed"&&typeof result2["code"]!=="string"||!isDeepStrictEqual(receipt,workspaceUploadResult(metadata,result2["state"],result2["code"])))refuse3("Workspace upload receipt is invalid.");return receipt}let result;if(pid===null){result=workspaceUploadResult(metadata,"failed","ssh_runtime_file_upload_not_started")}else if(started&&bytes!==void 0){result=await writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope)}else{let live=true;try{live=alive(Number(pid))}catch{}if(live)return workspaceUploadResult(metadata,"pending");result=await inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope)}await writeSshPrivateJson(receiptPath,result);return result}__name(workspaceUpload,"workspaceUpload");async function executeSshBootstrap(value){const request=object(value);if(request["protocolVersion"]!==1||!ID.test(text(request["nodeId"])))refuse3("Runtime bootstrap protocol is invalid.");const nodeId=text(request["nodeId"]);const stateDirectory=absolute(request["stateDirectory"]);const operation=text(request["operation"]);if(operation==="probe"||operation==="ensure"){if(Number(process.versions.node.split(".")[0])<22){throw new SshBootstrapError("ssh_runtime_node_unsupported","Runtime requires Node.js 22 or later.")}}if(operation==="probe"){const root=absolute(request["root"]);const roots=request["allowedRoots"];if(!Array.isArray(roots)||roots.length===0||!roots.some(candidate=>within(absolute(candidate),root)))refuse3("Directory is outside the configured roots.");if(within(root,stateDirectory)||within(stateDirectory,root))refuse3("Runtime state and Workspace roots must not overlap.");if(request["files"]!==void 0){const fileOperation=object(request["files"])["operation"];const uploading=["upload","upload-status"].includes(String(fileOperation));const identity2=request["identity"]===void 0?void 0:identityDocument(request["identity"]);const marker=identity2?markerDocument(request["marker"],identity2):void 0;if(identity2&&identity2.root!==root)refuse3("Storage root conflicts.");if(identity2&&!uploading)await verifySshStorage(identity2,marker);const expected=identity2??object(request["localRootIdentity"]);try{if(request["sessionFileScope"]!==void 0&&identity2)refuse3("Session file scopes require local storage.");const sessionScope=sessionWorkspaceFileScope(request["sessionFileScope"],request["cwdRelative"]);const fileIdentity={device:text(expected.device),inode:text(expected.inode)};const files=uploading?await workspaceUpload(request,fileIdentity,async()=>{if(identity2)await verifySshStorage(identity2,marker)},sessionScope):await readWorkspaceFiles(root,text(request["cwdRelative"]),request["files"],fileIdentity,sessionScope);if(identity2&&!uploading)await verifySshStorage(identity2,marker);return{qwenVersion:await getCliVersion(),files}}catch(error){if(error instanceof WorkspaceFileError)throw new SshBootstrapError(error.code,error.message);throw error}}const identity=await inspectSshStorage(root);if(request["cwdRelative"]!==void 0){const relative=text(request["cwdRelative"]);const cwd=path3.resolve(root,relative);if(path3.isAbsolute(relative)||!within(root,cwd)||cwd!==await fs3.realpath(cwd)||!(await fs3.stat(cwd)).isDirectory())refuse3("Working directory is unavailable.");await fs3.access(cwd,constants3.R_OK|constants3.W_OK|constants3.X_OK)}return{platform:process.platform,nodeVersion:process.version,qwenVersion:await getCliVersion(),identity,marker:await optionalJson(path3.join(root,MARKER))??null}}if(operation==="register-storage"){const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity);await writeSshPrivateJson(path3.join(identity.root,MARKER),marker);await verifySshStorage(identity,marker);return{identity,marker}}await privateDirectory(stateDirectory);if(operation==="ensure")return ensure(request,nodeId,stateDirectory);const directory=resourceDirectory(stateDirectory,text(request["resourceId"]));const record=await readSshRuntimeRecord(directory);if(record.nodeId!==nodeId||record.stateDirectory!==stateDirectory)refuse3("Runtime node identity conflicts.");let observed=await observe(record);if(operation==="observe")return observed;if(operation!=="stop")refuse3("Runtime bootstrap operation is unsupported.");const retirementId=text(request["retirementId"]);if(!UUID.test(retirementId))refuse3("Runtime retirement identity is invalid.");if(observed["state"]==="INTENT"){await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:record.boot.provisionRequestId,retirementId});observed=await observe(record)}const claim=object(await readSshPrivateJson(path3.join(directory,"launch.claim")));if(claim["retirementId"]!==void 0&&claim["retirementId"]!==retirementId)refuse3("Runtime retirement identity conflicts.");if(observed["state"]==="RETIRED"){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});return observed}if(observed["state"]==="FAILED"||claim["retirementId"]===retirementId){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});await verifySshStorage(record.identity,record.marker);await writeSshPrivateJson(path3.join(directory,"clean.json"),sshCleanProof(record,retirementId,new Date().toISOString()));return observe(record)}if(observed["state"]==="STARTING"||observed["state"]==="BLOCKED"&&observed["pid"]===null)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime startup has not completed.",true);if(observed["state"]!=="READY")throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime is not reachable for clean retirement.");await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});const ready=observed["ready"];try{await attest(record,ready);const response=await fetch(`${ready.url}${SSH_RETIRE_PATH}`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify({protocolVersion:1,resourceId:record.resourceId,retirementId}),redirect:"error",signal:AbortSignal.timeout(15e3)});if(!response.ok)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement is not proven.",true);await response.arrayBuffer()}catch(error){if(error instanceof SshBootstrapError)throw error;if((await observe(record))["state"]!=="RETIRED")throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement response is unavailable.",true)}for(let attempt=0;attempt<100;attempt++){const result=await observe(record);if(result["state"]==="RETIRED")return result;await new Promise(resolve=>setTimeout(resolve,50))}throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime process has not exited.",true)}__name(executeSshBootstrap,"executeSshBootstrap");async function runManagedRuntimeBootstrap(help=false,workspaceFileUpload=false){if(help){process.stdout.write(`${JSON.stringify({protocolVersion:1,capabilities:{workspaceFiles:1,workspaceFileUpload:1}})}
4
4
  `);return}let response;try{const chunks=[];let size=0;for await(const chunk of process.stdin){const bytes=Buffer.from(chunk);size+=bytes.length;if(size>(workspaceFileUpload?MAX_UPLOAD_REQUEST_BYTES:MAX_BYTES))refuse3("Runtime bootstrap request exceeds its limit.");chunks.push(bytes)}const source=new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks));const request=object(JSON.parse(source));const files=request["files"];const upload=files&&typeof files==="object"&&!Array.isArray(files)?["upload","upload-status"].includes(String(files["operation"])):false;if(workspaceFileUpload!==upload||upload&&request["operation"]!=="probe")refuse3("Workspace upload requires its dedicated bootstrap entry.");response={protocolVersion:1,ok:true,result:await executeSshBootstrap(request)}}catch(error){const known=error instanceof SshBootstrapError?error:new SshBootstrapError("ssh_runtime_state_unavailable","Runtime bootstrap state is unavailable.");response={protocolVersion:1,ok:false,error:{code:known.code,message:known.message,retryable:known.retryable}}}process.stdout.write(`${JSON.stringify(response)}
5
5
  `)}__name(runManagedRuntimeBootstrap,"runManagedRuntimeBootstrap");function sshResourcePath(record){return resourceDirectory(record.stateDirectory,record.resourceId)}__name(sshResourcePath,"sshResourcePath");export{SSH_RETIRE_PATH,SshBootstrapError,readSshPrivateJson,writeSshPrivateJson,inspectSshStorage,verifySshStorage,readSshRuntimeRecord,sshCleanProof,sshRuntimeHeaders,executeSshBootstrap,runManagedRuntimeBootstrap,sshResourcePath};
6
6
  /**