@hostclubeos/miraos 0.0.6-beta → 0.0.7-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 (39) hide show
  1. package/chunks/{acpAgent-OGBFWA5R.js → acpAgent-JC4KGTLW.js} +2 -2
  2. package/chunks/{chunk-BB2C4HKQ.js → chunk-3NB3FFLR.js} +1 -1
  3. package/chunks/{chunk-Y3BCVTFB.js → chunk-5RYDKYIR.js} +1 -1
  4. package/chunks/{chunk-5JKJSIIP.js → chunk-67PM7M5R.js} +1 -1
  5. package/chunks/{chunk-YVORE4W4.js → chunk-6T25QVBX.js} +1 -1
  6. package/chunks/{chunk-34YXJ3CX.js → chunk-7SAR6NXA.js} +1 -1
  7. package/chunks/{chunk-GPI53DWB.js → chunk-BSLIVO6O.js} +1 -1
  8. package/chunks/{chunk-IC2WDA6V.js → chunk-DF6TBGS2.js} +1 -1
  9. package/chunks/{chunk-JRPR5IME.js → chunk-G35E5UB3.js} +1 -1
  10. package/chunks/{chunk-ORVQPZMQ.js → chunk-GN7ODRDE.js} +1 -1
  11. package/chunks/{chunk-HMID4D72.js → chunk-H2QXWIRZ.js} +1 -1
  12. package/chunks/{chunk-RGVXNWZA.js → chunk-JDABSS6M.js} +1 -1
  13. package/chunks/{chunk-SHLTP6ZB.js → chunk-JJQJFMPL.js} +1 -1
  14. package/chunks/{chunk-3GA3NTAV.js → chunk-MMGNOY3U.js} +3 -3
  15. package/chunks/{chunk-HHSHBOT7.js → chunk-N7WQH6L4.js} +2 -2
  16. package/chunks/{chunk-F2XELUO3.js → chunk-PSSJDUZB.js} +1 -1
  17. package/chunks/{chunk-7JT2V4AW.js → chunk-TXL535SJ.js} +1 -1
  18. package/chunks/{chunk-TI7J4HX2.js → chunk-VRAHMOQQ.js} +1 -1
  19. package/chunks/{chunk-VGPV5AVJ.js → chunk-WCLAVBNR.js} +1 -1
  20. package/chunks/{daemon-status-provider-FCQ4YYAY.js → daemon-status-provider-UX574XBB.js} +1 -1
  21. package/chunks/{fast-path-ZBD7IYQM.js → fast-path-OQWHYDXC.js} +1 -1
  22. package/chunks/{llm-DQNQEAFW.js → llm-R2RFT63S.js} +3 -3
  23. package/chunks/{local-ZRC4XZCJ.js → local-AONDQYFL.js} +1 -1
  24. package/chunks/{managed-local-serve-B2KOLPB5.js → managed-local-serve-DRNC6PTL.js} +1 -1
  25. package/chunks/{managed-runtime-bootstrap-MREL5UC2.js → managed-runtime-bootstrap-K3GRKDNQ.js} +1 -1
  26. package/chunks/{managed-runtime-ssh-worker-GUKAZFAJ.js → managed-runtime-ssh-worker-AVNBWFYC.js} +1 -1
  27. package/chunks/{memory-ZYPCFYPF.js → memory-JVT5LAWJ.js} +1 -1
  28. package/chunks/{nonInteractiveCli-JG6PKBAD.js → nonInteractiveCli-2GHQYHGW.js} +1 -1
  29. package/chunks/{review-N3VFZQMI.js → review-NDK2B7XI.js} +1 -1
  30. package/chunks/{run-qwen-serve-4MZRQFXK.js → run-qwen-serve-P5X5OZUH.js} +1 -1
  31. package/chunks/{serve-EQN6QAXF.js → serve-UHEH433U.js} +1 -1
  32. package/chunks/{server-CCEHAI25.js → server-ARYDETSZ.js} +1 -1
  33. package/chunks/{session-HNUJSV5A.js → session-HKWGCZF2.js} +1 -1
  34. package/chunks/{start-opentui-ui-6MCAEWAW.js → start-opentui-ui-S7A4FBGP.js} +1 -1
  35. package/chunks/{startInteractiveUI-657JWOTK.js → startInteractiveUI-DY6DWFW7.js} +2 -2
  36. package/chunks/{validateNonInterActiveAuth-CP5WFNAE.js → validateNonInterActiveAuth-P2F6MYO6.js} +1 -1
  37. package/chunks/{version-SIM74L5K.js → version-2ZFKVIIW.js} +1 -1
  38. package/cli.js +1 -1
  39. package/package.json +2 -2
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{formatLoopDetectedMessage,settleChatRecording,subscribeToHeadlessChatRecordingFailures}from"./chunk-PGKFDR73.js";import{JsonOutputAdapter}from"./chunk-VGPV5AVJ.js";import{StreamJsonOutputAdapter}from"./chunk-JRPR5IME.js";import{normalizePartList}from"./chunk-HIO3M52C.js";import{handleAtCommand}from"./chunk-WC72OWF2.js";import{buildInitialSystemReminders,buildSystemMessage,computeUsageFromMetrics,createAgentToolProgressHandler,createToolProgressHandler,extractPartsFromUserMessage,handleSlashCommand,insertAfterFunctionResponses,isSlashCommand}from"./chunk-BB2C4HKQ.js";import{formatDuration}from"./chunk-7VP4KALB.js";import{ModSession}from"./chunk-AE6E2YKY.js";import{frameModPrompt}from"./chunk-5KRYBTZV.js";import{cleanupReviewWorktreeLeases}from"./chunk-CUY6CVSL.js";import{RunBudgetEnforcer}from"./chunk-3GA3NTAV.js";import{sanitizeTerminalText}from"./chunk-64CA3W6G.js";import{AlreadyReportedError,handleBudgetExceededError,handleCancellationError,handleError,handleMaxTurnsExceededError,handleToolError}from"./chunk-4KIFAVR2.js";import{t}from"./chunk-FK5L2WVV.js";import{isInlineModelOverrideAllowed}from"./chunk-YQXX44YA.js";import{buildGoalContinuationParts,buildSessionRecoveryPlanFromApiHistory,detectAutonomousSentinel,detectLoopSentinel}from"./chunk-3MBYQYPC.js";import{restoreWorktreeContext}from"./chunk-DVN6DAWO.js";import{executeToolCall}from"./chunk-ZOWMHZWO.js";import{GoalPersistenceUnavailableError,PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE,createDuplicateProviderToolCallResponse,finalizeToolResponses,findPlanModeEntryBatchBoundaryIndex,findRepeatedDuplicateProviderToolCall,getCachedToolCallFingerprint,getLastApiPromptCancellation,goalToolResultProvenance,isReplayOfHandledToolCall,isToolCallConcurrencySafe,markDuplicateProviderToolCallResponseSent,parseAndFormatApiError,partitionByConcurrencySafety,recordHandledToolCall,runAgentLoop}from"./chunk-PFKTTUGS.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{GOAL_PAUSE_REASON_HEADLESS_RUN_ENDED,GOAL_PAUSE_REASON_USER_INTERRUPT,addAgentOutputMessageAttributes,goalPauseReasonForHeadlessFailure,goalPauseReasonForRunBudget}from"./chunk-7Z2ZH5CW.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,hasImageParts,runVisionBridge,shouldRunVisionBridge,splitImageParts,uiTelemetryService}from"./chunk-MJEL7DIE.js";import{clampInlineMediaPart}from"./chunk-Q6UAOTP3.js";import{endInteractionSpan,getActiveInteractionSpan,isTelemetrySdkInitialized,shutdownTelemetry}from"./chunk-JJAEIBSV.js";import{registerCleanup}from"./chunk-PFECH6U6.js";import{isWrappedSystemReminderPart}from"./chunk-DMM5LJWL.js";import{ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{FatalInputError,getErrorType}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("NON_INTERACTIVE_CLI");async function waitForPendingMemoryTasks(client,signal,memoryWaitStopSignal){const promises=client.getPendingMemoryTaskPromises();if(promises.length===0)return;const pending=new Set(promises);const settled=Promise.allSettled(promises.map(promise=>promise.then(()=>{pending.delete(promise)},()=>{pending.delete(promise)})));let stopWaiting;const stopped=new Promise(resolve=>{stopWaiting=resolve});signal.addEventListener("abort",stopWaiting,{once:true});memoryWaitStopSignal?.addEventListener("abort",stopWaiting,{once:true});try{if(signal.aborted||memoryWaitStopSignal?.aborted){stopWaiting()}else{debugLogger.debug(`[runNonInteractive] Waiting for ${promises.length} tracked memory task(s)`)}await Promise.race([settled,stopped])}finally{signal.removeEventListener("abort",stopWaiting);memoryWaitStopSignal?.removeEventListener("abort",stopWaiting);client.removePendingMemoryTaskPromises(promises.filter(promise=>!pending.has(promise)))}if(signal.aborted){debugLogger.debug("[runNonInteractive] Abandoned memory wait after abort; tasks may still be running");signal.throwIfAborted()}if(pending.size>0&&memoryWaitStopSignal?.aborted){debugLogger.debug(`[runNonInteractive] Stopped waiting at the session EOF deadline; ${pending.size} tracked memory task(s) may still be running`);return}debugLogger.debug("[runNonInteractive] Tracked memory tasks settled")}__name(waitForPendingMemoryTasks,"waitForPendingMemoryTasks");var debugLogger2=createDebugLogger("NON_INTERACTIVE_CLI");var TurnInterruptedError=class extends Error{static{__name(this,"TurnInterruptedError")}constructor(){super("Operation cancelled.");this.name="TurnInterruptedError"}};var ModTurnAbortedError=class extends TurnInterruptedError{static{__name(this,"ModTurnAbortedError")}constructor(){super();this.message="A Mod ended the turn."}};var restoredBackgroundAgentSessions=new WeakMap;var STRUCTURED_SHUTDOWN_HOLDBACK_MS=500;var ONE_SHOT_MEMORY_WAIT_TIMEOUT_MS=5e3;function isHeadlessLoopSentinel(prompt){return detectLoopSentinel(prompt)!==null||detectAutonomousSentinel(prompt)!==null}__name(isHeadlessLoopSentinel,"isHeadlessLoopSentinel");var SUPPRESSED_OUTPUT_SUCCESS="Skipped: this turn's structured_output contract took precedence as the terminal output.";var SUPPRESSED_OUTPUT_RETRY=`${SUPPRESSED_OUTPUT_SUCCESS} Re-issue this call in a separate turn if needed.`;function suppressedOutputBody(structuredCaptured){return structuredCaptured?SUPPRESSED_OUTPUT_SUCCESS:SUPPRESSED_OUTPUT_RETRY}__name(suppressedOutputBody,"suppressedOutputBody");function sameGoalPermit(left,right){return left?.goalId===right.goalId&&left.revision===right.revision&&left.turnId===right.turnId}__name(sameGoalPermit,"sameGoalPermit");function formatGoalState(snapshot,operation){const goal=snapshot.goal;if(!goal){return operation==="clear"?"Goal cleared.":"No Goal is set."}const status=goal.status==="usage_limited"?"usage limited":goal.status;const summary=`Goal ${status}: ${goal.objective}`;const usage=[];if(goal.turnCount>0){const turns=goal.turnBudget??goal.turnCount;usage.push(`${goal.turnCount}${goal.turnBudget===void 0?"":` of ${goal.turnBudget}`} ${turns===1?"turn":"turns"}`)}if(goal.activeTimeMs>0&&goal.activeTimeBudgetMs!==void 0){usage.push(`${formatDuration(goal.activeTimeMs,{hideTrailingZeros:true})} of ${formatDuration(goal.activeTimeBudgetMs,{hideTrailingZeros:true})} active`)}if(goal.tokensUsed>0){const used=goal.tokensUsed.toLocaleString("en-US");usage.push(goal.tokenBudget===void 0?`${used} tokens`:`${used} of ${goal.tokenBudget.toLocaleString("en-US")} tokens`)}const lines=[summary];if(usage.length>0)lines.push(`Usage: ${usage.join(" \xB7 ")}`);if(goal.status!=="active"&&goal.lastReason){lines.push(`Reason: ${sanitizeTerminalText(goal.lastReason)}`)}return lines.join("\n")}__name(formatGoalState,"formatGoalState");async function claimUserGoalTurn(runtime,turnKey,signal){const immediate=runtime.permitForTurn(turnKey)??runtime.beginTurn(turnKey);if(immediate||runtime.getSnapshot().goal?.status!=="active"){return immediate}return new Promise((resolve,reject)=>{let settled=false;let unsubscribe=__name(()=>{},"unsubscribe");const finish=__name((permit,error)=>{if(settled)return;settled=true;unsubscribe();signal.removeEventListener("abort",onAbort);if(error!==void 0)reject(error);else resolve(permit)},"finish");const inspect=__name(()=>{try{const permit=runtime.permitForTurn(turnKey);if(permit||runtime.getSnapshot().goal?.status!=="active"){finish(permit)}}catch(error){finish(void 0,error)}},"inspect");const onAbort=__name(()=>finish(void 0),"onAbort");unsubscribe=runtime.subscribe(inspect);signal.addEventListener("abort",onAbort,{once:true});if(signal.aborted)onAbort();else inspect()})}__name(claimUserGoalTurn,"claimUserGoalTurn");function skipHeadlessLoopSentinel(scheduler,job){if(!isHeadlessLoopSentinel(job.prompt)){return false}if(job.recurring&&!job.durable){debugLogger2.debug("skipHeadlessLoopSentinel: cleaning up recurring session loop.md cron in headless mode",{jobId:job.id});void scheduler.delete(job.id).catch(()=>{})}return true}__name(skipHeadlessLoopSentinel,"skipHeadlessLoopSentinel");var PROVIDER_DUPLICATE_ID_LOOP_STOP={loopType:"global_tool_call_duplicate",loopReason:"provider_duplicate_id"};function emitLoopDetectedMessage(config,stop){const message=formatLoopDetectedMessage(stop);if(config.getOutputFormat()!=="text"){return message}process.stderr.write(`${message}
3
+ import{formatLoopDetectedMessage,settleChatRecording,subscribeToHeadlessChatRecordingFailures}from"./chunk-PGKFDR73.js";import{JsonOutputAdapter}from"./chunk-WCLAVBNR.js";import{StreamJsonOutputAdapter}from"./chunk-G35E5UB3.js";import{normalizePartList}from"./chunk-HIO3M52C.js";import{handleAtCommand}from"./chunk-WC72OWF2.js";import{buildInitialSystemReminders,buildSystemMessage,computeUsageFromMetrics,createAgentToolProgressHandler,createToolProgressHandler,extractPartsFromUserMessage,handleSlashCommand,insertAfterFunctionResponses,isSlashCommand}from"./chunk-3NB3FFLR.js";import{formatDuration}from"./chunk-7VP4KALB.js";import{ModSession}from"./chunk-AE6E2YKY.js";import{frameModPrompt}from"./chunk-5KRYBTZV.js";import{cleanupReviewWorktreeLeases}from"./chunk-CUY6CVSL.js";import{RunBudgetEnforcer}from"./chunk-MMGNOY3U.js";import{sanitizeTerminalText}from"./chunk-64CA3W6G.js";import{AlreadyReportedError,handleBudgetExceededError,handleCancellationError,handleError,handleMaxTurnsExceededError,handleToolError}from"./chunk-4KIFAVR2.js";import{t}from"./chunk-FK5L2WVV.js";import{isInlineModelOverrideAllowed}from"./chunk-YQXX44YA.js";import{buildGoalContinuationParts,buildSessionRecoveryPlanFromApiHistory,detectAutonomousSentinel,detectLoopSentinel}from"./chunk-3MBYQYPC.js";import{restoreWorktreeContext}from"./chunk-DVN6DAWO.js";import{executeToolCall}from"./chunk-ZOWMHZWO.js";import{GoalPersistenceUnavailableError,PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE,createDuplicateProviderToolCallResponse,finalizeToolResponses,findPlanModeEntryBatchBoundaryIndex,findRepeatedDuplicateProviderToolCall,getCachedToolCallFingerprint,getLastApiPromptCancellation,goalToolResultProvenance,isReplayOfHandledToolCall,isToolCallConcurrencySafe,markDuplicateProviderToolCallResponseSent,parseAndFormatApiError,partitionByConcurrencySafety,recordHandledToolCall,runAgentLoop}from"./chunk-PFKTTUGS.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{GOAL_PAUSE_REASON_HEADLESS_RUN_ENDED,GOAL_PAUSE_REASON_USER_INTERRUPT,addAgentOutputMessageAttributes,goalPauseReasonForHeadlessFailure,goalPauseReasonForRunBudget}from"./chunk-7Z2ZH5CW.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,hasImageParts,runVisionBridge,shouldRunVisionBridge,splitImageParts,uiTelemetryService}from"./chunk-MJEL7DIE.js";import{clampInlineMediaPart}from"./chunk-Q6UAOTP3.js";import{endInteractionSpan,getActiveInteractionSpan,isTelemetrySdkInitialized,shutdownTelemetry}from"./chunk-JJAEIBSV.js";import{registerCleanup}from"./chunk-PFECH6U6.js";import{isWrappedSystemReminderPart}from"./chunk-DMM5LJWL.js";import{ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{FatalInputError,getErrorType}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("NON_INTERACTIVE_CLI");async function waitForPendingMemoryTasks(client,signal,memoryWaitStopSignal){const promises=client.getPendingMemoryTaskPromises();if(promises.length===0)return;const pending=new Set(promises);const settled=Promise.allSettled(promises.map(promise=>promise.then(()=>{pending.delete(promise)},()=>{pending.delete(promise)})));let stopWaiting;const stopped=new Promise(resolve=>{stopWaiting=resolve});signal.addEventListener("abort",stopWaiting,{once:true});memoryWaitStopSignal?.addEventListener("abort",stopWaiting,{once:true});try{if(signal.aborted||memoryWaitStopSignal?.aborted){stopWaiting()}else{debugLogger.debug(`[runNonInteractive] Waiting for ${promises.length} tracked memory task(s)`)}await Promise.race([settled,stopped])}finally{signal.removeEventListener("abort",stopWaiting);memoryWaitStopSignal?.removeEventListener("abort",stopWaiting);client.removePendingMemoryTaskPromises(promises.filter(promise=>!pending.has(promise)))}if(signal.aborted){debugLogger.debug("[runNonInteractive] Abandoned memory wait after abort; tasks may still be running");signal.throwIfAborted()}if(pending.size>0&&memoryWaitStopSignal?.aborted){debugLogger.debug(`[runNonInteractive] Stopped waiting at the session EOF deadline; ${pending.size} tracked memory task(s) may still be running`);return}debugLogger.debug("[runNonInteractive] Tracked memory tasks settled")}__name(waitForPendingMemoryTasks,"waitForPendingMemoryTasks");var debugLogger2=createDebugLogger("NON_INTERACTIVE_CLI");var TurnInterruptedError=class extends Error{static{__name(this,"TurnInterruptedError")}constructor(){super("Operation cancelled.");this.name="TurnInterruptedError"}};var ModTurnAbortedError=class extends TurnInterruptedError{static{__name(this,"ModTurnAbortedError")}constructor(){super();this.message="A Mod ended the turn."}};var restoredBackgroundAgentSessions=new WeakMap;var STRUCTURED_SHUTDOWN_HOLDBACK_MS=500;var ONE_SHOT_MEMORY_WAIT_TIMEOUT_MS=5e3;function isHeadlessLoopSentinel(prompt){return detectLoopSentinel(prompt)!==null||detectAutonomousSentinel(prompt)!==null}__name(isHeadlessLoopSentinel,"isHeadlessLoopSentinel");var SUPPRESSED_OUTPUT_SUCCESS="Skipped: this turn's structured_output contract took precedence as the terminal output.";var SUPPRESSED_OUTPUT_RETRY=`${SUPPRESSED_OUTPUT_SUCCESS} Re-issue this call in a separate turn if needed.`;function suppressedOutputBody(structuredCaptured){return structuredCaptured?SUPPRESSED_OUTPUT_SUCCESS:SUPPRESSED_OUTPUT_RETRY}__name(suppressedOutputBody,"suppressedOutputBody");function sameGoalPermit(left,right){return left?.goalId===right.goalId&&left.revision===right.revision&&left.turnId===right.turnId}__name(sameGoalPermit,"sameGoalPermit");function formatGoalState(snapshot,operation){const goal=snapshot.goal;if(!goal){return operation==="clear"?"Goal cleared.":"No Goal is set."}const status=goal.status==="usage_limited"?"usage limited":goal.status;const summary=`Goal ${status}: ${goal.objective}`;const usage=[];if(goal.turnCount>0){const turns=goal.turnBudget??goal.turnCount;usage.push(`${goal.turnCount}${goal.turnBudget===void 0?"":` of ${goal.turnBudget}`} ${turns===1?"turn":"turns"}`)}if(goal.activeTimeMs>0&&goal.activeTimeBudgetMs!==void 0){usage.push(`${formatDuration(goal.activeTimeMs,{hideTrailingZeros:true})} of ${formatDuration(goal.activeTimeBudgetMs,{hideTrailingZeros:true})} active`)}if(goal.tokensUsed>0){const used=goal.tokensUsed.toLocaleString("en-US");usage.push(goal.tokenBudget===void 0?`${used} tokens`:`${used} of ${goal.tokenBudget.toLocaleString("en-US")} tokens`)}const lines=[summary];if(usage.length>0)lines.push(`Usage: ${usage.join(" \xB7 ")}`);if(goal.status!=="active"&&goal.lastReason){lines.push(`Reason: ${sanitizeTerminalText(goal.lastReason)}`)}return lines.join("\n")}__name(formatGoalState,"formatGoalState");async function claimUserGoalTurn(runtime,turnKey,signal){const immediate=runtime.permitForTurn(turnKey)??runtime.beginTurn(turnKey);if(immediate||runtime.getSnapshot().goal?.status!=="active"){return immediate}return new Promise((resolve,reject)=>{let settled=false;let unsubscribe=__name(()=>{},"unsubscribe");const finish=__name((permit,error)=>{if(settled)return;settled=true;unsubscribe();signal.removeEventListener("abort",onAbort);if(error!==void 0)reject(error);else resolve(permit)},"finish");const inspect=__name(()=>{try{const permit=runtime.permitForTurn(turnKey);if(permit||runtime.getSnapshot().goal?.status!=="active"){finish(permit)}}catch(error){finish(void 0,error)}},"inspect");const onAbort=__name(()=>finish(void 0),"onAbort");unsubscribe=runtime.subscribe(inspect);signal.addEventListener("abort",onAbort,{once:true});if(signal.aborted)onAbort();else inspect()})}__name(claimUserGoalTurn,"claimUserGoalTurn");function skipHeadlessLoopSentinel(scheduler,job){if(!isHeadlessLoopSentinel(job.prompt)){return false}if(job.recurring&&!job.durable){debugLogger2.debug("skipHeadlessLoopSentinel: cleaning up recurring session loop.md cron in headless mode",{jobId:job.id});void scheduler.delete(job.id).catch(()=>{})}return true}__name(skipHeadlessLoopSentinel,"skipHeadlessLoopSentinel");var PROVIDER_DUPLICATE_ID_LOOP_STOP={loopType:"global_tool_call_duplicate",loopReason:"provider_duplicate_id"};function emitLoopDetectedMessage(config,stop){const message=formatLoopDetectedMessage(stop);if(config.getOutputFormat()!=="text"){return message}process.stderr.write(`${message}
4
4
  `);return message}__name(emitLoopDetectedMessage,"emitLoopDetectedMessage");function emitNonInteractiveAssistantText(adapter,message){adapter.startAssistantMessage();adapter.processEvent({type:"content",value:message});adapter.finalizeAssistantMessage()}__name(emitNonInteractiveAssistantText,"emitNonInteractiveAssistantText");async function emitNonInteractiveFinalMessage(params){const{message,isError,adapter,config}=params;emitNonInteractiveAssistantText(adapter,message);const metrics=uiTelemetryService.getMetrics();const usage=computeUsageFromMetrics(metrics);const outputFormat=config.getOutputFormat();const stats=outputFormat==="json"?uiTelemetryService.getMetrics():void 0;await params.beforeEmit();adapter.emitResult({isError,durationMs:Date.now()-params.startTimeMs,apiDurationMs:0,numTurns:0,errorMessage:isError?message:void 0,usage,stats,summary:message})}__name(emitNonInteractiveFinalMessage,"emitNonInteractiveFinalMessage");function partitionHeadlessToolCalls(requests,config){let skillBefore=false;return partitionByConcurrencySafety(requests,request=>{const executionRequest=getHeadlessExecutionRequest(request,config);const canonicalName=canonicalToolName(executionRequest.name);const kind=config.getToolRegistry().getTool(canonicalName)?.kind;const inputMayChange=kind==="execute"&&(skillBefore||!config.getDisableAllHooks()&&(config.hasHooksForEvent("PreToolUse")||config.hasHooksForEvent("PermissionRequest")));skillBefore||=canonicalName===ToolNames.SKILL;return!inputMayChange&&isToolCallConcurrencySafe(executionRequest.name,kind,executionRequest.args)})}__name(partitionHeadlessToolCalls,"partitionHeadlessToolCalls");function getHeadlessExecutionRequest(request,config){if(canonicalToolName(request.name)!==ToolNames.TOOL_CALL){return request}const targetName=request.args["name"];let targetArgs=request.args["arguments"];if(typeof targetArgs==="string"){try{targetArgs=JSON.parse(targetArgs)}catch{return request}}if(typeof targetName!=="string"||typeof targetArgs!=="object"||targetArgs===null||Array.isArray(targetArgs)){return request}const registry=config.getToolRegistry();const target=registry.getTool(canonicalToolName(targetName));if(!target||!registry.isDeferredAndHidden(target.name)){return request}return{...request,name:target.name,args:targetArgs}}__name(getHeadlessExecutionRequest,"getHeadlessExecutionRequest");async function runNonInteractive(config,settings,input,prompt_id,options={}){return promptIdContext.run(prompt_id,async()=>{let adapter;const outputFormat=config.getOutputFormat();if(options.adapter){adapter=options.adapter}else if(outputFormat==="stream-json"){adapter=new StreamJsonOutputAdapter(config,config.getIncludePartialMessages())}else{adapter=new JsonOutputAdapter(config)}const ownsAdapter=options.adapter===void 0;const modSession=options.modSession??ModSession.create(config,settings,adapter);const ownsModSession=options.modSession===void 0;let modTurn;const unsubscribeRecordingFailure=ownsAdapter?subscribeToHeadlessChatRecordingFailures(config,adapter):void 0;let chatRecordingSettlement;const settleBeforeTerminalOutput=__name(()=>{chatRecordingSettlement??=(async()=>{await modTurn?.complete(abortController.signal.aborted&&!budgetEnforcer.getExceeded()?"aborted":"error");if(ownsModSession)await modSession?.close();modSession?.flushLogs();await settleChatRecording(config,{finalize:ownsAdapter})})();return chatRecordingSettlement},"settleBeforeTerminalOutput");const drainPendingMemoryTasks=__name((successTerminal=false)=>{const client=config.getLlmClient();if(options.memoryWaitStopSignal){return waitForPendingMemoryTasks(client,abortController.signal,options.memoryWaitStopSignal)}if(successTerminal){return waitForPendingMemoryTasks(client,abortController.signal)}const oneShotMemoryWindow=new AbortController;const oneShotMemoryWindowTimer=setTimeout(()=>oneShotMemoryWindow.abort(),ONE_SHOT_MEMORY_WAIT_TIMEOUT_MS);return waitForPendingMemoryTasks(client,abortController.signal,oneShotMemoryWindow.signal).finally(()=>clearTimeout(oneShotMemoryWindowTimer))},"drainPendingMemoryTasks");let resultEmitted=false;const emitResult=__name(async result=>{try{await settleBeforeTerminalOutput();adapter.emitResult(result);resultEmitted=true;options.onResultEmitted?.();await modSession?.flushOutput()}finally{await drainPendingMemoryTasks(!result.isError)}},"emitResult");const sessionId=config.getSessionId();const permissionMode=config.getApprovalMode();const cleanupReviewWorktrees=__name(gitTimeout=>{if(config.getShellExecutionSandbox?.())return;cleanupReviewWorktreeLeases({sessionId,promptId:prompt_id,repositoryRoot:config.getProjectRoot(),gitTimeout})},"cleanupReviewWorktrees");const unregisterReviewWorktreeCleanup=registerCleanup(()=>cleanupReviewWorktrees(1e3));let turnCount=0;let limitedTurnCount=0;let totalApiDurationMs=0;const startTime=Date.now();let activeInteractionPromptId=prompt_id;let activeInteractionOwner;const selectActiveInteraction=__name((promptId,startsInteraction=false)=>{if(startsInteraction||activeInteractionPromptId!==promptId){activeInteractionOwner=void 0}activeInteractionPromptId=promptId},"selectActiveInteraction");const captureActiveInteractionOwner=__name(()=>{activeInteractionOwner??=getActiveInteractionSpan(activeInteractionPromptId);return activeInteractionOwner},"captureActiveInteractionOwner");const endActiveInteraction=__name((status,metadata={})=>{const owner=captureActiveInteractionOwner();if(!owner||getActiveInteractionSpan(activeInteractionPromptId)!==owner){return}endInteractionSpan(status,{promptId:activeInteractionPromptId,...metadata})},"endActiveInteraction");const llmClient=config.getLlmClient();const abortController=options.abortController??new AbortController;const queuedGoalTurns=[];let activeGoalTurn;let goalRuntimeUnsubscribe;const emitGoalSnapshot=__name(snapshot=>{adapter.processEvent({type:"goal_state",value:snapshot})},"emitGoalSnapshot");const observeGoalRuntime=__name(runtime=>{goalRuntimeUnsubscribe??=runtime.subscribe(emitGoalSnapshot)},"observeGoalRuntime");const enforceSessionTurnLimit=__name(async isRuntimeGoalTurn=>{if(isRuntimeGoalTurn)return;limitedTurnCount++;const maxSessionTurns=config.getMaxSessionTurns();if(maxSessionTurns>=0&&limitedTurnCount>maxSessionTurns){await failClosedActiveGoalTurn("Headless Goal stopped after the session turn limit");await settleBeforeTerminalOutput();await handleMaxTurnsExceededError(config)}},"enforceSessionTurnLimit");let goalHostUnbind;const goalHost={startGoalTurn:__name(async input2=>{if(queuedGoalTurns.some(({permit:permit2})=>permit2.turnId===input2.permit.turnId)){return}const{permit,...continuation}=input2;queuedGoalTurns.push({permit:{...permit},turnKey:`goal-runtime:${permit.turnId}`,controller:new AbortController,origin:"runtime",...continuation})},"startGoalTurn"),preemptGoalTurn:__name(reason=>{for(const turn of queuedGoalTurns.splice(0)){turn.controller.abort(reason)}activeGoalTurn?.controller.abort(reason)},"preemptGoalTurn")};const bindGoalHost=__name(()=>{goalHostUnbind??=config.bindGoalTurnHost(goalHost)},"bindGoalHost");const markGoalTurnDelivered=__name(turn=>{try{config.getGoalRuntime().markTurnDelivered(turn.turnKey)}catch{}},"markGoalTurnDelivered");let settlingGoalTurn;let goalTurnSettlement;const failClosedActiveGoalTurn=__name((reason,pauseReason)=>{const turn=activeGoalTurn;if(!turn)return Promise.resolve();if(settlingGoalTurn===turn&&goalTurnSettlement){return goalTurnSettlement}settlingGoalTurn=turn;goalTurnSettlement=(async()=>{if(!turn.controller.signal.aborted){turn.controller.abort(reason)}try{const runtime=await config.getGoalRuntimeReady();if(!sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){return}if(runtime.getSnapshot().goal?.status==="active"){try{await runtime.dispatch({action:"pause",expectedGoalId:turn.permit.goalId,expectedRevision:turn.permit.revision,reason:pauseReason??goalPauseReasonForHeadlessFailure(reason)})}catch(error){debugLogger2.warn("Failed to pause terminal headless Goal",error)}}try{await config.getChatRecordingService?.()?.flush()}catch(error){debugLogger2.warn("Failed to flush terminal headless Goal",error)}if(sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){await runtime.finishTurn(turn.permit)}}catch(error){debugLogger2.warn("Failed to close terminal headless Goal",error)}finally{if(activeGoalTurn===turn){activeGoalTurn=void 0}if(settlingGoalTurn===turn){settlingGoalTurn=void 0;goalTurnSettlement=void 0}}})();return goalTurnSettlement},"failClosedActiveGoalTurn");const finishGoalTurn=__name(async turn=>{const runtime=await config.getGoalRuntimeReady();if(!sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){return}let abortSettlement;const pauseOnAbort=__name(()=>{const exceeded=budgetEnforcer.getExceeded();abortSettlement??=runtime.dispatch({action:"pause",expectedGoalId:turn.permit.goalId,expectedRevision:turn.permit.revision,reason:exceeded?goalPauseReasonForRunBudget(exceeded.kind):GOAL_PAUSE_REASON_USER_INTERRUPT}).then(()=>void 0).catch(error=>{debugLogger2.warn("Failed to pause aborted headless Goal",error)})},"pauseOnAbort");abortController.signal.addEventListener("abort",pauseOnAbort,{once:true});if(abortController.signal.aborted)pauseOnAbort();try{if(!abortController.signal.aborted){await runtime.finishTurn(turn.permit)}}finally{abortController.signal.removeEventListener("abort",pauseOnAbort);await abortSettlement}},"finishGoalTurn");const budgetEnforcer=new RunBudgetEnforcer({maxWallTimeSeconds:config.getMaxWallTimeSeconds(),maxToolCalls:config.getMaxToolCalls()},abortController);const stampBudgetAbort=__name(()=>{const exceeded=budgetEnforcer.getExceeded();if(!exceeded)return;endActiveInteraction("error",{errorMessage:exceeded.message,errorType:"run_budget_exceeded"})},"stampBudgetAbort");abortController.signal.addEventListener("abort",stampBudgetAbort,{once:true});budgetEnforcer.start();let abortExitCommitted=false;const markAbortExitCommitted=__name(()=>{abortExitCommitted=true},"markAbortExitCommitted");const routeAbort=__name(async()=>{const exceeded=budgetEnforcer.getExceeded();endActiveInteraction(exceeded?"error":"cancelled",{...exceeded?{errorMessage:exceeded.message,errorType:"run_budget_exceeded"}:{}});await failClosedActiveGoalTurn(exceeded?.message??"Headless Goal execution was cancelled",exceeded?goalPauseReasonForRunBudget(exceeded.kind):GOAL_PAUSE_REASON_USER_INTERRUPT);await settleBeforeTerminalOutput();if(exceeded){await handleBudgetExceededError(config,exceeded,markAbortExitCommitted);throw new Error(exceeded.message)}const reason=abortController.signal.reason;if(reason instanceof TurnInterruptedError&&(options.recoverableCancellation===true||reason instanceof ModTurnAbortedError)){throw reason}await handleCancellationError(config,markAbortExitCommitted);throw new Error("Operation cancelled.")},"routeAbort");const localQueue=[];const pullModPrompts=__name(()=>{for(let prompt=modSession?.takeSubmittedPrompt();prompt;prompt=modSession?.takeSubmittedPrompt())localQueue.push({displayText:prompt.text,modelText:frameModPrompt(prompt),sendMessageType:"userQuery",modPrompt:prompt})},"pullModPrompts");const sdkOnlyMonitorQueue=[];const isCancelledMonitorEvent=__name(item=>Boolean(item.monitorId&&item.sdkNotification?.status==="running"&&config.getMonitorRegistry().get(item.monitorId)?.status==="cancelled"),"isCancelledMonitorEvent");const emitNotificationToSdk=__name(item=>{if(item.sendMessageType!=="notification")return;adapter.emitUserMessage([{text:item.displayText}]);if(item.sdkNotification){adapter.emitSystemMessage("task_notification",item.sdkNotification)}},"emitNotificationToSdk");const emitModPromptToSdk=__name(prompt=>{adapter.emitUserMessage([{text:prompt.text}]);adapter.emitSystemMessage("mod_prompt",{mod:prompt.plugin})},"emitModPromptToSdk");const flushQueuedNotificationsToSdk=__name(queue=>{while(queue.length>0){const item=queue.shift();if(!isCancelledMonitorEvent(item)){emitNotificationToSdk(item)}}},"flushQueuedNotificationsToSdk");let captureMonitorTurnsInLocalQueue=true;let oneShotMonitorsFinalized=false;const finalizeOneShotMonitors=__name(()=>{if(options.captureMonitorNotifications===false||oneShotMonitorsFinalized)return;oneShotMonitorsFinalized=true;captureMonitorTurnsInLocalQueue=false;config.getMonitorRegistry().abortAll();flushQueuedNotificationsToSdk(sdkOnlyMonitorQueue)},"finalizeOneShotMonitors");let pipeBroken=false;let workflowApprovalChannelRegistered=false;const stdoutErrorHandler=__name(err=>{if(err.code==="EPIPE"&&!pipeBroken){pipeBroken=true;process.stdout.destroy()}},"stdoutErrorHandler");const shutdownHandler=__name(()=>{debugLogger2.debug("[runNonInteractive] Shutdown signal received");abortController.abort()},"shutdownHandler");const pendingTeammateMessages=[];let boundManager=null;let approvalListener=null;const detachFromManager=__name(m=>{m.setLeaderMessageCallback(null);if(approvalListener){m.getEventEmitter().off("teammate_approval_request",approvalListener);approvalListener=null}},"detachFromManager");const onTeamManagerChangeHandler=__name(manager=>{if(boundManager&&boundManager!==manager){detachFromManager(boundManager)}boundManager=manager;if(manager){manager.setLeaderMessageCallback(formatted=>{pendingTeammateMessages.push(formatted)});if(options.controlService){approvalListener=__name(event=>{options.controlService.permission.handleTeammateApproval(event).catch(err=>{debugLogger2.warn("Teammate approval handling failed:",err)})},"approvalListener")}else{approvalListener=__name(event=>{const mode=config.getApprovalMode();const confirmationDetails=event.confirmationDetails;const requiresExplicitHostApproval=confirmationDetails?.type!=="plan"&&confirmationDetails!==void 0&&"hideAlwaysAllow"in confirmationDetails&&confirmationDetails.hideAlwaysAllow===true;if(mode==="yolo"&&!requiresExplicitHostApproval){event.respond("proceed_once").catch(err=>{debugLogger2.warn("Teammate approval ProceedOnce failed:",err)});return}const reason=requiresExplicitHostApproval?mode==="yolo"?`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": this request requires an explicit interactive approval surface and cannot be bypassed by YOLO mode.`:`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": this request requires an explicit interactive approval surface, which is unavailable in non-stream-json mode with the current approval mode (${mode}). Use --input-format stream-json --output-format stream-json to review it.`:`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": current approval mode (${mode}) cannot prompt in non-stream-json mode. Use --yolo or stream-json to allow teammate tool calls.`;process.stderr.write(`[team] ${reason}
5
5
  `);pendingTeammateMessages.push(`<team_notice>
6
6
  ${reason}
@@ -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-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}})}
3
+ import{createManagedContextAttestationResponse,isManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{getCliVersion}from"./chunk-6T25QVBX.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
  /**
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{appEvents}from"./chunk-3GA3NTAV.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,SKIP_UPDATE_CHECK_ENV_VAR,requestUpdateOnExit}from"./chunk-T5PDEAU5.js";import{IdeClient}from"./chunk-PFKTTUGS.js";import{getAllProviderBaseUrls}from"./chunk-AJ75BPTA.js";import{detectRuntime,getOrCreateSharedDispatcher,preloadRuntimeFetchModule,redactProxyCredentials}from"./chunk-E5XJBLSO.js";import{initializeTelemetry}from"./chunk-JJAEIBSV.js";import{recordStartupEvent}from"./chunk-H4XFFVZ2.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("PRECONNECT");var preconnectFired=false;var preconnectInFlight;var DEFAULT_BASE_URLS={openai:"https://api.openai.com","qwen-oauth":"https://coding.dashscope.aliyuncs.com",anthropic:"https://api.anthropic.com",dashscope:"https://dashscope.aliyuncs.com"};var ALL_DEFAULT_URLS=[...Object.values(DEFAULT_BASE_URLS),...getAllProviderBaseUrls()];function shouldSkipPreconnect(){if(process.env["NODE_EXTRA_CA_CERTS"]){debugLogger.debug("Skipping preconnect: custom CA certificate configured");return true}return false}__name(shouldSkipPreconnect,"shouldSkipPreconnect");function isInSandboxMode(){return process.env["SANDBOX"]!==void 0}__name(isInSandboxMode,"isInSandboxMode");function isDefaultBaseUrl(baseUrl){const normalizedInput=baseUrl.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return ALL_DEFAULT_URLS.some(defaultUrl=>{const normalizedDefault=defaultUrl.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return normalizedInput===normalizedDefault||normalizedInput.startsWith(normalizedDefault+"/")})}__name(isDefaultBaseUrl,"isDefaultBaseUrl");function getPreconnectTargetUrl(authType,resolvedBaseUrl){if(resolvedBaseUrl&&/^https?:\/\//i.test(resolvedBaseUrl)){if(isDefaultBaseUrl(resolvedBaseUrl)){return resolvedBaseUrl}debugLogger.debug("Skipping preconnect: resolved baseUrl is not a default URL");return void 0}if(authType&&DEFAULT_BASE_URLS[authType]){return DEFAULT_BASE_URLS[authType]}return void 0}__name(getPreconnectTargetUrl,"getPreconnectTargetUrl");function preconnectApi(authType,options={}){if(preconnectFired){return}if(process.env["QWEN_CODE_DISABLE_PRECONNECT"]==="1"){debugLogger.debug("Preconnect disabled by environment variable");preconnectFired=true;return}if(isInSandboxMode()){debugLogger.debug("Skipping preconnect: sandbox mode detected");preconnectFired=true;return}if(shouldSkipPreconnect()){preconnectFired=true;return}if(detectRuntime()!=="node"){debugLogger.debug("Skipping preconnect: unsupported runtime");preconnectFired=true;return}if(!options.proxy){debugLogger.debug("Skipping preconnect dispatcher: no proxy configured");return}const proxy=options.proxy;const targetUrl=getPreconnectTargetUrl(authType,options.resolvedBaseUrl);if(!targetUrl){debugLogger.debug("No target URL for preconnect");return}preconnectFired=true;debugLogger.debug(`Preconnecting to: ${targetUrl}`);preconnectInFlight=(async()=>{await preloadRuntimeFetchModule();const dispatcher=getOrCreateSharedDispatcher(proxy);const{fetch:undiciFetch}=await loadUndici();await undiciFetch(targetUrl,{method:"HEAD",signal:AbortSignal.timeout(5e3),headers:{"User-Agent":"QwenCode-Preconnect/1.0"},dispatcher});debugLogger.debug("Preconnect completed")})().catch(error=>{const redactedError=redactProxyCredentials(String(error));debugLogger.debug(`Preconnect failed (ignored): ${redactedError}`)})}__name(preconnectApi,"preconnectApi");var debugLogger2=createDebugLogger("STARTUP_PREFETCH");var DEFERRED_IDE_CONNECT_TIMEOUT_MS=15e3;var earlyStarted=new WeakSet;var postRenderStarted=new WeakSet;function withTimeout(promise,name,timeoutMs,onTimeout=()=>{}){let timeoutId;let timedOut=false;const runTimeoutCleanup=__name(()=>{void Promise.resolve().then(onTimeout).catch(err=>{debugLogger2.debug(`${name} timeout cleanup failed:`,err)})},"runTimeoutCleanup");const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{timedOut=true;runTimeoutCleanup();reject(new Error(`${name} timed out after ${timeoutMs}ms`))},timeoutMs);timeoutId.unref?.()});void promise.then(()=>{if(timedOut){runTimeoutCleanup()}},err=>{if(timedOut){debugLogger2.debug(`${name} underlying error after timeout:`,err)}});return Promise.race([promise,timeout]).finally(()=>{if(timeoutId){clearTimeout(timeoutId)}})}__name(withTimeout,"withTimeout");function runDeferredTask(name,task){recordStartupEvent("startup_prefetch_started",{name});void Promise.resolve().then(task).then(()=>{recordStartupEvent("startup_prefetch_completed",{name})}).catch(err=>{recordStartupEvent("startup_prefetch_failed",{name});debugLogger2.warn(`${name} failed:`,err)})}__name(runDeferredTask,"runDeferredTask");async function disconnectIdeAfterDeferredTimeout(){const ideClient=await IdeClient.getInstance();await ideClient.disconnect()}__name(disconnectIdeAfterDeferredTimeout,"disconnectIdeAfterDeferredTimeout");function startEarlyStartupPrefetches(config){if(earlyStarted.has(config))return;earlyStarted.add(config);try{const modelsConfig=config.getModelsConfig();const authType=modelsConfig.getCurrentAuthType();const resolvedBaseUrl=modelsConfig.getGenerationConfig().baseUrl;const proxy=config.getProxy();preconnectApi(authType,{resolvedBaseUrl,proxy})}catch(error){debugLogger2.debug(`Preconnect skipped due to error getting authType: ${error}`)}}__name(startEarlyStartupPrefetches,"startEarlyStartupPrefetches");var UPDATE_CHECK_DELAY_MS=3e3;function startPostRenderPrefetches(config,settings,options={}){if(postRenderStarted.has(config))return;postRenderStarted.add(config);if(settings.merged.general?.enableAutoUpdate!==false&&process.env[SKIP_UPDATE_CHECK_ENV_VAR]!=="true"&&!process.env[CUSTOM_SANDBOX_IMAGE_ENV_VAR]){runDeferredTask("update_check",async()=>{await new Promise(resolve=>{setTimeout(resolve,UPDATE_CHECK_DELAY_MS).unref?.()});const[{checkForUpdatesDetailed,describeUpdateCheckFailure},{handleAutoUpdate},{getInstallationInfo},{updateEventEmitter},{t}]=await Promise.all([import("./updateCheck-7NMXUCTN.js"),import("./handleAutoUpdate-MLUFTWFP.js"),import("./installationInfo-SAMHABWV.js"),import("./updateEventEmitter-HCGBOCP2.js"),import("./i18n-QAPQLOC3.js")]);const updateCheckSkippedMessage=__name(error=>t("Update check skipped ({{reason}}) \u2014 run /update to retry.",{reason:describeUpdateCheckFailure(error)}),"updateCheckSkippedMessage");try{const result=await checkForUpdatesDetailed();if(result.status==="update"){const projectRoot=config.getProjectRoot();const hostUpdateRelaunch=process.env[HOST_UPDATE_RELAUNCH_ENV_VAR];if(hostUpdateRelaunch==="true"){updateEventEmitter.emit("update-info",{message:`${result.info.message}
3
+ import{appEvents}from"./chunk-MMGNOY3U.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,SKIP_UPDATE_CHECK_ENV_VAR,requestUpdateOnExit}from"./chunk-T5PDEAU5.js";import{IdeClient}from"./chunk-PFKTTUGS.js";import{getAllProviderBaseUrls}from"./chunk-AJ75BPTA.js";import{detectRuntime,getOrCreateSharedDispatcher,preloadRuntimeFetchModule,redactProxyCredentials}from"./chunk-E5XJBLSO.js";import{initializeTelemetry}from"./chunk-JJAEIBSV.js";import{recordStartupEvent}from"./chunk-H4XFFVZ2.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("PRECONNECT");var preconnectFired=false;var preconnectInFlight;var DEFAULT_BASE_URLS={openai:"https://api.openai.com","qwen-oauth":"https://coding.dashscope.aliyuncs.com",anthropic:"https://api.anthropic.com",dashscope:"https://dashscope.aliyuncs.com"};var ALL_DEFAULT_URLS=[...Object.values(DEFAULT_BASE_URLS),...getAllProviderBaseUrls()];function shouldSkipPreconnect(){if(process.env["NODE_EXTRA_CA_CERTS"]){debugLogger.debug("Skipping preconnect: custom CA certificate configured");return true}return false}__name(shouldSkipPreconnect,"shouldSkipPreconnect");function isInSandboxMode(){return process.env["SANDBOX"]!==void 0}__name(isInSandboxMode,"isInSandboxMode");function isDefaultBaseUrl(baseUrl){const normalizedInput=baseUrl.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return ALL_DEFAULT_URLS.some(defaultUrl=>{const normalizedDefault=defaultUrl.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return normalizedInput===normalizedDefault||normalizedInput.startsWith(normalizedDefault+"/")})}__name(isDefaultBaseUrl,"isDefaultBaseUrl");function getPreconnectTargetUrl(authType,resolvedBaseUrl){if(resolvedBaseUrl&&/^https?:\/\//i.test(resolvedBaseUrl)){if(isDefaultBaseUrl(resolvedBaseUrl)){return resolvedBaseUrl}debugLogger.debug("Skipping preconnect: resolved baseUrl is not a default URL");return void 0}if(authType&&DEFAULT_BASE_URLS[authType]){return DEFAULT_BASE_URLS[authType]}return void 0}__name(getPreconnectTargetUrl,"getPreconnectTargetUrl");function preconnectApi(authType,options={}){if(preconnectFired){return}if(process.env["QWEN_CODE_DISABLE_PRECONNECT"]==="1"){debugLogger.debug("Preconnect disabled by environment variable");preconnectFired=true;return}if(isInSandboxMode()){debugLogger.debug("Skipping preconnect: sandbox mode detected");preconnectFired=true;return}if(shouldSkipPreconnect()){preconnectFired=true;return}if(detectRuntime()!=="node"){debugLogger.debug("Skipping preconnect: unsupported runtime");preconnectFired=true;return}if(!options.proxy){debugLogger.debug("Skipping preconnect dispatcher: no proxy configured");return}const proxy=options.proxy;const targetUrl=getPreconnectTargetUrl(authType,options.resolvedBaseUrl);if(!targetUrl){debugLogger.debug("No target URL for preconnect");return}preconnectFired=true;debugLogger.debug(`Preconnecting to: ${targetUrl}`);preconnectInFlight=(async()=>{await preloadRuntimeFetchModule();const dispatcher=getOrCreateSharedDispatcher(proxy);const{fetch:undiciFetch}=await loadUndici();await undiciFetch(targetUrl,{method:"HEAD",signal:AbortSignal.timeout(5e3),headers:{"User-Agent":"QwenCode-Preconnect/1.0"},dispatcher});debugLogger.debug("Preconnect completed")})().catch(error=>{const redactedError=redactProxyCredentials(String(error));debugLogger.debug(`Preconnect failed (ignored): ${redactedError}`)})}__name(preconnectApi,"preconnectApi");var debugLogger2=createDebugLogger("STARTUP_PREFETCH");var DEFERRED_IDE_CONNECT_TIMEOUT_MS=15e3;var earlyStarted=new WeakSet;var postRenderStarted=new WeakSet;function withTimeout(promise,name,timeoutMs,onTimeout=()=>{}){let timeoutId;let timedOut=false;const runTimeoutCleanup=__name(()=>{void Promise.resolve().then(onTimeout).catch(err=>{debugLogger2.debug(`${name} timeout cleanup failed:`,err)})},"runTimeoutCleanup");const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{timedOut=true;runTimeoutCleanup();reject(new Error(`${name} timed out after ${timeoutMs}ms`))},timeoutMs);timeoutId.unref?.()});void promise.then(()=>{if(timedOut){runTimeoutCleanup()}},err=>{if(timedOut){debugLogger2.debug(`${name} underlying error after timeout:`,err)}});return Promise.race([promise,timeout]).finally(()=>{if(timeoutId){clearTimeout(timeoutId)}})}__name(withTimeout,"withTimeout");function runDeferredTask(name,task){recordStartupEvent("startup_prefetch_started",{name});void Promise.resolve().then(task).then(()=>{recordStartupEvent("startup_prefetch_completed",{name})}).catch(err=>{recordStartupEvent("startup_prefetch_failed",{name});debugLogger2.warn(`${name} failed:`,err)})}__name(runDeferredTask,"runDeferredTask");async function disconnectIdeAfterDeferredTimeout(){const ideClient=await IdeClient.getInstance();await ideClient.disconnect()}__name(disconnectIdeAfterDeferredTimeout,"disconnectIdeAfterDeferredTimeout");function startEarlyStartupPrefetches(config){if(earlyStarted.has(config))return;earlyStarted.add(config);try{const modelsConfig=config.getModelsConfig();const authType=modelsConfig.getCurrentAuthType();const resolvedBaseUrl=modelsConfig.getGenerationConfig().baseUrl;const proxy=config.getProxy();preconnectApi(authType,{resolvedBaseUrl,proxy})}catch(error){debugLogger2.debug(`Preconnect skipped due to error getting authType: ${error}`)}}__name(startEarlyStartupPrefetches,"startEarlyStartupPrefetches");var UPDATE_CHECK_DELAY_MS=3e3;function startPostRenderPrefetches(config,settings,options={}){if(postRenderStarted.has(config))return;postRenderStarted.add(config);if(settings.merged.general?.enableAutoUpdate!==false&&process.env[SKIP_UPDATE_CHECK_ENV_VAR]!=="true"&&!process.env[CUSTOM_SANDBOX_IMAGE_ENV_VAR]){runDeferredTask("update_check",async()=>{await new Promise(resolve=>{setTimeout(resolve,UPDATE_CHECK_DELAY_MS).unref?.()});const[{checkForUpdatesDetailed,describeUpdateCheckFailure},{handleAutoUpdate},{getInstallationInfo},{updateEventEmitter},{t}]=await Promise.all([import("./updateCheck-7NMXUCTN.js"),import("./handleAutoUpdate-MLUFTWFP.js"),import("./installationInfo-SAMHABWV.js"),import("./updateEventEmitter-HCGBOCP2.js"),import("./i18n-QAPQLOC3.js")]);const updateCheckSkippedMessage=__name(error=>t("Update check skipped ({{reason}}) \u2014 run /update to retry.",{reason:describeUpdateCheckFailure(error)}),"updateCheckSkippedMessage");try{const result=await checkForUpdatesDetailed();if(result.status==="update"){const projectRoot=config.getProjectRoot();const hostUpdateRelaunch=process.env[HOST_UPDATE_RELAUNCH_ENV_VAR];if(hostUpdateRelaunch==="true"){updateEventEmitter.emit("update-info",{message:`${result.info.message}
4
4
  ${t("Run /update to install the update on the host.")}`});return}if(hostUpdateRelaunch==="false"){updateEventEmitter.emit("update-info",{message:`${result.info.message}
5
5
  ${t("Update Qwen Code on the host, then restart the sandbox.")}`});return}const installationInfo=getInstallationInfo(projectRoot,true);if(installationInfo.packageManager==="npm"){void handleAutoUpdate(result.info,settings,projectRoot);return}if(installationInfo.updateCommand||installationInfo.isStandalone&&installationInfo.standaloneDir){if(requestUpdateOnExit()){updateEventEmitter.emit("update-info",{message:`${result.info.message}
6
6
  ${t("The update will be installed after you exit this session.")}`})}else{updateEventEmitter.emit("update-info",{message:`${result.info.message}
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{BaseJsonOutputAdapter}from"./chunk-JRPR5IME.js";import{observeHeadlessJsonToolResultWire}from"./chunk-SOCXRMZM.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonOutputAdapter=class extends BaseJsonOutputAdapter{static{__name(this,"JsonOutputAdapter")}messages=[];attemptMessageCheckpoint=0;lastAssistantMessageAtAttemptStart=null;constructor(config){super(config)}emitMessageImpl(message){this.messages.push(message);if(typeof message==="object"&&message!==null&&"type"in message&&message.type==="assistant"){this.updateLastAssistantMessage(message)}}shouldEmitStreamEvents(){return false}startAssistantMessage(){this.attemptMessageCheckpoint=this.messages.length;this.lastAssistantMessageAtAttemptStart=this.lastAssistantMessage;super.startAssistantMessage()}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant"||!message.message.content.some(block=>block.type==="tool_use"&&discardedIds.has(block.id)));this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.messages.findLast(message=>message.type==="assistant")??this.lastAssistantMessageAtAttemptStart}}else{const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant");this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.lastAssistantMessageAtAttemptStart}super.restartAttempt(preserveText,discardedToolCalls)}finalizeAssistantMessage(){return this.finalizeAssistantMessageInternal(this.mainAgentMessageState,null)}emitResult(options){const resultMessage=this.buildResultMessage(options,this.lastAssistantMessage);this.messages.push(resultMessage);if(this.config.getOutputFormat()==="text"){if(resultMessage.is_error){process.stderr.write(`${resultMessage.error?.message||""}
3
+ import{BaseJsonOutputAdapter}from"./chunk-G35E5UB3.js";import{observeHeadlessJsonToolResultWire}from"./chunk-SOCXRMZM.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonOutputAdapter=class extends BaseJsonOutputAdapter{static{__name(this,"JsonOutputAdapter")}messages=[];attemptMessageCheckpoint=0;lastAssistantMessageAtAttemptStart=null;constructor(config){super(config)}emitMessageImpl(message){this.messages.push(message);if(typeof message==="object"&&message!==null&&"type"in message&&message.type==="assistant"){this.updateLastAssistantMessage(message)}}shouldEmitStreamEvents(){return false}startAssistantMessage(){this.attemptMessageCheckpoint=this.messages.length;this.lastAssistantMessageAtAttemptStart=this.lastAssistantMessage;super.startAssistantMessage()}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant"||!message.message.content.some(block=>block.type==="tool_use"&&discardedIds.has(block.id)));this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.messages.findLast(message=>message.type==="assistant")??this.lastAssistantMessageAtAttemptStart}}else{const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant");this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.lastAssistantMessageAtAttemptStart}super.restartAttempt(preserveText,discardedToolCalls)}finalizeAssistantMessage(){return this.finalizeAssistantMessageInternal(this.mainAgentMessageState,null)}emitResult(options){const resultMessage=this.buildResultMessage(options,this.lastAssistantMessage);this.messages.push(resultMessage);if(this.config.getOutputFormat()==="text"){if(resultMessage.is_error){process.stderr.write(`${resultMessage.error?.message||""}
4
4
  `)}else{process.stdout.write(`${resultMessage.result}
5
5
  `)}}else{const json=JSON.stringify(this.messages);const frame=`${json}
6
6
  `;observeHeadlessJsonToolResultWire(this.messages,frame);process.stdout.write(frame)}}emitMessage(message){this.messages.push(message)}};export{JsonOutputAdapter};
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{createDaemonStatusProvider}from"./chunk-RGVXNWZA.js";import"./chunk-GPI53DWB.js";import"./chunk-IC2WDA6V.js";import"./chunk-YBIENZ5E.js";import"./chunk-EXVVGGII.js";import"./chunk-L42NTHIT.js";import"./chunk-JDHMSERR.js";import"./chunk-OFWAMIMB.js";import"./chunk-IFPLGH5C.js";import"./chunk-QDSIJTQB.js";import"./chunk-3Y4UVTLL.js";import"./chunk-2QYDBHYZ.js";import"./chunk-YCAEGUZI.js";import"./chunk-BVUZGX6E.js";import"./chunk-CVMEBFLL.js";import"./chunk-L5UULTGF.js";import"./chunk-3KZHPZVZ.js";import"./chunk-CFTFKWPW.js";import"./chunk-NIEO2TBE.js";import"./chunk-7JDZEB77.js";import"./chunk-3MBYQYPC.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-YVORE4W4.js";import"./chunk-6KMPLONS.js";import"./chunk-TV5T4EZP.js";import"./chunk-MD3ZEOBX.js";import"./chunk-YLTVHXPO.js";import"./chunk-QPYXXB22.js";import"./chunk-DVN6DAWO.js";import"./chunk-46VUDNCL.js";import"./chunk-UNDRWCST.js";import"./chunk-KK6SQPYG.js";import"./chunk-TWJ4XBED.js";import"./chunk-4WYKHP7Q.js";import"./chunk-UNJYVYTC.js";import"./chunk-MUNBJIEX.js";import"./chunk-54CHQYA3.js";import"./chunk-4WMR7RZB.js";import"./chunk-HSN5QUS7.js";import"./chunk-KMAE5NUB.js";import"./chunk-ZOWMHZWO.js";import"./chunk-XWYUQMLN.js";import"./chunk-RKDS7A4H.js";import"./chunk-W6IOHGWW.js";import"./chunk-SXO35MFJ.js";import"./chunk-UGDAT4C4.js";import"./chunk-DECUAM3U.js";import"./chunk-MSAAQ2I7.js";import"./chunk-YU67VCCO.js";import"./chunk-PFKTTUGS.js";import"./chunk-R2EHHA2C.js";import"./chunk-MSIXO7NT.js";import"./chunk-ZIXAINJY.js";import"./chunk-HMCTSPVJ.js";import"./chunk-PHIPLV2I.js";import"./chunk-HW7ZRPZU.js";import"./chunk-A6G5TAIF.js";import"./chunk-I7KO7V6B.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-KZSUHQLD.js";import"./chunk-BTHQHTOB.js";import"./chunk-QVPT37XZ.js";import"./chunk-B5ZFH363.js";import"./chunk-DXUYBMFK.js";import"./chunk-BWTFZBMG.js";import"./chunk-HA7ADBWO.js";import"./chunk-I44IFX3I.js";import"./chunk-PSKT6KWO.js";import"./chunk-UJSVTVKB.js";import"./chunk-UHJUDWBV.js";import"./chunk-BG67XABA.js";import"./chunk-DNYXZVBT.js";import"./chunk-VMRQ6FA2.js";import"./chunk-OMBCQ6CU.js";import"./chunk-JB3XRNK7.js";import"./chunk-NVXFGZ4Z.js";import"./chunk-CV2UAEZA.js";import"./chunk-6RGS6DOB.js";import"./chunk-7Z2ZH5CW.js";import"./chunk-PNF77EBK.js";import"./chunk-YSZPZI2U.js";import"./chunk-QTJPOTU5.js";import"./chunk-G5PYYZMM.js";import"./chunk-TASTRW4D.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-IUVB7EIZ.js";import"./chunk-2BASBY3Z.js";import"./chunk-KYK53GFP.js";import"./chunk-T5XGTSQU.js";import"./chunk-JIQVUYBI.js";import"./chunk-THN4FBQ7.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-NNRKBCOC.js";import"./chunk-QL74SOQ5.js";import"./chunk-AV674UXZ.js";import"./chunk-KVSDMMDD.js";import"./chunk-744VRMDB.js";import"./chunk-EW3EVEYN.js";import"./chunk-IC42HQCH.js";import"./chunk-7UK4WJWS.js";import"./chunk-YIW3H46P.js";import"./chunk-6EDEOERB.js";import"./chunk-OV2J3OED.js";import"./chunk-AIGBQN6R.js";import"./chunk-4GNHXVJZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-NCBA52SB.js";import"./chunk-QTCO5I4C.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-NTRFETZB.js";import"./chunk-C6KSOOGV.js";import"./chunk-2W7KMUTJ.js";import"./chunk-33P4RB6G.js";import"./chunk-RQHIWFQL.js";import"./chunk-BSFNCIBS.js";import"./chunk-DLFX4M6C.js";import"./chunk-VFB6Q74I.js";import"./chunk-NSZJIBK7.js";import"./chunk-PWRX5WNL.js";import"./chunk-3MG44MZK.js";import"./chunk-476F6QIM.js";import"./chunk-W2ZVZ6LS.js";import"./chunk-KP77CL5U.js";import"./chunk-AGEDDL7Z.js";import"./chunk-MJEL7DIE.js";import"./chunk-KNXXVHVG.js";import"./chunk-JEV36CS7.js";import"./chunk-W5NWIGKO.js";import"./chunk-CQGP2BAW.js";import"./chunk-PWOQASXT.js";import"./chunk-FCQWRGW5.js";import"./chunk-6JHMYZNS.js";import"./chunk-Z6AR5XE5.js";import"./chunk-JWTMTDHE.js";import"./chunk-6QJWBGMS.js";import"./chunk-5PWKCDV6.js";import"./chunk-2GF3E5MI.js";import"./chunk-GJPZ5CKS.js";import"./chunk-UEWEDD5Y.js";import"./chunk-AJ75BPTA.js";import"./chunk-IDHSLPPU.js";import"./chunk-AIAYQAPA.js";import"./chunk-EV2CXPMN.js";import"./chunk-E5XJBLSO.js";import"./chunk-4ZBZL23U.js";import"./chunk-2NJJHZ52.js";import"./chunk-X64RXJQQ.js";import"./chunk-Q6UAOTP3.js";import"./chunk-BODSGVSR.js";import"./chunk-XMANRGPK.js";import"./chunk-JJAEIBSV.js";import"./chunk-KQX4H2D3.js";import"./chunk-BIOVWBME.js";import"./chunk-SW54YEPK.js";import"./chunk-7DOOXUDG.js";import"./chunk-RP57XAJ2.js";import"./chunk-HETUGUHE.js";import"./chunk-4DIWAQ5G.js";import"./chunk-EW6HVTD5.js";import"./chunk-DBRQGEEI.js";import"./chunk-DMM5LJWL.js";import"./chunk-ZQMVXHGH.js";import"./chunk-4WFJ5OPA.js";import"./chunk-Y2OCBVI6.js";import"./chunk-TL3SF2GA.js";import"./chunk-LPUWZZK2.js";import"./chunk-LWVCLDHV.js";import"./chunk-JOJLS3IB.js";import"./chunk-D6CEQ2GY.js";import"./chunk-TM6ZCBR7.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-H7OS7XH3.js";import"./chunk-7LLG2W7I.js";import"./chunk-46KPDLFH.js";import"./chunk-I4H7NUVP.js";import"./chunk-5VB4YX3Z.js";import"./chunk-2ZK2FGZQ.js";import"./chunk-E7MYPQGV.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{createDaemonStatusProvider};
3
+ import{createDaemonStatusProvider}from"./chunk-JDABSS6M.js";import"./chunk-BSLIVO6O.js";import"./chunk-DF6TBGS2.js";import"./chunk-YBIENZ5E.js";import"./chunk-EXVVGGII.js";import"./chunk-L42NTHIT.js";import"./chunk-JDHMSERR.js";import"./chunk-OFWAMIMB.js";import"./chunk-IFPLGH5C.js";import"./chunk-QDSIJTQB.js";import"./chunk-3Y4UVTLL.js";import"./chunk-2QYDBHYZ.js";import"./chunk-YCAEGUZI.js";import"./chunk-BVUZGX6E.js";import"./chunk-CVMEBFLL.js";import"./chunk-L5UULTGF.js";import"./chunk-3KZHPZVZ.js";import"./chunk-CFTFKWPW.js";import"./chunk-NIEO2TBE.js";import"./chunk-7JDZEB77.js";import"./chunk-3MBYQYPC.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-6T25QVBX.js";import"./chunk-6KMPLONS.js";import"./chunk-TV5T4EZP.js";import"./chunk-MD3ZEOBX.js";import"./chunk-YLTVHXPO.js";import"./chunk-QPYXXB22.js";import"./chunk-DVN6DAWO.js";import"./chunk-46VUDNCL.js";import"./chunk-UNDRWCST.js";import"./chunk-KK6SQPYG.js";import"./chunk-TWJ4XBED.js";import"./chunk-4WYKHP7Q.js";import"./chunk-UNJYVYTC.js";import"./chunk-MUNBJIEX.js";import"./chunk-54CHQYA3.js";import"./chunk-4WMR7RZB.js";import"./chunk-HSN5QUS7.js";import"./chunk-KMAE5NUB.js";import"./chunk-ZOWMHZWO.js";import"./chunk-XWYUQMLN.js";import"./chunk-RKDS7A4H.js";import"./chunk-W6IOHGWW.js";import"./chunk-SXO35MFJ.js";import"./chunk-UGDAT4C4.js";import"./chunk-DECUAM3U.js";import"./chunk-MSAAQ2I7.js";import"./chunk-YU67VCCO.js";import"./chunk-PFKTTUGS.js";import"./chunk-R2EHHA2C.js";import"./chunk-MSIXO7NT.js";import"./chunk-ZIXAINJY.js";import"./chunk-HMCTSPVJ.js";import"./chunk-PHIPLV2I.js";import"./chunk-HW7ZRPZU.js";import"./chunk-A6G5TAIF.js";import"./chunk-I7KO7V6B.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-KZSUHQLD.js";import"./chunk-BTHQHTOB.js";import"./chunk-QVPT37XZ.js";import"./chunk-B5ZFH363.js";import"./chunk-DXUYBMFK.js";import"./chunk-BWTFZBMG.js";import"./chunk-HA7ADBWO.js";import"./chunk-I44IFX3I.js";import"./chunk-PSKT6KWO.js";import"./chunk-UJSVTVKB.js";import"./chunk-UHJUDWBV.js";import"./chunk-BG67XABA.js";import"./chunk-DNYXZVBT.js";import"./chunk-VMRQ6FA2.js";import"./chunk-OMBCQ6CU.js";import"./chunk-JB3XRNK7.js";import"./chunk-NVXFGZ4Z.js";import"./chunk-CV2UAEZA.js";import"./chunk-6RGS6DOB.js";import"./chunk-7Z2ZH5CW.js";import"./chunk-PNF77EBK.js";import"./chunk-YSZPZI2U.js";import"./chunk-QTJPOTU5.js";import"./chunk-G5PYYZMM.js";import"./chunk-TASTRW4D.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-IUVB7EIZ.js";import"./chunk-2BASBY3Z.js";import"./chunk-KYK53GFP.js";import"./chunk-T5XGTSQU.js";import"./chunk-JIQVUYBI.js";import"./chunk-THN4FBQ7.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-NNRKBCOC.js";import"./chunk-QL74SOQ5.js";import"./chunk-AV674UXZ.js";import"./chunk-KVSDMMDD.js";import"./chunk-744VRMDB.js";import"./chunk-EW3EVEYN.js";import"./chunk-IC42HQCH.js";import"./chunk-7UK4WJWS.js";import"./chunk-YIW3H46P.js";import"./chunk-6EDEOERB.js";import"./chunk-OV2J3OED.js";import"./chunk-AIGBQN6R.js";import"./chunk-4GNHXVJZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-NCBA52SB.js";import"./chunk-QTCO5I4C.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-NTRFETZB.js";import"./chunk-C6KSOOGV.js";import"./chunk-2W7KMUTJ.js";import"./chunk-33P4RB6G.js";import"./chunk-RQHIWFQL.js";import"./chunk-BSFNCIBS.js";import"./chunk-DLFX4M6C.js";import"./chunk-VFB6Q74I.js";import"./chunk-NSZJIBK7.js";import"./chunk-PWRX5WNL.js";import"./chunk-3MG44MZK.js";import"./chunk-476F6QIM.js";import"./chunk-W2ZVZ6LS.js";import"./chunk-KP77CL5U.js";import"./chunk-AGEDDL7Z.js";import"./chunk-MJEL7DIE.js";import"./chunk-KNXXVHVG.js";import"./chunk-JEV36CS7.js";import"./chunk-W5NWIGKO.js";import"./chunk-CQGP2BAW.js";import"./chunk-PWOQASXT.js";import"./chunk-FCQWRGW5.js";import"./chunk-6JHMYZNS.js";import"./chunk-Z6AR5XE5.js";import"./chunk-JWTMTDHE.js";import"./chunk-6QJWBGMS.js";import"./chunk-5PWKCDV6.js";import"./chunk-2GF3E5MI.js";import"./chunk-GJPZ5CKS.js";import"./chunk-UEWEDD5Y.js";import"./chunk-AJ75BPTA.js";import"./chunk-IDHSLPPU.js";import"./chunk-AIAYQAPA.js";import"./chunk-EV2CXPMN.js";import"./chunk-E5XJBLSO.js";import"./chunk-4ZBZL23U.js";import"./chunk-2NJJHZ52.js";import"./chunk-X64RXJQQ.js";import"./chunk-Q6UAOTP3.js";import"./chunk-BODSGVSR.js";import"./chunk-XMANRGPK.js";import"./chunk-JJAEIBSV.js";import"./chunk-KQX4H2D3.js";import"./chunk-BIOVWBME.js";import"./chunk-SW54YEPK.js";import"./chunk-7DOOXUDG.js";import"./chunk-RP57XAJ2.js";import"./chunk-HETUGUHE.js";import"./chunk-4DIWAQ5G.js";import"./chunk-EW6HVTD5.js";import"./chunk-DBRQGEEI.js";import"./chunk-DMM5LJWL.js";import"./chunk-ZQMVXHGH.js";import"./chunk-4WFJ5OPA.js";import"./chunk-Y2OCBVI6.js";import"./chunk-TL3SF2GA.js";import"./chunk-LPUWZZK2.js";import"./chunk-LWVCLDHV.js";import"./chunk-JOJLS3IB.js";import"./chunk-D6CEQ2GY.js";import"./chunk-TM6ZCBR7.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import"./chunk-H7OS7XH3.js";import"./chunk-7LLG2W7I.js";import"./chunk-46KPDLFH.js";import"./chunk-I4H7NUVP.js";import"./chunk-5VB4YX3Z.js";import"./chunk-2ZK2FGZQ.js";import"./chunk-E7MYPQGV.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import"./chunk-VKDAXTCZ.js";import"./chunk-KBWJGX7I.js";export{createDaemonStatusProvider};
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
3
  import{RUNTIME_STARTUP_CANCELLED_MESSAGE}from"./chunk-UKMS3RLB.js";import{getHeadlessYoloSafetyWarning}from"./chunk-Z57KDB5F.js";import{MAX_COMPACTED_REPLAY_MAX_BYTES,normalizeMaxRingBytes}from"./chunk-OFWAMIMB.js";import{isValidMemoryBudgetMb,memoryBudgetRangeError}from"./chunk-2QYDBHYZ.js";import{InvalidExecutionSandboxConfigError,assertExecutionSandboxSupported}from"./chunk-EKRCICRK.js";import"./chunk-ERGT5BD3.js";import{normalizeServeFastPathArgv}from"./chunk-X7QN6R6K.js";import"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var HELP_AND_VERSION_FLAGS=new Set(["--help","-h","--version","-v"]);var MCP_BUDGET_WARN_FRACTION=.75;var NUMBER_OPTIONS=new Map([["port","port"],["maxSessions","max-sessions"],["maxTotalSessions","max-total-sessions"],["maxPendingPromptsPerSession","max-pending-prompts-per-session"],["maxConnections","max-connections"],["eventRingSize","event-ring-size"],["eventRingMaxBytes","event-ring-max-bytes"],["compactedReplayMaxBytes","compacted-replay-max-bytes"],["maxJournalEvents","max-journal-events"],["maxJournalBytes","max-journal-bytes"],["mcp-client-budget","mcp-client-budget"],["memoryBudgetMb","memory-budget-mb"],["promptDeadlineMs","prompt-deadline-ms"],["writerIdleTimeoutMs","writer-idle-timeout-ms"],["channelIdleTimeoutMs","channel-idle-timeout-ms"],["initializeTimeoutMs","initialize-timeout-ms"],["sessionRestoreTimeoutMs","session-restore-timeout-ms"],["sessionReapIntervalMs","session-reap-interval-ms"],["sessionIdleTimeoutMs","session-idle-timeout-ms"],["sessionPromptSettledCloseGraceMs","session-prompt-settled-close-grace-ms"],["permissionResponseTimeoutMs","permission-response-timeout-ms"],["rateLimitPrompt","rate-limit-prompt"],["rateLimitMutation","rate-limit-mutation"],["rateLimitRead","rate-limit-read"],["rateLimitWindowMs","rate-limit-window-ms"]]);var NUMBER_OPTION_BY_FLAG=invertOptionMap(NUMBER_OPTIONS);var STRING_OPTION_BY_FLAG=new Map([["hostname","hostname"],["token","token"],["workspace","workspace"],["conversations-dir","conversationsDir"],["memory-project-scope","memoryProjectScope"],["tls-cert","tlsCert"],["tls-key","tlsKey"]]);var BOOLEAN_OPTION_BY_FLAG=new Map([["require-auth","requireAuth"],["enable-session-shell","enableSessionShell"],["web","serveWebShell"],["open","open"],["open-with-auth","open-with-auth"],["token-qr","tokenQr"],["http-bridge","http-bridge"],["allow-private-auth-base-url","allowPrivateAuthBaseUrl"],["experimental-lsp","experimentalLsp"],["restore-ask-user-question","restoreAskUserQuestion"],["rate-limit","rateLimit"]]);function invertOptionMap(source){const out=new Map;for(const[target,flag]of source){out.set(flag,target)}return out}__name(invertOptionMap,"invertOptionMap");function readOptionValue(argv,index,inlineValue){if(inlineValue!==void 0){return{value:inlineValue,nextIndex:index}}const value=argv[index+1];if(value===void 0||value.startsWith("-")){return null}return{value,nextIndex:index+1}}__name(readOptionValue,"readOptionValue");function parseNumber(value){if(value.trim()==="")return null;const parsed=Number(value);return Number.isNaN(parsed)?null:parsed}__name(parseNumber,"parseNumber");function parseBooleanValue(value){if(value==="true")return true;if(value==="false")return false;return null}__name(parseBooleanValue,"parseBooleanValue");function parsePositiveIntegerEnv(raw){if(raw===void 0||raw==="")return void 0;const trimmed=raw?.trim();if(!trimmed||!/^\d+$/.test(trimmed))return Number.NaN;const parsed=Number(trimmed);return Number.isSafeInteger(parsed)&&parsed>0?parsed:Number.NaN}__name(parsePositiveIntegerEnv,"parsePositiveIntegerEnv");function isTruthyEnv(value){return value==="1"||value==="true"}__name(isTruthyEnv,"isTruthyEnv");function writeStderrLine(line){process.stderr.write(line.endsWith("\n")?line:`${line}
4
- `)}__name(writeStderrLine,"writeStderrLine");function setServeOption(options,key,value){options[key]=value}__name(setServeOption,"setServeOption");function getRateLimitValidationError(options){for(const[name,value]of[["--rate-limit-prompt",options.rateLimitPrompt],["--rate-limit-mutation",options.rateLimitMutation],["--rate-limit-read",options.rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){return`qwen serve: ${name} must be a positive integer.`}}if(options.rateLimitWindowMs!==void 0&&(!Number.isFinite(options.rateLimitWindowMs)||!Number.isInteger(options.rateLimitWindowMs)||options.rateLimitWindowMs<1e3)){return"qwen serve: --rate-limit-window-ms must be an integer >= 1000."}return null}__name(getRateLimitValidationError,"getRateLimitValidationError");function getServeFastPathValidationError(parsed){const mcpClientBudget=parsed.options.mcpClientBudget;if(mcpClientBudget!==void 0&&(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0)){return"qwen serve: --mcp-client-budget must be a positive integer."}if(parsed.options.mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){return"qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N."}const maxPendingPromptsPerSession=parsed.options.maxPendingPromptsPerSession;if(maxPendingPromptsPerSession!==void 0&&maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){return"qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited)."}try{normalizeMaxRingBytes(parsed.options.eventRingMaxBytes)}catch(error){return`qwen serve: ${error instanceof Error?error.message:String(error)}`}const compactedReplayMaxBytes=parsed.options.compactedReplayMaxBytes;if(compactedReplayMaxBytes!==void 0&&(!Number.isSafeInteger(compactedReplayMaxBytes)||compactedReplayMaxBytes<1||compactedReplayMaxBytes>MAX_COMPACTED_REPLAY_MAX_BYTES)){return`qwen serve: --compacted-replay-max-bytes must be a positive safe integer in [1, ${MAX_COMPACTED_REPLAY_MAX_BYTES}].`}const maxJournalEvents=parsed.options.maxJournalEvents;if(maxJournalEvents!==void 0&&(!Number.isSafeInteger(maxJournalEvents)||maxJournalEvents<1)){return"qwen serve: --max-journal-events must be a positive safe integer."}const maxJournalBytes=parsed.options.maxJournalBytes;if(maxJournalBytes!==void 0&&(!Number.isSafeInteger(maxJournalBytes)||maxJournalBytes<1)){return"qwen serve: --max-journal-bytes must be a positive safe integer."}const memoryBudgetMb=parsed.options.memoryBudgetMb;if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){return memoryBudgetRangeError()}return null}__name(getServeFastPathValidationError,"getServeFastPathValidationError");function blockForever(){return new Promise(()=>{})}__name(blockForever,"blockForever");async function waitForServeRuntimeOrExit(handle){try{await handle.runtimeReady}catch(err){if(err instanceof Error&&err.message===RUNTIME_STARTUP_CANCELLED_MESSAGE){return}writeStderrLine(`qwen serve: runtime startup failed after listener was ready: ${err instanceof Error?err.message:String(err)}`);await handle.close().catch(()=>void 0);process.exit(1)}}__name(waitForServeRuntimeOrExit,"waitForServeRuntimeOrExit");function applyRateLimitEnvDefaults(options,env){if(options.rateLimit===void 0&&isTruthyEnv(env["QWEN_SERVE_RATE_LIMIT"])){options.rateLimit=true}if(options.rateLimit){options.rateLimitPrompt??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_PROMPT"]);options.rateLimitMutation??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_MUTATION"]);options.rateLimitRead??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_READ"]);options.rateLimitWindowMs??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_WINDOW_MS"])}}__name(applyRateLimitEnvDefaults,"applyRateLimitEnvDefaults");function discardRateLimitTuningWhenDisabled(options){if(options.rateLimit===true)return;delete options.rateLimitPrompt;delete options.rateLimitMutation;delete options.rateLimitRead;delete options.rateLimitWindowMs}__name(discardRateLimitTuningWhenDisabled,"discardRateLimitTuningWhenDisabled");async function bootstrapServeFastPathEnvironment(workspace){const{loadServeFastPathEnvironment,loadServeFastPathSettings,preResolveServeFastPathHomeEnvOverrides}=await import("./fast-path-settings-QGSXJF45.js");preResolveServeFastPathHomeEnvOverrides();const workspaceDir=workspace??process.cwd();const settings=loadServeFastPathSettings(workspaceDir);loadServeFastPathEnvironment(settings,workspaceDir);return settings}__name(bootstrapServeFastPathEnvironment,"bootstrapServeFastPathEnvironment");function parseServeFastPathArgs(rawArgv,env=process.env){const argv=normalizeServeFastPathArgv(rawArgv);if(argv[0]!=="serve")return{kind:"fallback"};if(argv.some(arg=>HELP_AND_VERSION_FLAGS.has(arg))){return{kind:"fallback"}}const options={hostname:"127.0.0.1",mode:"http-bridge",port:4170};let open=false;let openWithAuth=false;let httpBridge=true;let mcpBudgetModeRaw;let mcpClientBudget;let explicitRateLimit;for(let i=1;i<argv.length;i++){const arg=argv[i];if(arg==="--")return{kind:"fallback"};if(!arg.startsWith("--"))return{kind:"fallback"};const withoutPrefix=arg.slice(2);const equalsIndex=withoutPrefix.indexOf("=");const rawFlag=equalsIndex===-1?withoutPrefix:withoutPrefix.slice(0,equalsIndex);const inlineValue=equalsIndex===-1?void 0:withoutPrefix.slice(equalsIndex+1);const negated=rawFlag.startsWith("no-");const flag=negated?rawFlag.slice(3):rawFlag;const booleanTarget=BOOLEAN_OPTION_BY_FLAG.get(flag);if(booleanTarget){let value=!negated;if(inlineValue!==void 0){const parsed=parseBooleanValue(inlineValue);if(parsed===null||negated)return{kind:"fallback"};value=parsed}if(booleanTarget==="open"){open=value}else if(booleanTarget==="open-with-auth"){openWithAuth=value}else if(booleanTarget==="http-bridge"){httpBridge=value}else{setServeOption(options,booleanTarget,value);if(booleanTarget==="rateLimit"){explicitRateLimit=value}}continue}if(negated)return{kind:"fallback"};const numberTarget=NUMBER_OPTION_BY_FLAG.get(flag);if(numberTarget){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;const value=parseNumber(read.value);if(value===null)return{kind:"fallback"};if(numberTarget==="mcp-client-budget"){mcpClientBudget=value}else{setServeOption(options,numberTarget,value)}continue}const stringTarget=STRING_OPTION_BY_FLAG.get(flag);if(stringTarget){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if((stringTarget==="workspace"||stringTarget==="conversationsDir")&&(options[stringTarget]!==void 0||read.value==="")){return{kind:"fallback"}}setServeOption(options,stringTarget,read.value);continue}if(flag==="memory-pressure-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if(read.value!=="off"&&read.value!=="observe"){return{kind:"fallback"}}options.memoryPressureMode=read.value;continue}if(flag==="child-heap-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if(read.value!=="off"&&read.value!=="observe"&&read.value!=="admit"&&read.value!=="enforce"){return{kind:"fallback"}}options.childHeapMode=read.value;continue}if(flag==="mcp-budget-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;mcpBudgetModeRaw=read.value;continue}if(flag==="allow-origin"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;options.allowOrigins=[...options.allowOrigins??[],read.value];continue}return{kind:"fallback"}}if(mcpBudgetModeRaw!==void 0&&mcpBudgetModeRaw!=="enforce"&&mcpBudgetModeRaw!=="warn"&&mcpBudgetModeRaw!=="off"){return{kind:"fallback"}}if(options.memoryProjectScope!==void 0&&options.memoryProjectScope!=="git-root"&&options.memoryProjectScope!=="workspace"){return{kind:"fallback"}}const mcpBudgetMode=mcpBudgetModeRaw??(mcpClientBudget!==void 0?"warn":"off");if(mcpClientBudget!==void 0)options.mcpClientBudget=mcpClientBudget;options.mcpBudgetMode=mcpBudgetMode;if(explicitRateLimit!==void 0){options.rateLimit=explicitRateLimit}applyRateLimitEnvDefaults(options,env);return{kind:"serve",open:open||openWithAuth,openWithAuth,httpBridge,options}}__name(parseServeFastPathArgs,"parseServeFastPathArgs");async function maybeOpenWebShellBrowser(handle,open,openWithAuth){if(!open)return;try{await handle.runtimeReady}catch{return}const{maybeOpenWebShellBrowser:openBrowser}=await import("./serve-EQN6QAXF.js");await openBrowser(handle,true,openWithAuth)}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function emitHeadlessYoloWarning(settings){if(!settings)return;const warning=getHeadlessYoloSafetyWarning({getApprovalMode:__name(()=>settings.tools?.approvalMode,"getApprovalMode"),getSandbox:__name(()=>settings.tools?.sandbox,"getSandbox"),getShellExecutionSandbox:__name(()=>settings.tools?.executionSandbox,"getShellExecutionSandbox")});if(warning){writeStderrLine(warning)}}__name(emitHeadlessYoloWarning,"emitHeadlessYoloWarning");function writeServeWarnings(parsed){if(!parsed.httpBridge){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(parsed.options.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}const mcpClientBudget=parsed.options.mcpClientBudget;if(mcpClientBudget!==void 0){const resolvedMcpMode=parsed.options.mcpBudgetMode??"warn";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)`:""))}}__name(writeServeWarnings,"writeServeWarnings");async function tryRunServeFastPath(rawArgv=process.argv.slice(2)){const parsed=parseServeFastPathArgs(rawArgv);if(parsed.kind==="fallback")return false;const validationError=getServeFastPathValidationError(parsed)||(parsed.options.rateLimit===true?getRateLimitValidationError(parsed.options):null);if(validationError){writeStderrLine(validationError);process.exit(1)}let settings;try{settings=await bootstrapServeFastPathEnvironment(parsed.options.workspace)}catch(err){if(err instanceof InvalidExecutionSandboxConfigError)throw err;writeStderrLine(`qwen serve: fast-path bootstrap failed, falling back to full startup: ${err instanceof Error?err.message:String(err)}`);return false}assertExecutionSandboxSupported(settings??{},"serve / ACP / web terminals");applyRateLimitEnvDefaults(parsed.options,process.env);discardRateLimitTuningWhenDisabled(parsed.options);const rateLimitError=getRateLimitValidationError(parsed.options);if(rateLimitError){writeStderrLine(rateLimitError);process.exit(1)}writeServeWarnings(parsed);if(parsed.openWithAuth){try{const{applyOpenWithAuth}=await import("./open-with-auth-Z6WKB2OO.js");applyOpenWithAuth(parsed.options)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}}const{runQwenServe}=await import("./run-qwen-serve-4MZRQFXK.js");let handle;try{handle=await runQwenServe(parsed.options,{updateRestartArgv:rawArgv,...settings?{bootSettings:settings}:{},resolveOnListen:true,deferRuntimeUntilFirstHealth:!parsed.open});try{emitHeadlessYoloWarning(settings)}catch{}await maybeOpenWebShellBrowser(handle,parsed.open,parsed.openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await waitForServeRuntimeOrExit(handle);await blockForever();return true}__name(tryRunServeFastPath,"tryRunServeFastPath");export{bootstrapServeFastPathEnvironment,parseServeFastPathArgs,tryRunServeFastPath,waitForServeRuntimeOrExit};
4
+ `)}__name(writeStderrLine,"writeStderrLine");function setServeOption(options,key,value){options[key]=value}__name(setServeOption,"setServeOption");function getRateLimitValidationError(options){for(const[name,value]of[["--rate-limit-prompt",options.rateLimitPrompt],["--rate-limit-mutation",options.rateLimitMutation],["--rate-limit-read",options.rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){return`qwen serve: ${name} must be a positive integer.`}}if(options.rateLimitWindowMs!==void 0&&(!Number.isFinite(options.rateLimitWindowMs)||!Number.isInteger(options.rateLimitWindowMs)||options.rateLimitWindowMs<1e3)){return"qwen serve: --rate-limit-window-ms must be an integer >= 1000."}return null}__name(getRateLimitValidationError,"getRateLimitValidationError");function getServeFastPathValidationError(parsed){const mcpClientBudget=parsed.options.mcpClientBudget;if(mcpClientBudget!==void 0&&(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0)){return"qwen serve: --mcp-client-budget must be a positive integer."}if(parsed.options.mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){return"qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N."}const maxPendingPromptsPerSession=parsed.options.maxPendingPromptsPerSession;if(maxPendingPromptsPerSession!==void 0&&maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){return"qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited)."}try{normalizeMaxRingBytes(parsed.options.eventRingMaxBytes)}catch(error){return`qwen serve: ${error instanceof Error?error.message:String(error)}`}const compactedReplayMaxBytes=parsed.options.compactedReplayMaxBytes;if(compactedReplayMaxBytes!==void 0&&(!Number.isSafeInteger(compactedReplayMaxBytes)||compactedReplayMaxBytes<1||compactedReplayMaxBytes>MAX_COMPACTED_REPLAY_MAX_BYTES)){return`qwen serve: --compacted-replay-max-bytes must be a positive safe integer in [1, ${MAX_COMPACTED_REPLAY_MAX_BYTES}].`}const maxJournalEvents=parsed.options.maxJournalEvents;if(maxJournalEvents!==void 0&&(!Number.isSafeInteger(maxJournalEvents)||maxJournalEvents<1)){return"qwen serve: --max-journal-events must be a positive safe integer."}const maxJournalBytes=parsed.options.maxJournalBytes;if(maxJournalBytes!==void 0&&(!Number.isSafeInteger(maxJournalBytes)||maxJournalBytes<1)){return"qwen serve: --max-journal-bytes must be a positive safe integer."}const memoryBudgetMb=parsed.options.memoryBudgetMb;if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){return memoryBudgetRangeError()}return null}__name(getServeFastPathValidationError,"getServeFastPathValidationError");function blockForever(){return new Promise(()=>{})}__name(blockForever,"blockForever");async function waitForServeRuntimeOrExit(handle){try{await handle.runtimeReady}catch(err){if(err instanceof Error&&err.message===RUNTIME_STARTUP_CANCELLED_MESSAGE){return}writeStderrLine(`qwen serve: runtime startup failed after listener was ready: ${err instanceof Error?err.message:String(err)}`);await handle.close().catch(()=>void 0);process.exit(1)}}__name(waitForServeRuntimeOrExit,"waitForServeRuntimeOrExit");function applyRateLimitEnvDefaults(options,env){if(options.rateLimit===void 0&&isTruthyEnv(env["QWEN_SERVE_RATE_LIMIT"])){options.rateLimit=true}if(options.rateLimit){options.rateLimitPrompt??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_PROMPT"]);options.rateLimitMutation??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_MUTATION"]);options.rateLimitRead??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_READ"]);options.rateLimitWindowMs??=parsePositiveIntegerEnv(env["QWEN_SERVE_RATE_LIMIT_WINDOW_MS"])}}__name(applyRateLimitEnvDefaults,"applyRateLimitEnvDefaults");function discardRateLimitTuningWhenDisabled(options){if(options.rateLimit===true)return;delete options.rateLimitPrompt;delete options.rateLimitMutation;delete options.rateLimitRead;delete options.rateLimitWindowMs}__name(discardRateLimitTuningWhenDisabled,"discardRateLimitTuningWhenDisabled");async function bootstrapServeFastPathEnvironment(workspace){const{loadServeFastPathEnvironment,loadServeFastPathSettings,preResolveServeFastPathHomeEnvOverrides}=await import("./fast-path-settings-QGSXJF45.js");preResolveServeFastPathHomeEnvOverrides();const workspaceDir=workspace??process.cwd();const settings=loadServeFastPathSettings(workspaceDir);loadServeFastPathEnvironment(settings,workspaceDir);return settings}__name(bootstrapServeFastPathEnvironment,"bootstrapServeFastPathEnvironment");function parseServeFastPathArgs(rawArgv,env=process.env){const argv=normalizeServeFastPathArgv(rawArgv);if(argv[0]!=="serve")return{kind:"fallback"};if(argv.some(arg=>HELP_AND_VERSION_FLAGS.has(arg))){return{kind:"fallback"}}const options={hostname:"127.0.0.1",mode:"http-bridge",port:4170};let open=false;let openWithAuth=false;let httpBridge=true;let mcpBudgetModeRaw;let mcpClientBudget;let explicitRateLimit;for(let i=1;i<argv.length;i++){const arg=argv[i];if(arg==="--")return{kind:"fallback"};if(!arg.startsWith("--"))return{kind:"fallback"};const withoutPrefix=arg.slice(2);const equalsIndex=withoutPrefix.indexOf("=");const rawFlag=equalsIndex===-1?withoutPrefix:withoutPrefix.slice(0,equalsIndex);const inlineValue=equalsIndex===-1?void 0:withoutPrefix.slice(equalsIndex+1);const negated=rawFlag.startsWith("no-");const flag=negated?rawFlag.slice(3):rawFlag;const booleanTarget=BOOLEAN_OPTION_BY_FLAG.get(flag);if(booleanTarget){let value=!negated;if(inlineValue!==void 0){const parsed=parseBooleanValue(inlineValue);if(parsed===null||negated)return{kind:"fallback"};value=parsed}if(booleanTarget==="open"){open=value}else if(booleanTarget==="open-with-auth"){openWithAuth=value}else if(booleanTarget==="http-bridge"){httpBridge=value}else{setServeOption(options,booleanTarget,value);if(booleanTarget==="rateLimit"){explicitRateLimit=value}}continue}if(negated)return{kind:"fallback"};const numberTarget=NUMBER_OPTION_BY_FLAG.get(flag);if(numberTarget){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;const value=parseNumber(read.value);if(value===null)return{kind:"fallback"};if(numberTarget==="mcp-client-budget"){mcpClientBudget=value}else{setServeOption(options,numberTarget,value)}continue}const stringTarget=STRING_OPTION_BY_FLAG.get(flag);if(stringTarget){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if((stringTarget==="workspace"||stringTarget==="conversationsDir")&&(options[stringTarget]!==void 0||read.value==="")){return{kind:"fallback"}}setServeOption(options,stringTarget,read.value);continue}if(flag==="memory-pressure-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if(read.value!=="off"&&read.value!=="observe"){return{kind:"fallback"}}options.memoryPressureMode=read.value;continue}if(flag==="child-heap-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;if(read.value!=="off"&&read.value!=="observe"&&read.value!=="admit"&&read.value!=="enforce"){return{kind:"fallback"}}options.childHeapMode=read.value;continue}if(flag==="mcp-budget-mode"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;mcpBudgetModeRaw=read.value;continue}if(flag==="allow-origin"){const read=readOptionValue(argv,i,inlineValue);if(!read)return{kind:"fallback"};i=read.nextIndex;options.allowOrigins=[...options.allowOrigins??[],read.value];continue}return{kind:"fallback"}}if(mcpBudgetModeRaw!==void 0&&mcpBudgetModeRaw!=="enforce"&&mcpBudgetModeRaw!=="warn"&&mcpBudgetModeRaw!=="off"){return{kind:"fallback"}}if(options.memoryProjectScope!==void 0&&options.memoryProjectScope!=="git-root"&&options.memoryProjectScope!=="workspace"){return{kind:"fallback"}}const mcpBudgetMode=mcpBudgetModeRaw??(mcpClientBudget!==void 0?"warn":"off");if(mcpClientBudget!==void 0)options.mcpClientBudget=mcpClientBudget;options.mcpBudgetMode=mcpBudgetMode;if(explicitRateLimit!==void 0){options.rateLimit=explicitRateLimit}applyRateLimitEnvDefaults(options,env);return{kind:"serve",open:open||openWithAuth,openWithAuth,httpBridge,options}}__name(parseServeFastPathArgs,"parseServeFastPathArgs");async function maybeOpenWebShellBrowser(handle,open,openWithAuth){if(!open)return;try{await handle.runtimeReady}catch{return}const{maybeOpenWebShellBrowser:openBrowser}=await import("./serve-UHEH433U.js");await openBrowser(handle,true,openWithAuth)}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function emitHeadlessYoloWarning(settings){if(!settings)return;const warning=getHeadlessYoloSafetyWarning({getApprovalMode:__name(()=>settings.tools?.approvalMode,"getApprovalMode"),getSandbox:__name(()=>settings.tools?.sandbox,"getSandbox"),getShellExecutionSandbox:__name(()=>settings.tools?.executionSandbox,"getShellExecutionSandbox")});if(warning){writeStderrLine(warning)}}__name(emitHeadlessYoloWarning,"emitHeadlessYoloWarning");function writeServeWarnings(parsed){if(!parsed.httpBridge){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(parsed.options.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}const mcpClientBudget=parsed.options.mcpClientBudget;if(mcpClientBudget!==void 0){const resolvedMcpMode=parsed.options.mcpBudgetMode??"warn";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)`:""))}}__name(writeServeWarnings,"writeServeWarnings");async function tryRunServeFastPath(rawArgv=process.argv.slice(2)){const parsed=parseServeFastPathArgs(rawArgv);if(parsed.kind==="fallback")return false;const validationError=getServeFastPathValidationError(parsed)||(parsed.options.rateLimit===true?getRateLimitValidationError(parsed.options):null);if(validationError){writeStderrLine(validationError);process.exit(1)}let settings;try{settings=await bootstrapServeFastPathEnvironment(parsed.options.workspace)}catch(err){if(err instanceof InvalidExecutionSandboxConfigError)throw err;writeStderrLine(`qwen serve: fast-path bootstrap failed, falling back to full startup: ${err instanceof Error?err.message:String(err)}`);return false}assertExecutionSandboxSupported(settings??{},"serve / ACP / web terminals");applyRateLimitEnvDefaults(parsed.options,process.env);discardRateLimitTuningWhenDisabled(parsed.options);const rateLimitError=getRateLimitValidationError(parsed.options);if(rateLimitError){writeStderrLine(rateLimitError);process.exit(1)}writeServeWarnings(parsed);if(parsed.openWithAuth){try{const{applyOpenWithAuth}=await import("./open-with-auth-Z6WKB2OO.js");applyOpenWithAuth(parsed.options)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}}const{runQwenServe}=await import("./run-qwen-serve-P5X5OZUH.js");let handle;try{handle=await runQwenServe(parsed.options,{updateRestartArgv:rawArgv,...settings?{bootSettings:settings}:{},resolveOnListen:true,deferRuntimeUntilFirstHealth:!parsed.open});try{emitHeadlessYoloWarning(settings)}catch{}await maybeOpenWebShellBrowser(handle,parsed.open,parsed.openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await waitForServeRuntimeOrExit(handle);await blockForever();return true}__name(tryRunServeFastPath,"tryRunServeFastPath");export{bootstrapServeFastPathEnvironment,parseServeFastPathArgs,tryRunServeFastPath,waitForServeRuntimeOrExit};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2025 Qwen Team