@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.
- package/chunks/{acpAgent-OGBFWA5R.js → acpAgent-JC4KGTLW.js} +2 -2
- package/chunks/{chunk-BB2C4HKQ.js → chunk-3NB3FFLR.js} +1 -1
- package/chunks/{chunk-Y3BCVTFB.js → chunk-5RYDKYIR.js} +1 -1
- package/chunks/{chunk-5JKJSIIP.js → chunk-67PM7M5R.js} +1 -1
- package/chunks/{chunk-YVORE4W4.js → chunk-6T25QVBX.js} +1 -1
- package/chunks/{chunk-34YXJ3CX.js → chunk-7SAR6NXA.js} +1 -1
- package/chunks/{chunk-GPI53DWB.js → chunk-BSLIVO6O.js} +1 -1
- package/chunks/{chunk-IC2WDA6V.js → chunk-DF6TBGS2.js} +1 -1
- package/chunks/{chunk-JRPR5IME.js → chunk-G35E5UB3.js} +1 -1
- package/chunks/{chunk-ORVQPZMQ.js → chunk-GN7ODRDE.js} +1 -1
- package/chunks/{chunk-HMID4D72.js → chunk-H2QXWIRZ.js} +1 -1
- package/chunks/{chunk-RGVXNWZA.js → chunk-JDABSS6M.js} +1 -1
- package/chunks/{chunk-SHLTP6ZB.js → chunk-JJQJFMPL.js} +1 -1
- package/chunks/{chunk-3GA3NTAV.js → chunk-MMGNOY3U.js} +3 -3
- package/chunks/{chunk-HHSHBOT7.js → chunk-N7WQH6L4.js} +2 -2
- package/chunks/{chunk-F2XELUO3.js → chunk-PSSJDUZB.js} +1 -1
- package/chunks/{chunk-7JT2V4AW.js → chunk-TXL535SJ.js} +1 -1
- package/chunks/{chunk-TI7J4HX2.js → chunk-VRAHMOQQ.js} +1 -1
- package/chunks/{chunk-VGPV5AVJ.js → chunk-WCLAVBNR.js} +1 -1
- package/chunks/{daemon-status-provider-FCQ4YYAY.js → daemon-status-provider-UX574XBB.js} +1 -1
- package/chunks/{fast-path-ZBD7IYQM.js → fast-path-OQWHYDXC.js} +1 -1
- package/chunks/{llm-DQNQEAFW.js → llm-R2RFT63S.js} +3 -3
- package/chunks/{local-ZRC4XZCJ.js → local-AONDQYFL.js} +1 -1
- package/chunks/{managed-local-serve-B2KOLPB5.js → managed-local-serve-DRNC6PTL.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-MREL5UC2.js → managed-runtime-bootstrap-K3GRKDNQ.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-GUKAZFAJ.js → managed-runtime-ssh-worker-AVNBWFYC.js} +1 -1
- package/chunks/{memory-ZYPCFYPF.js → memory-JVT5LAWJ.js} +1 -1
- package/chunks/{nonInteractiveCli-JG6PKBAD.js → nonInteractiveCli-2GHQYHGW.js} +1 -1
- package/chunks/{review-N3VFZQMI.js → review-NDK2B7XI.js} +1 -1
- package/chunks/{run-qwen-serve-4MZRQFXK.js → run-qwen-serve-P5X5OZUH.js} +1 -1
- package/chunks/{serve-EQN6QAXF.js → serve-UHEH433U.js} +1 -1
- package/chunks/{server-CCEHAI25.js → server-ARYDETSZ.js} +1 -1
- package/chunks/{session-HNUJSV5A.js → session-HKWGCZF2.js} +1 -1
- package/chunks/{start-opentui-ui-6MCAEWAW.js → start-opentui-ui-S7A4FBGP.js} +1 -1
- package/chunks/{startInteractiveUI-657JWOTK.js → startInteractiveUI-DY6DWFW7.js} +2 -2
- package/chunks/{validateNonInterActiveAuth-CP5WFNAE.js → validateNonInterActiveAuth-P2F6MYO6.js} +1 -1
- package/chunks/{version-SIM74L5K.js → version-2ZFKVIIW.js} +1 -1
- package/cli.js +1 -1
- package/package.json +2 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{ExtensionRefreshState}from"./chunk-254YDSL2.js";import{billableOutputTokens,calculateCost,commandRestrictionNames,computeGenerationRates,computeSessionStats,diffCommand,extensionOwnerLabel,filterCommandsForMode,findInlineMathExpressions,formatCompressionTokenCount,formatDuration,formatTokenCount,getCompressionFailureStatusText,getSystemInfoFields,skillOriginLabel}from"./chunk-7VP4KALB.js";import{isKittyProtocolEnabled}from"./chunk-HKA2IEQ6.js";import{VSCODE_SHIFT_ENTER_SEQUENCE,isWaylandSession,writeOsc52}from"./chunk-K7VOBDFT.js";import{contextCommand}from"./chunk-P5543CFV.js";import{getInteractiveModSession}from"./chunk-AE6E2YKY.js";import{themeManager}from"./chunk-GXNGLDUN.js";import{validateAuthMethod}from"./chunk-VBJV7T47.js";import{clearSkillArgs,skillArgsNote,skillArgsPath,staleArgsWarning,writeSkillArgs}from"./chunk-JEC6WHFT.js";import{GITHUB_WORKFLOW_PATHS,INSIGHT_CSS,INSIGHT_JS,collectSessionData,extractInjections,generateExportFilename,normalizeSessionData,setupGithub,toHtml,toJson,toJsonl,toMarkdown}from"./chunk-SOCXRMZM.js";import{appEvents,checkAdvisorModelAvailability,isAdvisorModelEligible,resolveHookSettingsForConfig}from"./chunk-3GA3NTAV.js";import{MarkdownCommandDefSchema,parseMarkdownCommand}from"./chunk-ZLUQTFP3.js";import{formatUnsupportedVoiceModelMessage,getVoiceSettingsScope,isSelectableVoiceModel,isVoiceEnabled,readVoiceMode,readVoiceModel}from"./chunk-FS67DOZQ.js";import{applyProjectHooksApproval,getProjectHooksForApproval}from"./chunk-GY4ID3EB.js";import{stripUnsafeCharacters,toCodePoints,truncateToWidth}from"./chunk-64CA3W6G.js";import{rollbackStandaloneUpdate}from"./chunk-RWFOQXPU.js";import{getExtendedSystemInfo,getGitVersion,getNpmVersion}from"./chunk-GPI53DWB.js";import{getReasoningEffortsForConfig}from"./chunk-JQOLNQQN.js";import{formatAuxModelSelectorForDisplay}from"./chunk-L42NTHIT.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{getInstallationInfo}from"./chunk-GOZ5FAUV.js";import{SERVE_CONTROL_EXT_METHODS,SERVE_STATUS_EXT_METHODS}from"./chunk-YCAEGUZI.js";import{getErrorMessage as getErrorMessage2}from"./chunk-4KIFAVR2.js";import{OUTPUT_LANGUAGE_AUTO,getAllSettingKeys,getDefaultValue,getFlattenedSchema,getNestedProperty,getPersistScopeForModelSelection,getSettingDefinition,isAutoLanguage,nextBooleanSettingValue,resolveOutputLanguageOrPreserveAuto,validateSettingValue,writeOutputLanguageAndRegisterPath}from"./chunk-23543L6E.js";import{getCurrentLanguage,setLanguageAsync,t}from"./chunk-FK5L2WVV.js";import{SUPPORTED_LANGUAGES,getSupportedLanguageIds,resolveSupportedLanguage}from"./chunk-UWMLSAQY.js";import{ACP_ROUTE_ID_PREFIX,isInlineModelOverrideAllowed,parseAcpModelOption,resolveAcpFastModelSelector}from"./chunk-YQXX44YA.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-EKRCICRK.js";import{isFolderTrustEnabled,loadTrustedFolders}from"./chunk-WZTO3EYG.js";import{BTW_MAX_INPUT_LENGTH,Logger,analyzeToolResultRetention,buildBtwCacheSafeParams,buildLearnSkillPrompt,buildLearnVideoSkillRequest,describePeerInboxFailure,encodeInsightErrorMessage,encodeInsightProgressMessage,encodeInsightReadyMessage,findOutputStyle,generateSessionRecap,getBtwSession,getIdeInstaller,getLastPeerInboxFailure,getMCPServerPrompts,isWsl,listPeerControllers,loadOutputStyleCatalog,parseLearnVideoInput,readPathFromWorkspace,removePeerController}from"./chunk-3MBYQYPC.js";import{canonicalizeMsgId,describeHoldCause}from"./chunk-UNDRWCST.js";import{buildBareRememberPrompt,buildManagedRememberPrompt}from"./chunk-KK6SQPYG.js";import{MAX_WORKFLOW_RESULT_PREVIEW_CHARS,buildWorkflowResultPreview,listWorkflowSnapshots,readWorkflowSnapshot}from"./chunk-TWJ4XBED.js";import{toCanonicalWorkspaceArtifactPath}from"./chunk-4WMR7RZB.js";import{executeModTool,modToolRequest}from"./chunk-ZOWMHZWO.js";import{resolveOpenAILogDir}from"./chunk-MSAAQ2I7.js";import{ArenaManager,ConditionalRulesRegistry,CoreToolScheduler,EXTENSIONS_CONFIG_FILENAME,ExtensionManager,GoalPersistenceUnavailableError,IdeClient,MAX_FAILURE_LINE_CHARS,QWEN_CODE_COMPANION_EXTENSION_NAME,REPORTED_FAILURE_KEYS,SESSION_TITLE_MAX_LENGTH,SessionService,appendAutoMemoryContext,appendToLastTextPart,buildBackgroundEntryLabel,buildFailureLines,collectMemoryDiagnostics,executeRuntimeShell,fetchPullRequestByReference,flatMapTextParts,getExtensionDescription,getExtensionDisplayName,getLastApiHistoryPromptId,getToolCallFingerprint,hookEventSupportsMatcher,ideContextStore,isActiveWorkflowStatus,isCompressionFailureStatus,isExtensionCommittedWithWarningsError,isSuccessStatus,isTerminalStatus,isTerminalWorkflowStatus,isValidSessionPrUrl,isWorkflowRunId,listSavedWorkflows,loadServerHierarchicalMemory,normalizeClaudeMcpServer,parseInstallSource,partToString,persistSessionUsage,pullRequestViewUrl,readSessionPrsDetailed,reportedFailureLines,require_toml,runForkedAgent,sanitizeWorkflowText,truncateWorkflowText,tryGenerateSessionTitle,upsertSessionPrs,withoutAutoMemorySnapshots}from"./chunk-PFKTTUGS.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{external_exports}from"./chunk-KZSUHQLD.js";import{canUseRipgrep}from"./chunk-HA7ADBWO.js";import{GitWorktreeService}from"./chunk-I44IFX3I.js";import{openBrowserSecurely}from"./chunk-UJSVTVKB.js";import{isInternalCodeModeToolResult,projectUserTranscriptForDisplay}from"./chunk-UHJUDWBV.js";import{normalizeSkillPriority}from"./chunk-DNYXZVBT.js";import{flattenPeerLabel}from"./chunk-VMRQ6FA2.js";import{getAutoSkillCuratorStatus,recordAutoSkillUsage,restoreArchivedAutoSkill,runAutoSkillCurator,setAutoSkillPinned}from"./chunk-NVXFGZ4Z.js";import{GOAL_PAUSE_REASON_COMMAND,emptyGoalSnapshot}from"./chunk-7Z2ZH5CW.js";import{resolveModelId}from"./chunk-QTJPOTU5.js";import{Ns}from"./chunk-TASTRW4D.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{isMediaPolicyToolHiddenFromModel}from"./chunk-S2ZKZXHX.js";import{BUILT_IN_OUTPUT_STYLES,getArenaSystemReminder,getInsightPrompt,getPlanModeSystemReminder,getProjectSummaryPrompt,isSystemMdActive,resolveMainSessionOutputStyle}from"./chunk-KVSDMMDD.js";import{isSignalTermination}from"./chunk-QTCO5I4C.js";import{escapeJsonTagCharacters,formatMemoryUsage}from"./chunk-NTRFETZB.js";import{captureHookExecutionOwner,runWithHookExecutionOwner}from"./chunk-KP77CL5U.js";import{COMBINED_PASS_TOLERANCE_FACTOR,IdeConnectionEvent,formatTokenUsageSummaryAsCsv,formatTokenUsageSummaryAsJson,getMCPServerStatus,isImageCapable,logIdeConnection,queryTokenUsage,recordSkillInvocation,uiTelemetryService}from"./chunk-MJEL7DIE.js";import{read}from"./chunk-KNXXVHVG.js";import{getAutoMemoryRoot}from"./chunk-CQGP2BAW.js";import{runSideQuery}from"./chunk-FCQWRGW5.js";import{getCurrentMemoryFilename}from"./chunk-6JHMYZNS.js";import{atomicWriteFileSync}from"./chunk-2GF3E5MI.js";import{buildRuntimeSnapshotId,findProviderByCredentials,isImageGenerationCapable,stripRuntimeSnapshotPrefix}from"./chunk-AJ75BPTA.js";import{REASONING_EFFORT_TIERS,applyReasoningEffort,normalizeReasoningEffort}from"./chunk-EV2CXPMN.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{redactUrlCredentials}from"./chunk-JJAEIBSV.js";import{AuthType}from"./chunk-EW6HVTD5.js";import{isCpuProfileRecording,startCpuProfile,stopCpuProfile}from"./chunk-USR2Y7B3.js";import{FORK_SUBAGENT_TYPE,getApiHistoryPromptId,markApiHistoryPrompt,stripStartupContext}from"./chunk-DMM5LJWL.js";import{applySkillSideEffects,buildSkillLlmContent}from"./chunk-ZQMVXHGH.js";import{HookEventName,sanitizeUserPromptExpansionAdditionalContext}from"./chunk-4WFJ5OPA.js";import{checkArgumentSafety,checkCommandPermissions,escapeShellArg,getShellConfiguration}from"./chunk-Y2OCBVI6.js";import{isShellProgressData}from"./chunk-D6CEQ2GY.js";import{ToolDisplayNamesMigration,ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger,updateSymlink}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{expandHomeDir,isSubpath,resolvePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";init_esbuild_shims();var MAX_STACKED_SKILLS=5;var isStackedSkillCompletableCommand=__name(command=>command.kind==="skill"&&command.userInvocable!==false&&!command.hidden,"isStackedSkillCompletableCommand");var isValidStackedSkillPrefix=__name((prefix,commands)=>{const trimmed=prefix.trim();if(!trimmed)return false;const tokens=trimmed.split(/\s+/);if(tokens.length>=MAX_STACKED_SKILLS)return false;return tokens.every(token=>{if(!token.startsWith("/"))return false;const command=findCommandByName(token.slice(1),commands);return command!==void 0&&isStackedSkillCompletableCommand(command)})},"isValidStackedSkillPrefix");var parseSlashCommand=__name((query,commands)=>{const trimmed=query.trim();const commandText=trimmed.substring(1).trim();const parts=commandText.split(/\s+/);const commandPath=parts.filter(p=>p);let currentCommands=commands;let commandToExecute;let pathIndex=0;const canonicalPath=[];let argsStart=0;for(const part of commandPath){let foundCommand=currentCommands.find(cmd=>cmd.name===part);if(!foundCommand){foundCommand=currentCommands.find(cmd=>cmd.altNames?.includes(part))}if(foundCommand){commandToExecute=foundCommand;canonicalPath.push(foundCommand.name);pathIndex++;const partIndex=commandText.indexOf(part,argsStart);argsStart=partIndex+part.length;if(foundCommand.subCommands){currentCommands=foundCommand.subCommands}else{break}}else{break}}const args=commandToExecute?commandText.slice(argsStart).trim():parts.slice(pathIndex).join(" ");return{commandToExecute,args,canonicalPath}},"parseSlashCommand");var parseStackedSlashCommands=__name((query,commands)=>{const trimmed=query.trim();if(!trimmed.startsWith("/")){return{skills:[],remainingText:trimmed,exceededMax:false}}const commandText=trimmed.substring(1);const skills=[];let pos=0;let restPos=0;let exceededMax=false;while(pos<commandText.length){while(pos<commandText.length&&/\s/.test(commandText[pos]))pos++;if(pos>=commandText.length){restPos=pos;break}const tokenStart=pos;while(pos<commandText.length&&!/\s/.test(commandText[pos]))pos++;const token=commandText.slice(tokenStart,pos);if(skills.length===0){if(token.startsWith("/"))break;const cmd2=findCommandByName(token,commands);if(!cmd2||cmd2.kind!=="skill")break;skills.push(cmd2);restPos=pos;continue}if(!token.startsWith("/"))break;const name=token.substring(1);if(!name)break;const cmd=findCommandByName(name,commands);if(!cmd||cmd.kind!=="skill")break;if(skills.length>=MAX_STACKED_SKILLS){exceededMax=true;break}skills.push(cmd);restPos=pos}if(skills.length<2){return{skills:[],remainingText:trimmed,exceededMax:false}}const afterSkills=commandText.slice(restPos).trim();return{skills,remainingText:afterSkills,exceededMax}},"parseStackedSlashCommands");function findCommandByName(name,commands){return commands.find(cmd=>cmd.name===name)??commands.find(cmd=>cmd.altNames?.includes(name))}__name(findCommandByName,"findCommandByName");var CONTEXT_FILES_ANNOUNCEMENT_PREFIX="Read context files:";function isContextFilesAnnouncement(item){return item.type==="info"&&typeof item.text==="string"&&item.text.startsWith(CONTEXT_FILES_ANNOUNCEMENT_PREFIX)}__name(isContextFilesAnnouncement,"isContextFilesAnnouncement");var CodePage={UTF8:65001,GBK:936,BIG5:950,LATIN1:1252};var isAtCommand=__name(query=>query.startsWith("@")||/\s@/.test(query),"isAtCommand");var SLASH_PATH_SEPARATOR_RE=/[/\\]/;var SLASH_COMMANDS_SKIP_RECORDING=new Set(["quit","exit","clear","reset","new","resume","delete","branch","btw","history"]);var getSlashCommandFirstToken=__name(query=>query.slice(1).trimStart().split(/\s+/u)[0]??"","getSlashCommandFirstToken");var hasSlashCommandPathSeparator=__name(query=>SLASH_PATH_SEPARATOR_RE.test(getSlashCommandFirstToken(query)),"hasSlashCommandPathSeparator");var isSlashCommand=__name(query=>{if(!query.startsWith("/")){return false}if(query.startsWith("//")){return false}if(query.startsWith("/*")){return false}if(hasSlashCommandPathSeparator(query)){return false}return true},"isSlashCommand");var BTW_COMMAND_RE=/^[/?]btw(?:\s|$)/;var isBtwCommand=__name(query=>{const trimmed=query.trim();return trimmed.length>0&&BTW_COMMAND_RE.test(trimmed)},"isBtwCommand");function consumesContextAnnouncementLatch(trimmedPrompt,options){if(trimmedPrompt.length===0){return false}if(/^\/btw(?:\s|$)/.test(trimmedPrompt)){return false}if(isSlashCommand(trimmedPrompt)){return parseSlashCommand(trimmedPrompt,options.slashCommands).commandToExecute?.modelInvocable===true}if(options.shellModeActive){return false}return true}__name(consumesContextAnnouncementLatch,"consumesContextAnnouncementLatch");var debugLogger=createDebugLogger("COMMAND_UTILS");var formatCommandFailure=__name((error,command)=>error instanceof Error&&error.code==="ENOENT"?`${command} not found`:error instanceof Error?error.message:String(error),"formatCommandFailure");var copyToClipboard=__name(async text=>{let wlCopyError;const run=__name((cmd,args,options)=>new Promise((resolve4,reject)=>{const child=options?spawn(cmd,args,options):spawn(cmd,args);let stderr="";if(child.stderr){child.stderr.on("data",chunk=>stderr+=chunk.toString())}child.on("error",reject);child.on("close",code=>{if(code===0)return resolve4();const errorMsg=stderr.trim();reject(new Error(`'${cmd}' exited with code ${code}${errorMsg?`: ${errorMsg}`:""}`))});if(child.stdin){child.stdin.on("error",reject);child.stdin.write(text);child.stdin.end()}else{reject(new Error("Child process has no stdin stream to write to."))}}),"run");const linuxOptions={stdio:["pipe","inherit","pipe"]};switch(process.platform){case"win32":return run("cmd",["/c",`chcp ${CodePage.UTF8} >nul && clip`]);case"darwin":return run("pbcopy",[]);case"linux":if(isWaylandSession()){try{await run("wl-copy",["-t","text/plain"],{stdio:["pipe","inherit","ignore"]});return}catch(error){wlCopyError=error;debugLogger.debug("wl-copy failed; falling back to other clipboard methods:",error)}}try{await run("xclip",["-selection","clipboard"],linuxOptions)}catch(primaryError){try{await run("xsel",["--clipboard","--input"],linuxOptions)}catch(fallbackError){const xclipNotFound=primaryError instanceof Error&&primaryError.code==="ENOENT";const xselNotFound=fallbackError instanceof Error&&fallbackError.code==="ENOENT";const wlCopyFailure=wlCopyError===void 0?"":`wl-copy failed ("${formatCommandFailure(wlCopyError,"wl-copy")}"); `;if(xclipNotFound&&xselNotFound){if(!writeOsc52(text)){throw new Error(`Clipboard unavailable: ${wlCopyFailure}xclip/xsel not found and OSC 52 requires a TTY. Try running inside a terminal emulator.`)}return}const primaryMsg=formatCommandFailure(primaryError,"xclip");const fallbackMsg=formatCommandFailure(fallbackError,"xsel");if(writeOsc52(text))return;throw new Error(`Clipboard unavailable: ${wlCopyFailure}xclip/xsel failed ("${primaryMsg}", "${fallbackMsg}") and OSC 52 requires a TTY. Try running inside a terminal emulator.`)}}return;default:throw new Error(`Unsupported platform: ${process.platform}`)}},"copyToClipboard");var getUrlOpenCommand=__name(()=>{let openCmd;switch(process.platform){case"darwin":openCmd="open";break;case"win32":openCmd="start";break;case"linux":openCmd="xdg-open";break;default:openCmd="xdg-open";debugLogger.warn(`Unknown platform: ${process.platform}. Attempting to open URLs with: ${openCmd}.`);break}return openCmd},"getUrlOpenCommand");function isMidInputCompletableCommand(cmd){return cmd.modelInvocable===true&&!cmd.hidden}__name(isMidInputCompletableCommand,"isMidInputCompletableCommand");function findMidInputSlashCommand(input,cursorOffset){const codePoints=toCodePoints(input);const beforeCursor=codePoints.slice(0,cursorOffset).join("");const match=beforeCursor.match(/\s\/([a-zA-Z0-9_:-]*)$/);if(!match)return null;const partialCommand=match[1];const slashPos=cursorOffset-1-partialCommand.length;const textAfterSlash=codePoints.slice(slashPos+1).join("");const commandMatch=textAfterSlash.match(/^[a-zA-Z0-9_:-]*/);const fullCommand=commandMatch?commandMatch[0]:"";if(cursorOffset!==slashPos+1+fullCommand.length)return null;return{token:"/"+fullCommand,startPos:slashPos,partialCommand}}__name(findMidInputSlashCommand,"findMidInputSlashCommand");function getBestSlashCommandMatch(partialCommand,commands,recentCommands){if(!partialCommand)return null;const query=partialCommand.toLowerCase();const matches=commands.filter(cmd=>{if(!isMidInputCompletableCommand(cmd))return false;const name=cmd.name.toLowerCase();return name.startsWith(query)&&(name!==query||!!cmd.argumentHint)}).sort((left,right)=>{const leftRecent=recentCommands?.get(left.name);const rightRecent=recentCommands?.get(right.name);const recentOrder=(rightRecent?.usedAt??0)-(leftRecent?.usedAt??0);return(right.completionPriority??0)-(left.completionPriority??0)||recentOrder||left.name.localeCompare(right.name)});const best=matches[0];if(!best)return null;return{suffix:best.name.slice(partialCommand.length),fullCommand:best.name,command:best,argumentHint:best.argumentHint}}__name(getBestSlashCommandMatch,"getBestSlashCommandMatch");var SLASH_TOKEN_RE=/(?:^|(?<=\s))\/([a-zA-Z][a-zA-Z0-9:_-]*)/g;function findSlashCommandTokens(text,commands){if(!text)return[];const commandMapEntries=[];for(const cmd of commands){commandMapEntries.push([cmd.name.toLowerCase(),cmd]);for(const altName of cmd.altNames??[]){commandMapEntries.push([altName.toLowerCase(),cmd])}}const commandMap=new Map(commandMapEntries);const tokens=[];let match;SLASH_TOKEN_RE.lastIndex=0;while((match=SLASH_TOKEN_RE.exec(text))!==null){const fullMatch=match[0];const commandName=match[1];const start=match.index;const end=start+fullMatch.length;const precedingChar=start>0?text[start-1]:null;const isLineStart=start===0||precedingChar==="\n";const cmd=commandMap.get(commandName.toLowerCase());let valid=false;if(cmd){if(isLineStart){valid=cmd.userInvocable!==false&&!cmd.hidden}else{const prefix=text.slice(0,start);valid=cmd.modelInvocable===true||isStackedSkillCompletableCommand(cmd)&&isValidStackedSkillPrefix(prefix,commands)}}tokens.push({start,end,commandName,valid})}return tokens}__name(findSlashCommandTokens,"findSlashCommandTokens");init_esbuild_shims();function formatBtwToolCallNotice(toolName){return t("(The model tried to call {{tool}} instead of answering directly. Try rephrasing or ask in the main conversation.)",{tool:toolName})}__name(formatBtwToolCallNotice,"formatBtwToolCallNotice");var NOTICE_MS=2e3;var activeView=null;function showBtwRequest(ui,session,requestId){activeView?.detach();const controller=new AbortController;const view={ui,session,requestId,browseId:null,shortcuts:false,detach:__name(()=>{unsubscribe();controller.signal.removeEventListener("abort",onAbort);clearTimeout(view.noticeTimer);clearTimeout(view.retryTimer);if(activeView===view)activeView=null},"detach")};const onAbort=__name(()=>{view.detach();session.abort(requestId)},"onAbort");controller.signal.addEventListener("abort",onAbort);const unsubscribe=session.subscribe(()=>render(view));ui.btwAbortControllerRef.current=controller;activeView=view;render(view)}__name(showBtwRequest,"showBtwRequest");function handleBtwViewKey(key){const view=activeView;if(!view)return false;if(key.ctrl||key.meta||key.paste){exitBrowseMode(view);return false}if(key.name==="left"||key.name==="right"){return browseBtwHistory(key.name==="left"?"older":"newer")}if(view.shortcuts){if(key.sequence==="c"&©BtwAnswer())return true;if(key.sequence==="x"&&clearBtwHistory())return true}if(key.name==="return"||key.sequence===" "){const ownRequest=view.session.getRequest(view.requestId);if(ownRequest?.outcome===null||project(view)?.isPending!==false){exitBrowseMode(view);return false}dismissBtwView();return true}exitBrowseMode(view);return false}__name(handleBtwViewKey,"handleBtwViewKey");function dismissBtwView(){const view=activeView;if(!view)return;view.detach();view.ui.btwAbortControllerRef.current=null;view.ui.setBtwItem(null)}__name(dismissBtwView,"dismissBtwView");function browseBtwHistory(direction){const view=activeView;if(!view)return false;const exchanges=browsableExchanges(view);const count=exchanges.length;if(count===0)return false;const current=exchanges.findIndex(exchange=>exchange.id===view.browseId);if(direction==="older"){view.browseId=current===-1?exchanges[count-1].id:exchanges[Math.max(0,current-1)].id}else if(view.browseId!==null){view.browseId=current===-1||current>=count-1?null:exchanges[current+1].id}view.shortcuts=true;render(view);return true}__name(browseBtwHistory,"browseBtwHistory");function clearBtwHistory(){const view=activeView;if(!view)return false;const ids=browsableExchanges(view).map(exchange=>exchange.id);if(ids.length===0)return false;view.browseId=null;view.session.removeExchanges(ids);return true}__name(clearBtwHistory,"clearBtwHistory");function copyBtwAnswer(copy=copyToClipboard){const view=activeView;if(!view)return false;const displayed=project(view);if(!displayed||displayed.isPending||displayed.isError)return false;void copy(displayed.answer).then(()=>setNotice(view,{text:t("Copied to clipboard")}),()=>setNotice(view,{text:t("Copy failed"),isError:true}));return true}__name(copyBtwAnswer,"copyBtwAnswer");function exitBrowseMode(view){if(!view.shortcuts)return;view.shortcuts=false;render(view)}__name(exitBrowseMode,"exitBrowseMode");function setNotice(view,notice){if(activeView!==view)return;clearTimeout(view.noticeTimer);view.notice=notice;render(view);view.noticeTimer=setTimeout(()=>{view.notice=void 0;render(view)},NOTICE_MS)}__name(setNotice,"setNotice");function browsableExchanges(view){return view.session.getSnapshot().exchanges.filter(exchange=>exchange.id!==view.requestId)}__name(browsableExchanges,"browsableExchanges");function render(view){if(activeView!==view)return;const btw=project(view);if(!btw){view.detach();view.ui.btwAbortControllerRef.current=null;view.ui.setBtwItem(null);return}clearTimeout(view.retryTimer);if(btw.retryStatus){view.retryTimer=setTimeout(()=>render(view),1e3)}view.ui.setBtwItem({type:"btw",btw})}__name(render,"render");function project(view){const exchanges=browsableExchanges(view);const ownRequestPending=view.session.getRequest(view.requestId)?.outcome===null;const common={historyCount:exchanges.length,...view.shortcuts?{browsing:true}:{},...ownRequestPending?{ownRequestPending:true}:{},...view.notice?{notice:view.notice}:{}};if(view.browseId!==null){const index=exchanges.findIndex(exchange2=>exchange2.id===view.browseId);if(index!==-1){const exchange2=exchanges[index];return{...common,question:exchange2.question,answer:exchange2.response,isPending:false,browsePosition:index+1}}view.browseId=null}const request=view.session.getRequest(view.requestId);if(request)return projectRequest(request,common);const exchange=view.session.getSnapshot().exchanges.find(entry=>entry.id===view.requestId);return exchange?{...common,question:exchange.question,answer:exchange.response,isPending:false}:null}__name(project,"project");function projectRequest(request,common){const base={...common,question:request.question};const outcome=request.outcome;if(!outcome){return{...base,answer:request.streamingText,isPending:true,...request.retry?{retryStatus:formatRetry(request.retry)}:{}}}switch(outcome.kind){case"answered":return{...base,answer:outcome.response,isPending:false};case"tool-call":return{...base,answer:formatBtwToolCallNotice(outcome.toolName),isPending:false};case"empty":return{...base,answer:t("No response received."),isPending:false};case"unavailable":return{...base,answer:t("No conversation context available for /btw"),isPending:false,isError:true};case"failed":return{...base,answer:t("(API error: {{error}})",{error:outcome.error}),isPending:false,isError:true};case"cancelled":return null;default:return null}}__name(projectRequest,"projectRequest");function formatRetry(retry){const seconds=Math.max(0,Math.ceil((retry.retryAt-Date.now())/1e3));return t("{{reason}} \xB7 retrying in {{seconds}}s \xB7 attempt {{attempt}}/{{max}}",{reason:retry.message?.split("\n")[0]||t("API error"),seconds:String(seconds),attempt:String(retry.attempt),max:String(retry.maxRetries)})}__name(formatRetry,"formatRetry");init_esbuild_shims();import{isDeepStrictEqual}from"node:util";function isCrossSessionMessagingEnabled(settings){const value=settings?.agents?.crossSessionMessaging;return value===void 0||value===true}__name(isCrossSessionMessagingEnabled,"isCrossSessionMessagingEnabled");function crossSessionMessagingSuppression(config){if(config?.isSafeMode?.()===true)return"safe-mode";if(config?.getBareMode?.()===true)return"bare";return void 0}__name(crossSessionMessagingSuppression,"crossSessionMessagingSuppression");function isCrossSessionMessagingActive(settings,config){return isCrossSessionMessagingEnabled(settings)&&crossSessionMessagingSuppression(config)===void 0}__name(isCrossSessionMessagingActive,"isCrossSessionMessagingActive");function switchIn(file){return file?.settings.agents?.crossSessionMessaging}__name(switchIn,"switchIn");function workspaceCounts(settings){return settings.isTrusted===true&&settings.workspaceSettingsActive===true}__name(workspaceCounts,"workspaceCounts");function isCrossSessionMessagingOptedIn(settings){if(switchIn(settings.user)===true)return true;return workspaceCounts(settings)&&switchIn(settings.workspace)===true}__name(isCrossSessionMessagingOptedIn,"isCrossSessionMessagingOptedIn");function crossSessionMessagingOffScope(settings){if(isCrossSessionMessagingEnabled(settings.merged))return void 0;const merged=settings.merged.agents?.crossSessionMessaging;if(switchIn(settings.system)!==void 0)return"system";if(isDeepStrictEqual(switchIn(settings.user),merged))return"user";if(isDeepStrictEqual(switchIn(settings.systemDefaults),merged)){return"system-defaults"}if(workspaceCounts(settings)&&isDeepStrictEqual(switchIn(settings.workspace),merged)){return"workspace"}return void 0}__name(crossSessionMessagingOffScope,"crossSessionMessagingOffScope");init_esbuild_shims();var debugLogger2=createDebugLogger("SESSION_MODEL");var AUTH_TYPES=new Set(Object.values(AuthType));function isAuthType(value){return AUTH_TYPES.has(value)}__name(isAuthType,"isAuthType");function registryHonoredBaseUrl(config,authType,modelId,baseUrl){if(typeof baseUrl!=="string"||!baseUrl){return void 0}return config.getResolvedModelConfig?.(authType,modelId,baseUrl)?baseUrl:void 0}__name(registryHonoredBaseUrl,"registryHonoredBaseUrl");async function recordDaemonSessionModel(config,payload){const recording=config.getChatRecordingService?.();if(!recording?.recordSessionModel)return;try{await recording.recordSessionModel(payload)}catch(error){debugLogger2.debug("recordSessionModel failed",error)}}__name(recordDaemonSessionModel,"recordDaemonSessionModel");async function recordDaemonSessionModelFromConfig(config){const modelId=config.getModel()?.trim();const authType=config.getAuthType();if(!modelId||!authType)return;const snapshot=config.getActiveRuntimeModelSnapshot?.();const registryBaseUrl=snapshot?void 0:config.getCurrentModelRegistryBaseUrl?.();await recordDaemonSessionModel(config,{modelId,authType,...typeof registryBaseUrl==="string"?{baseUrl:registryBaseUrl}:{},...snapshot?{isRuntime:true}:{}})}__name(recordDaemonSessionModelFromConfig,"recordDaemonSessionModelFromConfig");function hasMatchingRuntimeSnapshot(config,authType,modelId){const snapshot=config.getActiveRuntimeModelSnapshot?.();return snapshot?.authType===authType&&snapshot.modelId===modelId}__name(hasMatchingRuntimeSnapshot,"hasMatchingRuntimeSnapshot");function liveAuthType(config){return config.getAuthType()??config.getModelsConfig?.()?.getCurrentAuthType?.()}__name(liveAuthType,"liveAuthType");function runtimeSnapshotIdentity(snapshot){if(!snapshot)return void 0;if(typeof snapshot.id==="string"&&snapshot.id){return snapshot.id}if(snapshot.authType&&snapshot.modelId){return buildRuntimeSnapshotId(snapshot.authType,snapshot.modelId)}return void 0}__name(runtimeSnapshotIdentity,"runtimeSnapshotIdentity");function recordedRouteMatches(recorded,currentRegistryBaseUrl){if(!recorded||recorded.isRuntime)return true;const targetBaseUrl=recorded.baseUrl;if(targetBaseUrl===void 0){return currentRegistryBaseUrl===null||currentRegistryBaseUrl===void 0}if(targetBaseUrl===""){return currentRegistryBaseUrl===null||currentRegistryBaseUrl===void 0||currentRegistryBaseUrl===""}return currentRegistryBaseUrl===targetBaseUrl}__name(recordedRouteMatches,"recordedRouteMatches");async function applyRestoredSessionModel(config,projection){const recorded=projection?.runtime.recording.sessionModel;const fallbackModel=projection?.runtime.recording.lastAssistantModel;const recordedAuth=recorded?.authType?.trim();const authType=(recordedAuth&&isAuthType(recordedAuth)?recordedAuth:liveAuthType(config))?.trim();const modelId=recorded?.modelId||fallbackModel;if(!modelId?.trim()||!authType||!isAuthType(authType))return;const currentModel=stripRuntimeSnapshotPrefix(config.getModel()??"");const currentAuth=liveAuthType(config);const targetModel=stripRuntimeSnapshotPrefix(modelId.trim());const targetBaseUrl=recorded?.isRuntime?void 0:registryHonoredBaseUrl(config,authType,targetModel,recorded?.baseUrl);const recordedRoute=recorded?{...recorded,...targetBaseUrl?{baseUrl:targetBaseUrl}:{baseUrl:void 0}}:void 0;const currentRegistryBaseUrl=config.getCurrentModelRegistryBaseUrl?.();const baseUrlMatches=recordedRouteMatches(recordedRoute,currentRegistryBaseUrl);const currentRuntimeMatches=hasMatchingRuntimeSnapshot(config,authType,targetModel);if(currentModel===targetModel&¤tAuth===authType&&baseUrlMatches&&!(recorded&&!recorded.isRuntime&¤tRuntimeMatches)){return}const useRuntimeSnapshot=Boolean(recorded?.isRuntime)&&hasMatchingRuntimeSnapshot(config,authType,targetModel);const switchModelId=useRuntimeSnapshot?buildRuntimeSnapshotId(authType,targetModel):targetModel;const requireCachedCredentials=authType==="qwen-oauth"&¤tAuth!==authType;const switchOptions=targetBaseUrl||requireCachedCredentials?{...targetBaseUrl?{baseUrl:targetBaseUrl}:{},...requireCachedCredentials?{requireCachedCredentials:true}:{}}:void 0;try{await config.switchModel(authType,switchModelId,switchOptions)}catch(error){debugLogger2.warn(`restore session model failed (${targetModel}/${authType}): ${error instanceof Error?error.message:String(error)}`)}}__name(applyRestoredSessionModel,"applyRestoredSessionModel");async function restoreSessionModelThenAuthenticate(config,projection,authenticate){const originalAuth=liveAuthType(config);const originalModel=config.getModel();const originalBaseUrl=config.getCurrentModelRegistryBaseUrl?.();const originalRuntimeSnapshot=config.getActiveRuntimeModelSnapshot?.();await applyRestoredSessionModel(config,projection);try{await authenticate()}catch(error){if(liveAuthType(config)===originalAuth&&config.getModel()===originalModel&&(config.getCurrentModelRegistryBaseUrl?.()??void 0)===(originalBaseUrl??void 0)&&runtimeSnapshotIdentity(config.getActiveRuntimeModelSnapshot?.())===runtimeSnapshotIdentity(originalRuntimeSnapshot)){throw error}debugLogger2.warn("restored session model made authentication fail; retrying with settings model");if(!originalAuth||!originalModel){throw error}const rollbackModelId=originalRuntimeSnapshot?.authType===originalAuth&&originalRuntimeSnapshot.modelId===stripRuntimeSnapshotPrefix(originalModel)?buildRuntimeSnapshotId(originalAuth,stripRuntimeSnapshotPrefix(originalModel)):originalModel;try{await config.switchModel(originalAuth,rollbackModelId,typeof originalBaseUrl==="string"?{baseUrl:originalBaseUrl}:void 0)}catch{throw error}await authenticate()}}__name(restoreSessionModelThenAuthenticate,"restoreSessionModelThenAuthenticate");init_esbuild_shims();var SSH_SLASH_COMMAND_POLICY={allowSessionReset:false,allowWorkspaceSettingsWrite:false,persistModelSelection:false,blockedBuiltinCommandNames:[]};var sshCommands=new Set(["help","model","effort","compress","context"]);function isSshSessionCommandAllowed(command){return command.kind==="built-in"&&sshCommands.has(command.name)}__name(isSshSessionCommandAllowed,"isSshSessionCommandAllowed");var unsupportedSessionMethods=new Set([SERVE_STATUS_EXT_METHODS.sessionMessageGroups,SERVE_CONTROL_EXT_METHODS.sessionCd,SERVE_CONTROL_EXT_METHODS.sessionBranch,SERVE_CONTROL_EXT_METHODS.sessionSideTask,SERVE_CONTROL_EXT_METHODS.sessionForkAgent,SERVE_CONTROL_EXT_METHODS.sessionBtw,SERVE_CONTROL_EXT_METHODS.sessionArtifactsPersist,SERVE_CONTROL_EXT_METHODS.sessionMessagesDelete,SERVE_CONTROL_EXT_METHODS.sessionRewind,SERVE_CONTROL_EXT_METHODS.sessionWorkflowTaskAction,SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeAdd,SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeRemove,SERVE_CONTROL_EXT_METHODS.sessionLanguage,SERVE_CONTROL_EXT_METHODS.sessionManagedConversationBindingCommit,SERVE_CONTROL_EXT_METHODS.sessionManagedConversationBindingRelease,"rewindSession"]);function isSshWorkspaceExtMethodAllowed(method){return!(method.startsWith("qwen/control/workspace/")||method.startsWith("qwen/skills/")||method.startsWith("qwen/session/sources/")||method.startsWith("qwen/settings/")&&method!=="qwen/settings/getCore"||unsupportedSessionMethods.has(method))}__name(isSshWorkspaceExtMethodAllowed,"isSshWorkspaceExtMethodAllowed");init_esbuild_shims();init_esbuild_shims();var debugLogger3=createDebugLogger("CLI_COMMANDS");function commandOrigin(command){const owner=command.extensionName?`extension "${command.extensionName}"`:command.kind;return`${owner} command "${command.name}"`}__name(commandOrigin,"commandOrigin");var CommandService=class _CommandService{constructor(commands){this.commands=commands}static{__name(this,"CommandService")}static async create(loaders,signal,disabledNames){const results=await Promise.allSettled(loaders.map(loader=>loader.loadCommands(signal)));const allCommands=[];for(const result of results){if(result.status==="fulfilled"){allCommands.push(...result.value)}else{debugLogger3.debug("A command loader failed:",result.reason)}}const commandMap=new Map;for(const cmd of allCommands){let finalName=cmd.name;if(cmd.extensionName&&commandMap.has(cmd.name)){let renamedName=`${cmd.extensionName}.${cmd.name}`;let suffix=1;while(commandMap.has(renamedName)){renamedName=`${cmd.extensionName}.${cmd.name}${suffix}`;suffix++}finalName=renamedName}const shadowed=commandMap.get(finalName);if(shadowed){debugLogger3.warn(`Slash command "/${finalName}" from ${commandOrigin(shadowed)} is replaced by ${commandOrigin(cmd)}`)}commandMap.set(finalName,{...cmd,name:finalName})}if(disabledNames&&disabledNames.size>0){const normalizedDisabled=new Set;for(const entry of disabledNames){const trimmed=entry.trim();if(trimmed)normalizedDisabled.add(trimmed.toLowerCase())}if(normalizedDisabled.size>0){for(const[name,cmd]of Array.from(commandMap.entries())){if(commandRestrictionNames(cmd).some(candidate=>normalizedDisabled.has(candidate))){commandMap.delete(name)}}}}const finalCommands=Object.freeze(Array.from(commandMap.values()));return new _CommandService(finalCommands)}getCommands(){return this.commands}getCommandsForMode(mode){return Object.freeze(filterCommandsForMode(this.commands.filter(cmd=>!cmd.hidden&&cmd.userInvocable!==false),mode))}getModelInvocableCommands(){return this.commands.filter(cmd=>!cmd.hidden&&cmd.modelInvocable===true)}};init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import fs from"node:fs/promises";import path from"node:path";var debugLogger4=createDebugLogger("SESSION_PATHS");var OPENAI_LOG_SCAN_LIMIT=100;async function collectSessionPathInfo(context){const config=context.services.config;const sessionId=config?.getSessionId()||context.session.stats.sessionId||"unknown";const contentGeneratorConfig=config?.getContentGeneratorConfig();const workingDir=config?.getWorkingDir()||process.cwd();const openAILogDir=resolveOpenAILogDir(contentGeneratorConfig?.openAILoggingDir,workingDir);const openAILoggingEnabled=contentGeneratorConfig?.enableOpenAILogging===true;const latestOpenAILog=openAILoggingEnabled&&sessionId!=="unknown"?await findLatestOpenAILogForSession(openAILogDir,sessionId):void 0;const transcriptPath=config?.getTranscriptPath()||"";const debugLogPath=config?.getDebugMode()&&sessionId!=="unknown"?Storage.getDebugLogPath(sessionId):"";const planFilePath=config?.getPlanFilePath()||(sessionId==="unknown"?"":Storage.getPlanFilePath(sessionId));const planFileExists=planFilePath?await pathExists(planFilePath):false;const sections=[{title:"Session files",entries:[{label:"Session ID",value:sessionId},...transcriptPath?[{label:"Transcript",value:transcriptPath}]:[],...debugLogPath?[{label:"Debug log",value:debugLogPath}]:[],...planFileExists?[{label:"Plan file",value:planFilePath}]:[]]}];if(openAILoggingEnabled){sections.push({title:"OpenAI logs",entries:[{label:"Directory",value:openAILogDir},{label:"Latest for session",value:latestOpenAILog??"none yet"}]})}return{sections}}__name(collectSessionPathInfo,"collectSessionPathInfo");function formatSessionPathInfo(info){const lines=[];for(const[index,section]of info.sections.entries()){if(index>0){lines.push("")}lines.push(`${section.title}:`);for(const entry of section.entries){lines.push(` ${entry.label}: ${entry.value}`)}}return lines.join("\n")}__name(formatSessionPathInfo,"formatSessionPathInfo");async function findLatestOpenAILogForSession(logDir,sessionId){const files=await listLogFiles(logDir,name=>/^openai-.*\.json$/.test(name));for(const file of files){try{const raw=await fs.readFile(file,"utf-8");const parsed=JSON.parse(raw);if(hasContextSessionId(parsed,sessionId)){return file}}catch(error){if(error instanceof SyntaxError||error.code==="ENOENT"){continue}debugLogger4.warn("Error reading OpenAI log file",file,error)}}return void 0}__name(findLatestOpenAILogForSession,"findLatestOpenAILogForSession");async function listLogFiles(dir,predicate){try{const entries=await fs.readdir(dir,{withFileTypes:true});const files=[];for(const entry of entries){if(!entry.isFile()||!predicate(entry.name)){continue}insertRecentFile(files,path.join(dir,entry.name))}return files}catch(error){if(error.code!=="ENOENT"){debugLogger4.warn("Unable to list OpenAI log directory",dir,error)}return[]}}__name(listLogFiles,"listLogFiles");function insertRecentFile(files,file){const insertAt=files.findIndex(existing=>file>existing);if(insertAt===-1){if(files.length<OPENAI_LOG_SCAN_LIMIT){files.push(file)}return}files.splice(insertAt,0,file);if(files.length>OPENAI_LOG_SCAN_LIMIT){files.pop()}}__name(insertRecentFile,"insertRecentFile");async function pathExists(filePath){try{await fs.access(filePath);return true}catch{return false}}__name(pathExists,"pathExists");function hasContextSessionId(value,sessionId){if(!value||typeof value!=="object"){return false}const context=value.context;if(!context||typeof context!=="object"){return false}const ctx=context;return ctx.sessionId===sessionId||ctx.promptId===sessionId}__name(hasContextSessionId,"hasContextSessionId");var aboutCommand={name:"status",altNames:["about"],get description(){return t("show version info")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const systemInfo=await getExtendedSystemInfo(context);if(context.executionMode!=="interactive"){const authLabel=systemInfo.selectedAuthType==="qwen-subscription"?"Qwen Subscription":systemInfo.selectedAuthType;const lines=[`Qwen Code v${systemInfo.cliVersion}`,`Model: ${systemInfo.modelVersion}`,`Fast Model: ${systemInfo.fastModel??"not set"}`,`Auth: ${authLabel}`,`Platform: ${systemInfo.osPlatform} ${systemInfo.osArch} (${systemInfo.osRelease})`,`Node.js: ${systemInfo.nodeVersion}`,`Session: ${systemInfo.sessionId}`,...systemInfo.gitCommit?[`Git commit: ${systemInfo.gitCommit}`]:[],...systemInfo.ideClient?[`IDE: ${systemInfo.ideClient}`]:[],...systemInfo.lspStatus?[`LSP: ${systemInfo.lspStatus}`]:[]];return{type:"message",messageType:"info",content:lines.join("\n")}}const aboutItem={type:"about",systemInfo};context.ui.addItem(aboutItem,Date.now());return},"action"),subCommands:[{name:"paths",get description(){return t("show paths for current session files and logs")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const info=await collectSessionPathInfo(context);const content=formatSessionPathInfo(info);return{type:"message",messageType:"info",content}},"action")}]};init_esbuild_shims();var ADVISOR_SCHEMA={type:"object",additionalProperties:false,properties:{verdict:{type:"string",minLength:1},risks:{type:"string",minLength:1},missingEvidence:{type:"string",minLength:1},recommendation:{type:"string",minLength:1}},required:["verdict","risks","missingEvidence","recommendation"]};function buildAdvisorPrompt(focus){return["<system-reminder>","You are acting as an ADVISOR \u2014 an independent senior reviewer giving a second opinion on the conversation so far. The transcript above may be truncated to the most recent turns; treat what is shown as the evidence available to you.","","CRITICAL CONSTRAINTS:","- You have NO tools. Base every claim strictly on evidence present in the transcript; never claim to have verified something you could not observe.","- Do not perform the task or write the implementation. Review only.","- Be direct about problems: flawed assumptions, premature conclusions, unverified claims, risky next steps.","- The main conversation is NOT interrupted; your review is shown to the user only.","","Return exactly one JSON object with these string fields and no markdown fence, preamble, extra key, or commentary:","- verdict: one short paragraph stating whether the current approach or conclusion is sound.",'- risks: concrete risks or flawed assumptions, each citing transcript evidence. Write "None found" if none.',"- missingEvidence: claims asserted but not verified in the visible transcript (earlier verification may exist outside the shown window).","- recommendation: the single most valuable next action.","</system-reminder>","",focus||"Review the conversation above."].join("\n")}__name(buildAdvisorPrompt,"buildAdvisorPrompt");function formatAdvisorReview(value){const fields=["verdict","risks","missingEvidence","recommendation"];if(!value||Object.keys(value).length!==fields.length||fields.some(field=>{const fieldValue=value[field];return typeof fieldValue!=="string"||fieldValue.trim().length===0})){throw new Error("Advisor returned invalid structured output.")}const review=value;return["## Verdict",review.verdict.trim(),"## Risks",review.risks.trim(),"## Missing evidence",review.missingEvidence.trim(),"## Recommendation",review.recommendation.trim()].join("\n\n")}__name(formatAdvisorReview,"formatAdvisorReview");function parseJsonObjectText(text){const value=text?.trim();if(!value)return void 0;const firstStructuredChar=value.search(/[[{]/);if(firstStructuredChar!==-1&&value[firstStructuredChar]==="["){return void 0}const first=value.indexOf("{");const last=value.lastIndexOf("}");if(first===-1||last<=first)return void 0;try{const parsed=JSON.parse(value.slice(first,last+1));return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:void 0}catch{return void 0}}__name(parseJsonObjectText,"parseJsonObjectText");function formatAdvisorError(error){return t("Advisor review failed: {{error}}",{error:error instanceof Error?error.message:String(error||"Unknown error")})}__name(formatAdvisorError,"formatAdvisorError");function unavailableModelMessage(modelName,availableModelIds){const configured=availableModelIds.length>0?t("Configured models: {{models}}.",{models:availableModelIds.join(", ")}):t("No models are configured.");return[`Advisor model '${modelName}' is not configured.`,configured,"Configure models in settings.modelProviders, or run /advisor without arguments to choose a model."].join("\n")}__name(unavailableModelMessage,"unavailableModelMessage");async function setAdvisorModel(context,model){if(context.executionPolicy?.persistModelSelection===false){return{type:"message",messageType:"error",content:t("This model selection is not available in this session.")}}const{config,settings}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Advisor configuration is unavailable.")}}if(model){const availability=checkAdvisorModelAvailability(config,model);if(!availability.available){return{type:"message",messageType:"error",content:unavailableModelMessage(model,availability.availableModelIds)}}}const applied=await config.setAdvisorModel(model);if(applied===false){return{type:"message",messageType:"error",content:t("Advisor configuration is unavailable.")}}settings.setValue("User","advisorModel",model??"");return{type:"message",messageType:"info",content:model?t("Advisor set to {{model}}",{model}):t("Advisor disabled")}}__name(setAdvisorModel,"setAdvisorModel");async function askAdvisor(context,focus,abortSignal){const{config}=context.services;if(!config)throw new Error(t("Config not loaded."));const cacheSafeParams=buildBtwCacheSafeParams(config);if(!cacheSafeParams||config.getLlmClient().getHistoryForForkWindow().length===0){throw new Error(t("No conversation context available for /advisor"))}const advisorModel=config.getAdvisorModel();const result=await runForkedAgent({config,userMessage:buildAdvisorPrompt(focus),cacheSafeParams,jsonSchema:ADVISOR_SCHEMA,...advisorModel?{model:advisorModel}:{},abortSignal,disableModelFallbacks:true});return{text:formatAdvisorReview(result.jsonResult??parseJsonObjectText(result.text)),model:result.model}}__name(askAdvisor,"askAdvisor");var advisorCommand={name:"advisor",get description(){return t("Configure the Advisor model")},argumentHint:"[<model-id>|off|review [focus]]",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],completion:__name(async(context,partialArg)=>{const prefix=partialArg.trim();const fixed=[{value:"off",description:t("Disable Advisor")},{value:"review",description:t("Get a second opinion on the current conversation from a reviewer model")}].filter(({value})=>value.startsWith(prefix));if(!context.services.config||prefix.startsWith("review "))return fixed;return[...fixed,...context.services.config.getAllConfiguredModels().filter(model=>isAdvisorModelEligible(model)).map(model=>model.id).filter(id=>id.startsWith(prefix))]},"completion"),action:__name(async(context,args)=>{const value=context.invocation?.args?.trim()||args.trim();const[subcommand="",...rest]=value.split(/\s+/);const isReview=subcommand==="review";if(!isReview){if(!value){if(context.executionMode!=="interactive"){return{type:"message",messageType:"info",content:[`Advisor: ${context.services.config?.getAdvisorModel()?.split("\0")[0]??"off"}`,`Session calls: ${context.services.config?.getAdvisorUseCount()??0} / ${context.services.config?.getAdvisorMaxUses()||"unlimited"}`,"Each consultation sends the conversation to the selected provider and consumes additional tokens.","Use /advisor <model-id> or /advisor off."].join("\n")}}return{type:"dialog",dialog:"advisor-model"}}return setAdvisorModel(context,value.toLowerCase()==="off"?void 0:value)}const focus=rest.join(" ").trim();if(focus.length>BTW_MAX_INPUT_LENGTH){return{type:"message",messageType:"error",content:t("Focus too long (max {{max}} chars)",{max:String(BTW_MAX_INPUT_LENGTH)})}}const{config}=context.services;const{ui}=context;if(!config){return{type:"message",messageType:"error",content:t("Config not loaded.")}}if(!config.getModel()){return{type:"message",messageType:"error",content:t("No model configured.")}}const abortSignal=context.abortSignal??new AbortController().signal;const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){try{const review=await askAdvisor(context,focus,abortSignal);return{type:"message",messageType:"info",content:review.text}}catch(error){return{type:"message",messageType:"error",content:formatAdvisorError(error)}}}const turnInFlight=!ui.isIdleRef.current||ui.pendingItem!==null;if(turnInFlight){return{type:"message",messageType:"error",content:t("Another operation is in progress, wait for it to complete before running /advisor")}}try{ui.setPendingItem({type:"info",text:t("Consulting advisor...")});const review=await askAdvisor(context,focus,abortSignal);if(abortSignal.aborted)return;ui.addItem({type:"advisor",text:review.text,model:review.model},Date.now())}catch(error){if(abortSignal.aborted)return;ui.addItem({type:"error",text:formatAdvisorError(error)},Date.now())}finally{if(!abortSignal.aborted)ui.setPendingItem(null)}},"action")};init_esbuild_shims();function statusLabel(entry){switch(entry.kind){case"agent":{const status=entry.status;switch(status){case"completed":return"completed";case"failed":return`failed: ${entry.error??"unknown error"}`;case"cancelled":return"cancelled";case"paused":return entry.resumeBlockedReason?`paused (resume blocked): ${entry.resumeBlockedReason}`:"paused";case"running":return"running";default:{const _exhaustive=status;throw new Error(`statusLabel(agent): unknown status: ${JSON.stringify(_exhaustive)}`)}}}case"shell":{const status=entry.status;switch(status){case"completed":return`completed (exit ${entry.exitCode??"?"})`;case"failed":return`failed: ${entry.error??"unknown error"}`;case"cancelled":return"cancelled";case"running":return"running";default:{const _exhaustive=status;throw new Error(`statusLabel(shell): unknown status: ${JSON.stringify(_exhaustive)}`)}}}case"monitor":{const events=`${entry.eventCount} event${entry.eventCount===1?"":"s"}`;const status=entry.status;switch(status){case"completed":return entry.error?`completed (${entry.error}, ${events})`:`completed (exit ${entry.exitCode??"?"}, ${events})`;case"failed":return`failed: ${entry.error??"unknown error"} (${events})`;case"cancelled":return`cancelled (${events})`;case"running":return`running (${events})`;default:{const _exhaustive=status;throw new Error(`statusLabel(monitor): unknown status: ${JSON.stringify(_exhaustive)}`)}}}default:{const _exhaustive=entry;throw new Error(`statusLabel: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(statusLabel,"statusLabel");function taskLabel(entry){switch(entry.kind){case"agent":return buildBackgroundEntryLabel(entry);case"shell":return entry.command;case"monitor":return entry.description;default:{const _exhaustive=entry;throw new Error(`taskLabel: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskLabel,"taskLabel");function taskId(entry){switch(entry.kind){case"agent":return entry.agentId;case"shell":return entry.shellId;case"monitor":return entry.monitorId;default:{const _exhaustive=entry;throw new Error(`taskId: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskId,"taskId");function taskOutputPath(entry){switch(entry.kind){case"agent":case"shell":return entry.outputFile;case"monitor":return void 0;default:{const _exhaustive=entry;throw new Error(`taskOutputPath: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskOutputPath,"taskOutputPath");var tasksCommand={name:"tasks",get description(){return t("List background tasks (text dump \u2014 interactive dialog opens via the footer pill)")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:"Config not available."}}const agentEntries=[...config.getBackgroundTaskRegistry().getAll()];const shellEntries=[...config.getBackgroundShellRegistry().getAll()];const monitorEntries=[...config.getMonitorRegistry().getAll()];const entries=[...agentEntries,...shellEntries,...monitorEntries].sort((a,b)=>a.startTime-b.startTime);if(entries.length===0){return{type:"message",messageType:"info",content:"No background tasks."}}const now=Date.now();const lines=[];if(context.executionMode==="interactive"){lines.push(t("Tip: focus the Background tasks pill in the footer (use \u2193 from an empty composer) and press Enter for the interactive dialog with detail view + live updates."),"")}lines.push(`Background tasks (${entries.length} total)`,"");for(const entry of entries){const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});const pidPart=(entry.kind==="shell"||entry.kind==="monitor")&&entry.pid!==void 0?` pid=${entry.pid}`:"";lines.push(`[${taskId(entry)}] ${statusLabel(entry)} ${runtime}${pidPart} ${taskLabel(entry)}`);const outputPath=taskOutputPath(entry);if(outputPath){lines.push(` output: ${outputPath}`)}}return{type:"message",messageType:"info",content:stripUnsafeCharacters(lines.join("\n"))}},"action")};init_esbuild_shims();function snapshotToTask(s){return{id:s.runId,kind:"workflow",runId:s.runId,...s.parentSessionId?{parentSessionId:s.parentSessionId}:{},...s.toolUseId?{toolUseId:s.toolUseId}:{},...s.sourceRef?{sourceRef:{...s.sourceRef}}:{},...s.workflowCalls?{workflowCalls:s.workflowCalls.map(call=>({...call}))}:{},...s.workflowCallsTruncated?{workflowCallsTruncated:true}:{},...s.workflowName?{workflowName:s.workflowName}:{},description:s.meta?.name??s.runId,meta:s.meta,status:s.status,currentPhase:null,currentPhaseVisitId:null,phases:s.phases??[],phaseVisits:s.phaseVisits??[],dispatches:s.dispatches??[],sourceRunId:s.sourceRunId,startMode:s.startMode,agentsDispatched:s.agentsDispatched??0,agentsCompleted:s.agentsCompleted??0,recentLogs:s.recentLogs??[],events:s.events??[],tokensSpent:s.tokensSpent??0,tokenBudgetTotal:s.tokenBudgetTotal??null,perPhaseTokens:new Map(s.perPhaseTokens??[]),pendingApprovals:[],script:s.script??"",scriptPath:s.scriptPath,result:s.result,error:s.error,startTime:s.startTime,endTime:s.endTime,outputFile:"",outputOffset:0,notified:true,abortController:new AbortController}}__name(snapshotToTask,"snapshotToTask");function rowLine(entry,now){const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});const label=entry.meta?.name??entry.runId;const phase=entry.currentPhase?` \xB7 ${entry.currentPhase}`:"";const counts=entry.agentsDispatched>0?` \xB7 ${entry.agentsCompleted}/${entry.agentsDispatched} agents`:"";const phaseCount=entry.phases.length>0?` \xB7 ${entry.phases.length} ${entry.phases.length===1?"phase":"phases"}`:"";const budgetChip=entry.tokensSpent>0||entry.tokenBudgetTotal!==null?entry.tokenBudgetTotal!==null?` \xB7 ${formatTokenCount(entry.tokensSpent)}/${formatTokenCount(entry.tokenBudgetTotal)}t`:` \xB7 ${formatTokenCount(entry.tokensSpent)}t`:"";const errorTail=entry.status==="failed"&&entry.error?` \u2014 ${entry.error.slice(0,80)}`:"";return` ${entry.runId.padEnd(20)} ${entry.status.padEnd(10)} ${runtime.padStart(8)} ${label}${phase}${counts}${phaseCount}${budgetChip}${errorTail}`}__name(rowLine,"rowLine");var MAX_DETAIL_ERROR_CHARS=4096;function isHollow(value){if(typeof value!=="object"||value===null)return false;return Object.values(value).every(isHollow)}__name(isHollow,"isHollow");function withoutHollowFailures(result){if(typeof result!=="object"||result===null||Array.isArray(result)){return result}const kept={...result};for(const key of REPORTED_FAILURE_KEYS){try{if(isHollow(kept[key]))delete kept[key]}catch{}}return kept}__name(withoutHollowFailures,"withoutHollowFailures");function mayHaveLostDetail(result){return typeof result==="object"&&result!==null||typeof result==="string"&&result.startsWith("(non-JSON-serializable ")}__name(mayHaveLostDetail,"mayHaveLostDetail");function resultPreviewFor(entry,source){if(entry.status!=="completed")return{legacy:false};if(!source){return{preview:buildWorkflowResultPreview(entry.result),legacy:false}}const{snapshot}=source;if(snapshot.resultPreview){return{preview:snapshot.resultPreview,legacy:false}}if(!Object.hasOwn(snapshot,"result"))return{legacy:true};const{result}=snapshot;return{preview:{...buildWorkflowResultPreview(result),reportedFailures:reportedFailureLines(withoutHollowFailures(result))},legacy:mayHaveLostDetail(result)}}__name(resultPreviewFor,"resultPreviewFor");function indent(text,prefix){return text.split("\n").map(line=>prefix+line).join("\n")}__name(indent,"indent");async function confirmedSnapshotFile(config,runId){if(!isWorkflowRunId(runId)||!config.storage)return void 0;return await readWorkflowSnapshot(config,runId)?config.storage.getWorkflowRunSnapshotPath(runId):void 0}__name(confirmedSnapshotFile,"confirmedSnapshotFile");function detailLines(entry,now,source){const lines=[];const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});lines.push(`Workflow ${entry.runId}`);if(entry.meta?.name){lines.push(` name : ${entry.meta.name}`)}if(entry.meta?.description){lines.push(` description : ${entry.meta.description}`)}if(entry.meta?.whenToUse){lines.push(` whenToUse : ${entry.meta.whenToUse}`)}lines.push(` status : ${entry.status}`);lines.push(` runtime : ${runtime}`);if(entry.currentPhase){lines.push(` currentPhase: ${entry.currentPhase}`)}lines.push(` agents : ${entry.agentsCompleted}/${entry.agentsDispatched}`);lines.push(` tokens : ${formatTokenCount(entry.tokensSpent)}`);lines.push(` cap : ${entry.tokenBudgetTotal!==null?formatTokenCount(entry.tokenBudgetTotal):"(no cap)"}`);if(entry.error){const error=truncateWorkflowText(sanitizeWorkflowText(entry.error),MAX_DETAIL_ERROR_CHARS);lines.push(` error : ${error.split("\n").join("\n ")}`)}if(source?.file){lines.push(` snapshotFile: ${source.file}`)}if(entry.phases.length>0){lines.push("");lines.push(` Phases (${entry.phases.length})`);for(const phase of entry.phases){const phaseTokens=entry.perPhaseTokens.get(phase)??0;const chip=phaseTokens>0?` \xB7 ${formatTokenCount(phaseTokens)}t`:"";lines.push(` \xB7 ${phase}${chip}`)}const prePhaseTokens=entry.perPhaseTokens.get(null)??0;if(prePhaseTokens>0){lines.push(` \xB7 (no phase) \xB7 ${formatTokenCount(prePhaseTokens)}t`)}}if(entry.recentLogs.length>0){lines.push("");lines.push(` Logs (last ${entry.recentLogs.length})`);for(const line of entry.recentLogs){lines.push(` ${line}`)}}if(source&&source.snapshot.dispatches===void 0){lines.push(""," Failed agents: not recorded in this snapshot")}else{const failures=buildFailureLines(entry);if(failures.length>0){const count=entry.dispatches.filter(d=>d.status==="failed").length;lines.push("",` Failed agents (${count})`);for(const line of failures)lines.push(indent(line," "))}}const{preview:preview2,legacy}=resultPreviewFor(entry,source);const reported=(preview2?.reportedFailures??[]).map(line=>truncateWorkflowText(sanitizeWorkflowText(line),MAX_FAILURE_LINE_CHARS));if(reported.length>0){lines.push(""," Reported failures");for(const line of reported)lines.push(indent(line," "))}if(entry.status==="completed"){lines.push(""," Result");if(!preview2){lines.push(" (this snapshot did not record a result)")}else{const sanitized=sanitizeWorkflowText(preview2.text);const text=truncateWorkflowText(sanitized,MAX_WORKFLOW_RESULT_PREVIEW_CHARS);lines.push(indent(text," "));if(preview2.truncated||text!==sanitized){lines.push(` (preview truncated to ${MAX_WORKFLOW_RESULT_PREVIEW_CHARS} characters)`)}}if(legacy){lines.push(" (older snapshot: result details such as Error, Map, and Set values may be incomplete)")}}return lines}__name(detailLines,"detailLines");var workflowsCommand={name:"workflows",get description(){return t("List workflow runs or cooperatively pause/resume a live run")},get argumentHint(){return t("[mode [status|on|off] | runId | p <runId>]")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],subCommands:[{name:"mode",description:"Show or change this session\u2019s Workflow guidance mode",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async(context,args)=>{const config=context.services.config;if(!config?.isWorkflowModeSupported()){return{type:"message",messageType:"error",content:"Workflow mode is unavailable for this session owner."}}const value=args.trim()||"status";if(!["status","on","off"].includes(value)){return{type:"message",messageType:"error",content:"Usage: /workflows mode [status|on|off]"}}try{const state=value==="status"?config.getWorkflowMode():await config.setWorkflowMode(value==="on");return{type:"message",messageType:"info",content:`Workflow mode: ${state.requested?"on":"off"}${state.requested&&!state.effective?" (unavailable)":""}${state.reason?` \u2014 ${state.reason}`:""}`}}catch(error){return{type:"message",messageType:"error",content:error instanceof Error?error.message:String(error)}}},"action")}],action:__name(async(context,args)=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:"Config not available."}}if(!config.isWorkflowsEnabled()){return{type:"message",messageType:"error",content:"Workflows are disabled. Use /workflows mode status or off to manage the saved mode."}}const registry=config.getWorkflowRunRegistry();const allEntries=registry.list();const trimmedArgs=(args??"").trim();const tokens=trimmedArgs.split(/\s+/);if(tokens[0]==="p"){if(context.executionMode!=="interactive"){return{type:"message",messageType:"error",content:"Workflow pause controls are available only in the interactive TUI."}}if(tokens.length!==2||!tokens[1]){return{type:"message",messageType:"error",content:"Usage: /workflows p <runId>"}}const runId=tokens[1];let target=registry.get(runId);let fromSnapshot=false;if(!target){const snapshot=(await listWorkflowSnapshots(config)).find(s=>s.runId===runId);if(snapshot){target=snapshotToTask(snapshot);fromSnapshot=true}}if(!target){return{type:"message",messageType:"error",content:`Unknown live workflow runId: ${runId}`}}if(isTerminalWorkflowStatus(target.status)){return{type:"message",messageType:"error",content:`Workflow ${runId} is ${target.status} and cannot be paused or resumed.`}}if(!fromSnapshot&&!target.isBackgrounded){return{type:"message",messageType:"error",content:"Foreground workflow runs cannot be paused or resumed; only background runs support cooperative pause."}}if(target.status==="pausing"){return{type:"message",messageType:"warning",content:`Workflow ${runId} is still pausing; wait until it reaches paused before resuming.`}}if(target.status==="running"){return registry.pause(runId)?{type:"message",messageType:"info",content:`Cooperative pause requested for workflow ${runId}.`}:{type:"message",messageType:"error",content:`Workflow ${runId} could not be paused because its state changed.`}}if(target.status==="paused"){return registry.resume(runId)?{type:"message",messageType:"info",content:`Resume requested for workflow ${runId}.`}:{type:"message",messageType:"error",content:`Workflow ${runId} could not be resumed because its state changed.`}}return{type:"message",messageType:"error",content:`Workflow ${runId} is ${target.status} and cannot be paused or resumed.`}}if(trimmedArgs.length>0){let target=registry.get(trimmedArgs);let source;if(!target){const snapshot=(await listWorkflowSnapshots(config)).find(s=>s.runId===trimmedArgs);if(snapshot){target=snapshotToTask(snapshot);source={snapshot,file:await confirmedSnapshotFile(config,snapshot.runId)}}}if(!target){return{type:"message",messageType:"error",content:`Unknown workflow runId: ${trimmedArgs}`}}return{type:"message",messageType:"info",content:detailLines(target,Date.now(),source).join("\n")}}const snapshots=await listWorkflowSnapshots(config);const liveRunIds=new Set(allEntries.map(e=>e.runId));const snapshotTasks=snapshots.filter(s=>!liveRunIds.has(s.runId)).map(snapshotToTask);if(allEntries.length===0&&snapshotTasks.length===0){return{type:"message",messageType:"info",content:"No workflow runs recorded yet."}}const now=Date.now();const active=allEntries.filter(e=>isActiveWorkflowStatus(e.status)).sort((a,b)=>a.startTime-b.startTime);const terminal=[...allEntries.filter(e=>!isActiveWorkflowStatus(e.status)),...snapshotTasks].sort((a,b)=>(b.endTime??0)-(a.endTime??0));const lines=[];if(context.executionMode==="interactive"){lines.push(t("Tip: use `/workflows p <runId>` or Background tasks + p to cooperatively pause/resume; use `/workflows <runId>` for details."),"")}lines.push(`Workflow runs (${active.length+terminal.length} total \xB7 ${active.length} active)`,"");if(active.length>0){lines.push("Active");for(const entry of active)lines.push(rowLine(entry,now));lines.push("")}if(terminal.length>0){lines.push("Recent");for(const entry of terminal)lines.push(rowLine(entry,now))}return{type:"message",messageType:"info",content:lines.join("\n")}},"action")};init_esbuild_shims();var agentsCommand={name:"agents",get description(){return t("Manage subagents for specialized task delegation.")},kind:"built-in",supportedModes:["interactive"],subCommands:[{name:"manage",get description(){return t("Manage existing subagents (view, edit, delete).")},kind:"built-in",supportedModes:["interactive"],action:__name(()=>({type:"dialog",dialog:"subagent_list"}),"action")},{name:"create",get description(){return t("Create a new subagent with guided setup.")},kind:"built-in",supportedModes:["interactive"],action:__name(()=>({type:"dialog",dialog:"subagent_create"}),"action")}]};init_esbuild_shims();function parseArenaArgs(args){const modelsMatch=args.match(/--models\s+(\S+)/);let models=[];let task=args;if(modelsMatch){const modelStrings=modelsMatch[1].split(",").filter(Boolean);models=modelStrings.map(str=>{const colonIndex=str.indexOf(":");if(colonIndex>0){return{authType:str.substring(0,colonIndex),modelId:str.substring(colonIndex+1)}}return{modelId:str}});task=task.replace(/--models\s+\S+/,"").trim()}task=task.replace(/^["']|["']$/g,"").trim();return{models,task}}__name(parseArenaArgs,"parseArenaArgs");var debugLogger5=createDebugLogger("ARENA_COMMAND");function buildArenaExecutionInput(parsed,config){if(!parsed.task){return{type:"message",messageType:"error",content:[t("Usage: /arena start --models model1,model2 <task>"),"",t("Options:")," --models [authType:]model1,[authType:]model2",` ${t("Models to compete (required, at least 2)")}`,` ${t("Format: authType:modelId or just modelId")}`,"",t("Examples:"),' /arena start --models openai:gpt-4o,anthropic:claude-3 "implement sorting"',' /arena start --models qwen-coder-plus,kimi-for-coding "fix the bug"'].join("\n")}}if(parsed.models.length<2){return{type:"message",messageType:"error",content:[t("Arena requires at least 2 models. Use --models model1,model2 to specify."),t("Format: [authType:]modelId (e.g., openai:gpt-4o or just gpt-4o)")].join("\n")}}const contentGeneratorConfig=config.getContentGeneratorConfig();const defaultAuthType=contentGeneratorConfig?.authType??"openai";const modelsConfig=config.getModelsConfig();const models=[];for(const parsedModel of parsed.models){const authType=parsedModel.authType??defaultAuthType;const registryModels=modelsConfig.getAvailableModelsForAuthType(authType);const resolved=registryModels.find(m=>m.id===parsedModel.modelId);if(resolved?.imageOnly){return{type:"message",messageType:"error",content:t("Image-only model '{{model}}' cannot be used in an Arena session.",{model:parsedModel.modelId})}}models.push({modelId:parsedModel.modelId,authType,displayName:resolved?.label??parsedModel.modelId})}return{task:parsed.task,models,approvalMode:config.getApprovalMode()}}__name(buildArenaExecutionInput,"buildArenaExecutionInput");function recordArenaItem(config,item){try{const chatRecorder=config.getChatRecordingService();if(!chatRecorder)return;chatRecorder.recordSlashCommand({phase:"result",rawCommand:"/arena",outputHistoryItems:[{...item}]})}catch{debugLogger5.error("Failed to record arena history item")}}__name(recordArenaItem,"recordArenaItem");function executeArenaCommand(config,ui,input){let chatHistory;try{const fullHistory=config.getLlmClient().getChat().getHistoryShallow();chatHistory=stripStartupContext(fullHistory)}catch{debugLogger5.debug("Could not retrieve chat history for arena agents")}const manager=new ArenaManager(config);const emitter=manager.getEventEmitter();const detachListeners=[];const agentLabels=new Map;const addArenaMessage=__name((type,text)=>{ui.addItem({type,text},Date.now())},"addArenaMessage");const addAndRecordArenaMessage=__name((type,text)=>{const item={type,text};ui.addItem(item,Date.now());recordArenaItem(config,item)},"addAndRecordArenaMessage");const handleSessionStart=__name(event=>{const modelList=event.models.map((model,index)=>` ${index+1}. ${model.modelId}`).join("\n");addArenaMessage("info",t('Arena started with {{count}} agents on task: "{{task}}"\nModels:\n{{modelList}}',{count:String(event.models.length),task:event.task,modelList}))},"handleSessionStart");const handleAgentStart=__name(event=>{agentLabels.set(event.agentId,event.model.modelId);debugLogger5.debug(`Arena agent started: ${event.model.modelId} (${event.agentId})`)},"handleAgentStart");const handleSessionUpdate=__name(event=>{const attachHintPrefix="To view agent panes, run: ";if(event.message.startsWith(attachHintPrefix)){const command=event.message.slice(attachHintPrefix.length).trim();addAndRecordArenaMessage("info",t("Arena panes are running in tmux. Attach with: `{{command}}`",{command}));return}if(event.type==="success"){addAndRecordArenaMessage("success",event.message)}else if(event.type==="info"){addAndRecordArenaMessage("info",event.message)}else{addAndRecordArenaMessage("warning",event.message)}},"handleSessionUpdate");const handleAgentError=__name(event=>{const label=agentLabels.get(event.agentId)||event.agentId;addAndRecordArenaMessage("error",t("[{{label}}] failed: {{error}}",{label,error:event.error}))},"handleAgentError");const buildAgentCardData=__name(result=>({label:result.model.modelId,status:result.status,durationMs:result.stats.durationMs,totalTokens:result.stats.totalTokens,inputTokens:result.stats.inputTokens,outputTokens:result.stats.outputTokens,toolCalls:result.stats.toolCalls,successfulToolCalls:result.stats.successfulToolCalls,failedToolCalls:result.stats.failedToolCalls,rounds:result.stats.rounds,error:result.error,diff:result.diff,diffSummary:result.diffSummary,modifiedFiles:result.modifiedFiles,approachSummary:result.approachSummary}),"buildAgentCardData");const handleAgentComplete=__name(event=>{if(!isTerminalStatus(event.result.status)){return}const agent=buildAgentCardData(event.result);const item={type:"arena_agent_complete",agent};ui.addItem(item,Date.now());recordArenaItem(config,item)},"handleAgentComplete");const handleSessionError=__name(event=>{addAndRecordArenaMessage("error",`${event.error}`)},"handleSessionError");const handleSessionComplete=__name(event=>{const item={type:"arena_session_complete",sessionStatus:event.result.status,task:event.result.task,totalDurationMs:event.result.totalDurationMs??0,agents:event.result.agents.map(buildAgentCardData)};ui.addItem(item,Date.now());recordArenaItem(config,item)},"handleSessionComplete");emitter.on("session_start",handleSessionStart);detachListeners.push(()=>emitter.off("session_start",handleSessionStart));emitter.on("agent_start",handleAgentStart);detachListeners.push(()=>emitter.off("agent_start",handleAgentStart));emitter.on("session_update",handleSessionUpdate);detachListeners.push(()=>emitter.off("session_update",handleSessionUpdate));emitter.on("agent_error",handleAgentError);detachListeners.push(()=>emitter.off("agent_error",handleAgentError));emitter.on("agent_complete",handleAgentComplete);detachListeners.push(()=>emitter.off("agent_complete",handleAgentComplete));emitter.on("session_error",handleSessionError);detachListeners.push(()=>emitter.off("session_error",handleSessionError));emitter.on("session_complete",handleSessionComplete);detachListeners.push(()=>emitter.off("session_complete",handleSessionComplete));config.setArenaManager(manager);const cols=process.stdout.columns||120;const rows=Math.max((process.stdout.rows||40)-2,1);const lifecycle=manager.start({task:input.task,models:input.models,cols,rows,approvalMode:input.approvalMode,chatHistory}).then(()=>{debugLogger5.debug("Arena agents settled")},error=>{const message2=error instanceof Error?error.message:String(error);addAndRecordArenaMessage("error",`${message2}`);debugLogger5.error("Arena session failed:",error);config.setArenaManager(null);for(const detach of detachListeners){detach()}});manager.setLifecyclePromise(lifecycle)}__name(executeArenaCommand,"executeArenaCommand");var arenaCommand={name:"arena",get description(){return t("Manage Arena sessions")},kind:"built-in",subCommands:[{name:"start",get description(){return t("Start an Arena session with multiple models competing on the same task")},kind:"built-in",action:__name(async(context,args)=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode. Use interactive mode to start an Arena session.")}}const{services,ui}=context;const{config}=services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const existingManager=config.getArenaManager();if(existingManager){return{type:"message",messageType:"error",content:t("An Arena session exists. Use /arena stop or /arena select to end it before starting a new one.")}}const parsed=parseArenaArgs(args);if(parsed.models.length===0){return{type:"dialog",dialog:"arena_start"}}const executionInput=buildArenaExecutionInput(parsed,config);if("type"in executionInput){return executionInput}executeArenaCommand(config,ui,executionInput)},"action")},{name:"stop",get description(){return t("Stop the current Arena session")},kind:"built-in",action:__name(async context=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode. Use interactive mode to stop an Arena session.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No running Arena session found.")}}return{type:"dialog",dialog:"arena_stop"}},"action")},{name:"status",get description(){return t("Show the current Arena session status")},kind:"built-in",action:__name(async context=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No Arena session found. Start one with /arena start.")}}return{type:"dialog",dialog:"arena_status"}},"action")},{name:"select",altNames:["choose"],get description(){return t("Select a model result and merge its diff into the current workspace")},kind:"built-in",action:__name(async(context,args)=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No Arena session found. Start one with /arena start.")}}const sessionStatus=manager.getSessionStatus();if(sessionStatus==="running"||sessionStatus==="initializing"){return{type:"message",messageType:"error",content:t("Arena session is still running. Wait for it to complete or use /arena stop first.")}}const trimmedArgs=args.trim();if(trimmedArgs==="--discard"){if(!context.overwriteConfirmed){return{type:"confirm_action",prompt:t("Discard all Arena results and clean up worktrees?"),originalInvocation:{raw:context.invocation?.raw||"/arena select --discard"}}}await config.cleanupArenaRuntime(true);return{type:"message",messageType:"info",content:t("Arena results discarded. All worktrees cleaned up.")}}const agents=manager.getAgentStates();const hasSuccessful=agents.some(a=>isSuccessStatus(a.status));if(!hasSuccessful){return{type:"message",messageType:"error",content:[t("No successful agent results to select from. All agents failed or were cancelled."),t("Use /arena stop to end the session.")].join("\n")}}if(trimmedArgs){const matchingAgent=agents.find(a=>isSuccessStatus(a.status)&&a.model.modelId.toLowerCase()===trimmedArgs.toLowerCase());if(!matchingAgent){return{type:"message",messageType:"error",content:t('No idle agent found matching "{{name}}".',{name:trimmedArgs})}}const label=matchingAgent.model.modelId;const result=await manager.applyAgentResult(matchingAgent.agentId);if(!result.success){return{type:"message",messageType:"error",content:t("Failed to apply changes from {{label}}: {{error}}",{label,error:result.error??"Unknown error"})}}await config.cleanupArenaRuntime(true);return{type:"message",messageType:"info",content:t("Applied changes from {{label}} to workspace. Arena session complete.",{label})}}return{type:"dialog",dialog:"arena_select"}},"action")}]};init_esbuild_shims();init_esbuild_shims();function formatApprovalModeName(mode){switch(mode){case"plan":return t("plan mode");case"default":return t("Ask permissions");case"auto-edit":return t("auto-accept edits");case"auto":return t("Auto mode");case"yolo":return t("YOLO mode");default:return mode}}__name(formatApprovalModeName,"formatApprovalModeName");function formatApprovalModeDescription(mode){switch(mode){case"plan":return t("Analyze only, do not modify files or execute commands");case"default":return t("Require approval for file edits or shell commands");case"auto-edit":return t("Automatically approve file edits");case"auto":return t("Use classifier to automatically approve safe tool calls");case"yolo":return t("Automatically approve all tools");default:return mode}}__name(formatApprovalModeDescription,"formatApprovalModeDescription");function parseApprovalModeArg(arg){const trimmed=arg.trim().toLowerCase();if(!trimmed){return void 0}return APPROVAL_MODES.find(mode=>mode.toLowerCase()===trimmed)}__name(parseApprovalModeArg,"parseApprovalModeArg");var approvalModeCommand={name:"approval-mode",get description(){return t("View or change the approval mode for tool usage")},argumentHint:"<mode>",kind:"built-in",supportedModes:["interactive"],action:__name(async(context,args)=>{const mode=parseApprovalModeArg(args);if(!args.trim()){return{type:"dialog",dialog:"approval-mode"}}if(!mode){return{type:"message",messageType:"error",content:t('Invalid approval mode "{{arg}}". Valid modes: {{modes}}',{arg:args.trim(),modes:APPROVAL_MODES.join(", ")})}}const{config,settings}=context.services;let priorMode;if(config){try{priorMode=config.getApprovalMode()}catch(e){return{type:"message",messageType:"error",content:e.message}}}const autoModeNotices=mode==="auto"&&priorMode!=="auto"&&config?await import("./useAutoAcceptIndicator-ELMIP4TJ.js"):void 0;if(config){try{config.setApprovalMode(mode)}catch(e){return{type:"message",messageType:"error",content:e.message}}}if(autoModeNotices&&config){autoModeNotices.emitAutoModeEntryNotices({config,settings,addItem:context.ui.addItem})}return{type:"message",messageType:"info",content:t('Approval mode set to "{{mode}}"',{mode:formatApprovalModeName(mode)})}},"action")};init_esbuild_shims();var authCommand={name:"auth",altNames:["connect","login"],get description(){return t("Connect an LLM provider")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name((context,_args)=>{const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"info",content:t("Authentication configuration is only available in interactive mode. To configure authentication, run Qwen Code interactively and use /auth, or set environment variables: OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_MODEL.")}}return{type:"dialog",dialog:"auth"}},"action")};init_esbuild_shims();var branchCommand={name:"branch",kind:"built-in",get description(){return t("Fork the current conversation into a new session")},action:__name(async(context,args)=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Config is not available.")}}if(context.ui.isIdleRef?.current===false){return{type:"message",messageType:"error",content:t("Cannot branch while a response or tool call is in progress. Wait for it to finish or resolve the pending tool call.")}}const sessionService=config.getSessionService();const currentId=config.getSessionId();const hasRecords=await sessionService.sessionExists(currentId);if(!hasRecords){return{type:"message",messageType:"error",content:t("No conversation to branch.")}}const name=args.trim().replace(/[\r\n]+/g," ");return name?{type:"dialog",dialog:"branch",name}:{type:"dialog",dialog:"branch"}},"action")};init_esbuild_shims();function shortId(msgId){return msgId.replace(/-/g,"").slice(0,6)}__name(shortId,"shortId");function displayHandle(entry,held){const own=canonicalizeMsgId(entry.frame.msgId);let length=Math.min(shortId(entry.frame.msgId).length,own.length);const collides=__name(len=>held.some(other=>other!==entry&&canonicalizeMsgId(other.frame.msgId).startsWith(own.slice(0,len))),"collides");while(length<own.length&&collides(length)){length+=1}return own.slice(0,length)}__name(displayHandle,"displayHandle");function preview(text,max=100){const oneLine=flattenPeerLabel(text).replace(/\s+/g," ").trim();return oneLine.length>max?`${oneLine.slice(0,max-1)}\u2026`:oneLine}__name(preview,"preview");function describeRemaining(entry,expiryMs){if(expiryMs===null)return"";const wallAge=Date.now()-entry.heldAt;const age=entry.monotonicAt===void 0?wallAge:Math.max(wallAge,performance.now()-entry.monotonicAt);const remaining=expiryMs-age;if(remaining<=0)return", expiring now";const minutes=Math.ceil(remaining/6e4);return remaining<6e4?", less than a minute left":`, ${minutes} minute${minutes===1?"":"s"} left`}__name(describeRemaining,"describeRemaining");function formatHeldList(held,expiryFor=()=>null){if(held.length===0)return"No messages from other sessions are waiting.";const lines=held.map(entry=>{const peerLabel=entry.controller?flattenPeerLabel(entry.controller.label):flattenPeerLabel(entry.frame.fromName??entry.frame.from??(entry.selfSent?"this session":"unknown session"));const origin=entry.controller?"[controller]":entry.selfSent?"[own process]":"[peer]";const who=`${origin} ${peerLabel}`;const handle=flattenPeerLabel(displayHandle(entry,held));return` ${handle} ${who}
|
|
3
|
+
import{ExtensionRefreshState}from"./chunk-254YDSL2.js";import{billableOutputTokens,calculateCost,commandRestrictionNames,computeGenerationRates,computeSessionStats,diffCommand,extensionOwnerLabel,filterCommandsForMode,findInlineMathExpressions,formatCompressionTokenCount,formatDuration,formatTokenCount,getCompressionFailureStatusText,getSystemInfoFields,skillOriginLabel}from"./chunk-7VP4KALB.js";import{isKittyProtocolEnabled}from"./chunk-HKA2IEQ6.js";import{VSCODE_SHIFT_ENTER_SEQUENCE,isWaylandSession,writeOsc52}from"./chunk-K7VOBDFT.js";import{contextCommand}from"./chunk-P5543CFV.js";import{getInteractiveModSession}from"./chunk-AE6E2YKY.js";import{themeManager}from"./chunk-GXNGLDUN.js";import{validateAuthMethod}from"./chunk-VBJV7T47.js";import{clearSkillArgs,skillArgsNote,skillArgsPath,staleArgsWarning,writeSkillArgs}from"./chunk-JEC6WHFT.js";import{GITHUB_WORKFLOW_PATHS,INSIGHT_CSS,INSIGHT_JS,collectSessionData,extractInjections,generateExportFilename,normalizeSessionData,setupGithub,toHtml,toJson,toJsonl,toMarkdown}from"./chunk-SOCXRMZM.js";import{appEvents,checkAdvisorModelAvailability,isAdvisorModelEligible,resolveHookSettingsForConfig}from"./chunk-MMGNOY3U.js";import{MarkdownCommandDefSchema,parseMarkdownCommand}from"./chunk-ZLUQTFP3.js";import{formatUnsupportedVoiceModelMessage,getVoiceSettingsScope,isSelectableVoiceModel,isVoiceEnabled,readVoiceMode,readVoiceModel}from"./chunk-FS67DOZQ.js";import{applyProjectHooksApproval,getProjectHooksForApproval}from"./chunk-GY4ID3EB.js";import{stripUnsafeCharacters,toCodePoints,truncateToWidth}from"./chunk-64CA3W6G.js";import{rollbackStandaloneUpdate}from"./chunk-RWFOQXPU.js";import{getExtendedSystemInfo,getGitVersion,getNpmVersion}from"./chunk-BSLIVO6O.js";import{getReasoningEffortsForConfig}from"./chunk-JQOLNQQN.js";import{formatAuxModelSelectorForDisplay}from"./chunk-L42NTHIT.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{getInstallationInfo}from"./chunk-GOZ5FAUV.js";import{SERVE_CONTROL_EXT_METHODS,SERVE_STATUS_EXT_METHODS}from"./chunk-YCAEGUZI.js";import{getErrorMessage as getErrorMessage2}from"./chunk-4KIFAVR2.js";import{OUTPUT_LANGUAGE_AUTO,getAllSettingKeys,getDefaultValue,getFlattenedSchema,getNestedProperty,getPersistScopeForModelSelection,getSettingDefinition,isAutoLanguage,nextBooleanSettingValue,resolveOutputLanguageOrPreserveAuto,validateSettingValue,writeOutputLanguageAndRegisterPath}from"./chunk-23543L6E.js";import{getCurrentLanguage,setLanguageAsync,t}from"./chunk-FK5L2WVV.js";import{SUPPORTED_LANGUAGES,getSupportedLanguageIds,resolveSupportedLanguage}from"./chunk-UWMLSAQY.js";import{ACP_ROUTE_ID_PREFIX,isInlineModelOverrideAllowed,parseAcpModelOption,resolveAcpFastModelSelector}from"./chunk-YQXX44YA.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-EKRCICRK.js";import{isFolderTrustEnabled,loadTrustedFolders}from"./chunk-WZTO3EYG.js";import{BTW_MAX_INPUT_LENGTH,Logger,analyzeToolResultRetention,buildBtwCacheSafeParams,buildLearnSkillPrompt,buildLearnVideoSkillRequest,describePeerInboxFailure,encodeInsightErrorMessage,encodeInsightProgressMessage,encodeInsightReadyMessage,findOutputStyle,generateSessionRecap,getBtwSession,getIdeInstaller,getLastPeerInboxFailure,getMCPServerPrompts,isWsl,listPeerControllers,loadOutputStyleCatalog,parseLearnVideoInput,readPathFromWorkspace,removePeerController}from"./chunk-3MBYQYPC.js";import{canonicalizeMsgId,describeHoldCause}from"./chunk-UNDRWCST.js";import{buildBareRememberPrompt,buildManagedRememberPrompt}from"./chunk-KK6SQPYG.js";import{MAX_WORKFLOW_RESULT_PREVIEW_CHARS,buildWorkflowResultPreview,listWorkflowSnapshots,readWorkflowSnapshot}from"./chunk-TWJ4XBED.js";import{toCanonicalWorkspaceArtifactPath}from"./chunk-4WMR7RZB.js";import{executeModTool,modToolRequest}from"./chunk-ZOWMHZWO.js";import{resolveOpenAILogDir}from"./chunk-MSAAQ2I7.js";import{ArenaManager,ConditionalRulesRegistry,CoreToolScheduler,EXTENSIONS_CONFIG_FILENAME,ExtensionManager,GoalPersistenceUnavailableError,IdeClient,MAX_FAILURE_LINE_CHARS,QWEN_CODE_COMPANION_EXTENSION_NAME,REPORTED_FAILURE_KEYS,SESSION_TITLE_MAX_LENGTH,SessionService,appendAutoMemoryContext,appendToLastTextPart,buildBackgroundEntryLabel,buildFailureLines,collectMemoryDiagnostics,executeRuntimeShell,fetchPullRequestByReference,flatMapTextParts,getExtensionDescription,getExtensionDisplayName,getLastApiHistoryPromptId,getToolCallFingerprint,hookEventSupportsMatcher,ideContextStore,isActiveWorkflowStatus,isCompressionFailureStatus,isExtensionCommittedWithWarningsError,isSuccessStatus,isTerminalStatus,isTerminalWorkflowStatus,isValidSessionPrUrl,isWorkflowRunId,listSavedWorkflows,loadServerHierarchicalMemory,normalizeClaudeMcpServer,parseInstallSource,partToString,persistSessionUsage,pullRequestViewUrl,readSessionPrsDetailed,reportedFailureLines,require_toml,runForkedAgent,sanitizeWorkflowText,truncateWorkflowText,tryGenerateSessionTitle,upsertSessionPrs,withoutAutoMemorySnapshots}from"./chunk-PFKTTUGS.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{external_exports}from"./chunk-KZSUHQLD.js";import{canUseRipgrep}from"./chunk-HA7ADBWO.js";import{GitWorktreeService}from"./chunk-I44IFX3I.js";import{openBrowserSecurely}from"./chunk-UJSVTVKB.js";import{isInternalCodeModeToolResult,projectUserTranscriptForDisplay}from"./chunk-UHJUDWBV.js";import{normalizeSkillPriority}from"./chunk-DNYXZVBT.js";import{flattenPeerLabel}from"./chunk-VMRQ6FA2.js";import{getAutoSkillCuratorStatus,recordAutoSkillUsage,restoreArchivedAutoSkill,runAutoSkillCurator,setAutoSkillPinned}from"./chunk-NVXFGZ4Z.js";import{GOAL_PAUSE_REASON_COMMAND,emptyGoalSnapshot}from"./chunk-7Z2ZH5CW.js";import{resolveModelId}from"./chunk-QTJPOTU5.js";import{Ns}from"./chunk-TASTRW4D.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{isMediaPolicyToolHiddenFromModel}from"./chunk-S2ZKZXHX.js";import{BUILT_IN_OUTPUT_STYLES,getArenaSystemReminder,getInsightPrompt,getPlanModeSystemReminder,getProjectSummaryPrompt,isSystemMdActive,resolveMainSessionOutputStyle}from"./chunk-KVSDMMDD.js";import{isSignalTermination}from"./chunk-QTCO5I4C.js";import{escapeJsonTagCharacters,formatMemoryUsage}from"./chunk-NTRFETZB.js";import{captureHookExecutionOwner,runWithHookExecutionOwner}from"./chunk-KP77CL5U.js";import{COMBINED_PASS_TOLERANCE_FACTOR,IdeConnectionEvent,formatTokenUsageSummaryAsCsv,formatTokenUsageSummaryAsJson,getMCPServerStatus,isImageCapable,logIdeConnection,queryTokenUsage,recordSkillInvocation,uiTelemetryService}from"./chunk-MJEL7DIE.js";import{read}from"./chunk-KNXXVHVG.js";import{getAutoMemoryRoot}from"./chunk-CQGP2BAW.js";import{runSideQuery}from"./chunk-FCQWRGW5.js";import{getCurrentMemoryFilename}from"./chunk-6JHMYZNS.js";import{atomicWriteFileSync}from"./chunk-2GF3E5MI.js";import{buildRuntimeSnapshotId,findProviderByCredentials,isImageGenerationCapable,stripRuntimeSnapshotPrefix}from"./chunk-AJ75BPTA.js";import{REASONING_EFFORT_TIERS,applyReasoningEffort,normalizeReasoningEffort}from"./chunk-EV2CXPMN.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{redactUrlCredentials}from"./chunk-JJAEIBSV.js";import{AuthType}from"./chunk-EW6HVTD5.js";import{isCpuProfileRecording,startCpuProfile,stopCpuProfile}from"./chunk-USR2Y7B3.js";import{FORK_SUBAGENT_TYPE,getApiHistoryPromptId,markApiHistoryPrompt,stripStartupContext}from"./chunk-DMM5LJWL.js";import{applySkillSideEffects,buildSkillLlmContent}from"./chunk-ZQMVXHGH.js";import{HookEventName,sanitizeUserPromptExpansionAdditionalContext}from"./chunk-4WFJ5OPA.js";import{checkArgumentSafety,checkCommandPermissions,escapeShellArg,getShellConfiguration}from"./chunk-Y2OCBVI6.js";import{isShellProgressData}from"./chunk-D6CEQ2GY.js";import{ToolDisplayNamesMigration,ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger,updateSymlink}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{expandHomeDir,isSubpath,resolvePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";init_esbuild_shims();var MAX_STACKED_SKILLS=5;var isStackedSkillCompletableCommand=__name(command=>command.kind==="skill"&&command.userInvocable!==false&&!command.hidden,"isStackedSkillCompletableCommand");var isValidStackedSkillPrefix=__name((prefix,commands)=>{const trimmed=prefix.trim();if(!trimmed)return false;const tokens=trimmed.split(/\s+/);if(tokens.length>=MAX_STACKED_SKILLS)return false;return tokens.every(token=>{if(!token.startsWith("/"))return false;const command=findCommandByName(token.slice(1),commands);return command!==void 0&&isStackedSkillCompletableCommand(command)})},"isValidStackedSkillPrefix");var parseSlashCommand=__name((query,commands)=>{const trimmed=query.trim();const commandText=trimmed.substring(1).trim();const parts=commandText.split(/\s+/);const commandPath=parts.filter(p=>p);let currentCommands=commands;let commandToExecute;let pathIndex=0;const canonicalPath=[];let argsStart=0;for(const part of commandPath){let foundCommand=currentCommands.find(cmd=>cmd.name===part);if(!foundCommand){foundCommand=currentCommands.find(cmd=>cmd.altNames?.includes(part))}if(foundCommand){commandToExecute=foundCommand;canonicalPath.push(foundCommand.name);pathIndex++;const partIndex=commandText.indexOf(part,argsStart);argsStart=partIndex+part.length;if(foundCommand.subCommands){currentCommands=foundCommand.subCommands}else{break}}else{break}}const args=commandToExecute?commandText.slice(argsStart).trim():parts.slice(pathIndex).join(" ");return{commandToExecute,args,canonicalPath}},"parseSlashCommand");var parseStackedSlashCommands=__name((query,commands)=>{const trimmed=query.trim();if(!trimmed.startsWith("/")){return{skills:[],remainingText:trimmed,exceededMax:false}}const commandText=trimmed.substring(1);const skills=[];let pos=0;let restPos=0;let exceededMax=false;while(pos<commandText.length){while(pos<commandText.length&&/\s/.test(commandText[pos]))pos++;if(pos>=commandText.length){restPos=pos;break}const tokenStart=pos;while(pos<commandText.length&&!/\s/.test(commandText[pos]))pos++;const token=commandText.slice(tokenStart,pos);if(skills.length===0){if(token.startsWith("/"))break;const cmd2=findCommandByName(token,commands);if(!cmd2||cmd2.kind!=="skill")break;skills.push(cmd2);restPos=pos;continue}if(!token.startsWith("/"))break;const name=token.substring(1);if(!name)break;const cmd=findCommandByName(name,commands);if(!cmd||cmd.kind!=="skill")break;if(skills.length>=MAX_STACKED_SKILLS){exceededMax=true;break}skills.push(cmd);restPos=pos}if(skills.length<2){return{skills:[],remainingText:trimmed,exceededMax:false}}const afterSkills=commandText.slice(restPos).trim();return{skills,remainingText:afterSkills,exceededMax}},"parseStackedSlashCommands");function findCommandByName(name,commands){return commands.find(cmd=>cmd.name===name)??commands.find(cmd=>cmd.altNames?.includes(name))}__name(findCommandByName,"findCommandByName");var CONTEXT_FILES_ANNOUNCEMENT_PREFIX="Read context files:";function isContextFilesAnnouncement(item){return item.type==="info"&&typeof item.text==="string"&&item.text.startsWith(CONTEXT_FILES_ANNOUNCEMENT_PREFIX)}__name(isContextFilesAnnouncement,"isContextFilesAnnouncement");var CodePage={UTF8:65001,GBK:936,BIG5:950,LATIN1:1252};var isAtCommand=__name(query=>query.startsWith("@")||/\s@/.test(query),"isAtCommand");var SLASH_PATH_SEPARATOR_RE=/[/\\]/;var SLASH_COMMANDS_SKIP_RECORDING=new Set(["quit","exit","clear","reset","new","resume","delete","branch","btw","history"]);var getSlashCommandFirstToken=__name(query=>query.slice(1).trimStart().split(/\s+/u)[0]??"","getSlashCommandFirstToken");var hasSlashCommandPathSeparator=__name(query=>SLASH_PATH_SEPARATOR_RE.test(getSlashCommandFirstToken(query)),"hasSlashCommandPathSeparator");var isSlashCommand=__name(query=>{if(!query.startsWith("/")){return false}if(query.startsWith("//")){return false}if(query.startsWith("/*")){return false}if(hasSlashCommandPathSeparator(query)){return false}return true},"isSlashCommand");var BTW_COMMAND_RE=/^[/?]btw(?:\s|$)/;var isBtwCommand=__name(query=>{const trimmed=query.trim();return trimmed.length>0&&BTW_COMMAND_RE.test(trimmed)},"isBtwCommand");function consumesContextAnnouncementLatch(trimmedPrompt,options){if(trimmedPrompt.length===0){return false}if(/^\/btw(?:\s|$)/.test(trimmedPrompt)){return false}if(isSlashCommand(trimmedPrompt)){return parseSlashCommand(trimmedPrompt,options.slashCommands).commandToExecute?.modelInvocable===true}if(options.shellModeActive){return false}return true}__name(consumesContextAnnouncementLatch,"consumesContextAnnouncementLatch");var debugLogger=createDebugLogger("COMMAND_UTILS");var formatCommandFailure=__name((error,command)=>error instanceof Error&&error.code==="ENOENT"?`${command} not found`:error instanceof Error?error.message:String(error),"formatCommandFailure");var copyToClipboard=__name(async text=>{let wlCopyError;const run=__name((cmd,args,options)=>new Promise((resolve4,reject)=>{const child=options?spawn(cmd,args,options):spawn(cmd,args);let stderr="";if(child.stderr){child.stderr.on("data",chunk=>stderr+=chunk.toString())}child.on("error",reject);child.on("close",code=>{if(code===0)return resolve4();const errorMsg=stderr.trim();reject(new Error(`'${cmd}' exited with code ${code}${errorMsg?`: ${errorMsg}`:""}`))});if(child.stdin){child.stdin.on("error",reject);child.stdin.write(text);child.stdin.end()}else{reject(new Error("Child process has no stdin stream to write to."))}}),"run");const linuxOptions={stdio:["pipe","inherit","pipe"]};switch(process.platform){case"win32":return run("cmd",["/c",`chcp ${CodePage.UTF8} >nul && clip`]);case"darwin":return run("pbcopy",[]);case"linux":if(isWaylandSession()){try{await run("wl-copy",["-t","text/plain"],{stdio:["pipe","inherit","ignore"]});return}catch(error){wlCopyError=error;debugLogger.debug("wl-copy failed; falling back to other clipboard methods:",error)}}try{await run("xclip",["-selection","clipboard"],linuxOptions)}catch(primaryError){try{await run("xsel",["--clipboard","--input"],linuxOptions)}catch(fallbackError){const xclipNotFound=primaryError instanceof Error&&primaryError.code==="ENOENT";const xselNotFound=fallbackError instanceof Error&&fallbackError.code==="ENOENT";const wlCopyFailure=wlCopyError===void 0?"":`wl-copy failed ("${formatCommandFailure(wlCopyError,"wl-copy")}"); `;if(xclipNotFound&&xselNotFound){if(!writeOsc52(text)){throw new Error(`Clipboard unavailable: ${wlCopyFailure}xclip/xsel not found and OSC 52 requires a TTY. Try running inside a terminal emulator.`)}return}const primaryMsg=formatCommandFailure(primaryError,"xclip");const fallbackMsg=formatCommandFailure(fallbackError,"xsel");if(writeOsc52(text))return;throw new Error(`Clipboard unavailable: ${wlCopyFailure}xclip/xsel failed ("${primaryMsg}", "${fallbackMsg}") and OSC 52 requires a TTY. Try running inside a terminal emulator.`)}}return;default:throw new Error(`Unsupported platform: ${process.platform}`)}},"copyToClipboard");var getUrlOpenCommand=__name(()=>{let openCmd;switch(process.platform){case"darwin":openCmd="open";break;case"win32":openCmd="start";break;case"linux":openCmd="xdg-open";break;default:openCmd="xdg-open";debugLogger.warn(`Unknown platform: ${process.platform}. Attempting to open URLs with: ${openCmd}.`);break}return openCmd},"getUrlOpenCommand");function isMidInputCompletableCommand(cmd){return cmd.modelInvocable===true&&!cmd.hidden}__name(isMidInputCompletableCommand,"isMidInputCompletableCommand");function findMidInputSlashCommand(input,cursorOffset){const codePoints=toCodePoints(input);const beforeCursor=codePoints.slice(0,cursorOffset).join("");const match=beforeCursor.match(/\s\/([a-zA-Z0-9_:-]*)$/);if(!match)return null;const partialCommand=match[1];const slashPos=cursorOffset-1-partialCommand.length;const textAfterSlash=codePoints.slice(slashPos+1).join("");const commandMatch=textAfterSlash.match(/^[a-zA-Z0-9_:-]*/);const fullCommand=commandMatch?commandMatch[0]:"";if(cursorOffset!==slashPos+1+fullCommand.length)return null;return{token:"/"+fullCommand,startPos:slashPos,partialCommand}}__name(findMidInputSlashCommand,"findMidInputSlashCommand");function getBestSlashCommandMatch(partialCommand,commands,recentCommands){if(!partialCommand)return null;const query=partialCommand.toLowerCase();const matches=commands.filter(cmd=>{if(!isMidInputCompletableCommand(cmd))return false;const name=cmd.name.toLowerCase();return name.startsWith(query)&&(name!==query||!!cmd.argumentHint)}).sort((left,right)=>{const leftRecent=recentCommands?.get(left.name);const rightRecent=recentCommands?.get(right.name);const recentOrder=(rightRecent?.usedAt??0)-(leftRecent?.usedAt??0);return(right.completionPriority??0)-(left.completionPriority??0)||recentOrder||left.name.localeCompare(right.name)});const best=matches[0];if(!best)return null;return{suffix:best.name.slice(partialCommand.length),fullCommand:best.name,command:best,argumentHint:best.argumentHint}}__name(getBestSlashCommandMatch,"getBestSlashCommandMatch");var SLASH_TOKEN_RE=/(?:^|(?<=\s))\/([a-zA-Z][a-zA-Z0-9:_-]*)/g;function findSlashCommandTokens(text,commands){if(!text)return[];const commandMapEntries=[];for(const cmd of commands){commandMapEntries.push([cmd.name.toLowerCase(),cmd]);for(const altName of cmd.altNames??[]){commandMapEntries.push([altName.toLowerCase(),cmd])}}const commandMap=new Map(commandMapEntries);const tokens=[];let match;SLASH_TOKEN_RE.lastIndex=0;while((match=SLASH_TOKEN_RE.exec(text))!==null){const fullMatch=match[0];const commandName=match[1];const start=match.index;const end=start+fullMatch.length;const precedingChar=start>0?text[start-1]:null;const isLineStart=start===0||precedingChar==="\n";const cmd=commandMap.get(commandName.toLowerCase());let valid=false;if(cmd){if(isLineStart){valid=cmd.userInvocable!==false&&!cmd.hidden}else{const prefix=text.slice(0,start);valid=cmd.modelInvocable===true||isStackedSkillCompletableCommand(cmd)&&isValidStackedSkillPrefix(prefix,commands)}}tokens.push({start,end,commandName,valid})}return tokens}__name(findSlashCommandTokens,"findSlashCommandTokens");init_esbuild_shims();function formatBtwToolCallNotice(toolName){return t("(The model tried to call {{tool}} instead of answering directly. Try rephrasing or ask in the main conversation.)",{tool:toolName})}__name(formatBtwToolCallNotice,"formatBtwToolCallNotice");var NOTICE_MS=2e3;var activeView=null;function showBtwRequest(ui,session,requestId){activeView?.detach();const controller=new AbortController;const view={ui,session,requestId,browseId:null,shortcuts:false,detach:__name(()=>{unsubscribe();controller.signal.removeEventListener("abort",onAbort);clearTimeout(view.noticeTimer);clearTimeout(view.retryTimer);if(activeView===view)activeView=null},"detach")};const onAbort=__name(()=>{view.detach();session.abort(requestId)},"onAbort");controller.signal.addEventListener("abort",onAbort);const unsubscribe=session.subscribe(()=>render(view));ui.btwAbortControllerRef.current=controller;activeView=view;render(view)}__name(showBtwRequest,"showBtwRequest");function handleBtwViewKey(key){const view=activeView;if(!view)return false;if(key.ctrl||key.meta||key.paste){exitBrowseMode(view);return false}if(key.name==="left"||key.name==="right"){return browseBtwHistory(key.name==="left"?"older":"newer")}if(view.shortcuts){if(key.sequence==="c"&©BtwAnswer())return true;if(key.sequence==="x"&&clearBtwHistory())return true}if(key.name==="return"||key.sequence===" "){const ownRequest=view.session.getRequest(view.requestId);if(ownRequest?.outcome===null||project(view)?.isPending!==false){exitBrowseMode(view);return false}dismissBtwView();return true}exitBrowseMode(view);return false}__name(handleBtwViewKey,"handleBtwViewKey");function dismissBtwView(){const view=activeView;if(!view)return;view.detach();view.ui.btwAbortControllerRef.current=null;view.ui.setBtwItem(null)}__name(dismissBtwView,"dismissBtwView");function browseBtwHistory(direction){const view=activeView;if(!view)return false;const exchanges=browsableExchanges(view);const count=exchanges.length;if(count===0)return false;const current=exchanges.findIndex(exchange=>exchange.id===view.browseId);if(direction==="older"){view.browseId=current===-1?exchanges[count-1].id:exchanges[Math.max(0,current-1)].id}else if(view.browseId!==null){view.browseId=current===-1||current>=count-1?null:exchanges[current+1].id}view.shortcuts=true;render(view);return true}__name(browseBtwHistory,"browseBtwHistory");function clearBtwHistory(){const view=activeView;if(!view)return false;const ids=browsableExchanges(view).map(exchange=>exchange.id);if(ids.length===0)return false;view.browseId=null;view.session.removeExchanges(ids);return true}__name(clearBtwHistory,"clearBtwHistory");function copyBtwAnswer(copy=copyToClipboard){const view=activeView;if(!view)return false;const displayed=project(view);if(!displayed||displayed.isPending||displayed.isError)return false;void copy(displayed.answer).then(()=>setNotice(view,{text:t("Copied to clipboard")}),()=>setNotice(view,{text:t("Copy failed"),isError:true}));return true}__name(copyBtwAnswer,"copyBtwAnswer");function exitBrowseMode(view){if(!view.shortcuts)return;view.shortcuts=false;render(view)}__name(exitBrowseMode,"exitBrowseMode");function setNotice(view,notice){if(activeView!==view)return;clearTimeout(view.noticeTimer);view.notice=notice;render(view);view.noticeTimer=setTimeout(()=>{view.notice=void 0;render(view)},NOTICE_MS)}__name(setNotice,"setNotice");function browsableExchanges(view){return view.session.getSnapshot().exchanges.filter(exchange=>exchange.id!==view.requestId)}__name(browsableExchanges,"browsableExchanges");function render(view){if(activeView!==view)return;const btw=project(view);if(!btw){view.detach();view.ui.btwAbortControllerRef.current=null;view.ui.setBtwItem(null);return}clearTimeout(view.retryTimer);if(btw.retryStatus){view.retryTimer=setTimeout(()=>render(view),1e3)}view.ui.setBtwItem({type:"btw",btw})}__name(render,"render");function project(view){const exchanges=browsableExchanges(view);const ownRequestPending=view.session.getRequest(view.requestId)?.outcome===null;const common={historyCount:exchanges.length,...view.shortcuts?{browsing:true}:{},...ownRequestPending?{ownRequestPending:true}:{},...view.notice?{notice:view.notice}:{}};if(view.browseId!==null){const index=exchanges.findIndex(exchange2=>exchange2.id===view.browseId);if(index!==-1){const exchange2=exchanges[index];return{...common,question:exchange2.question,answer:exchange2.response,isPending:false,browsePosition:index+1}}view.browseId=null}const request=view.session.getRequest(view.requestId);if(request)return projectRequest(request,common);const exchange=view.session.getSnapshot().exchanges.find(entry=>entry.id===view.requestId);return exchange?{...common,question:exchange.question,answer:exchange.response,isPending:false}:null}__name(project,"project");function projectRequest(request,common){const base={...common,question:request.question};const outcome=request.outcome;if(!outcome){return{...base,answer:request.streamingText,isPending:true,...request.retry?{retryStatus:formatRetry(request.retry)}:{}}}switch(outcome.kind){case"answered":return{...base,answer:outcome.response,isPending:false};case"tool-call":return{...base,answer:formatBtwToolCallNotice(outcome.toolName),isPending:false};case"empty":return{...base,answer:t("No response received."),isPending:false};case"unavailable":return{...base,answer:t("No conversation context available for /btw"),isPending:false,isError:true};case"failed":return{...base,answer:t("(API error: {{error}})",{error:outcome.error}),isPending:false,isError:true};case"cancelled":return null;default:return null}}__name(projectRequest,"projectRequest");function formatRetry(retry){const seconds=Math.max(0,Math.ceil((retry.retryAt-Date.now())/1e3));return t("{{reason}} \xB7 retrying in {{seconds}}s \xB7 attempt {{attempt}}/{{max}}",{reason:retry.message?.split("\n")[0]||t("API error"),seconds:String(seconds),attempt:String(retry.attempt),max:String(retry.maxRetries)})}__name(formatRetry,"formatRetry");init_esbuild_shims();import{isDeepStrictEqual}from"node:util";function isCrossSessionMessagingEnabled(settings){const value=settings?.agents?.crossSessionMessaging;return value===void 0||value===true}__name(isCrossSessionMessagingEnabled,"isCrossSessionMessagingEnabled");function crossSessionMessagingSuppression(config){if(config?.isSafeMode?.()===true)return"safe-mode";if(config?.getBareMode?.()===true)return"bare";return void 0}__name(crossSessionMessagingSuppression,"crossSessionMessagingSuppression");function isCrossSessionMessagingActive(settings,config){return isCrossSessionMessagingEnabled(settings)&&crossSessionMessagingSuppression(config)===void 0}__name(isCrossSessionMessagingActive,"isCrossSessionMessagingActive");function switchIn(file){return file?.settings.agents?.crossSessionMessaging}__name(switchIn,"switchIn");function workspaceCounts(settings){return settings.isTrusted===true&&settings.workspaceSettingsActive===true}__name(workspaceCounts,"workspaceCounts");function isCrossSessionMessagingOptedIn(settings){if(switchIn(settings.user)===true)return true;return workspaceCounts(settings)&&switchIn(settings.workspace)===true}__name(isCrossSessionMessagingOptedIn,"isCrossSessionMessagingOptedIn");function crossSessionMessagingOffScope(settings){if(isCrossSessionMessagingEnabled(settings.merged))return void 0;const merged=settings.merged.agents?.crossSessionMessaging;if(switchIn(settings.system)!==void 0)return"system";if(isDeepStrictEqual(switchIn(settings.user),merged))return"user";if(isDeepStrictEqual(switchIn(settings.systemDefaults),merged)){return"system-defaults"}if(workspaceCounts(settings)&&isDeepStrictEqual(switchIn(settings.workspace),merged)){return"workspace"}return void 0}__name(crossSessionMessagingOffScope,"crossSessionMessagingOffScope");init_esbuild_shims();var debugLogger2=createDebugLogger("SESSION_MODEL");var AUTH_TYPES=new Set(Object.values(AuthType));function isAuthType(value){return AUTH_TYPES.has(value)}__name(isAuthType,"isAuthType");function registryHonoredBaseUrl(config,authType,modelId,baseUrl){if(typeof baseUrl!=="string"||!baseUrl){return void 0}return config.getResolvedModelConfig?.(authType,modelId,baseUrl)?baseUrl:void 0}__name(registryHonoredBaseUrl,"registryHonoredBaseUrl");async function recordDaemonSessionModel(config,payload){const recording=config.getChatRecordingService?.();if(!recording?.recordSessionModel)return;try{await recording.recordSessionModel(payload)}catch(error){debugLogger2.debug("recordSessionModel failed",error)}}__name(recordDaemonSessionModel,"recordDaemonSessionModel");async function recordDaemonSessionModelFromConfig(config){const modelId=config.getModel()?.trim();const authType=config.getAuthType();if(!modelId||!authType)return;const snapshot=config.getActiveRuntimeModelSnapshot?.();const registryBaseUrl=snapshot?void 0:config.getCurrentModelRegistryBaseUrl?.();await recordDaemonSessionModel(config,{modelId,authType,...typeof registryBaseUrl==="string"?{baseUrl:registryBaseUrl}:{},...snapshot?{isRuntime:true}:{}})}__name(recordDaemonSessionModelFromConfig,"recordDaemonSessionModelFromConfig");function hasMatchingRuntimeSnapshot(config,authType,modelId){const snapshot=config.getActiveRuntimeModelSnapshot?.();return snapshot?.authType===authType&&snapshot.modelId===modelId}__name(hasMatchingRuntimeSnapshot,"hasMatchingRuntimeSnapshot");function liveAuthType(config){return config.getAuthType()??config.getModelsConfig?.()?.getCurrentAuthType?.()}__name(liveAuthType,"liveAuthType");function runtimeSnapshotIdentity(snapshot){if(!snapshot)return void 0;if(typeof snapshot.id==="string"&&snapshot.id){return snapshot.id}if(snapshot.authType&&snapshot.modelId){return buildRuntimeSnapshotId(snapshot.authType,snapshot.modelId)}return void 0}__name(runtimeSnapshotIdentity,"runtimeSnapshotIdentity");function recordedRouteMatches(recorded,currentRegistryBaseUrl){if(!recorded||recorded.isRuntime)return true;const targetBaseUrl=recorded.baseUrl;if(targetBaseUrl===void 0){return currentRegistryBaseUrl===null||currentRegistryBaseUrl===void 0}if(targetBaseUrl===""){return currentRegistryBaseUrl===null||currentRegistryBaseUrl===void 0||currentRegistryBaseUrl===""}return currentRegistryBaseUrl===targetBaseUrl}__name(recordedRouteMatches,"recordedRouteMatches");async function applyRestoredSessionModel(config,projection){const recorded=projection?.runtime.recording.sessionModel;const fallbackModel=projection?.runtime.recording.lastAssistantModel;const recordedAuth=recorded?.authType?.trim();const authType=(recordedAuth&&isAuthType(recordedAuth)?recordedAuth:liveAuthType(config))?.trim();const modelId=recorded?.modelId||fallbackModel;if(!modelId?.trim()||!authType||!isAuthType(authType))return;const currentModel=stripRuntimeSnapshotPrefix(config.getModel()??"");const currentAuth=liveAuthType(config);const targetModel=stripRuntimeSnapshotPrefix(modelId.trim());const targetBaseUrl=recorded?.isRuntime?void 0:registryHonoredBaseUrl(config,authType,targetModel,recorded?.baseUrl);const recordedRoute=recorded?{...recorded,...targetBaseUrl?{baseUrl:targetBaseUrl}:{baseUrl:void 0}}:void 0;const currentRegistryBaseUrl=config.getCurrentModelRegistryBaseUrl?.();const baseUrlMatches=recordedRouteMatches(recordedRoute,currentRegistryBaseUrl);const currentRuntimeMatches=hasMatchingRuntimeSnapshot(config,authType,targetModel);if(currentModel===targetModel&¤tAuth===authType&&baseUrlMatches&&!(recorded&&!recorded.isRuntime&¤tRuntimeMatches)){return}const useRuntimeSnapshot=Boolean(recorded?.isRuntime)&&hasMatchingRuntimeSnapshot(config,authType,targetModel);const switchModelId=useRuntimeSnapshot?buildRuntimeSnapshotId(authType,targetModel):targetModel;const requireCachedCredentials=authType==="qwen-oauth"&¤tAuth!==authType;const switchOptions=targetBaseUrl||requireCachedCredentials?{...targetBaseUrl?{baseUrl:targetBaseUrl}:{},...requireCachedCredentials?{requireCachedCredentials:true}:{}}:void 0;try{await config.switchModel(authType,switchModelId,switchOptions)}catch(error){debugLogger2.warn(`restore session model failed (${targetModel}/${authType}): ${error instanceof Error?error.message:String(error)}`)}}__name(applyRestoredSessionModel,"applyRestoredSessionModel");async function restoreSessionModelThenAuthenticate(config,projection,authenticate){const originalAuth=liveAuthType(config);const originalModel=config.getModel();const originalBaseUrl=config.getCurrentModelRegistryBaseUrl?.();const originalRuntimeSnapshot=config.getActiveRuntimeModelSnapshot?.();await applyRestoredSessionModel(config,projection);try{await authenticate()}catch(error){if(liveAuthType(config)===originalAuth&&config.getModel()===originalModel&&(config.getCurrentModelRegistryBaseUrl?.()??void 0)===(originalBaseUrl??void 0)&&runtimeSnapshotIdentity(config.getActiveRuntimeModelSnapshot?.())===runtimeSnapshotIdentity(originalRuntimeSnapshot)){throw error}debugLogger2.warn("restored session model made authentication fail; retrying with settings model");if(!originalAuth||!originalModel){throw error}const rollbackModelId=originalRuntimeSnapshot?.authType===originalAuth&&originalRuntimeSnapshot.modelId===stripRuntimeSnapshotPrefix(originalModel)?buildRuntimeSnapshotId(originalAuth,stripRuntimeSnapshotPrefix(originalModel)):originalModel;try{await config.switchModel(originalAuth,rollbackModelId,typeof originalBaseUrl==="string"?{baseUrl:originalBaseUrl}:void 0)}catch{throw error}await authenticate()}}__name(restoreSessionModelThenAuthenticate,"restoreSessionModelThenAuthenticate");init_esbuild_shims();var SSH_SLASH_COMMAND_POLICY={allowSessionReset:false,allowWorkspaceSettingsWrite:false,persistModelSelection:false,blockedBuiltinCommandNames:[]};var sshCommands=new Set(["help","model","effort","compress","context"]);function isSshSessionCommandAllowed(command){return command.kind==="built-in"&&sshCommands.has(command.name)}__name(isSshSessionCommandAllowed,"isSshSessionCommandAllowed");var unsupportedSessionMethods=new Set([SERVE_STATUS_EXT_METHODS.sessionMessageGroups,SERVE_CONTROL_EXT_METHODS.sessionCd,SERVE_CONTROL_EXT_METHODS.sessionBranch,SERVE_CONTROL_EXT_METHODS.sessionSideTask,SERVE_CONTROL_EXT_METHODS.sessionForkAgent,SERVE_CONTROL_EXT_METHODS.sessionBtw,SERVE_CONTROL_EXT_METHODS.sessionArtifactsPersist,SERVE_CONTROL_EXT_METHODS.sessionMessagesDelete,SERVE_CONTROL_EXT_METHODS.sessionRewind,SERVE_CONTROL_EXT_METHODS.sessionWorkflowTaskAction,SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeAdd,SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeRemove,SERVE_CONTROL_EXT_METHODS.sessionLanguage,SERVE_CONTROL_EXT_METHODS.sessionManagedConversationBindingCommit,SERVE_CONTROL_EXT_METHODS.sessionManagedConversationBindingRelease,"rewindSession"]);function isSshWorkspaceExtMethodAllowed(method){return!(method.startsWith("qwen/control/workspace/")||method.startsWith("qwen/skills/")||method.startsWith("qwen/session/sources/")||method.startsWith("qwen/settings/")&&method!=="qwen/settings/getCore"||unsupportedSessionMethods.has(method))}__name(isSshWorkspaceExtMethodAllowed,"isSshWorkspaceExtMethodAllowed");init_esbuild_shims();init_esbuild_shims();var debugLogger3=createDebugLogger("CLI_COMMANDS");function commandOrigin(command){const owner=command.extensionName?`extension "${command.extensionName}"`:command.kind;return`${owner} command "${command.name}"`}__name(commandOrigin,"commandOrigin");var CommandService=class _CommandService{constructor(commands){this.commands=commands}static{__name(this,"CommandService")}static async create(loaders,signal,disabledNames){const results=await Promise.allSettled(loaders.map(loader=>loader.loadCommands(signal)));const allCommands=[];for(const result of results){if(result.status==="fulfilled"){allCommands.push(...result.value)}else{debugLogger3.debug("A command loader failed:",result.reason)}}const commandMap=new Map;for(const cmd of allCommands){let finalName=cmd.name;if(cmd.extensionName&&commandMap.has(cmd.name)){let renamedName=`${cmd.extensionName}.${cmd.name}`;let suffix=1;while(commandMap.has(renamedName)){renamedName=`${cmd.extensionName}.${cmd.name}${suffix}`;suffix++}finalName=renamedName}const shadowed=commandMap.get(finalName);if(shadowed){debugLogger3.warn(`Slash command "/${finalName}" from ${commandOrigin(shadowed)} is replaced by ${commandOrigin(cmd)}`)}commandMap.set(finalName,{...cmd,name:finalName})}if(disabledNames&&disabledNames.size>0){const normalizedDisabled=new Set;for(const entry of disabledNames){const trimmed=entry.trim();if(trimmed)normalizedDisabled.add(trimmed.toLowerCase())}if(normalizedDisabled.size>0){for(const[name,cmd]of Array.from(commandMap.entries())){if(commandRestrictionNames(cmd).some(candidate=>normalizedDisabled.has(candidate))){commandMap.delete(name)}}}}const finalCommands=Object.freeze(Array.from(commandMap.values()));return new _CommandService(finalCommands)}getCommands(){return this.commands}getCommandsForMode(mode){return Object.freeze(filterCommandsForMode(this.commands.filter(cmd=>!cmd.hidden&&cmd.userInvocable!==false),mode))}getModelInvocableCommands(){return this.commands.filter(cmd=>!cmd.hidden&&cmd.modelInvocable===true)}};init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import fs from"node:fs/promises";import path from"node:path";var debugLogger4=createDebugLogger("SESSION_PATHS");var OPENAI_LOG_SCAN_LIMIT=100;async function collectSessionPathInfo(context){const config=context.services.config;const sessionId=config?.getSessionId()||context.session.stats.sessionId||"unknown";const contentGeneratorConfig=config?.getContentGeneratorConfig();const workingDir=config?.getWorkingDir()||process.cwd();const openAILogDir=resolveOpenAILogDir(contentGeneratorConfig?.openAILoggingDir,workingDir);const openAILoggingEnabled=contentGeneratorConfig?.enableOpenAILogging===true;const latestOpenAILog=openAILoggingEnabled&&sessionId!=="unknown"?await findLatestOpenAILogForSession(openAILogDir,sessionId):void 0;const transcriptPath=config?.getTranscriptPath()||"";const debugLogPath=config?.getDebugMode()&&sessionId!=="unknown"?Storage.getDebugLogPath(sessionId):"";const planFilePath=config?.getPlanFilePath()||(sessionId==="unknown"?"":Storage.getPlanFilePath(sessionId));const planFileExists=planFilePath?await pathExists(planFilePath):false;const sections=[{title:"Session files",entries:[{label:"Session ID",value:sessionId},...transcriptPath?[{label:"Transcript",value:transcriptPath}]:[],...debugLogPath?[{label:"Debug log",value:debugLogPath}]:[],...planFileExists?[{label:"Plan file",value:planFilePath}]:[]]}];if(openAILoggingEnabled){sections.push({title:"OpenAI logs",entries:[{label:"Directory",value:openAILogDir},{label:"Latest for session",value:latestOpenAILog??"none yet"}]})}return{sections}}__name(collectSessionPathInfo,"collectSessionPathInfo");function formatSessionPathInfo(info){const lines=[];for(const[index,section]of info.sections.entries()){if(index>0){lines.push("")}lines.push(`${section.title}:`);for(const entry of section.entries){lines.push(` ${entry.label}: ${entry.value}`)}}return lines.join("\n")}__name(formatSessionPathInfo,"formatSessionPathInfo");async function findLatestOpenAILogForSession(logDir,sessionId){const files=await listLogFiles(logDir,name=>/^openai-.*\.json$/.test(name));for(const file of files){try{const raw=await fs.readFile(file,"utf-8");const parsed=JSON.parse(raw);if(hasContextSessionId(parsed,sessionId)){return file}}catch(error){if(error instanceof SyntaxError||error.code==="ENOENT"){continue}debugLogger4.warn("Error reading OpenAI log file",file,error)}}return void 0}__name(findLatestOpenAILogForSession,"findLatestOpenAILogForSession");async function listLogFiles(dir,predicate){try{const entries=await fs.readdir(dir,{withFileTypes:true});const files=[];for(const entry of entries){if(!entry.isFile()||!predicate(entry.name)){continue}insertRecentFile(files,path.join(dir,entry.name))}return files}catch(error){if(error.code!=="ENOENT"){debugLogger4.warn("Unable to list OpenAI log directory",dir,error)}return[]}}__name(listLogFiles,"listLogFiles");function insertRecentFile(files,file){const insertAt=files.findIndex(existing=>file>existing);if(insertAt===-1){if(files.length<OPENAI_LOG_SCAN_LIMIT){files.push(file)}return}files.splice(insertAt,0,file);if(files.length>OPENAI_LOG_SCAN_LIMIT){files.pop()}}__name(insertRecentFile,"insertRecentFile");async function pathExists(filePath){try{await fs.access(filePath);return true}catch{return false}}__name(pathExists,"pathExists");function hasContextSessionId(value,sessionId){if(!value||typeof value!=="object"){return false}const context=value.context;if(!context||typeof context!=="object"){return false}const ctx=context;return ctx.sessionId===sessionId||ctx.promptId===sessionId}__name(hasContextSessionId,"hasContextSessionId");var aboutCommand={name:"status",altNames:["about"],get description(){return t("show version info")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const systemInfo=await getExtendedSystemInfo(context);if(context.executionMode!=="interactive"){const authLabel=systemInfo.selectedAuthType==="qwen-subscription"?"Qwen Subscription":systemInfo.selectedAuthType;const lines=[`Qwen Code v${systemInfo.cliVersion}`,`Model: ${systemInfo.modelVersion}`,`Fast Model: ${systemInfo.fastModel??"not set"}`,`Auth: ${authLabel}`,`Platform: ${systemInfo.osPlatform} ${systemInfo.osArch} (${systemInfo.osRelease})`,`Node.js: ${systemInfo.nodeVersion}`,`Session: ${systemInfo.sessionId}`,...systemInfo.gitCommit?[`Git commit: ${systemInfo.gitCommit}`]:[],...systemInfo.ideClient?[`IDE: ${systemInfo.ideClient}`]:[],...systemInfo.lspStatus?[`LSP: ${systemInfo.lspStatus}`]:[]];return{type:"message",messageType:"info",content:lines.join("\n")}}const aboutItem={type:"about",systemInfo};context.ui.addItem(aboutItem,Date.now());return},"action"),subCommands:[{name:"paths",get description(){return t("show paths for current session files and logs")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const info=await collectSessionPathInfo(context);const content=formatSessionPathInfo(info);return{type:"message",messageType:"info",content}},"action")}]};init_esbuild_shims();var ADVISOR_SCHEMA={type:"object",additionalProperties:false,properties:{verdict:{type:"string",minLength:1},risks:{type:"string",minLength:1},missingEvidence:{type:"string",minLength:1},recommendation:{type:"string",minLength:1}},required:["verdict","risks","missingEvidence","recommendation"]};function buildAdvisorPrompt(focus){return["<system-reminder>","You are acting as an ADVISOR \u2014 an independent senior reviewer giving a second opinion on the conversation so far. The transcript above may be truncated to the most recent turns; treat what is shown as the evidence available to you.","","CRITICAL CONSTRAINTS:","- You have NO tools. Base every claim strictly on evidence present in the transcript; never claim to have verified something you could not observe.","- Do not perform the task or write the implementation. Review only.","- Be direct about problems: flawed assumptions, premature conclusions, unverified claims, risky next steps.","- The main conversation is NOT interrupted; your review is shown to the user only.","","Return exactly one JSON object with these string fields and no markdown fence, preamble, extra key, or commentary:","- verdict: one short paragraph stating whether the current approach or conclusion is sound.",'- risks: concrete risks or flawed assumptions, each citing transcript evidence. Write "None found" if none.',"- missingEvidence: claims asserted but not verified in the visible transcript (earlier verification may exist outside the shown window).","- recommendation: the single most valuable next action.","</system-reminder>","",focus||"Review the conversation above."].join("\n")}__name(buildAdvisorPrompt,"buildAdvisorPrompt");function formatAdvisorReview(value){const fields=["verdict","risks","missingEvidence","recommendation"];if(!value||Object.keys(value).length!==fields.length||fields.some(field=>{const fieldValue=value[field];return typeof fieldValue!=="string"||fieldValue.trim().length===0})){throw new Error("Advisor returned invalid structured output.")}const review=value;return["## Verdict",review.verdict.trim(),"## Risks",review.risks.trim(),"## Missing evidence",review.missingEvidence.trim(),"## Recommendation",review.recommendation.trim()].join("\n\n")}__name(formatAdvisorReview,"formatAdvisorReview");function parseJsonObjectText(text){const value=text?.trim();if(!value)return void 0;const firstStructuredChar=value.search(/[[{]/);if(firstStructuredChar!==-1&&value[firstStructuredChar]==="["){return void 0}const first=value.indexOf("{");const last=value.lastIndexOf("}");if(first===-1||last<=first)return void 0;try{const parsed=JSON.parse(value.slice(first,last+1));return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:void 0}catch{return void 0}}__name(parseJsonObjectText,"parseJsonObjectText");function formatAdvisorError(error){return t("Advisor review failed: {{error}}",{error:error instanceof Error?error.message:String(error||"Unknown error")})}__name(formatAdvisorError,"formatAdvisorError");function unavailableModelMessage(modelName,availableModelIds){const configured=availableModelIds.length>0?t("Configured models: {{models}}.",{models:availableModelIds.join(", ")}):t("No models are configured.");return[`Advisor model '${modelName}' is not configured.`,configured,"Configure models in settings.modelProviders, or run /advisor without arguments to choose a model."].join("\n")}__name(unavailableModelMessage,"unavailableModelMessage");async function setAdvisorModel(context,model){if(context.executionPolicy?.persistModelSelection===false){return{type:"message",messageType:"error",content:t("This model selection is not available in this session.")}}const{config,settings}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Advisor configuration is unavailable.")}}if(model){const availability=checkAdvisorModelAvailability(config,model);if(!availability.available){return{type:"message",messageType:"error",content:unavailableModelMessage(model,availability.availableModelIds)}}}const applied=await config.setAdvisorModel(model);if(applied===false){return{type:"message",messageType:"error",content:t("Advisor configuration is unavailable.")}}settings.setValue("User","advisorModel",model??"");return{type:"message",messageType:"info",content:model?t("Advisor set to {{model}}",{model}):t("Advisor disabled")}}__name(setAdvisorModel,"setAdvisorModel");async function askAdvisor(context,focus,abortSignal){const{config}=context.services;if(!config)throw new Error(t("Config not loaded."));const cacheSafeParams=buildBtwCacheSafeParams(config);if(!cacheSafeParams||config.getLlmClient().getHistoryForForkWindow().length===0){throw new Error(t("No conversation context available for /advisor"))}const advisorModel=config.getAdvisorModel();const result=await runForkedAgent({config,userMessage:buildAdvisorPrompt(focus),cacheSafeParams,jsonSchema:ADVISOR_SCHEMA,...advisorModel?{model:advisorModel}:{},abortSignal,disableModelFallbacks:true});return{text:formatAdvisorReview(result.jsonResult??parseJsonObjectText(result.text)),model:result.model}}__name(askAdvisor,"askAdvisor");var advisorCommand={name:"advisor",get description(){return t("Configure the Advisor model")},argumentHint:"[<model-id>|off|review [focus]]",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],completion:__name(async(context,partialArg)=>{const prefix=partialArg.trim();const fixed=[{value:"off",description:t("Disable Advisor")},{value:"review",description:t("Get a second opinion on the current conversation from a reviewer model")}].filter(({value})=>value.startsWith(prefix));if(!context.services.config||prefix.startsWith("review "))return fixed;return[...fixed,...context.services.config.getAllConfiguredModels().filter(model=>isAdvisorModelEligible(model)).map(model=>model.id).filter(id=>id.startsWith(prefix))]},"completion"),action:__name(async(context,args)=>{const value=context.invocation?.args?.trim()||args.trim();const[subcommand="",...rest]=value.split(/\s+/);const isReview=subcommand==="review";if(!isReview){if(!value){if(context.executionMode!=="interactive"){return{type:"message",messageType:"info",content:[`Advisor: ${context.services.config?.getAdvisorModel()?.split("\0")[0]??"off"}`,`Session calls: ${context.services.config?.getAdvisorUseCount()??0} / ${context.services.config?.getAdvisorMaxUses()||"unlimited"}`,"Each consultation sends the conversation to the selected provider and consumes additional tokens.","Use /advisor <model-id> or /advisor off."].join("\n")}}return{type:"dialog",dialog:"advisor-model"}}return setAdvisorModel(context,value.toLowerCase()==="off"?void 0:value)}const focus=rest.join(" ").trim();if(focus.length>BTW_MAX_INPUT_LENGTH){return{type:"message",messageType:"error",content:t("Focus too long (max {{max}} chars)",{max:String(BTW_MAX_INPUT_LENGTH)})}}const{config}=context.services;const{ui}=context;if(!config){return{type:"message",messageType:"error",content:t("Config not loaded.")}}if(!config.getModel()){return{type:"message",messageType:"error",content:t("No model configured.")}}const abortSignal=context.abortSignal??new AbortController().signal;const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){try{const review=await askAdvisor(context,focus,abortSignal);return{type:"message",messageType:"info",content:review.text}}catch(error){return{type:"message",messageType:"error",content:formatAdvisorError(error)}}}const turnInFlight=!ui.isIdleRef.current||ui.pendingItem!==null;if(turnInFlight){return{type:"message",messageType:"error",content:t("Another operation is in progress, wait for it to complete before running /advisor")}}try{ui.setPendingItem({type:"info",text:t("Consulting advisor...")});const review=await askAdvisor(context,focus,abortSignal);if(abortSignal.aborted)return;ui.addItem({type:"advisor",text:review.text,model:review.model},Date.now())}catch(error){if(abortSignal.aborted)return;ui.addItem({type:"error",text:formatAdvisorError(error)},Date.now())}finally{if(!abortSignal.aborted)ui.setPendingItem(null)}},"action")};init_esbuild_shims();function statusLabel(entry){switch(entry.kind){case"agent":{const status=entry.status;switch(status){case"completed":return"completed";case"failed":return`failed: ${entry.error??"unknown error"}`;case"cancelled":return"cancelled";case"paused":return entry.resumeBlockedReason?`paused (resume blocked): ${entry.resumeBlockedReason}`:"paused";case"running":return"running";default:{const _exhaustive=status;throw new Error(`statusLabel(agent): unknown status: ${JSON.stringify(_exhaustive)}`)}}}case"shell":{const status=entry.status;switch(status){case"completed":return`completed (exit ${entry.exitCode??"?"})`;case"failed":return`failed: ${entry.error??"unknown error"}`;case"cancelled":return"cancelled";case"running":return"running";default:{const _exhaustive=status;throw new Error(`statusLabel(shell): unknown status: ${JSON.stringify(_exhaustive)}`)}}}case"monitor":{const events=`${entry.eventCount} event${entry.eventCount===1?"":"s"}`;const status=entry.status;switch(status){case"completed":return entry.error?`completed (${entry.error}, ${events})`:`completed (exit ${entry.exitCode??"?"}, ${events})`;case"failed":return`failed: ${entry.error??"unknown error"} (${events})`;case"cancelled":return`cancelled (${events})`;case"running":return`running (${events})`;default:{const _exhaustive=status;throw new Error(`statusLabel(monitor): unknown status: ${JSON.stringify(_exhaustive)}`)}}}default:{const _exhaustive=entry;throw new Error(`statusLabel: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(statusLabel,"statusLabel");function taskLabel(entry){switch(entry.kind){case"agent":return buildBackgroundEntryLabel(entry);case"shell":return entry.command;case"monitor":return entry.description;default:{const _exhaustive=entry;throw new Error(`taskLabel: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskLabel,"taskLabel");function taskId(entry){switch(entry.kind){case"agent":return entry.agentId;case"shell":return entry.shellId;case"monitor":return entry.monitorId;default:{const _exhaustive=entry;throw new Error(`taskId: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskId,"taskId");function taskOutputPath(entry){switch(entry.kind){case"agent":case"shell":return entry.outputFile;case"monitor":return void 0;default:{const _exhaustive=entry;throw new Error(`taskOutputPath: unknown TaskEntry kind: ${JSON.stringify(_exhaustive)}`)}}}__name(taskOutputPath,"taskOutputPath");var tasksCommand={name:"tasks",get description(){return t("List background tasks (text dump \u2014 interactive dialog opens via the footer pill)")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async context=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:"Config not available."}}const agentEntries=[...config.getBackgroundTaskRegistry().getAll()];const shellEntries=[...config.getBackgroundShellRegistry().getAll()];const monitorEntries=[...config.getMonitorRegistry().getAll()];const entries=[...agentEntries,...shellEntries,...monitorEntries].sort((a,b)=>a.startTime-b.startTime);if(entries.length===0){return{type:"message",messageType:"info",content:"No background tasks."}}const now=Date.now();const lines=[];if(context.executionMode==="interactive"){lines.push(t("Tip: focus the Background tasks pill in the footer (use \u2193 from an empty composer) and press Enter for the interactive dialog with detail view + live updates."),"")}lines.push(`Background tasks (${entries.length} total)`,"");for(const entry of entries){const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});const pidPart=(entry.kind==="shell"||entry.kind==="monitor")&&entry.pid!==void 0?` pid=${entry.pid}`:"";lines.push(`[${taskId(entry)}] ${statusLabel(entry)} ${runtime}${pidPart} ${taskLabel(entry)}`);const outputPath=taskOutputPath(entry);if(outputPath){lines.push(` output: ${outputPath}`)}}return{type:"message",messageType:"info",content:stripUnsafeCharacters(lines.join("\n"))}},"action")};init_esbuild_shims();function snapshotToTask(s){return{id:s.runId,kind:"workflow",runId:s.runId,...s.parentSessionId?{parentSessionId:s.parentSessionId}:{},...s.toolUseId?{toolUseId:s.toolUseId}:{},...s.sourceRef?{sourceRef:{...s.sourceRef}}:{},...s.workflowCalls?{workflowCalls:s.workflowCalls.map(call=>({...call}))}:{},...s.workflowCallsTruncated?{workflowCallsTruncated:true}:{},...s.workflowName?{workflowName:s.workflowName}:{},description:s.meta?.name??s.runId,meta:s.meta,status:s.status,currentPhase:null,currentPhaseVisitId:null,phases:s.phases??[],phaseVisits:s.phaseVisits??[],dispatches:s.dispatches??[],sourceRunId:s.sourceRunId,startMode:s.startMode,agentsDispatched:s.agentsDispatched??0,agentsCompleted:s.agentsCompleted??0,recentLogs:s.recentLogs??[],events:s.events??[],tokensSpent:s.tokensSpent??0,tokenBudgetTotal:s.tokenBudgetTotal??null,perPhaseTokens:new Map(s.perPhaseTokens??[]),pendingApprovals:[],script:s.script??"",scriptPath:s.scriptPath,result:s.result,error:s.error,startTime:s.startTime,endTime:s.endTime,outputFile:"",outputOffset:0,notified:true,abortController:new AbortController}}__name(snapshotToTask,"snapshotToTask");function rowLine(entry,now){const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});const label=entry.meta?.name??entry.runId;const phase=entry.currentPhase?` \xB7 ${entry.currentPhase}`:"";const counts=entry.agentsDispatched>0?` \xB7 ${entry.agentsCompleted}/${entry.agentsDispatched} agents`:"";const phaseCount=entry.phases.length>0?` \xB7 ${entry.phases.length} ${entry.phases.length===1?"phase":"phases"}`:"";const budgetChip=entry.tokensSpent>0||entry.tokenBudgetTotal!==null?entry.tokenBudgetTotal!==null?` \xB7 ${formatTokenCount(entry.tokensSpent)}/${formatTokenCount(entry.tokenBudgetTotal)}t`:` \xB7 ${formatTokenCount(entry.tokensSpent)}t`:"";const errorTail=entry.status==="failed"&&entry.error?` \u2014 ${entry.error.slice(0,80)}`:"";return` ${entry.runId.padEnd(20)} ${entry.status.padEnd(10)} ${runtime.padStart(8)} ${label}${phase}${counts}${phaseCount}${budgetChip}${errorTail}`}__name(rowLine,"rowLine");var MAX_DETAIL_ERROR_CHARS=4096;function isHollow(value){if(typeof value!=="object"||value===null)return false;return Object.values(value).every(isHollow)}__name(isHollow,"isHollow");function withoutHollowFailures(result){if(typeof result!=="object"||result===null||Array.isArray(result)){return result}const kept={...result};for(const key of REPORTED_FAILURE_KEYS){try{if(isHollow(kept[key]))delete kept[key]}catch{}}return kept}__name(withoutHollowFailures,"withoutHollowFailures");function mayHaveLostDetail(result){return typeof result==="object"&&result!==null||typeof result==="string"&&result.startsWith("(non-JSON-serializable ")}__name(mayHaveLostDetail,"mayHaveLostDetail");function resultPreviewFor(entry,source){if(entry.status!=="completed")return{legacy:false};if(!source){return{preview:buildWorkflowResultPreview(entry.result),legacy:false}}const{snapshot}=source;if(snapshot.resultPreview){return{preview:snapshot.resultPreview,legacy:false}}if(!Object.hasOwn(snapshot,"result"))return{legacy:true};const{result}=snapshot;return{preview:{...buildWorkflowResultPreview(result),reportedFailures:reportedFailureLines(withoutHollowFailures(result))},legacy:mayHaveLostDetail(result)}}__name(resultPreviewFor,"resultPreviewFor");function indent(text,prefix){return text.split("\n").map(line=>prefix+line).join("\n")}__name(indent,"indent");async function confirmedSnapshotFile(config,runId){if(!isWorkflowRunId(runId)||!config.storage)return void 0;return await readWorkflowSnapshot(config,runId)?config.storage.getWorkflowRunSnapshotPath(runId):void 0}__name(confirmedSnapshotFile,"confirmedSnapshotFile");function detailLines(entry,now,source){const lines=[];const endTime=entry.endTime??now;const runtime=formatDuration(endTime-entry.startTime,{hideTrailingZeros:true});lines.push(`Workflow ${entry.runId}`);if(entry.meta?.name){lines.push(` name : ${entry.meta.name}`)}if(entry.meta?.description){lines.push(` description : ${entry.meta.description}`)}if(entry.meta?.whenToUse){lines.push(` whenToUse : ${entry.meta.whenToUse}`)}lines.push(` status : ${entry.status}`);lines.push(` runtime : ${runtime}`);if(entry.currentPhase){lines.push(` currentPhase: ${entry.currentPhase}`)}lines.push(` agents : ${entry.agentsCompleted}/${entry.agentsDispatched}`);lines.push(` tokens : ${formatTokenCount(entry.tokensSpent)}`);lines.push(` cap : ${entry.tokenBudgetTotal!==null?formatTokenCount(entry.tokenBudgetTotal):"(no cap)"}`);if(entry.error){const error=truncateWorkflowText(sanitizeWorkflowText(entry.error),MAX_DETAIL_ERROR_CHARS);lines.push(` error : ${error.split("\n").join("\n ")}`)}if(source?.file){lines.push(` snapshotFile: ${source.file}`)}if(entry.phases.length>0){lines.push("");lines.push(` Phases (${entry.phases.length})`);for(const phase of entry.phases){const phaseTokens=entry.perPhaseTokens.get(phase)??0;const chip=phaseTokens>0?` \xB7 ${formatTokenCount(phaseTokens)}t`:"";lines.push(` \xB7 ${phase}${chip}`)}const prePhaseTokens=entry.perPhaseTokens.get(null)??0;if(prePhaseTokens>0){lines.push(` \xB7 (no phase) \xB7 ${formatTokenCount(prePhaseTokens)}t`)}}if(entry.recentLogs.length>0){lines.push("");lines.push(` Logs (last ${entry.recentLogs.length})`);for(const line of entry.recentLogs){lines.push(` ${line}`)}}if(source&&source.snapshot.dispatches===void 0){lines.push(""," Failed agents: not recorded in this snapshot")}else{const failures=buildFailureLines(entry);if(failures.length>0){const count=entry.dispatches.filter(d=>d.status==="failed").length;lines.push("",` Failed agents (${count})`);for(const line of failures)lines.push(indent(line," "))}}const{preview:preview2,legacy}=resultPreviewFor(entry,source);const reported=(preview2?.reportedFailures??[]).map(line=>truncateWorkflowText(sanitizeWorkflowText(line),MAX_FAILURE_LINE_CHARS));if(reported.length>0){lines.push(""," Reported failures");for(const line of reported)lines.push(indent(line," "))}if(entry.status==="completed"){lines.push(""," Result");if(!preview2){lines.push(" (this snapshot did not record a result)")}else{const sanitized=sanitizeWorkflowText(preview2.text);const text=truncateWorkflowText(sanitized,MAX_WORKFLOW_RESULT_PREVIEW_CHARS);lines.push(indent(text," "));if(preview2.truncated||text!==sanitized){lines.push(` (preview truncated to ${MAX_WORKFLOW_RESULT_PREVIEW_CHARS} characters)`)}}if(legacy){lines.push(" (older snapshot: result details such as Error, Map, and Set values may be incomplete)")}}return lines}__name(detailLines,"detailLines");var workflowsCommand={name:"workflows",get description(){return t("List workflow runs or cooperatively pause/resume a live run")},get argumentHint(){return t("[mode [status|on|off] | runId | p <runId>]")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],subCommands:[{name:"mode",description:"Show or change this session\u2019s Workflow guidance mode",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async(context,args)=>{const config=context.services.config;if(!config?.isWorkflowModeSupported()){return{type:"message",messageType:"error",content:"Workflow mode is unavailable for this session owner."}}const value=args.trim()||"status";if(!["status","on","off"].includes(value)){return{type:"message",messageType:"error",content:"Usage: /workflows mode [status|on|off]"}}try{const state=value==="status"?config.getWorkflowMode():await config.setWorkflowMode(value==="on");return{type:"message",messageType:"info",content:`Workflow mode: ${state.requested?"on":"off"}${state.requested&&!state.effective?" (unavailable)":""}${state.reason?` \u2014 ${state.reason}`:""}`}}catch(error){return{type:"message",messageType:"error",content:error instanceof Error?error.message:String(error)}}},"action")}],action:__name(async(context,args)=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:"Config not available."}}if(!config.isWorkflowsEnabled()){return{type:"message",messageType:"error",content:"Workflows are disabled. Use /workflows mode status or off to manage the saved mode."}}const registry=config.getWorkflowRunRegistry();const allEntries=registry.list();const trimmedArgs=(args??"").trim();const tokens=trimmedArgs.split(/\s+/);if(tokens[0]==="p"){if(context.executionMode!=="interactive"){return{type:"message",messageType:"error",content:"Workflow pause controls are available only in the interactive TUI."}}if(tokens.length!==2||!tokens[1]){return{type:"message",messageType:"error",content:"Usage: /workflows p <runId>"}}const runId=tokens[1];let target=registry.get(runId);let fromSnapshot=false;if(!target){const snapshot=(await listWorkflowSnapshots(config)).find(s=>s.runId===runId);if(snapshot){target=snapshotToTask(snapshot);fromSnapshot=true}}if(!target){return{type:"message",messageType:"error",content:`Unknown live workflow runId: ${runId}`}}if(isTerminalWorkflowStatus(target.status)){return{type:"message",messageType:"error",content:`Workflow ${runId} is ${target.status} and cannot be paused or resumed.`}}if(!fromSnapshot&&!target.isBackgrounded){return{type:"message",messageType:"error",content:"Foreground workflow runs cannot be paused or resumed; only background runs support cooperative pause."}}if(target.status==="pausing"){return{type:"message",messageType:"warning",content:`Workflow ${runId} is still pausing; wait until it reaches paused before resuming.`}}if(target.status==="running"){return registry.pause(runId)?{type:"message",messageType:"info",content:`Cooperative pause requested for workflow ${runId}.`}:{type:"message",messageType:"error",content:`Workflow ${runId} could not be paused because its state changed.`}}if(target.status==="paused"){return registry.resume(runId)?{type:"message",messageType:"info",content:`Resume requested for workflow ${runId}.`}:{type:"message",messageType:"error",content:`Workflow ${runId} could not be resumed because its state changed.`}}return{type:"message",messageType:"error",content:`Workflow ${runId} is ${target.status} and cannot be paused or resumed.`}}if(trimmedArgs.length>0){let target=registry.get(trimmedArgs);let source;if(!target){const snapshot=(await listWorkflowSnapshots(config)).find(s=>s.runId===trimmedArgs);if(snapshot){target=snapshotToTask(snapshot);source={snapshot,file:await confirmedSnapshotFile(config,snapshot.runId)}}}if(!target){return{type:"message",messageType:"error",content:`Unknown workflow runId: ${trimmedArgs}`}}return{type:"message",messageType:"info",content:detailLines(target,Date.now(),source).join("\n")}}const snapshots=await listWorkflowSnapshots(config);const liveRunIds=new Set(allEntries.map(e=>e.runId));const snapshotTasks=snapshots.filter(s=>!liveRunIds.has(s.runId)).map(snapshotToTask);if(allEntries.length===0&&snapshotTasks.length===0){return{type:"message",messageType:"info",content:"No workflow runs recorded yet."}}const now=Date.now();const active=allEntries.filter(e=>isActiveWorkflowStatus(e.status)).sort((a,b)=>a.startTime-b.startTime);const terminal=[...allEntries.filter(e=>!isActiveWorkflowStatus(e.status)),...snapshotTasks].sort((a,b)=>(b.endTime??0)-(a.endTime??0));const lines=[];if(context.executionMode==="interactive"){lines.push(t("Tip: use `/workflows p <runId>` or Background tasks + p to cooperatively pause/resume; use `/workflows <runId>` for details."),"")}lines.push(`Workflow runs (${active.length+terminal.length} total \xB7 ${active.length} active)`,"");if(active.length>0){lines.push("Active");for(const entry of active)lines.push(rowLine(entry,now));lines.push("")}if(terminal.length>0){lines.push("Recent");for(const entry of terminal)lines.push(rowLine(entry,now))}return{type:"message",messageType:"info",content:lines.join("\n")}},"action")};init_esbuild_shims();var agentsCommand={name:"agents",get description(){return t("Manage subagents for specialized task delegation.")},kind:"built-in",supportedModes:["interactive"],subCommands:[{name:"manage",get description(){return t("Manage existing subagents (view, edit, delete).")},kind:"built-in",supportedModes:["interactive"],action:__name(()=>({type:"dialog",dialog:"subagent_list"}),"action")},{name:"create",get description(){return t("Create a new subagent with guided setup.")},kind:"built-in",supportedModes:["interactive"],action:__name(()=>({type:"dialog",dialog:"subagent_create"}),"action")}]};init_esbuild_shims();function parseArenaArgs(args){const modelsMatch=args.match(/--models\s+(\S+)/);let models=[];let task=args;if(modelsMatch){const modelStrings=modelsMatch[1].split(",").filter(Boolean);models=modelStrings.map(str=>{const colonIndex=str.indexOf(":");if(colonIndex>0){return{authType:str.substring(0,colonIndex),modelId:str.substring(colonIndex+1)}}return{modelId:str}});task=task.replace(/--models\s+\S+/,"").trim()}task=task.replace(/^["']|["']$/g,"").trim();return{models,task}}__name(parseArenaArgs,"parseArenaArgs");var debugLogger5=createDebugLogger("ARENA_COMMAND");function buildArenaExecutionInput(parsed,config){if(!parsed.task){return{type:"message",messageType:"error",content:[t("Usage: /arena start --models model1,model2 <task>"),"",t("Options:")," --models [authType:]model1,[authType:]model2",` ${t("Models to compete (required, at least 2)")}`,` ${t("Format: authType:modelId or just modelId")}`,"",t("Examples:"),' /arena start --models openai:gpt-4o,anthropic:claude-3 "implement sorting"',' /arena start --models qwen-coder-plus,kimi-for-coding "fix the bug"'].join("\n")}}if(parsed.models.length<2){return{type:"message",messageType:"error",content:[t("Arena requires at least 2 models. Use --models model1,model2 to specify."),t("Format: [authType:]modelId (e.g., openai:gpt-4o or just gpt-4o)")].join("\n")}}const contentGeneratorConfig=config.getContentGeneratorConfig();const defaultAuthType=contentGeneratorConfig?.authType??"openai";const modelsConfig=config.getModelsConfig();const models=[];for(const parsedModel of parsed.models){const authType=parsedModel.authType??defaultAuthType;const registryModels=modelsConfig.getAvailableModelsForAuthType(authType);const resolved=registryModels.find(m=>m.id===parsedModel.modelId);if(resolved?.imageOnly){return{type:"message",messageType:"error",content:t("Image-only model '{{model}}' cannot be used in an Arena session.",{model:parsedModel.modelId})}}models.push({modelId:parsedModel.modelId,authType,displayName:resolved?.label??parsedModel.modelId})}return{task:parsed.task,models,approvalMode:config.getApprovalMode()}}__name(buildArenaExecutionInput,"buildArenaExecutionInput");function recordArenaItem(config,item){try{const chatRecorder=config.getChatRecordingService();if(!chatRecorder)return;chatRecorder.recordSlashCommand({phase:"result",rawCommand:"/arena",outputHistoryItems:[{...item}]})}catch{debugLogger5.error("Failed to record arena history item")}}__name(recordArenaItem,"recordArenaItem");function executeArenaCommand(config,ui,input){let chatHistory;try{const fullHistory=config.getLlmClient().getChat().getHistoryShallow();chatHistory=stripStartupContext(fullHistory)}catch{debugLogger5.debug("Could not retrieve chat history for arena agents")}const manager=new ArenaManager(config);const emitter=manager.getEventEmitter();const detachListeners=[];const agentLabels=new Map;const addArenaMessage=__name((type,text)=>{ui.addItem({type,text},Date.now())},"addArenaMessage");const addAndRecordArenaMessage=__name((type,text)=>{const item={type,text};ui.addItem(item,Date.now());recordArenaItem(config,item)},"addAndRecordArenaMessage");const handleSessionStart=__name(event=>{const modelList=event.models.map((model,index)=>` ${index+1}. ${model.modelId}`).join("\n");addArenaMessage("info",t('Arena started with {{count}} agents on task: "{{task}}"\nModels:\n{{modelList}}',{count:String(event.models.length),task:event.task,modelList}))},"handleSessionStart");const handleAgentStart=__name(event=>{agentLabels.set(event.agentId,event.model.modelId);debugLogger5.debug(`Arena agent started: ${event.model.modelId} (${event.agentId})`)},"handleAgentStart");const handleSessionUpdate=__name(event=>{const attachHintPrefix="To view agent panes, run: ";if(event.message.startsWith(attachHintPrefix)){const command=event.message.slice(attachHintPrefix.length).trim();addAndRecordArenaMessage("info",t("Arena panes are running in tmux. Attach with: `{{command}}`",{command}));return}if(event.type==="success"){addAndRecordArenaMessage("success",event.message)}else if(event.type==="info"){addAndRecordArenaMessage("info",event.message)}else{addAndRecordArenaMessage("warning",event.message)}},"handleSessionUpdate");const handleAgentError=__name(event=>{const label=agentLabels.get(event.agentId)||event.agentId;addAndRecordArenaMessage("error",t("[{{label}}] failed: {{error}}",{label,error:event.error}))},"handleAgentError");const buildAgentCardData=__name(result=>({label:result.model.modelId,status:result.status,durationMs:result.stats.durationMs,totalTokens:result.stats.totalTokens,inputTokens:result.stats.inputTokens,outputTokens:result.stats.outputTokens,toolCalls:result.stats.toolCalls,successfulToolCalls:result.stats.successfulToolCalls,failedToolCalls:result.stats.failedToolCalls,rounds:result.stats.rounds,error:result.error,diff:result.diff,diffSummary:result.diffSummary,modifiedFiles:result.modifiedFiles,approachSummary:result.approachSummary}),"buildAgentCardData");const handleAgentComplete=__name(event=>{if(!isTerminalStatus(event.result.status)){return}const agent=buildAgentCardData(event.result);const item={type:"arena_agent_complete",agent};ui.addItem(item,Date.now());recordArenaItem(config,item)},"handleAgentComplete");const handleSessionError=__name(event=>{addAndRecordArenaMessage("error",`${event.error}`)},"handleSessionError");const handleSessionComplete=__name(event=>{const item={type:"arena_session_complete",sessionStatus:event.result.status,task:event.result.task,totalDurationMs:event.result.totalDurationMs??0,agents:event.result.agents.map(buildAgentCardData)};ui.addItem(item,Date.now());recordArenaItem(config,item)},"handleSessionComplete");emitter.on("session_start",handleSessionStart);detachListeners.push(()=>emitter.off("session_start",handleSessionStart));emitter.on("agent_start",handleAgentStart);detachListeners.push(()=>emitter.off("agent_start",handleAgentStart));emitter.on("session_update",handleSessionUpdate);detachListeners.push(()=>emitter.off("session_update",handleSessionUpdate));emitter.on("agent_error",handleAgentError);detachListeners.push(()=>emitter.off("agent_error",handleAgentError));emitter.on("agent_complete",handleAgentComplete);detachListeners.push(()=>emitter.off("agent_complete",handleAgentComplete));emitter.on("session_error",handleSessionError);detachListeners.push(()=>emitter.off("session_error",handleSessionError));emitter.on("session_complete",handleSessionComplete);detachListeners.push(()=>emitter.off("session_complete",handleSessionComplete));config.setArenaManager(manager);const cols=process.stdout.columns||120;const rows=Math.max((process.stdout.rows||40)-2,1);const lifecycle=manager.start({task:input.task,models:input.models,cols,rows,approvalMode:input.approvalMode,chatHistory}).then(()=>{debugLogger5.debug("Arena agents settled")},error=>{const message2=error instanceof Error?error.message:String(error);addAndRecordArenaMessage("error",`${message2}`);debugLogger5.error("Arena session failed:",error);config.setArenaManager(null);for(const detach of detachListeners){detach()}});manager.setLifecyclePromise(lifecycle)}__name(executeArenaCommand,"executeArenaCommand");var arenaCommand={name:"arena",get description(){return t("Manage Arena sessions")},kind:"built-in",subCommands:[{name:"start",get description(){return t("Start an Arena session with multiple models competing on the same task")},kind:"built-in",action:__name(async(context,args)=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode. Use interactive mode to start an Arena session.")}}const{services,ui}=context;const{config}=services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const existingManager=config.getArenaManager();if(existingManager){return{type:"message",messageType:"error",content:t("An Arena session exists. Use /arena stop or /arena select to end it before starting a new one.")}}const parsed=parseArenaArgs(args);if(parsed.models.length===0){return{type:"dialog",dialog:"arena_start"}}const executionInput=buildArenaExecutionInput(parsed,config);if("type"in executionInput){return executionInput}executeArenaCommand(config,ui,executionInput)},"action")},{name:"stop",get description(){return t("Stop the current Arena session")},kind:"built-in",action:__name(async context=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode. Use interactive mode to stop an Arena session.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No running Arena session found.")}}return{type:"dialog",dialog:"arena_stop"}},"action")},{name:"status",get description(){return t("Show the current Arena session status")},kind:"built-in",action:__name(async context=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No Arena session found. Start one with /arena start.")}}return{type:"dialog",dialog:"arena_status"}},"action")},{name:"select",altNames:["choose"],get description(){return t("Select a model result and merge its diff into the current workspace")},kind:"built-in",action:__name(async(context,args)=>{if(context.services.config?.getShellExecutionSandbox?.()){return{type:"message",messageType:"error",content:"Arena is unavailable in tool sandbox."}}const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"error",content:t("Arena is not supported in non-interactive mode.")}}const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Configuration not available.")}}const manager=config.getArenaManager();if(!manager){return{type:"message",messageType:"error",content:t("No Arena session found. Start one with /arena start.")}}const sessionStatus=manager.getSessionStatus();if(sessionStatus==="running"||sessionStatus==="initializing"){return{type:"message",messageType:"error",content:t("Arena session is still running. Wait for it to complete or use /arena stop first.")}}const trimmedArgs=args.trim();if(trimmedArgs==="--discard"){if(!context.overwriteConfirmed){return{type:"confirm_action",prompt:t("Discard all Arena results and clean up worktrees?"),originalInvocation:{raw:context.invocation?.raw||"/arena select --discard"}}}await config.cleanupArenaRuntime(true);return{type:"message",messageType:"info",content:t("Arena results discarded. All worktrees cleaned up.")}}const agents=manager.getAgentStates();const hasSuccessful=agents.some(a=>isSuccessStatus(a.status));if(!hasSuccessful){return{type:"message",messageType:"error",content:[t("No successful agent results to select from. All agents failed or were cancelled."),t("Use /arena stop to end the session.")].join("\n")}}if(trimmedArgs){const matchingAgent=agents.find(a=>isSuccessStatus(a.status)&&a.model.modelId.toLowerCase()===trimmedArgs.toLowerCase());if(!matchingAgent){return{type:"message",messageType:"error",content:t('No idle agent found matching "{{name}}".',{name:trimmedArgs})}}const label=matchingAgent.model.modelId;const result=await manager.applyAgentResult(matchingAgent.agentId);if(!result.success){return{type:"message",messageType:"error",content:t("Failed to apply changes from {{label}}: {{error}}",{label,error:result.error??"Unknown error"})}}await config.cleanupArenaRuntime(true);return{type:"message",messageType:"info",content:t("Applied changes from {{label}} to workspace. Arena session complete.",{label})}}return{type:"dialog",dialog:"arena_select"}},"action")}]};init_esbuild_shims();init_esbuild_shims();function formatApprovalModeName(mode){switch(mode){case"plan":return t("plan mode");case"default":return t("Ask permissions");case"auto-edit":return t("auto-accept edits");case"auto":return t("Auto mode");case"yolo":return t("YOLO mode");default:return mode}}__name(formatApprovalModeName,"formatApprovalModeName");function formatApprovalModeDescription(mode){switch(mode){case"plan":return t("Analyze only, do not modify files or execute commands");case"default":return t("Require approval for file edits or shell commands");case"auto-edit":return t("Automatically approve file edits");case"auto":return t("Use classifier to automatically approve safe tool calls");case"yolo":return t("Automatically approve all tools");default:return mode}}__name(formatApprovalModeDescription,"formatApprovalModeDescription");function parseApprovalModeArg(arg){const trimmed=arg.trim().toLowerCase();if(!trimmed){return void 0}return APPROVAL_MODES.find(mode=>mode.toLowerCase()===trimmed)}__name(parseApprovalModeArg,"parseApprovalModeArg");var approvalModeCommand={name:"approval-mode",get description(){return t("View or change the approval mode for tool usage")},argumentHint:"<mode>",kind:"built-in",supportedModes:["interactive"],action:__name(async(context,args)=>{const mode=parseApprovalModeArg(args);if(!args.trim()){return{type:"dialog",dialog:"approval-mode"}}if(!mode){return{type:"message",messageType:"error",content:t('Invalid approval mode "{{arg}}". Valid modes: {{modes}}',{arg:args.trim(),modes:APPROVAL_MODES.join(", ")})}}const{config,settings}=context.services;let priorMode;if(config){try{priorMode=config.getApprovalMode()}catch(e){return{type:"message",messageType:"error",content:e.message}}}const autoModeNotices=mode==="auto"&&priorMode!=="auto"&&config?await import("./useAutoAcceptIndicator-ELMIP4TJ.js"):void 0;if(config){try{config.setApprovalMode(mode)}catch(e){return{type:"message",messageType:"error",content:e.message}}}if(autoModeNotices&&config){autoModeNotices.emitAutoModeEntryNotices({config,settings,addItem:context.ui.addItem})}return{type:"message",messageType:"info",content:t('Approval mode set to "{{mode}}"',{mode:formatApprovalModeName(mode)})}},"action")};init_esbuild_shims();var authCommand={name:"auth",altNames:["connect","login"],get description(){return t("Connect an LLM provider")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name((context,_args)=>{const executionMode=context.executionMode??"interactive";if(executionMode!=="interactive"){return{type:"message",messageType:"info",content:t("Authentication configuration is only available in interactive mode. To configure authentication, run Qwen Code interactively and use /auth, or set environment variables: OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_MODEL.")}}return{type:"dialog",dialog:"auth"}},"action")};init_esbuild_shims();var branchCommand={name:"branch",kind:"built-in",get description(){return t("Fork the current conversation into a new session")},action:__name(async(context,args)=>{const{config}=context.services;if(!config){return{type:"message",messageType:"error",content:t("Config is not available.")}}if(context.ui.isIdleRef?.current===false){return{type:"message",messageType:"error",content:t("Cannot branch while a response or tool call is in progress. Wait for it to finish or resolve the pending tool call.")}}const sessionService=config.getSessionService();const currentId=config.getSessionId();const hasRecords=await sessionService.sessionExists(currentId);if(!hasRecords){return{type:"message",messageType:"error",content:t("No conversation to branch.")}}const name=args.trim().replace(/[\r\n]+/g," ");return name?{type:"dialog",dialog:"branch",name}:{type:"dialog",dialog:"branch"}},"action")};init_esbuild_shims();function shortId(msgId){return msgId.replace(/-/g,"").slice(0,6)}__name(shortId,"shortId");function displayHandle(entry,held){const own=canonicalizeMsgId(entry.frame.msgId);let length=Math.min(shortId(entry.frame.msgId).length,own.length);const collides=__name(len=>held.some(other=>other!==entry&&canonicalizeMsgId(other.frame.msgId).startsWith(own.slice(0,len))),"collides");while(length<own.length&&collides(length)){length+=1}return own.slice(0,length)}__name(displayHandle,"displayHandle");function preview(text,max=100){const oneLine=flattenPeerLabel(text).replace(/\s+/g," ").trim();return oneLine.length>max?`${oneLine.slice(0,max-1)}\u2026`:oneLine}__name(preview,"preview");function describeRemaining(entry,expiryMs){if(expiryMs===null)return"";const wallAge=Date.now()-entry.heldAt;const age=entry.monotonicAt===void 0?wallAge:Math.max(wallAge,performance.now()-entry.monotonicAt);const remaining=expiryMs-age;if(remaining<=0)return", expiring now";const minutes=Math.ceil(remaining/6e4);return remaining<6e4?", less than a minute left":`, ${minutes} minute${minutes===1?"":"s"} left`}__name(describeRemaining,"describeRemaining");function formatHeldList(held,expiryFor=()=>null){if(held.length===0)return"No messages from other sessions are waiting.";const lines=held.map(entry=>{const peerLabel=entry.controller?flattenPeerLabel(entry.controller.label):flattenPeerLabel(entry.frame.fromName??entry.frame.from??(entry.selfSent?"this session":"unknown session"));const origin=entry.controller?"[controller]":entry.selfSent?"[own process]":"[peer]";const who=`${origin} ${peerLabel}`;const handle=flattenPeerLabel(displayHandle(entry,held));return` ${handle} ${who}
|
|
4
4
|
${preview(entry.frame.message.content)}
|
|
5
5
|
held because ${describeHoldCause(entry.cause,entry.policyScope)}`+describeRemaining(entry,expiryFor(entry))});return[`${held.length} message${held.length===1?"":"s"} waiting for your review:`,...lines,"","Release with /peers accept <id|all>, or drop with /peers deny <id|all>."].join("\n")}__name(formatHeldList,"formatHeldList");function resolveHeld(held,token){const needle=token.toLowerCase();const exact=held.filter(entry=>canonicalizeMsgId(entry.frame.msgId)===needle);if(exact.length===1)return{kind:"one",msgId:exact[0].frame.msgId};const matches=held.filter(entry=>canonicalizeMsgId(entry.frame.msgId).startsWith(needle)||entry.frame.msgId.toLowerCase().startsWith(needle));if(matches.length===0)return{kind:"none"};if(matches.length>1)return{kind:"ambiguous"};return{kind:"one",msgId:matches[0].frame.msgId}}__name(resolveHeld,"resolveHeld");async function listControllers(){try{return await listPeerControllers()}catch(error){return{error:error instanceof Error?error.message:String(error)}}}__name(listControllers,"listControllers");function formatControllerList(controllers){if(!Array.isArray(controllers)){return`Could not read the trusted controllers: ${controllers.error}`}if(controllers.length===0){return`No trusted controllers. Without an explicit "accept" setting, a message that asserts no review class is held for your review, except one from a process this session started, which is always accepted. A sender's own review-class claim is not authenticated; set agents.crossSessionInbound to "hold" to review every inbound message.
|
|
6
6
|
Add one with: qwen sessions controllers add --label <name>`}const lines=controllers.map(record=>` ${record.id} ${flattenPeerLabel(record.label)} added ${formatCreated(record.createdAt)}`);return[`${controllers.length} trusted controller${controllers.length===1?"":"s"}. Messages presenting one of these tokens are delivered without per-message review unless crossSessionInbound is "hold" or "refuse". A process this session started is always accepted; other senders' review-class claims are not authenticated, so set crossSessionInbound to "hold" to review every inbound message:`,...lines,"","Revoke with /peers revoke <id>."].join("\n")}__name(formatControllerList,"formatControllerList");function formatCreated(createdAt){const date=new Date(createdAt);return Number.isNaN(date.getTime())?"unknown":date.toISOString().replace("T"," ").slice(0,16)}__name(formatCreated,"formatCreated");var peersCommand={name:"peers",kind:"built-in",get description(){return t("Review messages held from other Qwen Code sessions (accept | deny), and manage trusted controllers (controllers | revoke)")},action:__name(async(context,args)=>{const[verb,...rest]=args.trim().split(/\s+/).filter(Boolean);if(verb==="controllers"){return{type:"message",messageType:"info",content:formatControllerList(await listControllers())}}if(verb==="revoke"){const id=rest[0];if(id===void 0){return{type:"message",messageType:"error",content:"Which controller? Use /peers revoke <id> \u2014 /peers controllers lists the ids."}}let removed;try{removed=await removePeerController(id)}catch(error){return{type:"message",messageType:"error",content:`Could not revoke that controller: ${error instanceof Error?error.message:String(error)}`}}if(!removed){return{type:"message",messageType:"error",content:`No controller has the id "${flattenPeerLabel(id)}". Run /peers controllers to see them.`}}const forgotten=context.services.peerMessaging?.forgetController(removed.id)??0;const backlog=forgotten===0?"No held messages in this session used that grant.":`${forgotten} held message${forgotten===1?"":"s"} from it ${forgotten===1?"remains":"remain"} parked for review as ${forgotten===1?"an ordinary peer message":"ordinary peer messages"}.`;return{type:"message",messageType:"info",content:`Revoked the controller "${flattenPeerLabel(removed.label)}" (${removed.id}). Running sessions revalidate active connections, and new connections can no longer use its token. ${backlog}`}}const peerMessaging=context.services.peerMessaging;if(!peerMessaging){const settings=context.services.settings;const runtime=context.services.config;if(!isCrossSessionMessagingActive(settings?.merged,runtime)){const suppression=crossSessionMessagingSuppression(runtime);const offScope=settings?crossSessionMessagingOffScope(settings):void 0;const off=describeMessagingOff(offScope);let content;if(!suppression){content=off}else if(isCrossSessionMessagingEnabled(settings?.merged)){content=describeMessagingSuppressed(suppression)}else{content=`${off} ${describeSuppressionAlso(suppression)}`}return{type:"message",messageType:"info",content}}const failure=getLastPeerInboxFailure();if(failure?.cause==="unsupported_platform"){return{type:"message",messageType:"info",content:"Cross-session messaging is not available on this platform, so this session has no inbox and other sessions cannot reach it."}}return{type:"message",messageType:"error",content:failure?`Cross-session messaging is on, but this session has no inbox \u2014 it failed to bind its socket: ${describePeerInboxFailure(failure)}`:"Cross-session messaging is on, but this session has no inbox: it failed to register in the session registry, or the inbox is still starting. Re-run with DEBUG=1 to see the registration error."}}const held=peerMessaging.getHeld();if(verb===void 0||verb==="list"){peerMessaging.recordHeldListing(held);return{type:"message",messageType:"info",content:formatHeldList(held,entry=>peerMessaging.getHeldExpiryMs(entry.frame.toSessionId))}}if(verb!=="accept"&&verb!=="deny"){return{type:"message",messageType:"error",content:`Unknown subcommand "${verb}". Use /peers, /peers accept <id|all>, /peers deny <id|all>, /peers controllers, or /peers revoke <id>.`}}const decision=verb==="accept"?"approve":"deny";const target=rest[0];if(target===void 0){return{type:"message",messageType:"error",content:`Which message? Use /peers ${verb} <id|all> \u2014 /peers lists the ids.`}}if(peerMessaging.heldSetChangedSinceListing()){return{type:"message",messageType:"error",content:"The waiting list changed since you listed it \u2014 run /peers again to review what is waiting now."}}if(held.length===0){return{type:"message",messageType:"info",content:"No messages from other sessions are waiting."}}if(target.toLowerCase()==="all"){const ids=held.map(entry=>entry.frame.msgId);let count=0;let failed=0;let gone=0;for(const msgId of ids){const outcome2=peerMessaging.decide(msgId,decision);if(outcome2==="done")count+=1;else if(outcome2==="failed")failed+=1;else if(outcome2==="gone")gone+=1}peerMessaging.recordHeldListing(peerMessaging.getHeld());return{type:"message",messageType:"info",content:`${verb==="accept"?"Released":"Dropped"} ${count} message${count===1?"":"s"}.`+(failed>0?` ${failed} could not be delivered and ${failed===1?"is":"are"} still waiting \u2014 try again once the session catches up.`:"")+(gone>0?` ${gone} had already expired or been decided \u2014 run /peers to see what is waiting now.`:"")}}const resolved=resolveHeld(held,target);if(resolved.kind==="none"){return{type:"message",messageType:"error",content:`No held message matches "${target}". Run /peers to see what is waiting.`}}if(resolved.kind==="ambiguous"){return{type:"message",messageType:"error",content:`"${target}" matches more than one held message. Use more characters of the id.`}}const outcome=peerMessaging.decide(resolved.msgId,decision);peerMessaging.recordHeldListing(peerMessaging.getHeld());if(outcome==="gone"){return{type:"message",messageType:"info",content:"That message is no longer waiting \u2014 it may have expired or already been decided."}}if(outcome==="failed"){return{type:"message",messageType:"error",content:"The session could not take the message just now \u2014 its input queue is full, or it could not confirm it still holds the session. It is still waiting; try again in a moment."}}return{type:"message",messageType:"info",content:verb==="accept"?"Released to this session. It will be picked up on the next turn.":"Dropped. The sending session has been told."}},"action")};function describeMessagingOff(scope){switch(scope){case"workspace":return`Cross-session messaging is off: this repository's .qwen/settings.json turns "agents.crossSessionMessaging" off. A workspace may only make that setting stricter, so your user settings cannot turn it back on here. Remove the entry from that file, then restart.`;case"system":return'Cross-session messaging is off: system settings set "agents.crossSessionMessaging", and system settings override every other scope. Whoever manages them can remove the entry.';case"system-defaults":return'Cross-session messaging is off: the system defaults turn "agents.crossSessionMessaging" off. Set it to true in your user settings, then restart.';case"user":return'Cross-session messaging is off: your user settings turn "agents.crossSessionMessaging" off (only true, or leaving it unset, turns it on). Remove that entry, then restart.';default:return'Cross-session messaging is off because of the "agents.crossSessionMessaging" setting (only true, or leaving it unset, turns it on). Remove that entry, then restart.'}}__name(describeMessagingOff,"describeMessagingOff");var SUPPRESSION_PROSE={"safe-mode":{mode:"safe mode",channels:"--safe-mode, or QWEN_CODE_SAFE_MODE",effect:"which closes the surfaces other processes can reach"},bare:{mode:"bare mode",channels:"--bare, or QWEN_CODE_SIMPLE",effect:"which skips implicit startup work"}};function describeMessagingSuppressed(suppression){const{mode,channels,effect}=SUPPRESSION_PROSE[suppression];return`Cross-session messaging is off: this session runs in ${mode} (${channels}), ${effect}. The "agents.crossSessionMessaging" setting cannot turn it back on; restart without ${mode}.`}__name(describeMessagingSuppressed,"describeMessagingSuppressed");function describeSuppressionAlso(suppression){const{mode,channels,effect}=SUPPRESSION_PROSE[suppression];return`This session also runs in ${mode} (${channels}), ${effect}, so fixing the setting alone will not bring messaging back: restart without ${mode} as well.`}__name(describeSuppressionAlso,"describeSuppressionAlso");init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import*as fs2 from"node:fs";import*as path2 from"node:path";var TipHistory=class _TipHistory{static{__name(this,"TipHistory")}sessionShown=new Map;data;filePath;constructor(data,filePath){this.data=data;this.filePath=filePath}get sessionCount(){return this.data.sessionCount}get btwUseCount(){return this.data.btwUseCount??0}recordBtwUse(){this.data.btwUseCount=this.btwUseCount+1;this.persist()}isCooledDown(tipId,cooldownPrompts,currentPromptCount){const lastShown=this.sessionShown.get(tipId);if(lastShown===void 0)return true;return currentPromptCount-lastShown>=cooldownPrompts}getLastShown(tipId){if(this.sessionShown.has(tipId)){return Number.MAX_SAFE_INTEGER-1e6+(this.sessionShown.get(tipId)??0)}return this.normalizeEntry(this.data.tips[tipId]).lastSessionTimestamp}normalizeEntry(raw){if(typeof raw!=="object"||raw===null||Array.isArray(raw)){return{totalShown:0,lastSessionTimestamp:0}}const candidate=raw;return{totalShown:typeof candidate.totalShown==="number"&&Number.isFinite(candidate.totalShown)?candidate.totalShown:0,lastSessionTimestamp:typeof candidate.lastSessionTimestamp==="number"&&Number.isFinite(candidate.lastSessionTimestamp)?candidate.lastSessionTimestamp:0}}recordShown(tipId,currentPromptCount){this.sessionShown.set(tipId,currentPromptCount);const entry=this.normalizeEntry(this.data.tips[tipId]);entry.totalShown++;entry.lastSessionTimestamp=Date.now();this.data.tips[tipId]=entry;this.persist()}persist(){try{const dir=path2.dirname(this.filePath);if(!fs2.existsSync(dir)){fs2.mkdirSync(dir,{recursive:true})}atomicWriteFileSync(this.filePath,JSON.stringify(this.data,null,2),{mode:384,forceMode:true,noFollow:true})}catch{}}static load(){const filePath=path2.join(Storage.getGlobalQwenDir(),"tip_history.json");let data={sessionCount:0,tips:{}};try{if(fs2.existsSync(filePath)){const raw=fs2.readFileSync(filePath,"utf-8");const parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.sessionCount==="number"){data={sessionCount:Number.isFinite(parsed.sessionCount)&&parsed.sessionCount>=0?Math.floor(parsed.sessionCount):0,tips:parsed.tips??{},...typeof parsed.btwUseCount==="number"&&Number.isFinite(parsed.btwUseCount)&&parsed.btwUseCount>0?{btwUseCount:Math.floor(parsed.btwUseCount)}:{}}}}}catch{}data.sessionCount++;data.tips=typeof data.tips==="object"&&data.tips!==null&&!Array.isArray(data.tips)?data.tips:{};const history=new _TipHistory(data,filePath);history.persist();return history}};init_esbuild_shims();function selectTip(trigger,context,tips,history){const candidates=tips.filter(tip=>tip.trigger===trigger).filter(tip=>{try{return tip.isRelevant(context)}catch{return false}}).filter(tip=>history.isCooledDown(tip.id,tip.cooldownPrompts,context.sessionPromptCount));if(candidates.length===0)return null;candidates.sort((a,b)=>{if(b.priority!==a.priority)return b.priority-a.priority;return history.getLastShown(a.id)-history.getLastShown(b.id)});return candidates[0]??null}__name(selectTip,"selectTip");init_esbuild_shims();var tipRegistry=[{id:"context-critical",content:"Context near hard limit \u2014 auto-compact will force on next send. Consider /clear if you want to start fresh.",trigger:"post-response",isRelevant:__name(ctx=>ctx.thresholds!==void 0&&ctx.lastPromptTokenCount>=ctx.thresholds.hard,"isRelevant"),cooldownPrompts:3,priority:100},{id:"context-high",content:"Context is getting full. Use /compress to free up space.",trigger:"post-response",isRelevant:__name(ctx=>ctx.thresholds!==void 0&&ctx.lastPromptTokenCount>=ctx.thresholds.auto&&ctx.lastPromptTokenCount<ctx.thresholds.hard,"isRelevant"),cooldownPrompts:5,priority:90},{id:"compress-intro",content:"Long conversation? /compress summarizes history to free context.",trigger:"post-response",isRelevant:__name(ctx=>ctx.thresholds!==void 0&&ctx.lastPromptTokenCount>=ctx.thresholds.warn&&ctx.lastPromptTokenCount<ctx.thresholds.auto&&ctx.sessionPromptCount>5,"isRelevant"),cooldownPrompts:10,priority:50},{id:"new-user-slash",content:"Type / to open the command popup; Tab autocompletes slash commands and saved prompts.",trigger:"startup",isRelevant:__name(ctx=>ctx.sessionCount<5,"isRelevant"),cooldownPrompts:0,priority:70},{id:"new-user-qwenmd",content:"Add a QWEN.md file to give MiraOS persistent project context.",trigger:"startup",isRelevant:__name(ctx=>ctx.sessionCount<10,"isRelevant"),cooldownPrompts:0,priority:70},{id:"new-user-resume",content:"You can resume a previous conversation by running miraos --continue or miraos --resume.",trigger:"startup",isRelevant:__name(ctx=>ctx.sessionCount<10,"isRelevant"),cooldownPrompts:0,priority:70},{id:"shell-commands",content:"You can run any shell commands from Qwen Code using ! (e.g. !ls).",trigger:"startup",isRelevant:__name(ctx=>ctx.sessionCount<15,"isRelevant"),cooldownPrompts:0,priority:70},{id:"compress-startup",content:"Use /compress when the conversation gets long to summarize history and free up context.",trigger:"startup",isRelevant:__name(()=>true,"isRelevant"),cooldownPrompts:0,priority:50},{id:"approval-mode-win32",content:"You can switch permission mode quickly with Tab or /approval-mode.",trigger:"startup",isRelevant:__name(ctx=>ctx.platform==="win32","isRelevant"),cooldownPrompts:0,priority:50},{id:"approval-mode",content:"You can switch permission mode quickly with Shift+Tab or /approval-mode.",trigger:"startup",isRelevant:__name(ctx=>ctx.platform!=="win32","isRelevant"),cooldownPrompts:0,priority:50},{id:"insight-command",content:"Try /insight to generate personalized insights from your chat history.",trigger:"startup",isRelevant:__name(ctx=>ctx.sessionCount>20,"isRelevant"),cooldownPrompts:0,priority:70},{id:"btw-command",content:"Use /btw to ask a quick side question without disrupting the conversation.",trigger:"startup",isRelevant:__name(()=>true,"isRelevant"),cooldownPrompts:0,priority:50},{id:"clear-new",content:"Start a fresh idea with /clear or /new; the previous session stays available in history.",trigger:"startup",isRelevant:__name(()=>true,"isRelevant"),cooldownPrompts:0,priority:50},{id:"bug-report",content:"Use /bug to submit issues to the maintainers when something goes off.",trigger:"startup",isRelevant:__name(()=>true,"isRelevant"),cooldownPrompts:0,priority:50},{id:"auth-switch",content:"Switch auth type quickly with /auth.",trigger:"startup",isRelevant:__name(()=>true,"isRelevant"),cooldownPrompts:0,priority:50}];var _tipHistory=null;function getTipHistory(){if(!_tipHistory){_tipHistory=TipHistory.load()}return _tipHistory}__name(getTipHistory,"getTipHistory");function recordBtwUse(){_tipHistory?.recordBtwUse()}__name(recordBtwUse,"recordBtwUse");function formatBtwError(error){return t("Failed to answer btw question: {{error}}",{error})}__name(formatBtwError,"formatBtwError");function outcomeToMessage(outcome){switch(outcome.kind){case"answered":return{type:"message",messageType:"info",content:outcome.response};case"tool-call":return{type:"message",messageType:"info",content:formatBtwToolCallNotice(outcome.toolName)};case"empty":return{type:"message",messageType:"info",content:t("No response received.")};case"unavailable":return{type:"message",messageType:"error",content:formatBtwError(t("No conversation context available for /btw"))};case"failed":return{type:"message",messageType:"error",content:formatBtwError(outcome.error)};case"cancelled":default:return{type:"message",messageType:"error",content:formatBtwError(t("Cancelled"))}}}__name(outcomeToMessage,"outcomeToMessage");var btwCommand={name:"btw",get description(){return t("Ask a quick side question without affecting the main conversation")},kind:"built-in",supportedModes:["interactive","acp"],action:__name(async(context,args)=>{const question=args.trim();const{config}=context.services;const interactive=(context.executionMode??"interactive")==="interactive";if(!question){const session2=config&&interactive?getBtwSession(config):null;const reopenId=session2?.getReopenTargetId();if(session2&&reopenId){showBtwRequest(context.ui,session2,reopenId);return}return{type:"message",messageType:"error",content:t("Please provide a question. Usage: /btw <your question>")}}if(question.length>BTW_MAX_INPUT_LENGTH){return{type:"message",messageType:"error",content:t("Question too long (max {{max}} chars)",{max:String(BTW_MAX_INPUT_LENGTH)})}}if(!config){return{type:"message",messageType:"error",content:t("Config not loaded.")}}if(!config.getModel()){return{type:"message",messageType:"error",content:t("No model configured.")}}const session=getBtwSession(config);if(!interactive){const{done}=session.ask(question,{signal:context.abortSignal});return outcomeToMessage(await done)}recordBtwUse();const{id}=session.ask(question);showBtwRequest(context.ui,session,id)},"action")};init_esbuild_shims();var bugCommand={name:"bug",get description(){return t("submit a bug report")},kind:"built-in",argumentHint:"<description>",supportedModes:["interactive","non_interactive","acp"],canRunDuringStreaming:true,action:__name(async(context,args)=>{const bugDescription=(args||"").trim();const systemInfo=await getExtendedSystemInfo(context);const fields=getSystemInfoFields(systemInfo);const info=fields.map(field=>`${field.label}: ${field.value}`).join("\n");let bugReportUrl="https://github.com/QwenLM/qwen-code/issues/new?template=bug_report.yml&title={title}&info={info}";const bugCommandSettings=context.services.config?.getBugCommand();if(bugCommandSettings?.urlTemplate){bugReportUrl=bugCommandSettings.urlTemplate}bugReportUrl=bugReportUrl.replace("{title}",encodeURIComponent(bugDescription)).replace("{info}",encodeURIComponent(`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{appEvents}from"./chunk-
|
|
3
|
+
import{appEvents}from"./chunk-MMGNOY3U.js";import{assembleMcpServers,getPendingGatedMcpServers,getPromptableMcpServers}from"./chunk-SHKSVOTG.js";import{getMCPServerStatus}from"./chunk-MJEL7DIE.js";import{require_fast_deep_equal}from"./chunk-7LLG2W7I.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var debugLogger=createDebugLogger("MCP_HOT_RELOAD");var modelProvidersDebugLogger=createDebugLogger("MODEL_PROVIDERS_HOT_RELOAD");function mcpServersEqual(a,b){return(0,import_fast_deep_equal.default)(a??{},b??{})}__name(mcpServersEqual,"mcpServersEqual");function mcpGatingEqual(a,b){const norm=__name(xs=>[...xs??[]].sort(),"norm");const allowedEqual=a.allowed===void 0===(b.allowed===void 0)&&(0,import_fast_deep_equal.default)(norm(a.allowed),norm(b.allowed));return(0,import_fast_deep_equal.default)(norm(a.excluded),norm(b.excluded))&&allowedEqual&&(0,import_fast_deep_equal.default)(norm(a.pending),norm(b.pending))}__name(mcpGatingEqual,"mcpGatingEqual");function recomputeMcpGating(settings,assembled,cwd,bootAllowed,isYolo){const settingsAllowed=settings.merged.mcp?.allowed?.filter(Boolean);const excluded=settings.merged.mcp?.excluded?.filter(Boolean);let allowed=settingsAllowed;if(bootAllowed){allowed=settingsAllowed?settingsAllowed.filter(n=>bootAllowed.includes(n)):[...bootAllowed]}return{allowed,excluded:excluded&&excluded.length>0?excluded:void 0,pending:isYolo?void 0:getPendingGatedMcpServers(assembled,cwd)}}__name(recomputeMcpGating,"recomputeMcpGating");function registerMcpHotReload(watcher,settings,config,topTierMcpServers){debugLogger.debug("registered MCP hot-reload listener on SettingsWatcher");return watcher.addChangeListener(async events=>{debugLogger.debug(`settings change fired (${events.length} event(s)): ${events.map(e=>`${e.scope}:${e.changeType}`).join(", ")}`);const cwd=config.getTargetDir();const next=config.getBareMode()||config.isSafeMode()?{...topTierMcpServers}:assembleMcpServers(settings.merged.mcpServers,cwd,topTierMcpServers);const isYolo=config.getApprovalMode()==="yolo";const bootAllowed=config.getCliAllowedMcpServerNames();const nextGating=config.getBareMode()||config.isSafeMode()?{allowed:bootAllowed?[...bootAllowed]:void 0}:recomputeMcpGating(settings,next,cwd,bootAllowed,isYolo);const prevServers=config.getSettingsMcpServers();const prevGating=config.getMcpGating();debugLogger.debug(`assembled servers: prev=[${Object.keys(prevServers??{}).join(", ")}] next=[${Object.keys(next).join(", ")}]`);debugLogger.debug(`gating next: excluded=[${(nextGating.excluded??[]).join(", ")}] allowed=[${(nextGating.allowed??[]).join(", ")}] pending=[${(nextGating.pending??[]).join(", ")}]`);const serversChanged=!mcpServersEqual(prevServers,next);const gatingChanged=!mcpGatingEqual(prevGating,nextGating);if(!serversChanged&&!gatingChanged){debugLogger.debug("no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile");return}debugLogger.debug(`MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`);const promptable=getPromptableMcpServers(next,cwd);config.setExcludedMcpServers(nextGating.excluded??[]);config.setAllowedMcpServers(nextGating.allowed);config.setPendingMcpServers(nextGating.pending);try{await config.reinitializeMcpServers(next);const finalStatuses=Object.keys(next).map(name=>`${name}=${getMCPServerStatus(name)}`).join(", ");debugLogger.debug(`reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`)}catch(err){debugLogger.error(`reinitializeMcpServers threw: ${err instanceof Error?err.stack??err.message:String(err)}`);appEvents.emit("log-error","Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details.")}if(!isYolo&&promptable.length>0){debugLogger.debug(`gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed"}: [${promptable.join(", ")}]`);appEvents.emit("mcp-pending-approval-changed")}})}__name(registerMcpHotReload,"registerMcpHotReload");function registerModelProvidersHotReload(watcher,settings,config){modelProvidersDebugLogger.debug("registered modelProviders hot-reload listener on SettingsWatcher");let refreshAuthRetryPending=false;const reconcile=__name(async()=>{const next=settings.merged.modelProviders;const providersUnchanged=(0,import_fast_deep_equal.default)(config.getModelProvidersConfig()??{},next??{});if(providersUnchanged&&!refreshAuthRetryPending){return}if(!providersUnchanged){modelProvidersDebugLogger.debug("modelProviders changed \u2014 reloading model registry");try{config.reloadModelProvidersConfig(next)}catch(err){modelProvidersDebugLogger.error(`reloadModelProvidersConfig threw: ${err instanceof Error?err.stack??err.message:String(err)}`);return}}const authType=config.getAuthType();if(!authType){return}try{await config.refreshAuth(authType,true);refreshAuthRetryPending=false}catch(err){const alreadyPending=refreshAuthRetryPending;refreshAuthRetryPending=true;modelProvidersDebugLogger.error(`refreshAuth after modelProviders reload threw: ${err instanceof Error?err.stack??err.message:String(err)}`);if(!alreadyPending){appEvents.emit("log-error",`Model provider settings reloaded, but re-authenticating the active model failed: ${err instanceof Error?err.message:String(err)}. Select a model with /model or restart to apply the change.`)}}},"reconcile");void reconcile();return watcher.addChangeListener(reconcile)}__name(registerModelProvidersHotReload,"registerModelProvidersHotReload");export{recomputeMcpGating,registerMcpHotReload,registerModelProvidersHotReload};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen
|