@comate/zulu 1.3.2-beta.1 → 1.3.3
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/comate-engine/assets/skills/create-image-comate/SKILL.md +11 -8
- package/comate-engine/assets/skills/get-ugate-token-comate/SKILL.md +12 -12
- package/comate-engine/assets/skills/ku-operator-comate/SKILL.md +35 -7
- package/comate-engine/assets/skills/ku-operator-comate/examples.md +13 -0
- package/comate-engine/assets/skills/ku-operator-comate/scripts/ku_operator.py +35 -18
- package/comate-engine/node_modules/@baidu/comate-browser-use/dist/adapter-chrome/index.js +14986 -0
- package/comate-engine/node_modules/@baidu/comate-browser-use/dist/adapter-vscode/index.js +7460 -0
- package/comate-engine/node_modules/@baidu/comate-browser-use/dist/core/index.js +5388 -0
- package/comate-engine/node_modules/@baidu/comate-browser-use/dist/index.js +82228 -0
- package/comate-engine/node_modules/@baidu/comate-browser-use/dist/launch-chrome/index.js +73409 -0
- package/comate-engine/node_modules/@baidu/comate-browser-use/package.json +69 -0
- package/comate-engine/server.js +1 -1
- package/dist/bundle/index.js +2 -2
- package/package.json +1 -1
package/comate-engine/server.js
CHANGED
|
@@ -533,7 +533,7 @@ const path$7=path__default$1,util$8=t$1,isNaturalNumber=isNaturalNumber$1;var st
|
|
|
533
533
|
${e.map((e=>`- ${e}`)).join("\n")}
|
|
534
534
|
|
|
535
535
|
Note: Prefer using absolute paths over relative paths as tool call args when possible.
|
|
536
|
-
`}buildStaticContexts(e,t,r){const n=r.map((e=>({type:"GIT_STATUS",content:e})));return[...n,{type:"ENV",content:this.buildEnvDescription(e,t.defaultShell,t.os)}]}async buildStaticContextsAsync(e){const[t,r]=await Promise.all([safePromise(this.getSysInfo(e[0]),getDefaultSysInfo(e[0])),safePromise(getGitStatusDescriptionForMultiple(e),GIT_STATUS_ERROR_MESSAGE)]);return this.buildStaticContexts(e,t,r)}async buildUploadBaseInfo(e){const t=osName(),[r,n]=await Promise.all([getRepoName(e).catch((()=>"")),getCurrentBranch(e).catch((()=>""))]);return{os:getOsName(),osVersion:t,extName:kernel.env.ideName,extVersion:kernel.env.extensionVersion,ideType:kernel.env.ideSeries,ideName:kernel.env.ideName,ideVersion:kernel.env.ideVersion,vcsType:r?"git":void 0,vcsRepo:r,vcsBranchName:n,username:kernel.config.username,license:kernel.config.license,pluginVersion:kernel.env.extensionVersion,device:kernel.env.deviceId,triggerSource:"MISSION"===kernel.env.mode?"MISSION":""}}start(e){const t=this.params,r=this.buildSystemReminder(e.agent.agentId,e.agent.agentName);this.params=void 0,this.quotaExceedMessage="";const{query:n,modelKey:i,rootPath:o,rootPaths:s,agent:a,knowledges:c,rejectedFiles:A,selfDefineInstruction:l,rollbackMessageId:u,useCodebaseSearch:d,sessionStartContextPromise:h,appendSystemPrompt:p,channel:g,...f}=e;this.rootPath=o,this.rootPaths=s||[o];const m={agentId:a.agentId,agentName:a.agentName,isProjectAgent:!!a.isProjectAgent};kernel.logger.info("[Zulu] ParameterCollector start"),this.promise=Promise.all([safePromise(apiPostConvesation({...f,agentInfo:m}),{conversationId:-1,taskId:void 0,traceId:f.traceId},6e5),safePromise(this.getSysInfo(this.rootPath),getDefaultSysInfo(this.rootPath)),safePromise(this.getMcpServers(this.getAgentMcpServers(a)),[]),safePromise(hasCurrentCodebaseIndexed(),!1,6e4),safePromise(contextsFromWebview2AgentContext(c,A,o,this.virtualEditor,f.traceId),[]),safePromise(getGitStatusDescriptionForMultiple(this.rootPaths),GIT_STATUS_ERROR_MESSAGE),safePromise(getAllSkillMetadata(o,this.mcpManager),[]),safePromise(getAllAgents(o,!0),[]),safePromise(this.buildUploadBaseInfo(o),{}),safePromise(fetchQuota({key:kernel.config.key}),void 0),h??Promise.resolve(void 0),safePromise(iocContainer.get(FeatureSetProvider).getFeatures(["en_verif_sub"]),{})]).then((e=>{const o=e[0],s=e[1],A=e[2],h=e[3],E=e[4],C=e[5],I=e[6],y=e[7],B=e[8],b=e[9],w=this.detectSkillChanges(I),v=e[10],S=e[11];b?.exceeded&&(this.quotaExceedMessage=JSON.stringify(b.userActions));const Q=a.subagents?.map((e=>ProjectAgent.pickTaskProperties(e,A)))??[],_=y.map((e=>({agentName:e.name,description:e.description,isProjectAgent:!0,agentPrompt:e.agentPrompt,toolNames:e.toolNames,disallowedToolNames:e.disallowedToolNames}))),D=this.buildStaticContexts(this.rootPaths,s,C);this.knowledgeContexts=findNearestContextInAllRoundtrips(this.conversationAccessor?.getAllRoundtrips(),isKnowlegeContext),t||E.push(...D);const x=c.filter(isKnowlegeContext);x.length&&E.push(buildKnowledgeSummary(x)),l&&E.push({type:"SLASH_COMMAND",...l});const k={commands:c.filter((e=>e.type===ContextType.SLASH_COMMAND)).map((e=>e.name||e.id)),skills:c.filter((e=>e.type===ContextType.SELECT_SKILL)).map((e=>e.name||e.id)),subagents:c.filter((e=>e.type===ContextType.SELECT_SUBAGENT)).map((e=>e.name||e.id)),rules:[]},R={isMultiWorkspace:this.rootPaths.length>1},T=S.en_verif_sub,$=T?.enabled&&T?.value,N={taskId:o.taskId,conversationId:o.conversationId,agentId:a.agentId,uploadBaseInfo:B,query:n,modelKey:i,sysInfo:s,skillInfos:w?I:void 0,isUserQuery:!0,isMockQuery:!!f.isMockQuery,localIndex:h,contexts:E,mode:getAgentMode(a.agentId),signal:f.signal,traceId:f.traceId,rollbackMessageId:u,toolUseResults:[],subAgents:[...Q,Explore,General,...$?[Verification]:[],...this.knowledgeContexts.length?[DocExplore]:[],..._],agentInfo:m,agentVersion:5,isFirstQuery:!t,systemReminder:v?`${v}\n${r}`:r,extendUserQueryInfo:k,extend:R};return isZuluCli&&(d&&(R.useCodebaseSearch=!0),p&&(N.appendSystemPrompt=p),g&&(N.channel=g)),this.params=N,kernel.logger.info(`[Zulu] ParameterCollector finished, taskId=${N.taskId}`),N}))}async resume(e){if(!this.params)return;const{query:t="",agent:r,knowledgeList:n,isMockQuery:i=!1,...o}=e;if(this.params.query=t,t&&(this.params.isUserQuery=!0),void 0!==r){const e=this.buildSystemReminder(r.agentId,r.agentName);this.params.agentId=r.agentId,this.params.agentInfo={agentId:r.agentId,agentName:r.agentName,isProjectAgent:!!r.isProjectAgent},this.params.systemReminder=e}void 0!==n&&(this.params.contexts=await contextsFromWebview2AgentContext(n,[],this.rootPath,this.virtualEditor,this.params.traceId)),this.params.isMockQuery=i,this.updateParams(o)}async getAllRules(e){if(!this.rootPath||!this.conversationAccessor)return[];const t=this.virtualEditor,r=await getAllRules(this.rootPath,t);if(!r?.length)return[];const n=this.conversationAccessor.getLatestRoundtrip(),{globRules:i,alwaysApplyRules:o,selectRules:s,quoteRules:a}=collectCurrentRoundRules(r,n,this.rootPath,!!e),c=this.getAppliedRulesWithContext(e),A=new Map;for(const e of r){const t=getRuleSubtypeV2(e.metadata);A.set(`${t}:${e.path}`,e)}const l=[],u=[],d=[];for(const e of c){const t=`${e.type}:${e.path}`,r=A.get(t);r&&(e.type===GLOB_MATCHED_RULE?l.push(r):e.type===ALWAYS_APPLIED_RULE?u.push(r):e.type===SELECTED_RULE&&d.push(r))}const h=_$H.uniqBy([...i,...l],(e=>`${GLOB_MATCHED_RULE}:${e.path}`)),p=_$H.uniqBy([...o,...u],(e=>`${ALWAYS_APPLIED_RULE}:${e.path}`)),g=_$H.uniqBy([...s,...d],(e=>`${SELECTED_RULE}:${e.path}`)),f=[...h.map((e=>({type:GLOB_MATCHED_RULE,...e}))),...p.map((e=>({type:ALWAYS_APPLIED_RULE,...e}))),...s.map((e=>({type:SELECTED_RULE,...e})))];this.updateAppliedRulesWithContext(f,{deleteRules:[],mode:"override",ruleAccessor:e});return buildRuleContexts({globRules:h,alwaysApplyRules:p,selectRules:g,quoteRules:_$H.uniq([...a,...d.map((e=>e.name))]),diffRules:[],isFirst:!0})}isRuleAlreadyInserted(e,t){return e.includes(`<rule name="${t}"`)}getAppliedRulesWithContext(e){return e?.getLatestAppliedRules()??this.conversationAccessor?.getLatestAppliedRules()??[]}updateAppliedRulesWithContext(e,t){const{deleteRules:r,mode:n,ruleAccessor:i}=t??{};i?i.updateLatestAppliedRules(e,r,n):this.conversationAccessor?.updateLatestAppliedRules(e,r,n)}processToolResultsWithRules(e,t,r){if(!this.rootPath||!this.conversationAccessor)return e;const n=new Set,i=[];for(const r of e){const e=r.params.target_file;if("read_file"===r.name&&r.success&&e){const o=path__default$1.isAbsolute(e)?path__default$1.relative(this.rootPath,e):e,{globRules:s}=getActiveRules(this.rootPath,t,[e,o]),a=r.message||"",c=s.filter((e=>!n.has(e.path)&&!this.isRuleAlreadyInserted(a,e.name)));if(c.length>0){c.forEach((e=>n.add(e.path))),i.push(...c);const e=c.map((e=>buildRuleContent(e))).join("\n\n");r.message=a+"\n\n"+e}}}if(i.length>0){const e=i.map((e=>({type:GLOB_MATCHED_RULE,...e})));this.updateAppliedRulesWithContext(e,{ruleAccessor:r})}return e}processContextWithRules(e,t,r){if(!this.conversationAccessor)return e;const{ruleContexts:n,allCurrentRules:i,deleteRules:o}=processWorkspaceRules({rules:t,latestRoundtrip:this.conversationAccessor.getLatestRoundtrip(),latestAppliedRules:this.getAppliedRulesWithContext(r),isFirst:!this.conversationAccessor.getPreviousRoundtrip(),rootPath:this.rootPath,skipUserKnowledge:!!r});return this.updateAppliedRulesWithContext(i,{deleteRules:o,ruleAccessor:r}),[...e,...n]}extractRulePathsFromContexts(e){const t=new Set,r=new Set(["ALWAYS_APPLIED_RULE","ALWAYS_ADD_RULE","GLOB_MATCHED_RULE","DIFF_RULE"]);for(const n of e)r.has(n.type)&&"path"in n?t.add(n.path):"QUOTE_RULE"===n.type&&n.content.split("\n").forEach((e=>{t.add(e.replace(/^- /,""))}));return Array.from(t)}async getDynamicParams(e=!1,t,r){if(!this.rootPath||!this.conversationAccessor)return t;if(e){const[e,n,i,o]=await Promise.all([safePromise(this.getAllRules(r),[]),safePromise(this.getSysInfo(this.rootPath),getDefaultSysInfo(this.rootPath)),safePromise(getGitStatusDescriptionForMultiple(this.rootPaths),GIT_STATUS_ERROR_MESSAGE),safePromise(getAllSkillMetadata(this.rootPath,this.mcpManager),[])]);this.cachedSkillFingerprint=null,this.detectSkillChanges(o);const s=this.buildStaticContexts(this.rootPaths,n,i);return{...t,skillInfos:o,contexts:[...t.contexts||[],...s,...e]}}const n=await getAllRules(this.rootPath,this.virtualEditor),i=t.toolUseResults.length?this.processToolResultsWithRules(t.toolUseResults,n,r):t.toolUseResults;if(t.isUserQuery){const e=this.processContextWithRules(t.contexts,n,r),o=t.extendUserQueryInfo?{...t.extendUserQueryInfo,rules:this.extractRulePathsFromContexts(e)}:void 0;return{...t,contexts:e,toolUseResults:i,...o&&{extendUserQueryInfo:o}}}const o=await safePromise(getAllSkillMetadata(this.rootPath,this.mcpManager),[]),s=this.buildSkillFingerprint(o),a=null!==this.cachedSkillFingerprint&&s!==this.cachedSkillFingerprint;return a&&(this.cachedSkillFingerprint=s),{...t,contexts:t.contexts,toolUseResults:i,skillInfos:a?o:void 0}}}const FILE_MODIFICATION_TOOLS=["write_file","edit_file","delete_file"];class SpecEditorV2{_roundtrips;getStatus;mediator;conversationId;tabInfo={doc:{status:SpecTabStatus.IDLE},tasks:{status:SpecTabStatus.IDLE},changes:{status:SpecTabStatus.IDLE},summary:{status:SpecTabStatus.IDLE}};cachedSessionId="";isSpecSession=!1;constructor(e,t,r,n){this._roundtrips=e,this.getStatus=t,this.mediator=r,this.conversationId=n}get isSpec(){const e=this.roundtrips[0];return!!e&&12===e.request.payload.agent?.agentId}get specSessionId(){return this.getOrGenerateSessionId()}get hasDocFile(){return!!this.tabInfo.doc.path}get hasTasksFile(){return!!this.tabInfo.tasks.path}get hasSummaryFile(){return!!this.tabInfo.summary.path}get hasContent(){return this.hasDocFile||this.hasTasksFile||this.hasSummaryFile||this.tabInfo.changes.status!==SpecTabStatus.IDLE}get roundtrips(){return this._roundtrips.filter((e=>!e.discard))}static deriveConversationStatus(e=[]){const t=e[e.length-1];return t&&"assistant"===t.role?SpecEditorSessionStatus.Error:SpecEditorSessionStatus.Loading}beforeStartWork(){this.isSpec&&(this.pausePendingOrGeneratingTabs(),this.syncSpecProgress(SpecIconState.GENERATING))}afterStartWork(){if(!this.isSpec)return;this.pauseGeneratingTabs();const e=this.getCurrentIconState();this.syncSpecProgress(e)}async openSpecEditor(e,t=!1){const r=this.specSessionId,n=this.getCurrentIconState(),i={...this.tabInfo};i.changes={status:i.changes.status,diffInfo:this.getChangesFiles()};const o=this.roundtrips[0],s=o?.request.summary||o?.request.payload.query;await(this.mediator.specCommunicationService?.sendStateChanged({type:"FULL_STATE_SYNC",payload:{specSessionId:r,sessionName:s??"",iconState:n,activeTabIndex:this.getActiveStepIndex(e),open:!0,tabInfo:{doc:this.tabInfo.doc,tasks:this.tabInfo.tasks,changes:i.changes,summary:this.tabInfo.summary,preview:this.tabInfo.preview||{}},currentFile:e,isReRender:t}}))}beforeRollback(){this.isSpecSession=this.isSpec}async afterRollback(){if(0===this.roundtrips.length&&this.mediator.specCommunicationService?.syncSessionDeleted(this.conversationId,this.isSpecSession),!this.isSpecSession)return;const e=this.hasContent;this.rebuild(),e&&await this.openSpecEditor("",!0);const t=this.getCurrentIconState();await this.syncSpecProgress(t),0===this.roundtrips.length&&(this.cachedSessionId="")}rebuild(){if(!this.isSpecSession&&!this.isSpec)return;const e=this.collectModifiedFiles().map((e=>e.absolutePath)).reverse(),t=e.find(isSummaryFile),r=e.find(isDocFile),n=e.find(isTasksFile),i=e.filter(isNotSpecMarkdownFile),o=this.getCurrentPendingDocOrTasksPath(),s=this.rebuildSummaryTabStatus(t),a=this.rebuildChangesTabStatus(s,i),c=this.rebuildTasksTabStatus(a,n,o),A=this.rebuildDocTabStatus(c,r,o);this.tabInfo={doc:{status:A,path:r},tasks:{status:c,path:n},changes:{status:a},summary:{status:s,path:t}}}async afterFileChange(e){if(!this.isSpec)return;if(!("string"==typeof e.result.metadata.content))return;const t=this.hasContent,r=e.absolutePath;isSpecMarkdownFile(r)&&(e instanceof EditFile||e instanceof WriteFile)?await this.handleSpecMarkdownChange(e):(this.tabInfo.tasks.path&&await this.updateTabStatus("tasks",SpecTabStatus.EXECUTING),this.tabInfo.changes.status=SpecTabStatus.GENERATING,await this.syncTabStatus("changes")),this.hasContent&&!t&&await this.openSpecEditor(r,!0)}async afterGenerateQuerySummary(e,t){if(!this.isSpec)return;if(!(t===this.roundtrips[0]))return;const r=this.specSessionId;await(this.mediator.specCommunicationService?.sendStateChanged({type:"SESSION_TITLE_UPDATED",payload:{specSessionId:r,title:e}}))}async syncConversationState(){await(this.mediator.specCommunicationService?.syncConversationInfo(this.conversationId))}getCurrentPendingDocOrTasksPath(){const e=this.roundtrips[this.roundtrips.length-1];if(!e)return;const t=e.getLastToolTurnTools().filter(isSpecDocOrTasksFilePendingReview).pop();return t?.result.metadata.absolutePath}async handleSpecMarkdownChange(e){const t=e.absolutePath,r=e.result.metadata.askReview;if(isDocFile(t)){const e=r?SpecTabStatus.PENDING:SpecTabStatus.QUEUED;this.tabInfo.doc.path=t,this.tabInfo.doc.status=e,await this.updateTabStatus("doc",e)}else if(isTasksFile(t)){this.tabInfo.doc.path&&this.updateTabStatus("doc",SpecTabStatus.DONE);const e=this.tabInfo.tasks,n=r?SpecTabStatus.PENDING:e.status===SpecTabStatus.EXECUTING?SpecTabStatus.EXECUTING:SpecTabStatus.QUEUED;e.path=t,this.updateTabStatus("tasks",n)}else isSummaryFile(t)&&(this.tabInfo.summary.path=t,this.updateTabStatus("tasks",SpecTabStatus.DONE),this.updateTabStatus("changes",SpecTabStatus.DONE),this.updateTabStatus("summary",SpecTabStatus.DONE))}getOrGenerateSessionId(){if(this.cachedSessionId)return this.cachedSessionId;for(let e=this.roundtrips.length-1;e>=0;e--){const t=this.roundtrips[e]?.request.payload.specSessionId;if(t)return this.cachedSessionId=t,t}return this.cachedSessionId=randomUUID(),this.cachedSessionId}getCurrentIconState(){switch(this.getStatus()){case AgentConversationStatus.Running:return SpecIconState.GENERATING;case AgentConversationStatus.Cancelled:return SpecIconState.CANCELLED;case AgentConversationStatus.Completed:return Object.values(this.tabInfo).some((e=>e?.status===SpecTabStatus.PENDING))?SpecIconState.PENDING:SpecIconState.COMPLETED;default:return SpecIconState.ERROR}}collectModifiedFiles(){const e=new Map;for(const t of this.roundtrips)for(const r of t.getAllToolTurnTools()){if(!FILE_MODIFICATION_TOOLS.includes(r.name)||"executed"!==r.toolState)continue;const t=r.result.metadata,n=t.absolutePath;if(!n)continue;const i=t.originalContent||"",o=t.content||"",s=e.get(n);e.set(n,{absolutePath:n,source:s?s.source:i,content:o})}return Array.from(e.values())}getActiveStepIndex(e){if(!e){const e=this.tabInfo.tasks.status;return e===SpecTabStatus.PENDING||e===SpecTabStatus.EXECUTING?1:0}return e===this.tabInfo.preview?.path?4:e===this.tabInfo.doc.path?0:e===this.tabInfo.tasks.path?1:e===this.tabInfo.summary.path?3:2}getChangesFiles(){return this.collectModifiedFiles().filter((e=>isNotSpecMarkdownFile(e.absolutePath)))}async updateTabStatus(e,t){const r=this.tabInfo[e];r&&r.status!==t&&(r.status=t,await this.syncTabStatus(e))}async syncTabStatus(e){const t=this.specSessionId,r=this.tabInfo[e];if(!r)return;const n="changes"!==e&&"path"in r?r.path:void 0,i="changes"===e?this.getChangesFiles():void 0;await(this.mediator.specCommunicationService?.sendStateChanged({type:"TAB_STATUS_UPDATED",payload:{specSessionId:t,tabType:e,status:r.status,path:n,diffInfo:i}}));const o={doc:{loading:"spec/start",end:"spec/docEnd"},tasks:{loading:"spec/taskCreateStart",end:"spec/taskCreateEnd"},summary:{loading:"spec/taskExecuteEnd ",end:"spec/end"}}[e]?.[r.status];o&&sendIdeEventLog(o,{sessionId:t})}async pausePendingOrGeneratingTabs(){for(const e of["doc","tasks","changes","summary"]){const t=this.tabInfo[e];t&&(t.status!==SpecTabStatus.PENDING&&t.status!==SpecTabStatus.GENERATING||await this.updateTabStatus(e,SpecTabStatus.QUEUED))}}async pauseGeneratingTabs(){for(const e of["doc","tasks","changes","summary"]){const t=this.tabInfo[e];t&&t.status===SpecTabStatus.GENERATING&&await this.updateTabStatus(e,SpecTabStatus.QUEUED)}}rebuildSummaryTabStatus(e){return e?SpecTabStatus.DONE:SpecTabStatus.IDLE}rebuildChangesTabStatus(e,t){return e===SpecTabStatus.DONE?SpecTabStatus.DONE:t.length>0?SpecTabStatus.QUEUED:SpecTabStatus.IDLE}rebuildTasksTabStatus(e,t,r){return r&&t===r?SpecTabStatus.PENDING:e===SpecTabStatus.DONE?SpecTabStatus.DONE:e===SpecTabStatus.QUEUED?SpecTabStatus.EXECUTING:t?SpecTabStatus.QUEUED:SpecTabStatus.IDLE}rebuildDocTabStatus(e,t,r){return r&&t===r?SpecTabStatus.PENDING:e!==SpecTabStatus.IDLE?SpecTabStatus.DONE:t?SpecTabStatus.QUEUED:SpecTabStatus.IDLE}async syncSpecProgress(e){const t=this.collectHistoryTasks();await(this.mediator.specCommunicationService?.sendStateChanged({type:"SPEC_PROGRESS_UPDATED",payload:{specSessionId:this.specSessionId,iconStatus:e,historyTasks:t}}))}collectHistoryTasks(){const e=[];for(const t of this.roundtrips){const r=t.request.uuid;if(!r)continue;const n=t.request.payload.specExecutionTasks;n&&n.length>0&&e.push({userMessageId:r.toString(),tasks:n})}return e}}class AgentConversation extends ConversationThread{context;mcpManager;codeWrittenMetric;type=AgentConversationType.AgentConversation;inlineDiffView=!0;status=AgentConversationStatus.Ready;statistics=new AgentStatistics;token=new Token(this.id);parameterCollector;fileConsistencyChecker;executor=null;specEditor;commandResultQueue=[];constructor(e,t,r){super(e),this.context=e,this.mcpManager=t,this.codeWrittenMetric=r,this.status=AgentConversationStatus.Running,this.fileConsistencyChecker=new FileConsistencyChecker(this.virtualEditor,this.repo),this.parameterCollector=new ParameterCollector(this.mcpManager,this.virtualEditor),this.parameterCollector.setConversationAccessor(this.createConversationAccessor()),this.specEditor=new SpecEditorV2(this.roundtrips,(()=>this.status),this.mediator,this.id)}createConversationAccessor(){return{getLatestRoundtrip:()=>this.latestRoundtrip,getPreviousRoundtrip:()=>this.previousRoundtrip,getAllRoundtrips:()=>this.roundtrips,getLatestAppliedRules:()=>this.latestAppliedRules,updateLatestAppliedRules:(e,t,r)=>this.updateLatestAppliedRules(e,t,r)}}get metrics(){const e=this.latestRoundtrip.request.metrics,t=this.latestRoundtrip.request.payload?.model?.modelId||"Auto",r=this.latestRoundtrip.request.metrics?.path;return{...e,path:r,modelKey:t}}get agent(){return this.latestRoundtrip.request.payload.agent||DEFAULT_AGENT}firstTokenStartTime=0;sessionHookFired=!1;sessionEndFired=!1;sessionStartContextPromise;rollbackMessageId=void 0;icafeIssueId;updateSessionMeta=async e=>{Object.assign(this,e);const t=await this.chatSessionManager.find(this.id);t?.sessionUuid&&await this.chatSessionManager.save({...t,...e})};async startWork(e){this.startConversation(),this.firstTokenStartTime=performance.now();const t=e.request.payload;updateLastUsedKnowledgeContext(t.knowledgeList);const r=this.previousRoundtrip;let n,i,o=[],s=[];r&&(n=r.context.conversationId,i=r.context.taskId,o=getAdoptedFileStatusFromToolTurns(r.toolTurns),s=await this.getLastToolTurnResults(r.toolTurns),this.latestRoundtrip.appliedRules=r?.appliedRules??[]),this.fileConsistencyChecker.markCodeSelectionsAsRead(t.knowledgeList);const a=this.rollbackMessageId,c=await transformQuery(e.request.payload.query,t.knowledgeList);this.parameterCollector.start({knowledges:[...t.knowledgeList,...this.takeCommandResults()],rollbackMessageId:a,rejectedFiles:o,agent:this.agent,query:c,modelKey:e.request.payload.model?.modelId||"Auto",isMockQuery:e.request.payload.isMockQuery,rootPath:this.repo.rootPath,rootPaths:this.repo.rootPaths,conversationId:n,taskId:i,signal:this.token.signal,traceId:this.id,useCodebaseSearch:t.useCodebaseSearch,sessionStartContextPromise:this.sessionStartContextPromise,appendSystemPrompt:t.appendSystemPrompt,channel:t.channel,selfDefineInstruction:t.selfDefineInstruction?{name:t.command,isOfficial:!!t.command,content:t.selfDefineInstruction}:void 0}),this.updateAllMessages(),this.token.onNotify(this.handleTokenNotification.bind(this)),this.stream({toolUseResults:s});try{await this.token.waitForCompletion()}catch(e){const t=e instanceof Error?e.message:e?.toString()??"unknown error";"cancel"!==t&&(this.logger.error("AgentConversation error:",t),this.handleConversationError(t))}finally{await this.finalizeConversation(a),this.endConversation()}}async finalizeConversation(e){const t=this.latestRoundtrip.context.taskId;t&&await this.latestRoundtrip.calculateTokenUsage({taskId:t}),e&&await removeDiscardMsgAfterConsumed(this.id,this.chatSessionManager)}async getLastToolTurnResults(e){if(0===e.length)return[];const t=e[e.length-1],r=hasStreamBreakingTool(t.tools);return t.token.state===TokenNotifyState.CANCELLED||r?Promise.all(t.tools.map((async e=>{const t=isSpecDocOrTasksFilePendingReview(e)?await buildSpecFileToolSystemReminder(e,this.virtualEditor):void 0,r=e.result?.metadata?.hookSystemReminder,n=t||r||void 0;return{id:e.toolId,name:e.name,success:"executed"===e.toolState,params:e.toolHandler.params,message:e.result?e.result.output:ToolError.common.execution_aborted,result:getToolResultExtraContent(e),systemReminder:n}}))):[]}get latestRoundtrip(){return this.roundtrips[this.roundtrips.length-1]}handleTokenNotification(e){if("update"===e.name&&this.latestRoundtrip.updateWebviewMessages(),"command-result-ready"===e.name){const t=e.payload;return this.commandResultQueue.push(t),void this.autoResumeIfCompleted()}if("resume-stream"!==e.name){if(e.token.parent===this.token&&this.token.state!==TokenNotifyState.CANCELLED){const t=e.payload;if("completed"===e.name){const e=t?.map((e=>{const t=e.metadata.tool;return this.parameterCollector.collectTouchedAbsolutePathsAfterToolExecuted(t),{id:t.toolId,name:t.name,success:"executed"===t.toolState,params:t.toolHandler.params,truncatedMessage:getTruncatedMessage(t),result:getToolResultExtraContent(t),message:e.output,systemReminder:t.result?.metadata?.hookSystemReminder}})),r=t?.map((e=>e.metadata.tool));hasStreamBreakingTool(r)?this.token.break([]):this.stream({toolUseResults:e})}}}else this.resumeStream(e.payload)}async resumeStream(e){try{this.updateStatus(AgentConversationStatus.Running),this.startConversation();const t=await this.getLastToolTurnResults(this.latestRoundtrip.toolTurns);await this.parameterCollector.resume(e),this.stream({toolUseResults:t}),await this.token.waitForCompletion(),this.updateStatus(AgentConversationStatus.Completed),this.autoResumeIfCompleted()}catch(e){this.logger.error("AgentConversation error:",e),this.updateStatus(AgentConversationStatus.Failed)}finally{await this.finalizeConversation(this.rollbackMessageId),this.endConversation()}}async stream(e){const t=await this.parameterCollector.getParams();this.parameterCollector.quotaExceedMessage&&(this.latestRoundtrip.quotaExceedMessage=this.parameterCollector.quotaExceedMessage),this.latestRoundtrip.context.conversationId=t.conversationId,this.latestRoundtrip.context.taskId=t.taskId,this.beforeStream(t),t.isUserQuery&&(this.executor=null),this.executor||(this.executor=new AgentExecutor({parameterCollector:this.parameterCollector,rootPath:this.repo.rootPath,rootPaths:this.repo.rootPaths,virtualEditor:this.virtualEditor,traceId:t.traceId,conversationId:t.conversationId,taskId:t.taskId,fileConsistencyChecker:this.fileConsistencyChecker,mcpManager:this.mcpManager,signal:this.token.signal,userTurn:this.latestRoundtrip,specEditor:this.specEditor,updateSessionMeta:this.updateSessionMeta},this.latestRoundtrip.toolTurns,this.token)),markLastToolTurnCompletedIfCanceled(this.latestRoundtrip.toolTurns),this.latestRoundtrip.status=RoundtripStatus.Generating,await this.executor.executeStream({updatedParams:e,onUpdate:e=>{this.performanceLog("agent-first-token"),this.rollbackMessageId=void 0,this.latestRoundtrip.disabledRollback=!!e,this.latestRoundtrip.updateWebviewMessages()},onRollback:()=>this.handleRollbackOnError()})}handleRollbackOnError(){const e=this.latestRoundtrip.toolTurns,t=e[e.length-1],r=t?.rollbackMessageId;if(r)return this.rollbackMessageId=r,t.discard=!0,r}getToolsByPath(e){return this.latestRoundtrip.toolTurns.flatMap((t=>t.getToolsByAbosultePath(e)))}async acceptFile(e){const t=this.getToolsByPath(e),r=t[t.length-1];t.forEach((e=>e.accept())),await r.toolHandler.save();return{absolutePath:e,suggestions:await this.updateAcceptance(e,!0),originalContent:t[0].result.metadata.originalContent||"",modifiedContent:r.result.metadata.content||""}}async rejectFile(e){const t=this.getToolsByPath(e);t.forEach((e=>e.reject())),await t[0].toolHandler.revert();return{absolutePath:e,suggestions:await this.updateAcceptance(e,!1),originalContent:t[t.length-1].result.metadata.originalContent||"",modifiedContent:t[0].result.metadata.content||""}}async updateAcceptance(e,t){return this.latestRoundtrip.updateSuggestionsByPath(e,t?AcceptState.ACCEPT:AcceptState.REJECT)}async handleNewMessage(e){switch(e.action){case"execute-shell":case"insert-shell":await this.virtualEditor.executeTerminalShell({cmd:e.shell,cwd:this.repo.rootPath,duration:5e3,run:"execute-shell"===e.action});break;case"copy-code":case"open-rollback-file-diff":break;case"file-view":if(this.specEditor.isSpec&&isSpecMarkdownFile(e.absolutePath)){await this.specEditor.openSpecEditor(e.absolutePath);break}await this.virtualEditor.openDocument({absolutePath:e.absolutePath});break;case"file-diff":if(this.specEditor.isSpec&&isSpecMarkdownFile(e.absolutePath)){await this.specEditor.openSpecEditor(e.absolutePath);break}try{const t=this.getToolsByPath(e.absolutePath);if(0===t.length){await this.virtualEditor.openDocument({absolutePath:e.absolutePath});break}const r=t[0],n=r.result?.metadata?.originalContent||"",{content:i}=await this.virtualEditor.getDocument({absolutePath:e.absolutePath});if(isComateIDE)return void this.virtualEditor.openDocument({absolutePath:e.absolutePath});await this.virtualEditor.openVirtualDiffDocument({conversationId:this.id,absolutePath:e.absolutePath,content:n,modified:i,stream:!1,action:VirtualDocumentAction.EDIT,source:this.type})}catch(t){this.logger.error("Failed to open diff document, fallback to normal view:",t),await this.virtualEditor.openDocument({absolutePath:e.absolutePath})}break;case"file-accept":{const{suggestions:t}=await this.acceptFile(e.filePath);this.acceptLog(this.metrics,this.latestRoundtrip.reportedId,t);break}case"file-reject":{const{suggestions:t}=await this.rejectFile(e.filePath);this.acceptLog(this.metrics,this.latestRoundtrip.reportedId,t);break}case"compress-token-usage":{const e=this.latestRoundtrip.context.taskId;await this.latestRoundtrip.compressTokenUsage({taskId:e}),this.parameterCollector.resetSkillFingerprint();break}case"copy-all":{const t=this.roundtrips.find((t=>t.uuid===e.id));let r="";if(t){const e=t.reportedId?`\nReportID: ${t.reportedId}`:"",n=this.id?`\nConversationID: ${this.id}`:"";r=t.toText(e+n)}return r}case"user-feedback":{const t=this.roundtrips.find((t=>t.uuid===e.id)),r=t?.reportedId;if(!r)return void this.logger.warn("[Zulu] Roundtrip reportedId missing: message uuid=",e.id);modifyCode({uuid:r,...e.options});break}case"file-tool-result-view":{const{tool:t,absolutePath:r}=e;if(this.specEditor.isSpec&&isSpecMarkdownFile(r)){await this.specEditor.openSpecEditor(r);break}if(t){const e=this.latestRoundtrip.toolTurns.find((e=>e.match(t.toolTurnId))),n=e?.tools.find((e=>e.toolId===t.toolId));if(n&&n.result.metadata)return void await this.virtualEditor.openVirtualDiffDocument({absolutePath:r,content:n.result.metadata.originalContent||"",modified:n.result.metadata.content||"",source:AgentConversationType.E2EBotConversation,action:VirtualDocumentAction.PREVIEW})}await this.virtualEditor.openDocument({absolutePath:r});break}case"file-accept-all":case"file-reject-all":{const t=_$H.flatten(this.latestRoundtrip.toolTurns.map((e=>e.tools.filter((e=>e.isTouchFileHandler&&"executed"===e.toolState)).map((e=>e.toolHandler.result.metadata?.absolutePath)))));for(const r of _$H.uniq(t.filter(Boolean)))"file-accept-all"===e.action?await this.acceptFile(r):await this.rejectFile(r);await this.acceptLog(this.metrics,this.latestRoundtrip.reportedId,this.latestRoundtrip.multiSuggestions);break}case"inquire-rollback-message":{await this.stopGenerating();let t=e.retryMessageId;if(e.userMessageId){const r=this.roundtrips.find((t=>t.request.uuid===e.userMessageId));r&&(t=r.toolTurns[0]?.rollbackMessageId)}return(await this.getRollbackSummaryV2(t)).map((e=>_$H.omit(e,"changes")))}case"rollback-message":{this.specEditor.beforeRollback(),await this.rollbackAllFileChanges(e.selectedAbsolutePaths);const t=e.retryMessageId,r=e.userMessageId;this.rollbackMessageId=t,forEachRollbackToolTurn(this.roundtrips,r,t,(e=>{this.rollbackMessageId||this.latestRoundtrip?.disabledRollback||(this.rollbackMessageId=e.rollbackMessageId),e.discard=!0}));const n=this.roundtrips.findIndex((e=>e.request.uuid===r)),i=this.roundtrips[n];return 0===n?(this.roundtrips.length=0,await this.chatSessionManager.delete(this.id)):-1!==n&&this.roundtrips.slice(n).forEach((e=>e.discard=!0)),this.specEditor.afterRollback(),this.mediator.userBehaviorTracker?.trackPromptRollback(i,e.retryMessageId),{}}case"tool-call-action":this.token.broadcast(e.name,{toolId:e.toolId,payload:e?.payload}),this.trackToolCallAction(e.toolId,e.name);break;case"quota-exceed":{const t=new ToolTurn(randomUUID(),this.token.fork(ToolTurn.createTokenId(randomUUID())),{parameterCollector:this.parameterCollector,traceId:this.id,conversationId:this.latestRoundtrip.context.conversationId??0,taskId:this.latestRoundtrip.context.taskId??0,rootPath:this.repo.rootPath,rootPaths:this.repo.rootPaths,virtualEditor:this.virtualEditor,signal:(new AbortController).signal,fileConsistencyChecker:this.fileConsistencyChecker,mcpManager:this.mcpManager,userTurn:this.latestRoundtrip,specEditor:this.specEditor,updateSessionMeta:this.updateSessionMeta}),r=e.quotaAction||"Quota exceeded",n=new Exception(r,!0);t.elements.push(n),this.latestRoundtrip.toolTurns.push(t),await t.cancel(r);break}}}rebuildConversation(e){const t=e.messages[0]?.context;this.rollbackMessageId=e.rollbackMessageId,this.token.onNotify(this.handleTokenNotification.bind(this)),this.rebuildRoundtrips(e.messages,{parameterCollector:this.parameterCollector,rootPath:this.repo.rootPath,rootPaths:this.repo.rootPaths,virtualEditor:this.virtualEditor,traceId:this.id,conversationId:t?.conversationId,taskId:t?.taskId,fileConsistencyChecker:this.fileConsistencyChecker,mcpManager:this.mcpManager,signal:this.token.signal,userTurn:this.latestRoundtrip,specEditor:this.specEditor,updateSessionMeta:this.updateSessionMeta},this.token),this.status=this.deriveConversationStatus(),this.specEditor.rebuild(),this.fileConsistencyChecker.rebuild(e.fileCache)}async acceptLogOnEnd(){const{suggestions:e,changes:t}=await this.latestRoundtrip.updateAcceptSuggestionsV2(this.metrics);this.codeWrittenMetric.agentEdit(Object.values(t));const r=this.latestRoundtrip.request.payload.query.trim(),{agentContexts:n,agentTools:i,assistantContent:o}=this.statistics.export(this.latestRoundtrip);if(this.latestRoundtrip.toolTurns.length&&!(this.latestRoundtrip.toolTurns[0].elements[0]instanceof Exception)){const t=await this.generateMessageId(this.metrics,e,r,o,n,i);this.logger.info("[Zulu] Roundtrip completed: uuid=",t),this.latestRoundtrip.reportedId=t,this.latestRoundtrip.updateWebviewMessages(),this.acceptLog(this.metrics,this.latestRoundtrip.reportedId,e)}}async triggerStopHook(e){const t=this.latestRoundtrip?.context;return hookService.triggerHook(HookEvent.Stop,{...hookService.buildCommonInput(this.id,{sessionId:t?.conversationId,taskId:t?.taskId}),hook_event_name:HookEvent.Stop,status:e,loop_count:hookService.getLoopCount(this.id)})}async beforeStop(){return"block"!==(await this.triggerStopHook("cancelled")).decision&&(this.token.state===TokenNotifyState.IN_PROGRESS&&this.mediator.userBehaviorTracker?.trackTaskCancelled(this.latestRoundtrip),this.token.cancel(),!0)}async onRoundtripComplete(){const e=await this.triggerStopHook("completed");if(!1===e.continue){const t=e.stopReason||"Execution stopped by hook";return hookService.resetLoopCount(this.id),kernel.connect.sendWebviewMessage(PT_WEBVIEW_HOOK_BLOCKED,{hookEventName:"executionStopped",message:t}).catch((()=>{})),null}const t=e.reason;if("block"!==e.decision||!t)return hookService.resetLoopCount(this.id),null;const r=hookService.incrementLoopCount(this.id);return r>=hookService.loopLimit?(hookService.resetLoopCount(this.id),kernel.connect.sendWebviewMessage(PT_WEBVIEW_HOOK_BLOCKED,{hookEventName:"stopLimitReached",message:t,loopCount:r,loopLimit:hookService.loopLimit}).catch((()=>{})),null):{followup:t}}beforeStartWork(){this.token.reset(),this.specEditor.beforeStartWork()}afterStartWork(){this.specEditor.afterStartWork(),this.autoResumeIfCompleted()}async autoResumeIfCompleted(){if(this.status!==AgentConversationStatus.Completed)return;const e=this.takeCommandResults();if(e.length>0){const t=e.map((e=>e.id)),r=this.latestRoundtrip?.toolTurns??[],n=r[r.length-1];if(n){const e=n.getToolById(randomUUID());e.update("task_complete","FUNCTION_CALL_PARAMS_MERGE",{tasks:t}),e.execute()}this.resumeStream({knowledgeList:e})}}afterGenerateQuerySummary(e,t){this.specEditor.afterGenerateQuerySummary(e,t)}startConversation(){this.notifyPreviousToolsNewConversationStart(),this.virtualEditor.startConversationEditSession({conversationId:this.id,source:this.type}),this.sessionHookFired||(this.sessionHookFired=!0,this.sessionEndFired=!1,this.sessionStartContextPromise=hookService.triggerHook(HookEvent.SessionStart,{...hookService.buildCommonInput(this.id),hook_event_name:HookEvent.SessionStart}).then((e=>{const t=e.additionalContext;if(t)return`<system-reminder>\n${HookEvent.SessionStart} hook additional context: ${t}\n</system-reminder>`})).catch((()=>{})))}endConversation(){this.notifyCurrentToolsConversationEnd(),this.virtualEditor.endConversationEditSession({conversationId:this.id}),this.acceptLogOnEnd(),this.logger.logUploader?.logUserAction({category:"new-agent",action:"endConversation"})}triggerSessionEnd(e){if(!this.sessionHookFired||this.sessionEndFired)return;this.sessionEndFired=!0;const t=this.latestRoundtrip?.context;hookService.triggerHook(HookEvent.SessionEnd,{...hookService.buildCommonInput(this.id,{sessionId:t?.conversationId,taskId:t?.taskId}),hook_event_name:HookEvent.SessionEnd,reason:e}).catch((()=>{}))}setForeground(e){if(!e&&this.foreground){const e=this.status===AgentConversationStatus.Running?"completed":this.status;this.triggerSessionEnd(e)}super.setForeground(e)}get latestAppliedRules(){return this.latestRoundtrip?.appliedRules||[]}getSessionState(){const e=this.latestRoundtrip?.toolTurns??[],t=e[e.length-1];if(t){if(this.status===AgentConversationStatus.Running&&hasPendingConfirmationTool(t.tools))return SessionState.Confirming;if(this.status===AgentConversationStatus.Completed&&hasStreamBreakingTool(t.tools))return SessionState.Pending}return this.specEditor.isSpec&&this.specEditor.hasSummaryFile&&this.status===AgentConversationStatus.Completed?SessionState.Summarized:super.getSessionState()}updateLatestAppliedRules(e,t=[],r="merge"){if(this.latestRoundtrip)if("merge"===r){const r=mergeAndDeduplicateRules(e,this.latestRoundtrip.appliedRules??[],t);this.latestRoundtrip.appliedRules=r}else this.latestRoundtrip.appliedRules=e.map((e=>({type:e.type,path:e.path,content:e.content,metadata:e.metadata,md5:computeMd5(e.content)})))}beforeStream(e){e.isUserQuery?this.mediator.userBehaviorTracker?.trackNewTaskStarted(this.latestRoundtrip):this.latestRoundtrip.calculateTokenUsage({taskId:e.taskId})}performanceLog(e){if(this.firstTokenStartTime){const t=performance.now()-this.firstTokenStartTime;this.logger.logUploader?.performanceLog({plugin:this.metrics.modelKey,skill:this.metrics.function,duration:t,type:e}),this.logger.info(`[Performance] ${e} take ${t} ms`),this.firstTokenStartTime=0}}trackToolCallAction(e,t){for(const r of this.roundtrips)for(const n of r.toolTurns){const i=n.tools.find((t=>t.toolId===e));if(i)return void this.mediator.userBehaviorTracker?.trackToolCallAction(i,r,t)}}notifyPreviousToolsNewConversationStart(){const e=this.previousRoundtrip?.toolTurns??[];for(const t of e)t.token.notifyConversationStart()}notifyCurrentToolsConversationEnd(){const e=this.latestRoundtrip?.toolTurns??[];for(const t of e)t.token.notifyConversationEnd()}takeCommandResults(){const e=this.commandResultQueue;return this.commandResultQueue=[],e}parseAndUseStructuredString(e){try{const t=JSON.parse(e);return"userActions"in t?(this.latestRoundtrip.quotaExceedMessage=JSON.stringify(t.userActions),{label:""}):{label:e}}catch{return{label:e}}}handleConversationError(e){if(!e||"cancel"===e)return;const{label:t}=this.parseAndUseStructuredString(e);t&&this.logger.logUploader?.logUserAction({category:"new-agent",action:"abortConversation",label:t,content:this.id})}}const DEFAULT_COMMAND_FILES$1=new Set(["code-review-comate","debug-comate","unit-test-comate"]);function getCommandNameFromRelativePath$1(e){const t=basename$3(e,".md").trim();return DEFAULT_COMMAND_FILES$1.has(t)?t.slice(0,-7):t}function serializeCommand$1(e){const t={};e.displayName&&(t.displayName=e.displayName),e.description&&(t.description=e.description);const r=e.prompt||`\nWrite your command content here.\n\nThis command will be available in chat with /${e.commandName}\n`;return matter$1.stringify(r,t)}class PersonalCommand{static personalDir=join$7(homedir$1(),".comate");static commandGlob="commands/**.md";static async readAll(){const e=PersonalCommand.personalDir,t=await globby(PersonalCommand.commandGlob,{cwd:e}).catch((()=>[]));kernel.logger.info(`Found personal commands: ${t.join(",")}`);const r=await Promise.all(t.map((async t=>{const r=join$7(e,t);try{const e=await readFile$4(r,"utf-8"),{data:n,content:i}=matter$1(e),o=n,s=basename$3(t,".md").trim();if(DEFAULT_COMMAND_FILES$1.has(s))return null;const a=getCommandNameFromRelativePath$1(t);if(!a)return null;return{commandId:-1*statSync$2(r).birthtimeMs,commandName:a,displayName:o.displayName??a,description:o.description??"",prompt:i.trim(),visibility:"SELF",isProjectCommand:!1,relativePath:t,absolutePath:r}}catch(e){return kernel.logger.info(`Failed to read personal command ${t}: ${e}`),null}})));return r.filter((e=>null!==e))}static async write(e){const t=join$7(PersonalCommand.personalDir,"commands");await lib$f.ensureDir(t);const r=e.relativePath??join$7("commands",`${e.commandName}.md`),n=join$7(PersonalCommand.personalDir,r);await writeFile$2(n,serializeCommand$1(e));const i=getCommandNameFromRelativePath$1(r);return{commandId:-1*statSync$2(n).birthtimeMs,commandName:i,displayName:e.displayName||i,description:e.description,prompt:e.prompt,visibility:"SELF",isProjectCommand:!1,relativePath:r,absolutePath:n}}static async delete(e){try{await rm$1(join$7(PersonalCommand.personalDir,e))}catch{}}}const DEFAULT_COMMAND_FILES=new Set(["code-review-comate","debug-comate","unit-test-comate"]);function getCommandNameFromRelativePath(e){const t=basename$3(e,".md").trim();return DEFAULT_COMMAND_FILES.has(t)?t.slice(0,-7):t}function serializeCommand(e){const t={};e.displayName&&(t.displayName=e.displayName),e.description&&(t.description=e.description);const r=e.prompt||`\nWrite your command content here.\n\nThis command will be available in chat with /${e.commandName}\n`;return matter$1.stringify(r,t)}class ProjectCommand{static commandGlob=".comate/commands/**.md";static async readFromWorkspace(e){const t=await globby(ProjectCommand.commandGlob,{cwd:e}).catch((()=>[]));kernel.logger.info(`Found project commands: ${t.join(",")}`);const r=await Promise.all(t.map((async t=>{const r=join$7(e,t);try{const e=await readFile$4(r,"utf-8"),{data:n,content:i}=matter$1(e),o=n,s=getCommandNameFromRelativePath(t);if(!s)return null;return{commandId:-1*statSync$2(r).birthtimeMs,commandName:s,displayName:o.displayName??s,description:o.description??"",prompt:i.trim(),visibility:"WORKSPACE",isProjectCommand:!0,relativePath:t,absolutePath:r}}catch(e){return kernel.logger.info(`Failed to read project command ${t}: ${e}`),null}})));return r.filter((e=>null!==e))}static async write(e,t){const r=join$7(e,".comate","commands");await lib$f.ensureDir(r);const n=t.relativePath??join$7(".comate","commands",`${t.commandName}.md`),i=join$7(e,n);await writeFile$2(i,serializeCommand(t));const o=getCommandNameFromRelativePath(n);return{commandId:-1*statSync$2(i).birthtimeMs,commandName:o,displayName:t.displayName||o,description:t.description,prompt:t.prompt,visibility:"WORKSPACE",isProjectCommand:!0,relativePath:n,absolutePath:i}}static async delete(e,t){try{await rm$1(join$7(e,t))}catch{}}}class MultiDirAgent extends Agent{agentGlob="agents/**.md";isProjectAgent=!1;reportAgentName="PERSONAL_AGENT";visibility="SELF";static searchDirs=[join$7(homedir$1(),".comate-engine"),join$7(homedir$1(),".comate"),join$7(homedir$1(),".cursor"),join$7(homedir$1(),".claude")];static mainDir=join$7(homedir$1(),".comate");constructor(e,t,r,n){super(n||MultiDirAgent.mainDir,e,t,r)}static async find(e){return(await this.readAll()).find((t=>t.toJSON().agentName===e))}static async write(e){const t=join$7("agents",e.agentName+".md"),r=new MultiDirAgent(t,{name:e.agentName,enable:"boolean"!=typeof e.enable||e.enable,description:e.description,icon:e.agentImage,tools:Array.isArray(e.tools)?e.tools:[],mcpServers:Array.isArray(e.mcpInfos)?e.mcpInfos:[],parentAgents:Array.isArray(e.parentAgents)?e.parentAgents:[]},e.agentPrompt);return await r.save(),r.toJSON()}static async delete(e){const t=e.endsWith(".md")?e.replace(/\.md$/,"").replace(/^agents\//,""):e;for(const e of MultiDirAgent.searchDirs){const r=join$7("agents",`${t}.md`),n=join$7(e,r);try{return await access$1(n),void await Agent.deleteAgent(e,r)}catch{continue}}}static async update(e,t){const r=await this.find(e.name);if(r)return r.update(e,t),await r.save(),r;{const r=join$7("agents",`${e.name}.md`),n=new MultiDirAgent(r,e,t);return await n.save(),n}}static async readAll(){const e=[];for(const t of MultiDirAgent.searchDirs){const r=await Agent.readAgentsFromPath(t,"agents/**.md",((e,t,r,n)=>new MultiDirAgent(t,r,n,e)));e.push(...r)}const t=new Set;return e.filter((e=>{const r=e.toJSON().agentName;return!t.has(r)&&(t.add(r),!0)})).sort(((e,t)=>t.getAgentId()-e.getAgentId()))}}async function apiGetPromptTemplateList(){try{const e=await axiosInstance("/api/openapi/prompt/list",{method:"POST",headers:{"Content-Type":"application/json","X-Username":kernel.env.isInternal?kernel.config.username&&encodeURIComponent(kernel.config.username):kernel.config.license},data:JSON.stringify({page:0,pageSize:500,sortByTime:0,needUnused:0,key:kernel.config.license})});if("OK"!==e.data?.status)throw new Error(e.data.message);return e.data?.data?.content.map((e=>({uuid:e.promptId,name:e.promptName,description:e.promptDesc,prompt:e.prompt})))??[]}catch(e){throw e}}class StayAwakeManager{logger;caffeinateProcess=null;preventing=!1;constructor(e){this.logger=e}update(e){e?this.prevent():this.allow()}prevent(){if("darwin"===process$2.platform&&!this.preventing)try{const e=spawn$5("caffeinate",["-di","-w",String(process$2.pid)],{stdio:"ignore",detached:!1});e.unref(),e.on("error",(e=>{this.logger.warn("caffeinate spawn error",e.message),this.caffeinateProcess=null,this.preventing=!1})),e.on("exit",(()=>{this.caffeinateProcess=null,this.preventing=!1})),this.caffeinateProcess=e,this.preventing=!0,this.logger.info("caffeinate started, preventing system sleep")}catch(e){this.logger.warn("failed to start caffeinate",e?.message)}}allow(){if(this.preventing&&this.caffeinateProcess){try{this.caffeinateProcess.kill()}catch{}this.caffeinateProcess=null,this.preventing=!1,this.logger.info("caffeinate stopped, allowing system sleep")}}dispose(){this.allow()}}const{debounce:debounce}=_$H;class ConversationManager{repo;mediator;virtualEditor;chatSessionManager;logger;mcpManager;previewProxyServerManager;agentCodeWrittenMetric;conversations=new Map;foregroundConversationId="";stayAwakeManager;constructor(e,t,r,n,i,o,s,a){this.repo=e,this.mediator=t,this.virtualEditor=r,this.chatSessionManager=n,this.logger=i,this.mcpManager=o,this.previewProxyServerManager=s,this.agentCodeWrittenMetric=a,this.stayAwakeManager=new StayAwakeManager(this.logger),kernel.connect.onWebviewMessage(PT_WEBVIEW_REQUEST_CHAT_SNAPSHOT,this.requestChatSnapshot.bind(this)),kernel.connect.onWebviewMessage(PT_WEBVIEW_REQUEST_KNOWLEDGE_LIST,getWorkspaceFoldersOrKnowledges.bind(this)),kernel.connect.onWebviewMessage(PT_WEBVIEW_REQUEST_PROJECT_AGENT_LIST,(async()=>{const[e,t]=await Promise.all([ProjectAgent.readFromWorkspace(this.repo.rootPath),MultiDirAgent.readAll()]);return[...e,...t].map((e=>e.toJSON()))})),kernel.connect.onWebviewMessage(PT_WEBVIEW_SAVE_PROJECT_AGENT,(async e=>{if(e.global){return await MultiDirAgent.write(e)}const t=await ProjectAgent.write(this.repo.rootPath,e);return await this.virtualEditor.refreshProjectTree(),t})),kernel.connect.onWebviewMessage(PT_WEBVIEW_DELETE_PROJECT_AGENT,(async e=>{if(e.absolutePath)try{await rm$1(e.absolutePath)}catch{}else e.global?await MultiDirAgent.delete(e.relativePath):(await ProjectAgent.delete(this.repo.rootPath,e.relativePath),this.virtualEditor.refreshProjectTree())})),kernel.connect.onWebviewMessage(PT_WEBVIEW_REQUEST_COMMAND_LIST,(async()=>{const[e,t]=await Promise.all([ProjectCommand.readFromWorkspace(this.repo.rootPath),PersonalCommand.readAll()]);return[...e,...t]})),kernel.connect.onWebviewMessage(PT_WEBVIEW_SAVE_COMMAND,(async e=>{if(e.global)return PersonalCommand.write(e);const t=await ProjectCommand.write(this.repo.rootPath,e);return await this.virtualEditor.refreshProjectTree(),t})),kernel.connect.onWebviewMessage(PT_WEBVIEW_DELETE_COMMAND,(async e=>{if(e.absolutePath)try{await rm$1(e.absolutePath)}catch{}else e.global&&e.relativePath?await PersonalCommand.delete(e.relativePath):e.relativePath&&(await ProjectCommand.delete(this.repo.rootPath,e.relativePath),this.virtualEditor.refreshProjectTree())})),kernel.connect.onWebviewMessage(PT_WEBVIEW_REPORT_RUNNING_CONVERSATIONS,this.reportRunningConversations.bind(this)),kernel.connect.onWebviewMessage(PT_WEBVIEW_CHECK_CONVERSATIONS_RUNNING,this.checkConversationsRunning.bind(this)),kernel.connect.onWebviewMessage(PT_WEBVIEW_STOP_CONVERSATIONS,this.stopConversations.bind(this)),kernel.connect.onWebviewMessage(PT_WEBVIEW_SKILL_METADATA_FETCH,(async()=>{const[e,t,r,n]=await Promise.all([getAllSkill(this.repo.rootPath),getAllCommandNames(this.repo.rootPath),getAllAgents(this.repo.rootPath),isInternal()?Promise.resolve([]):apiGetPromptTemplateList().catch((()=>[]))]);setServerCommandCache(n);const i=new Set(t.map((e=>e.name))),o=n.filter((e=>!i.has(e.name))).map((e=>({name:e.name,directory:"",sourceType:CommandSource.Enterprise,sourceName:"Comate",description:e.description}))),s="true"===process.env.DISABLE_BUILT_IN_SKILLS?e.filter((e=>e.sourceType!==SkillSource.System)):e;return{skills:s,commands:[...t,...o],agents:r}})),kernel.connect.onWebviewMessage(PT_WEBVIEW_CONVERSATION_TITLE_UPDATE_REQUEST,this.updateConversationTitle.bind(this))}async updateConversationTitle(e){const{conversationId:t,title:r}=e;try{const e=await this.chatSessionManager.find(t);if(!e)return;if(e.title=r,e.messages&&e.messages.length>0){const t=e.messages.find((e=>"user"===e.role));t&&(t.summary=r)}await this.chatSessionManager.save(e);const n=this.conversations.get(t);if(n&&"roundtrips"in n){const e=n;if(e.roundtrips&&e.roundtrips.length>0){const t=e.roundtrips[0];t&&t.request&&t.request.setSummary(r)}}}catch(e){this.logger.error(`Failed to update conversation title: ${e}`)}}async reportRunningConversations(){const e=Array.from(this.conversations.values()).filter((e=>e.status===AgentConversationStatus.Running)).length;this.logger.logUploader?.logUserAction({category:"multiTask",action:"reportRunningConversations",label:String(e+1)})}async checkConversationsRunning(e){const t=e.conversationIds.filter((e=>{const t=this.conversations.get(e);return t?.status===AgentConversationStatus.Running}));return{hasRunning:t.length>0,runningIds:t}}async stopConversations(e){await Promise.allSettled(e.conversationIds.map((e=>{const t=this.conversations.get(e);return t?.status===AgentConversationStatus.Running?t.onConversationMessage({messageType:"stop-generating",conversationId:e,payload:{}}):Promise.resolve()})))}createConversation(e){const t={repo:this.repo,virtualEditor:this.virtualEditor,onStatusChange:this.onStatusChange.bind(this),onMessageChange:this.onMessageChange.bind(this),logger:this.logger,userDetail:this.mediator.userDetail(),mediator:this.mediator,chatSessionManager:this.chatSessionManager};switch(e.conversationType){case AgentConversationType.SecuBotConversation:return new SecuBotConversation(t,this.mediator);case AgentConversationType.E2EBotConversation:return new E2EBotConversation(t,this.mcpManager,this.previewProxyServerManager,this.agentCodeWrittenMetric);case AgentConversationType.DebugBotConversation:return new DebugBotConversation(t,this.mcpManager,this.sendCustomEventToIde.bind(this),this.previewProxyServerManager,this.agentCodeWrittenMetric);case AgentConversationType.AgentConversation:return new AgentConversation(t,this.mcpManager,this.agentCodeWrittenMetric);default:throw new Error(`Unknown conversation type: ${e.conversationType}`)}}addConversation(e){try{const t=this.createConversation(e);return e.conversationId&&t.setConversationId(e.conversationId),this.conversations.set(t.id,t),this.setForegroundConversation(t.id),t}catch(e){this.logger.error("addConversation",e)}}onStatusChange(e){this.mediator.specCommunicationService?.syncConversationInfo(e);const t=this.conversations.get(e).getConversationInfo();this.updateConversationMessages("conversation-status",t);const r=Array.from(this.conversations.values()).some((e=>e.status===AgentConversationStatus.Running));this.stayAwakeManager.update(r)}debouncedMap=new Map;onMessageChange(e,t,r){const n=this.conversations.get(e),i=n.getConversationInfo();e===this.foregroundConversationId&&(r?this.updateConversationMessageWithOptions(i,r):this.updateConversationMessages("conversation-messages",i,t));const o=t.find((e=>"user"===e.role));if(o){const r=o.summary||o.content?.trim()||o.payload?.command;if(!r)return;const s=n.status===AgentConversationStatus.Running,a=this.debouncedMap.get(i.id)||debounce((e=>this.chatSessionManager.save(e)),2e3,{leading:s});s&&this.debouncedMap.set(e,a);const c=n.fileConsistencyChecker.getAllCachedFiles();a({source:n.type===AgentConversationType.AgentConversation&&n.specEditor.isSpec?"SpecConversation":i.type,sessionUuid:i.id,specSessionId:o.payload?.specSessionId,messages:t,title:r,ctime:i.ctime,utime:i.utime,workspaceDirectory:this.repo.rootPath,summary:o.summary,fileCache:c,sessionState:n.getSessionState()}),s||this.debouncedMap.delete(e)}}mapSourceToConversationType(e){return"SpecConversation"===e?AgentConversationType.AgentConversation:"Spec"===e?AgentConversationType.E2EBotConversation:e}async rebuildConversationFromHistory(e){if(!e)return;this.logger.info("rebuildConversationFromHistory called",{conversationId:e});const t=await this.chatSessionManager.find(e);if(t)try{const e=this.createConversation({conversationType:this.mapSourceToConversationType(t.source),conversationId:t.sessionUuid,payload:{},messageType:"rebuild-conversation"});return e.setConversationId(t.sessionUuid),e.setCtime(t.ctime),e.setUtime(t.utime),e.rebuildConversation(t),e}catch(e){this.logger.error("rebuildConversationFromHistory",e.message)}}async rebuildFromTemp(e){const t=JSON.parse(readFileSync$1(e,"utf-8")),r=basename$4(e).replace("chat_session_",""),n=this.createConversation({conversationType:AgentConversationType.E2EBotConversation,conversationId:r,payload:{},messageType:"rebuild-conversation"});return n.setConversationId(t.sessionUuid),n.setCtime(t.ctime),n.setUtime(t.utime),n.rebuildConversation(t),n}setForegroundConversation(e){if(null===e)return Array.from(this.conversations.values()).forEach((e=>e.setForeground(!1))),this.foregroundConversationId="",void this.logger.info("clearForegroundConversation");const t=this.conversations.get(e);if(!t)return;Array.from(this.conversations.values()).forEach((t=>{t.id!==e&&t.setForeground(!1)})),this.foregroundConversationId!==e&&t.setForeground(!0),this.foregroundConversationId=e,this.logger.info("setForegroundConversation",e);const{processedMessages:r,webviewMessages:n}=t.toMessages();this.onMessageChange(e,r,{scope:"conversation",messages:n})}getConversation(e){return this.conversations.get(e)}getForegroundConversationId(){return this.foregroundConversationId}getConversationBySpecSessionId(e){const t=Array.from(this.conversations.values()).filter((t=>t.type===AgentConversationType.AgentConversation&&t.specEditor.specSessionId===e)).reverse();return t.find((e=>e.foreground))??t[0]}listAllConversations(){const e=Array.from(this.conversations).filter((([,e])=>e.toMessages().webviewMessages.length)).map((([,e])=>{const t=e.toMessages().webviewMessages.slice().reverse().find((e=>"user"===e.role));return{...e.getConversationInfo(),lastQuery:t?.content}}));return e.reverse()}async onNewMessage(e){const{conversationId:t}=e;let r=this.conversations.get(t);const n=e.payload?.query||"";if(/^chat_session(.*)[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(basename$4(n)))r=this.conversations.get(t),r||(r=await this.rebuildFromTemp(e.payload.query),this.conversations.set(r.id,r)),this.setForegroundConversation(r.id);else if(r){r=this.conversations.get(t);const n=await(r?.onConversationMessage(e));if("message-operation"===e.messageType)return n}else r=await this.rebuildConversationFromHistory(t),r?(this.conversations.set(r.id,r),this.setForegroundConversation(r.id),r.type===AgentConversationType.AgentConversation&&this.mediator.userBehaviorTracker?.trackSwitchSession(r.latestRoundtrip)):r=this.addConversation(e);if(r)return{id:r.id,status:r.status,type:r.type}}async sendCustomEventToIde(e,t){return this.mediator.sendToIde(e,t)}async updateConversationMessages(e,t,r){if(t.id!==this.foregroundConversationId)return;const n={data:{type:e,conversationInfo:t}};r&&(n.data.messages=r),this.sendMessageImmediately(n)}async updateConversationMessageWithOptions(e,t){if("conversation"===t.scope)this.updateConversationMessages("conversation-messages",e,t.messages);else if("message"===t.scope){const r={data:{type:"partial-message-data",conversationInfo:e,messages:[t.message]}};this.sendMessageImmediately(r)}else{const r={data:{type:"partial-message-elements",conversationInfo:e,messageData:t.messageData}};this.sendMessageImmediately(r)}}sendMessageImmediately(e){return isZuluCLI()?this.mediator.sendToIde("COMATE_AGENT_UPDATE_MESSAGE",e,{skipWriteLog:e.data.conversationInfo.status===AgentConversationStatus.Running}):kernel.connect.sendWebviewMessage(PT_COMATE_AGENT_UPDATE_MESSAGE,e.data)}async requestChatSnapshot(e){const t=(await this.chatSessionManager.find(e.conversationId)).messages.map((t=>"assistant"!==t.role||e.codeVisible?"user"===t.role?_$H.set(t,"payload.knowledgeList",t.payload.knowledgeList?.map((e=>"RULE"===e.type?{...e,content:safeReadFileSync(join$6(this.repo.rootPath,e.id))}:e))):t:{...t,elements:t.elements.map((e=>{if("TOOL_CALL"!==e.type)return e;const t=["workflowSnapshot.searchFiles","workflowSnapshot.result.result.content","workflowSnapshot.result.result.afterChangeFileContent","workflowSnapshot.result.result.beforeChangeFileContent","composer"];return e.toolName===WorkflowType.SearchFiles&&t.push("workflowSnapshot.result.result"),_$H.omit(e,t)}))}));return JSON.stringify(t)}}const __filename$2=fileURLToPath(import.meta.url),__dirname$2=path__default.dirname(__filename$2);async function resolveSourcePath(){const e=isDevMod?path__default.join(__dirname$2,"../../assets"):path__default.join(__dirname$2,"assets");try{if(await fs$H.pathExists(e))return e}catch(e){kernel.logger.error("[Assets] Error checking source path",e)}return null}async function syncCategory(e,t,r,n){const i=path__default.join(t,e),o=path__default.join(r,e);if(!await fs$H.pathExists(i))return void kernel.logger.info(`[Assets] Source directory not found: ${i}`);try{await ensureDirectoryExist(o)}catch(e){return void kernel.logger.error(`[Assets] Failed to create target directory: ${o}`,e)}const s=await fs$H.readdir(i);for(const t of s){const r=path__default.join(i,t),s=path__default.join(o,t);try{await n(r,s)}catch(r){kernel.logger.error(`[Assets] Failed to install ${e} '${t}'`,r)}}}async function installAssets(){if("true"===process.env.DISABLE_BUILT_IN_SKILLS)return void kernel.logger.info("[Assets] DISABLE_BUILT_IN_SKILLS is set, skip installing built-in assets.");const e=await resolveSourcePath();if(!e)return void kernel.logger.info("[Assets] Source directory not found.");const t=path__default.join(os__default$1.homedir(),DEFAULT_WORKSPACE_CONFIG_FOLDER);try{await ensureDirectoryExist(t)}catch(e){return void kernel.logger.error(`[Assets] Failed to create target path: ${t}`,e)}try{await Promise.all([syncCategory("skills",e,t,(async(e,t)=>{(await fs$H.stat(e)).isDirectory()&&(kernel.logger.info(`[Assets] Copying skill from ${e} to ${t}`),await fs$H.remove(t),await fs$H.copy(e,t))})),syncCategory("commands",e,t,(async(e,t)=>{if(!(await fs$H.stat(e)).isFile())return;kernel.logger.info(`[Assets] Copying command from ${e} to ${t}`);const r=await fs$H.stat(t).catch((()=>null));r?.isDirectory()&&await fs$H.remove(t),await fs$H.copy(e,t,{overwrite:!0})}))])}catch(e){return void kernel.logger.error("[Assets] Promise.all execution failed",e)}kernel.logger.info(`[Assets] Installed assets to ${t}`)}class CommonCache{logger;cache=new Map;constructor(e){this.logger=e}async setCache(e,t){try{this.cache.set(e,t)}catch(e){this.logger.error("set cache error: ",e.message)}}async getCache(e){try{return this.cache.get(e)}catch(e){return void this.logger.error("get cache error: ",e.message)}}}var PLATFORM,SYSTEM;async function getGitRepositoryUrl(e){try{const{stdout:t}=await execa("git",["config","--get","remote.origin.url"],{cwd:e});return t.trim()}catch{return null}}async function getGitBranch(e){try{const{stdout:t}=await execa("git",["branch","--show-current"],{cwd:e});return t.trim()}catch{return""}}async function getGitRepositoryInfo(e){const[t,r]=await Promise.all([getGitRepositoryUrl(e),getGitBranch(e)]);return{repositoryUrl:t,branch:r}}!function(e){e.INTERNAL="baidu-int",e.SAAS="baidu-saas"}(PLATFORM||(PLATFORM={})),function(e){e.WINDOWS="win32",e.LINUX="linux",e.FREEBSD="freebsd",e.OPENBSD="openbsd",e.SUNOS="sunos",e.MAC="darwin"}(SYSTEM||(SYSTEM={})),process.env.COMATE_ENGINE_PLATFORM,PLATFORM.INTERNAL,SYSTEM.WINDOWS,patchEnvPath();class StringChunkStream{chunks=[];append(e){this.chunks.push(e)}flush(e){return e&&this.append(e),{command:"draw",content:this.chunks}}replaceLast(e){this.chunks.length?this.chunks[this.chunks.length-1]=e:this.append(e)}flushReplaceLast(e){return this.replaceLast(e),this.flush()}fail(e){return this.chunks.length=0,{command:"fail",content:e}}}-1===Math.random()&&console.log("THIS IS COMATE");const PREAMBLE_SEPERATOR="win32"===process.platform?"\r\n---Prompt---\r\n":"\n---Prompt---\n",ANNOTATION_SEPERATOR="win32"===process.platform?"\r\n############\r\n":"\n############\n";function formatPrompt(e,t){return t?e.replace(/\{\{\s*((\w+)|(\[FILE\]\s*[\\\/\-\.\w]+))\s*\}\}/g,((e,r)=>{const n=t[r];return void 0!==n?String(n):e})):e}function getPreambleAndBody(e){let[t,r]=e.split(PREAMBLE_SEPERATOR);return void 0===r&&(r=t,t=""),[t,r.split(ANNOTATION_SEPERATOR)?.[0]??""]}function formatNumber(e,t){if(void 0===e)return;let r=0;if("number"==typeof e&&(r=e),"string"==typeof e){const t=e.trim();if(!/^\d+$/.test(t))return;r=parseInt(t,10)}return t?.isInteger&&!Number.isInteger(r)||void 0!==t?.min&&r<t.min||void 0!==t?.max&&r>t.max?void 0:r}function formatBoolean(e){if(void 0===e)return;if("boolean"==typeof e)return e;const t=String(e).trim().toLowerCase();return["true","1"].includes(t)}function parsePreamble(e){return{temperature:formatNumber(e.temperature,{min:0,max:1}),topP:formatNumber(e.topP,{min:0,max:1}),penaltyScore:formatNumber(e.penaltyScore,{min:1,max:2}),knowledgeList:e.knowledgeList?.filter((e=>e?.trim().length>0)),mergeUserKnowledge:formatBoolean(e.mergeUserKnowledge)}}function parsePromptFile(e,t){let[r,n]=getPreambleAndBody(t);const i=jsYaml.load(r,{json:!0})??{},{name:o,description:s,...a}=i,c=o?String(o):e;return{name:c,description:s??c,system:parsePreamble(a),promptTemplate:n}}const promptTemplatePreamble="\n# 自定义指令名称,必填\nname: 自定义指令名称\n# 自定义指令描述,可选\ndescription: 自定义指令的描述\n",defaultPromptTemplate="\n该部分内容为自定义Prompt具体内容,请根据需求直接修改此段话。比如:帮我生成一个随机数。\n",promptTemplateAnnotation="\n# =================高级Prompt编写说明==========================\n# Prompt支持以下多种变量配合使用:\n # {{ query }} 为用户输入框输入的内容\n # {{ knowledgeList }} 为knowledgelist配置和用户输入的知识,详细说明见最下方知识手册\n # {{ selectedCode }} 为用户当前选中代码\n # {{ activeFileContent}} 为IDE光标所在文件的内容\n # {{ activeFilelineContent}} 为IDE光标所在行的内容\n # {{ [FILE] path }} 为本地文件内容,将path替换为相对当前项目根目录的相对路径即可\n# 详细说明请见使用手册:https://ku.baidu-int.com/knowledge/HFVrC7hq1Q/_SKPgSwp2G/Hb6OQz5Jc7/PvZ5uWD8MdM0w_\n",parseFilePathInPromptTemplate=e=>{try{const t=/\{\{\s*(\[FILE\]\s*([\\\/\-\.\w]+))\s*\}\}/g,r={};let n;for(;null!==(n=t.exec(e));)r[n[1]]=n[2];return r}catch(e){return}},normalizeFilePath=(e,t)=>t?.includes("/")?"win32"===process.platform?path__default.join(e,t.replace(/\//g,path__default.sep)):path__default.join(e,t):t?.includes("\\")?"win32"===process.platform?path__default.join(e,t):path__default.join(e,t.replace(/\\/g,path__default.sep)):path__default.join(e,t);function generatePromptTemplate(e){let t=promptTemplatePreamble+PREAMBLE_SEPERATOR;return e||(t+=defaultPromptTemplate),e?.query&&(t+=`请回答我的问题:${e.query}`),t+ANNOTATION_SEPERATOR+promptTemplateAnnotation}const MAX_INPUT_STRING=modelMapMaxInputString[TextModel.ErnieBot4Turbo128]-2e3;class PromptTemplateService{mediator;logger;constructor(e,t){this.mediator=e,this.logger=t}async init(){this.logger.info("PromptTemplateService init"),this.getAll()}async getPromptTemplateDirectoryPath(){try{const e=await this.mediator.getWorkspaceFolders();if(e&&e.length>0){const t=URI$3.parse(e[0].uri).fsPath;return getPromptTemplateRootPath(t)}}catch(e){this.logger.error(e)}}async getDirectoryPromptTemplates(e){try{const t=await readdir$7(e,{withFileTypes:!0}),r=[];for(const n of t)if(n.isFile()&&n.name.endsWith(".prompt")){const t=path__default.join(e,"/",n.name),{success:i,data:o}=await this.validatePromptTemplate(t);if(i){const e=await readFile$3(t,{encoding:"utf8"}),i=n.name.replace(/\.prompt$/,""),{name:s,description:a}=parsePromptFile(i,e);r.unshift({uuid:i,name:s,description:a,ts:o?.ts||0})}}return r.sort(((e,t)=>t.ts-e.ts))}catch(e){return this.logger.error(e),[]}}async getAll(){try{if(isInternal()){if(isVscode){const e=await this.getPromptTemplateDirectoryPath();if(e){if(await isFolderAccessable(e)){return await this.getDirectoryPromptTemplates(e)}return[]}return[]}return[]}return await apiGetPromptTemplateList()??[]}catch(e){return this.logger.error(e),[]}}async create(e){try{const t=await this.getPromptTemplateDirectoryPath();if(t){await isFolderAccessable(t)||await mkdir$c(t,{recursive:!0});const r=path__default.join(t,`prompt_${dayjs$1().format("YYYY-MM-DD_HH_mm_ss")}.prompt`);return{uri:r,content:generatePromptTemplate(e)}}return"未打开工作区,无法创建自定义指令"}catch(e){return this.logger.error(e),"创建自定义指令失败"}}async save(e){try{const t=await this.getAll(),r=await this.getPromptTemplateDirectoryPath();if(r){const n=path__default.join(r,"/",e+".prompt"),i=await readFile$3(n,{encoding:"utf8"}),{name:o}=parsePromptFile(n,i);return void 0!==t.find((t=>t.name===o&&t.uuid!==e))?"该自定义指令已存在,请重新命名":void 0}return"未打开工作区"}catch(e){return this.logger.error(e),"保存自定义指令失败"}}async delete(e){try{const t=await this.getPromptTemplateDirectoryPath();if(t){const r=path__default.join(t,e+".prompt");return await isFileAccessable(r)?void await unlink(r):"该自定义指令不存在"}return"未打开工作区"}catch(e){return this.logger.error(e),"删除自定义指令失败"}}validateLength(e,t){if(e.length>MAX_INPUT_STRING)throw new Error(`${t},不能超过${MAX_INPUT_STRING}个字符,请简化或移除该部分内容。`)}async validatePromptTemplate(e){try{const t=await stat$g(e),r=t.size;return r>MAX_INPUT_STRING?{success:!1,message:"自定义指令文件过大,当前大小: "+r+" 字节"}:{success:!0,data:{ts:t.birthtimeMs||t.ctimeMs}}}catch(e){return this.logger.error("获取文件状态时出错:",e),{success:!1,message:"自定义指令文件获取失败,请先检查该文件是否存在"}}}generateMessageEvent(e,t,r){return{messageId:t,sessionId:"",data:{action:ACTION_CHAT_TASK_PROGRESS,payload:{taskId:String(t),messageId:t,chunk:r,informationList:[],capabilityName:e}}}}async processNormalKnowledgeList({query:e,inputKnowledgeList:t,templateKnowledgeList:r,mergeUserKnowledge:n}){let i="";if(r?.length||n&&t?.length){this.logger.info("Prompt 生成结果验证 [知识集检索(配置)]:",r?.join("/")),this.logger.info("Prompt 生成结果验证 [知识集检索(输入)]:",t.map((e=>e.uuid))?.join("/"));const o=await this.mediator.pluginConfigApi.getKnowledgeQueryResult(e,InformationQueryType.Text,t.map((e=>({uuid:e.uuid??e.id,type:"NORMAL"}))),{mergeUserKnowledge:n,knowledgeSets:r?.map((e=>({uuid:e,type:"NORMAL"})))});for(const e of o.chunks)i+=e.content?.trim();this.logger.info("Prompt 生成结果验证 [知识集检索(结果)]:",i),this.validateLength(i,"知识集检索结果过长")}return i}async processInputFileKnowledgeList(e){let t="";if(e?.length)for(const r of e)t+=r.content?.trim();return this.validateLength(t,"输入文件的文件内容过长"),t}async processTemplateFileKnowledgeList(e){const t={},r=await this.mediator.getWorkspaceFolders(),n=[];if(r?.[0]?.uri){const i=URI$3.parse(r[0].uri).fsPath;if(e){for(const[r,o]of Object.entries(e)){const e=normalizeFilePath(i,o);try{const i=await stat$g(e);if(i.isFile()){if(i.size>MAX_INPUT_STRING){n.push(`文件${o}内容过长`);continue}const s=await readFile$3(e,{encoding:"utf8"});t[r]=s?.trim()}}catch(e){n.push(`未找到文件${o}`);break}}if(n.length>0)throw new Error(n.join(","))}return t}return t}async*chat(e,t){const r=await this.getPromptTemplateDirectoryPath(),n=new StringChunkStream;if(r){const i=path__default.join(r,"/",t.input.capability+".prompt"),{success:o,message:s}=await this.validatePromptTemplate(i);if(!o)return void(yield this.generateMessageEvent(e,t.input.messageId,n.fail(s||"")));try{const r=await readFile$3(i,{encoding:"utf8"}),{system:o,promptTemplate:s}=parsePromptFile(i,r),a={query:t.input.query,selectedCode:t.context?.selectedCode,activeFileContent:t.context?.activeFileContent,activeFileLineContent:t.context?.activeFileLineContent,activeFileLanguage:t.context?.activeFileLanguage,knowledgeList:""},c=t.input.informationList?.filter((({type:e})=>["SYSTEM","NORMAL"].includes(e))),A=await this.processNormalKnowledgeList({query:t.input.query,inputKnowledgeList:c,templateKnowledgeList:o.knowledgeList,mergeUserKnowledge:o.mergeUserKnowledge}),l=parseFilePathInPromptTemplate(s);this.logger.info("Prompt 生成结果验证 [文件路径映射]:",JSON.stringify(l));const u=await this.processTemplateFileKnowledgeList(l);this.logger.info("Prompt 生成结果验证 [文件内容映射]:",JSON.stringify(u));const d=await this.processInputFileKnowledgeList(t.input.informationList?.filter((({type:e})=>["FILE","CURRENT_FILE"].includes(e))));a.knowledgeList=A+"\n"+d+"\n";const h=formatPrompt(s,{...a,...u})?.trim();if(!h)throw new Error("Prompt 为空,请确认自定义指令Prompt配置是否正确");this.logger.info("Prompt 生成结果验证:",h),this.validateLength(h,"您输入的内容和选中的内容总长度过长");const p=h.length>modelMapMaxInputString[TextModel.ErnieBot4]?TextModel.ErnieBot4Turbo128:TextModel.ErnieBot4,g=[{role:"user",content:h}];A?.length>0&&this.logger.logUploader?.logUserAction({category:"promptTemplate",action:"chatWithKnowledge",content:`inputKnowledgeList: ${c?.length},templateKnowledgeList: {${o?.knowledgeList?.length}},mergeUserKnowledge: ${o?.mergeUserKnowledge}`});const f=await this.mediator.llmApi.callErnieBotStreaming({messages:g,pluginName:"PromptTemplate",model:p,modelOptions:{temperature:o?.temperature,topP:o?.topP,penaltyScore:o?.penaltyScore},device:this.mediator.userDetail()?.device});let m="";for await(const r of f)m+=r.result,yield this.generateMessageEvent(e,t.input.messageId,n.flushReplaceLast(m))}catch(r){yield this.generateMessageEvent(e,t.input.messageId,n.fail(r?.message))}}}}class AppLaunchTracker{logger;lastExecutionDate;constructor(e){this.logger=e,this.lastExecutionDate="",this.initializeScheduler()}initializeScheduler(){setInterval((()=>{this.checkAndTrackLaunch()}),36e5),this.checkAndTrackLaunch()}checkAndTrackLaunch(){const e=(new Date).toDateString();this.lastExecutionDate!==e&&(this.trackLaunch(),this.lastExecutionDate=e)}trackLaunch(){this.logger.logUploader?.logUserAction({category:"engineInnerInit",content:"IDE channel initialized"})}}const sleep=e=>new Promise((t=>setTimeout(t,e)));class IScan{logger;mediator;pluginName="aiscan";capabilityName="codeStyleCheck";latestJobBuildId=null;constructor(e,t){this.logger=t,this.mediator=e}async startScan({ignoreNoErrorNotification:e,systemInfo:t}){try{const r=crypto$7.randomUUID();for await(const n of this.mediator.sendToPlugin(r,{action:ACTION_START_ISCAN,payload:{systemInfo:t,pluginName:this.pluginName,capabilityName:this.capabilityName,scanType:"init"}})){const r=n?.data.payload.chunk,{jobBuildId:i,errorMsg:o,status:s}=r;return this.logger.info("jobBuildResult",i,o,s),i?(this.latestJobBuildId=i,this.reportScanResult(e,t,i),!0):(this.logger.error("iScan job build error",o),!1)}return!1}catch(e){return this.logger.error("startScan failed",e instanceof Error?e.toString():e),!1}}async reportScanResult(e,t,r,n=3e5){const i=Date.now();let o=!1;for(;Date.now()-i<n&&!o;){if(this.latestJobBuildId!==r)return void this.logger.info("Scan job cancelled",r);try{const n=crypto$7.randomUUID();for await(const i of this.mediator.sendToPlugin(n,{action:ACTION_START_ISCAN,payload:{systemInfo:t,pluginName:this.pluginName,capabilityName:this.capabilityName,scanType:"getResult",jobBuildId:r}})){if(this.latestJobBuildId!==r)return void this.logger.info("Scan job cancelled during processing",r);const n=i?.data.payload.chunk;if(this.logger.info("reportScanResult",r,n),"SUCC"===n.status){o=!0;const i=(n.codestyle?.high||0)+(n.codestyle?.middle||0)+(n.codestyle?.low||0),s=(n.bugbye?.high||0)+(n.bugbye?.middle||0)+(n.bugbye?.low||0);if(e&&0===i&&0===s)return;const a=0===i&&0===s?"Comate代码扫描已完成,未发现任何问题!您可以放心继续下一步操作。":`Comate代码扫描已完成,发现 ${0===i?"":`${i} 个代码规范问题,`} ${0===s?"":`${s} 个代码缺陷问题,`} 建议您立即修复,避免合入被卡位。`,c=await currentBranch({fs:fs$1i,dir:t.cwd}),A=c?`git push origin HEAD:refs/for/${c}`:"git push origin master";this.mediator.sendToIde(ACTION_SCAN_NOTIFICATION,{notification:a,jobBuildId:r,buttonType:0!==i||0!==s?"detailButton":"pushButton",pushCommand:A})}break}await sleep(1e4)}catch(e){this.logger.error("get result failed",e instanceof Error?e.toString():e),await sleep(1e4)}}o||this.logger.error("get result timed out")}}const LATEST_PROTOCOL_VERSION="2025-06-18",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-03-26","2024-11-05","2024-10-07"],JSONRPC_VERSION="2.0",ProgressTokenSchema=z.union([z.string(),z.number().int()]),CursorSchema=z.string(),RequestMetaSchema=z.object({progressToken:z.optional(ProgressTokenSchema)}).passthrough(),BaseRequestParamsSchema=z.object({_meta:z.optional(RequestMetaSchema)}).passthrough(),RequestSchema=z.object({method:z.string(),params:z.optional(BaseRequestParamsSchema)}),BaseNotificationParamsSchema=z.object({_meta:z.optional(z.object({}).passthrough())}).passthrough(),NotificationSchema=z.object({method:z.string(),params:z.optional(BaseNotificationParamsSchema)}),ResultSchema=z.object({_meta:z.optional(z.object({}).passthrough())}).passthrough(),RequestIdSchema=z.union([z.string(),z.number().int()]),JSONRPCRequestSchema=z.object({jsonrpc:z.literal(JSONRPC_VERSION),id:RequestIdSchema}).merge(RequestSchema).strict(),isJSONRPCRequest=e=>JSONRPCRequestSchema.safeParse(e).success,JSONRPCNotificationSchema=z.object({jsonrpc:z.literal(JSONRPC_VERSION)}).merge(NotificationSchema).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema.safeParse(e).success,JSONRPCResponseSchema=z.object({jsonrpc:z.literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResponse=e=>JSONRPCResponseSchema.safeParse(e).success;var ErrorCode;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(ErrorCode||(ErrorCode={}));const JSONRPCErrorSchema=z.object({jsonrpc:z.literal(JSONRPC_VERSION),id:RequestIdSchema,error:z.object({code:z.number().int(),message:z.string(),data:z.optional(z.unknown())})}).strict(),isJSONRPCError=e=>JSONRPCErrorSchema.safeParse(e).success,JSONRPCMessageSchema=z.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResponseSchema,JSONRPCErrorSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/cancelled"),params:BaseNotificationParamsSchema.extend({requestId:RequestIdSchema,reason:z.string().optional()})}),IconSchema=z.object({src:z.string(),mimeType:z.optional(z.string()),sizes:z.optional(z.array(z.string()))}).passthrough(),IconsSchema=z.object({icons:z.array(IconSchema).optional()}).passthrough(),BaseMetadataSchema=z.object({name:z.string(),title:z.optional(z.string())}).passthrough(),ImplementationSchema=BaseMetadataSchema.extend({version:z.string(),websiteUrl:z.optional(z.string())}).merge(IconsSchema),ClientCapabilitiesSchema=z.object({experimental:z.optional(z.object({}).passthrough()),sampling:z.optional(z.object({}).passthrough()),elicitation:z.optional(z.object({}).passthrough()),roots:z.optional(z.object({listChanged:z.optional(z.boolean())}).passthrough())}).passthrough(),InitializeRequestSchema=RequestSchema.extend({method:z.literal("initialize"),params:BaseRequestParamsSchema.extend({protocolVersion:z.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema})}),ServerCapabilitiesSchema=z.object({experimental:z.optional(z.object({}).passthrough()),logging:z.optional(z.object({}).passthrough()),completions:z.optional(z.object({}).passthrough()),prompts:z.optional(z.object({listChanged:z.optional(z.boolean())}).passthrough()),resources:z.optional(z.object({subscribe:z.optional(z.boolean()),listChanged:z.optional(z.boolean())}).passthrough()),tools:z.optional(z.object({listChanged:z.optional(z.boolean())}).passthrough())}).passthrough(),InitializeResultSchema=ResultSchema.extend({protocolVersion:z.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z.optional(z.string())}),InitializedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/initialized")}),isInitializedNotification=e=>InitializedNotificationSchema.safeParse(e).success,PingRequestSchema=RequestSchema.extend({method:z.literal("ping")}),ProgressSchema=z.object({progress:z.number(),total:z.optional(z.number()),message:z.optional(z.string())}).passthrough(),ProgressNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/progress"),params:BaseNotificationParamsSchema.merge(ProgressSchema).extend({progressToken:ProgressTokenSchema})}),PaginatedRequestSchema=RequestSchema.extend({params:BaseRequestParamsSchema.extend({cursor:z.optional(CursorSchema)}).optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:z.optional(CursorSchema)}),ResourceContentsSchema=z.object({uri:z.string(),mimeType:z.optional(z.string()),_meta:z.optional(z.object({}).passthrough())}).passthrough(),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z.string()}),Base64Schema=z.string().refine((e=>{try{return atob(e),!0}catch(e){return!1}}),{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),ResourceSchema=BaseMetadataSchema.extend({uri:z.string(),description:z.optional(z.string()),mimeType:z.optional(z.string()),_meta:z.optional(z.object({}).passthrough())}).merge(IconsSchema),ResourceTemplateSchema=BaseMetadataSchema.extend({uriTemplate:z.string(),description:z.optional(z.string()),mimeType:z.optional(z.string()),_meta:z.optional(z.object({}).passthrough())}).merge(IconsSchema),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z.array(ResourceTemplateSchema)}),ReadResourceRequestSchema=RequestSchema.extend({method:z.literal("resources/read"),params:BaseRequestParamsSchema.extend({uri:z.string()})}),ReadResourceResultSchema=ResultSchema.extend({contents:z.array(z.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/resources/list_changed")}),SubscribeRequestSchema=RequestSchema.extend({method:z.literal("resources/subscribe"),params:BaseRequestParamsSchema.extend({uri:z.string()})}),UnsubscribeRequestSchema=RequestSchema.extend({method:z.literal("resources/unsubscribe"),params:BaseRequestParamsSchema.extend({uri:z.string()})}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/resources/updated"),params:BaseNotificationParamsSchema.extend({uri:z.string()})}),PromptArgumentSchema=z.object({name:z.string(),description:z.optional(z.string()),required:z.optional(z.boolean())}).passthrough(),PromptSchema=BaseMetadataSchema.extend({description:z.optional(z.string()),arguments:z.optional(z.array(PromptArgumentSchema)),_meta:z.optional(z.object({}).passthrough())}).merge(IconsSchema),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z.array(PromptSchema)}),GetPromptRequestSchema=RequestSchema.extend({method:z.literal("prompts/get"),params:BaseRequestParamsSchema.extend({name:z.string(),arguments:z.optional(z.record(z.string()))})}),TextContentSchema=z.object({type:z.literal("text"),text:z.string(),_meta:z.optional(z.object({}).passthrough())}).passthrough(),ImageContentSchema=z.object({type:z.literal("image"),data:Base64Schema,mimeType:z.string(),_meta:z.optional(z.object({}).passthrough())}).passthrough(),AudioContentSchema=z.object({type:z.literal("audio"),data:Base64Schema,mimeType:z.string(),_meta:z.optional(z.object({}).passthrough())}).passthrough(),EmbeddedResourceSchema=z.object({type:z.literal("resource"),resource:z.union([TextResourceContentsSchema,BlobResourceContentsSchema]),_meta:z.optional(z.object({}).passthrough())}).passthrough(),ResourceLinkSchema=ResourceSchema.extend({type:z.literal("resource_link")}),ContentBlockSchema=z.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z.object({role:z.enum(["user","assistant"]),content:ContentBlockSchema}).passthrough(),GetPromptResultSchema=ResultSchema.extend({description:z.optional(z.string()),messages:z.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/prompts/list_changed")}),ToolAnnotationsSchema=z.object({title:z.optional(z.string()),readOnlyHint:z.optional(z.boolean()),destructiveHint:z.optional(z.boolean()),idempotentHint:z.optional(z.boolean()),openWorldHint:z.optional(z.boolean())}).passthrough(),ToolSchema=BaseMetadataSchema.extend({description:z.optional(z.string()),inputSchema:z.object({type:z.literal("object"),properties:z.optional(z.object({}).passthrough()),required:z.optional(z.array(z.string()))}).passthrough(),outputSchema:z.optional(z.object({type:z.literal("object"),properties:z.optional(z.object({}).passthrough()),required:z.optional(z.array(z.string()))}).passthrough()),annotations:z.optional(ToolAnnotationsSchema),_meta:z.optional(z.object({}).passthrough())}).merge(IconsSchema),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z.array(ContentBlockSchema).default([]),structuredContent:z.object({}).passthrough().optional(),isError:z.optional(z.boolean())});CallToolResultSchema.or(ResultSchema.extend({toolResult:z.unknown()}));const CallToolRequestSchema=RequestSchema.extend({method:z.literal("tools/call"),params:BaseRequestParamsSchema.extend({name:z.string(),arguments:z.optional(z.record(z.unknown()))})}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/tools/list_changed")}),LoggingLevelSchema=z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestSchema=RequestSchema.extend({method:z.literal("logging/setLevel"),params:BaseRequestParamsSchema.extend({level:LoggingLevelSchema})}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/message"),params:BaseNotificationParamsSchema.extend({level:LoggingLevelSchema,logger:z.optional(z.string()),data:z.unknown()})}),ModelHintSchema=z.object({name:z.string().optional()}).passthrough(),ModelPreferencesSchema=z.object({hints:z.optional(z.array(ModelHintSchema)),costPriority:z.optional(z.number().min(0).max(1)),speedPriority:z.optional(z.number().min(0).max(1)),intelligencePriority:z.optional(z.number().min(0).max(1))}).passthrough(),SamplingMessageSchema=z.object({role:z.enum(["user","assistant"]),content:z.union([TextContentSchema,ImageContentSchema,AudioContentSchema])}).passthrough(),CreateMessageRequestSchema=RequestSchema.extend({method:z.literal("sampling/createMessage"),params:BaseRequestParamsSchema.extend({messages:z.array(SamplingMessageSchema),systemPrompt:z.optional(z.string()),includeContext:z.optional(z.enum(["none","thisServer","allServers"])),temperature:z.optional(z.number()),maxTokens:z.number().int(),stopSequences:z.optional(z.array(z.string())),metadata:z.optional(z.object({}).passthrough()),modelPreferences:z.optional(ModelPreferencesSchema)})}),CreateMessageResultSchema=ResultSchema.extend({model:z.string(),stopReason:z.optional(z.enum(["endTurn","stopSequence","maxTokens"]).or(z.string())),role:z.enum(["user","assistant"]),content:z.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema])}),BooleanSchemaSchema=z.object({type:z.literal("boolean"),title:z.optional(z.string()),description:z.optional(z.string()),default:z.optional(z.boolean())}).passthrough(),StringSchemaSchema=z.object({type:z.literal("string"),title:z.optional(z.string()),description:z.optional(z.string()),minLength:z.optional(z.number()),maxLength:z.optional(z.number()),format:z.optional(z.enum(["email","uri","date","date-time"]))}).passthrough(),NumberSchemaSchema=z.object({type:z.enum(["number","integer"]),title:z.optional(z.string()),description:z.optional(z.string()),minimum:z.optional(z.number()),maximum:z.optional(z.number())}).passthrough(),EnumSchemaSchema=z.object({type:z.literal("string"),title:z.optional(z.string()),description:z.optional(z.string()),enum:z.array(z.string()),enumNames:z.optional(z.array(z.string()))}).passthrough(),PrimitiveSchemaDefinitionSchema=z.union([BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema,EnumSchemaSchema]),ElicitRequestSchema=RequestSchema.extend({method:z.literal("elicitation/create"),params:BaseRequestParamsSchema.extend({message:z.string(),requestedSchema:z.object({type:z.literal("object"),properties:z.record(z.string(),PrimitiveSchemaDefinitionSchema),required:z.optional(z.array(z.string()))}).passthrough()})}),ElicitResultSchema=ResultSchema.extend({action:z.enum(["accept","decline","cancel"]),content:z.optional(z.record(z.string(),z.unknown()))}),ResourceTemplateReferenceSchema=z.object({type:z.literal("ref/resource"),uri:z.string()}).passthrough(),PromptReferenceSchema=z.object({type:z.literal("ref/prompt"),name:z.string()}).passthrough(),CompleteRequestSchema=RequestSchema.extend({method:z.literal("completion/complete"),params:BaseRequestParamsSchema.extend({ref:z.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z.object({name:z.string(),value:z.string()}).passthrough(),context:z.optional(z.object({arguments:z.optional(z.record(z.string(),z.string()))}))})}),CompleteResultSchema=ResultSchema.extend({completion:z.object({values:z.array(z.string()).max(100),total:z.optional(z.number().int()),hasMore:z.optional(z.boolean())}).passthrough()}),RootSchema=z.object({uri:z.string().startsWith("file://"),name:z.optional(z.string()),_meta:z.optional(z.object({}).passthrough())}).passthrough(),ListRootsRequestSchema=RequestSchema.extend({method:z.literal("roots/list")}),ListRootsResultSchema=ResultSchema.extend({roots:z.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/roots/list_changed")});z.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema]),z.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema]),z.union([EmptyResultSchema,CreateMessageResultSchema,ElicitResultSchema,ListRootsResultSchema]),z.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema]),z.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema]),z.union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema]);class McpError extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}}class TypedEventEmitter extends EventEmitter$c{on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}off(e,t){return super.off(e,t)}emit(e,...t){return super.emit(e,...t)}}const{omitBy:omitBy,isNil:isNil}=_$H,DEFAULT_MCP_TIMEOUT_SECONDS$1=30,deepDropNilValue=e=>{if(null==e)return e;if(Array.isArray(e))return e.filter((e=>null!=e)).map((e=>deepDropNilValue(e)));if("object"==typeof e&&e.constructor===Object){const t=omitBy(e,isNil),r={};for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(r[e]=deepDropNilValue(t[e]));return r}return e};function extractRuntimeConfig(e){return"stdio"===e.transportType?{command:e.command,args:e.args,env:e.env,cwd:e.cwd}:{url:e.url,requestInit:e.requestInit}}function filterComateEnv(e){return Object.fromEntries(Object.entries(e||process.env).filter((([e])=>!e.startsWith("COMATE_"))))}function expandTilde(e){return e.replace(/^~(?=$|\/|\\)/,homedir())}function offsetToLine(e,t){if(t<=0)return 0;const r=Math.min(t,e.length);let n=0;for(let t=0;t<r;t++){const r=e.charCodeAt(t);10!==r?13===r&&(10===e.charCodeAt(t+1)&&t++,n++):n++}return n}function offsetToLineColumn(e,t){if(t<=0)return{line:0,column:0};const r=Math.min(t,e.length);let n=0,i=0;for(let t=0;t<r;t++){const r=e.charCodeAt(t);10!==r?13===r&&(10===e.charCodeAt(t+1)&&t++,n++,i=t+1):(n++,i=t+1)}return{line:n,column:r-i}}function secondsToMs(e){return 1e3*e}function formatPathEnv(e){const t=e.PATH;if(!t)return"(未设置)";return t.split(path__default.delimiter).map(((e,t)=>` [${t+1}] ${e}`)).join("\n")}function formatEnvDiagnostics(e){return`当前 PATH 环境变量:\n${formatPathEnv({...process.env,...e})}`}function trySpawnOnce(e,t,r){return new Promise((n=>{const i=spawn$5(e,t,{stdio:["ignore","pipe","pipe"],shell:!1,windowsHide:!0});let o="",s="",a=!1;const c=e=>{a||(a=!0,clearTimeout(A),i.removeAllListeners(),n(e))},A=setTimeout((()=>{i.kill("SIGKILL"),c({code:null,timeout:!0})}),r);i.stdout?.on("data",(e=>o+=e.toString())),i.stderr?.on("data",(e=>s+=e.toString())),i.on("error",(e=>{c({code:null,err:e})})),i.on("close",(e=>{c({code:e})}))}))}function createScanner(e,t=!1){const r=e.length;let n=0,i="",o=0,s=16,a=0,c=0,A=0,l=0,u=0;function d(t,r){let i=0,o=0;for(;i<t||!r;){let t=e.charCodeAt(n);if(t>=48&&t<=57)o=16*o+t-48;else if(t>=65&&t<=70)o=16*o+t-65+10;else{if(!(t>=97&&t<=102))break;o=16*o+t-97+10}n++,i++}return i<t&&(o=-1),o}function h(){if(i="",u=0,o=n,c=a,l=A,n>=r)return o=r,s=17;let t=e.charCodeAt(n);if(isWhiteSpace(t)){do{n++,i+=String.fromCharCode(t),t=e.charCodeAt(n)}while(isWhiteSpace(t));return s=15}if(isLineBreak(t))return n++,i+=String.fromCharCode(t),13===t&&10===e.charCodeAt(n)&&(n++,i+="\n"),a++,A=n,s=14;switch(t){case 123:return n++,s=1;case 125:return n++,s=2;case 91:return n++,s=3;case 93:return n++,s=4;case 58:return n++,s=6;case 44:return n++,s=5;case 34:return n++,i=function(){let t="",i=n;for(;;){if(n>=r){t+=e.substring(i,n),u=2;break}const o=e.charCodeAt(n);if(34===o){t+=e.substring(i,n),n++;break}if(92!==o){if(o>=0&&o<=31){if(isLineBreak(o)){t+=e.substring(i,n),u=2;break}u=6}n++}else{if(t+=e.substring(i,n),n++,n>=r){u=2;break}switch(e.charCodeAt(n++)){case 34:t+='"';break;case 92:t+="\\";break;case 47:t+="/";break;case 98:t+="\b";break;case 102:t+="\f";break;case 110:t+="\n";break;case 114:t+="\r";break;case 116:t+="\t";break;case 117:const e=d(4,!0);e>=0?t+=String.fromCharCode(e):u=4;break;default:u=5}i=n}}return t}(),s=10;case 47:const c=n-1;if(47===e.charCodeAt(n+1)){for(n+=2;n<r&&!isLineBreak(e.charCodeAt(n));)n++;return i=e.substring(c,n),s=12}if(42===e.charCodeAt(n+1)){n+=2;const t=r-1;let o=!1;for(;n<t;){const t=e.charCodeAt(n);if(42===t&&47===e.charCodeAt(n+1)){n+=2,o=!0;break}n++,isLineBreak(t)&&(13===t&&10===e.charCodeAt(n)&&n++,a++,A=n)}return o||(n++,u=1),i=e.substring(c,n),s=13}return i+=String.fromCharCode(t),n++,s=16;case 45:if(i+=String.fromCharCode(t),n++,n===r||!isDigit(e.charCodeAt(n)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return i+=function(){let t=n;if(48===e.charCodeAt(n))n++;else for(n++;n<e.length&&isDigit(e.charCodeAt(n));)n++;if(n<e.length&&46===e.charCodeAt(n)){if(n++,!(n<e.length&&isDigit(e.charCodeAt(n))))return u=3,e.substring(t,n);for(n++;n<e.length&&isDigit(e.charCodeAt(n));)n++}let r=n;if(n<e.length&&(69===e.charCodeAt(n)||101===e.charCodeAt(n)))if(n++,(n<e.length&&43===e.charCodeAt(n)||45===e.charCodeAt(n))&&n++,n<e.length&&isDigit(e.charCodeAt(n))){for(n++;n<e.length&&isDigit(e.charCodeAt(n));)n++;r=n}else u=3;return e.substring(t,r)}(),s=11;default:for(;n<r&&p(t);)n++,t=e.charCodeAt(n);if(o!==n){switch(i=e.substring(o,n),i){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return i+=String.fromCharCode(t),n++,s=16}}function p(e){if(isWhiteSpace(e)||isLineBreak(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}return{setPosition:function(e){n=e,i="",o=0,s=16,u=0},getPosition:()=>n,scan:t?function(){let e;do{e=h()}while(e>=12&&e<=15);return e}:h,getToken:()=>s,getTokenValue:()=>i,getTokenOffset:()=>o,getTokenLength:()=>n-o,getTokenStartLine:()=>c,getTokenStartCharacter:()=>o-l,getTokenError:()=>u}}function isWhiteSpace(e){return 32===e||9===e}function isLineBreak(e){return 10===e||13===e}function isDigit(e){return e>=48&&e<=57}var CharacterCodes;!function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",e[e.formFeed=12]="formFeed",e[e.tab=9]="tab"}(CharacterCodes||(CharacterCodes={}));const cachedSpaces=new Array(20).fill(0).map(((e,t)=>" ".repeat(t))),maxCachedValues=200,cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map(((e,t)=>"\n"+" ".repeat(t))),"\r":new Array(maxCachedValues).fill(0).map(((e,t)=>"\r"+" ".repeat(t))),"\r\n":new Array(maxCachedValues).fill(0).map(((e,t)=>"\r\n"+" ".repeat(t)))},"\t":{"\n":new Array(maxCachedValues).fill(0).map(((e,t)=>"\n"+"\t".repeat(t))),"\r":new Array(maxCachedValues).fill(0).map(((e,t)=>"\r"+"\t".repeat(t))),"\r\n":new Array(maxCachedValues).fill(0).map(((e,t)=>"\r\n"+"\t".repeat(t)))}},supportedEols=["\n","\r","\r\n"];function format$6(e,t,r){let n,i,o,s,a;if(t){for(s=t.offset,a=s+t.length,o=s;o>0&&!isEOL(e,o-1);)o--;let c=a;for(;c<e.length&&!isEOL(e,c);)c++;i=e.substring(o,c),n=computeIndentLevel(i,r)}else i=e,n=0,o=0,s=0,a=e.length;const c=getEOL(r,e),A=supportedEols.includes(c);let l,u=0,d=0;l=r.insertSpaces?cachedSpaces[r.tabSize||4]??repeat(cachedSpaces[1],r.tabSize||4):"\t";const h="\t"===l?"\t":" ";let p=createScanner(i,!1),g=!1;function f(){if(u>1)return repeat(c,u)+repeat(l,n+d);const e=l.length*(n+d);return!A||e>cachedBreakLinesWithSpaces[h][c].length?c+repeat(l,n+d):e<=0?c:cachedBreakLinesWithSpaces[h][c][e]}function m(){let e=p.scan();for(u=0;15===e||14===e;)14===e&&r.keepLines?u+=1:14===e&&(u=1),e=p.scan();return g=16===e||0!==p.getTokenError(),e}const E=[];function C(r,n,i){g||t&&!(n<a&&i>s)||e.substring(n,i)===r||E.push({offset:n,length:i-n,content:r})}let I=m();if(r.keepLines&&u>0&&C(repeat(c,u),0,0),17!==I){let e=p.getTokenOffset()+o;C(l.length*n<20&&r.insertSpaces?cachedSpaces[l.length*n]:repeat(l,n),o,e)}for(;17!==I;){let e=p.getTokenOffset()+p.getTokenLength()+o,t=m(),n="",i=!1;for(;0===u&&(12===t||13===t);){let r=p.getTokenOffset()+o;C(cachedSpaces[1],e,r),e=p.getTokenOffset()+p.getTokenLength()+o,i=12===t,n=i?f():"",t=m()}if(2===t)1!==I&&d--,r.keepLines&&u>0||!r.keepLines&&1!==I?n=f():r.keepLines&&(n=cachedSpaces[1]);else if(4===t)3!==I&&d--,r.keepLines&&u>0||!r.keepLines&&3!==I?n=f():r.keepLines&&(n=cachedSpaces[1]);else{switch(I){case 3:case 1:d++,n=r.keepLines&&u>0||!r.keepLines?f():cachedSpaces[1];break;case 5:n=r.keepLines&&u>0||!r.keepLines?f():cachedSpaces[1];break;case 12:n=f();break;case 13:u>0?n=f():i||(n=cachedSpaces[1]);break;case 6:r.keepLines&&u>0?n=f():i||(n=cachedSpaces[1]);break;case 10:r.keepLines&&u>0?n=f():6!==t||i||(n="");break;case 7:case 8:case 9:case 11:case 2:case 4:r.keepLines&&u>0?n=f():12!==t&&13!==t||i?5!==t&&17!==t&&(g=!0):n=cachedSpaces[1];break;case 16:g=!0}u>0&&(12===t||13===t)&&(n=f())}17===t&&(n=r.keepLines&&u>0?f():r.insertFinalNewline?c:"");C(n,e,p.getTokenOffset()+o),I=t}return E}function repeat(e,t){let r="";for(let n=0;n<t;n++)r+=e;return r}function computeIndentLevel(e,t){let r=0,n=0;const i=t.tabSize||4;for(;r<e.length;){let t=e.charAt(r);if(t===cachedSpaces[1])n++;else{if("\t"!==t)break;n+=i}r++}return Math.floor(n/i)}function getEOL(e,t){for(let e=0;e<t.length;e++){const r=t.charAt(e);if("\r"===r)return e+1<t.length&&"\n"===t.charAt(e+1)?"\r\n":"\r";if("\n"===r)return"\n"}return e&&e.eol||"\n"}function isEOL(e,t){return-1!=="\r\n".indexOf(e.charAt(t))}var ParseOptions,ScanError,SyntaxKind;function parse$f(e,t=[],r=ParseOptions.DEFAULT){let n=null,i=[];const o=[];function s(e){Array.isArray(i)?i.push(e):null!==n&&(i[n]=e)}const a={onObjectBegin:()=>{const e={};s(e),o.push(i),i=e,n=null},onObjectProperty:e=>{n=e},onObjectEnd:()=>{i=o.pop()},onArrayBegin:()=>{const e=[];s(e),o.push(i),i=e,n=null},onArrayEnd:()=>{i=o.pop()},onLiteralValue:s,onError:(e,r,n)=>{t.push({error:e,offset:r,length:n})}};return visit(e,a,r),i[0]}function parseTree$1(e,t=[],r=ParseOptions.DEFAULT){let n={type:"array",offset:-1,length:-1,children:[],parent:void 0};function i(e){"property"===n.type&&(n.length=e-n.offset,n=n.parent)}function o(e){return n.children.push(e),e}const s={onObjectBegin:e=>{n=o({type:"object",offset:e,length:-1,parent:n,children:[]})},onObjectProperty:(e,t,r)=>{n=o({type:"property",offset:t,length:-1,parent:n,children:[]}),n.children.push({type:"string",value:e,offset:t,length:r,parent:n})},onObjectEnd:(e,t)=>{i(e+t),n.length=e+t-n.offset,n=n.parent,i(e+t)},onArrayBegin:(e,t)=>{n=o({type:"array",offset:e,length:-1,parent:n,children:[]})},onArrayEnd:(e,t)=>{n.length=e+t-n.offset,n=n.parent,i(e+t)},onLiteralValue:(e,t,r)=>{o({type:getNodeType(e),offset:t,length:r,parent:n,value:e}),i(t+r)},onSeparator:(e,t,r)=>{"property"===n.type&&(":"===e?n.colonOffset=t:","===e&&i(t))},onError:(e,r,n)=>{t.push({error:e,offset:r,length:n})}};visit(e,s,r);const a=n.children[0];return a&&delete a.parent,a}function findNodeAtLocation$1(e,t){if(!e)return;let r=e;for(let e of t)if("string"==typeof e){if("object"!==r.type||!Array.isArray(r.children))return;let t=!1;for(const n of r.children)if(Array.isArray(n.children)&&n.children[0].value===e&&2===n.children.length){r=n.children[1],t=!0;break}if(!t)return}else{const t=e;if("array"!==r.type||t<0||!Array.isArray(r.children)||t>=r.children.length)return;r=r.children[t]}return r}function visit(e,t,r=ParseOptions.DEFAULT){const n=createScanner(e,!1),i=[];let o=0;function s(e){return e?t=>0===o&&e(t,n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter()):()=>!0}function a(e){return e?t=>0===o&&e(t,n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter(),(()=>i.slice())):()=>!0}function c(e){return e?()=>{if(o>0)o++;else{!1===e(n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter(),(()=>i.slice()))&&(o=1)}}:()=>!0}function A(e){return e?()=>{o>0&&o--,0===o&&e(n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter())}:()=>!0}const l=c(t.onObjectBegin),u=a(t.onObjectProperty),d=A(t.onObjectEnd),h=c(t.onArrayBegin),p=A(t.onArrayEnd),g=a(t.onLiteralValue),f=s(t.onSeparator),m=(C=t.onComment)?()=>0===o&&C(n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter()):()=>!0,E=s(t.onError);var C;const I=r&&r.disallowComments,y=r&&r.allowTrailingComma;function B(){for(;;){const e=n.scan();switch(n.getTokenError()){case 4:b(14);break;case 5:b(15);break;case 3:b(13);break;case 1:I||b(11);break;case 2:b(12);break;case 6:b(16)}switch(e){case 12:case 13:I?b(10):m();break;case 16:b(1);break;case 15:case 14:break;default:return e}}}function b(e,t=[],r=[]){if(E(e),t.length+r.length>0){let e=n.getToken();for(;17!==e;){if(-1!==t.indexOf(e)){B();break}if(-1!==r.indexOf(e))break;e=B()}}}function w(e){const t=n.getTokenValue();return e?g(t):(u(t),i.push(t)),B(),!0}function v(){switch(n.getToken()){case 3:return function(){h(),B();let e=!0,t=!1;for(;4!==n.getToken()&&17!==n.getToken();){if(5===n.getToken()){if(t||b(4,[],[]),f(","),B(),4===n.getToken()&&y)break}else t&&b(6,[],[]);e?(i.push(0),e=!1):i[i.length-1]++,v()||b(4,[],[4,5]),t=!0}return p(),e||i.pop(),4!==n.getToken()?b(8,[4],[]):B(),!0}();case 1:return function(){l(),B();let e=!1;for(;2!==n.getToken()&&17!==n.getToken();){if(5===n.getToken()){if(e||b(4,[],[]),f(","),B(),2===n.getToken()&&y)break}else e&&b(6,[],[]);(10!==n.getToken()?(b(3,[],[2,5]),0):(w(!1),6===n.getToken()?(f(":"),B(),v()||b(4,[],[2,5])):b(5,[],[2,5]),i.pop(),1))||b(4,[],[2,5]),e=!0}return d(),2!==n.getToken()?b(7,[2],[]):B(),!0}();case 10:return w(!0);default:return function(){switch(n.getToken()){case 11:const e=n.getTokenValue();let t=Number(e);isNaN(t)&&(b(2),t=0),g(t);break;case 7:g(null);break;case 8:g(!0);break;case 9:g(!1);break;default:return!1}return B(),!0}()}}return B(),17===n.getToken()?!!r.allowEmptyContent||(b(4,[],[]),!1):v()?(17!==n.getToken()&&b(9,[],[]),!0):(b(4,[],[]),!1)}function getNodeType(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":return e?Array.isArray(e)?"array":"object":"null";default:return"null"}}function setProperty(e,t,r,n){const i=t.slice(),o=parseTree$1(e,[]);let s,a;for(;i.length>0&&(a=i.pop(),s=findNodeAtLocation$1(o,i),void 0===s&&void 0!==r);)r="string"==typeof a?{[a]:r}:[r];if(s){if("object"===s.type&&"string"==typeof a&&Array.isArray(s.children)){const t=findNodeAtLocation$1(s,[a]);if(void 0!==t){if(void 0===r){if(!t.parent)throw new Error("Malformed AST");const r=s.children.indexOf(t.parent);let i,o=t.parent.offset+t.parent.length;if(r>0){let e=s.children[r-1];i=e.offset+e.length}else if(i=s.offset+1,s.children.length>1){o=s.children[1].offset}return withFormatting(e,{offset:i,length:o-i,content:""},n)}return withFormatting(e,{offset:t.offset,length:t.length,content:JSON.stringify(r)},n)}{if(void 0===r)return[];const t=`${JSON.stringify(a)}: ${JSON.stringify(r)}`,i=n.getInsertionIndex?n.getInsertionIndex(s.children.map((e=>e.children[0].value))):s.children.length;let o;if(i>0){let e=s.children[i-1];o={offset:e.offset+e.length,length:0,content:","+t}}else o=0===s.children.length?{offset:s.offset+1,length:0,content:t}:{offset:s.offset+1,length:0,content:t+","};return withFormatting(e,o,n)}}if("array"===s.type&&"number"==typeof a&&Array.isArray(s.children)){const t=a;if(-1===t){const t=`${JSON.stringify(r)}`;let i;if(0===s.children.length)i={offset:s.offset+1,length:0,content:t};else{const e=s.children[s.children.length-1];i={offset:e.offset+e.length,length:0,content:","+t}}return withFormatting(e,i,n)}if(void 0===r&&s.children.length>=0){const t=a,r=s.children[t];let i;if(1===s.children.length)i={offset:s.offset+1,length:s.length-2,content:""};else if(s.children.length-1===t){let e=s.children[t-1],r=e.offset+e.length;i={offset:r,length:s.offset+s.length-2-r,content:""}}else i={offset:r.offset,length:s.children[t+1].offset-r.offset,content:""};return withFormatting(e,i,n)}if(void 0!==r){let t;const i=`${JSON.stringify(r)}`;if(!n.isArrayInsertion&&s.children.length>a){const e=s.children[a];t={offset:e.offset,length:e.length,content:i}}else if(0===s.children.length||0===a)t={offset:s.offset+1,length:0,content:0===s.children.length?i:i+","};else{const e=a>s.children.length?s.children.length:a,r=s.children[e-1];t={offset:r.offset+r.length,length:0,content:","+i}}return withFormatting(e,t,n)}throw new Error(`Can not ${void 0===r?"remove":n.isArrayInsertion?"insert":"modify"} Array index ${t} as length is not sufficient`)}throw new Error(`Can not add ${"number"!=typeof a?"index":"property"} to parent of type ${s.type}`)}if(void 0===r)throw new Error("Can not delete in empty document");return withFormatting(e,{offset:o?o.offset:0,length:o?o.length:0,content:JSON.stringify(r)},n)}function withFormatting(e,t,r){if(!r.formattingOptions)return[t];let n=applyEdit(e,t),i=t.offset,o=t.offset+t.content.length;if(0===t.length||0===t.content.length){for(;i>0&&!isEOL(n,i-1);)i--;for(;o<n.length&&!isEOL(n,o);)o++}const s=format$6(n,{offset:i,length:o-i},{...r.formattingOptions,keepLines:!1});for(let e=s.length-1;e>=0;e--){const t=s[e];n=applyEdit(n,t),i=Math.min(i,t.offset),o=Math.max(o,t.offset+t.length),o+=t.content.length-t.length}return[{offset:i,length:e.length-(n.length-o)-i,content:n.substring(i,o)}]}function applyEdit(e,t){return e.substring(0,t.offset)+t.content+e.substring(t.offset+t.length)}!function(e){e.DEFAULT={allowTrailingComma:!1}}(ParseOptions||(ParseOptions={})),function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"}(ScanError||(ScanError={})),function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"}(SyntaxKind||(SyntaxKind={}));const parse$e=parse$f,parseTree=parseTree$1,findNodeAtLocation=findNodeAtLocation$1;var ParseErrorCode;function printParseErrorCode(e){switch(e){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}function modify(e,t,r,n){return setProperty(e,t,r,n)}function applyEdits(e,t){let r=t.slice(0).sort(((e,t)=>{const r=e.offset-t.offset;return 0===r?e.length-t.length:r})),n=e.length;for(let t=r.length-1;t>=0;t--){let i=r[t];if(!(i.offset+i.length<=n))throw new Error("Overlapping edit");e=applyEdit(e,i),n=i.offset}return e}!function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"}(ParseErrorCode||(ParseErrorCode={}));const FIELD_ALIASES={transportType:["type","transport","transport_type","transport-type"],command:["cmd","bin","exec","executable","program"],args:["arguments","params","parameters","argv","commandArgs"],cwd:["workdir","workingDir","workingDirectory","dir"],env:["environment","envs"],headers:["httpHeaders"],url:["endpoint"],timeout:["timeoutSeconds"]},normalizeAliasKey=e=>e.toLowerCase().replace(/[_-]/g,""),ALIAS_LOOKUP={};for(const[Sn,Qn]of Object.entries(FIELD_ALIASES))for(const _n of[Sn,...Qn]){const Dn=normalizeAliasKey(_n);Dn in ALIAS_LOOKUP||(ALIAS_LOOKUP[Dn]=Sn)}function normalizeTransportType(e){if("string"!=typeof e)throw new Error("Transport type must be a string");const t=e.trim().toLowerCase().replace(/-/g,"");if("streamablehttp"===t||"http"===t)return"streamableHttp";if("sse"===t)return"sse";if("stdio"===t)return"stdio";throw new Error(`Unsupported transport type: ${e}. Supported types are: stdio, sse, streamableHttp`)}function normalizeBoolean(e){if("boolean"==typeof e)return e;if("string"==typeof e){const t=e.toLowerCase().trim();if("true"===t)return!0;if("false"===t)return!1}throw new Error(`Invalid boolean value: ${e}. Use true, false, "true", or "false"`)}function normalizeNumber(e){if("number"==typeof e)return e;if("string"==typeof e){const t=parseFloat(e.trim());if(!isNaN(t)&&isFinite(t))return t}throw new Error(`Invalid number value: ${e}. Use a number or numeric string`)}function normalizeString(e){if("string"==typeof e)return e.trim();throw new Error(`Invalid string value: ${e}. Use a string`)}function normalizeArray(e){return(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.trim():e))}function normalizeObject(e){if("object"==typeof e&&null!==e&&!Array.isArray(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}throw new Error(`Invalid object value: ${e}. Use an object or JSON string`)}const NORMALIZATION_RULES={transportType:normalizeTransportType,disabled:normalizeBoolean,timeout:normalizeNumber,args:normalizeArray,command:normalizeString,cwd:normalizeString,url:normalizeString,env:normalizeObject,headers:normalizeObject};function normalizeConfigValues(e){const t={...e};for(const[e,r]of Object.entries(NORMALIZATION_RULES))if(e in t)try{t[e]=r(t[e])}catch(t){throw new Error(`Failed to normalize field '${e}': ${t.message}`)}return t}function normalizeFields(e){const t={};for(const[r,n]of Object.entries(e)){const e="string"==typeof r?ALIAS_LOOKUP[normalizeAliasKey(r)]:void 0;e?e in t&&r!==e||(t[e]=n):t[r]=n}return void 0!==t.url&&(t.headers={...t.requestInit?.headers,...t.headers}),normalizeConfigValues(t)}function validateBasicConfig(e,t){if(!e)throw new Error("Server name cannot be empty");const r=void 0!==t.url,n=void 0!==t.command;if(!r&&!n)throw new Error(`Server ${e} must have either url or command`);if(r&&n)throw new Error(`Server ${e} cannot have both url and command`)}function validateTransportType(e,t,r){if("stdio"===r&&!t.command)throw new Error(`Server ${e} with transportType 'stdio' must have command`);if(("sse"===r||"streamableHttp"===r)&&!t.url)throw new Error(`Server ${e} with transportType '${r}' must have url`)}const DEFAULT_MCP_TIMEOUT_SECONDS=30;function fillStdioDefaults(e){return{timeout:DEFAULT_MCP_TIMEOUT_SECONDS,disabled:!1,args:[],env:{},cwd:homedir(),...e,transportType:"stdio"}}function fillSseDefaults(e){const{headers:t,...r}=e;return{timeout:DEFAULT_MCP_TIMEOUT_SECONDS,disabled:!1,...r,transportType:"sse",requestInit:{...e.requestInit,headers:t||e.requestInit?.headers||{}}}}function fillStreamableHttpDefaults(e){const{headers:t,...r}=e;return{timeout:DEFAULT_MCP_TIMEOUT_SECONDS,disabled:!1,...r,transportType:"streamableHttp",requestInit:{...e.requestInit,headers:t||e.requestInit?.headers||{}}}}function fillDefaults(e,t){if("stdio"===t)return fillStdioDefaults(e);if("sse"===t)return fillSseDefaults(e);if("streamableHttp"===t)return fillStreamableHttpDefaults(e);throw new Error(`Unsupported transport type: ${t}`)}const ENV_VARIABLES={USERNAME:()=>kernel.config.username,WORKSPACE:()=>{const e=kernel.env.workspaceInfo.rootUri;return fileURLToPath$1(e)}};function replaceEnvVariable(e){return"string"!=typeof e?e:e.replace(/\$COMATE\.ENV\.([A-Z_]+)/g,((e,t)=>{const r=ENV_VARIABLES[t];return r?r():`$COMATE.ENV.${t}`}))}function resolveHttpEnvVariables(e){const t=e.requestInit?.headers||{},r={};for(const[e,n]of Object.entries(t))r[e]="string"==typeof n?replaceEnvVariable(n):n;return{...e,requestInit:{...e.requestInit,headers:r}}}function resolveStdioEnvVariables(e){const t=replaceEnvVariable(e.command),r=e.args.map((e=>replaceEnvVariable(e))),n=Object.fromEntries(Object.entries(e.env).map((([e,t])=>[e,replaceEnvVariable(t)])));return{...e,command:t,args:r,env:n,cwd:replaceEnvVariable(e.cwd)}}function resolveEnvVariables(e,t){if("stdio"===t)return resolveStdioEnvVariables(e);return"sse"===t||"streamableHttp"===t?resolveHttpEnvVariables(e):e}function resolveStdioPathVariables(e){const t=e=>{if(!e)return e;const t=expandTilde(e);return e.startsWith("~")?path__default.normalize(t):t};return{...e,command:t(e.command),args:e.args.map(t),cwd:t(e.cwd)}}function resolvePathVariables(e,t){return"stdio"===t?resolveStdioPathVariables(e):e}const{isPlainObject:isPlainObject$2}=_$H;function assertServersObject(e,t){if(!isPlainObject$2(e))throw new Error(t);return e}function extractRawSettings(e,t){if("mcpServers"in e)return assertServersObject(e.mcpServers,'"mcpServers" 字段应为对象');if("servers"in e)return t?.warn('检测到 "servers" 字段,已兼容处理为 "mcpServers"。请更新为正式字段以获得完整支持。'),assertServersObject(e.servers,'"servers" 字段应为对象');throw new Error('缺少 "mcpServers" 字段')}function inferTransportType(e){if(e.transportType)return e.transportType;if(void 0!==e.url){const t=e.url.toLowerCase();return t.endsWith("/sse")?"sse":(t.endsWith("/mcp"),"streamableHttp")}if(void 0!==e.command)return"stdio";throw new Error("Cannot infer transport type from config")}function processServerConfig(e,t){const r=normalizeFields(t);validateBasicConfig(e,r);const n=inferTransportType(r);validateTransportType(e,r,n);const i=resolvePathVariables(resolveEnvVariables(fillDefaults(r,n),n),n);return deepDropNilValue(i)}function deriveParsedSettings(e,t){const r={};for(const[n,i]of Object.entries(e))r[n]={...processServerConfig(n,i),source:t};return r}function parseMcpSettingsRoot(e,t,r){if(!isPlainObject$2(e))throw new Error("MCP 设置文件的根节点必须是对象");const n=extractRawSettings(e,r);return{raw:n,parsed:deriveParsedSettings(n,t)}}function parseMcpSettingsDocument(e,t,r){const n=[],i=parse$e(e,n,{allowTrailingComma:!0,disallowComments:!1});if(n.length>0){const[{error:t,offset:r=0}]=n,{line:i,column:o}=offsetToLineColumn(e,r),s=`${printParseErrorCode(t)} (行 ${i+1}, 列 ${o+1})`;throw new Error(s)}return parseMcpSettingsRoot(i,t,r)}const{isEmpty:isEmpty}=_$H;class McpSettingsFileStore extends TypedEventEmitter{filePath;source;mcpLogger;watcher;snapshot={raw:{},parsed:{}};status="uninitialized";constructor(e,t,r){super(),this.filePath=e,this.source=t,this.mcpLogger=r,this.watchMcpSettingsFile()}async getSnapshot(){return await this.ensureSnapshotLoaded(),{...this.snapshot}}async dispose(){await(this.watcher?.close()),this.watcher=void 0,this.snapshot={raw:{},parsed:{}},this.status="uninitialized"}getSettingsFilePath(){return this.filePath}getSource(){return this.source}getStatus(){return this.status}async ensureSnapshotLoaded(){if("uninitialized"!==this.status)return;if(!await isFileAccessable(this.filePath))return void this.transitionToMissing();const e=await kernel.fs.readFile(this.filePath,"utf-8"),t=this.syncStateFromContent(e);if("parse_error"===t.state)throw t.error}syncStateFromContent(e,t){const r={...this.snapshot};if(!e.trim())return this.transitionToMissing(),{state:"missing",previousSnapshot:r};try{const t=parseMcpSettingsDocument(e,this.source,this.mcpLogger),n=!equal$6(t.parsed,r.parsed);return this.transitionToParsed(t),{state:"parsed",snapshot:t,previousSnapshot:r,changed:n}}catch(e){if(!t||"manual"===t.type){const r=t?`手动操作(${t.operation})`:"初始加载";this.mcpLogger.error("MCP 设置解析失败",r,e.message)}return this.transitionToParseError(),{state:"parse_error",previousSnapshot:r,error:e}}}transitionToMissing(){this.snapshot={raw:{},parsed:{}},this.status="missing"}transitionToParsed(e){this.snapshot={raw:e.raw,parsed:e.parsed},this.status="parsed"}transitionToParseError(){this.status="parse_error"}emitSyncResult(e,t){if(this.logSyncOutcome(e,t),"missing"!==e.state)"parsed"!==e.state?this.emit("parseError",{snapshot:this.snapshot,previousSnapshot:e.previousSnapshot,error:e.error,source:t}):this.emit("parsed",{snapshot:this.snapshot,previousSnapshot:e.previousSnapshot,changed:e.changed,source:t});else{const r=!isEmpty(e.previousSnapshot.parsed);this.emit("missing",{snapshot:this.snapshot,previousSnapshot:e.previousSnapshot,hadConfigs:r,source:t})}}async fileContentChangeHandler(e){const t=await kernel.fs.readFile(this.filePath,"utf-8"),r={type:"fs",event:e},n=this.syncStateFromContent(t,r);this.emitSyncResult(n,r)}watchMcpSettingsFile(){try{const e="global"===this.source?this.filePath:path__default.dirname(this.filePath);this.watcher=chokidar.watch(e,{persistent:!0,ignoreInitial:!0}),this.watcher.on("add",(async t=>{t===this.filePath&&(this.mcpLogger.info(`文件添加事件:监视对象 ${e},变动对象 ${t}`),await this.fileContentChangeHandler("add"))})).on("change",(async t=>{t===this.filePath&&(this.mcpLogger.info(`文件改动事件:监视对象 ${e},变动对象 ${t}`),await this.fileContentChangeHandler("change"))})).on("unlink",(t=>{if(t===this.filePath){this.mcpLogger.info(`文件删除事件:监视对象 ${e},变动对象 ${t}`);const r={...this.snapshot},n=!isEmpty(r.parsed);this.transitionToMissing(),this.emit("missing",{snapshot:this.snapshot,previousSnapshot:r,hadConfigs:n,source:{type:"fs",event:"unlink"}})}})).on("unlinkDir",(t=>{this.mcpLogger.info(`文件夹删除事件:监视对象 ${e},变动对象 ${t}`),"global"!==this.source&&e===t&&this.watcher?.add(e)}))}catch(e){this.mcpLogger.error("获取 MCP 设置文件失败",e.message)}}logSyncOutcome(e,t){const r="manual"===t.type?`手动操作(${t.operation})`:`文件事件(${t.event})`;if("missing"!==e.state)if("parsed"!==e.state)this.mcpLogger.error("MCP 设置状态 -> parse_error",r,`path=${this.filePath}`,e.error.message);else{const t=e.changed?"changed":"unchanged";this.mcpLogger.info("MCP 设置状态 -> parsed",r,`status=${t}`,`path=${this.filePath}`)}else this.mcpLogger.info("MCP 设置状态 -> missing",r,`path=${this.filePath}`)}}const DEFAULT_SETTINGS_JSON={mcpServers:{}},JSONC_FORMAT_OPTIONS={insertSpaces:!0,tabSize:4};function ensureContentHasRoot(e){const t=e.trim()?e:JSON.stringify(DEFAULT_SETTINGS_JSON,null,4),r=[],n=parse$e(t,r,{allowTrailingComma:!0,disallowComments:!1});if(!r.length&&n&&"object"==typeof n&&void 0!==n.mcpServers)return t;return applyEdits(t,modify(t,["mcpServers"],{},{formattingOptions:JSONC_FORMAT_OPTIONS}))}function updateJsoncContent(e,t,r,n){let i=ensureContentHasRoot(e);if("delete"!==r&&!n)throw new Error("更新/新增配置不能为空");if("delete"===r){return applyEdits(i,modify(i,["mcpServers",t],void 0,{formattingOptions:JSONC_FORMAT_OPTIONS,isArrayInsertion:!1}))}const o=modify(i,["mcpServers",t],n,{formattingOptions:JSONC_FORMAT_OPTIONS,getInsertionIndex:e=>"add"===r?0:e.length});return i=applyEdits(i,o),i}class McpSettingsFileEditor{store;virtualEditor;mcpLogger;constructor(e,t,r){this.store=e,this.virtualEditor=t,this.mcpLogger=r}async ensureFileExists(){const e=this.store.getSettingsFilePath();if(!await isFileAccessable(e)){const t=path__default.dirname(e);await kernel.fs.mkdir(t,{recursive:!0}),await kernel.fs.writeFile(e,JSON.stringify(DEFAULT_SETTINGS_JSON,null,4)),this.mcpLogger.info(`创建配置文件 path=${e}`)}}async updateServer(e,t,r){if(await this.ensureFileExists(),await this.store.ensureSnapshotLoaded(),"parse_error"===this.store.getStatus())throw new Error("配置文件存在语法错误,请先修复");const n=await this.store.getSnapshot(),i=this.applyMutation(n.raw,e,t,r),o=await this.saveSettings(i,e,t);return this.getLineNumbers(t,e,o)}async fetchServer(e){await this.ensureFileExists();const t=await this.store.getSnapshot();if(!e||!t.raw[e])return{startLine:0,endLine:0};const r=await this.readSettingsContent();return this.getLineNumbers("update",e,r)}applyMutation(e,t,r,n){if("add"===r){if(!n)throw new Error("新增配置不能为空");const{[t]:r,...i}=e;return{[t]:n,...i}}if("delete"===r){const{[t]:r,...n}=e;return n}if("update"===r){if(!e[t])throw new Error(`Server ${t} 不存在`);return{...e,[t]:{...e[t],...n??{}}}}return e}async saveSettings(e,t,r){const n=this.store.getSettingsFilePath(),i=updateJsoncContent(await this.readSettingsContent(),t,r,"delete"===r?void 0:e[t]);return await this.virtualEditor.saveDocumentWithReplaceContentAndOpen({absolutePath:n,content:i}),await this.virtualEditor.openDocument({absolutePath:n}),i}async readSettingsContent(){try{return await kernel.fs.readFile(this.store.getSettingsFilePath(),"utf-8")}catch{return JSON.stringify(DEFAULT_SETTINGS_JSON,null,4)}}getLineNumbers(e,t,r){if("delete"===e)return{startLine:0,endLine:0};const n=[],i=parseTree(r,n,{allowTrailingComma:!0,disallowComments:!1});if(!i||n.length)return{startLine:0,endLine:0};const o=findNodeAtLocation(i,["mcpServers"]),s=o?.children?.find((e=>e.children?.[0].value===t)),a=s?.children?.[0],c=s?.children?.[1];if(!a||!c)return{startLine:0,endLine:0};return{startLine:offsetToLine(r,a.offset),endLine:offsetToLine(r,c.offset+c.length)}}}class McpSettingsAggregator extends TypedEventEmitter{mcpLogger;stores;editors;constructor(e,t,r){super(),this.mcpLogger=t;const n=getGlobalSettingsPath(),i=getProjectSettingsPath(e),o=getLocalSettingsPath(e);t.info("初始化 MCP 配置聚合器:\n",`global=${n}\n`,`project=${i}\n`,`local=${o}`);const s=new McpSettingsFileStore(n,"global",t),a=new McpSettingsFileStore(i,"project",t),c=new McpSettingsFileStore(o,"local",t);this.stores=new Map([["global",s],["project",a],["local",c]]),this.editors=new Map([["global",new McpSettingsFileEditor(s,r,t)],["project",new McpSettingsFileEditor(a,r,t)],["local",new McpSettingsFileEditor(c,r,t)]]),this.registerStoreListeners()}getStore(e){return this.stores.get(e)}getEditor(e){return this.editors.get(e)}async getMergedSnapshot(e=!1){const t=await Promise.all(["global","project","local"].map((e=>this.stores.get(e))).filter((e=>!!e)).map((e=>e.getSnapshot())));return this.mergeSnapshots(t,e)}async getLayeredSettings(e=!1){const[t,r,n]=await Promise.all([this.stores.get("global")?.getSnapshot()??{raw:{},parsed:{}},this.stores.get("project")?.getSnapshot()??{raw:{},parsed:{}},this.stores.get("local")?.getSnapshot()??{raw:{},parsed:{}}]);if(e){const e={global:Object.keys(t.parsed).length,project:Object.keys(r.parsed).length,local:Object.keys(n.parsed).length};this.mcpLogger.info(`MCP 分层配置获取完成: global=${e.global}, project=${e.project}, local=${e.local}`)}return{global:t,project:r,local:n}}async dispose(){this.mcpLogger.info("销毁 MCP 配置聚合器");for(const e of this.stores.values())e.removeAllListeners(),await e.dispose();this.stores.clear(),this.editors.clear()}registerStoreListeners(){for(const e of this.stores.values())e.on("parsed",(()=>{this.handleStoreChange()})),e.on("missing",(()=>{this.handleStoreChange()})),e.on("parseError",(({error:t})=>{this.emit("parseError",{error:t,source:e.getSource()})}))}async handleStoreChange(){const e=await this.getMergedSnapshot(!0);this.emit("changed",e)}mergeSnapshots(e,t=!1){const r={},n={},i=new Map,o=new Map;for(const t of e){for(const[e,r]of Object.entries(t.parsed)){const t=i.get(e);if(t){const n=o.get(e)||[t];n.push(r.source),o.set(e,n)}i.set(e,r.source)}Object.assign(r,t.raw),Object.assign(n,t.parsed)}if(t&&o.size>0){const e=Array.from(o.entries()).map((([e,t])=>`${e}(${t.join("→")})`)).join(", ");this.mcpLogger.info(`MCP 配置合并完成,共 ${i.size} 个服务器`,`配置覆盖: ${e}`)}return{raw:r,parsed:n}}}class McpSettingsWatcher{mcpLogger;eventGateway;aggregator;normalizedChangeHandlers=new Set;lastMergedSnapshot;debouncedEmitChange;constructor(e,t,r){this.mcpLogger=e,this.eventGateway=r;const n=kernel.env.workspaceInfo.rootPath;if(!n)throw new Error("未打开工作区,请打开工作区");this.aggregator=new McpSettingsAggregator(n,e,t),this.debouncedEmitChange=_$H.debounce((()=>{this.emitAggregatedChange()}),100),this.aggregator.on("changed",(e=>{this.lastMergedSnapshot=e,this.debouncedEmitChange()})),this.aggregator.on("parseError",(({error:e,source:t})=>{this.debouncedEmitChange.cancel(),this.lastMergedSnapshot=void 0,this.mcpLogger.error(`MCP 配置文件解析失败 (${t})`,e.message),this.eventGateway.notifyConfigUpdated({error:`${t} 配置文件解析失败: ${e.message}`})})),this.registerGatewayHandlers()}onParsedSettingsChange(e){return this.normalizedChangeHandlers.add(e),()=>{this.normalizedChangeHandlers.delete(e)}}async getMergedSnapshot(){return this.aggregator.getMergedSnapshot()}async getLayeredSnapshot(){return this.aggregator.getLayeredSettings()}async dispose(){this.eventGateway.unregisterRequestHandler(PT_WEBVIEW_MCP_CONFIG_CREATE_REQUEST),this.eventGateway.unregisterRequestHandler(PT_WEBVIEW_MCP_CONFIG_FETCH_REQUEST),this.eventGateway.unregisterRequestHandler(PT_WEBVIEW_MCP_CONFIG_UPDATE_REQUEST),await this.aggregator.dispose(),this.normalizedChangeHandlers.clear(),this.debouncedEmitChange.cancel()}registerGatewayHandlers(){this.eventGateway.registerRequestHandler(PT_WEBVIEW_MCP_CONFIG_CREATE_REQUEST,(e=>this.createMcpServerConfig(e))),this.eventGateway.registerRequestHandler(PT_WEBVIEW_MCP_CONFIG_FETCH_REQUEST,(e=>this.fetchMcpServerConfig(e))),this.eventGateway.registerRequestHandler(PT_WEBVIEW_MCP_CONFIG_UPDATE_REQUEST,(e=>this.updateServerSettings(e)))}async createMcpServerConfig(e){const t=this.aggregator.getEditor(e);if(!t)throw new Error(`无法获取 ${e} 层级的编辑器`);await t.ensureFileExists();const r=this.aggregator.getStore(e);if(!r)throw new Error(`无法获取 ${e} 层级的配置存储`);return r.getSettingsFilePath()}async updateServerSettings(e){const{serverName:t,type:r,source:n}=e,i="config"in e?e.config:void 0,o=this.aggregator.getEditor(n);if(!o)throw new Error(`无法获取 ${n} 层级的编辑器`);const s=this.aggregator.getStore(n);if(!s)throw new Error(`无法获取 ${n} 层级的配置存储`);this.mcpLogger.info(`手动 ${r} MCP Server ${t} target=${n}`);const{startLine:a,endLine:c}=await o.updateServer(t,r,i),A=await this.aggregator.getMergedSnapshot();return{filePath:s.getSettingsFilePath(),startLine:a,endLine:c,snapshot:A,config:A.parsed}}async fetchMcpServerConfig(e){const t=await this.aggregator.getMergedSnapshot(),{name:r,source:n}=e,i=this.aggregator.getStore(n);if(!i)throw new Error(`无法获取 ${n} 层级的配置存储`);if(!r||!t.raw[r])return{filePath:i.getSettingsFilePath(),startLine:0,endLine:0,snapshot:t,config:t.parsed};const o=this.aggregator.getEditor(n);if(!o)throw new Error(`无法获取 ${n} 层级的编辑器`);const{startLine:s,endLine:a}=await o.fetchServer(r);return{filePath:i.getSettingsFilePath(),startLine:s,endLine:a,snapshot:t,config:t.parsed}}async emitAggregatedChange(){const e=this.lastMergedSnapshot;if(!e)return;const t=await this.aggregator.getLayeredSettings(!0);await this.eventGateway.notifyConfigUpdated({layered:t});for(const t of this.normalizedChangeHandlers)try{t(e)}catch(e){this.mcpLogger.error("执行 MCP 配置变更回调失败",e.message)}}}const getCurrentTime=()=>dayjs$1().format("YYYY-MM-DD HH:mm:ss.SSS"),getLogFileName=()=>`mcp-${dayjs$1().format("YYYY-MM-DD")}.log`;class McpLogger{static createdOutputChannelKeys=new Set;logFolder="";currentLogFile="";currentDate="";stream=null;serverName;constructor(e){this.serverName=e,this.init()}get normalizedAbsolutedPath(){return isJetbrains?formatWin32PathSep(this.currentLogFile):this.currentLogFile}init(){if(this.logFolder=path__default.join(homedir(),".comate-engine","mcp-log"),fs__default$1.mkdirSync(this.logFolder,{recursive:!0}),this.currentDate=dayjs$1().format("YYYY-MM-DD"),this.currentLogFile=path__default.join(this.logFolder,getLogFileName()),isVscode){const e=this.getOutputChannelKey();McpLogger.createdOutputChannelKeys.has(e)||(McpLogger.createdOutputChannelKeys.add(e),kernel.connect.sendNotification(KERNEL_MCP_OUTPUT_CHANNEL_CREATE,{serverName:this.serverName}))}this.cleanOldLogs()}log(e,t){const r=this.serverName?`[${this.serverName}] `:"",n=t.map((e=>{if(e instanceof Error)return`${e.message}\n${e.stack||""}`;if("object"==typeof e&&null!==e)try{return JSON.stringify(e,null,2)}catch{return String(e)}return String(e)})),i=`[${getCurrentTime()}] [${e}] ${r}${n.join(" ")}`;isVscode&&kernel.connect.sendNotification(KERNEL_MCP_OUTPUT_CHANNEL_MESSAGE,{serverName:this.serverName,message:i});try{this.ensureStream()&&this.stream?.writable&&this.stream.write(i+"\n")}catch(e){kernel.logger.error("MCP 日志写入文件失败:",e)}}info(...e){this.log("INFO",e)}warn(...e){this.log("WARN",e)}error(...e){this.log("ERROR",e)}dispose(){this.stream&&this.stream.end()}async cleanOldLogs(e=3){try{const t=await fs__default$1.promises.readdir(this.logFolder),r=dayjs$1();for(const n of t)n.startsWith("mcp-")&&n.endsWith(".log")&&await this.cleanSingleLogFile(n,r,e)}catch{this.warn("日志清理失败")}}async cleanSingleLogFile(e,t,r){const n=path__default.join(this.logFolder,e);try{const i=await fs__default$1.promises.stat(n);t.diff(dayjs$1(i.mtime),"day")>r&&(await fs__default$1.promises.unlink(n),this.info(`已清理旧日志文件: ${e}`))}catch{}}getCurrentLogFilePath(){const e=dayjs$1().format("YYYY-MM-DD");return this.currentDate!==e&&(this.currentDate=e,this.currentLogFile=path__default.join(this.logFolder,getLogFileName()),this.stream&&(this.stream.end(),this.stream=null)),this.currentLogFile}ensureStream(){try{if(!this.stream||!this.stream.writable){const e=this.getCurrentLogFilePath();this.stream=fs__default$1.createWriteStream(e,{flags:"a"})}return!0}catch(e){return kernel.logger.error("MCP 日志流创建失败:",e),!1}}getOutputChannelKey(){return this.serverName??"__global__"}}class ConcurrentPool{maxConcurrent;running;pending;queue;completionListeners=[];constructor(e=5){this.maxConcurrent=e,this.queue=[],this.running=0,this.pending=0}add(e){return this.pending++,new Promise(((t,r)=>{this.queue.push((()=>Promise.resolve(e()).then(t).catch(r).finally((()=>{this.running--,this.pending--,this.next(),this.checkAllTasksDone()})))),this.next()}))}next(){for(;this.running<this.maxConcurrent&&this.queue.length>0;){const e=this.queue.shift();this.running++,e()}}checkAllTasksDone(){0===this.pending&&(this.completionListeners.forEach((e=>e())),this.completionListeners=[])}allTasksDone(){return new Promise((e=>{0===this.pending?e():this.completionListeners.push(e)}))}}const DEFAULT_REQUEST_TIMEOUT_MSEC=6e4;class Protocol{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(CancelledNotificationSchema,(e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)})),this.setNotificationHandler(ProgressNotificationSchema,(e=>{this._onprogress(e)})),this.setRequestHandler(PingRequestSchema,(e=>({})))}_setupTimeout(e,t,r,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new McpError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,r,n;this._transport=e;const i=null===(t=this.transport)||void 0===t?void 0:t.onclose;this._transport.onclose=()=>{null==i||i(),this._onclose()};const o=null===(r=this.transport)||void 0===r?void 0:r.onerror;this._transport.onerror=e=>{null==o||o(e),this._onerror(e)};const s=null===(n=this._transport)||void 0===n?void 0:n.onmessage;this._transport.onmessage=(e,t)=>{null==s||s(e,t),isJSONRPCResponse(e)||isJSONRPCError(e)?this._onresponse(e):isJSONRPCRequest(e)?this._onrequest(e,t):isJSONRPCNotification(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new McpError(ErrorCode.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then((()=>r(e))).catch((e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`))))}_onrequest(e,t){var r,n;const i=null!==(r=this._requestHandlers.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler,o=this._transport;if(void 0===i)return void(null==o||o.send({jsonrpc:"2.0",id:e.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}}).catch((e=>this._onerror(new Error(`Failed to send an error response: ${e}`)))));const s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);const a={signal:s.signal,sessionId:null==o?void 0:o.sessionId,_meta:null===(n=e.params)||void 0===n?void 0:n._meta,sendNotification:t=>this.notification(t,{relatedRequestId:e.id}),sendRequest:(t,r,n)=>this.request(t,r,{...n,relatedRequestId:e.id}),authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo};Promise.resolve().then((()=>i(e,a))).then((t=>{if(!s.signal.aborted)return null==o?void 0:o.send({result:t,jsonrpc:"2.0",id:e.id})}),(t=>{var r;if(!s.signal.aborted)return null==o?void 0:o.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:ErrorCode.InternalError,message:null!==(r=t.message)&&void 0!==r?r:"Internal error"}})})).catch((e=>this._onerror(new Error(`Failed to send response: ${e}`)))).finally((()=>{this._requestHandlerAbortControllers.delete(e.id)}))}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),i=this._progressHandlers.get(n);if(!i)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(e){return void o(e)}i(r)}_onresponse(e){const t=Number(e.id),r=this._responseHandlers.get(t);if(void 0!==r)if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),isJSONRPCResponse(e))r(e);else{r(new McpError(e.error.code,e.error.message,e.error.data))}else this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){const{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}=null!=r?r:{};return new Promise(((s,a)=>{var c,A,l,u,d,h;if(!this._transport)return void a(new Error("Not connected"));!0===(null===(c=this._options)||void 0===c?void 0:c.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(A=null==r?void 0:r.signal)||void 0===A||A.throwIfAborted();const p=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:p};(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(p,r.onprogress),g.params={...e.params,_meta:{...(null===(l=e.params)||void 0===l?void 0:l._meta)||{},progressToken:p}});const f=e=>{var t;this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(e)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}).catch((e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)))),a(e)};this._responseHandlers.set(p,(e=>{var n;if(!(null===(n=null==r?void 0:r.signal)||void 0===n?void 0:n.aborted)){if(e instanceof Error)return a(e);try{const r=t.parse(e.result);s(r)}catch(e){a(e)}}})),null===(u=null==r?void 0:r.signal)||void 0===u||u.addEventListener("abort",(()=>{var e;f(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)}));const m=null!==(d=null==r?void 0:r.timeout)&&void 0!==d?d:DEFAULT_REQUEST_TIMEOUT_MSEC;this._setupTimeout(p,m,null==r?void 0:r.maxTotalTimeout,(()=>f(new McpError(ErrorCode.RequestTimeout,"Request timed out",{timeout:m}))),null!==(h=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==h&&h),this._transport.send(g,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}).catch((e=>{this._cleanupTimeout(p),a(e)}))}))}async notification(e,t){var r,n;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);if((null!==(n=null===(r=this._options)||void 0===r?void 0:r.debouncedNotificationMethods)&&void 0!==n?n:[]).includes(e.method)&&!e.params&&!(null==t?void 0:t.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then((()=>{var r;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const n={...e,jsonrpc:"2.0"};null===(r=this._transport)||void 0===r||r.send(n,t).catch((e=>this._onerror(e)))}))}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,((r,n)=>Promise.resolve(t(e.parse(r),n))))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,(r=>Promise.resolve(t(e.parse(r)))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function mergeCapabilities(e,t){return Object.entries(t).reduce(((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e)),{...e})}var uri_all={exports:{}};
|
|
536
|
+
`}buildStaticContexts(e,t,r){const n=r.map((e=>({type:"GIT_STATUS",content:e})));return[...n,{type:"ENV",content:this.buildEnvDescription(e,t.defaultShell,t.os)}]}async buildStaticContextsAsync(e){const[t,r]=await Promise.all([safePromise(this.getSysInfo(e[0]),getDefaultSysInfo(e[0])),safePromise(getGitStatusDescriptionForMultiple(e),GIT_STATUS_ERROR_MESSAGE)]);return this.buildStaticContexts(e,t,r)}async buildUploadBaseInfo(e){const t=osName(),[r,n]=await Promise.all([getRepoName(e).catch((()=>"")),getCurrentBranch(e).catch((()=>""))]);return{os:getOsName(),osVersion:t,extName:kernel.env.ideName,extVersion:kernel.env.extensionVersion,ideType:kernel.env.ideSeries,ideName:kernel.env.ideName,ideVersion:kernel.env.ideVersion,vcsType:r?"git":void 0,vcsRepo:r,vcsBranchName:n,username:kernel.config.username,license:kernel.config.license,pluginVersion:kernel.env.extensionVersion,device:kernel.env.deviceId,triggerSource:"MISSION"===kernel.env.mode?"MISSION":""}}start(e){const t=this.params,r=this.buildSystemReminder(e.agent.agentId,e.agent.agentName);this.params=void 0,this.quotaExceedMessage="";const{query:n,modelKey:i,rootPath:o,rootPaths:s,agent:a,knowledges:c,rejectedFiles:A,selfDefineInstruction:l,rollbackMessageId:u,useCodebaseSearch:d,sessionStartContextPromise:h,appendSystemPrompt:p,channel:g,...f}=e;this.rootPath=o,this.rootPaths=s||[o];const m={agentId:a.agentId,agentName:a.agentName,isProjectAgent:!!a.isProjectAgent};kernel.logger.info("[Zulu] ParameterCollector start"),this.promise=Promise.all([safePromise(apiPostConvesation({...f,agentInfo:m}),{conversationId:-1,taskId:void 0,traceId:f.traceId},6e5),safePromise(this.getSysInfo(this.rootPath),getDefaultSysInfo(this.rootPath)),safePromise(this.getMcpServers(this.getAgentMcpServers(a)),[]),safePromise(hasCurrentCodebaseIndexed(),!1,6e4),safePromise(contextsFromWebview2AgentContext(c,A,o,this.virtualEditor,f.traceId),[]),safePromise(getGitStatusDescriptionForMultiple(this.rootPaths),GIT_STATUS_ERROR_MESSAGE),safePromise(getAllSkillMetadata(o,this.mcpManager),[]),safePromise(getAllAgents(o,!0),[]),safePromise(this.buildUploadBaseInfo(o),{}),safePromise(fetchQuota({key:kernel.config.key}),void 0),h??Promise.resolve(void 0),safePromise(iocContainer.get(FeatureSetProvider).getFeatures(["en_verif_sub"]),{})]).then((e=>{const o=e[0],s=e[1],A=e[2],h=e[3],E=e[4],C=e[5],I=e[6],y=e[7],B=e[8],b=e[9],w=this.detectSkillChanges(I),v=e[10],S=e[11];b?.exceeded&&(this.quotaExceedMessage=JSON.stringify(b.userActions));const Q=a.subagents?.map((e=>ProjectAgent.pickTaskProperties(e,A)))??[],_=y.map((e=>({agentName:e.name,description:e.description,isProjectAgent:!0,agentPrompt:e.agentPrompt,toolNames:e.toolNames,disallowedToolNames:e.disallowedToolNames}))),D=this.buildStaticContexts(this.rootPaths,s,C);this.knowledgeContexts=findNearestContextInAllRoundtrips(this.conversationAccessor?.getAllRoundtrips(),isKnowlegeContext),t||E.push(...D);const x=c.filter(isKnowlegeContext);x.length&&E.push(buildKnowledgeSummary(x)),l&&E.push({type:"SLASH_COMMAND",...l});const k={commands:c.filter((e=>e.type===ContextType.SLASH_COMMAND)).map((e=>e.name||e.id)),skills:c.filter((e=>e.type===ContextType.SELECT_SKILL)).map((e=>e.name||e.id)),subagents:c.filter((e=>e.type===ContextType.SELECT_SUBAGENT)).map((e=>e.name||e.id)),rules:[]},R={isMultiWorkspace:this.rootPaths.length>1},T=S.en_verif_sub,$=T?.enabled&&T?.value,N={taskId:o.taskId,conversationId:o.conversationId,agentId:a.agentId,uploadBaseInfo:B,query:n,modelKey:i,sysInfo:s,skillInfos:w?I:void 0,isUserQuery:!0,isMockQuery:!!f.isMockQuery,localIndex:h,contexts:E,mode:getAgentMode(a.agentId),signal:f.signal,traceId:f.traceId,rollbackMessageId:u,toolUseResults:[],subAgents:[...Q,Explore,General,...$?[Verification]:[],...this.knowledgeContexts.length?[DocExplore]:[],..._],agentInfo:m,agentVersion:5,isFirstQuery:!t,systemReminder:v?`${v}\n${r}`:r,extendUserQueryInfo:k,extend:R};return isZuluCli&&(d&&(R.useCodebaseSearch=!0),p&&(N.appendSystemPrompt=p),g&&(N.channel=g)),this.params=N,kernel.logger.info(`[Zulu] ParameterCollector finished, taskId=${N.taskId}`),N}))}async resume(e){if(!this.params)return;const{query:t="",agent:r,knowledgeList:n,isMockQuery:i=!1,...o}=e;if(this.params.query=t,t&&(this.params.isUserQuery=!0),void 0!==r){const e=this.buildSystemReminder(r.agentId,r.agentName);this.params.agentId=r.agentId,this.params.agentInfo={agentId:r.agentId,agentName:r.agentName,isProjectAgent:!!r.isProjectAgent},this.params.systemReminder=e}void 0!==n&&(this.params.contexts=await contextsFromWebview2AgentContext(n,[],this.rootPath,this.virtualEditor,this.params.traceId)),this.params.isMockQuery=i,this.updateParams(o)}async getAllRules(e){if(!this.rootPath||!this.conversationAccessor)return[];const t=this.virtualEditor,r=await getAllRules(this.rootPath,t);if(!r?.length)return[];const n=this.conversationAccessor.getLatestRoundtrip(),{globRules:i,alwaysApplyRules:o,selectRules:s,quoteRules:a}=collectCurrentRoundRules(r,n,this.rootPath,!!e),c=this.getAppliedRulesWithContext(e),A=new Map;for(const e of r){const t=getRuleSubtypeV2(e.metadata);A.set(`${t}:${e.path}`,e)}const l=[],u=[],d=[];for(const e of c){const t=`${e.type}:${e.path}`,r=A.get(t);r&&(e.type===GLOB_MATCHED_RULE?l.push(r):e.type===ALWAYS_APPLIED_RULE?u.push(r):e.type===SELECTED_RULE&&d.push(r))}const h=_$H.uniqBy([...i,...l],(e=>`${GLOB_MATCHED_RULE}:${e.path}`)),p=_$H.uniqBy([...o,...u],(e=>`${ALWAYS_APPLIED_RULE}:${e.path}`)),g=_$H.uniqBy([...s,...d],(e=>`${SELECTED_RULE}:${e.path}`)),f=[...h.map((e=>({type:GLOB_MATCHED_RULE,...e}))),...p.map((e=>({type:ALWAYS_APPLIED_RULE,...e}))),...s.map((e=>({type:SELECTED_RULE,...e})))];this.updateAppliedRulesWithContext(f,{deleteRules:[],mode:"override",ruleAccessor:e});return buildRuleContexts({globRules:h,alwaysApplyRules:p,selectRules:g,quoteRules:_$H.uniq([...a,...d.map((e=>e.name))]),diffRules:[],isFirst:!0})}isRuleAlreadyInserted(e,t){return e.includes(`<rule name="${t}"`)}getAppliedRulesWithContext(e){return e?.getLatestAppliedRules()??this.conversationAccessor?.getLatestAppliedRules()??[]}updateAppliedRulesWithContext(e,t){const{deleteRules:r,mode:n,ruleAccessor:i}=t??{};i?i.updateLatestAppliedRules(e,r,n):this.conversationAccessor?.updateLatestAppliedRules(e,r,n)}processToolResultsWithRules(e,t,r){if(!this.rootPath||!this.conversationAccessor)return e;const n=new Set,i=[];for(const r of e){const e=r.params.target_file;if("read_file"===r.name&&r.success&&e){const o=path__default$1.isAbsolute(e)?path__default$1.relative(this.rootPath,e):e,{globRules:s}=getActiveRules(this.rootPath,t,[e,o]),a=r.message||"",c=s.filter((e=>!n.has(e.path)&&!this.isRuleAlreadyInserted(a,e.name)));if(c.length>0){c.forEach((e=>n.add(e.path))),i.push(...c);const e=c.map((e=>buildRuleContent(e))).join("\n\n");r.message=a+"\n\n"+e}}}if(i.length>0){const e=i.map((e=>({type:GLOB_MATCHED_RULE,...e})));this.updateAppliedRulesWithContext(e,{ruleAccessor:r})}return e}processContextWithRules(e,t,r){if(!this.conversationAccessor)return e;const{ruleContexts:n,allCurrentRules:i,deleteRules:o}=processWorkspaceRules({rules:t,latestRoundtrip:this.conversationAccessor.getLatestRoundtrip(),latestAppliedRules:this.getAppliedRulesWithContext(r),isFirst:!this.conversationAccessor.getPreviousRoundtrip(),rootPath:this.rootPath,skipUserKnowledge:!!r});return this.updateAppliedRulesWithContext(i,{deleteRules:o,ruleAccessor:r}),[...e,...n]}extractRulePathsFromContexts(e){const t=new Set,r=new Set(["ALWAYS_APPLIED_RULE","ALWAYS_ADD_RULE","GLOB_MATCHED_RULE","DIFF_RULE"]);for(const n of e)r.has(n.type)&&"path"in n?t.add(n.path):"QUOTE_RULE"===n.type&&n.content.split("\n").forEach((e=>{t.add(e.replace(/^- /,""))}));return Array.from(t)}async getDynamicParams(e=!1,t,r){if(!this.rootPath||!this.conversationAccessor)return t;if(e){const[e,n,i,o]=await Promise.all([safePromise(this.getAllRules(r),[]),safePromise(this.getSysInfo(this.rootPath),getDefaultSysInfo(this.rootPath)),safePromise(getGitStatusDescriptionForMultiple(this.rootPaths),GIT_STATUS_ERROR_MESSAGE),safePromise(getAllSkillMetadata(this.rootPath,this.mcpManager),[])]);this.cachedSkillFingerprint=null,this.detectSkillChanges(o);const s=this.buildStaticContexts(this.rootPaths,n,i);return{...t,skillInfos:o,contexts:[...t.contexts||[],...s,...e]}}const n=await getAllRules(this.rootPath,this.virtualEditor),i=t.toolUseResults.length?this.processToolResultsWithRules(t.toolUseResults,n,r):t.toolUseResults;if(t.isUserQuery){const e=this.processContextWithRules(t.contexts,n,r),o=t.extendUserQueryInfo?{...t.extendUserQueryInfo,rules:this.extractRulePathsFromContexts(e)}:void 0;return{...t,contexts:e,toolUseResults:i,...o&&{extendUserQueryInfo:o}}}const o=await safePromise(getAllSkillMetadata(this.rootPath,this.mcpManager),[]),s=this.buildSkillFingerprint(o),a=null!==this.cachedSkillFingerprint&&s!==this.cachedSkillFingerprint;return a&&(this.cachedSkillFingerprint=s),{...t,contexts:t.contexts,toolUseResults:i,skillInfos:a?o:void 0}}}const FILE_MODIFICATION_TOOLS=["write_file","edit_file","delete_file"];class SpecEditorV2{_roundtrips;getStatus;mediator;conversationId;tabInfo={doc:{status:SpecTabStatus.IDLE},tasks:{status:SpecTabStatus.IDLE},changes:{status:SpecTabStatus.IDLE},summary:{status:SpecTabStatus.IDLE}};cachedSessionId="";isSpecSession=!1;constructor(e,t,r,n){this._roundtrips=e,this.getStatus=t,this.mediator=r,this.conversationId=n}get isSpec(){const e=this.roundtrips[0];return!!e&&12===e.request.payload.agent?.agentId}get specSessionId(){return this.getOrGenerateSessionId()}get hasDocFile(){return!!this.tabInfo.doc.path}get hasTasksFile(){return!!this.tabInfo.tasks.path}get hasSummaryFile(){return!!this.tabInfo.summary.path}get hasContent(){return this.hasDocFile||this.hasTasksFile||this.hasSummaryFile||this.tabInfo.changes.status!==SpecTabStatus.IDLE}get roundtrips(){return this._roundtrips.filter((e=>!e.discard))}static deriveConversationStatus(e=[]){const t=e[e.length-1];return t&&"assistant"===t.role?SpecEditorSessionStatus.Error:SpecEditorSessionStatus.Loading}beforeStartWork(){this.isSpec&&(this.pausePendingOrGeneratingTabs(),this.syncSpecProgress(SpecIconState.GENERATING))}afterStartWork(){if(!this.isSpec)return;this.pauseGeneratingTabs();const e=this.getCurrentIconState();this.syncSpecProgress(e)}async openSpecEditor(e,t=!1){const r=this.specSessionId,n=this.getCurrentIconState(),i={...this.tabInfo};i.changes={status:i.changes.status,diffInfo:this.getChangesFiles()};const o=this.roundtrips[0],s=o?.request.summary||o?.request.payload.query;await(this.mediator.specCommunicationService?.sendStateChanged({type:"FULL_STATE_SYNC",payload:{specSessionId:r,sessionName:s??"",iconState:n,activeTabIndex:this.getActiveStepIndex(e),open:!0,tabInfo:{doc:this.tabInfo.doc,tasks:this.tabInfo.tasks,changes:i.changes,summary:this.tabInfo.summary,preview:this.tabInfo.preview||{}},currentFile:e,isReRender:t}}))}beforeRollback(){this.isSpecSession=this.isSpec}async afterRollback(){if(0===this.roundtrips.length&&this.mediator.specCommunicationService?.syncSessionDeleted(this.conversationId,this.isSpecSession),!this.isSpecSession)return;const e=this.hasContent;this.rebuild(),e&&await this.openSpecEditor("",!0);const t=this.getCurrentIconState();await this.syncSpecProgress(t),0===this.roundtrips.length&&(this.cachedSessionId="")}rebuild(){if(!this.isSpecSession&&!this.isSpec)return;const e=this.collectModifiedFiles().map((e=>e.absolutePath)).reverse(),t=e.find(isSummaryFile),r=e.find(isDocFile),n=e.find(isTasksFile),i=e.filter(isNotSpecMarkdownFile),o=this.getCurrentPendingDocOrTasksPath(),s=this.rebuildSummaryTabStatus(t),a=this.rebuildChangesTabStatus(s,i),c=this.rebuildTasksTabStatus(a,n,o),A=this.rebuildDocTabStatus(c,r,o);this.tabInfo={doc:{status:A,path:r},tasks:{status:c,path:n},changes:{status:a},summary:{status:s,path:t}}}async afterFileChange(e){if(!this.isSpec)return;if(!("string"==typeof e.result.metadata.content))return;const t=this.hasContent,r=e.absolutePath;isSpecMarkdownFile(r)&&(e instanceof EditFile||e instanceof WriteFile)?await this.handleSpecMarkdownChange(e):(this.tabInfo.tasks.path&&await this.updateTabStatus("tasks",SpecTabStatus.EXECUTING),this.tabInfo.changes.status=SpecTabStatus.GENERATING,await this.syncTabStatus("changes")),this.hasContent&&!t&&await this.openSpecEditor(r,!0)}async afterGenerateQuerySummary(e,t){if(!this.isSpec)return;if(!(t===this.roundtrips[0]))return;const r=this.specSessionId;await(this.mediator.specCommunicationService?.sendStateChanged({type:"SESSION_TITLE_UPDATED",payload:{specSessionId:r,title:e}}))}async syncConversationState(){await(this.mediator.specCommunicationService?.syncConversationInfo(this.conversationId))}getCurrentPendingDocOrTasksPath(){const e=this.roundtrips[this.roundtrips.length-1];if(!e)return;const t=e.getLastToolTurnTools().filter(isSpecDocOrTasksFilePendingReview).pop();return t?.result.metadata.absolutePath}async handleSpecMarkdownChange(e){const t=e.absolutePath,r=e.result.metadata.askReview;if(isDocFile(t)){const e=r?SpecTabStatus.PENDING:SpecTabStatus.QUEUED;this.tabInfo.doc.path=t,await this.updateTabStatus("doc",e)}else if(isTasksFile(t)){this.tabInfo.doc.path&&this.updateTabStatus("doc",SpecTabStatus.DONE);const e=this.tabInfo.tasks,n=r?SpecTabStatus.PENDING:e.status===SpecTabStatus.EXECUTING?SpecTabStatus.EXECUTING:SpecTabStatus.QUEUED;e.path=t,this.updateTabStatus("tasks",n)}else isSummaryFile(t)&&(this.tabInfo.summary.path=t,this.updateTabStatus("tasks",SpecTabStatus.DONE),this.updateTabStatus("changes",SpecTabStatus.DONE),this.updateTabStatus("summary",SpecTabStatus.DONE))}getOrGenerateSessionId(){if(this.cachedSessionId)return this.cachedSessionId;for(let e=this.roundtrips.length-1;e>=0;e--){const t=this.roundtrips[e]?.request.payload.specSessionId;if(t)return this.cachedSessionId=t,t}return this.cachedSessionId=randomUUID(),this.cachedSessionId}getCurrentIconState(){switch(this.getStatus()){case AgentConversationStatus.Running:return SpecIconState.GENERATING;case AgentConversationStatus.Cancelled:return SpecIconState.CANCELLED;case AgentConversationStatus.Completed:return Object.values(this.tabInfo).some((e=>e?.status===SpecTabStatus.PENDING))?SpecIconState.PENDING:SpecIconState.COMPLETED;default:return SpecIconState.ERROR}}collectModifiedFiles(){const e=new Map;for(const t of this.roundtrips)for(const r of t.getAllToolTurnTools()){if(!FILE_MODIFICATION_TOOLS.includes(r.name)||"executed"!==r.toolState)continue;const t=r.result.metadata,n=t.absolutePath;if(!n)continue;const i=t.originalContent||"",o=t.content||"",s=e.get(n);e.set(n,{absolutePath:n,source:s?s.source:i,content:o})}return Array.from(e.values())}getActiveStepIndex(e){if(!e){const e=this.tabInfo.tasks.status;return e===SpecTabStatus.PENDING||e===SpecTabStatus.EXECUTING?1:0}return e===this.tabInfo.preview?.path?4:e===this.tabInfo.doc.path?0:e===this.tabInfo.tasks.path?1:e===this.tabInfo.summary.path?3:2}getChangesFiles(){return this.collectModifiedFiles().filter((e=>isNotSpecMarkdownFile(e.absolutePath)))}async updateTabStatus(e,t){const r=this.tabInfo[e];r&&r.status!==t&&(r.status=t,await this.syncTabStatus(e))}async syncTabStatus(e){const t=this.specSessionId,r=this.tabInfo[e];if(!r)return;const n="changes"!==e&&"path"in r?r.path:void 0,i="changes"===e?this.getChangesFiles():void 0;await(this.mediator.specCommunicationService?.sendStateChanged({type:"TAB_STATUS_UPDATED",payload:{specSessionId:t,tabType:e,status:r.status,path:n,diffInfo:i}}));const o={doc:{loading:"spec/start",end:"spec/docEnd"},tasks:{loading:"spec/taskCreateStart",end:"spec/taskCreateEnd"},summary:{loading:"spec/taskExecuteEnd ",end:"spec/end"}}[e]?.[r.status];o&&sendIdeEventLog(o,{sessionId:t})}async pausePendingOrGeneratingTabs(){for(const e of["doc","tasks","changes","summary"]){const t=this.tabInfo[e];t&&(t.status!==SpecTabStatus.PENDING&&t.status!==SpecTabStatus.GENERATING||await this.updateTabStatus(e,SpecTabStatus.QUEUED))}}async pauseGeneratingTabs(){for(const e of["doc","tasks","changes","summary"]){const t=this.tabInfo[e];t&&t.status===SpecTabStatus.GENERATING&&await this.updateTabStatus(e,SpecTabStatus.QUEUED)}}rebuildSummaryTabStatus(e){return e?SpecTabStatus.DONE:SpecTabStatus.IDLE}rebuildChangesTabStatus(e,t){return e===SpecTabStatus.DONE?SpecTabStatus.DONE:t.length>0?SpecTabStatus.QUEUED:SpecTabStatus.IDLE}rebuildTasksTabStatus(e,t,r){return r&&t===r?SpecTabStatus.PENDING:e===SpecTabStatus.DONE?SpecTabStatus.DONE:e===SpecTabStatus.QUEUED?SpecTabStatus.EXECUTING:t?SpecTabStatus.QUEUED:SpecTabStatus.IDLE}rebuildDocTabStatus(e,t,r){return r&&t===r?SpecTabStatus.PENDING:e!==SpecTabStatus.IDLE?SpecTabStatus.DONE:t?SpecTabStatus.QUEUED:SpecTabStatus.IDLE}async syncSpecProgress(e){const t=this.collectHistoryTasks();await(this.mediator.specCommunicationService?.sendStateChanged({type:"SPEC_PROGRESS_UPDATED",payload:{specSessionId:this.specSessionId,iconStatus:e,historyTasks:t}}))}collectHistoryTasks(){const e=[];for(const t of this.roundtrips){const r=t.request.uuid;if(!r)continue;const n=t.request.payload.specExecutionTasks;n&&n.length>0&&e.push({userMessageId:r.toString(),tasks:n})}return e}}class AgentConversation extends ConversationThread{context;mcpManager;codeWrittenMetric;type=AgentConversationType.AgentConversation;inlineDiffView=!0;status=AgentConversationStatus.Ready;statistics=new AgentStatistics;token=new Token(this.id);parameterCollector;fileConsistencyChecker;executor=null;specEditor;commandResultQueue=[];constructor(e,t,r){super(e),this.context=e,this.mcpManager=t,this.codeWrittenMetric=r,this.status=AgentConversationStatus.Running,this.fileConsistencyChecker=new FileConsistencyChecker(this.virtualEditor,this.repo),this.parameterCollector=new ParameterCollector(this.mcpManager,this.virtualEditor),this.parameterCollector.setConversationAccessor(this.createConversationAccessor()),this.specEditor=new SpecEditorV2(this.roundtrips,(()=>this.status),this.mediator,this.id)}createConversationAccessor(){return{getLatestRoundtrip:()=>this.latestRoundtrip,getPreviousRoundtrip:()=>this.previousRoundtrip,getAllRoundtrips:()=>this.roundtrips,getLatestAppliedRules:()=>this.latestAppliedRules,updateLatestAppliedRules:(e,t,r)=>this.updateLatestAppliedRules(e,t,r)}}get metrics(){const e=this.latestRoundtrip.request.metrics,t=this.latestRoundtrip.request.payload?.model?.modelId||"Auto",r=this.latestRoundtrip.request.metrics?.path;return{...e,path:r,modelKey:t}}get agent(){return this.latestRoundtrip.request.payload.agent||DEFAULT_AGENT}firstTokenStartTime=0;sessionHookFired=!1;sessionEndFired=!1;sessionStartContextPromise;rollbackMessageId=void 0;icafeIssueId;updateSessionMeta=async e=>{Object.assign(this,e);const t=await this.chatSessionManager.find(this.id);t?.sessionUuid&&await this.chatSessionManager.save({...t,...e})};async startWork(e){this.startConversation(),this.firstTokenStartTime=performance.now();const t=e.request.payload;updateLastUsedKnowledgeContext(t.knowledgeList);const r=this.previousRoundtrip;let n,i,o=[],s=[];r&&(n=r.context.conversationId,i=r.context.taskId,o=getAdoptedFileStatusFromToolTurns(r.toolTurns),s=await this.getLastToolTurnResults(r.toolTurns),this.latestRoundtrip.appliedRules=r?.appliedRules??[]),this.fileConsistencyChecker.markCodeSelectionsAsRead(t.knowledgeList);const a=this.rollbackMessageId,c=await transformQuery(e.request.payload.query,t.knowledgeList);this.parameterCollector.start({knowledges:[...t.knowledgeList,...this.takeCommandResults()],rollbackMessageId:a,rejectedFiles:o,agent:this.agent,query:c,modelKey:e.request.payload.model?.modelId||"Auto",isMockQuery:e.request.payload.isMockQuery,rootPath:this.repo.rootPath,rootPaths:this.repo.rootPaths,conversationId:n,taskId:i,signal:this.token.signal,traceId:this.id,useCodebaseSearch:t.useCodebaseSearch,sessionStartContextPromise:this.sessionStartContextPromise,appendSystemPrompt:t.appendSystemPrompt,channel:t.channel,selfDefineInstruction:t.selfDefineInstruction?{name:t.command,isOfficial:!!t.command,content:t.selfDefineInstruction}:void 0}),this.updateAllMessages(),this.token.onNotify(this.handleTokenNotification.bind(this)),this.stream({toolUseResults:s});try{await this.token.waitForCompletion()}catch(e){const t=e instanceof Error?e.message:e?.toString()??"unknown error";"cancel"!==t&&(this.logger.error("AgentConversation error:",t),this.handleConversationError(t))}finally{await this.finalizeConversation(a),this.endConversation()}}async finalizeConversation(e){const t=this.latestRoundtrip.context.taskId;t&&await this.latestRoundtrip.calculateTokenUsage({taskId:t}),e&&await removeDiscardMsgAfterConsumed(this.id,this.chatSessionManager)}async getLastToolTurnResults(e){if(0===e.length)return[];const t=e[e.length-1],r=hasStreamBreakingTool(t.tools);return t.token.state===TokenNotifyState.CANCELLED||r?Promise.all(t.tools.map((async e=>{const t=isSpecDocOrTasksFilePendingReview(e)?await buildSpecFileToolSystemReminder(e,this.virtualEditor):void 0,r=e.result?.metadata?.hookSystemReminder,n=t||r||void 0;return{id:e.toolId,name:e.name,success:"executed"===e.toolState,params:e.toolHandler.params,message:e.result?e.result.output:ToolError.common.execution_aborted,result:getToolResultExtraContent(e),systemReminder:n}}))):[]}get latestRoundtrip(){return this.roundtrips[this.roundtrips.length-1]}handleTokenNotification(e){if("update"===e.name&&this.latestRoundtrip.updateWebviewMessages(),"command-result-ready"===e.name){const t=e.payload;return this.commandResultQueue.push(t),void this.autoResumeIfCompleted()}if("resume-stream"!==e.name){if(e.token.parent===this.token&&this.token.state!==TokenNotifyState.CANCELLED){const t=e.payload;if("completed"===e.name){const e=t?.map((e=>{const t=e.metadata.tool;return this.parameterCollector.collectTouchedAbsolutePathsAfterToolExecuted(t),{id:t.toolId,name:t.name,success:"executed"===t.toolState,params:t.toolHandler.params,truncatedMessage:getTruncatedMessage(t),result:getToolResultExtraContent(t),message:e.output,systemReminder:t.result?.metadata?.hookSystemReminder}})),r=t?.map((e=>e.metadata.tool));hasStreamBreakingTool(r)?this.token.break([]):this.stream({toolUseResults:e})}}}else this.resumeStream(e.payload)}async resumeStream(e){try{this.updateStatus(AgentConversationStatus.Running),this.startConversation();const t=await this.getLastToolTurnResults(this.latestRoundtrip.toolTurns);await this.parameterCollector.resume(e),this.stream({toolUseResults:t}),await this.token.waitForCompletion(),this.updateStatus(AgentConversationStatus.Completed),this.autoResumeIfCompleted()}catch(e){this.logger.error("AgentConversation error:",e),this.updateStatus(AgentConversationStatus.Failed)}finally{await this.finalizeConversation(this.rollbackMessageId),this.endConversation()}}async stream(e){const t=await this.parameterCollector.getParams();this.parameterCollector.quotaExceedMessage&&(this.latestRoundtrip.quotaExceedMessage=this.parameterCollector.quotaExceedMessage),this.latestRoundtrip.context.conversationId=t.conversationId,this.latestRoundtrip.context.taskId=t.taskId,this.beforeStream(t),t.isUserQuery&&(this.executor=null),this.executor||(this.executor=new AgentExecutor({parameterCollector:this.parameterCollector,rootPath:this.repo.rootPath,rootPaths:this.repo.rootPaths,virtualEditor:this.virtualEditor,traceId:t.traceId,conversationId:t.conversationId,taskId:t.taskId,fileConsistencyChecker:this.fileConsistencyChecker,mcpManager:this.mcpManager,signal:this.token.signal,userTurn:this.latestRoundtrip,specEditor:this.specEditor,updateSessionMeta:this.updateSessionMeta},this.latestRoundtrip.toolTurns,this.token)),markLastToolTurnCompletedIfCanceled(this.latestRoundtrip.toolTurns),this.latestRoundtrip.status=RoundtripStatus.Generating,await this.executor.executeStream({updatedParams:e,onUpdate:e=>{this.performanceLog("agent-first-token"),this.rollbackMessageId=void 0,this.latestRoundtrip.disabledRollback=!!e,this.latestRoundtrip.updateWebviewMessages()},onRollback:()=>this.handleRollbackOnError()})}handleRollbackOnError(){const e=this.latestRoundtrip.toolTurns,t=e[e.length-1],r=t?.rollbackMessageId;if(r)return this.rollbackMessageId=r,t.discard=!0,r}getToolsByPath(e){return this.latestRoundtrip.toolTurns.flatMap((t=>t.getToolsByAbosultePath(e)))}async acceptFile(e){const t=this.getToolsByPath(e),r=t[t.length-1];t.forEach((e=>e.accept())),await r.toolHandler.save();return{absolutePath:e,suggestions:await this.updateAcceptance(e,!0),originalContent:t[0].result.metadata.originalContent||"",modifiedContent:r.result.metadata.content||""}}async rejectFile(e){const t=this.getToolsByPath(e);t.forEach((e=>e.reject())),await t[0].toolHandler.revert();return{absolutePath:e,suggestions:await this.updateAcceptance(e,!1),originalContent:t[t.length-1].result.metadata.originalContent||"",modifiedContent:t[0].result.metadata.content||""}}async updateAcceptance(e,t){return this.latestRoundtrip.updateSuggestionsByPath(e,t?AcceptState.ACCEPT:AcceptState.REJECT)}async handleNewMessage(e){switch(e.action){case"execute-shell":case"insert-shell":await this.virtualEditor.executeTerminalShell({cmd:e.shell,cwd:this.repo.rootPath,duration:5e3,run:"execute-shell"===e.action});break;case"copy-code":case"open-rollback-file-diff":break;case"file-view":if(this.specEditor.isSpec&&isSpecMarkdownFile(e.absolutePath)){await this.specEditor.openSpecEditor(e.absolutePath);break}await this.virtualEditor.openDocument({absolutePath:e.absolutePath});break;case"file-diff":if(this.specEditor.isSpec&&isSpecMarkdownFile(e.absolutePath)){await this.specEditor.openSpecEditor(e.absolutePath);break}try{const t=this.getToolsByPath(e.absolutePath);if(0===t.length){await this.virtualEditor.openDocument({absolutePath:e.absolutePath});break}const r=t[0],n=r.result?.metadata?.originalContent||"",{content:i}=await this.virtualEditor.getDocument({absolutePath:e.absolutePath});if(isComateIDE)return void this.virtualEditor.openDocument({absolutePath:e.absolutePath});await this.virtualEditor.openVirtualDiffDocument({conversationId:this.id,absolutePath:e.absolutePath,content:n,modified:i,stream:!1,action:VirtualDocumentAction.EDIT,source:this.type})}catch(t){this.logger.error("Failed to open diff document, fallback to normal view:",t),await this.virtualEditor.openDocument({absolutePath:e.absolutePath})}break;case"file-accept":{const{suggestions:t}=await this.acceptFile(e.filePath);this.acceptLog(this.metrics,this.latestRoundtrip.reportedId,t);break}case"file-reject":{const{suggestions:t}=await this.rejectFile(e.filePath);this.acceptLog(this.metrics,this.latestRoundtrip.reportedId,t);break}case"compress-token-usage":{const e=this.latestRoundtrip.context.taskId;await this.latestRoundtrip.compressTokenUsage({taskId:e}),this.parameterCollector.resetSkillFingerprint();break}case"copy-all":{const t=this.roundtrips.find((t=>t.uuid===e.id));let r="";if(t){const e=t.reportedId?`\nReportID: ${t.reportedId}`:"",n=this.id?`\nConversationID: ${this.id}`:"";r=t.toText(e+n)}return r}case"user-feedback":{const t=this.roundtrips.find((t=>t.uuid===e.id)),r=t?.reportedId;if(!r)return void this.logger.warn("[Zulu] Roundtrip reportedId missing: message uuid=",e.id);modifyCode({uuid:r,...e.options});break}case"file-tool-result-view":{const{tool:t,absolutePath:r}=e;if(this.specEditor.isSpec&&isSpecMarkdownFile(r)){await this.specEditor.openSpecEditor(r);break}if(t){const e=this.latestRoundtrip.toolTurns.find((e=>e.match(t.toolTurnId))),n=e?.tools.find((e=>e.toolId===t.toolId));if(n&&n.result.metadata)return void await this.virtualEditor.openVirtualDiffDocument({absolutePath:r,content:n.result.metadata.originalContent||"",modified:n.result.metadata.content||"",source:AgentConversationType.E2EBotConversation,action:VirtualDocumentAction.PREVIEW})}await this.virtualEditor.openDocument({absolutePath:r});break}case"file-accept-all":case"file-reject-all":{const t=_$H.flatten(this.latestRoundtrip.toolTurns.map((e=>e.tools.filter((e=>e.isTouchFileHandler&&"executed"===e.toolState)).map((e=>e.toolHandler.result.metadata?.absolutePath)))));for(const r of _$H.uniq(t.filter(Boolean)))"file-accept-all"===e.action?await this.acceptFile(r):await this.rejectFile(r);await this.acceptLog(this.metrics,this.latestRoundtrip.reportedId,this.latestRoundtrip.multiSuggestions);break}case"inquire-rollback-message":{await this.stopGenerating();let t=e.retryMessageId;if(e.userMessageId){const r=this.roundtrips.find((t=>t.request.uuid===e.userMessageId));r&&(t=r.toolTurns[0]?.rollbackMessageId)}return(await this.getRollbackSummaryV2(t)).map((e=>_$H.omit(e,"changes")))}case"rollback-message":{this.specEditor.beforeRollback(),await this.rollbackAllFileChanges(e.selectedAbsolutePaths);const t=e.retryMessageId,r=e.userMessageId;this.rollbackMessageId=t,forEachRollbackToolTurn(this.roundtrips,r,t,(e=>{this.rollbackMessageId||this.latestRoundtrip?.disabledRollback||(this.rollbackMessageId=e.rollbackMessageId),e.discard=!0}));const n=this.roundtrips.findIndex((e=>e.request.uuid===r)),i=this.roundtrips[n];return 0===n?(this.roundtrips.length=0,await this.chatSessionManager.delete(this.id)):-1!==n&&this.roundtrips.slice(n).forEach((e=>e.discard=!0)),this.specEditor.afterRollback(),this.mediator.userBehaviorTracker?.trackPromptRollback(i,e.retryMessageId),{}}case"tool-call-action":this.token.broadcast(e.name,{toolId:e.toolId,payload:e?.payload}),this.trackToolCallAction(e.toolId,e.name);break;case"quota-exceed":{const t=new ToolTurn(randomUUID(),this.token.fork(ToolTurn.createTokenId(randomUUID())),{parameterCollector:this.parameterCollector,traceId:this.id,conversationId:this.latestRoundtrip.context.conversationId??0,taskId:this.latestRoundtrip.context.taskId??0,rootPath:this.repo.rootPath,rootPaths:this.repo.rootPaths,virtualEditor:this.virtualEditor,signal:(new AbortController).signal,fileConsistencyChecker:this.fileConsistencyChecker,mcpManager:this.mcpManager,userTurn:this.latestRoundtrip,specEditor:this.specEditor,updateSessionMeta:this.updateSessionMeta}),r=e.quotaAction||"Quota exceeded",n=new Exception(r,!0);t.elements.push(n),this.latestRoundtrip.toolTurns.push(t),await t.cancel(r);break}}}rebuildConversation(e){const t=e.messages[0]?.context;this.rollbackMessageId=e.rollbackMessageId,this.token.onNotify(this.handleTokenNotification.bind(this)),this.rebuildRoundtrips(e.messages,{parameterCollector:this.parameterCollector,rootPath:this.repo.rootPath,rootPaths:this.repo.rootPaths,virtualEditor:this.virtualEditor,traceId:this.id,conversationId:t?.conversationId,taskId:t?.taskId,fileConsistencyChecker:this.fileConsistencyChecker,mcpManager:this.mcpManager,signal:this.token.signal,userTurn:this.latestRoundtrip,specEditor:this.specEditor,updateSessionMeta:this.updateSessionMeta},this.token),this.status=this.deriveConversationStatus(),this.specEditor.rebuild(),this.fileConsistencyChecker.rebuild(e.fileCache)}async acceptLogOnEnd(){const{suggestions:e,changes:t}=await this.latestRoundtrip.updateAcceptSuggestionsV2(this.metrics);this.codeWrittenMetric.agentEdit(Object.values(t));const r=this.latestRoundtrip.request.payload.query.trim(),{agentContexts:n,agentTools:i,assistantContent:o}=this.statistics.export(this.latestRoundtrip);if(this.latestRoundtrip.toolTurns.length&&!(this.latestRoundtrip.toolTurns[0].elements[0]instanceof Exception)){const t=await this.generateMessageId(this.metrics,e,r,o,n,i);this.logger.info("[Zulu] Roundtrip completed: uuid=",t),this.latestRoundtrip.reportedId=t,this.latestRoundtrip.updateWebviewMessages(),this.acceptLog(this.metrics,this.latestRoundtrip.reportedId,e)}}async triggerStopHook(e){const t=this.latestRoundtrip?.context;return hookService.triggerHook(HookEvent.Stop,{...hookService.buildCommonInput(this.id,{sessionId:t?.conversationId,taskId:t?.taskId}),hook_event_name:HookEvent.Stop,status:e,loop_count:hookService.getLoopCount(this.id)})}async beforeStop(){return"block"!==(await this.triggerStopHook("cancelled")).decision&&(this.token.state===TokenNotifyState.IN_PROGRESS&&this.mediator.userBehaviorTracker?.trackTaskCancelled(this.latestRoundtrip),this.token.cancel(),!0)}async onRoundtripComplete(){const e=await this.triggerStopHook("completed");if(!1===e.continue){const t=e.stopReason||"Execution stopped by hook";return hookService.resetLoopCount(this.id),kernel.connect.sendWebviewMessage(PT_WEBVIEW_HOOK_BLOCKED,{hookEventName:"executionStopped",message:t}).catch((()=>{})),null}const t=e.reason;if("block"!==e.decision||!t)return hookService.resetLoopCount(this.id),null;const r=hookService.incrementLoopCount(this.id);return r>=hookService.loopLimit?(hookService.resetLoopCount(this.id),kernel.connect.sendWebviewMessage(PT_WEBVIEW_HOOK_BLOCKED,{hookEventName:"stopLimitReached",message:t,loopCount:r,loopLimit:hookService.loopLimit}).catch((()=>{})),null):{followup:t}}beforeStartWork(){this.token.reset(),this.specEditor.beforeStartWork()}afterStartWork(){this.specEditor.afterStartWork(),this.autoResumeIfCompleted()}async autoResumeIfCompleted(){if(this.status!==AgentConversationStatus.Completed)return;const e=this.latestRoundtrip?.toolTurns??[],t=e[e.length-1];if(!t||hasStreamBreakingTool(t.tools))return;const r=this.takeCommandResults();if(r.length>0){const e=r.map((e=>e.id)),n=t.getToolById(randomUUID());n.update("task_complete","FUNCTION_CALL_PARAMS_MERGE",{tasks:e}),n.execute(),this.resumeStream({knowledgeList:r})}}afterGenerateQuerySummary(e,t){this.specEditor.afterGenerateQuerySummary(e,t)}startConversation(){this.notifyPreviousToolsNewConversationStart(),this.virtualEditor.startConversationEditSession({conversationId:this.id,source:this.type}),this.sessionHookFired||(this.sessionHookFired=!0,this.sessionEndFired=!1,this.sessionStartContextPromise=hookService.triggerHook(HookEvent.SessionStart,{...hookService.buildCommonInput(this.id),hook_event_name:HookEvent.SessionStart}).then((e=>{const t=e.additionalContext;if(t)return`<system-reminder>\n${HookEvent.SessionStart} hook additional context: ${t}\n</system-reminder>`})).catch((()=>{})))}endConversation(){this.notifyCurrentToolsConversationEnd(),this.virtualEditor.endConversationEditSession({conversationId:this.id}),this.acceptLogOnEnd(),this.logger.logUploader?.logUserAction({category:"new-agent",action:"endConversation"})}triggerSessionEnd(e){if(!this.sessionHookFired||this.sessionEndFired)return;this.sessionEndFired=!0;const t=this.latestRoundtrip?.context;hookService.triggerHook(HookEvent.SessionEnd,{...hookService.buildCommonInput(this.id,{sessionId:t?.conversationId,taskId:t?.taskId}),hook_event_name:HookEvent.SessionEnd,reason:e}).catch((()=>{}))}setForeground(e){if(!e&&this.foreground){const e=this.status===AgentConversationStatus.Running?"completed":this.status;this.triggerSessionEnd(e)}super.setForeground(e)}get latestAppliedRules(){return this.latestRoundtrip?.appliedRules||[]}getSessionState(){const e=this.latestRoundtrip?.toolTurns??[],t=e[e.length-1];if(t){if(this.status===AgentConversationStatus.Running&&hasPendingConfirmationTool(t.tools))return SessionState.Confirming;if(this.status===AgentConversationStatus.Completed&&hasStreamBreakingTool(t.tools))return SessionState.Pending}return this.specEditor.isSpec&&this.specEditor.hasSummaryFile&&this.status===AgentConversationStatus.Completed?SessionState.Summarized:super.getSessionState()}updateLatestAppliedRules(e,t=[],r="merge"){if(this.latestRoundtrip)if("merge"===r){const r=mergeAndDeduplicateRules(e,this.latestRoundtrip.appliedRules??[],t);this.latestRoundtrip.appliedRules=r}else this.latestRoundtrip.appliedRules=e.map((e=>({type:e.type,path:e.path,content:e.content,metadata:e.metadata,md5:computeMd5(e.content)})))}beforeStream(e){e.isUserQuery?this.mediator.userBehaviorTracker?.trackNewTaskStarted(this.latestRoundtrip):this.latestRoundtrip.calculateTokenUsage({taskId:e.taskId})}performanceLog(e){if(this.firstTokenStartTime){const t=performance.now()-this.firstTokenStartTime;this.logger.logUploader?.performanceLog({plugin:this.metrics.modelKey,skill:this.metrics.function,duration:t,type:e}),this.logger.info(`[Performance] ${e} take ${t} ms`),this.firstTokenStartTime=0}}trackToolCallAction(e,t){for(const r of this.roundtrips)for(const n of r.toolTurns){const i=n.tools.find((t=>t.toolId===e));if(i)return void this.mediator.userBehaviorTracker?.trackToolCallAction(i,r,t)}}notifyPreviousToolsNewConversationStart(){const e=this.previousRoundtrip?.toolTurns??[];for(const t of e)t.token.notifyConversationStart()}notifyCurrentToolsConversationEnd(){const e=this.latestRoundtrip?.toolTurns??[];for(const t of e)t.token.notifyConversationEnd()}takeCommandResults(){const e=this.commandResultQueue;return this.commandResultQueue=[],e}parseAndUseStructuredString(e){try{const t=JSON.parse(e);return"userActions"in t?(this.latestRoundtrip.quotaExceedMessage=JSON.stringify(t.userActions),{label:""}):{label:e}}catch{return{label:e}}}handleConversationError(e){if(!e||"cancel"===e)return;const{label:t}=this.parseAndUseStructuredString(e);t&&this.logger.logUploader?.logUserAction({category:"new-agent",action:"abortConversation",label:t,content:this.id})}}const DEFAULT_COMMAND_FILES$1=new Set(["code-review-comate","debug-comate","unit-test-comate"]);function getCommandNameFromRelativePath$1(e){const t=basename$3(e,".md").trim();return DEFAULT_COMMAND_FILES$1.has(t)?t.slice(0,-7):t}function serializeCommand$1(e){const t={};e.displayName&&(t.displayName=e.displayName),e.description&&(t.description=e.description);const r=e.prompt||`\nWrite your command content here.\n\nThis command will be available in chat with /${e.commandName}\n`;return matter$1.stringify(r,t)}class PersonalCommand{static personalDir=join$7(homedir$1(),".comate");static commandGlob="commands/**.md";static async readAll(){const e=PersonalCommand.personalDir,t=await globby(PersonalCommand.commandGlob,{cwd:e}).catch((()=>[]));kernel.logger.info(`Found personal commands: ${t.join(",")}`);const r=await Promise.all(t.map((async t=>{const r=join$7(e,t);try{const e=await readFile$4(r,"utf-8"),{data:n,content:i}=matter$1(e),o=n,s=basename$3(t,".md").trim();if(DEFAULT_COMMAND_FILES$1.has(s))return null;const a=getCommandNameFromRelativePath$1(t);if(!a)return null;return{commandId:-1*statSync$2(r).birthtimeMs,commandName:a,displayName:o.displayName??a,description:o.description??"",prompt:i.trim(),visibility:"SELF",isProjectCommand:!1,relativePath:t,absolutePath:r}}catch(e){return kernel.logger.info(`Failed to read personal command ${t}: ${e}`),null}})));return r.filter((e=>null!==e))}static async write(e){const t=join$7(PersonalCommand.personalDir,"commands");await lib$f.ensureDir(t);const r=e.relativePath??join$7("commands",`${e.commandName}.md`),n=join$7(PersonalCommand.personalDir,r);await writeFile$2(n,serializeCommand$1(e));const i=getCommandNameFromRelativePath$1(r);return{commandId:-1*statSync$2(n).birthtimeMs,commandName:i,displayName:e.displayName||i,description:e.description,prompt:e.prompt,visibility:"SELF",isProjectCommand:!1,relativePath:r,absolutePath:n}}static async delete(e){try{await rm$1(join$7(PersonalCommand.personalDir,e))}catch{}}}const DEFAULT_COMMAND_FILES=new Set(["code-review-comate","debug-comate","unit-test-comate"]);function getCommandNameFromRelativePath(e){const t=basename$3(e,".md").trim();return DEFAULT_COMMAND_FILES.has(t)?t.slice(0,-7):t}function serializeCommand(e){const t={};e.displayName&&(t.displayName=e.displayName),e.description&&(t.description=e.description);const r=e.prompt||`\nWrite your command content here.\n\nThis command will be available in chat with /${e.commandName}\n`;return matter$1.stringify(r,t)}class ProjectCommand{static commandGlob=".comate/commands/**.md";static async readFromWorkspace(e){const t=await globby(ProjectCommand.commandGlob,{cwd:e}).catch((()=>[]));kernel.logger.info(`Found project commands: ${t.join(",")}`);const r=await Promise.all(t.map((async t=>{const r=join$7(e,t);try{const e=await readFile$4(r,"utf-8"),{data:n,content:i}=matter$1(e),o=n,s=getCommandNameFromRelativePath(t);if(!s)return null;return{commandId:-1*statSync$2(r).birthtimeMs,commandName:s,displayName:o.displayName??s,description:o.description??"",prompt:i.trim(),visibility:"WORKSPACE",isProjectCommand:!0,relativePath:t,absolutePath:r}}catch(e){return kernel.logger.info(`Failed to read project command ${t}: ${e}`),null}})));return r.filter((e=>null!==e))}static async write(e,t){const r=join$7(e,".comate","commands");await lib$f.ensureDir(r);const n=t.relativePath??join$7(".comate","commands",`${t.commandName}.md`),i=join$7(e,n);await writeFile$2(i,serializeCommand(t));const o=getCommandNameFromRelativePath(n);return{commandId:-1*statSync$2(i).birthtimeMs,commandName:o,displayName:t.displayName||o,description:t.description,prompt:t.prompt,visibility:"WORKSPACE",isProjectCommand:!0,relativePath:n,absolutePath:i}}static async delete(e,t){try{await rm$1(join$7(e,t))}catch{}}}class MultiDirAgent extends Agent{agentGlob="agents/**.md";isProjectAgent=!1;reportAgentName="PERSONAL_AGENT";visibility="SELF";static searchDirs=[join$7(homedir$1(),".comate-engine"),join$7(homedir$1(),".comate"),join$7(homedir$1(),".cursor"),join$7(homedir$1(),".claude")];static mainDir=join$7(homedir$1(),".comate");constructor(e,t,r,n){super(n||MultiDirAgent.mainDir,e,t,r)}static async find(e){return(await this.readAll()).find((t=>t.toJSON().agentName===e))}static async write(e){const t=join$7("agents",e.agentName+".md"),r=new MultiDirAgent(t,{name:e.agentName,enable:"boolean"!=typeof e.enable||e.enable,description:e.description,icon:e.agentImage,tools:Array.isArray(e.tools)?e.tools:[],mcpServers:Array.isArray(e.mcpInfos)?e.mcpInfos:[],parentAgents:Array.isArray(e.parentAgents)?e.parentAgents:[]},e.agentPrompt);return await r.save(),r.toJSON()}static async delete(e){const t=e.endsWith(".md")?e.replace(/\.md$/,"").replace(/^agents\//,""):e;for(const e of MultiDirAgent.searchDirs){const r=join$7("agents",`${t}.md`),n=join$7(e,r);try{return await access$1(n),void await Agent.deleteAgent(e,r)}catch{continue}}}static async update(e,t){const r=await this.find(e.name);if(r)return r.update(e,t),await r.save(),r;{const r=join$7("agents",`${e.name}.md`),n=new MultiDirAgent(r,e,t);return await n.save(),n}}static async readAll(){const e=[];for(const t of MultiDirAgent.searchDirs){const r=await Agent.readAgentsFromPath(t,"agents/**.md",((e,t,r,n)=>new MultiDirAgent(t,r,n,e)));e.push(...r)}const t=new Set;return e.filter((e=>{const r=e.toJSON().agentName;return!t.has(r)&&(t.add(r),!0)})).sort(((e,t)=>t.getAgentId()-e.getAgentId()))}}async function apiGetPromptTemplateList(){try{const e=await axiosInstance("/api/openapi/prompt/list",{method:"POST",headers:{"Content-Type":"application/json","X-Username":kernel.env.isInternal?kernel.config.username&&encodeURIComponent(kernel.config.username):kernel.config.license},data:JSON.stringify({page:0,pageSize:500,sortByTime:0,needUnused:0,key:kernel.config.license})});if("OK"!==e.data?.status)throw new Error(e.data.message);return e.data?.data?.content.map((e=>({uuid:e.promptId,name:e.promptName,description:e.promptDesc,prompt:e.prompt})))??[]}catch(e){throw e}}class StayAwakeManager{logger;caffeinateProcess=null;preventing=!1;constructor(e){this.logger=e}update(e){e?this.prevent():this.allow()}prevent(){if("darwin"===process$2.platform&&!this.preventing)try{const e=spawn$5("caffeinate",["-di","-w",String(process$2.pid)],{stdio:"ignore",detached:!1});e.unref(),e.on("error",(e=>{this.logger.warn("caffeinate spawn error",e.message),this.caffeinateProcess=null,this.preventing=!1})),e.on("exit",(()=>{this.caffeinateProcess=null,this.preventing=!1})),this.caffeinateProcess=e,this.preventing=!0,this.logger.info("caffeinate started, preventing system sleep")}catch(e){this.logger.warn("failed to start caffeinate",e?.message)}}allow(){if(this.preventing&&this.caffeinateProcess){try{this.caffeinateProcess.kill()}catch{}this.caffeinateProcess=null,this.preventing=!1,this.logger.info("caffeinate stopped, allowing system sleep")}}dispose(){this.allow()}}const{debounce:debounce}=_$H;class ConversationManager{repo;mediator;virtualEditor;chatSessionManager;logger;mcpManager;previewProxyServerManager;agentCodeWrittenMetric;conversations=new Map;foregroundConversationId="";stayAwakeManager;constructor(e,t,r,n,i,o,s,a){this.repo=e,this.mediator=t,this.virtualEditor=r,this.chatSessionManager=n,this.logger=i,this.mcpManager=o,this.previewProxyServerManager=s,this.agentCodeWrittenMetric=a,this.stayAwakeManager=new StayAwakeManager(this.logger),kernel.connect.onWebviewMessage(PT_WEBVIEW_REQUEST_CHAT_SNAPSHOT,this.requestChatSnapshot.bind(this)),kernel.connect.onWebviewMessage(PT_WEBVIEW_REQUEST_KNOWLEDGE_LIST,getWorkspaceFoldersOrKnowledges.bind(this)),kernel.connect.onWebviewMessage(PT_WEBVIEW_REQUEST_PROJECT_AGENT_LIST,(async()=>{const[e,t]=await Promise.all([ProjectAgent.readFromWorkspace(this.repo.rootPath),MultiDirAgent.readAll()]);return[...e,...t].map((e=>e.toJSON()))})),kernel.connect.onWebviewMessage(PT_WEBVIEW_SAVE_PROJECT_AGENT,(async e=>{if(e.global){return await MultiDirAgent.write(e)}const t=await ProjectAgent.write(this.repo.rootPath,e);return await this.virtualEditor.refreshProjectTree(),t})),kernel.connect.onWebviewMessage(PT_WEBVIEW_DELETE_PROJECT_AGENT,(async e=>{if(e.absolutePath)try{await rm$1(e.absolutePath)}catch{}else e.global?await MultiDirAgent.delete(e.relativePath):(await ProjectAgent.delete(this.repo.rootPath,e.relativePath),this.virtualEditor.refreshProjectTree())})),kernel.connect.onWebviewMessage(PT_WEBVIEW_REQUEST_COMMAND_LIST,(async()=>{const[e,t]=await Promise.all([ProjectCommand.readFromWorkspace(this.repo.rootPath),PersonalCommand.readAll()]);return[...e,...t]})),kernel.connect.onWebviewMessage(PT_WEBVIEW_SAVE_COMMAND,(async e=>{if(e.global)return PersonalCommand.write(e);const t=await ProjectCommand.write(this.repo.rootPath,e);return await this.virtualEditor.refreshProjectTree(),t})),kernel.connect.onWebviewMessage(PT_WEBVIEW_DELETE_COMMAND,(async e=>{if(e.absolutePath)try{await rm$1(e.absolutePath)}catch{}else e.global&&e.relativePath?await PersonalCommand.delete(e.relativePath):e.relativePath&&(await ProjectCommand.delete(this.repo.rootPath,e.relativePath),this.virtualEditor.refreshProjectTree())})),kernel.connect.onWebviewMessage(PT_WEBVIEW_REPORT_RUNNING_CONVERSATIONS,this.reportRunningConversations.bind(this)),kernel.connect.onWebviewMessage(PT_WEBVIEW_CHECK_CONVERSATIONS_RUNNING,this.checkConversationsRunning.bind(this)),kernel.connect.onWebviewMessage(PT_WEBVIEW_STOP_CONVERSATIONS,this.stopConversations.bind(this)),kernel.connect.onWebviewMessage(PT_WEBVIEW_SKILL_METADATA_FETCH,(async()=>{const[e,t,r,n]=await Promise.all([getAllSkill(this.repo.rootPath),getAllCommandNames(this.repo.rootPath),getAllAgents(this.repo.rootPath),isInternal()?Promise.resolve([]):apiGetPromptTemplateList().catch((()=>[]))]);setServerCommandCache(n);const i=new Set(t.map((e=>e.name))),o=n.filter((e=>!i.has(e.name))).map((e=>({name:e.name,directory:"",sourceType:CommandSource.Enterprise,sourceName:"Comate",description:e.description}))),s="true"===process.env.DISABLE_BUILT_IN_SKILLS?e.filter((e=>e.sourceType!==SkillSource.System)):e;return{skills:s,commands:[...t,...o],agents:r}})),kernel.connect.onWebviewMessage(PT_WEBVIEW_CONVERSATION_TITLE_UPDATE_REQUEST,this.updateConversationTitle.bind(this))}async updateConversationTitle(e){const{conversationId:t,title:r}=e;try{const e=await this.chatSessionManager.find(t);if(!e)return;if(e.title=r,e.messages&&e.messages.length>0){const t=e.messages.find((e=>"user"===e.role));t&&(t.summary=r)}await this.chatSessionManager.save(e);const n=this.conversations.get(t);if(n&&"roundtrips"in n){const e=n;if(e.roundtrips&&e.roundtrips.length>0){const t=e.roundtrips[0];t&&t.request&&t.request.setSummary(r)}}}catch(e){this.logger.error(`Failed to update conversation title: ${e}`)}}async reportRunningConversations(){const e=Array.from(this.conversations.values()).filter((e=>e.status===AgentConversationStatus.Running)).length;this.logger.logUploader?.logUserAction({category:"multiTask",action:"reportRunningConversations",label:String(e+1)})}async checkConversationsRunning(e){const t=e.conversationIds.filter((e=>{const t=this.conversations.get(e);return t?.status===AgentConversationStatus.Running}));return{hasRunning:t.length>0,runningIds:t}}async stopConversations(e){await Promise.allSettled(e.conversationIds.map((e=>{const t=this.conversations.get(e);return t?.status===AgentConversationStatus.Running?t.onConversationMessage({messageType:"stop-generating",conversationId:e,payload:{}}):Promise.resolve()})))}createConversation(e){const t={repo:this.repo,virtualEditor:this.virtualEditor,onStatusChange:this.onStatusChange.bind(this),onMessageChange:this.onMessageChange.bind(this),logger:this.logger,userDetail:this.mediator.userDetail(),mediator:this.mediator,chatSessionManager:this.chatSessionManager};switch(e.conversationType){case AgentConversationType.SecuBotConversation:return new SecuBotConversation(t,this.mediator);case AgentConversationType.E2EBotConversation:return new E2EBotConversation(t,this.mcpManager,this.previewProxyServerManager,this.agentCodeWrittenMetric);case AgentConversationType.DebugBotConversation:return new DebugBotConversation(t,this.mcpManager,this.sendCustomEventToIde.bind(this),this.previewProxyServerManager,this.agentCodeWrittenMetric);case AgentConversationType.AgentConversation:return new AgentConversation(t,this.mcpManager,this.agentCodeWrittenMetric);default:throw new Error(`Unknown conversation type: ${e.conversationType}`)}}addConversation(e){try{const t=this.createConversation(e);return e.conversationId&&t.setConversationId(e.conversationId),this.conversations.set(t.id,t),this.setForegroundConversation(t.id),t}catch(e){this.logger.error("addConversation",e)}}onStatusChange(e){this.mediator.specCommunicationService?.syncConversationInfo(e);const t=this.conversations.get(e).getConversationInfo();this.updateConversationMessages("conversation-status",t);const r=Array.from(this.conversations.values()).some((e=>e.status===AgentConversationStatus.Running));this.stayAwakeManager.update(r)}debouncedMap=new Map;onMessageChange(e,t,r){const n=this.conversations.get(e),i=n.getConversationInfo();e===this.foregroundConversationId&&(r?this.updateConversationMessageWithOptions(i,r):this.updateConversationMessages("conversation-messages",i,t));const o=t.find((e=>"user"===e.role));if(o){const r=o.summary||o.content?.trim()||o.payload?.command;if(!r)return;const s=n.status===AgentConversationStatus.Running,a=this.debouncedMap.get(i.id)||debounce((e=>this.chatSessionManager.save(e)),2e3,{leading:s});s&&this.debouncedMap.set(e,a);const c=n.fileConsistencyChecker.getAllCachedFiles();a({source:n.type===AgentConversationType.AgentConversation&&n.specEditor.isSpec?"SpecConversation":i.type,sessionUuid:i.id,specSessionId:o.payload?.specSessionId,messages:t,title:r,ctime:i.ctime,utime:i.utime,workspaceDirectory:this.repo.rootPath,summary:o.summary,fileCache:c,sessionState:n.getSessionState()}),s||this.debouncedMap.delete(e)}}mapSourceToConversationType(e){return"SpecConversation"===e?AgentConversationType.AgentConversation:"Spec"===e?AgentConversationType.E2EBotConversation:e}async rebuildConversationFromHistory(e){if(!e)return;this.logger.info("rebuildConversationFromHistory called",{conversationId:e});const t=await this.chatSessionManager.find(e);if(t)try{const e=this.createConversation({conversationType:this.mapSourceToConversationType(t.source),conversationId:t.sessionUuid,payload:{},messageType:"rebuild-conversation"});return e.setConversationId(t.sessionUuid),e.setCtime(t.ctime),e.setUtime(t.utime),e.rebuildConversation(t),e}catch(e){this.logger.error("rebuildConversationFromHistory",e.message)}}async rebuildFromTemp(e){const t=JSON.parse(readFileSync$1(e,"utf-8")),r=basename$4(e).replace("chat_session_",""),n=this.createConversation({conversationType:AgentConversationType.E2EBotConversation,conversationId:r,payload:{},messageType:"rebuild-conversation"});return n.setConversationId(t.sessionUuid),n.setCtime(t.ctime),n.setUtime(t.utime),n.rebuildConversation(t),n}setForegroundConversation(e){if(null===e)return Array.from(this.conversations.values()).forEach((e=>e.setForeground(!1))),this.foregroundConversationId="",void this.logger.info("clearForegroundConversation");const t=this.conversations.get(e);if(!t)return;Array.from(this.conversations.values()).forEach((t=>{t.id!==e&&t.setForeground(!1)})),this.foregroundConversationId!==e&&t.setForeground(!0),this.foregroundConversationId=e,this.logger.info("setForegroundConversation",e);const{processedMessages:r,webviewMessages:n}=t.toMessages();this.onMessageChange(e,r,{scope:"conversation",messages:n})}getConversation(e){return this.conversations.get(e)}getForegroundConversationId(){return this.foregroundConversationId}getConversationBySpecSessionId(e){const t=Array.from(this.conversations.values()).filter((t=>t.type===AgentConversationType.AgentConversation&&t.specEditor.specSessionId===e)).reverse();return t.find((e=>e.foreground))??t[0]}listAllConversations(){const e=Array.from(this.conversations).filter((([,e])=>e.toMessages().webviewMessages.length)).map((([,e])=>{const t=e.toMessages().webviewMessages.slice().reverse().find((e=>"user"===e.role));return{...e.getConversationInfo(),lastQuery:t?.content}}));return e.reverse()}async onNewMessage(e){const{conversationId:t}=e;let r=this.conversations.get(t);const n=e.payload?.query||"";if(/^chat_session(.*)[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(basename$4(n)))r=this.conversations.get(t),r||(r=await this.rebuildFromTemp(e.payload.query),this.conversations.set(r.id,r)),this.setForegroundConversation(r.id);else if(r){r=this.conversations.get(t);const n=await(r?.onConversationMessage(e));if("message-operation"===e.messageType)return n}else r=await this.rebuildConversationFromHistory(t),r?(this.conversations.set(r.id,r),this.setForegroundConversation(r.id),r.type===AgentConversationType.AgentConversation&&this.mediator.userBehaviorTracker?.trackSwitchSession(r.latestRoundtrip)):r=this.addConversation(e);if(r)return{id:r.id,status:r.status,type:r.type}}async sendCustomEventToIde(e,t){return this.mediator.sendToIde(e,t)}async updateConversationMessages(e,t,r){if(t.id!==this.foregroundConversationId)return;const n={data:{type:e,conversationInfo:t}};r&&(n.data.messages=r),this.sendMessageImmediately(n)}async updateConversationMessageWithOptions(e,t){if("conversation"===t.scope)this.updateConversationMessages("conversation-messages",e,t.messages);else if("message"===t.scope){const r={data:{type:"partial-message-data",conversationInfo:e,messages:[t.message]}};this.sendMessageImmediately(r)}else{const r={data:{type:"partial-message-elements",conversationInfo:e,messageData:t.messageData}};this.sendMessageImmediately(r)}}sendMessageImmediately(e){return isZuluCLI()?this.mediator.sendToIde("COMATE_AGENT_UPDATE_MESSAGE",e,{skipWriteLog:e.data.conversationInfo.status===AgentConversationStatus.Running}):kernel.connect.sendWebviewMessage(PT_COMATE_AGENT_UPDATE_MESSAGE,e.data)}async requestChatSnapshot(e){const t=(await this.chatSessionManager.find(e.conversationId)).messages.map((t=>"assistant"!==t.role||e.codeVisible?"user"===t.role?_$H.set(t,"payload.knowledgeList",t.payload.knowledgeList?.map((e=>"RULE"===e.type?{...e,content:safeReadFileSync(join$6(this.repo.rootPath,e.id))}:e))):t:{...t,elements:t.elements.map((e=>{if("TOOL_CALL"!==e.type)return e;const t=["workflowSnapshot.searchFiles","workflowSnapshot.result.result.content","workflowSnapshot.result.result.afterChangeFileContent","workflowSnapshot.result.result.beforeChangeFileContent","composer"];return e.toolName===WorkflowType.SearchFiles&&t.push("workflowSnapshot.result.result"),_$H.omit(e,t)}))}));return JSON.stringify(t)}}const __filename$2=fileURLToPath(import.meta.url),__dirname$2=path__default.dirname(__filename$2);async function resolveSourcePath(){const e=isDevMod?path__default.join(__dirname$2,"../../assets"):path__default.join(__dirname$2,"assets");try{if(await fs$H.pathExists(e))return e}catch(e){kernel.logger.error("[Assets] Error checking source path",e)}return null}async function syncCategory(e,t,r,n){const i=path__default.join(t,e),o=path__default.join(r,e);if(!await fs$H.pathExists(i))return void kernel.logger.info(`[Assets] Source directory not found: ${i}`);try{await ensureDirectoryExist(o)}catch(e){return void kernel.logger.error(`[Assets] Failed to create target directory: ${o}`,e)}const s=await fs$H.readdir(i);for(const t of s){const r=path__default.join(i,t),s=path__default.join(o,t);try{await n(r,s)}catch(r){kernel.logger.error(`[Assets] Failed to install ${e} '${t}'`,r)}}}async function installAssets(){if("true"===process.env.DISABLE_BUILT_IN_SKILLS)return void kernel.logger.info("[Assets] DISABLE_BUILT_IN_SKILLS is set, skip installing built-in assets.");const e=await resolveSourcePath();if(!e)return void kernel.logger.info("[Assets] Source directory not found.");const t=path__default.join(os__default$1.homedir(),DEFAULT_WORKSPACE_CONFIG_FOLDER);try{await ensureDirectoryExist(t)}catch(e){return void kernel.logger.error(`[Assets] Failed to create target path: ${t}`,e)}try{await Promise.all([syncCategory("skills",e,t,(async(e,t)=>{(await fs$H.stat(e)).isDirectory()&&(kernel.logger.info(`[Assets] Copying skill from ${e} to ${t}`),await fs$H.remove(t),await fs$H.copy(e,t))})),syncCategory("commands",e,t,(async(e,t)=>{if(!(await fs$H.stat(e)).isFile())return;kernel.logger.info(`[Assets] Copying command from ${e} to ${t}`);const r=await fs$H.stat(t).catch((()=>null));r?.isDirectory()&&await fs$H.remove(t),await fs$H.copy(e,t,{overwrite:!0})}))])}catch(e){return void kernel.logger.error("[Assets] Promise.all execution failed",e)}kernel.logger.info(`[Assets] Installed assets to ${t}`)}class CommonCache{logger;cache=new Map;constructor(e){this.logger=e}async setCache(e,t){try{this.cache.set(e,t)}catch(e){this.logger.error("set cache error: ",e.message)}}async getCache(e){try{return this.cache.get(e)}catch(e){return void this.logger.error("get cache error: ",e.message)}}}var PLATFORM,SYSTEM;async function getGitRepositoryUrl(e){try{const{stdout:t}=await execa("git",["config","--get","remote.origin.url"],{cwd:e});return t.trim()}catch{return null}}async function getGitBranch(e){try{const{stdout:t}=await execa("git",["branch","--show-current"],{cwd:e});return t.trim()}catch{return""}}async function getGitRepositoryInfo(e){const[t,r]=await Promise.all([getGitRepositoryUrl(e),getGitBranch(e)]);return{repositoryUrl:t,branch:r}}!function(e){e.INTERNAL="baidu-int",e.SAAS="baidu-saas"}(PLATFORM||(PLATFORM={})),function(e){e.WINDOWS="win32",e.LINUX="linux",e.FREEBSD="freebsd",e.OPENBSD="openbsd",e.SUNOS="sunos",e.MAC="darwin"}(SYSTEM||(SYSTEM={})),process.env.COMATE_ENGINE_PLATFORM,PLATFORM.INTERNAL,SYSTEM.WINDOWS,patchEnvPath();class StringChunkStream{chunks=[];append(e){this.chunks.push(e)}flush(e){return e&&this.append(e),{command:"draw",content:this.chunks}}replaceLast(e){this.chunks.length?this.chunks[this.chunks.length-1]=e:this.append(e)}flushReplaceLast(e){return this.replaceLast(e),this.flush()}fail(e){return this.chunks.length=0,{command:"fail",content:e}}}-1===Math.random()&&console.log("THIS IS COMATE");const PREAMBLE_SEPERATOR="win32"===process.platform?"\r\n---Prompt---\r\n":"\n---Prompt---\n",ANNOTATION_SEPERATOR="win32"===process.platform?"\r\n############\r\n":"\n############\n";function formatPrompt(e,t){return t?e.replace(/\{\{\s*((\w+)|(\[FILE\]\s*[\\\/\-\.\w]+))\s*\}\}/g,((e,r)=>{const n=t[r];return void 0!==n?String(n):e})):e}function getPreambleAndBody(e){let[t,r]=e.split(PREAMBLE_SEPERATOR);return void 0===r&&(r=t,t=""),[t,r.split(ANNOTATION_SEPERATOR)?.[0]??""]}function formatNumber(e,t){if(void 0===e)return;let r=0;if("number"==typeof e&&(r=e),"string"==typeof e){const t=e.trim();if(!/^\d+$/.test(t))return;r=parseInt(t,10)}return t?.isInteger&&!Number.isInteger(r)||void 0!==t?.min&&r<t.min||void 0!==t?.max&&r>t.max?void 0:r}function formatBoolean(e){if(void 0===e)return;if("boolean"==typeof e)return e;const t=String(e).trim().toLowerCase();return["true","1"].includes(t)}function parsePreamble(e){return{temperature:formatNumber(e.temperature,{min:0,max:1}),topP:formatNumber(e.topP,{min:0,max:1}),penaltyScore:formatNumber(e.penaltyScore,{min:1,max:2}),knowledgeList:e.knowledgeList?.filter((e=>e?.trim().length>0)),mergeUserKnowledge:formatBoolean(e.mergeUserKnowledge)}}function parsePromptFile(e,t){let[r,n]=getPreambleAndBody(t);const i=jsYaml.load(r,{json:!0})??{},{name:o,description:s,...a}=i,c=o?String(o):e;return{name:c,description:s??c,system:parsePreamble(a),promptTemplate:n}}const promptTemplatePreamble="\n# 自定义指令名称,必填\nname: 自定义指令名称\n# 自定义指令描述,可选\ndescription: 自定义指令的描述\n",defaultPromptTemplate="\n该部分内容为自定义Prompt具体内容,请根据需求直接修改此段话。比如:帮我生成一个随机数。\n",promptTemplateAnnotation="\n# =================高级Prompt编写说明==========================\n# Prompt支持以下多种变量配合使用:\n # {{ query }} 为用户输入框输入的内容\n # {{ knowledgeList }} 为knowledgelist配置和用户输入的知识,详细说明见最下方知识手册\n # {{ selectedCode }} 为用户当前选中代码\n # {{ activeFileContent}} 为IDE光标所在文件的内容\n # {{ activeFilelineContent}} 为IDE光标所在行的内容\n # {{ [FILE] path }} 为本地文件内容,将path替换为相对当前项目根目录的相对路径即可\n# 详细说明请见使用手册:https://ku.baidu-int.com/knowledge/HFVrC7hq1Q/_SKPgSwp2G/Hb6OQz5Jc7/PvZ5uWD8MdM0w_\n",parseFilePathInPromptTemplate=e=>{try{const t=/\{\{\s*(\[FILE\]\s*([\\\/\-\.\w]+))\s*\}\}/g,r={};let n;for(;null!==(n=t.exec(e));)r[n[1]]=n[2];return r}catch(e){return}},normalizeFilePath=(e,t)=>t?.includes("/")?"win32"===process.platform?path__default.join(e,t.replace(/\//g,path__default.sep)):path__default.join(e,t):t?.includes("\\")?"win32"===process.platform?path__default.join(e,t):path__default.join(e,t.replace(/\\/g,path__default.sep)):path__default.join(e,t);function generatePromptTemplate(e){let t=promptTemplatePreamble+PREAMBLE_SEPERATOR;return e||(t+=defaultPromptTemplate),e?.query&&(t+=`请回答我的问题:${e.query}`),t+ANNOTATION_SEPERATOR+promptTemplateAnnotation}const MAX_INPUT_STRING=modelMapMaxInputString[TextModel.ErnieBot4Turbo128]-2e3;class PromptTemplateService{mediator;logger;constructor(e,t){this.mediator=e,this.logger=t}async init(){this.logger.info("PromptTemplateService init"),this.getAll()}async getPromptTemplateDirectoryPath(){try{const e=await this.mediator.getWorkspaceFolders();if(e&&e.length>0){const t=URI$3.parse(e[0].uri).fsPath;return getPromptTemplateRootPath(t)}}catch(e){this.logger.error(e)}}async getDirectoryPromptTemplates(e){try{const t=await readdir$7(e,{withFileTypes:!0}),r=[];for(const n of t)if(n.isFile()&&n.name.endsWith(".prompt")){const t=path__default.join(e,"/",n.name),{success:i,data:o}=await this.validatePromptTemplate(t);if(i){const e=await readFile$3(t,{encoding:"utf8"}),i=n.name.replace(/\.prompt$/,""),{name:s,description:a}=parsePromptFile(i,e);r.unshift({uuid:i,name:s,description:a,ts:o?.ts||0})}}return r.sort(((e,t)=>t.ts-e.ts))}catch(e){return this.logger.error(e),[]}}async getAll(){try{if(isInternal()){if(isVscode){const e=await this.getPromptTemplateDirectoryPath();if(e){if(await isFolderAccessable(e)){return await this.getDirectoryPromptTemplates(e)}return[]}return[]}return[]}return await apiGetPromptTemplateList()??[]}catch(e){return this.logger.error(e),[]}}async create(e){try{const t=await this.getPromptTemplateDirectoryPath();if(t){await isFolderAccessable(t)||await mkdir$c(t,{recursive:!0});const r=path__default.join(t,`prompt_${dayjs$1().format("YYYY-MM-DD_HH_mm_ss")}.prompt`);return{uri:r,content:generatePromptTemplate(e)}}return"未打开工作区,无法创建自定义指令"}catch(e){return this.logger.error(e),"创建自定义指令失败"}}async save(e){try{const t=await this.getAll(),r=await this.getPromptTemplateDirectoryPath();if(r){const n=path__default.join(r,"/",e+".prompt"),i=await readFile$3(n,{encoding:"utf8"}),{name:o}=parsePromptFile(n,i);return void 0!==t.find((t=>t.name===o&&t.uuid!==e))?"该自定义指令已存在,请重新命名":void 0}return"未打开工作区"}catch(e){return this.logger.error(e),"保存自定义指令失败"}}async delete(e){try{const t=await this.getPromptTemplateDirectoryPath();if(t){const r=path__default.join(t,e+".prompt");return await isFileAccessable(r)?void await unlink(r):"该自定义指令不存在"}return"未打开工作区"}catch(e){return this.logger.error(e),"删除自定义指令失败"}}validateLength(e,t){if(e.length>MAX_INPUT_STRING)throw new Error(`${t},不能超过${MAX_INPUT_STRING}个字符,请简化或移除该部分内容。`)}async validatePromptTemplate(e){try{const t=await stat$g(e),r=t.size;return r>MAX_INPUT_STRING?{success:!1,message:"自定义指令文件过大,当前大小: "+r+" 字节"}:{success:!0,data:{ts:t.birthtimeMs||t.ctimeMs}}}catch(e){return this.logger.error("获取文件状态时出错:",e),{success:!1,message:"自定义指令文件获取失败,请先检查该文件是否存在"}}}generateMessageEvent(e,t,r){return{messageId:t,sessionId:"",data:{action:ACTION_CHAT_TASK_PROGRESS,payload:{taskId:String(t),messageId:t,chunk:r,informationList:[],capabilityName:e}}}}async processNormalKnowledgeList({query:e,inputKnowledgeList:t,templateKnowledgeList:r,mergeUserKnowledge:n}){let i="";if(r?.length||n&&t?.length){this.logger.info("Prompt 生成结果验证 [知识集检索(配置)]:",r?.join("/")),this.logger.info("Prompt 生成结果验证 [知识集检索(输入)]:",t.map((e=>e.uuid))?.join("/"));const o=await this.mediator.pluginConfigApi.getKnowledgeQueryResult(e,InformationQueryType.Text,t.map((e=>({uuid:e.uuid??e.id,type:"NORMAL"}))),{mergeUserKnowledge:n,knowledgeSets:r?.map((e=>({uuid:e,type:"NORMAL"})))});for(const e of o.chunks)i+=e.content?.trim();this.logger.info("Prompt 生成结果验证 [知识集检索(结果)]:",i),this.validateLength(i,"知识集检索结果过长")}return i}async processInputFileKnowledgeList(e){let t="";if(e?.length)for(const r of e)t+=r.content?.trim();return this.validateLength(t,"输入文件的文件内容过长"),t}async processTemplateFileKnowledgeList(e){const t={},r=await this.mediator.getWorkspaceFolders(),n=[];if(r?.[0]?.uri){const i=URI$3.parse(r[0].uri).fsPath;if(e){for(const[r,o]of Object.entries(e)){const e=normalizeFilePath(i,o);try{const i=await stat$g(e);if(i.isFile()){if(i.size>MAX_INPUT_STRING){n.push(`文件${o}内容过长`);continue}const s=await readFile$3(e,{encoding:"utf8"});t[r]=s?.trim()}}catch(e){n.push(`未找到文件${o}`);break}}if(n.length>0)throw new Error(n.join(","))}return t}return t}async*chat(e,t){const r=await this.getPromptTemplateDirectoryPath(),n=new StringChunkStream;if(r){const i=path__default.join(r,"/",t.input.capability+".prompt"),{success:o,message:s}=await this.validatePromptTemplate(i);if(!o)return void(yield this.generateMessageEvent(e,t.input.messageId,n.fail(s||"")));try{const r=await readFile$3(i,{encoding:"utf8"}),{system:o,promptTemplate:s}=parsePromptFile(i,r),a={query:t.input.query,selectedCode:t.context?.selectedCode,activeFileContent:t.context?.activeFileContent,activeFileLineContent:t.context?.activeFileLineContent,activeFileLanguage:t.context?.activeFileLanguage,knowledgeList:""},c=t.input.informationList?.filter((({type:e})=>["SYSTEM","NORMAL"].includes(e))),A=await this.processNormalKnowledgeList({query:t.input.query,inputKnowledgeList:c,templateKnowledgeList:o.knowledgeList,mergeUserKnowledge:o.mergeUserKnowledge}),l=parseFilePathInPromptTemplate(s);this.logger.info("Prompt 生成结果验证 [文件路径映射]:",JSON.stringify(l));const u=await this.processTemplateFileKnowledgeList(l);this.logger.info("Prompt 生成结果验证 [文件内容映射]:",JSON.stringify(u));const d=await this.processInputFileKnowledgeList(t.input.informationList?.filter((({type:e})=>["FILE","CURRENT_FILE"].includes(e))));a.knowledgeList=A+"\n"+d+"\n";const h=formatPrompt(s,{...a,...u})?.trim();if(!h)throw new Error("Prompt 为空,请确认自定义指令Prompt配置是否正确");this.logger.info("Prompt 生成结果验证:",h),this.validateLength(h,"您输入的内容和选中的内容总长度过长");const p=h.length>modelMapMaxInputString[TextModel.ErnieBot4]?TextModel.ErnieBot4Turbo128:TextModel.ErnieBot4,g=[{role:"user",content:h}];A?.length>0&&this.logger.logUploader?.logUserAction({category:"promptTemplate",action:"chatWithKnowledge",content:`inputKnowledgeList: ${c?.length},templateKnowledgeList: {${o?.knowledgeList?.length}},mergeUserKnowledge: ${o?.mergeUserKnowledge}`});const f=await this.mediator.llmApi.callErnieBotStreaming({messages:g,pluginName:"PromptTemplate",model:p,modelOptions:{temperature:o?.temperature,topP:o?.topP,penaltyScore:o?.penaltyScore},device:this.mediator.userDetail()?.device});let m="";for await(const r of f)m+=r.result,yield this.generateMessageEvent(e,t.input.messageId,n.flushReplaceLast(m))}catch(r){yield this.generateMessageEvent(e,t.input.messageId,n.fail(r?.message))}}}}class AppLaunchTracker{logger;lastExecutionDate;constructor(e){this.logger=e,this.lastExecutionDate="",this.initializeScheduler()}initializeScheduler(){setInterval((()=>{this.checkAndTrackLaunch()}),36e5),this.checkAndTrackLaunch()}checkAndTrackLaunch(){const e=(new Date).toDateString();this.lastExecutionDate!==e&&(this.trackLaunch(),this.lastExecutionDate=e)}trackLaunch(){this.logger.logUploader?.logUserAction({category:"engineInnerInit",content:"IDE channel initialized"})}}const sleep=e=>new Promise((t=>setTimeout(t,e)));class IScan{logger;mediator;pluginName="aiscan";capabilityName="codeStyleCheck";latestJobBuildId=null;constructor(e,t){this.logger=t,this.mediator=e}async startScan({ignoreNoErrorNotification:e,systemInfo:t}){try{const r=crypto$7.randomUUID();for await(const n of this.mediator.sendToPlugin(r,{action:ACTION_START_ISCAN,payload:{systemInfo:t,pluginName:this.pluginName,capabilityName:this.capabilityName,scanType:"init"}})){const r=n?.data.payload.chunk,{jobBuildId:i,errorMsg:o,status:s}=r;return this.logger.info("jobBuildResult",i,o,s),i?(this.latestJobBuildId=i,this.reportScanResult(e,t,i),!0):(this.logger.error("iScan job build error",o),!1)}return!1}catch(e){return this.logger.error("startScan failed",e instanceof Error?e.toString():e),!1}}async reportScanResult(e,t,r,n=3e5){const i=Date.now();let o=!1;for(;Date.now()-i<n&&!o;){if(this.latestJobBuildId!==r)return void this.logger.info("Scan job cancelled",r);try{const n=crypto$7.randomUUID();for await(const i of this.mediator.sendToPlugin(n,{action:ACTION_START_ISCAN,payload:{systemInfo:t,pluginName:this.pluginName,capabilityName:this.capabilityName,scanType:"getResult",jobBuildId:r}})){if(this.latestJobBuildId!==r)return void this.logger.info("Scan job cancelled during processing",r);const n=i?.data.payload.chunk;if(this.logger.info("reportScanResult",r,n),"SUCC"===n.status){o=!0;const i=(n.codestyle?.high||0)+(n.codestyle?.middle||0)+(n.codestyle?.low||0),s=(n.bugbye?.high||0)+(n.bugbye?.middle||0)+(n.bugbye?.low||0);if(e&&0===i&&0===s)return;const a=0===i&&0===s?"Comate代码扫描已完成,未发现任何问题!您可以放心继续下一步操作。":`Comate代码扫描已完成,发现 ${0===i?"":`${i} 个代码规范问题,`} ${0===s?"":`${s} 个代码缺陷问题,`} 建议您立即修复,避免合入被卡位。`,c=await currentBranch({fs:fs$1i,dir:t.cwd}),A=c?`git push origin HEAD:refs/for/${c}`:"git push origin master";this.mediator.sendToIde(ACTION_SCAN_NOTIFICATION,{notification:a,jobBuildId:r,buttonType:0!==i||0!==s?"detailButton":"pushButton",pushCommand:A})}break}await sleep(1e4)}catch(e){this.logger.error("get result failed",e instanceof Error?e.toString():e),await sleep(1e4)}}o||this.logger.error("get result timed out")}}const LATEST_PROTOCOL_VERSION="2025-06-18",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-03-26","2024-11-05","2024-10-07"],JSONRPC_VERSION="2.0",ProgressTokenSchema=z.union([z.string(),z.number().int()]),CursorSchema=z.string(),RequestMetaSchema=z.object({progressToken:z.optional(ProgressTokenSchema)}).passthrough(),BaseRequestParamsSchema=z.object({_meta:z.optional(RequestMetaSchema)}).passthrough(),RequestSchema=z.object({method:z.string(),params:z.optional(BaseRequestParamsSchema)}),BaseNotificationParamsSchema=z.object({_meta:z.optional(z.object({}).passthrough())}).passthrough(),NotificationSchema=z.object({method:z.string(),params:z.optional(BaseNotificationParamsSchema)}),ResultSchema=z.object({_meta:z.optional(z.object({}).passthrough())}).passthrough(),RequestIdSchema=z.union([z.string(),z.number().int()]),JSONRPCRequestSchema=z.object({jsonrpc:z.literal(JSONRPC_VERSION),id:RequestIdSchema}).merge(RequestSchema).strict(),isJSONRPCRequest=e=>JSONRPCRequestSchema.safeParse(e).success,JSONRPCNotificationSchema=z.object({jsonrpc:z.literal(JSONRPC_VERSION)}).merge(NotificationSchema).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema.safeParse(e).success,JSONRPCResponseSchema=z.object({jsonrpc:z.literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResponse=e=>JSONRPCResponseSchema.safeParse(e).success;var ErrorCode;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(ErrorCode||(ErrorCode={}));const JSONRPCErrorSchema=z.object({jsonrpc:z.literal(JSONRPC_VERSION),id:RequestIdSchema,error:z.object({code:z.number().int(),message:z.string(),data:z.optional(z.unknown())})}).strict(),isJSONRPCError=e=>JSONRPCErrorSchema.safeParse(e).success,JSONRPCMessageSchema=z.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResponseSchema,JSONRPCErrorSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/cancelled"),params:BaseNotificationParamsSchema.extend({requestId:RequestIdSchema,reason:z.string().optional()})}),IconSchema=z.object({src:z.string(),mimeType:z.optional(z.string()),sizes:z.optional(z.array(z.string()))}).passthrough(),IconsSchema=z.object({icons:z.array(IconSchema).optional()}).passthrough(),BaseMetadataSchema=z.object({name:z.string(),title:z.optional(z.string())}).passthrough(),ImplementationSchema=BaseMetadataSchema.extend({version:z.string(),websiteUrl:z.optional(z.string())}).merge(IconsSchema),ClientCapabilitiesSchema=z.object({experimental:z.optional(z.object({}).passthrough()),sampling:z.optional(z.object({}).passthrough()),elicitation:z.optional(z.object({}).passthrough()),roots:z.optional(z.object({listChanged:z.optional(z.boolean())}).passthrough())}).passthrough(),InitializeRequestSchema=RequestSchema.extend({method:z.literal("initialize"),params:BaseRequestParamsSchema.extend({protocolVersion:z.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema})}),ServerCapabilitiesSchema=z.object({experimental:z.optional(z.object({}).passthrough()),logging:z.optional(z.object({}).passthrough()),completions:z.optional(z.object({}).passthrough()),prompts:z.optional(z.object({listChanged:z.optional(z.boolean())}).passthrough()),resources:z.optional(z.object({subscribe:z.optional(z.boolean()),listChanged:z.optional(z.boolean())}).passthrough()),tools:z.optional(z.object({listChanged:z.optional(z.boolean())}).passthrough())}).passthrough(),InitializeResultSchema=ResultSchema.extend({protocolVersion:z.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z.optional(z.string())}),InitializedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/initialized")}),isInitializedNotification=e=>InitializedNotificationSchema.safeParse(e).success,PingRequestSchema=RequestSchema.extend({method:z.literal("ping")}),ProgressSchema=z.object({progress:z.number(),total:z.optional(z.number()),message:z.optional(z.string())}).passthrough(),ProgressNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/progress"),params:BaseNotificationParamsSchema.merge(ProgressSchema).extend({progressToken:ProgressTokenSchema})}),PaginatedRequestSchema=RequestSchema.extend({params:BaseRequestParamsSchema.extend({cursor:z.optional(CursorSchema)}).optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:z.optional(CursorSchema)}),ResourceContentsSchema=z.object({uri:z.string(),mimeType:z.optional(z.string()),_meta:z.optional(z.object({}).passthrough())}).passthrough(),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z.string()}),Base64Schema=z.string().refine((e=>{try{return atob(e),!0}catch(e){return!1}}),{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),ResourceSchema=BaseMetadataSchema.extend({uri:z.string(),description:z.optional(z.string()),mimeType:z.optional(z.string()),_meta:z.optional(z.object({}).passthrough())}).merge(IconsSchema),ResourceTemplateSchema=BaseMetadataSchema.extend({uriTemplate:z.string(),description:z.optional(z.string()),mimeType:z.optional(z.string()),_meta:z.optional(z.object({}).passthrough())}).merge(IconsSchema),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z.array(ResourceTemplateSchema)}),ReadResourceRequestSchema=RequestSchema.extend({method:z.literal("resources/read"),params:BaseRequestParamsSchema.extend({uri:z.string()})}),ReadResourceResultSchema=ResultSchema.extend({contents:z.array(z.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/resources/list_changed")}),SubscribeRequestSchema=RequestSchema.extend({method:z.literal("resources/subscribe"),params:BaseRequestParamsSchema.extend({uri:z.string()})}),UnsubscribeRequestSchema=RequestSchema.extend({method:z.literal("resources/unsubscribe"),params:BaseRequestParamsSchema.extend({uri:z.string()})}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/resources/updated"),params:BaseNotificationParamsSchema.extend({uri:z.string()})}),PromptArgumentSchema=z.object({name:z.string(),description:z.optional(z.string()),required:z.optional(z.boolean())}).passthrough(),PromptSchema=BaseMetadataSchema.extend({description:z.optional(z.string()),arguments:z.optional(z.array(PromptArgumentSchema)),_meta:z.optional(z.object({}).passthrough())}).merge(IconsSchema),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z.array(PromptSchema)}),GetPromptRequestSchema=RequestSchema.extend({method:z.literal("prompts/get"),params:BaseRequestParamsSchema.extend({name:z.string(),arguments:z.optional(z.record(z.string()))})}),TextContentSchema=z.object({type:z.literal("text"),text:z.string(),_meta:z.optional(z.object({}).passthrough())}).passthrough(),ImageContentSchema=z.object({type:z.literal("image"),data:Base64Schema,mimeType:z.string(),_meta:z.optional(z.object({}).passthrough())}).passthrough(),AudioContentSchema=z.object({type:z.literal("audio"),data:Base64Schema,mimeType:z.string(),_meta:z.optional(z.object({}).passthrough())}).passthrough(),EmbeddedResourceSchema=z.object({type:z.literal("resource"),resource:z.union([TextResourceContentsSchema,BlobResourceContentsSchema]),_meta:z.optional(z.object({}).passthrough())}).passthrough(),ResourceLinkSchema=ResourceSchema.extend({type:z.literal("resource_link")}),ContentBlockSchema=z.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z.object({role:z.enum(["user","assistant"]),content:ContentBlockSchema}).passthrough(),GetPromptResultSchema=ResultSchema.extend({description:z.optional(z.string()),messages:z.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/prompts/list_changed")}),ToolAnnotationsSchema=z.object({title:z.optional(z.string()),readOnlyHint:z.optional(z.boolean()),destructiveHint:z.optional(z.boolean()),idempotentHint:z.optional(z.boolean()),openWorldHint:z.optional(z.boolean())}).passthrough(),ToolSchema=BaseMetadataSchema.extend({description:z.optional(z.string()),inputSchema:z.object({type:z.literal("object"),properties:z.optional(z.object({}).passthrough()),required:z.optional(z.array(z.string()))}).passthrough(),outputSchema:z.optional(z.object({type:z.literal("object"),properties:z.optional(z.object({}).passthrough()),required:z.optional(z.array(z.string()))}).passthrough()),annotations:z.optional(ToolAnnotationsSchema),_meta:z.optional(z.object({}).passthrough())}).merge(IconsSchema),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z.array(ContentBlockSchema).default([]),structuredContent:z.object({}).passthrough().optional(),isError:z.optional(z.boolean())});CallToolResultSchema.or(ResultSchema.extend({toolResult:z.unknown()}));const CallToolRequestSchema=RequestSchema.extend({method:z.literal("tools/call"),params:BaseRequestParamsSchema.extend({name:z.string(),arguments:z.optional(z.record(z.unknown()))})}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/tools/list_changed")}),LoggingLevelSchema=z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestSchema=RequestSchema.extend({method:z.literal("logging/setLevel"),params:BaseRequestParamsSchema.extend({level:LoggingLevelSchema})}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/message"),params:BaseNotificationParamsSchema.extend({level:LoggingLevelSchema,logger:z.optional(z.string()),data:z.unknown()})}),ModelHintSchema=z.object({name:z.string().optional()}).passthrough(),ModelPreferencesSchema=z.object({hints:z.optional(z.array(ModelHintSchema)),costPriority:z.optional(z.number().min(0).max(1)),speedPriority:z.optional(z.number().min(0).max(1)),intelligencePriority:z.optional(z.number().min(0).max(1))}).passthrough(),SamplingMessageSchema=z.object({role:z.enum(["user","assistant"]),content:z.union([TextContentSchema,ImageContentSchema,AudioContentSchema])}).passthrough(),CreateMessageRequestSchema=RequestSchema.extend({method:z.literal("sampling/createMessage"),params:BaseRequestParamsSchema.extend({messages:z.array(SamplingMessageSchema),systemPrompt:z.optional(z.string()),includeContext:z.optional(z.enum(["none","thisServer","allServers"])),temperature:z.optional(z.number()),maxTokens:z.number().int(),stopSequences:z.optional(z.array(z.string())),metadata:z.optional(z.object({}).passthrough()),modelPreferences:z.optional(ModelPreferencesSchema)})}),CreateMessageResultSchema=ResultSchema.extend({model:z.string(),stopReason:z.optional(z.enum(["endTurn","stopSequence","maxTokens"]).or(z.string())),role:z.enum(["user","assistant"]),content:z.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema])}),BooleanSchemaSchema=z.object({type:z.literal("boolean"),title:z.optional(z.string()),description:z.optional(z.string()),default:z.optional(z.boolean())}).passthrough(),StringSchemaSchema=z.object({type:z.literal("string"),title:z.optional(z.string()),description:z.optional(z.string()),minLength:z.optional(z.number()),maxLength:z.optional(z.number()),format:z.optional(z.enum(["email","uri","date","date-time"]))}).passthrough(),NumberSchemaSchema=z.object({type:z.enum(["number","integer"]),title:z.optional(z.string()),description:z.optional(z.string()),minimum:z.optional(z.number()),maximum:z.optional(z.number())}).passthrough(),EnumSchemaSchema=z.object({type:z.literal("string"),title:z.optional(z.string()),description:z.optional(z.string()),enum:z.array(z.string()),enumNames:z.optional(z.array(z.string()))}).passthrough(),PrimitiveSchemaDefinitionSchema=z.union([BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema,EnumSchemaSchema]),ElicitRequestSchema=RequestSchema.extend({method:z.literal("elicitation/create"),params:BaseRequestParamsSchema.extend({message:z.string(),requestedSchema:z.object({type:z.literal("object"),properties:z.record(z.string(),PrimitiveSchemaDefinitionSchema),required:z.optional(z.array(z.string()))}).passthrough()})}),ElicitResultSchema=ResultSchema.extend({action:z.enum(["accept","decline","cancel"]),content:z.optional(z.record(z.string(),z.unknown()))}),ResourceTemplateReferenceSchema=z.object({type:z.literal("ref/resource"),uri:z.string()}).passthrough(),PromptReferenceSchema=z.object({type:z.literal("ref/prompt"),name:z.string()}).passthrough(),CompleteRequestSchema=RequestSchema.extend({method:z.literal("completion/complete"),params:BaseRequestParamsSchema.extend({ref:z.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z.object({name:z.string(),value:z.string()}).passthrough(),context:z.optional(z.object({arguments:z.optional(z.record(z.string(),z.string()))}))})}),CompleteResultSchema=ResultSchema.extend({completion:z.object({values:z.array(z.string()).max(100),total:z.optional(z.number().int()),hasMore:z.optional(z.boolean())}).passthrough()}),RootSchema=z.object({uri:z.string().startsWith("file://"),name:z.optional(z.string()),_meta:z.optional(z.object({}).passthrough())}).passthrough(),ListRootsRequestSchema=RequestSchema.extend({method:z.literal("roots/list")}),ListRootsResultSchema=ResultSchema.extend({roots:z.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z.literal("notifications/roots/list_changed")});z.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema]),z.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema]),z.union([EmptyResultSchema,CreateMessageResultSchema,ElicitResultSchema,ListRootsResultSchema]),z.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema]),z.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema]),z.union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema]);class McpError extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}}class TypedEventEmitter extends EventEmitter$c{on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}off(e,t){return super.off(e,t)}emit(e,...t){return super.emit(e,...t)}}const{omitBy:omitBy,isNil:isNil}=_$H,DEFAULT_MCP_TIMEOUT_SECONDS$1=30,deepDropNilValue=e=>{if(null==e)return e;if(Array.isArray(e))return e.filter((e=>null!=e)).map((e=>deepDropNilValue(e)));if("object"==typeof e&&e.constructor===Object){const t=omitBy(e,isNil),r={};for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(r[e]=deepDropNilValue(t[e]));return r}return e};function extractRuntimeConfig(e){return"stdio"===e.transportType?{command:e.command,args:e.args,env:e.env,cwd:e.cwd}:{url:e.url,requestInit:e.requestInit}}function filterComateEnv(e){return Object.fromEntries(Object.entries(e||process.env).filter((([e])=>!e.startsWith("COMATE_"))))}function expandTilde(e){return e.replace(/^~(?=$|\/|\\)/,homedir())}function offsetToLine(e,t){if(t<=0)return 0;const r=Math.min(t,e.length);let n=0;for(let t=0;t<r;t++){const r=e.charCodeAt(t);10!==r?13===r&&(10===e.charCodeAt(t+1)&&t++,n++):n++}return n}function offsetToLineColumn(e,t){if(t<=0)return{line:0,column:0};const r=Math.min(t,e.length);let n=0,i=0;for(let t=0;t<r;t++){const r=e.charCodeAt(t);10!==r?13===r&&(10===e.charCodeAt(t+1)&&t++,n++,i=t+1):(n++,i=t+1)}return{line:n,column:r-i}}function secondsToMs(e){return 1e3*e}function formatPathEnv(e){const t=e.PATH;if(!t)return"(未设置)";return t.split(path__default.delimiter).map(((e,t)=>` [${t+1}] ${e}`)).join("\n")}function formatEnvDiagnostics(e){return`当前 PATH 环境变量:\n${formatPathEnv({...process.env,...e})}`}function trySpawnOnce(e,t,r){return new Promise((n=>{const i=spawn$5(e,t,{stdio:["ignore","pipe","pipe"],shell:!1,windowsHide:!0});let o="",s="",a=!1;const c=e=>{a||(a=!0,clearTimeout(A),i.removeAllListeners(),n(e))},A=setTimeout((()=>{i.kill("SIGKILL"),c({code:null,timeout:!0})}),r);i.stdout?.on("data",(e=>o+=e.toString())),i.stderr?.on("data",(e=>s+=e.toString())),i.on("error",(e=>{c({code:null,err:e})})),i.on("close",(e=>{c({code:e})}))}))}function createScanner(e,t=!1){const r=e.length;let n=0,i="",o=0,s=16,a=0,c=0,A=0,l=0,u=0;function d(t,r){let i=0,o=0;for(;i<t||!r;){let t=e.charCodeAt(n);if(t>=48&&t<=57)o=16*o+t-48;else if(t>=65&&t<=70)o=16*o+t-65+10;else{if(!(t>=97&&t<=102))break;o=16*o+t-97+10}n++,i++}return i<t&&(o=-1),o}function h(){if(i="",u=0,o=n,c=a,l=A,n>=r)return o=r,s=17;let t=e.charCodeAt(n);if(isWhiteSpace(t)){do{n++,i+=String.fromCharCode(t),t=e.charCodeAt(n)}while(isWhiteSpace(t));return s=15}if(isLineBreak(t))return n++,i+=String.fromCharCode(t),13===t&&10===e.charCodeAt(n)&&(n++,i+="\n"),a++,A=n,s=14;switch(t){case 123:return n++,s=1;case 125:return n++,s=2;case 91:return n++,s=3;case 93:return n++,s=4;case 58:return n++,s=6;case 44:return n++,s=5;case 34:return n++,i=function(){let t="",i=n;for(;;){if(n>=r){t+=e.substring(i,n),u=2;break}const o=e.charCodeAt(n);if(34===o){t+=e.substring(i,n),n++;break}if(92!==o){if(o>=0&&o<=31){if(isLineBreak(o)){t+=e.substring(i,n),u=2;break}u=6}n++}else{if(t+=e.substring(i,n),n++,n>=r){u=2;break}switch(e.charCodeAt(n++)){case 34:t+='"';break;case 92:t+="\\";break;case 47:t+="/";break;case 98:t+="\b";break;case 102:t+="\f";break;case 110:t+="\n";break;case 114:t+="\r";break;case 116:t+="\t";break;case 117:const e=d(4,!0);e>=0?t+=String.fromCharCode(e):u=4;break;default:u=5}i=n}}return t}(),s=10;case 47:const c=n-1;if(47===e.charCodeAt(n+1)){for(n+=2;n<r&&!isLineBreak(e.charCodeAt(n));)n++;return i=e.substring(c,n),s=12}if(42===e.charCodeAt(n+1)){n+=2;const t=r-1;let o=!1;for(;n<t;){const t=e.charCodeAt(n);if(42===t&&47===e.charCodeAt(n+1)){n+=2,o=!0;break}n++,isLineBreak(t)&&(13===t&&10===e.charCodeAt(n)&&n++,a++,A=n)}return o||(n++,u=1),i=e.substring(c,n),s=13}return i+=String.fromCharCode(t),n++,s=16;case 45:if(i+=String.fromCharCode(t),n++,n===r||!isDigit(e.charCodeAt(n)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return i+=function(){let t=n;if(48===e.charCodeAt(n))n++;else for(n++;n<e.length&&isDigit(e.charCodeAt(n));)n++;if(n<e.length&&46===e.charCodeAt(n)){if(n++,!(n<e.length&&isDigit(e.charCodeAt(n))))return u=3,e.substring(t,n);for(n++;n<e.length&&isDigit(e.charCodeAt(n));)n++}let r=n;if(n<e.length&&(69===e.charCodeAt(n)||101===e.charCodeAt(n)))if(n++,(n<e.length&&43===e.charCodeAt(n)||45===e.charCodeAt(n))&&n++,n<e.length&&isDigit(e.charCodeAt(n))){for(n++;n<e.length&&isDigit(e.charCodeAt(n));)n++;r=n}else u=3;return e.substring(t,r)}(),s=11;default:for(;n<r&&p(t);)n++,t=e.charCodeAt(n);if(o!==n){switch(i=e.substring(o,n),i){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return i+=String.fromCharCode(t),n++,s=16}}function p(e){if(isWhiteSpace(e)||isLineBreak(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}return{setPosition:function(e){n=e,i="",o=0,s=16,u=0},getPosition:()=>n,scan:t?function(){let e;do{e=h()}while(e>=12&&e<=15);return e}:h,getToken:()=>s,getTokenValue:()=>i,getTokenOffset:()=>o,getTokenLength:()=>n-o,getTokenStartLine:()=>c,getTokenStartCharacter:()=>o-l,getTokenError:()=>u}}function isWhiteSpace(e){return 32===e||9===e}function isLineBreak(e){return 10===e||13===e}function isDigit(e){return e>=48&&e<=57}var CharacterCodes;!function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",e[e.formFeed=12]="formFeed",e[e.tab=9]="tab"}(CharacterCodes||(CharacterCodes={}));const cachedSpaces=new Array(20).fill(0).map(((e,t)=>" ".repeat(t))),maxCachedValues=200,cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map(((e,t)=>"\n"+" ".repeat(t))),"\r":new Array(maxCachedValues).fill(0).map(((e,t)=>"\r"+" ".repeat(t))),"\r\n":new Array(maxCachedValues).fill(0).map(((e,t)=>"\r\n"+" ".repeat(t)))},"\t":{"\n":new Array(maxCachedValues).fill(0).map(((e,t)=>"\n"+"\t".repeat(t))),"\r":new Array(maxCachedValues).fill(0).map(((e,t)=>"\r"+"\t".repeat(t))),"\r\n":new Array(maxCachedValues).fill(0).map(((e,t)=>"\r\n"+"\t".repeat(t)))}},supportedEols=["\n","\r","\r\n"];function format$6(e,t,r){let n,i,o,s,a;if(t){for(s=t.offset,a=s+t.length,o=s;o>0&&!isEOL(e,o-1);)o--;let c=a;for(;c<e.length&&!isEOL(e,c);)c++;i=e.substring(o,c),n=computeIndentLevel(i,r)}else i=e,n=0,o=0,s=0,a=e.length;const c=getEOL(r,e),A=supportedEols.includes(c);let l,u=0,d=0;l=r.insertSpaces?cachedSpaces[r.tabSize||4]??repeat(cachedSpaces[1],r.tabSize||4):"\t";const h="\t"===l?"\t":" ";let p=createScanner(i,!1),g=!1;function f(){if(u>1)return repeat(c,u)+repeat(l,n+d);const e=l.length*(n+d);return!A||e>cachedBreakLinesWithSpaces[h][c].length?c+repeat(l,n+d):e<=0?c:cachedBreakLinesWithSpaces[h][c][e]}function m(){let e=p.scan();for(u=0;15===e||14===e;)14===e&&r.keepLines?u+=1:14===e&&(u=1),e=p.scan();return g=16===e||0!==p.getTokenError(),e}const E=[];function C(r,n,i){g||t&&!(n<a&&i>s)||e.substring(n,i)===r||E.push({offset:n,length:i-n,content:r})}let I=m();if(r.keepLines&&u>0&&C(repeat(c,u),0,0),17!==I){let e=p.getTokenOffset()+o;C(l.length*n<20&&r.insertSpaces?cachedSpaces[l.length*n]:repeat(l,n),o,e)}for(;17!==I;){let e=p.getTokenOffset()+p.getTokenLength()+o,t=m(),n="",i=!1;for(;0===u&&(12===t||13===t);){let r=p.getTokenOffset()+o;C(cachedSpaces[1],e,r),e=p.getTokenOffset()+p.getTokenLength()+o,i=12===t,n=i?f():"",t=m()}if(2===t)1!==I&&d--,r.keepLines&&u>0||!r.keepLines&&1!==I?n=f():r.keepLines&&(n=cachedSpaces[1]);else if(4===t)3!==I&&d--,r.keepLines&&u>0||!r.keepLines&&3!==I?n=f():r.keepLines&&(n=cachedSpaces[1]);else{switch(I){case 3:case 1:d++,n=r.keepLines&&u>0||!r.keepLines?f():cachedSpaces[1];break;case 5:n=r.keepLines&&u>0||!r.keepLines?f():cachedSpaces[1];break;case 12:n=f();break;case 13:u>0?n=f():i||(n=cachedSpaces[1]);break;case 6:r.keepLines&&u>0?n=f():i||(n=cachedSpaces[1]);break;case 10:r.keepLines&&u>0?n=f():6!==t||i||(n="");break;case 7:case 8:case 9:case 11:case 2:case 4:r.keepLines&&u>0?n=f():12!==t&&13!==t||i?5!==t&&17!==t&&(g=!0):n=cachedSpaces[1];break;case 16:g=!0}u>0&&(12===t||13===t)&&(n=f())}17===t&&(n=r.keepLines&&u>0?f():r.insertFinalNewline?c:"");C(n,e,p.getTokenOffset()+o),I=t}return E}function repeat(e,t){let r="";for(let n=0;n<t;n++)r+=e;return r}function computeIndentLevel(e,t){let r=0,n=0;const i=t.tabSize||4;for(;r<e.length;){let t=e.charAt(r);if(t===cachedSpaces[1])n++;else{if("\t"!==t)break;n+=i}r++}return Math.floor(n/i)}function getEOL(e,t){for(let e=0;e<t.length;e++){const r=t.charAt(e);if("\r"===r)return e+1<t.length&&"\n"===t.charAt(e+1)?"\r\n":"\r";if("\n"===r)return"\n"}return e&&e.eol||"\n"}function isEOL(e,t){return-1!=="\r\n".indexOf(e.charAt(t))}var ParseOptions,ScanError,SyntaxKind;function parse$f(e,t=[],r=ParseOptions.DEFAULT){let n=null,i=[];const o=[];function s(e){Array.isArray(i)?i.push(e):null!==n&&(i[n]=e)}const a={onObjectBegin:()=>{const e={};s(e),o.push(i),i=e,n=null},onObjectProperty:e=>{n=e},onObjectEnd:()=>{i=o.pop()},onArrayBegin:()=>{const e=[];s(e),o.push(i),i=e,n=null},onArrayEnd:()=>{i=o.pop()},onLiteralValue:s,onError:(e,r,n)=>{t.push({error:e,offset:r,length:n})}};return visit(e,a,r),i[0]}function parseTree$1(e,t=[],r=ParseOptions.DEFAULT){let n={type:"array",offset:-1,length:-1,children:[],parent:void 0};function i(e){"property"===n.type&&(n.length=e-n.offset,n=n.parent)}function o(e){return n.children.push(e),e}const s={onObjectBegin:e=>{n=o({type:"object",offset:e,length:-1,parent:n,children:[]})},onObjectProperty:(e,t,r)=>{n=o({type:"property",offset:t,length:-1,parent:n,children:[]}),n.children.push({type:"string",value:e,offset:t,length:r,parent:n})},onObjectEnd:(e,t)=>{i(e+t),n.length=e+t-n.offset,n=n.parent,i(e+t)},onArrayBegin:(e,t)=>{n=o({type:"array",offset:e,length:-1,parent:n,children:[]})},onArrayEnd:(e,t)=>{n.length=e+t-n.offset,n=n.parent,i(e+t)},onLiteralValue:(e,t,r)=>{o({type:getNodeType(e),offset:t,length:r,parent:n,value:e}),i(t+r)},onSeparator:(e,t,r)=>{"property"===n.type&&(":"===e?n.colonOffset=t:","===e&&i(t))},onError:(e,r,n)=>{t.push({error:e,offset:r,length:n})}};visit(e,s,r);const a=n.children[0];return a&&delete a.parent,a}function findNodeAtLocation$1(e,t){if(!e)return;let r=e;for(let e of t)if("string"==typeof e){if("object"!==r.type||!Array.isArray(r.children))return;let t=!1;for(const n of r.children)if(Array.isArray(n.children)&&n.children[0].value===e&&2===n.children.length){r=n.children[1],t=!0;break}if(!t)return}else{const t=e;if("array"!==r.type||t<0||!Array.isArray(r.children)||t>=r.children.length)return;r=r.children[t]}return r}function visit(e,t,r=ParseOptions.DEFAULT){const n=createScanner(e,!1),i=[];let o=0;function s(e){return e?t=>0===o&&e(t,n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter()):()=>!0}function a(e){return e?t=>0===o&&e(t,n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter(),(()=>i.slice())):()=>!0}function c(e){return e?()=>{if(o>0)o++;else{!1===e(n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter(),(()=>i.slice()))&&(o=1)}}:()=>!0}function A(e){return e?()=>{o>0&&o--,0===o&&e(n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter())}:()=>!0}const l=c(t.onObjectBegin),u=a(t.onObjectProperty),d=A(t.onObjectEnd),h=c(t.onArrayBegin),p=A(t.onArrayEnd),g=a(t.onLiteralValue),f=s(t.onSeparator),m=(C=t.onComment)?()=>0===o&&C(n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter()):()=>!0,E=s(t.onError);var C;const I=r&&r.disallowComments,y=r&&r.allowTrailingComma;function B(){for(;;){const e=n.scan();switch(n.getTokenError()){case 4:b(14);break;case 5:b(15);break;case 3:b(13);break;case 1:I||b(11);break;case 2:b(12);break;case 6:b(16)}switch(e){case 12:case 13:I?b(10):m();break;case 16:b(1);break;case 15:case 14:break;default:return e}}}function b(e,t=[],r=[]){if(E(e),t.length+r.length>0){let e=n.getToken();for(;17!==e;){if(-1!==t.indexOf(e)){B();break}if(-1!==r.indexOf(e))break;e=B()}}}function w(e){const t=n.getTokenValue();return e?g(t):(u(t),i.push(t)),B(),!0}function v(){switch(n.getToken()){case 3:return function(){h(),B();let e=!0,t=!1;for(;4!==n.getToken()&&17!==n.getToken();){if(5===n.getToken()){if(t||b(4,[],[]),f(","),B(),4===n.getToken()&&y)break}else t&&b(6,[],[]);e?(i.push(0),e=!1):i[i.length-1]++,v()||b(4,[],[4,5]),t=!0}return p(),e||i.pop(),4!==n.getToken()?b(8,[4],[]):B(),!0}();case 1:return function(){l(),B();let e=!1;for(;2!==n.getToken()&&17!==n.getToken();){if(5===n.getToken()){if(e||b(4,[],[]),f(","),B(),2===n.getToken()&&y)break}else e&&b(6,[],[]);(10!==n.getToken()?(b(3,[],[2,5]),0):(w(!1),6===n.getToken()?(f(":"),B(),v()||b(4,[],[2,5])):b(5,[],[2,5]),i.pop(),1))||b(4,[],[2,5]),e=!0}return d(),2!==n.getToken()?b(7,[2],[]):B(),!0}();case 10:return w(!0);default:return function(){switch(n.getToken()){case 11:const e=n.getTokenValue();let t=Number(e);isNaN(t)&&(b(2),t=0),g(t);break;case 7:g(null);break;case 8:g(!0);break;case 9:g(!1);break;default:return!1}return B(),!0}()}}return B(),17===n.getToken()?!!r.allowEmptyContent||(b(4,[],[]),!1):v()?(17!==n.getToken()&&b(9,[],[]),!0):(b(4,[],[]),!1)}function getNodeType(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":return e?Array.isArray(e)?"array":"object":"null";default:return"null"}}function setProperty(e,t,r,n){const i=t.slice(),o=parseTree$1(e,[]);let s,a;for(;i.length>0&&(a=i.pop(),s=findNodeAtLocation$1(o,i),void 0===s&&void 0!==r);)r="string"==typeof a?{[a]:r}:[r];if(s){if("object"===s.type&&"string"==typeof a&&Array.isArray(s.children)){const t=findNodeAtLocation$1(s,[a]);if(void 0!==t){if(void 0===r){if(!t.parent)throw new Error("Malformed AST");const r=s.children.indexOf(t.parent);let i,o=t.parent.offset+t.parent.length;if(r>0){let e=s.children[r-1];i=e.offset+e.length}else if(i=s.offset+1,s.children.length>1){o=s.children[1].offset}return withFormatting(e,{offset:i,length:o-i,content:""},n)}return withFormatting(e,{offset:t.offset,length:t.length,content:JSON.stringify(r)},n)}{if(void 0===r)return[];const t=`${JSON.stringify(a)}: ${JSON.stringify(r)}`,i=n.getInsertionIndex?n.getInsertionIndex(s.children.map((e=>e.children[0].value))):s.children.length;let o;if(i>0){let e=s.children[i-1];o={offset:e.offset+e.length,length:0,content:","+t}}else o=0===s.children.length?{offset:s.offset+1,length:0,content:t}:{offset:s.offset+1,length:0,content:t+","};return withFormatting(e,o,n)}}if("array"===s.type&&"number"==typeof a&&Array.isArray(s.children)){const t=a;if(-1===t){const t=`${JSON.stringify(r)}`;let i;if(0===s.children.length)i={offset:s.offset+1,length:0,content:t};else{const e=s.children[s.children.length-1];i={offset:e.offset+e.length,length:0,content:","+t}}return withFormatting(e,i,n)}if(void 0===r&&s.children.length>=0){const t=a,r=s.children[t];let i;if(1===s.children.length)i={offset:s.offset+1,length:s.length-2,content:""};else if(s.children.length-1===t){let e=s.children[t-1],r=e.offset+e.length;i={offset:r,length:s.offset+s.length-2-r,content:""}}else i={offset:r.offset,length:s.children[t+1].offset-r.offset,content:""};return withFormatting(e,i,n)}if(void 0!==r){let t;const i=`${JSON.stringify(r)}`;if(!n.isArrayInsertion&&s.children.length>a){const e=s.children[a];t={offset:e.offset,length:e.length,content:i}}else if(0===s.children.length||0===a)t={offset:s.offset+1,length:0,content:0===s.children.length?i:i+","};else{const e=a>s.children.length?s.children.length:a,r=s.children[e-1];t={offset:r.offset+r.length,length:0,content:","+i}}return withFormatting(e,t,n)}throw new Error(`Can not ${void 0===r?"remove":n.isArrayInsertion?"insert":"modify"} Array index ${t} as length is not sufficient`)}throw new Error(`Can not add ${"number"!=typeof a?"index":"property"} to parent of type ${s.type}`)}if(void 0===r)throw new Error("Can not delete in empty document");return withFormatting(e,{offset:o?o.offset:0,length:o?o.length:0,content:JSON.stringify(r)},n)}function withFormatting(e,t,r){if(!r.formattingOptions)return[t];let n=applyEdit(e,t),i=t.offset,o=t.offset+t.content.length;if(0===t.length||0===t.content.length){for(;i>0&&!isEOL(n,i-1);)i--;for(;o<n.length&&!isEOL(n,o);)o++}const s=format$6(n,{offset:i,length:o-i},{...r.formattingOptions,keepLines:!1});for(let e=s.length-1;e>=0;e--){const t=s[e];n=applyEdit(n,t),i=Math.min(i,t.offset),o=Math.max(o,t.offset+t.length),o+=t.content.length-t.length}return[{offset:i,length:e.length-(n.length-o)-i,content:n.substring(i,o)}]}function applyEdit(e,t){return e.substring(0,t.offset)+t.content+e.substring(t.offset+t.length)}!function(e){e.DEFAULT={allowTrailingComma:!1}}(ParseOptions||(ParseOptions={})),function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"}(ScanError||(ScanError={})),function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"}(SyntaxKind||(SyntaxKind={}));const parse$e=parse$f,parseTree=parseTree$1,findNodeAtLocation=findNodeAtLocation$1;var ParseErrorCode;function printParseErrorCode(e){switch(e){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}function modify(e,t,r,n){return setProperty(e,t,r,n)}function applyEdits(e,t){let r=t.slice(0).sort(((e,t)=>{const r=e.offset-t.offset;return 0===r?e.length-t.length:r})),n=e.length;for(let t=r.length-1;t>=0;t--){let i=r[t];if(!(i.offset+i.length<=n))throw new Error("Overlapping edit");e=applyEdit(e,i),n=i.offset}return e}!function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"}(ParseErrorCode||(ParseErrorCode={}));const FIELD_ALIASES={transportType:["type","transport","transport_type","transport-type"],command:["cmd","bin","exec","executable","program"],args:["arguments","params","parameters","argv","commandArgs"],cwd:["workdir","workingDir","workingDirectory","dir"],env:["environment","envs"],headers:["httpHeaders"],url:["endpoint"],timeout:["timeoutSeconds"]},normalizeAliasKey=e=>e.toLowerCase().replace(/[_-]/g,""),ALIAS_LOOKUP={};for(const[Sn,Qn]of Object.entries(FIELD_ALIASES))for(const _n of[Sn,...Qn]){const Dn=normalizeAliasKey(_n);Dn in ALIAS_LOOKUP||(ALIAS_LOOKUP[Dn]=Sn)}function normalizeTransportType(e){if("string"!=typeof e)throw new Error("Transport type must be a string");const t=e.trim().toLowerCase().replace(/-/g,"");if("streamablehttp"===t||"http"===t)return"streamableHttp";if("sse"===t)return"sse";if("stdio"===t)return"stdio";throw new Error(`Unsupported transport type: ${e}. Supported types are: stdio, sse, streamableHttp`)}function normalizeBoolean(e){if("boolean"==typeof e)return e;if("string"==typeof e){const t=e.toLowerCase().trim();if("true"===t)return!0;if("false"===t)return!1}throw new Error(`Invalid boolean value: ${e}. Use true, false, "true", or "false"`)}function normalizeNumber(e){if("number"==typeof e)return e;if("string"==typeof e){const t=parseFloat(e.trim());if(!isNaN(t)&&isFinite(t))return t}throw new Error(`Invalid number value: ${e}. Use a number or numeric string`)}function normalizeString(e){if("string"==typeof e)return e.trim();throw new Error(`Invalid string value: ${e}. Use a string`)}function normalizeArray(e){return(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.trim():e))}function normalizeObject(e){if("object"==typeof e&&null!==e&&!Array.isArray(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}throw new Error(`Invalid object value: ${e}. Use an object or JSON string`)}const NORMALIZATION_RULES={transportType:normalizeTransportType,disabled:normalizeBoolean,timeout:normalizeNumber,args:normalizeArray,command:normalizeString,cwd:normalizeString,url:normalizeString,env:normalizeObject,headers:normalizeObject};function normalizeConfigValues(e){const t={...e};for(const[e,r]of Object.entries(NORMALIZATION_RULES))if(e in t)try{t[e]=r(t[e])}catch(t){throw new Error(`Failed to normalize field '${e}': ${t.message}`)}return t}function normalizeFields(e){const t={};for(const[r,n]of Object.entries(e)){const e="string"==typeof r?ALIAS_LOOKUP[normalizeAliasKey(r)]:void 0;e?e in t&&r!==e||(t[e]=n):t[r]=n}return void 0!==t.url&&(t.headers={...t.requestInit?.headers,...t.headers}),normalizeConfigValues(t)}function validateBasicConfig(e,t){if(!e)throw new Error("Server name cannot be empty");const r=void 0!==t.url,n=void 0!==t.command;if(!r&&!n)throw new Error(`Server ${e} must have either url or command`);if(r&&n)throw new Error(`Server ${e} cannot have both url and command`)}function validateTransportType(e,t,r){if("stdio"===r&&!t.command)throw new Error(`Server ${e} with transportType 'stdio' must have command`);if(("sse"===r||"streamableHttp"===r)&&!t.url)throw new Error(`Server ${e} with transportType '${r}' must have url`)}const DEFAULT_MCP_TIMEOUT_SECONDS=30;function fillStdioDefaults(e){return{timeout:DEFAULT_MCP_TIMEOUT_SECONDS,disabled:!1,args:[],env:{},cwd:homedir(),...e,transportType:"stdio"}}function fillSseDefaults(e){const{headers:t,...r}=e;return{timeout:DEFAULT_MCP_TIMEOUT_SECONDS,disabled:!1,...r,transportType:"sse",requestInit:{...e.requestInit,headers:t||e.requestInit?.headers||{}}}}function fillStreamableHttpDefaults(e){const{headers:t,...r}=e;return{timeout:DEFAULT_MCP_TIMEOUT_SECONDS,disabled:!1,...r,transportType:"streamableHttp",requestInit:{...e.requestInit,headers:t||e.requestInit?.headers||{}}}}function fillDefaults(e,t){if("stdio"===t)return fillStdioDefaults(e);if("sse"===t)return fillSseDefaults(e);if("streamableHttp"===t)return fillStreamableHttpDefaults(e);throw new Error(`Unsupported transport type: ${t}`)}const ENV_VARIABLES={USERNAME:()=>kernel.config.username,WORKSPACE:()=>{const e=kernel.env.workspaceInfo.rootUri;return fileURLToPath$1(e)}};function replaceEnvVariable(e){return"string"!=typeof e?e:e.replace(/\$COMATE\.ENV\.([A-Z_]+)/g,((e,t)=>{const r=ENV_VARIABLES[t];return r?r():`$COMATE.ENV.${t}`}))}function resolveHttpEnvVariables(e){const t=e.requestInit?.headers||{},r={};for(const[e,n]of Object.entries(t))r[e]="string"==typeof n?replaceEnvVariable(n):n;return{...e,requestInit:{...e.requestInit,headers:r}}}function resolveStdioEnvVariables(e){const t=replaceEnvVariable(e.command),r=e.args.map((e=>replaceEnvVariable(e))),n=Object.fromEntries(Object.entries(e.env).map((([e,t])=>[e,replaceEnvVariable(t)])));return{...e,command:t,args:r,env:n,cwd:replaceEnvVariable(e.cwd)}}function resolveEnvVariables(e,t){if("stdio"===t)return resolveStdioEnvVariables(e);return"sse"===t||"streamableHttp"===t?resolveHttpEnvVariables(e):e}function resolveStdioPathVariables(e){const t=e=>{if(!e)return e;const t=expandTilde(e);return e.startsWith("~")?path__default.normalize(t):t};return{...e,command:t(e.command),args:e.args.map(t),cwd:t(e.cwd)}}function resolvePathVariables(e,t){return"stdio"===t?resolveStdioPathVariables(e):e}const{isPlainObject:isPlainObject$2}=_$H;function assertServersObject(e,t){if(!isPlainObject$2(e))throw new Error(t);return e}function extractRawSettings(e,t){if("mcpServers"in e)return assertServersObject(e.mcpServers,'"mcpServers" 字段应为对象');if("servers"in e)return t?.warn('检测到 "servers" 字段,已兼容处理为 "mcpServers"。请更新为正式字段以获得完整支持。'),assertServersObject(e.servers,'"servers" 字段应为对象');throw new Error('缺少 "mcpServers" 字段')}function inferTransportType(e){if(e.transportType)return e.transportType;if(void 0!==e.url){const t=e.url.toLowerCase();return t.endsWith("/sse")?"sse":(t.endsWith("/mcp"),"streamableHttp")}if(void 0!==e.command)return"stdio";throw new Error("Cannot infer transport type from config")}function processServerConfig(e,t){const r=normalizeFields(t);validateBasicConfig(e,r);const n=inferTransportType(r);validateTransportType(e,r,n);const i=resolvePathVariables(resolveEnvVariables(fillDefaults(r,n),n),n);return deepDropNilValue(i)}function deriveParsedSettings(e,t){const r={};for(const[n,i]of Object.entries(e))r[n]={...processServerConfig(n,i),source:t};return r}function parseMcpSettingsRoot(e,t,r){if(!isPlainObject$2(e))throw new Error("MCP 设置文件的根节点必须是对象");const n=extractRawSettings(e,r);return{raw:n,parsed:deriveParsedSettings(n,t)}}function parseMcpSettingsDocument(e,t,r){const n=[],i=parse$e(e,n,{allowTrailingComma:!0,disallowComments:!1});if(n.length>0){const[{error:t,offset:r=0}]=n,{line:i,column:o}=offsetToLineColumn(e,r),s=`${printParseErrorCode(t)} (行 ${i+1}, 列 ${o+1})`;throw new Error(s)}return parseMcpSettingsRoot(i,t,r)}const{isEmpty:isEmpty}=_$H;class McpSettingsFileStore extends TypedEventEmitter{filePath;source;mcpLogger;watcher;snapshot={raw:{},parsed:{}};status="uninitialized";constructor(e,t,r){super(),this.filePath=e,this.source=t,this.mcpLogger=r,this.watchMcpSettingsFile()}async getSnapshot(){return await this.ensureSnapshotLoaded(),{...this.snapshot}}async dispose(){await(this.watcher?.close()),this.watcher=void 0,this.snapshot={raw:{},parsed:{}},this.status="uninitialized"}getSettingsFilePath(){return this.filePath}getSource(){return this.source}getStatus(){return this.status}async ensureSnapshotLoaded(){if("uninitialized"!==this.status)return;if(!await isFileAccessable(this.filePath))return void this.transitionToMissing();const e=await kernel.fs.readFile(this.filePath,"utf-8"),t=this.syncStateFromContent(e);if("parse_error"===t.state)throw t.error}syncStateFromContent(e,t){const r={...this.snapshot};if(!e.trim())return this.transitionToMissing(),{state:"missing",previousSnapshot:r};try{const t=parseMcpSettingsDocument(e,this.source,this.mcpLogger),n=!equal$6(t.parsed,r.parsed);return this.transitionToParsed(t),{state:"parsed",snapshot:t,previousSnapshot:r,changed:n}}catch(e){if(!t||"manual"===t.type){const r=t?`手动操作(${t.operation})`:"初始加载";this.mcpLogger.error("MCP 设置解析失败",r,e.message)}return this.transitionToParseError(),{state:"parse_error",previousSnapshot:r,error:e}}}transitionToMissing(){this.snapshot={raw:{},parsed:{}},this.status="missing"}transitionToParsed(e){this.snapshot={raw:e.raw,parsed:e.parsed},this.status="parsed"}transitionToParseError(){this.status="parse_error"}emitSyncResult(e,t){if(this.logSyncOutcome(e,t),"missing"!==e.state)"parsed"!==e.state?this.emit("parseError",{snapshot:this.snapshot,previousSnapshot:e.previousSnapshot,error:e.error,source:t}):this.emit("parsed",{snapshot:this.snapshot,previousSnapshot:e.previousSnapshot,changed:e.changed,source:t});else{const r=!isEmpty(e.previousSnapshot.parsed);this.emit("missing",{snapshot:this.snapshot,previousSnapshot:e.previousSnapshot,hadConfigs:r,source:t})}}async fileContentChangeHandler(e){const t=await kernel.fs.readFile(this.filePath,"utf-8"),r={type:"fs",event:e},n=this.syncStateFromContent(t,r);this.emitSyncResult(n,r)}watchMcpSettingsFile(){try{const e="global"===this.source?this.filePath:path__default.dirname(this.filePath);this.watcher=chokidar.watch(e,{persistent:!0,ignoreInitial:!0}),this.watcher.on("add",(async t=>{t===this.filePath&&(this.mcpLogger.info(`文件添加事件:监视对象 ${e},变动对象 ${t}`),await this.fileContentChangeHandler("add"))})).on("change",(async t=>{t===this.filePath&&(this.mcpLogger.info(`文件改动事件:监视对象 ${e},变动对象 ${t}`),await this.fileContentChangeHandler("change"))})).on("unlink",(t=>{if(t===this.filePath){this.mcpLogger.info(`文件删除事件:监视对象 ${e},变动对象 ${t}`);const r={...this.snapshot},n=!isEmpty(r.parsed);this.transitionToMissing(),this.emit("missing",{snapshot:this.snapshot,previousSnapshot:r,hadConfigs:n,source:{type:"fs",event:"unlink"}})}})).on("unlinkDir",(t=>{this.mcpLogger.info(`文件夹删除事件:监视对象 ${e},变动对象 ${t}`),"global"!==this.source&&e===t&&this.watcher?.add(e)}))}catch(e){this.mcpLogger.error("获取 MCP 设置文件失败",e.message)}}logSyncOutcome(e,t){const r="manual"===t.type?`手动操作(${t.operation})`:`文件事件(${t.event})`;if("missing"!==e.state)if("parsed"!==e.state)this.mcpLogger.error("MCP 设置状态 -> parse_error",r,`path=${this.filePath}`,e.error.message);else{const t=e.changed?"changed":"unchanged";this.mcpLogger.info("MCP 设置状态 -> parsed",r,`status=${t}`,`path=${this.filePath}`)}else this.mcpLogger.info("MCP 设置状态 -> missing",r,`path=${this.filePath}`)}}const DEFAULT_SETTINGS_JSON={mcpServers:{}},JSONC_FORMAT_OPTIONS={insertSpaces:!0,tabSize:4};function ensureContentHasRoot(e){const t=e.trim()?e:JSON.stringify(DEFAULT_SETTINGS_JSON,null,4),r=[],n=parse$e(t,r,{allowTrailingComma:!0,disallowComments:!1});if(!r.length&&n&&"object"==typeof n&&void 0!==n.mcpServers)return t;return applyEdits(t,modify(t,["mcpServers"],{},{formattingOptions:JSONC_FORMAT_OPTIONS}))}function updateJsoncContent(e,t,r,n){let i=ensureContentHasRoot(e);if("delete"!==r&&!n)throw new Error("更新/新增配置不能为空");if("delete"===r){return applyEdits(i,modify(i,["mcpServers",t],void 0,{formattingOptions:JSONC_FORMAT_OPTIONS,isArrayInsertion:!1}))}const o=modify(i,["mcpServers",t],n,{formattingOptions:JSONC_FORMAT_OPTIONS,getInsertionIndex:e=>"add"===r?0:e.length});return i=applyEdits(i,o),i}class McpSettingsFileEditor{store;virtualEditor;mcpLogger;constructor(e,t,r){this.store=e,this.virtualEditor=t,this.mcpLogger=r}async ensureFileExists(){const e=this.store.getSettingsFilePath();if(!await isFileAccessable(e)){const t=path__default.dirname(e);await kernel.fs.mkdir(t,{recursive:!0}),await kernel.fs.writeFile(e,JSON.stringify(DEFAULT_SETTINGS_JSON,null,4)),this.mcpLogger.info(`创建配置文件 path=${e}`)}}async updateServer(e,t,r){if(await this.ensureFileExists(),await this.store.ensureSnapshotLoaded(),"parse_error"===this.store.getStatus())throw new Error("配置文件存在语法错误,请先修复");const n=await this.store.getSnapshot(),i=this.applyMutation(n.raw,e,t,r),o=await this.saveSettings(i,e,t);return this.getLineNumbers(t,e,o)}async fetchServer(e){await this.ensureFileExists();const t=await this.store.getSnapshot();if(!e||!t.raw[e])return{startLine:0,endLine:0};const r=await this.readSettingsContent();return this.getLineNumbers("update",e,r)}applyMutation(e,t,r,n){if("add"===r){if(!n)throw new Error("新增配置不能为空");const{[t]:r,...i}=e;return{[t]:n,...i}}if("delete"===r){const{[t]:r,...n}=e;return n}if("update"===r){if(!e[t])throw new Error(`Server ${t} 不存在`);return{...e,[t]:{...e[t],...n??{}}}}return e}async saveSettings(e,t,r){const n=this.store.getSettingsFilePath(),i=updateJsoncContent(await this.readSettingsContent(),t,r,"delete"===r?void 0:e[t]);return await this.virtualEditor.saveDocumentWithReplaceContentAndOpen({absolutePath:n,content:i}),await this.virtualEditor.openDocument({absolutePath:n}),i}async readSettingsContent(){try{return await kernel.fs.readFile(this.store.getSettingsFilePath(),"utf-8")}catch{return JSON.stringify(DEFAULT_SETTINGS_JSON,null,4)}}getLineNumbers(e,t,r){if("delete"===e)return{startLine:0,endLine:0};const n=[],i=parseTree(r,n,{allowTrailingComma:!0,disallowComments:!1});if(!i||n.length)return{startLine:0,endLine:0};const o=findNodeAtLocation(i,["mcpServers"]),s=o?.children?.find((e=>e.children?.[0].value===t)),a=s?.children?.[0],c=s?.children?.[1];if(!a||!c)return{startLine:0,endLine:0};return{startLine:offsetToLine(r,a.offset),endLine:offsetToLine(r,c.offset+c.length)}}}class McpSettingsAggregator extends TypedEventEmitter{mcpLogger;stores;editors;constructor(e,t,r){super(),this.mcpLogger=t;const n=getGlobalSettingsPath(),i=getProjectSettingsPath(e),o=getLocalSettingsPath(e);t.info("初始化 MCP 配置聚合器:\n",`global=${n}\n`,`project=${i}\n`,`local=${o}`);const s=new McpSettingsFileStore(n,"global",t),a=new McpSettingsFileStore(i,"project",t),c=new McpSettingsFileStore(o,"local",t);this.stores=new Map([["global",s],["project",a],["local",c]]),this.editors=new Map([["global",new McpSettingsFileEditor(s,r,t)],["project",new McpSettingsFileEditor(a,r,t)],["local",new McpSettingsFileEditor(c,r,t)]]),this.registerStoreListeners()}getStore(e){return this.stores.get(e)}getEditor(e){return this.editors.get(e)}async getMergedSnapshot(e=!1){const t=await Promise.all(["global","project","local"].map((e=>this.stores.get(e))).filter((e=>!!e)).map((e=>e.getSnapshot())));return this.mergeSnapshots(t,e)}async getLayeredSettings(e=!1){const[t,r,n]=await Promise.all([this.stores.get("global")?.getSnapshot()??{raw:{},parsed:{}},this.stores.get("project")?.getSnapshot()??{raw:{},parsed:{}},this.stores.get("local")?.getSnapshot()??{raw:{},parsed:{}}]);if(e){const e={global:Object.keys(t.parsed).length,project:Object.keys(r.parsed).length,local:Object.keys(n.parsed).length};this.mcpLogger.info(`MCP 分层配置获取完成: global=${e.global}, project=${e.project}, local=${e.local}`)}return{global:t,project:r,local:n}}async dispose(){this.mcpLogger.info("销毁 MCP 配置聚合器");for(const e of this.stores.values())e.removeAllListeners(),await e.dispose();this.stores.clear(),this.editors.clear()}registerStoreListeners(){for(const e of this.stores.values())e.on("parsed",(()=>{this.handleStoreChange()})),e.on("missing",(()=>{this.handleStoreChange()})),e.on("parseError",(({error:t})=>{this.emit("parseError",{error:t,source:e.getSource()})}))}async handleStoreChange(){const e=await this.getMergedSnapshot(!0);this.emit("changed",e)}mergeSnapshots(e,t=!1){const r={},n={},i=new Map,o=new Map;for(const t of e){for(const[e,r]of Object.entries(t.parsed)){const t=i.get(e);if(t){const n=o.get(e)||[t];n.push(r.source),o.set(e,n)}i.set(e,r.source)}Object.assign(r,t.raw),Object.assign(n,t.parsed)}if(t&&o.size>0){const e=Array.from(o.entries()).map((([e,t])=>`${e}(${t.join("→")})`)).join(", ");this.mcpLogger.info(`MCP 配置合并完成,共 ${i.size} 个服务器`,`配置覆盖: ${e}`)}return{raw:r,parsed:n}}}class McpSettingsWatcher{mcpLogger;eventGateway;aggregator;normalizedChangeHandlers=new Set;lastMergedSnapshot;debouncedEmitChange;constructor(e,t,r){this.mcpLogger=e,this.eventGateway=r;const n=kernel.env.workspaceInfo.rootPath;if(!n)throw new Error("未打开工作区,请打开工作区");this.aggregator=new McpSettingsAggregator(n,e,t),this.debouncedEmitChange=_$H.debounce((()=>{this.emitAggregatedChange()}),100),this.aggregator.on("changed",(e=>{this.lastMergedSnapshot=e,this.debouncedEmitChange()})),this.aggregator.on("parseError",(({error:e,source:t})=>{this.debouncedEmitChange.cancel(),this.lastMergedSnapshot=void 0,this.mcpLogger.error(`MCP 配置文件解析失败 (${t})`,e.message),this.eventGateway.notifyConfigUpdated({error:`${t} 配置文件解析失败: ${e.message}`})})),this.registerGatewayHandlers()}onParsedSettingsChange(e){return this.normalizedChangeHandlers.add(e),()=>{this.normalizedChangeHandlers.delete(e)}}async getMergedSnapshot(){return this.aggregator.getMergedSnapshot()}async getLayeredSnapshot(){return this.aggregator.getLayeredSettings()}async dispose(){this.eventGateway.unregisterRequestHandler(PT_WEBVIEW_MCP_CONFIG_CREATE_REQUEST),this.eventGateway.unregisterRequestHandler(PT_WEBVIEW_MCP_CONFIG_FETCH_REQUEST),this.eventGateway.unregisterRequestHandler(PT_WEBVIEW_MCP_CONFIG_UPDATE_REQUEST),await this.aggregator.dispose(),this.normalizedChangeHandlers.clear(),this.debouncedEmitChange.cancel()}registerGatewayHandlers(){this.eventGateway.registerRequestHandler(PT_WEBVIEW_MCP_CONFIG_CREATE_REQUEST,(e=>this.createMcpServerConfig(e))),this.eventGateway.registerRequestHandler(PT_WEBVIEW_MCP_CONFIG_FETCH_REQUEST,(e=>this.fetchMcpServerConfig(e))),this.eventGateway.registerRequestHandler(PT_WEBVIEW_MCP_CONFIG_UPDATE_REQUEST,(e=>this.updateServerSettings(e)))}async createMcpServerConfig(e){const t=this.aggregator.getEditor(e);if(!t)throw new Error(`无法获取 ${e} 层级的编辑器`);await t.ensureFileExists();const r=this.aggregator.getStore(e);if(!r)throw new Error(`无法获取 ${e} 层级的配置存储`);return r.getSettingsFilePath()}async updateServerSettings(e){const{serverName:t,type:r,source:n}=e,i="config"in e?e.config:void 0,o=this.aggregator.getEditor(n);if(!o)throw new Error(`无法获取 ${n} 层级的编辑器`);const s=this.aggregator.getStore(n);if(!s)throw new Error(`无法获取 ${n} 层级的配置存储`);this.mcpLogger.info(`手动 ${r} MCP Server ${t} target=${n}`);const{startLine:a,endLine:c}=await o.updateServer(t,r,i),A=await this.aggregator.getMergedSnapshot();return{filePath:s.getSettingsFilePath(),startLine:a,endLine:c,snapshot:A,config:A.parsed}}async fetchMcpServerConfig(e){const t=await this.aggregator.getMergedSnapshot(),{name:r,source:n}=e,i=this.aggregator.getStore(n);if(!i)throw new Error(`无法获取 ${n} 层级的配置存储`);if(!r||!t.raw[r])return{filePath:i.getSettingsFilePath(),startLine:0,endLine:0,snapshot:t,config:t.parsed};const o=this.aggregator.getEditor(n);if(!o)throw new Error(`无法获取 ${n} 层级的编辑器`);const{startLine:s,endLine:a}=await o.fetchServer(r);return{filePath:i.getSettingsFilePath(),startLine:s,endLine:a,snapshot:t,config:t.parsed}}async emitAggregatedChange(){const e=this.lastMergedSnapshot;if(!e)return;const t=await this.aggregator.getLayeredSettings(!0);await this.eventGateway.notifyConfigUpdated({layered:t});for(const t of this.normalizedChangeHandlers)try{t(e)}catch(e){this.mcpLogger.error("执行 MCP 配置变更回调失败",e.message)}}}const getCurrentTime=()=>dayjs$1().format("YYYY-MM-DD HH:mm:ss.SSS"),getLogFileName=()=>`mcp-${dayjs$1().format("YYYY-MM-DD")}.log`;class McpLogger{static createdOutputChannelKeys=new Set;logFolder="";currentLogFile="";currentDate="";stream=null;serverName;constructor(e){this.serverName=e,this.init()}get normalizedAbsolutedPath(){return isJetbrains?formatWin32PathSep(this.currentLogFile):this.currentLogFile}init(){if(this.logFolder=path__default.join(homedir(),".comate-engine","mcp-log"),fs__default$1.mkdirSync(this.logFolder,{recursive:!0}),this.currentDate=dayjs$1().format("YYYY-MM-DD"),this.currentLogFile=path__default.join(this.logFolder,getLogFileName()),isVscode){const e=this.getOutputChannelKey();McpLogger.createdOutputChannelKeys.has(e)||(McpLogger.createdOutputChannelKeys.add(e),kernel.connect.sendNotification(KERNEL_MCP_OUTPUT_CHANNEL_CREATE,{serverName:this.serverName}))}this.cleanOldLogs()}log(e,t){const r=this.serverName?`[${this.serverName}] `:"",n=t.map((e=>{if(e instanceof Error)return`${e.message}\n${e.stack||""}`;if("object"==typeof e&&null!==e)try{return JSON.stringify(e,null,2)}catch{return String(e)}return String(e)})),i=`[${getCurrentTime()}] [${e}] ${r}${n.join(" ")}`;isVscode&&kernel.connect.sendNotification(KERNEL_MCP_OUTPUT_CHANNEL_MESSAGE,{serverName:this.serverName,message:i});try{this.ensureStream()&&this.stream?.writable&&this.stream.write(i+"\n")}catch(e){kernel.logger.error("MCP 日志写入文件失败:",e)}}info(...e){this.log("INFO",e)}warn(...e){this.log("WARN",e)}error(...e){this.log("ERROR",e)}dispose(){this.stream&&this.stream.end()}async cleanOldLogs(e=3){try{const t=await fs__default$1.promises.readdir(this.logFolder),r=dayjs$1();for(const n of t)n.startsWith("mcp-")&&n.endsWith(".log")&&await this.cleanSingleLogFile(n,r,e)}catch{this.warn("日志清理失败")}}async cleanSingleLogFile(e,t,r){const n=path__default.join(this.logFolder,e);try{const i=await fs__default$1.promises.stat(n);t.diff(dayjs$1(i.mtime),"day")>r&&(await fs__default$1.promises.unlink(n),this.info(`已清理旧日志文件: ${e}`))}catch{}}getCurrentLogFilePath(){const e=dayjs$1().format("YYYY-MM-DD");return this.currentDate!==e&&(this.currentDate=e,this.currentLogFile=path__default.join(this.logFolder,getLogFileName()),this.stream&&(this.stream.end(),this.stream=null)),this.currentLogFile}ensureStream(){try{if(!this.stream||!this.stream.writable){const e=this.getCurrentLogFilePath();this.stream=fs__default$1.createWriteStream(e,{flags:"a"})}return!0}catch(e){return kernel.logger.error("MCP 日志流创建失败:",e),!1}}getOutputChannelKey(){return this.serverName??"__global__"}}class ConcurrentPool{maxConcurrent;running;pending;queue;completionListeners=[];constructor(e=5){this.maxConcurrent=e,this.queue=[],this.running=0,this.pending=0}add(e){return this.pending++,new Promise(((t,r)=>{this.queue.push((()=>Promise.resolve(e()).then(t).catch(r).finally((()=>{this.running--,this.pending--,this.next(),this.checkAllTasksDone()})))),this.next()}))}next(){for(;this.running<this.maxConcurrent&&this.queue.length>0;){const e=this.queue.shift();this.running++,e()}}checkAllTasksDone(){0===this.pending&&(this.completionListeners.forEach((e=>e())),this.completionListeners=[])}allTasksDone(){return new Promise((e=>{0===this.pending?e():this.completionListeners.push(e)}))}}const DEFAULT_REQUEST_TIMEOUT_MSEC=6e4;class Protocol{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(CancelledNotificationSchema,(e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)})),this.setNotificationHandler(ProgressNotificationSchema,(e=>{this._onprogress(e)})),this.setRequestHandler(PingRequestSchema,(e=>({})))}_setupTimeout(e,t,r,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new McpError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,r,n;this._transport=e;const i=null===(t=this.transport)||void 0===t?void 0:t.onclose;this._transport.onclose=()=>{null==i||i(),this._onclose()};const o=null===(r=this.transport)||void 0===r?void 0:r.onerror;this._transport.onerror=e=>{null==o||o(e),this._onerror(e)};const s=null===(n=this._transport)||void 0===n?void 0:n.onmessage;this._transport.onmessage=(e,t)=>{null==s||s(e,t),isJSONRPCResponse(e)||isJSONRPCError(e)?this._onresponse(e):isJSONRPCRequest(e)?this._onrequest(e,t):isJSONRPCNotification(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new McpError(ErrorCode.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then((()=>r(e))).catch((e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`))))}_onrequest(e,t){var r,n;const i=null!==(r=this._requestHandlers.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler,o=this._transport;if(void 0===i)return void(null==o||o.send({jsonrpc:"2.0",id:e.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}}).catch((e=>this._onerror(new Error(`Failed to send an error response: ${e}`)))));const s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);const a={signal:s.signal,sessionId:null==o?void 0:o.sessionId,_meta:null===(n=e.params)||void 0===n?void 0:n._meta,sendNotification:t=>this.notification(t,{relatedRequestId:e.id}),sendRequest:(t,r,n)=>this.request(t,r,{...n,relatedRequestId:e.id}),authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo};Promise.resolve().then((()=>i(e,a))).then((t=>{if(!s.signal.aborted)return null==o?void 0:o.send({result:t,jsonrpc:"2.0",id:e.id})}),(t=>{var r;if(!s.signal.aborted)return null==o?void 0:o.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:ErrorCode.InternalError,message:null!==(r=t.message)&&void 0!==r?r:"Internal error"}})})).catch((e=>this._onerror(new Error(`Failed to send response: ${e}`)))).finally((()=>{this._requestHandlerAbortControllers.delete(e.id)}))}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),i=this._progressHandlers.get(n);if(!i)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(e){return void o(e)}i(r)}_onresponse(e){const t=Number(e.id),r=this._responseHandlers.get(t);if(void 0!==r)if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),isJSONRPCResponse(e))r(e);else{r(new McpError(e.error.code,e.error.message,e.error.data))}else this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){const{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}=null!=r?r:{};return new Promise(((s,a)=>{var c,A,l,u,d,h;if(!this._transport)return void a(new Error("Not connected"));!0===(null===(c=this._options)||void 0===c?void 0:c.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(A=null==r?void 0:r.signal)||void 0===A||A.throwIfAborted();const p=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:p};(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(p,r.onprogress),g.params={...e.params,_meta:{...(null===(l=e.params)||void 0===l?void 0:l._meta)||{},progressToken:p}});const f=e=>{var t;this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(e)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}).catch((e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)))),a(e)};this._responseHandlers.set(p,(e=>{var n;if(!(null===(n=null==r?void 0:r.signal)||void 0===n?void 0:n.aborted)){if(e instanceof Error)return a(e);try{const r=t.parse(e.result);s(r)}catch(e){a(e)}}})),null===(u=null==r?void 0:r.signal)||void 0===u||u.addEventListener("abort",(()=>{var e;f(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)}));const m=null!==(d=null==r?void 0:r.timeout)&&void 0!==d?d:DEFAULT_REQUEST_TIMEOUT_MSEC;this._setupTimeout(p,m,null==r?void 0:r.maxTotalTimeout,(()=>f(new McpError(ErrorCode.RequestTimeout,"Request timed out",{timeout:m}))),null!==(h=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==h&&h),this._transport.send(g,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}).catch((e=>{this._cleanupTimeout(p),a(e)}))}))}async notification(e,t){var r,n;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);if((null!==(n=null===(r=this._options)||void 0===r?void 0:r.debouncedNotificationMethods)&&void 0!==n?n:[]).includes(e.method)&&!e.params&&!(null==t?void 0:t.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then((()=>{var r;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const n={...e,jsonrpc:"2.0"};null===(r=this._transport)||void 0===r||r.send(n,t).catch((e=>this._onerror(e)))}))}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,((r,n)=>Promise.resolve(t(e.parse(r),n))))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,(r=>Promise.resolve(t(e.parse(r)))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function mergeCapabilities(e,t){return Object.entries(t).reduce(((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e)),{...e})}var uri_all={exports:{}};
|
|
537
537
|
/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */!function(e){function t(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length>1){t[0]=t[0].slice(0,-1);for(var n=t.length-1,i=1;i<n;++i)t[i]=t[i].slice(1,-1);return t[n]=t[n].slice(1),t.join("")}return t[0]}function r(e){return"(?:"+e+")"}function n(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function i(e){return e.toUpperCase()}function o(e){return null!=e?e instanceof Array?e:"number"!=typeof e.length||e.split||e.setInterval||e.call?[e]:Array.prototype.slice.call(e):[]}function s(e,t){var r=e;if(t)for(var n in t)r[n]=t[n];return r}function a(e){var n="[A-Za-z]",i="[0-9]",o=t(i,"[A-Fa-f]"),s=r(r("%[EFef]"+o+"%"+o+o+"%"+o+o)+"|"+r("%[89A-Fa-f]"+o+"%"+o+o)+"|"+r("%"+o+o)),a="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",c=t("[\\:\\/\\?\\#\\[\\]\\@]",a),A=e?"[\\uE000-\\uF8FF]":"[]",l=t(n,i,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]");r(n+t(n,i,"[\\+\\-\\.]")+"*"),r(r(s+"|"+t(l,a,"[\\:]"))+"*");var u=r(r("25[0-5]")+"|"+r("2[0-4]"+i)+"|"+r("1"+i+i)+"|"+r("0?[1-9]"+i)+"|0?0?"+i),d=r(u+"\\."+u+"\\."+u+"\\."+u),h=r(o+"{1,4}"),p=r(r(h+"\\:"+h)+"|"+d),g=r(r(h+"\\:")+"{6}"+p),f=r("\\:\\:"+r(h+"\\:")+"{5}"+p),m=r(r(h)+"?\\:\\:"+r(h+"\\:")+"{4}"+p),E=r(r(r(h+"\\:")+"{0,1}"+h)+"?\\:\\:"+r(h+"\\:")+"{3}"+p),C=r(r(r(h+"\\:")+"{0,2}"+h)+"?\\:\\:"+r(h+"\\:")+"{2}"+p),I=r(r(r(h+"\\:")+"{0,3}"+h)+"?\\:\\:"+h+"\\:"+p),y=r(r(r(h+"\\:")+"{0,4}"+h)+"?\\:\\:"+p),B=r(r(r(h+"\\:")+"{0,5}"+h)+"?\\:\\:"+h),b=r(r(r(h+"\\:")+"{0,6}"+h)+"?\\:\\:"),w=r([g,f,m,E,C,I,y,B,b].join("|")),v=r(r(l+"|"+s)+"+");r("[vV]"+o+"+\\."+t(l,a,"[\\:]")+"+"),r(r(s+"|"+t(l,a))+"*");var S=r(s+"|"+t(l,a,"[\\:\\@]"));return r(r(s+"|"+t(l,a,"[\\@]"))+"+"),r(r(S+"|"+t("[\\/\\?]",A))+"*"),{NOT_SCHEME:new RegExp(t("[^]",n,i,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",l,a),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",l,a),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",l,a),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",l,a),"g"),NOT_QUERY:new RegExp(t("[^\\%]",l,a,"[\\:\\@\\/\\?]",A),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",l,a,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",l,a),"g"),UNRESERVED:new RegExp(l,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",l,c),"g"),PCT_ENCODED:new RegExp(s,"g"),IPV4ADDRESS:new RegExp("^("+d+")$"),IPV6ADDRESS:new RegExp("^\\[?("+w+")"+r(r("\\%25|\\%(?!"+o+"{2})")+"("+v+")")+"?\\]?$")}}var c=a(!1),A=a(!0),l=function(){function e(e,t){var r=[],n=!0,i=!1,o=void 0;try{for(var s,a=e[Symbol.iterator]();!(n=(s=a.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(e){i=!0,o=e}finally{try{!n&&a.return&&a.return()}finally{if(i)throw o}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),u=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)},d=2147483647,h=36,p=1,g=26,f=38,m=700,E=72,C=128,I="-",y=/^xn--/,B=/[^\0-\x7E]/,b=/[\x2E\u3002\uFF0E\uFF61]/g,w={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},v=h-p,S=Math.floor,Q=String.fromCharCode;function _(e){throw new RangeError(w[e])}function D(e,t){for(var r=[],n=e.length;n--;)r[n]=t(e[n]);return r}function x(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+D((e=e.replace(b,".")).split("."),t).join(".")}function k(e){for(var t=[],r=0,n=e.length;r<n;){var i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<n){var o=e.charCodeAt(r++);56320==(64512&o)?t.push(((1023&i)<<10)+(1023&o)+65536):(t.push(i),r--)}else t.push(i)}return t}var R=function(e){return String.fromCodePoint.apply(String,u(e))},T=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:h},$=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},N=function(e,t,r){var n=0;for(e=r?S(e/m):e>>1,e+=S(e/t);e>v*g>>1;n+=h)e=S(e/v);return S(n+(v+1)*e/(e+f))},F=function(e){var t=[],r=e.length,n=0,i=C,o=E,s=e.lastIndexOf(I);s<0&&(s=0);for(var a=0;a<s;++a)e.charCodeAt(a)>=128&&_("not-basic"),t.push(e.charCodeAt(a));for(var c=s>0?s+1:0;c<r;){for(var A=n,l=1,u=h;;u+=h){c>=r&&_("invalid-input");var f=T(e.charCodeAt(c++));(f>=h||f>S((d-n)/l))&&_("overflow"),n+=f*l;var m=u<=o?p:u>=o+g?g:u-o;if(f<m)break;var y=h-m;l>S(d/y)&&_("overflow"),l*=y}var B=t.length+1;o=N(n-A,B,0==A),S(n/B)>d-i&&_("overflow"),i+=S(n/B),n%=B,t.splice(n++,0,i)}return String.fromCodePoint.apply(String,t)},M=function(e){var t=[],r=(e=k(e)).length,n=C,i=0,o=E,s=!0,a=!1,c=void 0;try{for(var A,l=e[Symbol.iterator]();!(s=(A=l.next()).done);s=!0){var u=A.value;u<128&&t.push(Q(u))}}catch(e){a=!0,c=e}finally{try{!s&&l.return&&l.return()}finally{if(a)throw c}}var f=t.length,m=f;for(f&&t.push(I);m<r;){var y=d,B=!0,b=!1,w=void 0;try{for(var v,D=e[Symbol.iterator]();!(B=(v=D.next()).done);B=!0){var x=v.value;x>=n&&x<y&&(y=x)}}catch(e){b=!0,w=e}finally{try{!B&&D.return&&D.return()}finally{if(b)throw w}}var R=m+1;y-n>S((d-i)/R)&&_("overflow"),i+=(y-n)*R,n=y;var T=!0,F=!1,M=void 0;try{for(var P,L=e[Symbol.iterator]();!(T=(P=L.next()).done);T=!0){var O=P.value;if(O<n&&++i>d&&_("overflow"),O==n){for(var U=i,G=h;;G+=h){var H=G<=o?p:G>=o+g?g:G-o;if(U<H)break;var j=U-H,q=h-H;t.push(Q($(H+j%q,0))),U=S(j/q)}t.push(Q($(U,0))),o=N(i,R,m==f),i=0,++m}}}catch(e){F=!0,M=e}finally{try{!T&&L.return&&L.return()}finally{if(F)throw M}}++i,++n}return t.join("")},P=function(e){return x(e,(function(e){return y.test(e)?F(e.slice(4).toLowerCase()):e}))},L=function(e){return x(e,(function(e){return B.test(e)?"xn--"+M(e):e}))},O={version:"2.1.0",ucs2:{decode:k,encode:R},decode:F,encode:M,toASCII:L,toUnicode:P},U={};function G(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function H(e){for(var t="",r=0,n=e.length;r<n;){var i=parseInt(e.substr(r+1,2),16);if(i<128)t+=String.fromCharCode(i),r+=3;else if(i>=194&&i<224){if(n-r>=6){var o=parseInt(e.substr(r+4,2),16);t+=String.fromCharCode((31&i)<<6|63&o)}else t+=e.substr(r,6);r+=6}else if(i>=224){if(n-r>=9){var s=parseInt(e.substr(r+4,2),16),a=parseInt(e.substr(r+7,2),16);t+=String.fromCharCode((15&i)<<12|(63&s)<<6|63&a)}else t+=e.substr(r,9);r+=9}else t+=e.substr(r,3),r+=3}return t}function j(e,t){function r(e){var r=H(e);return r.match(t.UNRESERVED)?r:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,r).replace(t.NOT_USERINFO,G).replace(t.PCT_ENCODED,i)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_HOST,G).replace(t.PCT_ENCODED,i)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,r).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,G).replace(t.PCT_ENCODED,i)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,r).replace(t.NOT_QUERY,G).replace(t.PCT_ENCODED,i)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,r).replace(t.NOT_FRAGMENT,G).replace(t.PCT_ENCODED,i)),e}function q(e){return e.replace(/^0*(.*)/,"$1")||"0"}function K(e,t){var r=e.match(t.IPV4ADDRESS)||[],n=l(r,2)[1];return n?n.split(".").map(q).join("."):e}function W(e,t){var r=e.match(t.IPV6ADDRESS)||[],n=l(r,3),i=n[1],o=n[2];if(i){for(var s=i.toLowerCase().split("::").reverse(),a=l(s,2),c=a[0],A=a[1],u=A?A.split(":").map(q):[],d=c.split(":").map(q),h=t.IPV4ADDRESS.test(d[d.length-1]),p=h?7:8,g=d.length-p,f=Array(p),m=0;m<p;++m)f[m]=u[m]||d[g+m]||"";h&&(f[p-1]=K(f[p-1],t));var E=f.reduce((function(e,t,r){if(!t||"0"===t){var n=e[e.length-1];n&&n.index+n.length===r?n.length++:e.push({index:r,length:1})}return e}),[]),C=E.sort((function(e,t){return t.length-e.length}))[0],I=void 0;if(C&&C.length>1){var y=f.slice(0,C.index),B=f.slice(C.index+C.length);I=y.join(":")+"::"+B.join(":")}else I=f.join(":");return o&&(I+="%"+o),I}return e}var J=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Y=void 0==="".match(/(){0}/)[1];function z(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={},n=!1!==t.iri?A:c;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var i=e.match(J);if(i){Y?(r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5])):(r.scheme=i[1]||void 0,r.userinfo=-1!==e.indexOf("@")?i[3]:void 0,r.host=-1!==e.indexOf("//")?i[4]:void 0,r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=-1!==e.indexOf("?")?i[7]:void 0,r.fragment=-1!==e.indexOf("#")?i[8]:void 0,isNaN(r.port)&&(r.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?i[4]:void 0)),r.host&&(r.host=W(K(r.host,n),n)),void 0!==r.scheme||void 0!==r.userinfo||void 0!==r.host||void 0!==r.port||r.path||void 0!==r.query?void 0===r.scheme?r.reference="relative":void 0===r.fragment?r.reference="absolute":r.reference="uri":r.reference="same-document",t.reference&&"suffix"!==t.reference&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");var o=U[(t.scheme||r.scheme||"").toLowerCase()];if(t.unicodeSupport||o&&o.unicodeSupport)j(r,n);else{if(r.host&&(t.domainHost||o&&o.domainHost))try{r.host=O.toASCII(r.host.replace(n.PCT_ENCODED,H).toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to ASCII via punycode: "+e}j(r,c)}o&&o.parse&&o.parse(r,t)}else r.error=r.error||"URI can not be parsed.";return r}function V(e,t){var r=!1!==t.iri?A:c,n=[];return void 0!==e.userinfo&&(n.push(e.userinfo),n.push("@")),void 0!==e.host&&n.push(W(K(String(e.host),r),r).replace(r.IPV6ADDRESS,(function(e,t,r){return"["+t+(r?"%25"+r:"")+"]"}))),"number"!=typeof e.port&&"string"!=typeof e.port||(n.push(":"),n.push(String(e.port))),n.length?n.join(""):void 0}var X=/^\.\.?\//,Z=/^\/\.(\/|$)/,ee=/^\/\.\.(\/|$)/,te=/^\/?(?:.|\n)*?(?=\/|$)/;function re(e){for(var t=[];e.length;)if(e.match(X))e=e.replace(X,"");else if(e.match(Z))e=e.replace(Z,"/");else if(e.match(ee))e=e.replace(ee,"/"),t.pop();else if("."===e||".."===e)e="";else{var r=e.match(te);if(!r)throw new Error("Unexpected dot segment condition");var n=r[0];e=e.slice(n.length),t.push(n)}return t.join("")}function ne(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.iri?A:c,n=[],i=U[(t.scheme||e.scheme||"").toLowerCase()];if(i&&i.serialize&&i.serialize(e,t),e.host)if(r.IPV6ADDRESS.test(e.host));else if(t.domainHost||i&&i.domainHost)try{e.host=t.iri?O.toUnicode(e.host):O.toASCII(e.host.replace(r.PCT_ENCODED,H).toLowerCase())}catch(r){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+r}j(e,r),"suffix"!==t.reference&&e.scheme&&(n.push(e.scheme),n.push(":"));var o=V(e,t);if(void 0!==o&&("suffix"!==t.reference&&n.push("//"),n.push(o),e.path&&"/"!==e.path.charAt(0)&&n.push("/")),void 0!==e.path){var s=e.path;t.absolutePath||i&&i.absolutePath||(s=re(s)),void 0===o&&(s=s.replace(/^\/\//,"/%2F")),n.push(s)}return void 0!==e.query&&(n.push("?"),n.push(e.query)),void 0!==e.fragment&&(n.push("#"),n.push(e.fragment)),n.join("")}function ie(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={};return arguments[3]||(e=z(ne(e,r),r),t=z(ne(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(n.scheme=t.scheme,n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=re(t.path||""),n.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=re(t.path||""),n.query=t.query):(t.path?("/"===t.path.charAt(0)?n.path=re(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?n.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:n.path=t.path:n.path="/"+t.path,n.path=re(n.path)),n.query=t.query):(n.path=e.path,void 0!==t.query?n.query=t.query:n.query=e.query),n.userinfo=e.userinfo,n.host=e.host,n.port=e.port),n.scheme=e.scheme),n.fragment=t.fragment,n}function oe(e,t,r){var n=s({scheme:"null"},r);return ne(ie(z(e,n),z(t,n),n,!0),n)}function se(e,t){return"string"==typeof e?e=ne(z(e,t),t):"object"===n(e)&&(e=z(ne(e,t),t)),e}function ae(e,t,r){return"string"==typeof e?e=ne(z(e,r),r):"object"===n(e)&&(e=ne(e,r)),"string"==typeof t?t=ne(z(t,r),r):"object"===n(t)&&(t=ne(t,r)),e===t}function ce(e,t){return e&&e.toString().replace(t&&t.iri?A.ESCAPE:c.ESCAPE,G)}function Ae(e,t){return e&&e.toString().replace(t&&t.iri?A.PCT_ENCODED:c.PCT_ENCODED,H)}var le={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var r="https"===String(e.scheme).toLowerCase();return e.port!==(r?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},ue={scheme:"https",domainHost:le.domainHost,parse:le.parse,serialize:le.serialize};function de(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var he={scheme:"ws",domainHost:!0,parse:function(e,t){var r=e;return r.secure=de(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r},serialize:function(e,t){if(e.port!==(de(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var r=e.resourceName.split("?"),n=l(r,2),i=n[0],o=n[1];e.path=i&&"/"!==i?i:void 0,e.query=o,e.resourceName=void 0}return e.fragment=void 0,e}},pe={scheme:"wss",domainHost:he.domainHost,parse:he.parse,serialize:he.serialize},ge={},fe="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",me="[0-9A-Fa-f]",Ee=r(r("%[EFef]"+me+"%"+me+me+"%"+me+me)+"|"+r("%[89A-Fa-f]"+me+"%"+me+me)+"|"+r("%"+me+me)),Ce="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",Ie=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),ye="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",Be=new RegExp(fe,"g"),be=new RegExp(Ee,"g"),we=new RegExp(t("[^]",Ce,"[\\.]",'[\\"]',Ie),"g"),ve=new RegExp(t("[^]",fe,ye),"g"),Se=ve;function Qe(e){var t=H(e);return t.match(Be)?t:e}var _e={scheme:"mailto",parse:function(e,t){var r=e,n=r.to=r.path?r.path.split(","):[];if(r.path=void 0,r.query){for(var i=!1,o={},s=r.query.split("&"),a=0,c=s.length;a<c;++a){var A=s[a].split("=");switch(A[0]){case"to":for(var l=A[1].split(","),u=0,d=l.length;u<d;++u)n.push(l[u]);break;case"subject":r.subject=Ae(A[1],t);break;case"body":r.body=Ae(A[1],t);break;default:i=!0,o[Ae(A[0],t)]=Ae(A[1],t)}}i&&(r.headers=o)}r.query=void 0;for(var h=0,p=n.length;h<p;++h){var g=n[h].split("@");if(g[0]=Ae(g[0]),t.unicodeSupport)g[1]=Ae(g[1],t).toLowerCase();else try{g[1]=O.toASCII(Ae(g[1],t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}n[h]=g.join("@")}return r},serialize:function(e,t){var r=e,n=o(e.to);if(n){for(var s=0,a=n.length;s<a;++s){var c=String(n[s]),A=c.lastIndexOf("@"),l=c.slice(0,A).replace(be,Qe).replace(be,i).replace(we,G),u=c.slice(A+1);try{u=t.iri?O.toUnicode(u):O.toASCII(Ae(u,t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}n[s]=l+"@"+u}r.path=n.join(",")}var d=e.headers=e.headers||{};e.subject&&(d.subject=e.subject),e.body&&(d.body=e.body);var h=[];for(var p in d)d[p]!==ge[p]&&h.push(p.replace(be,Qe).replace(be,i).replace(ve,G)+"="+d[p].replace(be,Qe).replace(be,i).replace(Se,G));return h.length&&(r.query=h.join("&")),r}},De=/^([^\:]+)\:(.*)/,xe={scheme:"urn",parse:function(e,t){var r=e.path&&e.path.match(De),n=e;if(r){var i=t.scheme||n.scheme||"urn",o=r[1].toLowerCase(),s=r[2],a=i+":"+(t.nid||o),c=U[a];n.nid=o,n.nss=s,n.path=void 0,c&&(n=c.parse(n,t))}else n.error=n.error||"URN can not be parsed.";return n},serialize:function(e,t){var r=t.scheme||e.scheme||"urn",n=e.nid,i=r+":"+(t.nid||n),o=U[i];o&&(e=o.serialize(e,t));var s=e,a=e.nss;return s.path=(n||t.nid)+":"+a,s}},ke=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,Re={scheme:"urn:uuid",parse:function(e,t){var r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&r.uuid.match(ke)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e,t){var r=e;return r.nss=(e.uuid||"").toLowerCase(),r}};U[le.scheme]=le,U[ue.scheme]=ue,U[he.scheme]=he,U[pe.scheme]=pe,U[_e.scheme]=_e,U[xe.scheme]=xe,U[Re.scheme]=Re,e.SCHEMES=U,e.pctEncChar=G,e.pctDecChars=H,e.parse=z,e.removeDotSegments=re,e.serialize=ne,e.resolveComponents=ie,e.resolve=oe,e.normalize=se,e.equal=ae,e.escapeComponent=ce,e.unescapeComponent=Ae,Object.defineProperty(e,"__esModule",{value:!0})}(uri_all.exports);var uri_allExports=uri_all.exports,ucs2length$1=function(e){for(var t,r=0,n=e.length,i=0;i<n;)r++,(t=e.charCodeAt(i++))>=55296&&t<=56319&&i<n&&56320==(64512&(t=e.charCodeAt(i)))&&i++;return r},util$7={copy:copy,checkDataType:checkDataType,checkDataTypes:checkDataTypes,coerceToTypes:coerceToTypes,toHash:toHash$1,getProperty:getProperty,escapeQuotes:escapeQuotes,equal:fastDeepEqual,ucs2length:ucs2length$1,varOccurences:varOccurences,varReplace:varReplace,schemaHasRules:schemaHasRules,schemaHasRulesExcept:schemaHasRulesExcept,schemaUnknownRules:schemaUnknownRules,toQuotedString:toQuotedString,getPathExpr:getPathExpr,getPath:getPath,getData:getData,unescapeFragment:unescapeFragment,unescapeJsonPointer:unescapeJsonPointer,escapeFragment:escapeFragment,escapeJsonPointer:escapeJsonPointer};function copy(e,t){for(var r in t=t||{},e)t[r]=e[r];return t}function checkDataType(e,t,r,n){var i=n?" !== ":" === ",o=n?" || ":" && ",s=n?"!":"",a=n?"":"!";switch(e){case"null":return t+i+"null";case"array":return s+"Array.isArray("+t+")";case"object":return"("+s+t+o+"typeof "+t+i+'"object"'+o+a+"Array.isArray("+t+"))";case"integer":return"(typeof "+t+i+'"number"'+o+a+"("+t+" % 1)"+o+t+i+t+(r?o+s+"isFinite("+t+")":"")+")";case"number":return"(typeof "+t+i+'"'+e+'"'+(r?o+s+"isFinite("+t+")":"")+")";default:return"typeof "+t+i+'"'+e+'"'}}function checkDataTypes(e,t,r){if(1===e.length)return checkDataType(e[0],t,r,!0);var n="",i=toHash$1(e);for(var o in i.array&&i.object&&(n=i.null?"(":"(!"+t+" || ",n+="typeof "+t+' !== "object")',delete i.null,delete i.array,delete i.object),i.number&&delete i.integer,i)n+=(n?" && ":"")+checkDataType(o,t,r,!0);return n}var COERCE_TO_TYPES=toHash$1(["string","number","integer","boolean","null"]);function coerceToTypes(e,t){if(Array.isArray(t)){for(var r=[],n=0;n<t.length;n++){var i=t[n];(COERCE_TO_TYPES[i]||"array"===e&&"array"===i)&&(r[r.length]=i)}if(r.length)return r}else{if(COERCE_TO_TYPES[t])return[t];if("array"===e&&"array"===t)return["array"]}}function toHash$1(e){for(var t={},r=0;r<e.length;r++)t[e[r]]=!0;return t}var IDENTIFIER$1=/^[a-z$_][a-z$_0-9]*$/i,SINGLE_QUOTE=/'|\\/g;function getProperty(e){return"number"==typeof e?"["+e+"]":IDENTIFIER$1.test(e)?"."+e:"['"+escapeQuotes(e)+"']"}function escapeQuotes(e){return e.replace(SINGLE_QUOTE,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function varOccurences(e,t){t+="[^0-9]";var r=e.match(new RegExp(t,"g"));return r?r.length:0}function varReplace(e,t,r){return t+="([^0-9])",r=r.replace(/\$/g,"$$$$"),e.replace(new RegExp(t,"g"),r+"$1")}function schemaHasRules(e,t){if("boolean"==typeof e)return!e;for(var r in e)if(t[r])return!0}function schemaHasRulesExcept(e,t,r){if("boolean"==typeof e)return!e&&"not"!=r;for(var n in e)if(n!=r&&t[n])return!0}function schemaUnknownRules(e,t){if("boolean"!=typeof e)for(var r in e)if(!t[r])return r}function toQuotedString(e){return"'"+escapeQuotes(e)+"'"}function getPathExpr(e,t,r,n){return joinPaths(e,r?"'/' + "+t+(n?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):n?"'[' + "+t+" + ']'":"'[\\'' + "+t+" + '\\']'")}function getPath(e,t,r){return joinPaths(e,toQuotedString(r?"/"+escapeJsonPointer(t):getProperty(t)))}var JSON_POINTER$1=/^\/(?:[^~]|~0|~1)*$/,RELATIVE_JSON_POINTER$1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData(e,t,r){var n,i,o,s;if(""===e)return"rootData";if("/"==e[0]){if(!JSON_POINTER$1.test(e))throw new Error("Invalid JSON-pointer: "+e);i=e,o="rootData"}else{if(!(s=e.match(RELATIVE_JSON_POINTER$1)))throw new Error("Invalid JSON-pointer: "+e);if(n=+s[1],"#"==(i=s[2])){if(n>=t)throw new Error("Cannot access property/index "+n+" levels up, current level is "+t);return r[t-n]}if(n>t)throw new Error("Cannot access data "+n+" levels up, current level is "+t);if(o="data"+(t-n||""),!i)return o}for(var a=o,c=i.split("/"),A=0;A<c.length;A++){var l=c[A];l&&(a+=" && "+(o+=getProperty(unescapeJsonPointer(l))))}return a}function joinPaths(e,t){return'""'==e?t:(e+" + "+t).replace(/([^\\])' \+ '/g,"$1")}function unescapeFragment(e){return unescapeJsonPointer(decodeURIComponent(e))}function escapeFragment(e){return encodeURIComponent(escapeJsonPointer(e))}function escapeJsonPointer(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeJsonPointer(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var util$6=util$7,schema_obj=SchemaObject$2;function SchemaObject$2(e){util$6.copy(e,this)}var jsonSchemaTraverse={exports:{}},traverse$1=jsonSchemaTraverse.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),_traverse(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function _traverse(e,t,r,n,i,o,s,a,c,A){if(n&&"object"==typeof n&&!Array.isArray(n)){for(var l in t(n,i,o,s,a,c,A),n){var u=n[l];if(Array.isArray(u)){if(l in traverse$1.arrayKeywords)for(var d=0;d<u.length;d++)_traverse(e,t,r,u[d],i+"/"+l+"/"+d,o,i,l,n,d)}else if(l in traverse$1.propsKeywords){if(u&&"object"==typeof u)for(var h in u)_traverse(e,t,r,u[h],i+"/"+l+"/"+escapeJsonPtr(h),o,i,l,n,h)}else(l in traverse$1.keywords||e.allKeys&&!(l in traverse$1.skipKeywords))&&_traverse(e,t,r,u,i+"/"+l,o,i,l,n)}r(n,i,o,s,a,c,A)}}function escapeJsonPtr(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}traverse$1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},traverse$1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},traverse$1.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},traverse$1.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};var jsonSchemaTraverseExports=jsonSchemaTraverse.exports,URI$1=uri_allExports,equal$1=fastDeepEqual,util$5=util$7,SchemaObject$1=schema_obj,traverse=jsonSchemaTraverseExports,resolve_1=resolve$7;function resolve$7(e,t,r){var n=this._refs[r];if("string"==typeof n){if(!this._refs[n])return resolve$7.call(this,e,t,n);n=this._refs[n]}if((n=n||this._schemas[r])instanceof SchemaObject$1)return inlineRef(n.schema,this._opts.inlineRefs)?n.schema:n.validate||this._compile(n);var i,o,s,a=resolveSchema.call(this,t,r);return a&&(i=a.schema,t=a.root,s=a.baseId),i instanceof SchemaObject$1?o=i.validate||e.call(this,i.schema,t,void 0,s):void 0!==i&&(o=inlineRef(i,this._opts.inlineRefs)?i:e.call(this,i,t,void 0,s)),o}function resolveSchema(e,t){var r=URI$1.parse(t),n=_getFullPath(r),i=getFullPath(this._getId(e.schema));if(0===Object.keys(e.schema).length||n!==i){var o=normalizeId(n),s=this._refs[o];if("string"==typeof s)return resolveRecursive.call(this,e,s,r);if(s instanceof SchemaObject$1)s.validate||this._compile(s),e=s;else{if(!((s=this._schemas[o])instanceof SchemaObject$1))return;if(s.validate||this._compile(s),o==normalizeId(t))return{schema:s,root:e,baseId:i};e=s}if(!e.schema)return;i=getFullPath(this._getId(e.schema))}return getJsonPointer.call(this,r,i,e.schema,e)}function resolveRecursive(e,t,r){var n=resolveSchema.call(this,e,t);if(n){var i=n.schema,o=n.baseId;e=n.root;var s=this._getId(i);return s&&(o=resolveUrl(o,s)),getJsonPointer.call(this,r,o,i,e)}}resolve$7.normalizeId=normalizeId,resolve$7.fullPath=getFullPath,resolve$7.url=resolveUrl,resolve$7.ids=resolveIds,resolve$7.inlineRef=inlineRef,resolve$7.schema=resolveSchema;var PREVENT_SCOPE_CHANGE=util$5.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(e,t,r,n){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var i=e.fragment.split("/"),o=1;o<i.length;o++){var s=i[o];if(s){if(void 0===(r=r[s=util$5.unescapeFragment(s)]))break;var a;if(!PREVENT_SCOPE_CHANGE[s]&&((a=this._getId(r))&&(t=resolveUrl(t,a)),r.$ref)){var c=resolveUrl(t,r.$ref),A=resolveSchema.call(this,n,c);A&&(r=A.schema,n=A.root,t=A.baseId)}}}return void 0!==r&&r!==n.schema?{schema:r,root:n,baseId:t}:void 0}}var SIMPLE_INLINED=util$5.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function inlineRef(e,t){return!1!==t&&(void 0===t||!0===t?checkNoRef(e):t?countKeys(e)<=t:void 0)}function checkNoRef(e){var t;if(Array.isArray(e)){for(var r=0;r<e.length;r++)if("object"==typeof(t=e[r])&&!checkNoRef(t))return!1}else for(var n in e){if("$ref"==n)return!1;if("object"==typeof(t=e[n])&&!checkNoRef(t))return!1}return!0}function countKeys(e){var t,r=0;if(Array.isArray(e)){for(var n=0;n<e.length;n++)if("object"==typeof(t=e[n])&&(r+=countKeys(t)),r==1/0)return 1/0}else for(var i in e){if("$ref"==i)return 1/0;if(SIMPLE_INLINED[i])r++;else if("object"==typeof(t=e[i])&&(r+=countKeys(t)+1),r==1/0)return 1/0}return r}function getFullPath(e,t){return!1!==t&&(e=normalizeId(e)),_getFullPath(URI$1.parse(e))}function _getFullPath(e){return URI$1.serialize(e).split("#")[0]+"#"}var TRAILING_SLASH_HASH=/#\/?$/;function normalizeId(e){return e?e.replace(TRAILING_SLASH_HASH,""):""}function resolveUrl(e,t){return t=normalizeId(t),URI$1.resolve(e,t)}function resolveIds(e){var t=normalizeId(this._getId(e)),r={"":t},n={"":getFullPath(t,!1)},i={},o=this;return traverse(e,{allKeys:!0},(function(e,t,s,a,c,A,l){if(""!==t){var u=o._getId(e),d=r[a],h=n[a]+"/"+c;if(void 0!==l&&(h+="/"+("number"==typeof l?l:util$5.escapeFragment(l))),"string"==typeof u){u=d=normalizeId(d?URI$1.resolve(d,u):u);var p=o._refs[u];if("string"==typeof p&&(p=o._refs[p]),p&&p.schema){if(!equal$1(e,p.schema))throw new Error('id "'+u+'" resolves to more than one schema')}else if(u!=normalizeId(h))if("#"==u[0]){if(i[u]&&!equal$1(e,i[u]))throw new Error('id "'+u+'" resolves to more than one schema');i[u]=e}else o._refs[u]=h}r[t]=d,n[t]=h}})),i}var resolve$6=resolve_1,error_classes={Validation:errorSubclass(ValidationError$1),MissingRef:errorSubclass(MissingRefError$1)};function ValidationError$1(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}function MissingRefError$1(e,t,r){this.message=r||MissingRefError$1.message(e,t),this.missingRef=resolve$6.url(e,t),this.missingSchema=resolve$6.normalizeId(resolve$6.fullPath(this.missingRef))}function errorSubclass(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}MissingRefError$1.message=function(e,t){return"can't resolve reference "+t+" from id "+e};var fastJsonStableStringify=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r,n="boolean"==typeof t.cycles&&t.cycles,i=t.cmp&&(r=t.cmp,function(e){return function(t,n){var i={key:t,value:e[t]},o={key:n,value:e[n]};return r(i,o)}}),o=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var r,s;if(Array.isArray(t)){for(s="[",r=0;r<t.length;r++)r&&(s+=","),s+=e(t[r])||"null";return s+"]"}if(null===t)return"null";if(-1!==o.indexOf(t)){if(n)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=o.push(t)-1,c=Object.keys(t).sort(i&&i(t));for(s="",r=0;r<c.length;r++){var A=c[r],l=e(t[A]);l&&(s&&(s+=","),s+=JSON.stringify(A)+":"+l)}return o.splice(a,1),"{"+s+"}"}}(e)},validate$1=function(e,t,r){var n="",i=!0===e.schema.$async,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),s=e.self._getId(e.schema);if(e.opts.strictKeywords){var a=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(a){var c="unknown keyword: "+a;if("log"!==e.opts.strictKeywords)throw new Error(c);e.logger.warn(c)}}if(e.isTop&&(n+=" var validate = ",i&&(e.async=!0,n+="async "),n+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",s&&(e.opts.sourceCode||e.opts.processCode)&&(n+=" /*# sourceURL="+s+" */ ")),"boolean"==typeof e.schema||!o&&!e.schema.$ref){t="false schema";var A=e.level,l=e.dataLevel,u=e.schema[t],d=e.schemaPath+e.util.getProperty(t),h=e.errSchemaPath+"/"+t,p=!e.opts.allErrors,g="data"+(l||""),f="valid"+A;if(!1===e.schema){e.isTop?p=!0:n+=" var "+f+" = false; ",(z=z||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: {} ",!1!==e.opts.messages&&(n+=" , message: 'boolean schema is false' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";var m=n;n=z.pop(),!e.compositeRule&&p?e.async?n+=" throw new ValidationError(["+m+"]); ":n+=" validate.errors = ["+m+"]; return false; ":n+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?n+=i?" return data; ":" validate.errors = null; return true; ":n+=" var "+f+" = true; ";return e.isTop&&(n+=" }; return validate; "),n}if(e.isTop){var E=e.isTop;A=e.level=0,l=e.dataLevel=0,g="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var C="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(C);e.logger.warn(C)}n+=" var vErrors = null; ",n+=" var errors = 0; ",n+=" if (rootData === undefined) rootData = data; "}else{A=e.level,g="data"+((l=e.dataLevel)||"");if(s&&(e.baseId=e.resolve.url(e.baseId,s)),i&&!e.async)throw new Error("async schema in sync schema");n+=" var errs_"+A+" = errors;"}f="valid"+A,p=!e.opts.allErrors;var I="",y="",B=e.schema.type,b=Array.isArray(B);if(B&&e.opts.nullable&&!0===e.schema.nullable&&(b?-1==B.indexOf("null")&&(B=B.concat("null")):"null"!=B&&(B=[B,"null"],b=!0)),b&&1==B.length&&(B=B[0],b=!1),e.schema.$ref&&o){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(n+=" "+e.RULES.all.$comment.code(e,"$comment")),B){if(e.opts.coerceTypes)var w=e.util.coerceToTypes(e.opts.coerceTypes,B);var v=e.RULES.types[B];if(w||b||!0===v||v&&!V(v)){d=e.schemaPath+".type",h=e.errSchemaPath+"/type",d=e.schemaPath+".type",h=e.errSchemaPath+"/type";var S=b?"checkDataTypes":"checkDataType";if(n+=" if ("+e.util[S](B,g,e.opts.strictNumbers,!0)+") { ",w){var Q="dataType"+A,_="coerced"+A;n+=" var "+Q+" = typeof "+g+"; var "+_+" = undefined; ","array"==e.opts.coerceTypes&&(n+=" if ("+Q+" == 'object' && Array.isArray("+g+") && "+g+".length == 1) { "+g+" = "+g+"[0]; "+Q+" = typeof "+g+"; if ("+e.util.checkDataType(e.schema.type,g,e.opts.strictNumbers)+") "+_+" = "+g+"; } "),n+=" if ("+_+" !== undefined) ; ";var D=w;if(D)for(var x,k=-1,R=D.length-1;k<R;)"string"==(x=D[k+=1])?n+=" else if ("+Q+" == 'number' || "+Q+" == 'boolean') "+_+" = '' + "+g+"; else if ("+g+" === null) "+_+" = ''; ":"number"==x||"integer"==x?(n+=" else if ("+Q+" == 'boolean' || "+g+" === null || ("+Q+" == 'string' && "+g+" && "+g+" == +"+g+" ","integer"==x&&(n+=" && !("+g+" % 1)"),n+=")) "+_+" = +"+g+"; "):"boolean"==x?n+=" else if ("+g+" === 'false' || "+g+" === 0 || "+g+" === null) "+_+" = false; else if ("+g+" === 'true' || "+g+" === 1) "+_+" = true; ":"null"==x?n+=" else if ("+g+" === '' || "+g+" === 0 || "+g+" === false) "+_+" = null; ":"array"==e.opts.coerceTypes&&"array"==x&&(n+=" else if ("+Q+" == 'string' || "+Q+" == 'number' || "+Q+" == 'boolean' || "+g+" == null) "+_+" = ["+g+"]; ");n+=" else { ",(z=z||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",n+=b?""+B.join(","):""+B,n+="' } ",!1!==e.opts.messages&&(n+=" , message: 'should be ",n+=b?""+B.join(","):""+B,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";m=n;n=z.pop(),!e.compositeRule&&p?e.async?n+=" throw new ValidationError(["+m+"]); ":n+=" validate.errors = ["+m+"]; return false; ":n+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } if ("+_+" !== undefined) { ";var T=l?"data"+(l-1||""):"parentData";n+=" "+g+" = "+_+"; ",l||(n+="if ("+T+" !== undefined)"),n+=" "+T+"["+(l?e.dataPathArr[l]:"parentDataProperty")+"] = "+_+"; } "}else{(z=z||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",n+=b?""+B.join(","):""+B,n+="' } ",!1!==e.opts.messages&&(n+=" , message: 'should be ",n+=b?""+B.join(","):""+B,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";m=n;n=z.pop(),!e.compositeRule&&p?e.async?n+=" throw new ValidationError(["+m+"]); ":n+=" validate.errors = ["+m+"]; return false; ":n+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}n+=" } "}}if(e.schema.$ref&&!o)n+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",p&&(n+=" } if (errors === ",n+=E?"0":"errs_"+A,n+=") { ",y+="}");else{var $=e.RULES;if($)for(var N=-1,F=$.length-1;N<F;)if(V(v=$[N+=1])){if(v.type&&(n+=" if ("+e.util.checkDataType(v.type,g,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==v.type&&e.schema.properties){u=e.schema.properties;var M=Object.keys(u);if(M)for(var P,L=-1,O=M.length-1;L<O;){if(void 0!==(H=u[P=M[L+=1]]).default){var U=g+e.util.getProperty(P);if(e.compositeRule){if(e.opts.strictDefaults){C="default is ignored for: "+U;if("log"!==e.opts.strictDefaults)throw new Error(C);e.logger.warn(C)}}else n+=" if ("+U+" === undefined ","empty"==e.opts.useDefaults&&(n+=" || "+U+" === null || "+U+" === '' "),n+=" ) "+U+" = ","shared"==e.opts.useDefaults?n+=" "+e.useDefault(H.default)+" ":n+=" "+JSON.stringify(H.default)+" ",n+="; "}}}else if("array"==v.type&&Array.isArray(e.schema.items)){var G=e.schema.items;if(G){k=-1;for(var H,j=G.length-1;k<j;)if(void 0!==(H=G[k+=1]).default){U=g+"["+k+"]";if(e.compositeRule){if(e.opts.strictDefaults){C="default is ignored for: "+U;if("log"!==e.opts.strictDefaults)throw new Error(C);e.logger.warn(C)}}else n+=" if ("+U+" === undefined ","empty"==e.opts.useDefaults&&(n+=" || "+U+" === null || "+U+" === '' "),n+=" ) "+U+" = ","shared"==e.opts.useDefaults?n+=" "+e.useDefault(H.default)+" ":n+=" "+JSON.stringify(H.default)+" ",n+="; "}}}var q=v.rules;if(q)for(var K,W=-1,J=q.length-1;W<J;)if(X(K=q[W+=1])){var Y=K.code(e,K.keyword,v.type);Y&&(n+=" "+Y+" ",p&&(I+="}"))}if(p&&(n+=" "+I+" ",I=""),v.type&&(n+=" } ",B&&B===v.type&&!w)){n+=" else { ";var z;d=e.schemaPath+".type",h=e.errSchemaPath+"/type";(z=z||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",n+=b?""+B.join(","):""+B,n+="' } ",!1!==e.opts.messages&&(n+=" , message: 'should be ",n+=b?""+B.join(","):""+B,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";m=n;n=z.pop(),!e.compositeRule&&p?e.async?n+=" throw new ValidationError(["+m+"]); ":n+=" validate.errors = ["+m+"]; return false; ":n+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } "}p&&(n+=" if (errors === ",n+=E?"0":"errs_"+A,n+=") { ",y+="}")}}function V(e){for(var t=e.rules,r=0;r<t.length;r++)if(X(t[r]))return!0}function X(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var r=t.implements,n=0;n<r.length;n++)if(void 0!==e.schema[r[n]])return!0}(t)}return p&&(n+=" "+y+" "),E?(i?(n+=" if (errors === 0) return data; ",n+=" else throw new ValidationError(vErrors); "):(n+=" validate.errors = vErrors; ",n+=" return errors === 0; "),n+=" }; return validate;"):n+=" var "+f+" = errors === errs_"+A+";",n},resolve$5=resolve_1,util$4=util$7,errorClasses$1=error_classes,stableStringify$1=fastJsonStableStringify,validateGenerator=validate$1,ucs2length=util$4.ucs2length,equal=fastDeepEqual,ValidationError=errorClasses$1.Validation,compile_1=compile$2;function compile$2(e,t,r,n){var i=this,o=this._opts,s=[void 0],a={},c=[],A={},l=[],u={},d=[];t=t||{schema:e,refVal:s,refs:a};var h=checkCompiling.call(this,e,t,n),p=this._compilations[h.index];if(h.compiling)return p.callValidate=function e(){var t=p.validate,r=t.apply(this,arguments);return e.errors=t.errors,r};var g=this._formats,f=this.RULES;try{var m=C(e,t,r,n);p.validate=m;var E=p.callValidate;return E&&(E.schema=m.schema,E.errors=null,E.refs=m.refs,E.refVal=m.refVal,E.root=m.root,E.$async=m.$async,o.sourceCode&&(E.source=m.source)),m}finally{endCompiling.call(this,e,t,n)}function C(e,r,n,A){var u=!r||r&&r.schema==e;if(r.schema!=t.schema)return compile$2.call(i,e,r,n,A);var h,p=!0===e.$async,m=validateGenerator({isTop:!0,schema:e,isRoot:u,baseId:A,root:r,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:errorClasses$1.MissingRef,RULES:f,validate:validateGenerator,util:util$4,resolve:resolve$5,resolveRef:I,usePattern:b,useDefault:w,useCustomRule:v,opts:o,formats:g,logger:i.logger,self:i});m=vars(s,refValCode)+vars(c,patternCode)+vars(l,defaultCode)+vars(d,customRuleCode$1)+m,o.processCode&&(m=o.processCode(m,e));try{h=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",m)(i,f,g,t,s,l,d,equal,ucs2length,ValidationError),s[0]=h}catch(e){throw i.logger.error("Error compiling schema, function code:",m),e}return h.schema=e,h.errors=null,h.refs=a,h.refVal=s,h.root=u?h:r,p&&(h.$async=!0),!0===o.sourceCode&&(h.source={code:m,patterns:c,defaults:l}),h}function I(e,n,c){n=resolve$5.url(e,n);var A,l,u=a[n];if(void 0!==u)return B(A=s[u],l="refVal["+u+"]");if(!c&&t.refs){var d=t.refs[n];if(void 0!==d)return B(A=t.refVal[d],l=y(n,A))}l=y(n);var h=resolve$5.call(i,C,t,n);if(void 0===h){var p=r&&r[n];p&&(h=resolve$5.inlineRef(p,o.inlineRefs)?p:compile$2.call(i,p,t,r,e))}if(void 0!==h)return function(e,t){var r=a[e];s[r]=t}(n,h),B(h,l);!function(e){delete a[e]}(n)}function y(e,t){var r=s.length;return s[r]=t,a[e]=r,"refVal"+r}function B(e,t){return"object"==typeof e||"boolean"==typeof e?{code:t,schema:e,inline:!0}:{code:t,$async:e&&!!e.$async}}function b(e){var t=A[e];return void 0===t&&(t=A[e]=c.length,c[t]=e),"pattern"+t}function w(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return util$4.toQuotedString(e);case"object":if(null===e)return"null";var t=stableStringify$1(e),r=u[t];return void 0===r&&(r=u[t]=l.length,l[r]=e),"default"+r}}function v(e,t,r,n){if(!1!==i._opts.validateSchema){var s=e.definition.dependencies;if(s&&!s.every((function(e){return Object.prototype.hasOwnProperty.call(r,e)})))throw new Error("parent schema must have all required keywords: "+s.join(","));var a=e.definition.validateSchema;if(a)if(!a(t)){var c="keyword schema is invalid: "+i.errorsText(a.errors);if("log"!=i._opts.validateSchema)throw new Error(c);i.logger.error(c)}}var A,l=e.definition.compile,u=e.definition.inline,h=e.definition.macro;if(l)A=l.call(i,t,r,n);else if(h)A=h.call(i,t,r,n),!1!==o.validateSchema&&i.validateSchema(A,!0);else if(u)A=u.call(i,n,e.keyword,t,r);else if(!(A=e.definition.validate))return;if(void 0===A)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var p=d.length;return d[p]=A,{code:"customRule"+p,validate:A}}}function checkCompiling(e,t,r){var n=compIndex.call(this,e,t,r);return n>=0?{index:n,compiling:!0}:(n=this._compilations.length,this._compilations[n]={schema:e,root:t,baseId:r},{index:n,compiling:!1})}function endCompiling(e,t,r){var n=compIndex.call(this,e,t,r);n>=0&&this._compilations.splice(n,1)}function compIndex(e,t,r){for(var n=0;n<this._compilations.length;n++){var i=this._compilations[n];if(i.schema==e&&i.root==t&&i.baseId==r)return n}return-1}function patternCode(e,t){return"var pattern"+e+" = new RegExp("+util$4.toQuotedString(t[e])+");"}function defaultCode(e){return"var default"+e+" = defaults["+e+"];"}function refValCode(e,t){return void 0===t[e]?"":"var refVal"+e+" = refVal["+e+"];"}function customRuleCode$1(e){return"var customRule"+e+" = customRules["+e+"];"}function vars(e,t){if(!e.length)return"";for(var r="",n=0;n<e.length;n++)r+=t(n,e);return r}var cache={exports:{}},Cache$1=cache.exports=function(){this._cache={}};Cache$1.prototype.put=function(e,t){this._cache[e]=t},Cache$1.prototype.get=function(e){return this._cache[e]},Cache$1.prototype.del=function(e){delete this._cache[e]},Cache$1.prototype.clear=function(){this._cache={}};var cacheExports=cache.exports,util$3=util$7,DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31],TIME=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,HOSTNAME=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,URIREF=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,URITEMPLATE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,URL$2=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,UUID=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,JSON_POINTER=/^(?:\/(?:[^~/]|~0|~1)*)*$/,JSON_POINTER_URI_FRAGMENT=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,RELATIVE_JSON_POINTER=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,formats_1=formats$2;function formats$2(e){return e="full"==e?"full":"fast",util$3.copy(formats$2[e])}function isLeapYear(e){return e%4==0&&(e%100!=0||e%400==0)}function date(e){var t=e.match(DATE);if(!t)return!1;var r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(2==n&&isLeapYear(r)?29:DAYS[n])}function time(e,t){var r=e.match(TIME);if(!r)return!1;var n=r[1],i=r[2],o=r[3],s=r[5];return(n<=23&&i<=59&&o<=59||23==n&&59==i&&60==o)&&(!t||s)}formats$2.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":URITEMPLATE,url:URL$2,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:HOSTNAME,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:regex,uuid:UUID,"json-pointer":JSON_POINTER,"json-pointer-uri-fragment":JSON_POINTER_URI_FRAGMENT,"relative-json-pointer":RELATIVE_JSON_POINTER},formats$2.full={date:date,time:time,"date-time":date_time,uri:uri,"uri-reference":URIREF,"uri-template":URITEMPLATE,url:URL$2,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:HOSTNAME,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:regex,uuid:UUID,"json-pointer":JSON_POINTER,"json-pointer-uri-fragment":JSON_POINTER_URI_FRAGMENT,"relative-json-pointer":RELATIVE_JSON_POINTER};var DATE_TIME_SEPARATOR=/t|\s/i;function date_time(e){var t=e.split(DATE_TIME_SEPARATOR);return 2==t.length&&date(t[0])&&time(t[1],!0)}var NOT_URI_FRAGMENT=/\/|:/;function uri(e){return NOT_URI_FRAGMENT.test(e)&&URI.test(e)}var Z_ANCHOR=/[^\\]\\Z/;function regex(e){if(Z_ANCHOR.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}var ref=function(e,t,r){var n,i,o=" ",s=e.level,a=e.dataLevel,c=e.schema[t],A=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(a||""),d="valid"+s;if("#"==c||"#/"==c)e.isRoot?(n=e.async,i="validate"):(n=!0===e.root.schema.$async,i="root.refVal[0]");else{var h=e.resolveRef(e.baseId,c,e.isRoot);if(void 0===h){var p=e.MissingRefError.message(e.baseId,c);if("fail"==e.opts.missingRefs){e.logger.error(p),(E=E||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(A)+" , params: { ref: '"+e.util.escapeQuotes(c)+"' } ",!1!==e.opts.messages&&(o+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(c)+"' "),e.opts.verbose&&(o+=" , schema: "+e.util.toQuotedString(c)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),o+=" } "):o+=" {} ";var g=o;o=E.pop(),!e.compositeRule&&l?e.async?o+=" throw new ValidationError(["+g+"]); ":o+=" validate.errors = ["+g+"]; return false; ":o+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",l&&(o+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,c,p);e.logger.warn(p),l&&(o+=" if (true) { ")}}else if(h.inline){var f=e.util.copy(e);f.level++;var m="valid"+f.level;f.schema=h.schema,f.schemaPath="",f.errSchemaPath=c,o+=" "+e.validate(f).replace(/validate\.schema/g,h.code)+" ",l&&(o+=" if ("+m+") { ")}else n=!0===h.$async||e.async&&!1!==h.$async,i=h.code}if(i){var E;(E=E||[]).push(o),o="",e.opts.passContext?o+=" "+i+".call(this, ":o+=" "+i+"( ",o+=" "+u+", (dataPath || '')",'""'!=e.errorPath&&(o+=" + "+e.errorPath);var C=o+=" , "+(a?"data"+(a-1||""):"parentData")+" , "+(a?e.dataPathArr[a]:"parentDataProperty")+", rootData) ";if(o=E.pop(),n){if(!e.async)throw new Error("async schema referenced by sync schema");l&&(o+=" var "+d+"; "),o+=" try { await "+C+"; ",l&&(o+=" "+d+" = true; "),o+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",l&&(o+=" "+d+" = false; "),o+=" } ",l&&(o+=" if ("+d+") { ")}else o+=" if (!"+C+") { if (vErrors === null) vErrors = "+i+".errors; else vErrors = vErrors.concat("+i+".errors); errors = vErrors.length; } ",l&&(o+=" else { ")}return o},allOf=function(e,t,r){var n=" ",i=e.schema[t],o=e.schemaPath+e.util.getProperty(t),s=e.errSchemaPath+"/"+t,a=!e.opts.allErrors,c=e.util.copy(e),A="";c.level++;var l="valid"+c.level,u=c.baseId,d=!0,h=i;if(h)for(var p,g=-1,f=h.length-1;g<f;)p=h[g+=1],(e.opts.strictKeywords?"object"==typeof p&&Object.keys(p).length>0||!1===p:e.util.schemaHasRules(p,e.RULES.all))&&(d=!1,c.schema=p,c.schemaPath=o+"["+g+"]",c.errSchemaPath=s+"/"+g,n+=" "+e.validate(c)+" ",c.baseId=u,a&&(n+=" if ("+l+") { ",A+="}"));return a&&(n+=d?" if (true) { ":" "+A.slice(0,-1)+" "),n},anyOf=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="valid"+i,d="errs__"+i,h=e.util.copy(e),p="";h.level++;var g="valid"+h.level,f=s.every((function(t){return e.opts.strictKeywords?"object"==typeof t&&Object.keys(t).length>0||!1===t:e.util.schemaHasRules(t,e.RULES.all)}));if(f){var m=h.baseId;n+=" var "+d+" = errors; var "+u+" = false; ";var E=e.compositeRule;e.compositeRule=h.compositeRule=!0;var C=s;if(C)for(var I,y=-1,B=C.length-1;y<B;)I=C[y+=1],h.schema=I,h.schemaPath=a+"["+y+"]",h.errSchemaPath=c+"/"+y,n+=" "+e.validate(h)+" ",h.baseId=m,n+=" "+u+" = "+u+" || "+g+"; if (!"+u+") { ",p+="}";e.compositeRule=h.compositeRule=E,n+=" "+p+" if (!"+u+") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(n+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&A&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else A&&(n+=" if (true) { ");return n},comment=function(e,t,r){var n=" ",i=e.schema[t],o=e.errSchemaPath+"/"+t;e.opts.allErrors;var s=e.util.toQuotedString(i);return!0===e.opts.$comment?n+=" console.log("+s+");":"function"==typeof e.opts.$comment&&(n+=" self._opts.$comment("+s+", "+e.util.toQuotedString(o)+", validate.root.schema);"),n},_const=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="valid"+i,d=e.opts.$data&&s&&s.$data;d&&(n+=" var schema"+i+" = "+e.util.getData(s.$data,o,e.dataPathArr)+"; "),d||(n+=" var schema"+i+" = validate.schema"+a+";"),n+="var "+u+" = equal("+l+", schema"+i+"); if (!"+u+") { ";var h=h||[];h.push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+i+" } ",!1!==e.opts.messages&&(n+=" , message: 'should be equal to constant' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var p=n;return n=h.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",A&&(n+=" else { "),n},contains=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="valid"+i,d="errs__"+i,h=e.util.copy(e);h.level++;var p="valid"+h.level,g="i"+i,f=h.dataLevel=e.dataLevel+1,m="data"+f,E=e.baseId,C=e.opts.strictKeywords?"object"==typeof s&&Object.keys(s).length>0||!1===s:e.util.schemaHasRules(s,e.RULES.all);if(n+="var "+d+" = errors;var "+u+";",C){var I=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=s,h.schemaPath=a,h.errSchemaPath=c,n+=" var "+p+" = false; for (var "+g+" = 0; "+g+" < "+l+".length; "+g+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers,!0);var y=l+"["+g+"]";h.dataPathArr[f]=g;var B=e.validate(h);h.baseId=E,e.util.varOccurences(B,m)<2?n+=" "+e.util.varReplace(B,m,y)+" ":n+=" var "+m+" = "+y+"; "+B+" ",n+=" if ("+p+") break; } ",e.compositeRule=h.compositeRule=I,n+=" if (!"+p+") {"}else n+=" if ("+l+".length == 0) {";var b=b||[];b.push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(n+=" , message: 'should contain a valid item' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var w=n;return n=b.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+w+"]); ":n+=" validate.errors = ["+w+"]; return false; ":n+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { ",C&&(n+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } "),e.opts.allErrors&&(n+=" } "),n},dependencies=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="errs__"+i,d=e.util.copy(e),h="";d.level++;var p="valid"+d.level,g={},f={},m=e.opts.ownProperties;for(y in s)if("__proto__"!=y){var E=s[y],C=Array.isArray(E)?f:g;C[y]=E}n+="var "+u+" = errors;";var I=e.errorPath;for(var y in n+="var missing"+i+";",f)if((C=f[y]).length){if(n+=" if ( "+l+e.util.getProperty(y)+" !== undefined ",m&&(n+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(y)+"') "),A){n+=" && ( ";var B=C;if(B)for(var b=-1,w=B.length-1;b<w;){x=B[b+=1],b&&(n+=" || "),n+=" ( ( "+($=l+(T=e.util.getProperty(x)))+" === undefined ",m&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(x)+"') "),n+=") && (missing"+i+" = "+e.util.toQuotedString(e.opts.jsonPointers?x:T)+") ) "}n+=")) { ";var v="missing"+i,S="' + "+v+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(I,v,!0):I+" + "+v);var Q=Q||[];Q.push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(y)+"', missingProperty: '"+S+"', depsCount: "+C.length+", deps: '"+e.util.escapeQuotes(1==C.length?C[0]:C.join(", "))+"' } ",!1!==e.opts.messages&&(n+=" , message: 'should have ",1==C.length?n+="property "+e.util.escapeQuotes(C[0]):n+="properties "+e.util.escapeQuotes(C.join(", ")),n+=" when property "+e.util.escapeQuotes(y)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var _=n;n=Q.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+_+"]); ":n+=" validate.errors = ["+_+"]; return false; ":n+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{n+=" ) { ";var D=C;if(D)for(var x,k=-1,R=D.length-1;k<R;){x=D[k+=1];var T=e.util.getProperty(x),$=(S=e.util.escapeQuotes(x),l+T);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(I,x,e.opts.jsonPointers)),n+=" if ( "+$+" === undefined ",m&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(x)+"') "),n+=") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(y)+"', missingProperty: '"+S+"', depsCount: "+C.length+", deps: '"+e.util.escapeQuotes(1==C.length?C[0]:C.join(", "))+"' } ",!1!==e.opts.messages&&(n+=" , message: 'should have ",1==C.length?n+="property "+e.util.escapeQuotes(C[0]):n+="properties "+e.util.escapeQuotes(C.join(", ")),n+=" when property "+e.util.escapeQuotes(y)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}n+=" } ",A&&(h+="}",n+=" else { ")}e.errorPath=I;var N=d.baseId;for(var y in g){E=g[y];(e.opts.strictKeywords?"object"==typeof E&&Object.keys(E).length>0||!1===E:e.util.schemaHasRules(E,e.RULES.all))&&(n+=" "+p+" = true; if ( "+l+e.util.getProperty(y)+" !== undefined ",m&&(n+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(y)+"') "),n+=") { ",d.schema=E,d.schemaPath=a+e.util.getProperty(y),d.errSchemaPath=c+"/"+e.util.escapeFragment(y),n+=" "+e.validate(d)+" ",d.baseId=N,n+=" } ",A&&(n+=" if ("+p+") { ",h+="}"))}return A&&(n+=" "+h+" if ("+u+" == errors) {"),n},_enum=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="valid"+i,d=e.opts.$data&&s&&s.$data;d&&(n+=" var schema"+i+" = "+e.util.getData(s.$data,o,e.dataPathArr)+"; ");var h="i"+i,p="schema"+i;d||(n+=" var "+p+" = validate.schema"+a+";"),n+="var "+u+";",d&&(n+=" if (schema"+i+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+i+")) "+u+" = false; else {"),n+=u+" = false;for (var "+h+"=0; "+h+"<"+p+".length; "+h+"++) if (equal("+l+", "+p+"["+h+"])) { "+u+" = true; break; }",d&&(n+=" } "),n+=" if (!"+u+") { ";var g=g||[];g.push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+i+" } ",!1!==e.opts.messages&&(n+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var f=n;return n=g.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+f+"]); ":n+=" validate.errors = ["+f+"]; return false; ":n+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",A&&(n+=" else { "),n},format$5=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||"");if(!1===e.opts.format)return A&&(n+=" if (true) { "),n;var u,d=e.opts.$data&&s&&s.$data;d?(n+=" var schema"+i+" = "+e.util.getData(s.$data,o,e.dataPathArr)+"; ",u="schema"+i):u=s;var h=e.opts.unknownFormats,p=Array.isArray(h);if(d){n+=" var "+(g="format"+i)+" = formats["+u+"]; var "+(f="isObject"+i)+" = typeof "+g+" == 'object' && !("+g+" instanceof RegExp) && "+g+".validate; var "+(m="formatType"+i)+" = "+f+" && "+g+".type || 'string'; if ("+f+") { ",e.async&&(n+=" var async"+i+" = "+g+".async; "),n+=" "+g+" = "+g+".validate; } if ( ",d&&(n+=" ("+u+" !== undefined && typeof "+u+" != 'string') || "),n+=" (","ignore"!=h&&(n+=" ("+u+" && !"+g+" ",p&&(n+=" && self._opts.unknownFormats.indexOf("+u+") == -1 "),n+=") || "),n+=" ("+g+" && "+m+" == '"+r+"' && !(typeof "+g+" == 'function' ? ",e.async?n+=" (async"+i+" ? await "+g+"("+l+") : "+g+"("+l+")) ":n+=" "+g+"("+l+") ",n+=" : "+g+".test("+l+"))))) {"}else{var g;if(!(g=e.formats[s])){if("ignore"==h)return e.logger.warn('unknown format "'+s+'" ignored in schema at path "'+e.errSchemaPath+'"'),A&&(n+=" if (true) { "),n;if(p&&h.indexOf(s)>=0)return A&&(n+=" if (true) { "),n;throw new Error('unknown format "'+s+'" is used in schema at path "'+e.errSchemaPath+'"')}var f,m=(f="object"==typeof g&&!(g instanceof RegExp)&&g.validate)&&g.type||"string";if(f){var E=!0===g.async;g=g.validate}if(m!=r)return A&&(n+=" if (true) { "),n;if(E){if(!e.async)throw new Error("async format in sync schema");n+=" if (!(await "+(C="formats"+e.util.getProperty(s)+".validate")+"("+l+"))) { "}else{n+=" if (! ";var C="formats"+e.util.getProperty(s);f&&(C+=".validate"),n+="function"==typeof g?" "+C+"("+l+") ":" "+C+".test("+l+") ",n+=") { "}}var I=I||[];I.push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",n+=d?""+u:""+e.util.toQuotedString(s),n+=" } ",!1!==e.opts.messages&&(n+=" , message: 'should match format \"",n+=d?"' + "+u+" + '":""+e.util.escapeQuotes(s),n+="\"' "),e.opts.verbose&&(n+=" , schema: ",n+=d?"validate.schema"+a:""+e.util.toQuotedString(s),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var y=n;return n=I.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+y+"]); ":n+=" validate.errors = ["+y+"]; return false; ":n+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",A&&(n+=" else { "),n},_if=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="valid"+i,d="errs__"+i,h=e.util.copy(e);h.level++;var p="valid"+h.level,g=e.schema.then,f=e.schema.else,m=void 0!==g&&(e.opts.strictKeywords?"object"==typeof g&&Object.keys(g).length>0||!1===g:e.util.schemaHasRules(g,e.RULES.all)),E=void 0!==f&&(e.opts.strictKeywords?"object"==typeof f&&Object.keys(f).length>0||!1===f:e.util.schemaHasRules(f,e.RULES.all)),C=h.baseId;if(m||E){var I;h.createErrors=!1,h.schema=s,h.schemaPath=a,h.errSchemaPath=c,n+=" var "+d+" = errors; var "+u+" = true; ";var y=e.compositeRule;e.compositeRule=h.compositeRule=!0,n+=" "+e.validate(h)+" ",h.baseId=C,h.createErrors=!0,n+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.compositeRule=h.compositeRule=y,m?(n+=" if ("+p+") { ",h.schema=e.schema.then,h.schemaPath=e.schemaPath+".then",h.errSchemaPath=e.errSchemaPath+"/then",n+=" "+e.validate(h)+" ",h.baseId=C,n+=" "+u+" = "+p+"; ",m&&E?n+=" var "+(I="ifClause"+i)+" = 'then'; ":I="'then'",n+=" } ",E&&(n+=" else { ")):n+=" if (!"+p+") { ",E&&(h.schema=e.schema.else,h.schemaPath=e.schemaPath+".else",h.errSchemaPath=e.errSchemaPath+"/else",n+=" "+e.validate(h)+" ",h.baseId=C,n+=" "+u+" = "+p+"; ",m&&E?n+=" var "+(I="ifClause"+i)+" = 'else'; ":I="'else'",n+=" } "),n+=" if (!"+u+") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+I+" } ",!1!==e.opts.messages&&(n+=" , message: 'should match \"' + "+I+" + '\" schema' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&A&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } ",A&&(n+=" else { ")}else A&&(n+=" if (true) { ");return n},items=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="valid"+i,d="errs__"+i,h=e.util.copy(e),p="";h.level++;var g="valid"+h.level,f="i"+i,m=h.dataLevel=e.dataLevel+1,E="data"+m,C=e.baseId;if(n+="var "+d+" = errors;var "+u+";",Array.isArray(s)){var I=e.schema.additionalItems;if(!1===I){n+=" "+u+" = "+l+".length <= "+s.length+"; ";var y=c;c=e.errSchemaPath+"/additionalItems",n+=" if (!"+u+") { ";var B=B||[];B.push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+s.length+" } ",!1!==e.opts.messages&&(n+=" , message: 'should NOT have more than "+s.length+" items' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var b=n;n=B.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+b+"]); ":n+=" validate.errors = ["+b+"]; return false; ":n+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",c=y,A&&(p+="}",n+=" else { ")}var w=s;if(w)for(var v,S=-1,Q=w.length-1;S<Q;)if(v=w[S+=1],e.opts.strictKeywords?"object"==typeof v&&Object.keys(v).length>0||!1===v:e.util.schemaHasRules(v,e.RULES.all)){n+=" "+g+" = true; if ("+l+".length > "+S+") { ";var _=l+"["+S+"]";h.schema=v,h.schemaPath=a+"["+S+"]",h.errSchemaPath=c+"/"+S,h.errorPath=e.util.getPathExpr(e.errorPath,S,e.opts.jsonPointers,!0),h.dataPathArr[m]=S;var D=e.validate(h);h.baseId=C,e.util.varOccurences(D,E)<2?n+=" "+e.util.varReplace(D,E,_)+" ":n+=" var "+E+" = "+_+"; "+D+" ",n+=" } ",A&&(n+=" if ("+g+") { ",p+="}")}if("object"==typeof I&&(e.opts.strictKeywords?"object"==typeof I&&Object.keys(I).length>0||!1===I:e.util.schemaHasRules(I,e.RULES.all))){h.schema=I,h.schemaPath=e.schemaPath+".additionalItems",h.errSchemaPath=e.errSchemaPath+"/additionalItems",n+=" "+g+" = true; if ("+l+".length > "+s.length+") { for (var "+f+" = "+s.length+"; "+f+" < "+l+".length; "+f+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers,!0);_=l+"["+f+"]";h.dataPathArr[m]=f;D=e.validate(h);h.baseId=C,e.util.varOccurences(D,E)<2?n+=" "+e.util.varReplace(D,E,_)+" ":n+=" var "+E+" = "+_+"; "+D+" ",A&&(n+=" if (!"+g+") break; "),n+=" } } ",A&&(n+=" if ("+g+") { ",p+="}")}}else if(e.opts.strictKeywords?"object"==typeof s&&Object.keys(s).length>0||!1===s:e.util.schemaHasRules(s,e.RULES.all)){h.schema=s,h.schemaPath=a,h.errSchemaPath=c,n+=" for (var "+f+" = 0; "+f+" < "+l+".length; "+f+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers,!0);_=l+"["+f+"]";h.dataPathArr[m]=f;D=e.validate(h);h.baseId=C,e.util.varOccurences(D,E)<2?n+=" "+e.util.varReplace(D,E,_)+" ":n+=" var "+E+" = "+_+"; "+D+" ",A&&(n+=" if (!"+g+") break; "),n+=" }"}return A&&(n+=" "+p+" if ("+d+" == errors) {"),n},_limit=function(e,t,r){var n,i=" ",o=e.level,s=e.dataLevel,a=e.schema[t],c=e.schemaPath+e.util.getProperty(t),A=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(s||""),d=e.opts.$data&&a&&a.$data;d?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",n="schema"+o):n=a;var h="maximum"==t,p=h?"exclusiveMaximum":"exclusiveMinimum",g=e.schema[p],f=e.opts.$data&&g&&g.$data,m=h?"<":">",E=h?">":"<",C=void 0;if(!d&&"number"!=typeof a&&void 0!==a)throw new Error(t+" must be number");if(!f&&void 0!==g&&"number"!=typeof g&&"boolean"!=typeof g)throw new Error(p+" must be number or boolean");if(f){var I=e.util.getData(g.$data,s,e.dataPathArr),y="exclusive"+o,B="exclType"+o,b="exclIsNumber"+o,w="' + "+(Q="op"+o)+" + '";i+=" var schemaExcl"+o+" = "+I+"; ",i+=" var "+y+"; var "+B+" = typeof "+(I="schemaExcl"+o)+"; if ("+B+" != 'boolean' && "+B+" != 'undefined' && "+B+" != 'number') { ";var v;C=p;(v=v||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(C||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(A)+" , params: {} ",!1!==e.opts.messages&&(i+=" , message: '"+p+" should be boolean' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var S=i;i=v.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+S+"]); ":i+=" validate.errors = ["+S+"]; return false; ":i+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else if ( ",d&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),i+=" "+B+" == 'number' ? ( ("+y+" = "+n+" === undefined || "+I+" "+m+"= "+n+") ? "+u+" "+E+"= "+I+" : "+u+" "+E+" "+n+" ) : ( ("+y+" = "+I+" === true) ? "+u+" "+E+"= "+n+" : "+u+" "+E+" "+n+" ) || "+u+" !== "+u+") { var op"+o+" = "+y+" ? '"+m+"' : '"+m+"='; ",void 0===a&&(C=p,A=e.errSchemaPath+"/"+p,n=I,d=f)}else{w=m;if((b="number"==typeof g)&&d){var Q="'"+w+"'";i+=" if ( ",d&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),i+=" ( "+n+" === undefined || "+g+" "+m+"= "+n+" ? "+u+" "+E+"= "+g+" : "+u+" "+E+" "+n+" ) || "+u+" !== "+u+") { "}else{b&&void 0===a?(y=!0,C=p,A=e.errSchemaPath+"/"+p,n=g,E+="="):(b&&(n=Math[h?"min":"max"](g,a)),g===(!b||n)?(y=!0,C=p,A=e.errSchemaPath+"/"+p,E+="="):(y=!1,w+="="));Q="'"+w+"'";i+=" if ( ",d&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),i+=" "+u+" "+E+" "+n+" || "+u+" !== "+u+") { "}}C=C||t,(v=v||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(C||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(A)+" , params: { comparison: "+Q+", limit: "+n+", exclusive: "+y+" } ",!1!==e.opts.messages&&(i+=" , message: 'should be "+w+" ",i+=d?"' + "+n:n+"'"),e.opts.verbose&&(i+=" , schema: ",i+=d?"validate.schema"+c:""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";S=i;return i=v.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+S+"]); ":i+=" validate.errors = ["+S+"]; return false; ":i+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",l&&(i+=" else { "),i},_limitItems=function(e,t,r){var n,i=" ",o=e.level,s=e.dataLevel,a=e.schema[t],c=e.schemaPath+e.util.getProperty(t),A=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(s||""),d=e.opts.$data&&a&&a.$data;if(d?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",n="schema"+o):n=a,!d&&"number"!=typeof a)throw new Error(t+" must be number");i+="if ( ",d&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),i+=" "+u+".length "+("maxItems"==t?">":"<")+" "+n+") { ";var h=t,p=p||[];p.push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(h||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(A)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have ",i+="maxItems"==t?"more":"fewer",i+=" than ",i+=d?"' + "+n+" + '":""+a,i+=" items' "),e.opts.verbose&&(i+=" , schema: ",i+=d?"validate.schema"+c:""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var g=i;return i=p.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+g+"]); ":i+=" validate.errors = ["+g+"]; return false; ":i+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i},_limitLength=function(e,t,r){var n,i=" ",o=e.level,s=e.dataLevel,a=e.schema[t],c=e.schemaPath+e.util.getProperty(t),A=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(s||""),d=e.opts.$data&&a&&a.$data;if(d?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",n="schema"+o):n=a,!d&&"number"!=typeof a)throw new Error(t+" must be number");var h="maxLength"==t?">":"<";i+="if ( ",d&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),!1===e.opts.unicode?i+=" "+u+".length ":i+=" ucs2length("+u+") ",i+=" "+h+" "+n+") { ";var p=t,g=g||[];g.push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(p||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(A)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT be ",i+="maxLength"==t?"longer":"shorter",i+=" than ",i+=d?"' + "+n+" + '":""+a,i+=" characters' "),e.opts.verbose&&(i+=" , schema: ",i+=d?"validate.schema"+c:""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var f=i;return i=g.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+f+"]); ":i+=" validate.errors = ["+f+"]; return false; ":i+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i},_limitProperties=function(e,t,r){var n,i=" ",o=e.level,s=e.dataLevel,a=e.schema[t],c=e.schemaPath+e.util.getProperty(t),A=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(s||""),d=e.opts.$data&&a&&a.$data;if(d?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",n="schema"+o):n=a,!d&&"number"!=typeof a)throw new Error(t+" must be number");i+="if ( ",d&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),i+=" Object.keys("+u+").length "+("maxProperties"==t?">":"<")+" "+n+") { ";var h=t,p=p||[];p.push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(h||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(A)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have ",i+="maxProperties"==t?"more":"fewer",i+=" than ",i+=d?"' + "+n+" + '":""+a,i+=" properties' "),e.opts.verbose&&(i+=" , schema: ",i+=d?"validate.schema"+c:""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var g=i;return i=p.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+g+"]); ":i+=" validate.errors = ["+g+"]; return false; ":i+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i},multipleOf=function(e,t,r){var n,i=" ",o=e.level,s=e.dataLevel,a=e.schema[t],c=e.schemaPath+e.util.getProperty(t),A=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(s||""),d=e.opts.$data&&a&&a.$data;if(d?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",n="schema"+o):n=a,!d&&"number"!=typeof a)throw new Error(t+" must be number");i+="var division"+o+";if (",d&&(i+=" "+n+" !== undefined && ( typeof "+n+" != 'number' || "),i+=" (division"+o+" = "+u+" / "+n+", ",e.opts.multipleOfPrecision?i+=" Math.abs(Math.round(division"+o+") - division"+o+") > 1e-"+e.opts.multipleOfPrecision+" ":i+=" division"+o+" !== parseInt(division"+o+") ",i+=" ) ",d&&(i+=" ) "),i+=" ) { ";var h=h||[];h.push(i),i="",!1!==e.createErrors?(i+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(A)+" , params: { multipleOf: "+n+" } ",!1!==e.opts.messages&&(i+=" , message: 'should be multiple of ",i+=d?"' + "+n:n+"'"),e.opts.verbose&&(i+=" , schema: ",i+=d?"validate.schema"+c:""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var p=i;return i=h.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+p+"]); ":i+=" validate.errors = ["+p+"]; return false; ":i+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i},not=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="errs__"+i,d=e.util.copy(e);d.level++;var h="valid"+d.level;if(e.opts.strictKeywords?"object"==typeof s&&Object.keys(s).length>0||!1===s:e.util.schemaHasRules(s,e.RULES.all)){d.schema=s,d.schemaPath=a,d.errSchemaPath=c,n+=" var "+u+" = errors; ";var p,g=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.createErrors=!1,d.opts.allErrors&&(p=d.opts.allErrors,d.opts.allErrors=!1),n+=" "+e.validate(d)+" ",d.createErrors=!0,p&&(d.opts.allErrors=p),e.compositeRule=d.compositeRule=g,n+=" if ("+h+") { ";var f=f||[];f.push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var m=n;n=f.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+m+"]); ":n+=" validate.errors = ["+m+"]; return false; ":n+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { errors = "+u+"; if (vErrors !== null) { if ("+u+") vErrors.length = "+u+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else n+=" var err = ",!1!==e.createErrors?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",A&&(n+=" if (false) { ");return n},oneOf=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="valid"+i,d="errs__"+i,h=e.util.copy(e),p="";h.level++;var g="valid"+h.level,f=h.baseId,m="prevValid"+i,E="passingSchemas"+i;n+="var "+d+" = errors , "+m+" = false , "+u+" = false , "+E+" = null; ";var C=e.compositeRule;e.compositeRule=h.compositeRule=!0;var I=s;if(I)for(var y,B=-1,b=I.length-1;B<b;)y=I[B+=1],(e.opts.strictKeywords?"object"==typeof y&&Object.keys(y).length>0||!1===y:e.util.schemaHasRules(y,e.RULES.all))?(h.schema=y,h.schemaPath=a+"["+B+"]",h.errSchemaPath=c+"/"+B,n+=" "+e.validate(h)+" ",h.baseId=f):n+=" var "+g+" = true; ",B&&(n+=" if ("+g+" && "+m+") { "+u+" = false; "+E+" = ["+E+", "+B+"]; } else { ",p+="}"),n+=" if ("+g+") { "+u+" = "+m+" = true; "+E+" = "+B+"; }";return e.compositeRule=h.compositeRule=C,n+=p+"if (!"+u+") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+E+" } ",!1!==e.opts.messages&&(n+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&A&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+="} else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; }",e.opts.allErrors&&(n+=" } "),n},pattern=function(e,t,r){var n,i=" ",o=e.level,s=e.dataLevel,a=e.schema[t],c=e.schemaPath+e.util.getProperty(t),A=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(s||""),d=e.opts.$data&&a&&a.$data;d?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",n="schema"+o):n=a,i+="if ( ",d&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'string') || "),i+=" !"+(d?"(new RegExp("+n+"))":e.usePattern(a))+".test("+u+") ) { ";var h=h||[];h.push(i),i="",!1!==e.createErrors?(i+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(A)+" , params: { pattern: ",i+=d?""+n:""+e.util.toQuotedString(a),i+=" } ",!1!==e.opts.messages&&(i+=" , message: 'should match pattern \"",i+=d?"' + "+n+" + '":""+e.util.escapeQuotes(a),i+="\"' "),e.opts.verbose&&(i+=" , schema: ",i+=d?"validate.schema"+c:""+e.util.toQuotedString(a),i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var p=i;return i=h.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+p+"]); ":i+=" validate.errors = ["+p+"]; return false; ":i+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i},properties$2=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="errs__"+i,d=e.util.copy(e),h="";d.level++;var p="valid"+d.level,g="key"+i,f="idx"+i,m=d.dataLevel=e.dataLevel+1,E="data"+m,C="dataProperties"+i,I=Object.keys(s||{}).filter(T),y=e.schema.patternProperties||{},B=Object.keys(y).filter(T),b=e.schema.additionalProperties,w=I.length||B.length,v=!1===b,S="object"==typeof b&&Object.keys(b).length,Q=e.opts.removeAdditional,_=v||S||Q,D=e.opts.ownProperties,x=e.baseId,k=e.schema.required;if(k&&(!e.opts.$data||!k.$data)&&k.length<e.opts.loopRequired)var R=e.util.toHash(k);function T(e){return"__proto__"!==e}if(n+="var "+u+" = errors;var "+p+" = true;",D&&(n+=" var "+C+" = undefined;"),_){if(n+=D?" "+C+" = "+C+" || Object.keys("+l+"); for (var "+f+"=0; "+f+"<"+C+".length; "+f+"++) { var "+g+" = "+C+"["+f+"]; ":" for (var "+g+" in "+l+") { ",w){if(n+=" var isAdditional"+i+" = !(false ",I.length)if(I.length>8)n+=" || validate.schema"+a+".hasOwnProperty("+g+") ";else{var $=I;if($)for(var N=-1,F=$.length-1;N<F;)Y=$[N+=1],n+=" || "+g+" == "+e.util.toQuotedString(Y)+" "}if(B.length){var M=B;if(M)for(var P=-1,L=M.length-1;P<L;)oe=M[P+=1],n+=" || "+e.usePattern(oe)+".test("+g+") "}n+=" ); if (isAdditional"+i+") { "}if("all"==Q)n+=" delete "+l+"["+g+"]; ";else{var O=e.errorPath,U="' + "+g+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers)),v)if(Q)n+=" delete "+l+"["+g+"]; ";else{n+=" "+p+" = false; ";var G=c;c=e.errSchemaPath+"/additionalProperties",(re=re||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+U+"' } ",!1!==e.opts.messages&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is an invalid additional property":n+="should NOT have additional properties",n+="' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var H=n;n=re.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+H+"]); ":n+=" validate.errors = ["+H+"]; return false; ":n+=" var err = "+H+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=G,A&&(n+=" break; ")}else if(S)if("failing"==Q){n+=" var "+u+" = errors; ";var j=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.schema=b,d.schemaPath=e.schemaPath+".additionalProperties",d.errSchemaPath=e.errSchemaPath+"/additionalProperties",d.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers);var q=l+"["+g+"]";d.dataPathArr[m]=g;var K=e.validate(d);d.baseId=x,e.util.varOccurences(K,E)<2?n+=" "+e.util.varReplace(K,E,q)+" ":n+=" var "+E+" = "+q+"; "+K+" ",n+=" if (!"+p+") { errors = "+u+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+l+"["+g+"]; } ",e.compositeRule=d.compositeRule=j}else{d.schema=b,d.schemaPath=e.schemaPath+".additionalProperties",d.errSchemaPath=e.errSchemaPath+"/additionalProperties",d.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers);q=l+"["+g+"]";d.dataPathArr[m]=g;K=e.validate(d);d.baseId=x,e.util.varOccurences(K,E)<2?n+=" "+e.util.varReplace(K,E,q)+" ":n+=" var "+E+" = "+q+"; "+K+" ",A&&(n+=" if (!"+p+") break; ")}e.errorPath=O}w&&(n+=" } "),n+=" } ",A&&(n+=" if ("+p+") { ",h+="}")}var W=e.opts.useDefaults&&!e.compositeRule;if(I.length){var J=I;if(J)for(var Y,z=-1,V=J.length-1;z<V;){var X=s[Y=J[z+=1]];if(e.opts.strictKeywords?"object"==typeof X&&Object.keys(X).length>0||!1===X:e.util.schemaHasRules(X,e.RULES.all)){var Z=e.util.getProperty(Y),ee=(q=l+Z,W&&void 0!==X.default);d.schema=X,d.schemaPath=a+Z,d.errSchemaPath=c+"/"+e.util.escapeFragment(Y),d.errorPath=e.util.getPath(e.errorPath,Y,e.opts.jsonPointers),d.dataPathArr[m]=e.util.toQuotedString(Y);K=e.validate(d);if(d.baseId=x,e.util.varOccurences(K,E)<2){K=e.util.varReplace(K,E,q);var te=q}else{te=E;n+=" var "+E+" = "+q+"; "}if(ee)n+=" "+K+" ";else{if(R&&R[Y]){n+=" if ( "+te+" === undefined ",D&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(Y)+"') "),n+=") { "+p+" = false; ";O=e.errorPath,G=c;var re,ne=e.util.escapeQuotes(Y);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(O,Y,e.opts.jsonPointers)),c=e.errSchemaPath+"/required",(re=re||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+ne+"' } ",!1!==e.opts.messages&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+ne+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";H=n;n=re.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+H+"]); ":n+=" validate.errors = ["+H+"]; return false; ":n+=" var err = "+H+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=G,e.errorPath=O,n+=" } else { "}else A?(n+=" if ( "+te+" === undefined ",D&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(Y)+"') "),n+=") { "+p+" = true; } else { "):(n+=" if ("+te+" !== undefined ",D&&(n+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(Y)+"') "),n+=" ) { ");n+=" "+K+" } "}}A&&(n+=" if ("+p+") { ",h+="}")}}if(B.length){var ie=B;if(ie)for(var oe,se=-1,ae=ie.length-1;se<ae;){X=y[oe=ie[se+=1]];if(e.opts.strictKeywords?"object"==typeof X&&Object.keys(X).length>0||!1===X:e.util.schemaHasRules(X,e.RULES.all)){d.schema=X,d.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(oe),d.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(oe),n+=D?" "+C+" = "+C+" || Object.keys("+l+"); for (var "+f+"=0; "+f+"<"+C+".length; "+f+"++) { var "+g+" = "+C+"["+f+"]; ":" for (var "+g+" in "+l+") { ",n+=" if ("+e.usePattern(oe)+".test("+g+")) { ",d.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers);q=l+"["+g+"]";d.dataPathArr[m]=g;K=e.validate(d);d.baseId=x,e.util.varOccurences(K,E)<2?n+=" "+e.util.varReplace(K,E,q)+" ":n+=" var "+E+" = "+q+"; "+K+" ",A&&(n+=" if (!"+p+") break; "),n+=" } ",A&&(n+=" else "+p+" = true; "),n+=" } ",A&&(n+=" if ("+p+") { ",h+="}")}}}return A&&(n+=" "+h+" if ("+u+" == errors) {"),n},propertyNames=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="errs__"+i,d=e.util.copy(e);d.level++;var h="valid"+d.level;if(n+="var "+u+" = errors;",e.opts.strictKeywords?"object"==typeof s&&Object.keys(s).length>0||!1===s:e.util.schemaHasRules(s,e.RULES.all)){d.schema=s,d.schemaPath=a,d.errSchemaPath=c;var p="key"+i,g="idx"+i,f="i"+i,m="' + "+p+" + '",E="data"+(d.dataLevel=e.dataLevel+1),C="dataProperties"+i,I=e.opts.ownProperties,y=e.baseId;I&&(n+=" var "+C+" = undefined; "),n+=I?" "+C+" = "+C+" || Object.keys("+l+"); for (var "+g+"=0; "+g+"<"+C+".length; "+g+"++) { var "+p+" = "+C+"["+g+"]; ":" for (var "+p+" in "+l+") { ",n+=" var startErrs"+i+" = errors; ";var B=p,b=e.compositeRule;e.compositeRule=d.compositeRule=!0;var w=e.validate(d);d.baseId=y,e.util.varOccurences(w,E)<2?n+=" "+e.util.varReplace(w,E,B)+" ":n+=" var "+E+" = "+B+"; "+w+" ",e.compositeRule=d.compositeRule=b,n+=" if (!"+h+") { for (var "+f+"=startErrs"+i+"; "+f+"<errors; "+f+"++) { vErrors["+f+"].propertyName = "+p+"; } var err = ",!1!==e.createErrors?(n+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+m+"' } ",!1!==e.opts.messages&&(n+=" , message: 'property name \\'"+m+"\\' is invalid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&A&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),A&&(n+=" break; "),n+=" } }"}return A&&(n+=" if ("+u+" == errors) {"),n},required$1=function(e,t,r){var n=" ",i=e.level,o=e.dataLevel,s=e.schema[t],a=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,A=!e.opts.allErrors,l="data"+(o||""),u="valid"+i,d=e.opts.$data&&s&&s.$data;d&&(n+=" var schema"+i+" = "+e.util.getData(s.$data,o,e.dataPathArr)+"; ");var h="schema"+i;if(!d)if(s.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var p=[],g=s;if(g)for(var f,m=-1,E=g.length-1;m<E;){f=g[m+=1];var C=e.schema.properties[f];C&&(e.opts.strictKeywords?"object"==typeof C&&Object.keys(C).length>0||!1===C:e.util.schemaHasRules(C,e.RULES.all))||(p[p.length]=f)}}else p=s;if(d||p.length){var I=e.errorPath,y=d||p.length>=e.opts.loopRequired,B=e.opts.ownProperties;if(A)if(n+=" var missing"+i+"; ",y){d||(n+=" var "+h+" = validate.schema"+a+"; ");var b="' + "+(D="schema"+i+"["+(S="i"+i)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(I,D,e.opts.jsonPointers)),n+=" var "+u+" = true; ",d&&(n+=" if (schema"+i+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+i+")) "+u+" = false; else {"),n+=" for (var "+S+" = 0; "+S+" < "+h+".length; "+S+"++) { "+u+" = "+l+"["+h+"["+S+"]] !== undefined ",B&&(n+=" && Object.prototype.hasOwnProperty.call("+l+", "+h+"["+S+"]) "),n+="; if (!"+u+") break; } ",d&&(n+=" } "),n+=" if (!"+u+") { ",(_=_||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+b+"' } ",!1!==e.opts.messages&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+b+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var w=n;n=_.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+w+"]); ":n+=" validate.errors = ["+w+"]; return false; ":n+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else{n+=" if ( ";var v=p;if(v)for(var S=-1,Q=v.length-1;S<Q;){k=v[S+=1],S&&(n+=" || "),n+=" ( ( "+(N=l+($=e.util.getProperty(k)))+" === undefined ",B&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(k)+"') "),n+=") && (missing"+i+" = "+e.util.toQuotedString(e.opts.jsonPointers?k:$)+") ) "}n+=") { ";var _;b="' + "+(D="missing"+i)+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(I,D,!0):I+" + "+D),(_=_||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+b+"' } ",!1!==e.opts.messages&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+b+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";w=n;n=_.pop(),!e.compositeRule&&A?e.async?n+=" throw new ValidationError(["+w+"]); ":n+=" validate.errors = ["+w+"]; return false; ":n+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else if(y){d||(n+=" var "+h+" = validate.schema"+a+"; ");var D;b="' + "+(D="schema"+i+"["+(S="i"+i)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(I,D,e.opts.jsonPointers)),d&&(n+=" if ("+h+" && !Array.isArray("+h+")) { var err = ",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+b+"' } ",!1!==e.opts.messages&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+b+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+h+" !== undefined) { "),n+=" for (var "+S+" = 0; "+S+" < "+h+".length; "+S+"++) { if ("+l+"["+h+"["+S+"]] === undefined ",B&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", "+h+"["+S+"]) "),n+=") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+b+"' } ",!1!==e.opts.messages&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+b+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",d&&(n+=" } ")}else{var x=p;if(x)for(var k,R=-1,T=x.length-1;R<T;){k=x[R+=1];var $=e.util.getProperty(k),N=(b=e.util.escapeQuotes(k),l+$);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(I,k,e.opts.jsonPointers)),n+=" if ( "+N+" === undefined ",B&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(k)+"') "),n+=") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+b+"' } ",!1!==e.opts.messages&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+b+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+a+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=I}else A&&(n+=" if (true) {");return n},uniqueItems=function(e,t,r){var n,i=" ",o=e.level,s=e.dataLevel,a=e.schema[t],c=e.schemaPath+e.util.getProperty(t),A=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(s||""),d="valid"+o,h=e.opts.$data&&a&&a.$data;if(h?(i+=" var schema"+o+" = "+e.util.getData(a.$data,s,e.dataPathArr)+"; ",n="schema"+o):n=a,(a||h)&&!1!==e.opts.uniqueItems){h&&(i+=" var "+d+"; if ("+n+" === false || "+n+" === undefined) "+d+" = true; else if (typeof "+n+" != 'boolean') "+d+" = false; else { "),i+=" var i = "+u+".length , "+d+" = true , j; if (i > 1) { ";var p=e.schema.items&&e.schema.items.type,g=Array.isArray(p);if(!p||"object"==p||"array"==p||g&&(p.indexOf("object")>=0||p.indexOf("array")>=0))i+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+u+"[i], "+u+"[j])) { "+d+" = false; break outer; } } } ";else{i+=" var itemIndices = {}, item; for (;i--;) { var item = "+u+"[i]; ";var f="checkDataType"+(g?"s":"");i+=" if ("+e.util[f](p,"item",e.opts.strictNumbers,!0)+") continue; ",g&&(i+=" if (typeof item == 'string') item = '\"' + item; "),i+=" if (typeof itemIndices[item] == 'number') { "+d+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}i+=" } ",h&&(i+=" } "),i+=" if (!"+d+") { ";var m=m||[];m.push(i),i="",!1!==e.createErrors?(i+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(A)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+a,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var E=i;i=m.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+E+"]); ":i+=" validate.errors = ["+E+"]; return false; ":i+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",l&&(i+=" else { ")}else l&&(i+=" if (true) { ");return i},dotjs={$ref:ref,allOf:allOf,anyOf:anyOf,$comment:comment,const:_const,contains:contains,dependencies:dependencies,enum:_enum,format:format$5,if:_if,items:items,maximum:_limit,minimum:_limit,maxItems:_limitItems,minItems:_limitItems,maxLength:_limitLength,minLength:_limitLength,maxProperties:_limitProperties,minProperties:_limitProperties,multipleOf:multipleOf,not:not,oneOf:oneOf,pattern:pattern,properties:properties$2,propertyNames:propertyNames,required:required$1,uniqueItems:uniqueItems,validate:validate$1},ruleModules=dotjs,toHash=util$7.toHash,rules$1=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],t=["type","$comment"];return e.all=toHash(t),e.types=toHash(["number","integer","string","array","object","boolean","null"]),e.forEach((function(r){r.rules=r.rules.map((function(r){var n;if("object"==typeof r){var i=Object.keys(r)[0];n=r[i],r=i,n.forEach((function(r){t.push(r),e.all[r]=!0}))}return t.push(r),e.all[r]={keyword:r,code:ruleModules[r],implements:n}})),e.all.$comment={keyword:"$comment",code:ruleModules.$comment},r.type&&(e.types[r.type]=r)})),e.keywords=toHash(t.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),e.custom={},e},KEYWORDS=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],data=function(e,t){for(var r=0;r<t.length;r++){e=JSON.parse(JSON.stringify(e));var n,i=t[r].split("/"),o=e;for(n=1;n<i.length;n++)o=o[i[n]];for(n=0;n<KEYWORDS.length;n++){var s=KEYWORDS[n],a=o[s];a&&(o[s]={anyOf:[a,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return e},MissingRefError=error_classes.MissingRef,async=compileAsync;function compileAsync(e,t,r){var n=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof t&&(r=t,t=void 0);var i=o(e).then((function(){var r=n._addSchema(e,void 0,t);return r.validate||s(r)}));return r&&i.then((function(e){r(null,e)}),r),i;function o(e){var t=e.$schema;return t&&!n.getSchema(t)?compileAsync.call(n,{$ref:t},!0):Promise.resolve()}function s(e){try{return n._compile(e)}catch(r){if(r instanceof MissingRefError)return function(r){var i=r.missingSchema;if(A(i))throw new Error("Schema "+i+" is loaded but "+r.missingRef+" cannot be resolved");var a=n._loadingSchemas[i];a||(a=n._loadingSchemas[i]=n._opts.loadSchema(i)).then(c,c);return a.then((function(e){if(!A(i))return o(e).then((function(){A(i)||n.addSchema(e,i,void 0,t)}))})).then((function(){return s(e)}));function c(){delete n._loadingSchemas[i]}function A(e){return n._refs[e]||n._schemas[e]}}(r);throw r}}}var custom=function(e,t,r){var n,i,o=" ",s=e.level,a=e.dataLevel,c=e.schema[t],A=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,d="data"+(a||""),h="valid"+s,p="errs__"+s,g=e.opts.$data&&c&&c.$data;g?(o+=" var schema"+s+" = "+e.util.getData(c.$data,a,e.dataPathArr)+"; ",i="schema"+s):i=c;var f,m,E,C,I,y=this,B="definition"+s,b=y.definition,w="";if(g&&b.$data){I="keywordValidate"+s;var v=b.validateSchema;o+=" var "+B+" = RULES.custom['"+t+"'].definition; var "+I+" = "+B+".validate;"}else{if(!(C=e.useCustomRule(y,c,e.schema,e)))return;i="validate.schema"+A,I=C.code,f=b.compile,m=b.inline,E=b.macro}var S=I+".errors",Q="i"+s,_="ruleErr"+s,D=b.async;if(D&&!e.async)throw new Error("async keyword in sync schema");if(m||E||(o+=S+" = null;"),o+="var "+p+" = errors;var "+h+";",g&&b.$data&&(w+="}",o+=" if ("+i+" === undefined) { "+h+" = true; } else { ",v&&(w+="}",o+=" "+h+" = "+B+".validateSchema("+i+"); if ("+h+") { ")),m)b.statements?o+=" "+C.validate+" ":o+=" "+h+" = "+C.validate+"; ";else if(E){var x=e.util.copy(e);w="";x.level++;var k="valid"+x.level;x.schema=C.validate,x.schemaPath="";var R=e.compositeRule;e.compositeRule=x.compositeRule=!0;var T=e.validate(x).replace(/validate\.schema/g,I);e.compositeRule=x.compositeRule=R,o+=" "+T}else{(M=M||[]).push(o),o="",o+=" "+I+".call( ",e.opts.passContext?o+="this":o+="self",f||!1===b.schema?o+=" , "+d+" ":o+=" , "+i+" , "+d+" , validate.schema"+e.schemaPath+" ",o+=" , (dataPath || '')",'""'!=e.errorPath&&(o+=" + "+e.errorPath);var $=a?"data"+(a-1||""):"parentData",N=a?e.dataPathArr[a]:"parentDataProperty",F=o+=" , "+$+" , "+N+" , rootData ) ";o=M.pop(),!1===b.errors?(o+=" "+h+" = ",D&&(o+="await "),o+=F+"; "):o+=D?" var "+(S="customErrors"+s)+" = null; try { "+h+" = await "+F+"; } catch (e) { "+h+" = false; if (e instanceof ValidationError) "+S+" = e.errors; else throw e; } ":" "+S+" = null; "+h+" = "+F+"; "}if(b.modifying&&(o+=" if ("+$+") "+d+" = "+$+"["+N+"];"),o+=""+w,b.valid)u&&(o+=" if (true) { ");else{var M;o+=" if ( ",void 0===b.valid?(o+=" !",o+=E?""+k:""+h):o+=" "+!b.valid+" ",o+=") { ",n=y.keyword,(M=M||[]).push(o),o="",(M=M||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '"+(n||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { keyword: '"+y.keyword+"' } ",!1!==e.opts.messages&&(o+=" , message: 'should pass \""+y.keyword+"\" keyword validation' "),e.opts.verbose&&(o+=" , schema: validate.schema"+A+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),o+=" } "):o+=" {} ";var P=o;o=M.pop(),!e.compositeRule&&u?e.async?o+=" throw new ValidationError(["+P+"]); ":o+=" validate.errors = ["+P+"]; return false; ":o+=" var err = "+P+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var L=o;o=M.pop(),m?b.errors?"full"!=b.errors&&(o+=" for (var "+Q+"="+p+"; "+Q+"<errors; "+Q+"++) { var "+_+" = vErrors["+Q+"]; if ("+_+".dataPath === undefined) "+_+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+_+".schemaPath === undefined) { "+_+'.schemaPath = "'+l+'"; } ',e.opts.verbose&&(o+=" "+_+".schema = "+i+"; "+_+".data = "+d+"; "),o+=" } "):!1===b.errors?o+=" "+L+" ":(o+=" if ("+p+" == errors) { "+L+" } else { for (var "+Q+"="+p+"; "+Q+"<errors; "+Q+"++) { var "+_+" = vErrors["+Q+"]; if ("+_+".dataPath === undefined) "+_+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+_+".schemaPath === undefined) { "+_+'.schemaPath = "'+l+'"; } ',e.opts.verbose&&(o+=" "+_+".schema = "+i+"; "+_+".data = "+d+"; "),o+=" } } "):E?(o+=" var err = ",!1!==e.createErrors?(o+=" { keyword: '"+(n||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { keyword: '"+y.keyword+"' } ",!1!==e.opts.messages&&(o+=" , message: 'should pass \""+y.keyword+"\" keyword validation' "),e.opts.verbose&&(o+=" , schema: validate.schema"+A+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),o+=" } "):o+=" {} ",o+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?o+=" throw new ValidationError(vErrors); ":o+=" validate.errors = vErrors; return false; ")):!1===b.errors?o+=" "+L+" ":(o+=" if (Array.isArray("+S+")) { if (vErrors === null) vErrors = "+S+"; else vErrors = vErrors.concat("+S+"); errors = vErrors.length; for (var "+Q+"="+p+"; "+Q+"<errors; "+Q+"++) { var "+_+" = vErrors["+Q+"]; if ("+_+".dataPath === undefined) "+_+".dataPath = (dataPath || '') + "+e.errorPath+"; "+_+'.schemaPath = "'+l+'"; ',e.opts.verbose&&(o+=" "+_+".schema = "+i+"; "+_+".data = "+d+"; "),o+=" } } else { "+L+" } "),o+=" } ",u&&(o+=" else { ")}return o},$schema$1="http://json-schema.org/draft-07/schema#",$id$1="http://json-schema.org/draft-07/schema#",title="Core schema meta-schema",definitions={schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type$1=["object","boolean"],properties$1={$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},require$$13={$schema:$schema$1,$id:$id$1,title:title,definitions:definitions,type:type$1,properties:properties$1,default:!0},metaSchema=require$$13,definition_schema={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:metaSchema.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:metaSchema.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},IDENTIFIER=/^[a-z_$][a-z0-9_$-]*$/i,customRuleCode=custom,definitionSchema=definition_schema,keyword={add:addKeyword,get:getKeyword,remove:removeKeyword,validate:validateKeyword};function addKeyword(e,t){var r=this.RULES;if(r.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!IDENTIFIER.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(t){this.validateKeyword(t,!0);var n=t.type;if(Array.isArray(n))for(var i=0;i<n.length;i++)s(e,n[i],t);else s(e,n,t);var o=t.metaSchema;o&&(t.$data&&this._opts.$data&&(o={anyOf:[o,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),t.validateSchema=this.compile(o,!0))}function s(e,t,n){for(var i,o=0;o<r.length;o++){var s=r[o];if(s.type==t){i=s;break}}i||(i={type:t,rules:[]},r.push(i));var a={keyword:e,definition:n,custom:!0,code:customRuleCode,implements:n.implements};i.rules.push(a),r.custom[e]=a}return r.keywords[e]=r.all[e]=!0,this}function getKeyword(e){var t=this.RULES.custom[e];return t?t.definition:this.RULES.keywords[e]||!1}function removeKeyword(e){var t=this.RULES;delete t.keywords[e],delete t.all[e],delete t.custom[e];for(var r=0;r<t.length;r++)for(var n=t[r].rules,i=0;i<n.length;i++)if(n[i].keyword==e){n.splice(i,1);break}return this}function validateKeyword(e,t){validateKeyword.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(definitionSchema,!0);if(r(e))return!0;if(validateKeyword.errors=r.errors,t)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}var $schema="http://json-schema.org/draft-07/schema#",$id="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description="Meta-schema for $data reference (JSON Schema extension proposal)",type="object",required=["$data"],properties={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties=!1,require$$12={$schema:$schema,$id:$id,description:description,type:type,required:required,properties:properties,additionalProperties:additionalProperties},compileSchema=compile_1,resolve$4=resolve_1,Cache=cacheExports,SchemaObject=schema_obj,stableStringify=fastJsonStableStringify,formats$1=formats_1,rules=rules$1,$dataMetaSchema=data,util$2=util$7,ajv=Ajv;Ajv.prototype.validate=validate,Ajv.prototype.compile=compile$1,Ajv.prototype.addSchema=addSchema,Ajv.prototype.addMetaSchema=addMetaSchema,Ajv.prototype.validateSchema=validateSchema,Ajv.prototype.getSchema=getSchema,Ajv.prototype.removeSchema=removeSchema,Ajv.prototype.addFormat=addFormat,Ajv.prototype.errorsText=errorsText,Ajv.prototype._addSchema=_addSchema,Ajv.prototype._compile=_compile,Ajv.prototype.compileAsync=async;var customKeyword=keyword;Ajv.prototype.addKeyword=customKeyword.add,Ajv.prototype.getKeyword=customKeyword.get,Ajv.prototype.removeKeyword=customKeyword.remove,Ajv.prototype.validateKeyword=customKeyword.validate;var errorClasses=error_classes;Ajv.ValidationError=errorClasses.Validation,Ajv.MissingRefError=errorClasses.MissingRef,Ajv.$dataMetaSchema=$dataMetaSchema;var META_SCHEMA_ID="http://json-schema.org/draft-07/schema",META_IGNORE_OPTIONS=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],META_SUPPORT_DATA=["/properties"];function Ajv(e){if(!(this instanceof Ajv))return new Ajv(e);e=this._opts=util$2.copy(e)||{},setLogger(this),this._schemas={},this._refs={},this._fragments={},this._formats=formats$1(e.format),this._cache=e.cache||new Cache,this._loadingSchemas={},this._compilations=[],this.RULES=rules(),this._getId=chooseGetId(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=stableStringify),this._metaOpts=getMetaSchemaOptions(this),e.formats&&addInitialFormats(this),e.keywords&&addInitialKeywords(this),addDefaultMetaSchema(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),addInitialSchemas(this)}function validate(e,t){var r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var n=this._addSchema(e);r=n.validate||this._compile(n)}var i=r(t);return!0!==r.$async&&(this.errors=r.errors),i}function compile$1(e,t){var r=this._addSchema(e,void 0,t);return r.validate||this._compile(r)}function addSchema(e,t,r,n){if(Array.isArray(e)){for(var i=0;i<e.length;i++)this.addSchema(e[i],void 0,r,n);return this}var o=this._getId(e);if(void 0!==o&&"string"!=typeof o)throw new Error("schema id must be string");return checkUnique(this,t=resolve$4.normalizeId(t||o)),this._schemas[t]=this._addSchema(e,r,n,!0),this}function addMetaSchema(e,t,r){return this.addSchema(e,t,r,!0),this}function validateSchema(e,t){var r=e.$schema;if(void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(!(r=r||this._opts.defaultMeta||defaultMeta(this)))return this.logger.warn("meta-schema not available"),this.errors=null,!0;var n=this.validate(r,e);if(!n&&t){var i="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(i);this.logger.error(i)}return n}function defaultMeta(e){var t=e._opts.meta;return e._opts.defaultMeta="object"==typeof t?e._getId(t)||t:e.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0,e._opts.defaultMeta}function getSchema(e){var t=_getSchemaObj(this,e);switch(typeof t){case"object":return t.validate||this._compile(t);case"string":return this.getSchema(t);case"undefined":return _getSchemaFragment(this,e)}}function _getSchemaFragment(e,t){var r=resolve$4.schema.call(e,{schema:{}},t);if(r){var n=r.schema,i=r.root,o=r.baseId,s=compileSchema.call(e,n,i,void 0,o);return e._fragments[t]=new SchemaObject({ref:t,fragment:!0,schema:n,root:i,baseId:o,validate:s}),s}}function _getSchemaObj(e,t){return t=resolve$4.normalizeId(t),e._schemas[t]||e._refs[t]||e._fragments[t]}function removeSchema(e){if(e instanceof RegExp)return _removeAllSchemas(this,this._schemas,e),_removeAllSchemas(this,this._refs,e),this;switch(typeof e){case"undefined":return _removeAllSchemas(this,this._schemas),_removeAllSchemas(this,this._refs),this._cache.clear(),this;case"string":var t=_getSchemaObj(this,e);return t&&this._cache.del(t.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":var r=this._opts.serialize,n=r?r(e):e;this._cache.del(n);var i=this._getId(e);i&&(i=resolve$4.normalizeId(i),delete this._schemas[i],delete this._refs[i])}return this}function _removeAllSchemas(e,t,r){for(var n in t){var i=t[n];i.meta||r&&!r.test(n)||(e._cache.del(i.cacheKey),delete t[n])}}function _addSchema(e,t,r,n){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var i=this._opts.serialize,o=i?i(e):e,s=this._cache.get(o);if(s)return s;n=n||!1!==this._opts.addUsedSchema;var a=resolve$4.normalizeId(this._getId(e));a&&n&&checkUnique(this,a);var c,A=!1!==this._opts.validateSchema&&!t;A&&!(c=a&&a==resolve$4.normalizeId(e.$schema))&&this.validateSchema(e,!0);var l=resolve$4.ids.call(this,e),u=new SchemaObject({id:a,schema:e,localRefs:l,cacheKey:o,meta:r});return"#"!=a[0]&&n&&(this._refs[a]=u),this._cache.put(o,u),A&&c&&this.validateSchema(e,!0),u}function _compile(e,t){if(e.compiling)return e.validate=i,i.schema=e.schema,i.errors=null,i.root=t||i,!0===e.schema.$async&&(i.$async=!0),i;var r,n;e.compiling=!0,e.meta&&(r=this._opts,this._opts=this._metaOpts);try{n=compileSchema.call(this,e.schema,t,e.localRefs)}catch(t){throw delete e.validate,t}finally{e.compiling=!1,e.meta&&(this._opts=r)}return e.validate=n,e.refs=n.refs,e.refVal=n.refVal,e.root=n.root,n;function i(){var t=e.validate,r=t.apply(this,arguments);return i.errors=t.errors,r}}function chooseGetId(e){switch(e.schemaId){case"auto":return _get$IdOrId;case"id":return _getId;default:return _get$Id}}function _getId(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function _get$Id(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function _get$IdOrId(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function errorsText(e,t){if(!(e=e||this.errors))return"No errors";for(var r=void 0===(t=t||{}).separator?", ":t.separator,n=void 0===t.dataVar?"data":t.dataVar,i="",o=0;o<e.length;o++){var s=e[o];s&&(i+=n+s.dataPath+" "+s.message+r)}return i.slice(0,-r.length)}function addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this._formats[e]=t,this}function addDefaultMetaSchema(e){var t;if(e._opts.$data&&(t=require$$12,e.addMetaSchema(t,t.$id,!0)),!1!==e._opts.meta){var r=require$$13;e._opts.$data&&(r=$dataMetaSchema(r,META_SUPPORT_DATA)),e.addMetaSchema(r,META_SCHEMA_ID,!0),e._refs["http://json-schema.org/schema"]=META_SCHEMA_ID}}function addInitialSchemas(e){var t=e._opts.schemas;if(t)if(Array.isArray(t))e.addSchema(t);else for(var r in t)e.addSchema(t[r],r)}function addInitialFormats(e){for(var t in e._opts.formats){var r=e._opts.formats[t];e.addFormat(t,r)}}function addInitialKeywords(e){for(var t in e._opts.keywords){var r=e._opts.keywords[t];e.addKeyword(t,r)}}function checkUnique(e,t){if(e._schemas[t]||e._refs[t])throw new Error('schema with key or id "'+t+'" already exists')}function getMetaSchemaOptions(e){for(var t=util$2.copy(e._opts),r=0;r<META_IGNORE_OPTIONS.length;r++)delete t[META_IGNORE_OPTIONS[r]];return t}function setLogger(e){var t=e._opts.logger;if(!1===t)e.logger={log:noop$2,warn:noop$2,error:noop$2};else{if(void 0===t&&(t=console),!("object"==typeof t&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");e.logger=t}}function noop$2(){}var Ajv$1=getDefaultExportFromCjs(ajv),ErrorHandlingStrategy;class Client extends Protocol{constructor(e,t){var r;super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._ajv=new Ajv$1}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,e)}assertCapability(e,t){var r;if(!(null===(r=this._serverCapabilities)||void 0===r?void 0:r[e]))throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const r=await this.request({method:"initialize",params:{protocolVersion:LATEST_PROTOCOL_VERSION,capabilities:this._capabilities,clientInfo:this._clientInfo}},InitializeResultSchema,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!SUPPORTED_PROTOCOL_VERSIONS.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"})}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var t,r,n,i,o;switch(e){case"logging/setLevel":if(!(null===(t=this._serverCapabilities)||void 0===t?void 0:t.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(null===(r=this._serverCapabilities)||void 0===r?void 0:r.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(null===(n=this._serverCapabilities)||void 0===n?void 0:n.resources))throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(null===(i=this._serverCapabilities)||void 0===i?void 0:i.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(null===(o=this._serverCapabilities)||void 0===o?void 0:o.completions))throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){var t;if("notifications/roots/list_changed"===e)if(!(null===(t=this._capabilities.roots)||void 0===t?void 0:t.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`)}}async ping(e){return this.request({method:"ping"},EmptyResultSchema,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},CompleteResultSchema,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},EmptyResultSchema,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},GetPromptResultSchema,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},ListPromptsResultSchema,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},ListResourcesResultSchema,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},ListResourceTemplatesResultSchema,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},ReadResourceResultSchema,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},EmptyResultSchema,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},EmptyResultSchema,t)}async callTool(e,t=CallToolResultSchema,r){const n=await this.request({method:"tools/call",params:e},t,r),i=this.getToolOutputValidator(e.name);if(i){if(!n.structuredContent&&!n.isError)throw new McpError(ErrorCode.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{if(!i(n.structuredContent))throw new McpError(ErrorCode.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(i.errors)}`)}catch(e){if(e instanceof McpError)throw e;throw new McpError(ErrorCode.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return n}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const t of e)if(t.outputSchema)try{const e=this._ajv.compile(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}catch(e){}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},ListToolsResultSchema,t);return this.cacheToolOutputSchemas(r.tools),r}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}!function(e){e.RECONNECT="reconnect",e.DISCONNECT="disconnect",e.IGNORE="ignore",e.FALLBACK_TO_SSE="fallback_to_sse"}(ErrorHandlingStrategy||(ErrorHandlingStrategy={}));class McpConnectionError extends Error{strategy;friendlyMsg;context;constructor(e,t,r,n){super(t),this.name="McpConnectionError",this.friendlyMsg=e,this.strategy=r,this.context=n}}function handleNonAsciiError(e){return e.includes("Cannot convert argument to a ByteString")&&e.includes("greater than 255")?{friendlyMsg:"header 中只可使用可见 ASCII 字符,请检查配置中的 headers 是否包含中文或其他非 ASCII 字符",strategy:ErrorHandlingStrategy.DISCONNECT}:null}function handleConnectionRefusedError(e){return e.includes("ECONNREFUSED")?{friendlyMsg:"无法连接到服务器,请检查服务器是否启动并监听正确的端口",strategy:ErrorHandlingStrategy.DISCONNECT}:null}function handleStdioError(e){if(e.includes("Unexpected token")&&e.includes("is not valid JSON"))return{friendlyMsg:`忽略 stdio 服务器的非 JSON 输出:${e}`,strategy:ErrorHandlingStrategy.IGNORE};if(e.includes("ENOENT")){const t=/spawn\s+['"']?([^\s'"]+)['"']?\s+ENOENT/.exec(e)||/ENOENT.*spawn\s+['"']?([^\s'"]+)['"']?/.exec(e)||/command\s+['"']?([^\s'"]+)['"']?.*not found/.exec(e);return{friendlyMsg:`未找到命令 "${t?t[1]:"指定的命令"}",请检查可执行文件路径或安装所需的运行时环境`,strategy:ErrorHandlingStrategy.DISCONNECT,context:{showEnv:!0}}}return null}function handlePermissionError(e){return e.includes("EACCES")?{friendlyMsg:"权限不足,无法执行命令,请检查文件权限或以管理员身份运行",strategy:ErrorHandlingStrategy.DISCONNECT,context:{showEnv:!0}}:null}function handleSpawnFailedError(e){return e.includes("spawn")&&e.includes("failed")?{friendlyMsg:"无法启动服务进程,请检查命令路径和参数配置",strategy:ErrorHandlingStrategy.DISCONNECT}:null}function handleUnknownMessageIdError(e){return e.includes("unknown message ID")||e.includes("Received a response for an unknown message ID")?{friendlyMsg:`忽略未知消息 ID 的响应:${e}`,strategy:ErrorHandlingStrategy.IGNORE}:null}function handleTimeoutError(e){return e.includes("timeout")||e.includes("ETIMEDOUT")||e.includes("Body Timeout Error")?{friendlyMsg:"连接超时,将重试连接",strategy:ErrorHandlingStrategy.RECONNECT}:null}function handleConnectionResetError(e){return e.includes("ECONNRESET")||e.includes("read ECONNRESET")?{friendlyMsg:"连接被重置,将重试连接",strategy:ErrorHandlingStrategy.RECONNECT}:null}function handleStreamableHttpFallback(e){return e.includes("Method Not Allowed")||e.includes("Not Found")||e.includes("Bad Request")||e.includes("Internal Server Error")?{friendlyMsg:"StreamableHttp 连接失败,尝试降级到 SSE",strategy:ErrorHandlingStrategy.FALLBACK_TO_SSE}:null}function handleSseTerminatedError(e){return e.includes("TypeError: terminated")||e.includes("other side closed")?{friendlyMsg:"SSE 连接被终止,将重试连接",strategy:ErrorHandlingStrategy.RECONNECT}:null}function getStatusCodeFromError(e){const t=[/status code \((\d{3})\)/,/status (\d{3})/,/(\d{3})/];for(const r of t){const t=r.exec(e);if(t)return t[1]}return null}const HTTP_ERROR_MAPPING={400:{friendlyMsg:"StreamableHttp 请求格式不受支持",strategy:ErrorHandlingStrategy.FALLBACK_TO_SSE},401:{friendlyMsg:"认证失败,请检查您的凭据或访问权限",strategy:ErrorHandlingStrategy.DISCONNECT},403:{friendlyMsg:"访问被禁止,您没有访问此资源的权限",strategy:ErrorHandlingStrategy.DISCONNECT},404:{friendlyMsg:"StreamableHttp 端点不存在",strategy:ErrorHandlingStrategy.FALLBACK_TO_SSE},405:{friendlyMsg:"StreamableHttp 方法不支持",strategy:ErrorHandlingStrategy.FALLBACK_TO_SSE},406:{friendlyMsg:"服务器无法提供请求的内容格式",strategy:ErrorHandlingStrategy.DISCONNECT},429:{friendlyMsg:"请求过于频繁,请等待后重试",strategy:ErrorHandlingStrategy.RECONNECT},500:{friendlyMsg:"StreamableHttp 服务器内部错误",strategy:ErrorHandlingStrategy.FALLBACK_TO_SSE},502:{friendlyMsg:"服务器临时不可用",strategy:ErrorHandlingStrategy.DISCONNECT},503:{friendlyMsg:"服务器临时不可用",strategy:ErrorHandlingStrategy.DISCONNECT},504:{friendlyMsg:"服务器响应时间过长",strategy:ErrorHandlingStrategy.DISCONNECT}};function handleHttpStatusCodeError(e,t){const r=getStatusCodeFromError(e),n=r?HTTP_ERROR_MAPPING[r]:null;return n||{friendlyMsg:`连接错误 "${t}": ${e}`,strategy:ErrorHandlingStrategy.DISCONNECT}}function createMcpConnectionError(e,t){const r=e.message,n=[handleNonAsciiError,handleConnectionRefusedError,handleStdioError,handlePermissionError,handleSpawnFailedError,handleUnknownMessageIdError,handleTimeoutError,handleConnectionResetError,handleStreamableHttpFallback,handleSseTerminatedError];for(const e of n){const t=e(r);if(t)return new McpConnectionError(t.friendlyMsg,r,t.strategy,t.context)}const i=handleHttpStatusCodeError(r,t);return new McpConnectionError(i.friendlyMsg,r,i.strategy,i.context)}const DEFAULT_REQUEST_TIMEOUT_MS=5e3;class McpConnectionBase{connectionEventEmitter;mcpLogger;name;config;client;transport;state={status:"disconnected",error:"",tools:[]};roots=[];hasAnnouncedRoots=!1;constructor(e,t,r,n){this.connectionEventEmitter=r,this.mcpLogger=n,this.name=e;const i=t.parsed[e];if(!i)throw new Error(`Config for server ${e} not found in snapshot`);this.config=i}get isConnected(){return"connected"===this.state.status&&void 0!==this.client}async connect(){this.isConnected&&await this.disconnect();try{this.setError(""),await this.setStatus("connecting"),this.client=this.createClient(),this.transport=this.createTransport(),this.setupConnectionHandlers(),await this.client.connect(this.transport);const e=this.client.getServerVersion(),t=this.client.getInstructions();e&&(this.state.serverInfo={name:e.name,version:e.version,instructions:t||void 0},this.mcpLogger.info(`Server 信息: ${e.name} v${e.version}${t?` (包含 ${t.length} 字符的指令)`:""}`));const r=await this.fetchToolsList();this.state.tools=r,await this.setStatus("connected")}catch(e){const t=createMcpConnectionError(e instanceof Error?e:new Error(String(e)),this.name);if(t.strategy!==ErrorHandlingStrategy.IGNORE)throw this.setError(t.friendlyMsg),await this.setStatus("disconnected"),t}}async disconnect(){if(this.client)try{await this.client.close()}catch(e){this.mcpLogger.error("client 关闭失败:",e.message)}finally{this.mcpLogger.info("清理 client 和 transport 监听器"),this.client.onclose=void 0,this.client.onerror=void 0;const e=this.transport;e&&(e.onclose=void 0,e.onerror=e=>{this.mcpLogger.info(`server 关闭后发送:${e.message}`)},setTimeout((()=>{e.onmessage=void 0}),200)),this.client=void 0,this.transport=void 0}await this.setStatus("disconnected")}updateConfig(e){const t=e.parsed[this.name];if(!t)throw new Error(`Config for server ${this.name} not found in snapshot`);const r=JSON.stringify(this.config)!==JSON.stringify(t);return r&&(this.config=t),r}getClient(){if(!this.client)throw new Error("Client 不存在,请检查连接状态");if(!this.isConnected)throw new Error("未连接,请检查连接状态");return this.client}getTimeout(){return this.config.timeout}toWebviewFormat(){return{name:this.name,status:this.state.status,error:this.state.error,tools:this.state.tools,serverInfo:this.state.serverInfo,logPath:this.mcpLogger.normalizedAbsolutedPath}}setRoots(e){JSON.stringify(this.roots)!==JSON.stringify(e)&&(this.roots=e,this.hasAnnouncedRoots&&this.isConnected&&this.client&&(this.client.notification({method:"notifications/roots/list_changed"}),this.hasAnnouncedRoots=!1))}setupConnectionHandlers(){this.client&&(this.client.onclose=async()=>{this.mcpLogger.info("连接已关闭"),await this.setStatus("disconnected")})}async setStatus(e){const t=this.state.status;this.state.status!==e&&(this.state.status=e,this.connectionEventEmitter.emitConnectionStatusChange(this.name,t,e))}setError(e){this.state.error=e}async handleConnectionError(e,t){const r=createMcpConnectionError(e,this.name);if(this.mcpLogger.error(`${t} 类型 server 错误: ${r.message}`),r.context?.showEnv){const e=extractRuntimeConfig(this.config);"env"in e&&this.mcpLogger.error(formatEnvDiagnostics(e.env))}const n={[ErrorHandlingStrategy.RECONNECT]:async()=>{this.setError(r.friendlyMsg),await this.setStatus("disconnected"),await this.disconnect(),this.connectionEventEmitter.emitConnectionReconnectRequested(this.name)},[ErrorHandlingStrategy.DISCONNECT]:async()=>{this.setError(r.friendlyMsg),await this.setStatus("disconnected"),await this.disconnect()},[ErrorHandlingStrategy.IGNORE]:()=>{},[ErrorHandlingStrategy.FALLBACK_TO_SSE]:async()=>{throw r}},i=n[r.strategy]??n[ErrorHandlingStrategy.DISCONNECT];await i()}createClient(){const e=new Client({name:"comate",version:"1.0.0"},{capabilities:{roots:{listChanged:!0}}});return e.setNotificationHandler(ToolListChangedNotificationSchema,(async()=>{const e=await this.fetchToolsList();this.state.tools=e,this.connectionEventEmitter.emitConnectionToolsChange(this.name)})),e.setRequestHandler(ListRootsRequestSchema,(async()=>(this.hasAnnouncedRoots=!0,{roots:this.roots,_meta:{username:kernel.config.username}}))),e}async fetchToolsList(){try{if(!this.client)throw new Error("fetchToolsList 时 Client 不存在");const e=await this.client.request({method:"tools/list"},ListToolsResultSchema,{timeout:DEFAULT_REQUEST_TIMEOUT_MS});return(e?.tools||[]).map((e=>({...e,autoApprove:!1})))}catch(e){return this.mcpLogger.error("获取 tools 列表失败:",e.message),[]}}}let crypto$2;async function getRandomValues(e){return(await crypto$2).getRandomValues(new Uint8Array(e))}async function random(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let r="";const n=await getRandomValues(e);for(let i=0;i<e;i++){r+=t[n[i]%66]}return r}async function generateVerifier(e){return await random(e)}async function generateChallenge(e){const t=await(await crypto$2).subtle.digest("SHA-256",(new TextEncoder).encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function pkceChallenge(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await generateVerifier(e);return{code_verifier:t,code_challenge:await generateChallenge(t)}}crypto$2=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((e=>e.webcrypto));const SafeUrlSchema=z.string().url().superRefine(((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:z.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),z.NEVER})).refine((e=>{const t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol}),{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),OAuthProtectedResourceMetadataSchema=z.object({resource:z.string().url(),authorization_servers:z.array(SafeUrlSchema).optional(),jwks_uri:z.string().url().optional(),scopes_supported:z.array(z.string()).optional(),bearer_methods_supported:z.array(z.string()).optional(),resource_signing_alg_values_supported:z.array(z.string()).optional(),resource_name:z.string().optional(),resource_documentation:z.string().optional(),resource_policy_uri:z.string().url().optional(),resource_tos_uri:z.string().url().optional(),tls_client_certificate_bound_access_tokens:z.boolean().optional(),authorization_details_types_supported:z.array(z.string()).optional(),dpop_signing_alg_values_supported:z.array(z.string()).optional(),dpop_bound_access_tokens_required:z.boolean().optional()}).passthrough(),OAuthMetadataSchema=z.object({issuer:z.string(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:z.array(z.string()).optional(),response_types_supported:z.array(z.string()),response_modes_supported:z.array(z.string()).optional(),grant_types_supported:z.array(z.string()).optional(),token_endpoint_auth_methods_supported:z.array(z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:z.array(z.string()).optional(),service_documentation:SafeUrlSchema.optional(),revocation_endpoint:SafeUrlSchema.optional(),revocation_endpoint_auth_methods_supported:z.array(z.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:z.array(z.string()).optional(),introspection_endpoint:z.string().optional(),introspection_endpoint_auth_methods_supported:z.array(z.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:z.array(z.string()).optional(),code_challenge_methods_supported:z.array(z.string()).optional()}).passthrough(),OpenIdProviderMetadataSchema=z.object({issuer:z.string(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,userinfo_endpoint:SafeUrlSchema.optional(),jwks_uri:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:z.array(z.string()).optional(),response_types_supported:z.array(z.string()),response_modes_supported:z.array(z.string()).optional(),grant_types_supported:z.array(z.string()).optional(),acr_values_supported:z.array(z.string()).optional(),subject_types_supported:z.array(z.string()),id_token_signing_alg_values_supported:z.array(z.string()),id_token_encryption_alg_values_supported:z.array(z.string()).optional(),id_token_encryption_enc_values_supported:z.array(z.string()).optional(),userinfo_signing_alg_values_supported:z.array(z.string()).optional(),userinfo_encryption_alg_values_supported:z.array(z.string()).optional(),userinfo_encryption_enc_values_supported:z.array(z.string()).optional(),request_object_signing_alg_values_supported:z.array(z.string()).optional(),request_object_encryption_alg_values_supported:z.array(z.string()).optional(),request_object_encryption_enc_values_supported:z.array(z.string()).optional(),token_endpoint_auth_methods_supported:z.array(z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:z.array(z.string()).optional(),display_values_supported:z.array(z.string()).optional(),claim_types_supported:z.array(z.string()).optional(),claims_supported:z.array(z.string()).optional(),service_documentation:z.string().optional(),claims_locales_supported:z.array(z.string()).optional(),ui_locales_supported:z.array(z.string()).optional(),claims_parameter_supported:z.boolean().optional(),request_parameter_supported:z.boolean().optional(),request_uri_parameter_supported:z.boolean().optional(),require_request_uri_registration:z.boolean().optional(),op_policy_uri:SafeUrlSchema.optional(),op_tos_uri:SafeUrlSchema.optional()}).passthrough(),OpenIdProviderDiscoveryMetadataSchema=OpenIdProviderMetadataSchema.merge(OAuthMetadataSchema.pick({code_challenge_methods_supported:!0})),OAuthTokensSchema=z.object({access_token:z.string(),id_token:z.string().optional(),token_type:z.string(),expires_in:z.number().optional(),scope:z.string().optional(),refresh_token:z.string().optional()}).strip(),OAuthErrorResponseSchema=z.object({error:z.string(),error_description:z.string().optional(),error_uri:z.string().optional()}),OAuthClientMetadataSchema=z.object({redirect_uris:z.array(SafeUrlSchema),token_endpoint_auth_method:z.string().optional(),grant_types:z.array(z.string()).optional(),response_types:z.array(z.string()).optional(),client_name:z.string().optional(),client_uri:SafeUrlSchema.optional(),logo_uri:SafeUrlSchema.optional(),scope:z.string().optional(),contacts:z.array(z.string()).optional(),tos_uri:SafeUrlSchema.optional(),policy_uri:z.string().optional(),jwks_uri:SafeUrlSchema.optional(),jwks:z.any().optional(),software_id:z.string().optional(),software_version:z.string().optional(),software_statement:z.string().optional()}).strip(),OAuthClientInformationSchema=z.object({client_id:z.string(),client_secret:z.string().optional(),client_id_issued_at:z.number().optional(),client_secret_expires_at:z.number().optional()}).strip(),OAuthClientInformationFullSchema=OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);function resourceUrlFromServerUrl(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}function checkResourceAllowed({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),n="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==n.origin)return!1;if(r.pathname.length<n.pathname.length)return!1;const i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}z.object({error:z.string(),error_description:z.string().optional()}).strip(),z.object({token:z.string(),token_type_hint:z.string().optional()}).strip();class OAuthError extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class InvalidRequestError extends OAuthError{}InvalidRequestError.errorCode="invalid_request";class InvalidClientError extends OAuthError{}InvalidClientError.errorCode="invalid_client";class InvalidGrantError extends OAuthError{}InvalidGrantError.errorCode="invalid_grant";class UnauthorizedClientError extends OAuthError{}UnauthorizedClientError.errorCode="unauthorized_client";class UnsupportedGrantTypeError extends OAuthError{}UnsupportedGrantTypeError.errorCode="unsupported_grant_type";class InvalidScopeError extends OAuthError{}InvalidScopeError.errorCode="invalid_scope";class AccessDeniedError extends OAuthError{}AccessDeniedError.errorCode="access_denied";class ServerError extends OAuthError{}ServerError.errorCode="server_error";class TemporarilyUnavailableError extends OAuthError{}TemporarilyUnavailableError.errorCode="temporarily_unavailable";class UnsupportedResponseTypeError extends OAuthError{}UnsupportedResponseTypeError.errorCode="unsupported_response_type";class UnsupportedTokenTypeError extends OAuthError{}UnsupportedTokenTypeError.errorCode="unsupported_token_type";class InvalidTokenError extends OAuthError{}InvalidTokenError.errorCode="invalid_token";class MethodNotAllowedError extends OAuthError{}MethodNotAllowedError.errorCode="method_not_allowed";class TooManyRequestsError extends OAuthError{}TooManyRequestsError.errorCode="too_many_requests";class InvalidClientMetadataError extends OAuthError{}InvalidClientMetadataError.errorCode="invalid_client_metadata";class InsufficientScopeError extends OAuthError{}InsufficientScopeError.errorCode="insufficient_scope";const OAUTH_ERRORS={[InvalidRequestError.errorCode]:InvalidRequestError,[InvalidClientError.errorCode]:InvalidClientError,[InvalidGrantError.errorCode]:InvalidGrantError,[UnauthorizedClientError.errorCode]:UnauthorizedClientError,[UnsupportedGrantTypeError.errorCode]:UnsupportedGrantTypeError,[InvalidScopeError.errorCode]:InvalidScopeError,[AccessDeniedError.errorCode]:AccessDeniedError,[ServerError.errorCode]:ServerError,[TemporarilyUnavailableError.errorCode]:TemporarilyUnavailableError,[UnsupportedResponseTypeError.errorCode]:UnsupportedResponseTypeError,[UnsupportedTokenTypeError.errorCode]:UnsupportedTokenTypeError,[InvalidTokenError.errorCode]:InvalidTokenError,[MethodNotAllowedError.errorCode]:MethodNotAllowedError,[TooManyRequestsError.errorCode]:TooManyRequestsError,[InvalidClientMetadataError.errorCode]:InvalidClientMetadataError,[InsufficientScopeError.errorCode]:InsufficientScopeError};class UnauthorizedError extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}const AUTHORIZATION_CODE_RESPONSE_TYPE="code",AUTHORIZATION_CODE_CHALLENGE_METHOD="S256";function selectClientAuthMethod(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function applyClientAuthentication(e,t,r,n){const{client_id:i,client_secret:o}=t;switch(e){case"client_secret_basic":return void applyBasicAuth(i,o,r);case"client_secret_post":return void applyPostAuth(i,o,n);case"none":return void applyPublicAuth(i,n);default:throw new Error(`Unsupported client authentication method: ${e}`)}}function applyBasicAuth(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function applyPostAuth(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function applyPublicAuth(e,t){t.set("client_id",e)}async function parseErrorResponse(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=OAuthErrorResponseSchema.parse(JSON.parse(r)),{error:t,error_description:n,error_uri:i}=e;return new(OAUTH_ERRORS[t]||ServerError)(n||"",i)}catch(e){return new ServerError(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function auth(e,t){var r,n;try{return await authInternal(e,t)}catch(i){if(i instanceof InvalidClientError||i instanceof UnauthorizedClientError)return await(null===(r=e.invalidateCredentials)||void 0===r?void 0:r.call(e,"all")),await authInternal(e,t);if(i instanceof InvalidGrantError)return await(null===(n=e.invalidateCredentials)||void 0===n?void 0:n.call(e,"tokens")),await authInternal(e,t);throw i}}async function authInternal(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){let s,a;try{s=await discoverOAuthProtectedResourceMetadata(t,{resourceMetadataUrl:i},o),s.authorization_servers&&s.authorization_servers.length>0&&(a=s.authorization_servers[0])}catch(e){}a||(a=t);const c=await selectResourceURL(t,e,s),A=await discoverAuthorizationServerMetadata(a,{fetchFn:o});let l=await Promise.resolve(e.clientInformation());if(!l){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await registerClient(a,{metadata:A,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(t),l=t}if(void 0!==r){const t=await e.codeVerifier(),n=await exchangeAuthorization(a,{metadata:A,clientInformation:l,authorizationCode:r,codeVerifier:t,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(n),"AUTHORIZED"}const u=await e.tokens();if(null==u?void 0:u.refresh_token)try{const t=await refreshAuthorization(a,{metadata:A,clientInformation:l,refreshToken:u.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof OAuthError&&!(e instanceof ServerError))throw e}const d=e.state?await e.state():void 0,{authorizationUrl:h,codeVerifier:p}=await startAuthorization(a,{metadata:A,clientInformation:l,state:d,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(p),await e.redirectToAuthorization(h),"REDIRECT"}async function selectResourceURL(e,t,r){const n=resourceUrlFromServerUrl(e);if(t.validateResourceURL)return await t.validateResourceURL(n,null==r?void 0:r.resource);if(r){if(!checkResourceAllowed({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function extractResourceMetadataUrl(e){const t=e.headers.get("WWW-Authenticate");if(!t)return;const[r,n]=t.split(" ");if("bearer"!==r.toLowerCase()||!n)return;const i=/resource_metadata="([^"]*)"/.exec(t);if(i)try{return new URL(i[1])}catch(e){return}}async function discoverOAuthProtectedResourceMetadata(e,t,r=fetch){const n=await discoverMetadataWithFallback(e,"oauth-protected-resource",r,{protocolVersion:null==t?void 0:t.protocolVersion,metadataUrl:null==t?void 0:t.resourceMetadataUrl});if(!n||404===n.status)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return OAuthProtectedResourceMetadataSchema.parse(await n.json())}async function fetchWithCorsRetry(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?fetchWithCorsRetry(e,void 0,r):void 0;throw n}}function buildWellKnownPath(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function tryMetadataDiscovery(e,t,r=fetch){const n={"MCP-Protocol-Version":t};return await fetchWithCorsRetry(e,n,r)}function shouldAttemptFallback(e,t){return!e||e.status>=400&&e.status<500&&"/"!==t}async function discoverMetadataWithFallback(e,t,r,n){var i,o;const s=new URL(e),a=null!==(i=null==n?void 0:n.protocolVersion)&&void 0!==i?i:LATEST_PROTOCOL_VERSION;let c;if(null==n?void 0:n.metadataUrl)c=new URL(n.metadataUrl);else{const e=buildWellKnownPath(t,s.pathname);c=new URL(e,null!==(o=null==n?void 0:n.metadataServerUrl)&&void 0!==o?o:s),c.search=s.search}let A=await tryMetadataDiscovery(c,a,r);if(!(null==n?void 0:n.metadataUrl)&&shouldAttemptFallback(A,s.pathname)){const e=new URL(`/.well-known/${t}`,s);A=await tryMetadataDiscovery(e,a,r)}return A}function buildDiscoveryUrls(e){const t="string"==typeof e?new URL(e):e,r=[];if(!("/"!==t.pathname))return r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),r;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),r.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),r}async function discoverAuthorizationServerMetadata(e,{fetchFn:t=fetch,protocolVersion:r=LATEST_PROTOCOL_VERSION}={}){const n={"MCP-Protocol-Version":r},i=buildDiscoveryUrls(e);for(const{url:e,type:r}of i){const i=await fetchWithCorsRetry(e,n,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}return"oauth"===r?OAuthMetadataSchema.parse(await i.json()):OpenIdProviderDiscoveryMetadataSchema.parse(await i.json())}}}async function startAuthorization(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE))throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD))throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`)}else a=new URL("/authorize",e);const c=await pkceChallenge(),A=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",AUTHORIZATION_CODE_RESPONSE_TYPE),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",AUTHORIZATION_CODE_CHALLENGE_METHOD),a.searchParams.set("redirect_uri",String(n)),o&&a.searchParams.set("state",o),i&&a.searchParams.set("scope",i),(null==i?void 0:i.includes("offline_access"))&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",s.href),{authorizationUrl:a,codeVerifier:A}}async function exchangeAuthorization(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:a,fetchFn:c}){var A;const l="authorization_code",u=(null==t?void 0:t.token_endpoint)?new URL(t.token_endpoint):new URL("/token",e);if((null==t?void 0:t.grant_types_supported)&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:l,code:n,code_verifier:i,redirect_uri:String(o)});if(a)a(d,h,e,t);else{applyClientAuthentication(selectClientAuthMethod(r,null!==(A=null==t?void 0:t.token_endpoint_auth_methods_supported)&&void 0!==A?A:[]),r,d,h)}s&&h.set("resource",s.href);const p=await(null!=c?c:fetch)(u,{method:"POST",headers:d,body:h});if(!p.ok)throw await parseErrorResponse(p);return OAuthTokensSchema.parse(await p.json())}async function refreshAuthorization(e,{metadata:t,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){var a;const c="refresh_token";let A;if(t){if(A=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else A=new URL("/token",e);const l=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),u=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(l,u,e,t);else{applyClientAuthentication(selectClientAuthMethod(r,null!==(a=null==t?void 0:t.token_endpoint_auth_methods_supported)&&void 0!==a?a:[]),r,l,u)}i&&u.set("resource",i.href);const d=await(null!=s?s:fetch)(A,{method:"POST",headers:l,body:u});if(!d.ok)throw await parseErrorResponse(d);return OAuthTokensSchema.parse({refresh_token:n,...await d.json()})}async function registerClient(e,{metadata:t,clientMetadata:r,fetchFn:n}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);const o=await(null!=n?n:fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await parseErrorResponse(o);return OAuthClientInformationFullSchema.parse(await o.json())}class ParseError extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function noop$1(e){}function createParser(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=noop$1,onError:r=noop$1,onRetry:n=noop$1,onComment:i}=e;let o,s="",a=!0,c="",A="";function l(e){if(""===e)return c.length>0&&t({id:o,event:A||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),o=void 0,c="",void(A="");if(e.startsWith(":"))return void(i&&i(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1===r)u(e,"",e);else{const t=e.slice(0,r),n=" "===e[r+1]?2:1;u(t,e.slice(r+n),e)}}function u(e,t,i){switch(e){case"event":A=t;break;case"data":c=`${c}${t}\n`;break;case"id":o=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?n(parseInt(t,10)):r(new ParseError(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:i}));break;default:r(new ParseError(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:i}))}}return{feed:function(e){const t=a?e.replace(/^\xEF\xBB\xBF/,""):e,[r,n]=splitLines(`${s}${t}`);for(const e of r)l(e);s=n,a=!1},reset:function(e={}){s&&e.consume&&l(s),a=!0,o=void 0,c="",A="",s=""}}}function splitLines(e){const t=[];let r="",n=0;for(;n<e.length;){const i=e.indexOf("\r",n),o=e.indexOf("\n",n);let s=-1;if(-1!==i&&-1!==o?s=Math.min(i,o):-1!==i?s=i:-1!==o&&(s=o),-1===s){r=e.slice(n);break}{const r=e.slice(n,s);t.push(r),n=s+1,"\r"===e[n-1]&&"\n"===e[n]&&n++}}return[t,r]}class EventSourceParserStream extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let n;super({start(i){n=createParser({onEvent:e=>{i.enqueue(e)},onError(t){"terminate"===e?i.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){n.feed(e)}})}}const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class StreamableHTTPError extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class StreamableHTTPClientTransport{constructor(e,t){var r;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==t?void 0:t.requestInit,this._authProvider=null==t?void 0:t.authProvider,this._fetch=null==t?void 0:t.fetch,this._sessionId=null==t?void 0:t.sessionId,this._reconnectionOptions=null!==(r=null==t?void 0:t.reconnectionOptions)&&void 0!==r?r:DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS}async _authThenStart(){var e;if(!this._authProvider)throw new UnauthorizedError("No auth provider");let t;try{t=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw null===(e=this.onerror)||void 0===e||e.call(this,t),t}if("AUTHORIZED"!==t)throw new UnauthorizedError;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const t={};if(this._authProvider){const e=await this._authProvider.tokens();e&&(t.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=this._normalizeHeaders(null===(e=this._requestInit)||void 0===e?void 0:e.headers);return new Headers({...t,...r})}async _startOrAuthSse(e){var t,r,n;const{resumptionToken:i}=e;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),i&&n.set("last-event-id",i);const o=await(null!==(t=this._fetch)&&void 0!==t?t:fetch)(this._url,{method:"GET",headers:n,signal:null===(r=this._abortController)||void 0===r?void 0:r.signal});if(!o.ok){if(401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new StreamableHTTPError(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(e){throw null===(n=this.onerror)||void 0===n||n.call(this,e),e}}_getNextReconnectionDelay(e){const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,t=0){var r;const n=this._reconnectionOptions.maxRetries;if(n>0&&t>=n)return void(null===(r=this.onerror)||void 0===r||r.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`)));const i=this._getNextReconnectionDelay(t);setTimeout((()=>{this._startOrAuthSse(e).catch((r=>{var n;null===(n=this.onerror)||void 0===n||n.call(this,new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)}))}),i)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:n,replayMessageId:i}=t;let o;(async()=>{var t,s,a,c;try{const r=e.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).getReader();for(;;){const{value:e,done:a}=await r.read();if(a)break;if(e.id&&(o=e.id,null==n||n(e.id)),!e.event||"message"===e.event)try{const r=JSONRPCMessageSchema.parse(JSON.parse(e.data));void 0!==i&&isJSONRPCResponse(r)&&(r.id=i),null===(t=this.onmessage)||void 0===t||t.call(this,r)}catch(e){null===(s=this.onerror)||void 0===s||s.call(this,e)}}}catch(e){if(null===(a=this.onerror)||void 0===a||a.call(this,new Error(`SSE stream disconnected: ${e}`)),r&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:n,replayMessageId:i},0)}catch(e){null===(c=this.onerror)||void 0===c||c.call(this,new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new UnauthorizedError("No auth provider");if("AUTHORIZED"!==await auth(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new UnauthorizedError("Failed to authorize")}async close(){var e,t;null===(e=this._abortController)||void 0===e||e.abort(),null===(t=this.onclose)||void 0===t||t.call(this)}async send(e,t){var r,n,i,o;try{const{resumptionToken:o,onresumptiontoken:s}=t||{};if(o)return void this._startOrAuthSse({resumptionToken:o,replayMessageId:isJSONRPCRequest(e)?e.id:void 0}).catch((e=>{var t;return null===(t=this.onerror)||void 0===t?void 0:t.call(this,e)}));const a=await this._commonHeaders();a.set("content-type","application/json"),a.set("accept","application/json, text/event-stream");const c={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:null===(r=this._abortController)||void 0===r?void 0:r.signal},A=await(null!==(n=this._fetch)&&void 0!==n?n:fetch)(this._url,c),l=A.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!A.ok){if(401===A.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new StreamableHTTPError(401,"Server returned 401 after successful authentication");this._resourceMetadataUrl=extractResourceMetadataUrl(A);if("AUTHORIZED"!==await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new UnauthorizedError;return this._hasCompletedAuthFlow=!0,this.send(e)}const t=await A.text().catch((()=>null));throw new Error(`Error POSTing to endpoint (HTTP ${A.status}): ${t}`)}if(this._hasCompletedAuthFlow=!1,202===A.status)return void(isInitializedNotification(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch((e=>{var t;return null===(t=this.onerror)||void 0===t?void 0:t.call(this,e)})));const u=(Array.isArray(e)?e:[e]).filter((e=>"method"in e&&"id"in e&&void 0!==e.id)).length>0,d=A.headers.get("content-type");if(u)if(null==d?void 0:d.includes("text/event-stream"))this._handleSseStream(A.body,{onresumptiontoken:s},!1);else{if(!(null==d?void 0:d.includes("application/json")))throw new StreamableHTTPError(-1,`Unexpected content type: ${d}`);{const e=await A.json(),t=Array.isArray(e)?e.map((e=>JSONRPCMessageSchema.parse(e))):[JSONRPCMessageSchema.parse(e)];for(const e of t)null===(i=this.onmessage)||void 0===i||i.call(this,e)}}}catch(e){throw null===(o=this.onerror)||void 0===o||o.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,t,r;if(this._sessionId)try{const r=await this._commonHeaders(),n={...this._requestInit,method:"DELETE",headers:r,signal:null===(e=this._abortController)||void 0===e?void 0:e.signal},i=await(null!==(t=this._fetch)&&void 0!==t?t:fetch)(this._url,n);if(!i.ok&&405!==i.status)throw new StreamableHTTPError(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(e){throw null===(r=this.onerror)||void 0===r||r.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}class StreamableHttpConnection extends McpConnectionBase{keepAliveTimer;async disconnect(){this.keepAliveTimer&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=void 0),await super.disconnect()}createTransport(){const{url:e,requestInit:t}=extractRuntimeConfig(this.config);return new StreamableHTTPClientTransport(new URL(e),{requestInit:t})}setupConnectionHandlers(){this.client&&(this.keepAliveTimer=setInterval((async()=>{try{this.mcpLogger.info("send ping"),await(this.client?.ping())}catch(e){this.mcpLogger.error("ping fail"),this.keepAliveTimer&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=void 0)}}),6e4),this.client.onclose=async()=>{this.keepAliveTimer&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=void 0),await this.setStatus("disconnected")},this.client.onerror=async e=>{this.keepAliveTimer&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=void 0),await this.handleConnectionError(e,"streamableHttp")})}}let ErrorEvent$1=class extends Event{constructor(e,t){var r,n;super(e),this.code=null!=(r=null==t?void 0:t.code)?r:void 0,this.message=null!=(n=null==t?void 0:t.message)?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(inspectableError(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(inspectableError(this),t)}};function syntaxError(e){const t=globalThis.DOMException;return"function"==typeof t?new t(e,"SyntaxError"):new SyntaxError(e)}function flattenError(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(flattenError).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${flattenError(e.cause)}`:e.message:`${e}`}function inspectableError(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var __typeError=e=>{throw TypeError(e)},__accessCheck=(e,t,r)=>t.has(e)||__typeError("Cannot "+r),__privateGet=(e,t,r)=>(__accessCheck(e,t,"read from private field"),r?r.call(e):t.get(e)),__privateAdd=(e,t,r)=>t.has(e)?__typeError("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),__privateSet=(e,t,r,n)=>(__accessCheck(e,t,"write to private field"),t.set(e,r),r),__privateMethod=(e,t,r)=>(__accessCheck(e,t,"access private method"),r),_readyState,_url,_redirectUrl,_withCredentials,_fetch,_reconnectInterval,_reconnectTimer,_lastEventId,_controller,_parser,_onError,_onMessage,_onOpen,_EventSource_instances,connect_fn,_onFetchResponse,_onFetchError,getRequestOptions_fn,_onEvent,_onRetryChange,failConnection_fn,scheduleReconnect_fn,_reconnect;class EventSource extends EventTarget{constructor(e,t){var r,n;super(),__privateAdd(this,_EventSource_instances),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,__privateAdd(this,_readyState),__privateAdd(this,_url),__privateAdd(this,_redirectUrl),__privateAdd(this,_withCredentials),__privateAdd(this,_fetch),__privateAdd(this,_reconnectInterval),__privateAdd(this,_reconnectTimer),__privateAdd(this,_lastEventId,null),__privateAdd(this,_controller),__privateAdd(this,_parser),__privateAdd(this,_onError,null),__privateAdd(this,_onMessage,null),__privateAdd(this,_onOpen,null),__privateAdd(this,_onFetchResponse,(async e=>{var t;__privateGet(this,_parser).reset();const{body:r,redirected:n,status:i,headers:o}=e;if(204===i)return __privateMethod(this,_EventSource_instances,failConnection_fn).call(this,"Server sent HTTP 204, not reconnecting",204),void this.close();if(__privateSet(this,_redirectUrl,n?new URL(e.url):void 0),200!==i)return void __privateMethod(this,_EventSource_instances,failConnection_fn).call(this,`Non-200 status code (${i})`,i);if(!(o.get("content-type")||"").startsWith("text/event-stream"))return void __privateMethod(this,_EventSource_instances,failConnection_fn).call(this,'Invalid content type, expected "text/event-stream"',i);if(__privateGet(this,_readyState)===this.CLOSED)return;__privateSet(this,_readyState,this.OPEN);const s=new Event("open");if(null==(t=__privateGet(this,_onOpen))||t.call(this,s),this.dispatchEvent(s),"object"!=typeof r||!r||!("getReader"in r))return __privateMethod(this,_EventSource_instances,failConnection_fn).call(this,"Invalid response body, expected a web ReadableStream",i),void this.close();const a=new TextDecoder,c=r.getReader();let A=!0;do{const{done:e,value:t}=await c.read();t&&__privateGet(this,_parser).feed(a.decode(t,{stream:!e})),e&&(A=!1,__privateGet(this,_parser).reset(),__privateMethod(this,_EventSource_instances,scheduleReconnect_fn).call(this))}while(A)})),__privateAdd(this,_onFetchError,(e=>{__privateSet(this,_controller,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&__privateMethod(this,_EventSource_instances,scheduleReconnect_fn).call(this,flattenError(e))})),__privateAdd(this,_onEvent,(e=>{"string"==typeof e.id&&__privateSet(this,_lastEventId,e.id);const t=new MessageEvent(e.event||"message",{data:e.data,origin:__privateGet(this,_redirectUrl)?__privateGet(this,_redirectUrl).origin:__privateGet(this,_url).origin,lastEventId:e.id||""});__privateGet(this,_onMessage)&&(!e.event||"message"===e.event)&&__privateGet(this,_onMessage).call(this,t),this.dispatchEvent(t)})),__privateAdd(this,_onRetryChange,(e=>{__privateSet(this,_reconnectInterval,e)})),__privateAdd(this,_reconnect,(()=>{__privateSet(this,_reconnectTimer,void 0),__privateGet(this,_readyState)===this.CONNECTING&&__privateMethod(this,_EventSource_instances,connect_fn).call(this)}));try{if(e instanceof URL)__privateSet(this,_url,e);else{if("string"!=typeof e)throw new Error("Invalid URL");__privateSet(this,_url,new URL(e,getBaseURL()))}}catch{throw syntaxError("An invalid or illegal string was specified")}__privateSet(this,_parser,createParser({onEvent:__privateGet(this,_onEvent),onRetry:__privateGet(this,_onRetryChange)})),__privateSet(this,_readyState,this.CONNECTING),__privateSet(this,_reconnectInterval,3e3),__privateSet(this,_fetch,null!=(r=null==t?void 0:t.fetch)?r:globalThis.fetch),__privateSet(this,_withCredentials,null!=(n=null==t?void 0:t.withCredentials)&&n),__privateMethod(this,_EventSource_instances,connect_fn).call(this)}get readyState(){return __privateGet(this,_readyState)}get url(){return __privateGet(this,_url).href}get withCredentials(){return __privateGet(this,_withCredentials)}get onerror(){return __privateGet(this,_onError)}set onerror(e){__privateSet(this,_onError,e)}get onmessage(){return __privateGet(this,_onMessage)}set onmessage(e){__privateSet(this,_onMessage,e)}get onopen(){return __privateGet(this,_onOpen)}set onopen(e){__privateSet(this,_onOpen,e)}addEventListener(e,t,r){const n=t;super.addEventListener(e,n,r)}removeEventListener(e,t,r){const n=t;super.removeEventListener(e,n,r)}close(){__privateGet(this,_reconnectTimer)&&clearTimeout(__privateGet(this,_reconnectTimer)),__privateGet(this,_readyState)!==this.CLOSED&&(__privateGet(this,_controller)&&__privateGet(this,_controller).abort(),__privateSet(this,_readyState,this.CLOSED),__privateSet(this,_controller,void 0))}}function getBaseURL(){const e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}_readyState=new WeakMap,_url=new WeakMap,_redirectUrl=new WeakMap,_withCredentials=new WeakMap,_fetch=new WeakMap,_reconnectInterval=new WeakMap,_reconnectTimer=new WeakMap,_lastEventId=new WeakMap,_controller=new WeakMap,_parser=new WeakMap,_onError=new WeakMap,_onMessage=new WeakMap,_onOpen=new WeakMap,_EventSource_instances=new WeakSet,connect_fn=function(){__privateSet(this,_readyState,this.CONNECTING),__privateSet(this,_controller,new AbortController),__privateGet(this,_fetch)(__privateGet(this,_url),__privateMethod(this,_EventSource_instances,getRequestOptions_fn).call(this)).then(__privateGet(this,_onFetchResponse)).catch(__privateGet(this,_onFetchError))},_onFetchResponse=new WeakMap,_onFetchError=new WeakMap,getRequestOptions_fn=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...__privateGet(this,_lastEventId)?{"Last-Event-ID":__privateGet(this,_lastEventId)}:void 0},cache:"no-store",signal:null==(e=__privateGet(this,_controller))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},_onEvent=new WeakMap,_onRetryChange=new WeakMap,failConnection_fn=function(e,t){var r;__privateGet(this,_readyState)!==this.CLOSED&&__privateSet(this,_readyState,this.CLOSED);const n=new ErrorEvent$1("error",{code:t,message:e});null==(r=__privateGet(this,_onError))||r.call(this,n),this.dispatchEvent(n)},scheduleReconnect_fn=function(e,t){var r;if(__privateGet(this,_readyState)===this.CLOSED)return;__privateSet(this,_readyState,this.CONNECTING);const n=new ErrorEvent$1("error",{code:t,message:e});null==(r=__privateGet(this,_onError))||r.call(this,n),this.dispatchEvent(n),__privateSet(this,_reconnectTimer,setTimeout(__privateGet(this,_reconnect),__privateGet(this,_reconnectInterval)))},_reconnect=new WeakMap,EventSource.CONNECTING=0,EventSource.OPEN=1,EventSource.CLOSED=2;class SseError extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}}class SSEClientTransport{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=null==t?void 0:t.eventSourceInit,this._requestInit=null==t?void 0:t.requestInit,this._authProvider=null==t?void 0:t.authProvider,this._fetch=null==t?void 0:t.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new UnauthorizedError("No auth provider");let t;try{t=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw null===(e=this.onerror)||void 0===e||e.call(this,t),t}if("AUTHORIZED"!==t)throw new UnauthorizedError;return await this._startOrAuth()}async _commonHeaders(){var e;const t={};if(this._authProvider){const e=await this._authProvider.tokens();e&&(t.Authorization=`Bearer ${e.access_token}`)}return this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion),new Headers({...t,...null===(e=this._requestInit)||void 0===e?void 0:e.headers})}_startOrAuth(){var e,t,r;const n=null!==(r=null!==(t=null===(e=null==this?void 0:this._eventSourceInit)||void 0===e?void 0:e.fetch)&&void 0!==t?t:this._fetch)&&void 0!==r?r:fetch;return new Promise(((e,t)=>{this._eventSource=new EventSource(this._url.href,{...this._eventSourceInit,fetch:async(e,t)=>{const r=await this._commonHeaders();r.set("Accept","text/event-stream");const i=await n(e,{...t,headers:r});return 401===i.status&&i.headers.has("www-authenticate")&&(this._resourceMetadataUrl=extractResourceMetadataUrl(i)),i}}),this._abortController=new AbortController,this._eventSource.onerror=r=>{var n;if(401===r.code&&this._authProvider)return void this._authThenStart().then(e,t);const i=new SseError(r.code,r.message,r);t(i),null===(n=this.onerror)||void 0===n||n.call(this,i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(r=>{var n;const i=r;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){return t(e),null===(n=this.onerror)||void 0===n||n.call(this,e),void this.close()}e()})),this._eventSource.onmessage=e=>{var t,r;const n=e;let i;try{i=JSONRPCMessageSchema.parse(JSON.parse(n.data))}catch(e){return void(null===(t=this.onerror)||void 0===t||t.call(this,e))}null===(r=this.onmessage)||void 0===r||r.call(this,i)}}))}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new UnauthorizedError("No auth provider");if("AUTHORIZED"!==await auth(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new UnauthorizedError("Failed to authorize")}async close(){var e,t,r;null===(e=this._abortController)||void 0===e||e.abort(),null===(t=this._eventSource)||void 0===t||t.close(),null===(r=this.onclose)||void 0===r||r.call(this)}async send(e){var t,r,n;if(!this._endpoint)throw new Error("Not connected");try{const n=await this._commonHeaders();n.set("content-type","application/json");const i={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(e),signal:null===(t=this._abortController)||void 0===t?void 0:t.signal},o=await(null!==(r=this._fetch)&&void 0!==r?r:fetch)(this._endpoint,i);if(!o.ok){if(401===o.status&&this._authProvider){this._resourceMetadataUrl=extractResourceMetadataUrl(o);if("AUTHORIZED"!==await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new UnauthorizedError;return this.send(e)}const t=await o.text().catch((()=>null));throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${t}`)}}catch(e){throw null===(n=this.onerror)||void 0===n||n.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}}class SSEConnection extends McpConnectionBase{createTransport(){const{url:e,requestInit:t}=extractRuntimeConfig(this.config);let r=!1;const n=new SSEClientTransport(new URL(e),{requestInit:t,eventSourceInit:{fetch:async(e,t)=>r?(await n.close(),Promise.resolve(new Response(null,{status:503,statusText:"SSE Connection terminated, will reconnect on next message"}))):(r=!0,fetch(e,t))}});return n}setupConnectionHandlers(){this.client&&(super.setupConnectionHandlers(),this.client.onerror=async e=>{await this.handleConnectionError(e,"SSE")})}}var crossSpawn={exports:{}};const path$5=path__default$1,which=which_1,getPathKey=pathKeyExports;function resolveCommandAttempt(e,t){const r=e.options.env||process.env,n=process.cwd(),i=null!=e.options.cwd,o=i&&void 0!==process.chdir&&!process.chdir.disabled;if(o)try{process.chdir(e.options.cwd)}catch(e){}let s;try{s=which.sync(e.command,{path:r[getPathKey({env:r})],pathExt:t?path$5.delimiter:void 0})}catch(e){}finally{o&&process.chdir(n)}return s&&(s=path$5.resolve(i?e.options.cwd:"",s)),s}function resolveCommand$1(e){return resolveCommandAttempt(e)||resolveCommandAttempt(e,!0)}var resolveCommand_1=resolveCommand$1,_escape={};const metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(e){return e=e.replace(metaCharsRegExp,"^$1")}function escapeArgument(e,t){return e=(e=`"${e=(e=(e=`${e}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(metaCharsRegExp,"^$1"),t&&(e=e.replace(metaCharsRegExp,"^$1")),e}_escape.command=escapeCommand,_escape.argument=escapeArgument;const fs$4=fs__default,shebangCommand=shebangCommand$2;function readShebang$1(e){const t=Buffer.alloc(150);let r;try{r=fs$4.openSync(e,"r"),fs$4.readSync(r,t,0,150,0),fs$4.closeSync(r)}catch(e){}return shebangCommand(t.toString())}var readShebang_1=readShebang$1;const path$4=path__default$1,resolveCommand=resolveCommand_1,escape$1=_escape,readShebang=readShebang_1,isWin$1="win32"===process.platform,isExecutableRegExp=/\.(?:com|exe)$/i,isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(e){e.file=resolveCommand(e);const t=e.file&&readShebang(e.file);return t?(e.args.unshift(e.file),e.command=t,resolveCommand(e)):e.file}function parseNonShell(e){if(!isWin$1)return e;const t=detectShebang(e),r=!isExecutableRegExp.test(t);if(e.options.forceShell||r){const r=isCmdShimRegExp.test(t);e.command=path$4.normalize(e.command),e.command=escape$1.command(e.command),e.args=e.args.map((e=>escape$1.argument(e,r)));const n=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${n}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function parse$d(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null);const n={command:e,args:t=t?t.slice(0):[],options:r=Object.assign({},r),file:void 0,original:{command:e,args:t}};return r.shell?n:parseNonShell(n)}var parse_1=parse$d;const isWin="win32"===process.platform;function notFoundError(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function hookChildProcess(e,t){if(!isWin)return;const r=e.emit;e.emit=function(n,i){if("exit"===n){const n=verifyENOENT(i,t);if(n)return r.call(e,"error",n)}return r.apply(e,arguments)}}function verifyENOENT(e,t){return isWin&&1===e&&!t.file?notFoundError(t.original,"spawn"):null}function verifyENOENTSync(e,t){return isWin&&1===e&&!t.file?notFoundError(t.original,"spawnSync"):null}var enoent$1={hookChildProcess:hookChildProcess,verifyENOENT:verifyENOENT,verifyENOENTSync:verifyENOENTSync,notFoundError:notFoundError};const cp=require$$0__default,parse$c=parse_1,enoent=enoent$1;function spawn(e,t,r){const n=parse$c(e,t,r),i=cp.spawn(n.command,n.args,n.options);return enoent.hookChildProcess(i,n),i}function spawnSync(e,t,r){const n=parse$c(e,t,r),i=cp.spawnSync(n.command,n.args,n.options);return i.error=i.error||enoent.verifyENOENTSync(i.status,n),i}crossSpawn.exports=spawn,crossSpawn.exports.spawn=spawn,crossSpawn.exports.sync=spawnSync,crossSpawn.exports._parse=parse$c,crossSpawn.exports._enoent=enoent;var crossSpawnExports=crossSpawn.exports,spawn$1=getDefaultExportFromCjs(crossSpawnExports);class ReadBuffer{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),deserializeMessage(t)}clear(){this._buffer=void 0}}function deserializeMessage(e){return JSONRPCMessageSchema.parse(JSON.parse(e))}function serializeMessage(e){return JSON.stringify(e)+"\n"}const DEFAULT_INHERITED_ENV_VARS="win32"===process$2.platform?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function getDefaultEnvironment(){const e={};for(const t of DEFAULT_INHERITED_ENV_VARS){const r=process$2.env[t];void 0!==r&&(r.startsWith("()")||(e[t]=r))}return e}class StdioClientTransport{constructor(e){this._abortController=new AbortController,this._readBuffer=new ReadBuffer,this._stderrStream=null,this._serverParams=e,"pipe"!==e.stderr&&"overlapped"!==e.stderr||(this._stderrStream=new PassThrough$e)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise(((e,t)=>{var r,n,i,o,s;this._process=spawn$1(this._serverParams.command,null!==(r=this._serverParams.args)&&void 0!==r?r:[],{env:{...getDefaultEnvironment(),...this._serverParams.env},stdio:["pipe","pipe",null!==(n=this._serverParams.stderr)&&void 0!==n?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:"win32"===process$2.platform&&isElectron(),cwd:this._serverParams.cwd}),this._process.on("error",(e=>{var r,n;"AbortError"!==e.name?(t(e),null===(n=this.onerror)||void 0===n||n.call(this,e)):null===(r=this.onclose)||void 0===r||r.call(this)})),this._process.on("spawn",(()=>{e()})),this._process.on("close",(e=>{var t;this._process=void 0,null===(t=this.onclose)||void 0===t||t.call(this)})),null===(i=this._process.stdin)||void 0===i||i.on("error",(e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)})),null===(o=this._process.stdout)||void 0===o||o.on("data",(e=>{this._readBuffer.append(e),this.processReadBuffer()})),null===(s=this._process.stdout)||void 0===s||s.on("error",(e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)})),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)}))}get stderr(){var e,t;return this._stderrStream?this._stderrStream:null!==(t=null===(e=this._process)||void 0===e?void 0:e.stderr)&&void 0!==t?t:null}get pid(){var e,t;return null!==(t=null===(e=this._process)||void 0===e?void 0:e.pid)&&void 0!==t?t:null}processReadBuffer(){for(var e,t;;)try{const t=this._readBuffer.readMessage();if(null===t)break;null===(e=this.onmessage)||void 0===e||e.call(this,t)}catch(e){null===(t=this.onerror)||void 0===t||t.call(this,e)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise((t=>{var r;if(!(null===(r=this._process)||void 0===r?void 0:r.stdin))throw new Error("Not connected");const n=serializeMessage(e);this._process.stdin.write(n)?t():this._process.stdin.once("drain",t)}))}}function isElectron(){return"type"in process$2}class StdioConnection extends McpConnectionBase{createTransport(){const e=extractRuntimeConfig(this.config);return new StdioClientTransport({command:e.command,args:e.args,cwd:e.cwd||homedir(),env:{...filterComateEnv(),...e.env},stderr:"pipe"})}setupConnectionHandlers(){if(!this.client||!this.transport)return;super.setupConnectionHandlers();const e=this.transport;e.stderr?.on("data",(e=>{const t=decodeBuffer$1(e).trimEnd();this.mcpLogger.info(`Server 发送信息: ${t}`)})),this.client.onerror=async e=>{await this.handleConnectionError(e,"Stdio")}}}function createMcpConnection(e,t,r,n){const i=t.parsed[e];if(!i)throw new Error(`Config for server ${e} not found in snapshot`);switch(i.transportType){case"streamableHttp":return new StreamableHttpConnection(e,t,r,n);case"sse":return new SSEConnection(e,t,r,n);default:return new StdioConnection(e,t,r,n)}}function calculateServerSetChanges(e,t){const r=new Set(Array.from(e.keys())),n=new Set(Object.entries(t).filter((([,e])=>!e.disabled)).map((([e])=>e))),i=new Set([...r].filter((e=>!n.has(e)))),o=new Set([...n].filter((e=>!r.has(e)))),s=new Set([...n].filter((e=>r.has(e))));return{serversToDisable:i,serversToEnable:o,serversToKeepEnabled:s}}const MAX_RECONNECT_ATTEMPTS=5,RECONNECT_BASE_DELAY_MS=1e3;class ConnectionController{eventBus;mcpLogger;reportError;connections=new Map;serverLoggers=new Map;reconnectStates=new Map;pool;constructor(e,t,r){this.eventBus=e,this.mcpLogger=t,this.reportError=r}getConnection(e){return this.connections.get(e)}getConnections(){return this.connections.values()}getConnectionCount(){return this.connections.size}getConnectionsForWebview(e){return Array.from(this.connections.values()).flatMap((t=>{const r=e.parsed[t.name];return r?[{...t.toWebviewFormat(),disabled:r.disabled,source:r.source}]:(this.mcpLogger.warn(`MCP 连接 ${t.name} 缺少配置,跳过上报到 Webview`),[])}))}handleStatusChange(e,t){"connected"===t&&this.clearReconnectState(e)}async reconcile(e,t){const r=e.parsed,n=t?.forceAll??!1,{serversToDisable:i,serversToEnable:o,serversToKeepEnabled:s}=calculateServerSetChanges(this.connections,r),a=["MCP 连接状态变更:",` 需要禁用的服务器: ${Array.from(i).join(", ")||"无"}`,` 需要启用的服务器: ${Array.from(o).join(", ")||"无"}`,` 保持状态的服务器: ${Array.from(s).join(", ")||"无"}`];this.mcpLogger.info(a.join("\n")),this.pool=new ConcurrentPool(5),this.handleServersToDisable(i),this.handleServersToEnable(o,e),this.handleServersWithConfigChanges(s,e,n),await this.pool.allTasksDone(),this.pool=void 0}async restart(e,t){if(!t.parsed[e])throw new Error(`Config for server ${e} not found in snapshot`);await this.connectWithFallback(e,t,"重启")}async deleteConnection(e){const t=this.connections.get(e);if(t){try{await t.disconnect(),this.mcpLogger.info(`Server ${e} 连接已关闭`)}catch(t){this.mcpLogger.error(`Server ${e} 连接关闭失败:`,t.message)}this.connections.delete(e)}const r=this.serverLoggers.get(e);r&&(r.dispose(),this.serverLoggers.delete(e)),this.clearReconnectState(e)}async dispose(){for(const e of Array.from(this.connections.keys()))await this.deleteConnection(e);for(const e of this.reconnectStates.values())e.timer&&clearTimeout(e.timer);this.reconnectStates.clear()}async scheduleReconnect(e,t){const r=t.parsed[e];if(!r)return void this.mcpLogger.warn(`Server ${e} 请求重连但未找到配置`);if(r.disabled)return void this.mcpLogger.info(`Server ${e} 已被禁用,跳过重连`);const n=this.reconnectStates.get(e)??{attempts:0};if(n.timer)return void this.mcpLogger.info(`Server ${e} 已计划重连,跳过重复请求`);if(n.attempts>=MAX_RECONNECT_ATTEMPTS)return void this.mcpLogger.error(`Server "${e}" 已达到最大重连次数 ${MAX_RECONNECT_ATTEMPTS},停止重连`);n.attempts+=1;const i=RECONNECT_BASE_DELAY_MS*Math.pow(2,n.attempts);this.mcpLogger.info(`Server "${e}" 将在 ${i}ms 后开始第 ${n.attempts} 次重连尝试`),n.timer=setTimeout((async()=>{if(n.timer=void 0,r.disabled)return this.mcpLogger.info(`Server ${e} 因被禁用停止重连`),void this.clearReconnectState(e);try{await this.connectWithFallback(e,t,"异常重连"),this.clearReconnectState(e),this.mcpLogger.info(`Server "${e}" 重连成功`)}catch(t){const r=t instanceof Error?t.message:String(t);this.mcpLogger.error(`Server "${e}" 重连失败: ${r}`)}}),i),this.reconnectStates.set(e,n)}handleServersToDisable(e){for(const t of e)this.pool.add((async()=>{try{await this.deleteConnection(t),this.mcpLogger.info(`禁用 Server ${t} 成功`)}catch(e){const r=e;this.mcpLogger.error(`禁用 Server ${t} 失败: ${r.message}`),this.reportError(r.friendlyMsg)}}))}handleServersToEnable(e,t){for(const r of e){t.parsed[r]&&this.pool.add((async()=>{await this.connectWithFallback(r,t,"启用")}))}}handleServersWithConfigChanges(e,t,r){for(const n of e){const e=t.parsed[n];if(!e||e.disabled)continue;const i=this.connections.get(n);if(!i)continue;(r||i.updateConfig(t))&&this.pool.add((async()=>{await this.connectWithFallback(n,t,"保持")}))}}async createConnection(e,t){const r=this.connections.get(e);r&&(await r.disconnect(),this.connections.delete(e),this.mcpLogger.info(`关闭已存在的 Server ${e} 连接(createConnection)`));let n=this.serverLoggers.get(e);n||(n=new McpLogger(e),this.serverLoggers.set(e,n));const i=createMcpConnection(e,t,this.eventBus,n);this.connections.set(e,i),await i.connect(),this.clearReconnectState(e);try{const e=kernel.env.workspaceInfo.workspaceFolders;e&&e.length>0&&i.setRoots(e.map((e=>({uri:e.uri,name:e.name}))))}catch(t){this.mcpLogger.warn(`为 Server ${e} 设置 roots 失败:`,t.message)}}async deleteWithoutLogger(e){const t=this.connections.get(e);t&&(await t.disconnect(),this.connections.delete(e)),this.clearReconnectState(e)}async tryFallbackToSSE(e,t){const r={...t,transportType:"sse"},n={raw:{[e]:r},parsed:{[e]:r}};await this.deleteWithoutLogger(e);let i=this.serverLoggers.get(e);i||(i=new McpLogger(e),this.serverLoggers.set(e,i));const o=createMcpConnection(e,n,this.eventBus,i);this.connections.set(e,o),await o.connect(),this.clearReconnectState(e),this.mcpLogger.info(`Server ${e} 成功降级到 SSE 传输方式`)}async connectWithFallback(e,t,r){try{await this.createConnection(e,t),this.mcpLogger.info(`${r} Server ${e} 成功`)}catch(n){const i=n,o=t.parsed[e];if(!o||i.strategy!==ErrorHandlingStrategy.FALLBACK_TO_SSE||"streamableHttp"!==o.transportType)throw this.mcpLogger.error(`${r} Server ${e} 失败: ${i.message}`),this.reportError(i.friendlyMsg),i;this.mcpLogger.info(`Server ${e} StreamableHttp 连接失败,尝试降级到 SSE: ${i.friendlyMsg}`);try{await this.tryFallbackToSSE(e,o)}catch(t){const r=t;throw this.mcpLogger.error(`Server ${e} SSE 降级也失败: ${r.message}`),this.reportError(`StreamableHttp 和 SSE 连接均失败: ${r.friendlyMsg}`),r}}}clearReconnectState(e){const t=this.reconnectStates.get(e);t?.timer&&clearTimeout(t.timer),t&&this.reconnectStates.delete(e)}}class McpEventGateway extends TypedEventEmitter{mcpLogger;requestHandlers=new Map;constructor(e){super(),this.mcpLogger=e,this.registerKernelHandlers()}registerRequestHandler(e,t){this.requestHandlers.set(e,t)}unregisterRequestHandler(e){this.requestHandlers.delete(e)}async ensureWorkspaceTrusted(e){try{return!!await kernel.connect.sendRequest(KERNEL_WORKSPACE_TRUSTED_FETCH_REQUEST)||(await this.notifyWorkspaceUntrusted(e),!1)}catch(t){const r=t instanceof Error?t.message:String(t);return this.mcpLogger.info(`IDE 未实现工作区信任功能(${r}),默认允许加载 MCP servers (调用者: ${e})`),!0}}async notifyConnectionListChange(e,t){try{await kernel.connect.sendWebviewMessage(PT_KERNEL_MCP_CONNECTION_CHANGED_NOTIFICATION,e),this.mcpLogger.info("推送 MCP 变动"+(t?` (调用者: ${t})`:""))}catch(e){this.mcpLogger.info(`无法推送到 Webview(Webview 可能未初始化)${t?` (调用者: ${t})`:""},错误信息: ${e}`)}}async notifyConfigUpdated(e){try{await kernel.connect.sendWebviewMessage(PT_KERNEL_MCP_CONFIG_UPDATED_NOTIFICATION,e),this.mcpLogger.info("推送 MCP Config 变动")}catch(e){this.mcpLogger.error("向 WebView 推送 MCP 配置事件失败",e.message)}}async notifyWorkspaceUntrusted(e){try{await kernel.connect.sendNotification(KERNEL_WORKSPACE_TRUST_REQUIRED_NOTIFICATION,{message:"工作区不被信任,无法启动 MCP。请信任此工作区以启用 MCP 功能。"})}catch(e){const t=e instanceof Error?e.message:String(e);this.mcpLogger.warn(`发送工作区信任通知失败: ${t}`)}this.mcpLogger.warn(`工作区不被信任,无法启动 MCP (调用者: ${e})`),this.emit("workspaceTrustRequired",{caller:e})}registerKernelHandlers(){kernel.connect.onNotification(IDE_WORKSPACE_TRUSTED_DID_CHANGE_NOTIFICATION,(()=>{this.emit("workspaceTrustChanged")})),kernel.connect.onWebviewMessage(PT_WEBVIEW_MCP_CONNECTION_RELOAD_NOTIFICATION,(e=>{this.emit("webviewReloadRequested",{requestId:e})})),kernel.connect.onWebviewMessage(PT_WEBVIEW_MCP_SERVER_RESTART_NOTIFICATION,(e=>{this.emit("webviewRestartRequested",e)}));const e=[PT_WEBVIEW_MCP_SERVER_ENV_CHECK_REQUEST,PT_WEBVIEW_MCP_CONFIG_CREATE_REQUEST,PT_WEBVIEW_MCP_CONFIG_FETCH_REQUEST,PT_WEBVIEW_MCP_CONFIG_UPDATE_REQUEST];for(const t of e)kernel.connect.onWebviewMessage(t,(e=>this.dispatchRequest(t,e)))}async dispatchRequest(e,t){const r=this.requestHandlers.get(e);if(!r)throw new Error(`No handler registered for ${e}`);try{return await r(t)}catch(t){throw this.mcpLogger.error(`处理 ${e} 请求失败`,t instanceof Error?t.message:String(t)),t}}}class McpEventBus extends TypedEventEmitter{emitConnectionStatusChange(e,t,r){this.emit("connectionStatusChanged",{name:e,oldStatus:t,newStatus:r})}emitConnectionToolsChange(e){this.emit("connectionToolsChanged",{name:e})}emitConnectionReconnectRequested(e){this.emit("connectionReconnectRequested",{name:e})}}class McpManager{logger;mcpLogger=new McpLogger;error;resolveMediatorInitialized;settingsWatcher;connectionController;eventGateway;eventBus;mediatorInitialized=new Promise((e=>{this.resolveMediatorInitialized=e}));constructor(e,t){this.logger=t,this.mcpLogger.info("McpManager 开始初始化"),this.eventGateway=new McpEventGateway(this.mcpLogger),this.eventBus=new McpEventBus,this.connectionController=new ConnectionController(this.eventBus,this.mcpLogger,this.setGlobalError.bind(this)),this.eventGateway.registerRequestHandler(PT_WEBVIEW_MCP_SERVER_ENV_CHECK_REQUEST,(e=>this.checkServerCommandAvailability(e?.command))),this.registerGatewayHandlers(),this.settingsWatcher=new McpSettingsWatcher(this.mcpLogger,e,this.eventGateway),this.settingsWatcher.onParsedSettingsChange(this.onNormalizedConfigChanged.bind(this)),this.initializeMcpServers()}async callTool(e,t,r,n){const i=crypto$7.randomUUID();this.mcpLogger.info(`MCP 工具调用关联信息 - messageId: ${n.messageId}, elementId: ${n.elementId}, conversationId: ${n.requestInfo?.conversationId}, userMessageId: ${n.requestInfo?.messageId}`),kernel.env.isInternal||reportCallMcpTool({serverName:e,toolName:t,messageId:n?.requestInfo?.messageId,conversationId:n?.requestInfo?.conversationId,uuid:n.elementId}).catch((()=>{this.mcpLogger.warn("callTool 信息上报失败")})),this.mcpLogger.info(`调用 MCP 工具 [${e}/${t}],参数:`,r);const o=this.connectionController.getConnection(e);if(!o||!o.isConnected){const t=o?`MCP Server ${e} 未连接`:`未找到 MCP Server ${e} 的连接`;throw this.mcpLogger.error(t),new Error(t)}const s=(await this.settingsWatcher.getMergedSnapshot()).parsed[e],a=s?.source;this.logger.logUploader?.logUserAction({category:"mcp",action:"callToolStart",label:i,content:{serverName:e,toolName:t,toolArguments:JSON.stringify(r),messageId:n.messageId,source:a}}).catch((()=>{this.mcpLogger.warn("callToolStart 信息上报失败")}));const c=o.getTimeout(),A=secondsToMs(c||DEFAULT_MCP_TIMEOUT_SECONDS$1),l=await o.getClient().request({method:"tools/call",params:{name:t,arguments:r}},CallToolResultSchema,{timeout:A,onprogress:({progress:r,message:n,total:i})=>{this.mcpLogger.info(`[${e}/${t}] progress: ${n||""} ${r?`(${r}/${i??"?"})`:""}`)}});this.mcpLogger.info(`MCP 工具 [${e}/${t}] 调用完成,结果:`,l.content);try{const e=l._meta;e?.previewUrl&&(this.mcpLogger.info(`工具 ${t} 返回预览 URL: ${e.previewUrl}`),n.virtualEditor.openUrlInEditorWebview({url:e.previewUrl,title:e.previewTitle||"预览"}))}catch(e){this.mcpLogger.warn(`触发预览失败: ${e.message}`)}return this.logger.logUploader?.logUserAction({category:"mcp",action:"callToolEnd",label:i,content:`error: ${l?.isError}`}).catch((()=>{this.mcpLogger.warn("callToolEnd 信息上报失败")})),l}async getMergedSnapshot(){return this.settingsWatcher.getMergedSnapshot()}async getConnectionsForWebview(){const e=await this.settingsWatcher.getMergedSnapshot();return this.connectionController.getConnectionsForWebview(e)}async dispose(){await this.connectionController.dispose(),await this.settingsWatcher.dispose(),this.mcpLogger.dispose()}registerGatewayHandlers(){this.eventGateway.on("workspaceTrustChanged",(async()=>{await this.reloadMcpServers(),await this.pushConnectionList("IDE_WORKSPACE_TRUSTED_DID_CHANGE_NOTIFICATION")})),this.eventGateway.on("webviewReloadRequested",(async({requestId:e})=>{await this.reloadMcpServers(),await this.pushConnectionList("PT_WEBVIEW_MCP_CONNECTION_LIST_RELOAD",e)})),this.eventGateway.on("webviewRestartRequested",(async({serverName:e,requestId:t})=>{await this.restartSingleServer(e),await this.pushConnectionList(`PT_WEBVIEW_MCP_SERVER_RESTART-${e}`,t)})),this.eventBus.on("connectionStatusChanged",(async({name:e,oldStatus:t,newStatus:r})=>{this.connectionController.handleStatusChange(e,r),await this.pushConnectionList(`onStatusChange-${e}: ${t} -> ${r}`)})),this.eventBus.on("connectionToolsChanged",(async({name:e})=>{await this.pushConnectionList(`onToolsChange-${e}`)})),this.eventBus.on("connectionReconnectRequested",(async({name:e})=>{const t=await this.settingsWatcher.getMergedSnapshot();await this.connectionController.scheduleReconnect(e,t),await this.pushConnectionList(`onReconnectRequested-${e}`)})),this.eventGateway.on("workspaceTrustRequired",(async({caller:e})=>{await this.pushConnectionList(`workspace untrusted - ${e}`)}))}async initializeMcpServers(){try{this.mcpLogger.info("等待 mediator 初始化"),await this.mediatorInitialized,this.mcpLogger.info("等待 webview 初始化"),await kernel.connect.webviewInitialized,this.mcpLogger.info("开始初始化 MCP Servers");const e=await this.settingsWatcher.getMergedSnapshot(),t=await this.settingsWatcher.getLayeredSnapshot();if(this.eventGateway.notifyConfigUpdated({layered:t}),Object.keys(e.parsed).length){await this.eventGateway.ensureWorkspaceTrusted("connectAllServers")&&(this.error=void 0,await this.connectionController.reconcile(e,{forceAll:!0}))}this.mcpLogger.info("MCP Servers 初始化完成")}catch(e){"ENOENT"!==e?.code&&(this.error={message:`MCP 初始化失败, ${e.message}`,path:this.mcpLogger.normalizedAbsolutedPath},this.mcpLogger.error(this.error.message),await this.eventGateway.notifyConfigUpdated({error:this.error.message}))}await this.pushConnectionList("initializeMcpServers")}async reloadMcpServers(){try{this.error=void 0;const e=await this.settingsWatcher.getMergedSnapshot();this.mcpLogger.info("开始重启 MCP servers");if(!await this.eventGateway.ensureWorkspaceTrusted("connectAllServers"))return;await this.connectionController.reconcile(e,{forceAll:!0})}catch(e){const t=`更新 MCP Servers 失败: ${e.message}`;this.mcpLogger.error(t),this.error={message:t,path:this.mcpLogger.normalizedAbsolutedPath}}}async pushConnectionList(e,t){await this.eventGateway.notifyConnectionListChange({servers:await this.getConnectionsForWebview(),error:this.error,id:t},e)}async onNormalizedConfigChanged(e){this.mcpLogger.info("检测到 MCP 配置变更,开始更新连接");try{this.error=void 0;if(!await this.eventGateway.ensureWorkspaceTrusted("connectAllServers"))return void await this.pushConnectionList("mcp.json changed");await this.connectionController.reconcile(e,{forceAll:!1}),await this.pushConnectionList("mcp.json changed")}catch(e){const t=`处理 MCP 配置变更失败: ${e.message}`;this.mcpLogger.error(t),this.error={message:t,path:this.mcpLogger.normalizedAbsolutedPath}}}async restartSingleServer(e){try{const t=await this.settingsWatcher.getMergedSnapshot();if(!t.parsed[e]){const t=`未找到 Server ${e} 的配置`;return this.mcpLogger.error(t),void(this.error={message:t,path:this.mcpLogger.normalizedAbsolutedPath})}if(!await this.eventGateway.ensureWorkspaceTrusted("restartSingleServer"))return;await this.connectionController.restart(e,t)}catch(t){const r=`重启 Server ${e} 失败: ${t.message}`;this.mcpLogger.error(r),this.error={message:r,path:this.mcpLogger.normalizedAbsolutedPath}}}setGlobalError(e){this.error={message:e,path:this.mcpLogger.normalizedAbsolutedPath}}async checkServerCommandAvailability(e,t){if(!e?.trim())return{available:!1,error:"empty command"};const r=t?.timeoutMs??4e3,n=[["--version"],["-v"],["version"]];for(const t of n){const n=await trySpawnOnce(e,t,r);if("ENOENT"===n.err?.code||"EACCES"===n.err?.code)return this.mcpLogger.warn(`命令 "${e}" 不可用 (${n.err.code}): ${n.err.message}\n${formatEnvDiagnostics()}`),{available:!1,error:n.err.message};if(0===n.code)return{available:!0};if(n.timeout)return this.mcpLogger.warn(`命令 "${e}" 执行超时 (${r}ms)\n${formatEnvDiagnostics()}`),{available:!1,error:"timeout"}}return this.mcpLogger.warn(`命令 "${e}" 不支持常见的版本查询参数 (--version, -v, version)\n${formatEnvDiagnostics()}`),{available:!1,error:"no supported version flag"}}}class AISAService{logger;mediator;agentConfigList=[];constructor(e,t){this.logger=t,this.mediator=e}async init(){try{await this.fetchAgentConfigList()}catch(e){this.logger.error("AISAService init failed",e.message)}}async fetchAgentConfigList(){try{const e=await this.mediator.userDetail();if(!e.name)return void this.logger.warn("AISAService: Cannot fetch agent config without user name");const t=await axiosInstance.get("/api/aidevops/autocomate/rest/autowork/v1/agentConfig/list",{headers:{"Content-Type":"application/json","login-name":e.name,"Uuap-login-name":e.name}});200===t.data.code&&t.data.data?(this.agentConfigList=t.data.data,this.logger.info(`AISAService: Successfully fetched ${this.agentConfigList.length} agent configs`)):this.logger.error("AISAService: Failed to fetch agent config list",t.data.message)}catch(e){this.logger.error("AISAService: Error fetching agent config list",e.message)}}async buildKnowledgeList(e,t=".comate/rules/aicr.mdr"){const r=[],n=path__default.join(e,t);let i=!1;try{await fs$1i.access(n),i=!0,r.push({id:t,name:t,type:"RULE",path:t}),this.logger.info(`AISAService: Rule file found at ${t}`)}catch{this.logger.info(`AISAService: Rule file not found at ${t}`)}try{const t=await this.getCommitDiffKnowledgeList(e);r.push(...t)}catch(e){this.logger.error("AISAService: Error getting commit diff",e.message)}return{knowledgeList:r,isRuleExists:i}}async getCommitDiffKnowledgeList(e){try{if(!await currentBranch({fs:fs$1i,dir:e,fullname:!1}))return this.logger.info("AISAService: No current branch found, skipping commit diff"),[];const t=await log$5({fs:fs$1i,dir:e,depth:2});if(t.length<1)return this.logger.info("AISAService: No commits found, skipping commit diff"),[];const r=t[0],n=t[1];if(!n)return this.logger.info("AISAService: No parent commit found, skipping commit diff"),[];this.logger.info(`AISAService: Getting diff between ${n.oid.slice(0,7)} and ${r.oid.slice(0,7)}`);const i=[],o=new Map;await walk$1({fs:fs$1i,dir:e,trees:[TREE({ref:n.oid}),TREE({ref:r.oid})],map:async(e,[t,r])=>{if("."===e)return;const n=await(t?.oid()),i=await(r?.oid()),s=await(t?.type()),a=await(r?.type());"tree"===s&&"tree"===a||n!==i&&(!n&&i&&"blob"===a?o.set(e,{type:"added"}):n&&i&&("blob"===s||"blob"===a)?o.set(e,{type:"modified"}):n&&!i&&"blob"===s&&o.set(e,{type:"deleted"}))}});for(const[t,{type:s}]of o){const o=path__default.basename(t);if("deleted"!==s)if("added"===s)i.push({id:t,name:o,type:"FILE",path:t,url:`file://${path__default.join(e,t)}`});else try{const s=await this.getDiffContent(e,n.oid,r.oid,t),a=this.parseDiffBlocks(s);if(1===a.length){const r=a[0];i.push({id:`${t}-${r.startLine}-${r.endLine}`,name:o,type:"CODE_SELECTION",filePath:t,path:t,selection:[r.startLine,r.endLine],url:`file://${path__default.join(e,t)}`})}else i.push({id:t,name:o,type:"FILE",path:t,url:`file://${path__default.join(e,t)}`})}catch(r){this.logger.warn(`AISAService: Failed to get diff for ${t}, using FILE type`,r.message),i.push({id:t,name:o,type:"FILE",path:t,url:`file://${path__default.join(e,t)}`})}}return this.logger.info(`AISAService: Successfully created ${i.length} diff knowledge items`),i}catch(e){return this.logger.error("AISAService: Error getting commit diff knowledge list",e.message),[]}}async getDiffContent(e,t,r,n){const[i,o]=await Promise.all([readBlob({fs:fs$1i,dir:e,oid:t,filepath:n}),readBlob({fs:fs$1i,dir:e,oid:r,filepath:n})]),s=(new TextDecoder).decode(i.blob),a=(new TextDecoder).decode(o.blob),c=s.split("\n"),A=a.split("\n");let l="",u=1;for(let e=0;e<Math.max(c.length,A.length);e++)c[e]!==A[e]&&(l+=`@@ -${u},1 +${u},1 @@\n`,void 0!==c[e]&&(l+=`-${c[e]}\n`),void 0!==A[e]&&(l+=`+${A[e]}\n`)),u++;return l}parseDiffBlocks(e){const t=[],r=e.split("\n");let n=null;for(const e of r){const r=/^@@\s+-\d+(?:,\d+)?\s+\+(\d+)(?:,(\d+))?\s+@@/.exec(e);if(r){n&&t.push(n);const e=parseInt(r[1],10);n={startLine:e,endLine:e+(r[2]?parseInt(r[2],10):1)-1}}}n&&t.push(n);const i=[];for(const e of t)if(0===i.length)i.push(e);else{const t=i[i.length-1];e.startLine-t.endLine<=3?t.endLine=Math.max(t.endLine,e.endLine):i.push(e)}return i}async buildAISAPayload(e,t,r){try{const{knowledgeList:n,isRuleExists:i}=await this.buildKnowledgeList(e,t),o=i?"严格按照规则文件进行代码检查":"为我的代码库扫描代码质量与安全风险",s=this.agentConfigList[0],a={};this.agentConfigList.forEach((e=>{a[e.agentId]=e}));const c=s?{...s,errors:[],subagents:s.subAgents?.map((e=>a[e])).filter(Boolean)}:void 0;return{conversationType:AgentConversationType.AgentConversation,payload:{query:o,knowledgeList:n,model:r,agent:c},messageType:"add-message",conversationId:""}}catch(e){throw this.logger.error("AISAService: Error building AISA payload",e.message),e}}dispose(){this.agentConfigList=[]}}class SADiagnostic{logger;mediator;pluginName="devaux";capabilityName="SAProvider";systemInfo;aisaService;constructor(e,t){this.logger=t,this.mediator=e,this.aisaService=new AISAService(e,t)}async init(e,t,r){try{this.systemInfo=e;const n=crypto$7.randomUUID(),i=await this.mediator.sendToPluginOnce(n,{action:ACTION_SA_SCAN_DIAGNOSTIC,payload:{pluginName:this.pluginName,capabilityName:this.capabilityName,systemInfo:e,context:t,scanType:"config",diagnosticScanId:Date.now().toString(),data:r}}),o=i?.data.payload.chunk;if("AICR"===r?.type)return o;if(!o||!o.scanEnabled)return o;let s=0;for(;s<3;){const t=await this.mediator.sendToPluginOnce(n,{action:ACTION_SA_SCAN_DIAGNOSTIC,payload:{pluginName:this.pluginName,capabilityName:this.capabilityName,systemInfo:e,scanType:"init",diagnosticScanId:Date.now().toString(),data:r}}),i=t?.data.payload.chunk;if(i)return o}return{scanEnabled:!1,intervalMinute:o.intervalMinute}}catch(e){return this.logger.error("SA SCAN 初始化异常",e.message),{scanEnabled:!1,intervalMinute:10}}}async getSADiagnosticScanResult(e,t){try{const r=crypto$7.randomUUID();for await(const n of this.mediator.sendToPlugin(r,{action:ACTION_SA_SCAN_DIAGNOSTIC,payload:{pluginName:this.pluginName,capabilityName:this.capabilityName,systemInfo:e,scanType:"getResult",absolutePath:t,diagnosticScanId:Date.now().toString()}}))return n?.data.payload.chunk}catch(e){this.logger.error("获取SA扫描结果异常",e.message)}}async buildAISAPayload(e,t,r){return await this.aisaService.buildAISAPayload(e,t,r)}async initAISAService(){await this.aisaService.init()}dispose(){const e=crypto$7.randomUUID();this.mediator.launchSendToPlugin(e,{action:ACTION_SA_SCAN_DIAGNOSTIC,payload:{pluginName:this.pluginName,capabilityName:this.capabilityName,systemInfo:this.systemInfo,scanType:"destroy",diagnosticScanId:Date.now().toString()}}),this.aisaService.dispose()}}var dist={},factory={},httpProxyMiddleware={},httpProxy$3={exports:{}},eventemitter3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,n,o,s){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new i(n,o||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,i,o,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,A,l=this._events[a],u=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,n),!0;case 4:return l.fn.call(l.context,t,n,i),!0;case 5:return l.fn.call(l.context,t,n,i,o),!0;case 6:return l.fn.call(l.context,t,n,i,o,s),!0}for(A=1,c=new Array(u-1);A<u;A++)c[A-1]=arguments[A];l.fn.apply(l.context,c)}else{var d,h=l.length;for(A=0;A<h;A++)switch(l[A].once&&this.removeListener(e,l[A].fn,void 0,!0),u){case 1:l[A].fn.call(l[A].context);break;case 2:l[A].fn.call(l[A].context,t);break;case 3:l[A].fn.call(l[A].context,t,n);break;case 4:l[A].fn.call(l[A].context,t,n,i);break;default:if(!c)for(d=1,c=new Array(u-1);d<u;d++)c[d-1]=arguments[d];l[A].fn.apply(l[A].context,c)}}return!0},a.prototype.on=function(e,t,r){return o(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,i){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return s(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||i&&!a.once||n&&a.context!==n||s(this,o);else{for(var c=0,A=[],l=a.length;c<l;c++)(a[c].fn!==t||i&&!a[c].once||n&&a[c].context!==n)&&A.push(a[c]);A.length?this._events[o]=1===A.length?A[0]:A:s(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(eventemitter3);var eventemitter3Exports=eventemitter3.exports,common$3={},requiresPort=function(e,t){if(t=t.split(":")[0],!(e=+e))return!1;switch(t){case"http":case"ws":return 80!==e;case"https":case"wss":return 443!==e;case"ftp":return 21!==e;case"gopher":return 70!==e;case"file":return!1}return 0!==e};!function(e){var t=common$3,r=require$$0$e,n=t$1._extend,i=requiresPort,o=/(^|,)\s*upgrade\s*($|,)/i,s=/^https|wss/;t.isSSL=s,t.setupOutgoing=function(e,a,c,A){e.port=a[A||"target"].port||(s.test(a[A||"target"].protocol)?443:80),["host","hostname","socketPath","pfx","key","passphrase","cert","ca","ciphers","secureProtocol"].forEach((function(t){e[t]=a[A||"target"][t]})),e.method=a.method||c.method,e.headers=n({},c.headers),a.headers&&n(e.headers,a.headers),a.auth&&(e.auth=a.auth),a.ca&&(e.ca=a.ca),s.test(a[A||"target"].protocol)&&(e.rejectUnauthorized=void 0===a.secure||a.secure),e.agent=a.agent||!1,e.localAddress=a.localAddress,e.agent||(e.headers=e.headers||{},"string"==typeof e.headers.connection&&o.test(e.headers.connection)||(e.headers.connection="close"));var l=a[A||"target"],u=l&&!1!==a.prependPath&&l.path||"",d=a.toProxy?c.url:r.parse(c.url).path||"";return d=a.ignorePath?"":d,e.path=t.urlJoin(u,d),a.changeOrigin&&(e.headers.host=i(e.port,a[A||"target"].protocol)&&!~e.host.indexOf(":")?e.host+":"+e.port:e.host),e},t.setupSocket=function(e){return e.setTimeout(0),e.setNoDelay(!0),e.setKeepAlive(!0,0),e},t.getPort=function(e){var r=e.headers.host?e.headers.host.match(/:(\d+)/):"";return r?r[1]:t.hasEncryptedConnection(e)?"443":"80"},t.hasEncryptedConnection=function(e){return Boolean(e.connection.encrypted||e.connection.pair)},t.urlJoin=function(){var e,t=Array.prototype.slice.call(arguments),r=t.length-1,n=t[r].split("?");return t[r]=n.shift(),(e=[t.filter(Boolean).join("/").replace(/\/+/g,"/").replace("http:/","http://").replace("https:/","https://")]).push.apply(e,n),e.join("?")},t.rewriteCookieProperty=function e(t,r,n){return Array.isArray(t)?t.map((function(t){return e(t,r,n)})):t.replace(new RegExp("(;\\s*"+n+"=)([^;]+)","i"),(function(e,t,n){var i;if(n in r)i=r[n];else{if(!("*"in r))return e;i=r["*"]}return i?t+i:""}))}}();var url$3=require$$0$e,common$2=common$3,redirectRegex=/^201|30(1|2|7|8)$/,webOutgoing={removeChunked:function(e,t,r){"1.0"===e.httpVersion&&delete r.headers["transfer-encoding"]},setConnection:function(e,t,r){"1.0"===e.httpVersion?r.headers.connection=e.headers.connection||"close":"2.0"===e.httpVersion||r.headers.connection||(r.headers.connection=e.headers.connection||"keep-alive")},setRedirectHostRewrite:function(e,t,r,n){if((n.hostRewrite||n.autoRewrite||n.protocolRewrite)&&r.headers.location&&redirectRegex.test(r.statusCode)){var i=url$3.parse(n.target),o=url$3.parse(r.headers.location);if(i.host!=o.host)return;n.hostRewrite?o.host=n.hostRewrite:n.autoRewrite&&(o.host=e.headers.host),n.protocolRewrite&&(o.protocol=n.protocolRewrite),r.headers.location=o.format()}},writeHeaders:function(e,t,r,n){var i,o=n.cookieDomainRewrite,s=n.cookiePathRewrite,a=n.preserveHeaderKeyCase;if("string"==typeof o&&(o={"*":o}),"string"==typeof s&&(s={"*":s}),a&&null!=r.rawHeaders){i={};for(var c=0;c<r.rawHeaders.length;c+=2){var A=r.rawHeaders[c];i[A.toLowerCase()]=A}}Object.keys(r.headers).forEach((function(e){var n=r.headers[e];a&&i&&(e=i[e]||e),function(e,r){null!=r&&(o&&"set-cookie"===e.toLowerCase()&&(r=common$2.rewriteCookieProperty(r,o,"domain")),s&&"set-cookie"===e.toLowerCase()&&(r=common$2.rewriteCookieProperty(r,s,"path")),t.setHeader(String(e).trim(),r))}(e,n)}))},writeStatusCode:function(e,t,r){r.statusMessage?(t.statusCode=r.statusCode,t.statusMessage=r.statusMessage):t.statusCode=r.statusCode}},httpNative=require$$0$f,httpsNative=require$$1$3,web_o=webOutgoing,common$1=common$3,followRedirects=followRedirectsExports;web_o=Object.keys(web_o).map((function(e){return web_o[e]}));var nativeAgents={http:httpNative,https:httpsNative},webIncoming={deleteLength:function(e,t,r){"DELETE"!==e.method&&"OPTIONS"!==e.method||e.headers["content-length"]||(e.headers["content-length"]="0",delete e.headers["transfer-encoding"])},timeout:function(e,t,r){r.timeout&&e.socket.setTimeout(r.timeout)},XHeaders:function(e,t,r){if(r.xfwd){var n=e.isSpdy||common$1.hasEncryptedConnection(e),i={for:e.connection.remoteAddress||e.socket.remoteAddress,port:common$1.getPort(e),proto:n?"https":"http"};["for","port","proto"].forEach((function(t){e.headers["x-forwarded-"+t]=(e.headers["x-forwarded-"+t]||"")+(e.headers["x-forwarded-"+t]?",":"")+i[t]})),e.headers["x-forwarded-host"]=e.headers["x-forwarded-host"]||e.headers.host||""}},stream:function(e,t,r,n,i,o){i.emit("start",e,t,r.target||r.forward);var s=r.followRedirects?followRedirects:nativeAgents,a=s.http,c=s.https;if(r.forward){var A=("https:"===r.forward.protocol?c:a).request(common$1.setupOutgoing(r.ssl||{},r,e,"forward")),l=h(A,r.forward);if(e.on("error",l),A.on("error",l),(r.buffer||e).pipe(A),!r.target)return t.end()}var u=("https:"===r.target.protocol?c:a).request(common$1.setupOutgoing(r.ssl||{},r,e));u.on("socket",(function(n){i&&!u.getHeader("expect")&&i.emit("proxyReq",u,e,t,r)})),r.proxyTimeout&&u.setTimeout(r.proxyTimeout,(function(){u.abort()})),e.on("aborted",(function(){u.abort()}));var d=h(u,r.target);function h(r,n){return function(s){if(e.socket.destroyed&&"ECONNRESET"===s.code)return i.emit("econnreset",s,e,t,n),r.abort();o?o(s,e,t,n):i.emit("error",s,e,t,n)}}e.on("error",d),u.on("error",d),(r.buffer||e).pipe(u),u.on("response",(function(n){if(i&&i.emit("proxyRes",n,e,t),!t.headersSent&&!r.selfHandleResponse)for(var o=0;o<web_o.length&&!web_o[o](e,t,n,r);o++);t.finished?i&&i.emit("end",e,t,n):(n.on("end",(function(){i&&i.emit("end",e,t,n)})),r.selfHandleResponse||n.pipe(t))}))}},http$5=require$$0$f,https$1=require$$1$3,common=common$3,wsIncoming={checkMethodAndHeader:function(e,t){return"GET"===e.method&&e.headers.upgrade?"websocket"!==e.headers.upgrade.toLowerCase()?(t.destroy(),!0):void 0:(t.destroy(),!0)},XHeaders:function(e,t,r){if(r.xfwd){var n={for:e.connection.remoteAddress||e.socket.remoteAddress,port:common.getPort(e),proto:common.hasEncryptedConnection(e)?"wss":"ws"};["for","port","proto"].forEach((function(t){e.headers["x-forwarded-"+t]=(e.headers["x-forwarded-"+t]||"")+(e.headers["x-forwarded-"+t]?",":"")+n[t]}))}},stream:function(e,t,r,n,i,o){var s=function(e,t){return Object.keys(t).reduce((function(e,r){var n=t[r];if(!Array.isArray(n))return e.push(r+": "+n),e;for(var i=0;i<n.length;i++)e.push(r+": "+n[i]);return e}),[e]).join("\r\n")+"\r\n\r\n"};common.setupSocket(t),n&&n.length&&t.unshift(n);var a=(common.isSSL.test(r.target.protocol)?https$1:http$5).request(common.setupOutgoing(r.ssl||{},r,e));return i&&i.emit("proxyReqWs",a,e,t,r,n),a.on("error",c),a.on("response",(function(e){e.upgrade||(t.write(s("HTTP/"+e.httpVersion+" "+e.statusCode+" "+e.statusMessage,e.headers)),e.pipe(t))})),a.on("upgrade",(function(e,r,n){r.on("error",c),r.on("end",(function(){i.emit("close",e,r,n)})),t.on("error",(function(){r.end()})),common.setupSocket(r),n&&n.length&&r.unshift(n),t.write(s("HTTP/1.1 101 Switching Protocols",e.headers)),r.pipe(t).pipe(r),i.emit("open",r),i.emit("proxySocket",r)})),a.end();function c(r){o?o(r,e,t):i.emit("error",r,e,t),t.end()}}};
|
|
538
538
|
/*!
|
|
539
539
|
* Array of passes.
|