xiaozhi-client 1.9.3-rc.0 → 1.9.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.
@@ -1,12 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * MCP Server Proxy - 重构版
4
- * 现在基于 MCPServiceManager 和传输层抽象实现
5
- * 提供 Stdio 模式的 MCP 服务器,主要用于 Cursor 等客户端
6
- */
7
- /**
8
- * 主函数:启动 MCP 服务器代理
9
- */
10
- declare function main(): Promise<void>;
11
-
12
- export { main };
@@ -1,32 +0,0 @@
1
- #!/usr/bin/env node
2
- var Oe=Object.defineProperty;var c=(i,e)=>Oe(i,"name",{value:e,configurable:!0});import R from"process";import{EventEmitter as it}from"events";import{isAbsolute as Ht,resolve as jt}from"path";var O=(r=>(r.STDIO="stdio",r.SSE="sse",r.STREAMABLE_HTTP="streamable-http",r))(O||{});function He(i){return typeof i=="object"&&i!==null&&"type"in i&&i.type==="object"}c(He,"isValidToolJSONSchema");function Me(i){return He(i)?i:{type:"object",properties:{},required:[],additionalProperties:!0}}c(Me,"ensureToolJSONSchema");var H;(t=>{function i(r){if(!r||typeof r!="object")return r;let o=JSON.parse(JSON.stringify(r));if(!("type"in o))return o;let n=o.type;if(n==="sse"||n==="streamable-http")return o;let s;return n==="streamableHttp"||n==="streamable_http"?s="streamable-http":n==="s_se"||n==="s-se"?s="sse":s=e(n),(s==="sse"||s==="streamable-http")&&(o.type=s),o}t.normalizeTypeField=i,c(i,"normalizeTypeField");function e(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}c(e,"convertToKebabCase")})(H||={});function ye(i,e){try{let r=new URL(i).pathname;return r.endsWith("/sse")?"sse":r.endsWith("/mcp")?"streamable-http":(e?.serviceName,"streamable-http")}catch{return e?.serviceName,"streamable-http"}}c(ye,"inferTransportTypeFromUrl");function Pe(i){if(i.type)return H.normalizeTypeField(i);if(i.command)return{...i,type:"stdio"};if(i.url!==void 0&&i.url!==null){let e=ye(i.url,{serviceName:i.name});return{...i,type:e}}throw new Error(`\u65E0\u6CD5\u4E3A\u670D\u52A1 ${i.name} \u63A8\u65AD\u4F20\u8F93\u7C7B\u578B\u3002\u8BF7\u663E\u5F0F\u6307\u5B9A type \u5B57\u6BB5\uFF0C\u6216\u63D0\u4F9B command/url \u914D\u7F6E`)}c(Pe,"inferTransportTypeFromConfig");import*as v from"fs";import*as M from"path";import B from"chalk";import j from"pino";import{z as je}from"zod";var Fe=je.enum(["fatal","error","warn","info","debug","trace"]);function ze(i){let e=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),r=String(i.getDate()).padStart(2,"0"),o=String(i.getHours()).padStart(2,"0"),n=String(i.getMinutes()).padStart(2,"0"),s=String(i.getSeconds()).padStart(2,"0");return`${e}-${t}-${r} ${o}:${n}:${s}`}c(ze,"formatDateTime");var ae=class{static{c(this,"Logger")}logFilePath=null;pinoInstance;isDaemonMode;logLevel;maxLogFileSize=10*1024*1024;maxLogFiles=5;constructor(e="info"){this.isDaemonMode=process.env.XIAOZHI_DAEMON==="true",this.logLevel=this.validateLogLevel(e),this.pinoInstance=this.createPinoInstance()}validateLogLevel(e){let t=e.toLowerCase(),r=Fe.safeParse(t);return r.success?r.data:"info"}createPinoInstance(){let e=[];if(!this.isDaemonMode){let t=this.createOptimizedConsoleStream();e.push({level:this.logLevel,stream:t})}return this.logFilePath&&e.push({level:this.logLevel,stream:j.destination({dest:this.logFilePath,sync:!1,append:!0,mkdir:!0})}),e.length===0&&e.push({level:this.logLevel,stream:j.destination({dest:"/dev/null"})}),j({level:this.logLevel,timestamp:j.stdTimeFunctions?.isoTime||(()=>`,"time":${Date.now()}`),formatters:{level:c((t,r)=>({level:r}),"level")},base:null,serializers:{err:j.stdSerializers?.err||(t=>t)}},j.multistream(e,{dedupe:!0}))}createOptimizedConsoleStream(){let e=new Map([[20,{name:"DEBUG",color:B.gray}],[30,{name:"INFO",color:B.blue}],[40,{name:"WARN",color:B.yellow}],[50,{name:"ERROR",color:B.red}],[60,{name:"FATAL",color:B.red}]]);return{write:c(t=>{try{let r=JSON.parse(t),o=this.formatConsoleMessageOptimized(r,e);this.safeWrite(`${o}
3
- `)}catch{this.safeWrite(t)}},"write")}}safeWrite(e){try{process.stderr&&typeof process.stderr.write=="function"&&process.stderr.write(e)}catch{}}formatConsoleMessageOptimized(e,t){let r=ze(new Date),o=t.get(e.level)||{name:"UNKNOWN",color:c(a=>a,"color")},n=o.color(`[${o.name}]`),s=e.msg;if(e.args&&Array.isArray(e.args)){let a=e.args.map(u=>typeof u=="object"?JSON.stringify(u):String(u)).join(" ");s=`${s} ${a}`}return`[${r}] ${n} ${s}`}initLogFile(e){this.logFilePath=M.join(e,"xiaozhi.log"),this.rotateLogFileIfNeeded(),v.existsSync(this.logFilePath)||v.writeFileSync(this.logFilePath,""),this.pinoInstance=this.createPinoInstance()}enableFileLogging(e){e&&this.logFilePath&&(this.pinoInstance=this.createPinoInstance())}info(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}success(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}warn(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.warn(e):this.pinoInstance.warn({args:t},e):this.pinoInstance.warn(e,t[0]||"")}error(e,...t){if(typeof e=="string")if(t.length===0)this.pinoInstance.error(e);else{let r=t.map(o=>o instanceof Error?this.pinoInstance.level==="debug"?o.message:{message:o.message,stack:o.stack,name:o.name,cause:o.cause}:o);this.pinoInstance.error({args:r},e)}else{let r=this.enhanceErrorObject(e);this.pinoInstance.error(r,t[0]||"")}}debug(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.debug(e):this.pinoInstance.debug({args:t},e):this.pinoInstance.debug(e,t[0]||"")}log(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}enhanceErrorObject(e){let t={...e};for(let[r,o]of Object.entries(t))o instanceof Error&&(t[r]={message:o.message,stack:o.stack,name:o.name,cause:o.cause});return t}rotateLogFileIfNeeded(){if(!(!this.logFilePath||!v.existsSync(this.logFilePath)))try{v.statSync(this.logFilePath).size>this.maxLogFileSize&&this.rotateLogFile()}catch{}}rotateLogFile(){if(this.logFilePath)try{let e=M.dirname(this.logFilePath),t=M.basename(this.logFilePath,".log");for(let o=this.maxLogFiles-1;o>=1;o--){let n=M.join(e,`${t}.${o}.log`),s=M.join(e,`${t}.${o+1}.log`);v.existsSync(n)&&(o===this.maxLogFiles-1?v.unlinkSync(n):v.renameSync(n,s))}let r=M.join(e,`${t}.1.log`);v.renameSync(this.logFilePath,r)}catch{}}cleanupOldLogs(){if(this.logFilePath)try{let e=M.dirname(this.logFilePath),t=M.basename(this.logFilePath,".log");for(let r=this.maxLogFiles+1;r<=this.maxLogFiles+10;r++){let o=M.join(e,`${t}.${r}.log`);v.existsSync(o)&&v.unlinkSync(o)}}catch{}}setLogFileOptions(e,t){this.maxLogFileSize=e,this.maxLogFiles=t}withTag(e){return this}close(){}setLevel(e){this.logLevel=this.validateLogLevel(e),this.pinoInstance=this.createPinoInstance()}getLevel(){return this.logLevel}},ie=null,_e="info";function Ue(){return ie||(ie=new ae(_e)),ie}c(Ue,"getLogger");var l=Ue();var Wt=l.withTag("ConfigAdapter");function be(i){return i.includes("modelscope.net")||i.includes("modelscope.cn")}c(be,"isModelScopeURL");import{copyFileSync as Je,existsSync as K,readFileSync as Ve,writeFileSync as Ge}from"fs";import{dirname as Ke,resolve as A}from"path";import{fileURLToPath as qe}from"url";import{EventEmitter as We}from"events";var le=class extends We{static{c(this,"EventBus")}logger;eventStats=new Map;maxListeners=50;constructor(){super(),this.logger=l.withTag("EventBus"),this.setMaxListeners(this.maxListeners),this.setupErrorHandling()}setupErrorHandling(){this.on("error",e=>{this.logger.error("EventBus \u5185\u90E8\u9519\u8BEF:",e)}),this.on("newListener",e=>{let t=this.listenerCount(e);t>this.maxListeners*.8&&this.logger.warn(`\u4E8B\u4EF6 ${e} \u7684\u76D1\u542C\u5668\u6570\u91CF\u8FC7\u591A: ${t}`)})}emitEvent(e,t){try{return this.updateEventStats(e),this.logger.debug(`\u53D1\u5C04\u4E8B\u4EF6: ${e}`,t),super.emit(e,t)}catch(r){return this.logger.error(`\u53D1\u5C04\u4E8B\u4EF6\u5931\u8D25: ${e}`,r),r instanceof Error&&this.emit("error",r),!1}}onEvent(e,t){return this.logger.debug(`\u6DFB\u52A0\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.on(e,t)}onceEvent(e,t){this.logger.debug(`\u6DFB\u52A0\u4E00\u6B21\u6027\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`);let r=c(o=>{try{t(o)}catch(n){throw this.emit("error",n),n}finally{this.offEvent(e,r)}},"onceListener");return this.on(e,r)}offEvent(e,t){return this.logger.debug(`\u79FB\u9664\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.off(e,t)}updateEventStats(e){let t=this.eventStats.get(e)||{count:0,lastEmitted:new Date};t.count++,t.lastEmitted=new Date,this.eventStats.set(e,t)}getEventStats(){let e={};for(let[t,r]of this.eventStats)e[t]={...r};return e}getListenerStats(){let e={};for(let t of this.eventNames())e[t]=this.listenerCount(t);return e}clearEventStats(){this.eventStats.clear(),this.logger.info("\u4E8B\u4EF6\u7EDF\u8BA1\u5DF2\u6E05\u7406")}getStatus(){return{totalEvents:this.eventStats.size,totalListeners:Object.values(this.getListenerStats()).reduce((e,t)=>e+t,0),eventStats:this.getEventStats(),listenerStats:this.getListenerStats()}}destroy(){this.removeAllListeners(),this.eventStats.clear(),this.logger.info("EventBus \u5DF2\u9500\u6BC1")}},ce=null;function b(){return ce||(ce=new le),ce}c(b,"getEventBus");function Be(i){if(!i||typeof i!="object")throw new Error("\u670D\u52A1\u914D\u7F6E\u5FC5\u987B\u662F\u4E00\u4E2A\u6709\u6548\u7684\u5BF9\u8C61");if("command"in i&&typeof i.command=="string")return"stdio";if("type"in i&&i.type==="sse")return"sse";if("type"in i&&i.type==="streamable-http"||"url"in i&&typeof i.url=="string")return"streamable-http";throw new Error("\u65E0\u6CD5\u8BC6\u522B\u7684 MCP \u670D\u52A1\u914D\u7F6E\u7C7B\u578B\u3002\u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5\uFF08stdio\uFF09\u3001type: 'sse' \u5B57\u6BB5\uFF08sse\uFF09\u6216 url \u5B57\u6BB5\uFF08streamable-http\uFF09")}c(Be,"getMcpServerCommunicationType");function ue(i,e){if(!e||typeof e!="object"||Array.isArray(e))return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u5FC5\u987B\u662F\u4E00\u4E2A\u5BF9\u8C61`};try{let t=Be(e),r=e;switch(t){case"stdio":if(!r.command||typeof r.command!="string")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7F3A\u5C11\u5FC5\u9700\u7684 command \u5B57\u6BB5\u6216\u5B57\u6BB5\u7C7B\u578B\u4E0D\u6B63\u786E`};if(!Array.isArray(r.args))return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4`};if(r.env&&(typeof r.env!="object"||Array.isArray(r.env)))return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61`};break;case"sse":if(r.type!=="sse")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 type \u5B57\u6BB5\u5FC5\u987B\u662F "sse"`};if(!r.url||typeof r.url!="string")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7F3A\u5C11\u5FC5\u9700\u7684 url \u5B57\u6BB5\u6216\u5B57\u6BB5\u7C7B\u578B\u4E0D\u6B63\u786E`};if(r.headers&&(typeof r.headers!="object"||Array.isArray(r.headers)))return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 headers \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61`};break;case"streamable-http":if(!r.url||typeof r.url!="string")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7F3A\u5C11\u5FC5\u9700\u7684 url \u5B57\u6BB5\u6216\u5B57\u6BB5\u7C7B\u578B\u4E0D\u6B63\u786E`};if(r.type&&r.type!=="streamable-http")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 type \u5B57\u6BB5\u5982\u679C\u5B58\u5728\uFF0C\u5FC5\u987B\u662F "streamable-http"`};if(r.headers&&(typeof r.headers!="object"||Array.isArray(r.headers)))return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 headers \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61`};break;default:return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u7C7B\u578B\u65E0\u6CD5\u8BC6\u522B`}}return{valid:!0}}catch(t){return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u65E0\u6548: ${t instanceof Error?t.message:"\u672A\u77E5\u9519\u8BEF"}`}}}c(ue,"validateMcpServerConfig");import*as q from"comment-json";import we from"dayjs";import ge from"json5";import*as Re from"json5-writer";var Ee=Ke(qe(import.meta.url)),me={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},pe=class i{static{c(this,"ConfigManager")}static instance;defaultConfigPath;config=null;currentConfigPath=null;json5Writer=null;eventBus=b();statsUpdateLocks=new Map;statsUpdateLockTimeouts=new Map;STATS_UPDATE_TIMEOUT=5e3;constructor(){let e=[A(Ee,"templates","default","xiaozhi.config.json"),A(Ee,"..","templates","default","xiaozhi.config.json"),A(process.cwd(),"templates","default","xiaozhi.config.json")];this.defaultConfigPath=e.find(t=>K(t))||e[0]}getConfigFilePath(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),t=["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"];for(let r of t){let o=A(e,r);if(K(o))return o}return A(e,"xiaozhi.config.json")}getConfigFileFormat(e){return e.endsWith(".json5")?"json5":e.endsWith(".jsonc")?"jsonc":"json"}static getInstance(){return i.instance||(i.instance=new i),i.instance}configExists(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),t=["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"];for(let r of t){let o=A(e,r);if(K(o))return!0}return!1}initConfig(e="json"){if(!K(this.defaultConfigPath))throw new Error(`\u9ED8\u8BA4\u914D\u7F6E\u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${this.defaultConfigPath}`);if(this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u521D\u59CB\u5316");let t=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),r=`xiaozhi.config.${e}`,o=A(t,r);Je(this.defaultConfigPath,o),this.config=null,this.json5Writer=null}loadConfig(){if(!this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C xiaozhi init \u521D\u59CB\u5316\u914D\u7F6E");try{let e=this.getConfigFilePath();this.currentConfigPath=e;let t=this.getConfigFileFormat(e),o=Ve(e,"utf8").replace(/^\uFEFF/,""),n;switch(t){case"json5":n=ge.parse(o),this.json5Writer=Re.load(o);break;case"jsonc":n=q.parse(o);break;default:n=JSON.parse(o);break}return this.validateConfig(n),n}catch(e){throw e instanceof SyntaxError?new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF: ${e.message}`):e}}validateConfig(e){if(!e||typeof e!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A\u6839\u5BF9\u8C61\u65E0\u6548");let t=e;if(t.mcpEndpoint===void 0||t.mcpEndpoint===null)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5B57\u6BB5\u65E0\u6548");if(typeof t.mcpEndpoint!="string")if(Array.isArray(t.mcpEndpoint)){for(let r of t.mcpEndpoint)if(typeof r!="string"||r.trim()==="")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u5B57\u7B26\u4E32\u6570\u7EC4");if(!t.mcpServers||typeof t.mcpServers!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers \u5B57\u6BB5\u65E0\u6548");for(let[r,o]of Object.entries(t.mcpServers)){if(!o||typeof o!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${r} \u65E0\u6548`);let n=H.normalizeTypeField(o),s=ue(r,n);if(!s.valid)throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A${s.error}`)}}getConfig(){return this.config=this.loadConfig(),JSON.parse(JSON.stringify(this.config))}getMutableConfig(){return this.config||(this.config=this.loadConfig()),this.config}getMcpEndpoint(){let e=this.getConfig();return Array.isArray(e.mcpEndpoint)?e.mcpEndpoint[0]||"":e.mcpEndpoint}getMcpEndpoints(){let e=this.getConfig();return Array.isArray(e.mcpEndpoint)?[...e.mcpEndpoint]:e.mcpEndpoint?[e.mcpEndpoint]:[]}getMcpServers(){return this.getConfig().mcpServers}getMcpServerConfig(){return this.getConfig().mcpServerConfig||{}}getServerToolsConfig(e){return this.getMcpServerConfig()[e]?.tools||{}}isToolEnabled(e,t){return this.getServerToolsConfig(e)[t]?.enable!==!1}updateMcpEndpoint(e){if(Array.isArray(e)){for(let r of e)if(!r||typeof r!="string")throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}let t=this.getMutableConfig();t.mcpEndpoint=e,this.saveConfig(t)}addMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getMutableConfig(),r=this.getMcpEndpoints();if(r.includes(e))throw new Error(`MCP \u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728`);let o=[...r,e];t.mcpEndpoint=o,this.saveConfig(t)}removeMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getMutableConfig(),r=this.getMcpEndpoints();if(r.indexOf(e)===-1)throw new Error(`MCP \u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);let n=r.filter(s=>s!==e);t.mcpEndpoint=n,this.saveConfig(t)}updateMcpServer(e,t){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let r=ue(e,t);if(!r.valid)throw new Error(r.error||"\u670D\u52A1\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");let o=this.getMutableConfig();o.mcpServers[e]=t,this.saveConfig(o)}removeMcpServer(e){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getMutableConfig();if(!t.mcpServers[e])throw new Error(`\u670D\u52A1 ${e} \u4E0D\u5B58\u5728`);if(delete t.mcpServers[e],t.mcpServerConfig?.[e]&&delete t.mcpServerConfig[e],t.customMCP?.tools){let r=t.customMCP.tools.filter(o=>o.handler?.type==="mcp"&&o.handler.config?.serviceName===e);for(let o of r){let n=t.customMCP.tools.findIndex(s=>s.name===o.name);n!==-1&&t.customMCP.tools.splice(n,1)}t.customMCP.tools.length===0&&(t.customMCP=void 0)}this.saveConfig(t),this.eventBus.emitEvent("config:updated",{type:"customMCP",timestamp:new Date}),l.info(`\u6210\u529F\u79FB\u9664 MCP \u670D\u52A1 ${e} \u53CA\u5176\u76F8\u5173\u914D\u7F6E`)}updateServerToolsConfig(e,t){let r=this.getMutableConfig();r.mcpServerConfig||(r.mcpServerConfig={}),Object.keys(t).length===0?delete r.mcpServerConfig[e]:r.mcpServerConfig[e]={tools:t},this.saveConfig(r),this.eventBus.emitEvent("config:updated",{type:"serverTools",serviceName:e,timestamp:new Date})}removeServerToolsConfig(e){let r={...this.getConfig()};r.mcpServerConfig&&(delete r.mcpServerConfig[e],this.saveConfig(r))}cleanupInvalidServerToolsConfig(){let e=this.getMutableConfig();if(!e.mcpServerConfig)return;let t=Object.keys(e.mcpServers),o=Object.keys(e.mcpServerConfig).filter(n=>!t.includes(n));if(o.length>0){for(let n of o)delete e.mcpServerConfig[n];this.saveConfig(e),l.info(`\u5DF2\u6E05\u7406 ${o.length} \u4E2A\u65E0\u6548\u7684\u670D\u52A1\u5DE5\u5177\u914D\u7F6E: ${o.join(", ")}`)}}setToolEnabled(e,t,r,o){let n=this.getMutableConfig();n.mcpServerConfig||(n.mcpServerConfig={}),n.mcpServerConfig[e]||(n.mcpServerConfig[e]={tools:{}}),n.mcpServerConfig[e].tools[t]={...n.mcpServerConfig[e].tools[t],enable:r,...o&&{description:o}},this.saveConfig(n)}saveConfig(e){try{this.validateConfig(e);let t;this.currentConfigPath?t=this.currentConfigPath:(t=this.getConfigFilePath(),this.currentConfigPath=t);let r=this.getConfigFileFormat(t),o;switch(r){case"json5":try{this.json5Writer?(this.json5Writer.write(e),o=this.json5Writer.toSource()):o=ge.stringify(e,null,2)}catch{o=ge.stringify(e,null,2)}break;case"jsonc":try{o=q.stringify(e,null,2)}catch{o=JSON.stringify(e,null,2)}break;default:o=JSON.stringify(e,null,2);break}Ge(t,o,"utf8"),this.config=e,this.notifyConfigUpdate(e)}catch(t){throw new Error(`\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}reloadConfig(){this.config=null,this.currentConfigPath=null,this.json5Writer=null}getConfigPath(){return this.getConfigFilePath()}getDefaultConfigPath(){return this.defaultConfigPath}getConnectionConfig(){let t=this.getConfig().connection||{};return{heartbeatInterval:t.heartbeatInterval??me.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??me.heartbeatTimeout,reconnectInterval:t.reconnectInterval??me.reconnectInterval}}getHeartbeatInterval(){return this.getConnectionConfig().heartbeatInterval}getHeartbeatTimeout(){return this.getConnectionConfig().heartbeatTimeout}getReconnectInterval(){return this.getConnectionConfig().reconnectInterval}updateConnectionConfig(e){let t=this.getMutableConfig();t.connection||(t.connection={}),Object.assign(t.connection,e),this.saveConfig(t)}async updateToolUsageStats(e,t,r){try{if(typeof t=="string"&&r){let o=e,n=t,s=r;await Promise.all([this._updateMCPServerToolStats(o,n,s),this.updateCustomMCPToolStats(o,n,s)]),l.debug(`\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${o}/${n}`)}else{let o=e,n=t,s=new Date().toISOString();await this.updateCustomMCPToolStats(o,s,n),l.debug(`CustomMCP \u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${o}`)}}catch(o){if(typeof t=="string"&&r){let n=e,s=t;l.error(`\u66F4\u65B0\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${n}/${s}): ${o instanceof Error?o.message:String(o)}`)}else{let n=e;l.error(`\u66F4\u65B0 CustomMCP \u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${n}): ${o instanceof Error?o.message:String(o)}`)}}}async updateMCPServerToolStats(e,t,r,o=!0){await this._updateMCPServerToolStats(e,t,r,o)}setHeartbeatInterval(e){if(e<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatInterval:e})}setHeartbeatTimeout(e){if(e<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatTimeout:e})}setReconnectInterval(e){if(e<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({reconnectInterval:e})}getModelScopeConfig(){return this.getConfig().modelscope||{}}getModelScopeApiKey(){return this.getModelScopeConfig().apiKey||process.env.MODELSCOPE_API_TOKEN}updateModelScopeConfig(e){let t=this.getMutableConfig();t.modelscope||(t.modelscope={}),Object.assign(t.modelscope,e),this.saveConfig(t)}setModelScopeApiKey(e){if(!e||typeof e!="string")throw new Error("API Key \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");this.updateModelScopeConfig({apiKey:e})}getCustomMCPConfig(){return this.getConfig().customMCP||null}getCustomMCPTools(){let e=this.getCustomMCPConfig();return!e||!e.tools?[]:e.tools}validateCustomMCPTools(e){if(!Array.isArray(e))return!1;for(let t of e){if(!t.name||typeof t.name!="string")return l.warn(`CustomMCP \u5DE5\u5177\u7F3A\u5C11\u6709\u6548\u7684 name \u5B57\u6BB5: ${JSON.stringify(t)}`),!1;if(!t.description||typeof t.description!="string")return l.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 description \u5B57\u6BB5`),!1;if(!t.inputSchema||typeof t.inputSchema!="object")return l.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 inputSchema \u5B57\u6BB5`),!1;if(!t.handler||typeof t.handler!="object")return l.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 handler \u5B57\u6BB5`),!1;if(!["proxy","function","http","script","chain","mcp"].includes(t.handler.type))return l.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7684 handler.type \u5FC5\u987B\u662F 'proxy', 'function', 'http', 'script', 'chain' \u6216 'mcp'`),!1;if(!this.validateHandlerConfig(t.name,t.handler))return!1}return!0}validateHandlerConfig(e,t){switch(t.type){case"proxy":return this.validateProxyHandler(e,t);case"http":return this.validateHttpHandler(e,t);case"function":return this.validateFunctionHandler(e,t);case"script":return this.validateScriptHandler(e,t);case"chain":return this.validateChainHandler(e,t);case"mcp":return this.validateMCPHandler(e,t);default:return l.warn(`CustomMCP \u5DE5\u5177 ${e} \u4F7F\u7528\u4E86\u672A\u77E5\u7684\u5904\u7406\u5668\u7C7B\u578B`),!1}}validateProxyHandler(e,t){return t.platform?["coze","openai","anthropic","custom"].includes(t.platform)?!t.config||typeof t.config!="object"?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u7F3A\u5C11 config \u5B57\u6BB5`),!1):t.platform==="coze"&&!t.config.workflow_id&&!t.config.bot_id?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 Coze \u5904\u7406\u5668\u5FC5\u987B\u63D0\u4F9B workflow_id \u6216 bot_id`),!1):!0:(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u5E73\u53F0: ${t.platform}`),!1):(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u7F3A\u5C11 platform \u5B57\u6BB5`),!1)}validateHttpHandler(e,t){if(!t.url||typeof t.url!="string")return l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 http \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 url \u5B57\u6BB5`),!1;try{new URL(t.url)}catch{return l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 http \u5904\u7406\u5668 url \u683C\u5F0F\u65E0\u6548: ${t.url}`),!1}return t.method&&!["GET","POST","PUT","DELETE","PATCH"].includes(t.method)?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 http \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684 HTTP \u65B9\u6CD5: ${t.method}`),!1):!0}validateFunctionHandler(e,t){return!t.module||typeof t.module!="string"?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 function \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 module \u5B57\u6BB5`),!1):!t.function||typeof t.function!="string"?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 function \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 function \u5B57\u6BB5`),!1):!0}validateScriptHandler(e,t){return!t.script||typeof t.script!="string"?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 script \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 script \u5B57\u6BB5`),!1):t.interpreter&&!["node","python","bash"].includes(t.interpreter)?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 script \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u89E3\u91CA\u5668: ${t.interpreter}`),!1):!0}validateChainHandler(e,t){return!t.tools||!Array.isArray(t.tools)||t.tools.length===0?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 chain \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 tools \u6570\u7EC4`),!1):["sequential","parallel"].includes(t.mode)?["stop","continue","retry"].includes(t.error_handling)?!0:(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 chain \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u9519\u8BEF\u5904\u7406\u7B56\u7565: ${t.error_handling}`),!1):(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 chain \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u6267\u884C\u6A21\u5F0F: ${t.mode}`),!1)}validateMCPHandler(e,t){return!t.config||typeof t.config!="object"?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11 config \u5B57\u6BB5`),!1):!t.config.serviceName||typeof t.config.serviceName!="string"?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 serviceName`),!1):!t.config.toolName||typeof t.config.toolName!="string"?(l.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 toolName`),!1):!0}hasValidCustomMCPTools(){try{let e=this.getCustomMCPTools();return e.length===0?!1:this.validateCustomMCPTools(e)}catch(e){return l.error("\u68C0\u67E5 customMCP \u5DE5\u5177\u914D\u7F6E\u65F6\u51FA\u9519:",e),!1}}addCustomMCPTool(e){if(!e||typeof e!="object")throw new Error("\u5DE5\u5177\u914D\u7F6E\u4E0D\u80FD\u4E3A\u7A7A");let t=this.getMutableConfig();if(t.customMCP||(t.customMCP={tools:[]}),t.customMCP.tools.find(o=>o.name===e.name))throw new Error(`\u5DE5\u5177 "${e.name}" \u5DF2\u5B58\u5728`);if(!this.validateCustomMCPTools([e]))throw new Error("\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");t.customMCP.tools.unshift(e),this.saveConfig(t),l.info(`\u6210\u529F\u6DFB\u52A0\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${e.name}`)}async addCustomMCPTools(e){if(!Array.isArray(e))throw new Error("\u5DE5\u5177\u914D\u7F6E\u5FC5\u987B\u662F\u6570\u7EC4");if(e.length===0)return;let t=this.getMutableConfig();t.customMCP||(t.customMCP={tools:[]});let r=new Set(t.customMCP.tools.map(n=>n.name)),o=e.filter(n=>!r.has(n.name));if(o.length>0){if(!this.validateCustomMCPTools(o))throw new Error("\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");t.customMCP.tools.push(...o),this.saveConfig(t),this.eventBus.emitEvent("config:updated",{type:"customMCP",timestamp:new Date}),l.debug(`\u6210\u529F\u6279\u91CF\u6DFB\u52A0 ${o.length} \u4E2A\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${o.map(n=>n.name).join(", ")}`)}}removeCustomMCPTool(e){if(!e||typeof e!="string")throw new Error("\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");let t=this.getMutableConfig();if(!t.customMCP||!t.customMCP.tools)throw new Error("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177");let r=t.customMCP.tools.findIndex(o=>o.name===e);if(r===-1)throw new Error(`\u5DE5\u5177 "${e}" \u4E0D\u5B58\u5728`);t.customMCP.tools.splice(r,1),this.saveConfig(t),l.info(`\u6210\u529F\u5220\u9664\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${e}`)}updateCustomMCPTool(e,t){if(!e||typeof e!="string")throw new Error("\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");if(!t||typeof t!="object")throw new Error("\u66F4\u65B0\u540E\u7684\u5DE5\u5177\u914D\u7F6E\u4E0D\u80FD\u4E3A\u7A7A");let r=this.getMutableConfig();if(!r.customMCP||!r.customMCP.tools)throw new Error("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177");let o=r.customMCP.tools.findIndex(n=>n.name===e);if(o===-1)throw new Error(`\u5DE5\u5177 "${e}" \u4E0D\u5B58\u5728`);if(!this.validateCustomMCPTools([t]))throw new Error("\u66F4\u65B0\u540E\u7684\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");r.customMCP.tools[o]=t,this.saveConfig(r),l.debug(`\u6210\u529F\u66F4\u65B0\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${e}`)}updateCustomMCPTools(e){if(!Array.isArray(e))throw new Error("\u5DE5\u5177\u914D\u7F6E\u5FC5\u987B\u662F\u6570\u7EC4");if(!this.validateCustomMCPTools(e))throw new Error("\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");let t=this.getMutableConfig();t.customMCP||(t.customMCP={tools:[]}),t.customMCP.tools=e,this.saveConfig(t),this.eventBus.emitEvent("config:updated",{type:"customMCP",timestamp:new Date}),l.debug(`\u6210\u529F\u66F4\u65B0\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u914D\u7F6E\uFF0C\u5171 ${e.length} \u4E2A\u5DE5\u5177`)}getWebUIConfig(){return this.getConfig().webUI||{}}getWebUIPort(){return this.getWebUIConfig().port??9999}notifyConfigUpdate(e){try{let t=global.__webServer;t&&typeof t.broadcastConfigUpdate=="function"&&t.broadcastConfigUpdate(e)}catch{}}updateWebUIConfig(e){let t=this.getMutableConfig();t.webUI||(t.webUI={}),Object.assign(t.webUI,e),this.saveConfig(t)}setWebUIPort(e){if(!Number.isInteger(e)||e<=0||e>65535)throw new Error("\u7AEF\u53E3\u53F7\u5FC5\u987B\u662F 1-65535 \u4E4B\u95F4\u7684\u6574\u6570");this.updateWebUIConfig({port:e})}updatePlatformConfig(e,t){let r=this.getMutableConfig();r.platforms||(r.platforms={}),r.platforms[e]=t,this.saveConfig(r)}getCozePlatformConfig(){let t=this.getConfig().platforms?.coze;return!t||!t.token?null:{token:t.token}}getCozeToken(){return this.getCozePlatformConfig()?.token||null}setCozePlatformConfig(e){if(!e.token||typeof e.token!="string"||e.token.trim()==="")throw new Error("\u6263\u5B50 API Token \u4E0D\u80FD\u4E3A\u7A7A");this.updatePlatformConfig("coze",{token:e.token.trim()})}isCozeConfigValid(){let e=this.getCozePlatformConfig();return e!==null&&typeof e.token=="string"&&e.token.trim()!==""}async _updateMCPServerToolStats(e,t,r,o=!0){let n=this.getMutableConfig();n.mcpServerConfig||(n.mcpServerConfig={}),n.mcpServerConfig[e]||(n.mcpServerConfig[e]={tools:{}}),n.mcpServerConfig[e].tools[t]||(n.mcpServerConfig[e].tools[t]={enable:!0});let s=n.mcpServerConfig[e].tools[t],a=s.usageCount||0,u=s.lastUsedTime;o&&(s.usageCount=a+1),(!u||new Date(r)>new Date(u))&&(s.lastUsedTime=we(r).format("YYYY-MM-DD HH:mm:ss")),this.saveConfig(n)}async updateCustomMCPToolStats(e,t,r){try{let o,n,s=!0,a;if(typeof r=="string"){let P=e;o=`${P}__${t}`,n=r,a=`${P}/${t}`}else o=e,n=t,s=r||!0,a=o;let u=this.getCustomMCPTools(),g=u.findIndex(P=>P.name===o);if(g===-1)return;let p=[...u],m=p[g];m.stats||(m.stats={});let S=m.stats.usageCount||0,T=m.stats.lastUsedTime;s&&(m.stats.usageCount=S+1),(!T||new Date(n)>new Date(T))&&(m.stats.lastUsedTime=we(n).format("YYYY-MM-DD HH:mm:ss")),await this.updateCustomMCPTools(p)}catch(o){if(typeof r=="string"){let n=e,s=t;l.error(`\u66F4\u65B0 customMCP \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25 (${n}/${s}): ${o instanceof Error?o.message:String(o)}`)}else{let n=e;l.error(`\u66F4\u65B0 customMCP \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25 (${n}): ${o instanceof Error?o.message:String(o)}`)}}}async acquireStatsUpdateLock(e){if(this.statsUpdateLocks.has(e))return l.debug(`\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u66F4\u65B0\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8DF3\u8FC7\u672C\u6B21\u66F4\u65B0`),!1;let t=new Promise(o=>{});this.statsUpdateLocks.set(e,t);let r=setTimeout(()=>{this.releaseStatsUpdateLock(e)},this.STATS_UPDATE_TIMEOUT);return this.statsUpdateLockTimeouts.set(e,r),!0}releaseStatsUpdateLock(e){this.statsUpdateLocks.delete(e);let t=this.statsUpdateLockTimeouts.get(e);t&&(clearTimeout(t),this.statsUpdateLockTimeouts.delete(e)),l.debug(`\u5DF2\u91CA\u653E\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u66F4\u65B0\u9501`)}async updateToolUsageStatsWithLock(e,t=!0){let r=`custommcp_${e}`;if(await this.acquireStatsUpdateLock(r))try{await this.updateToolUsageStats(e,t),l.debug(`\u5DE5\u5177 ${e} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(o){throw l.error(`\u5DE5\u5177 ${e} \u7EDF\u8BA1\u66F4\u65B0\u5931\u8D25:`,o),o}finally{this.releaseStatsUpdateLock(r)}}async updateMCPServerToolStatsWithLock(e,t,r,o=!0){let n=`mcpserver_${e}_${t}`;if(await this.acquireStatsUpdateLock(n))try{await this.updateMCPServerToolStats(e,t,r,o),l.debug(`MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(s){throw l.error(`MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u66F4\u65B0\u5931\u8D25:`,s),s}finally{this.releaseStatsUpdateLock(n)}}clearAllStatsUpdateLocks(){let e=this.statsUpdateLocks.size;this.statsUpdateLocks.clear();for(let t of this.statsUpdateLockTimeouts.values())clearTimeout(t);this.statsUpdateLockTimeouts.clear(),e>0&&l.info(`\u5DF2\u6E05\u7406 ${e} \u4E2A\u7EDF\u8BA1\u66F4\u65B0\u9501`)}getStatsUpdateLocks(){return Array.from(this.statsUpdateLocks.keys())}getToolCallLogConfig(){return this.getConfig().toolCallLog||{}}updateToolCallLogConfig(e){let t=this.getMutableConfig();t.toolCallLog||(t.toolCallLog={}),Object.assign(t.toolCallLog,e),this.saveConfig(t)}getConfigDir(){return process.env.XIAOZHI_CONFIG_DIR||process.cwd()}},f=pe.getInstance();import{createHash as Qe}from"crypto";function w(i,e){let t=Qe("md5").update(JSON.stringify(e||{})).digest("hex");return`${i}_${t}`}c(w,"generateCacheKey");function L(i,e){let t=new Date(i).getTime();return Date.now()-t>e}c(L,"isCacheExpired");function x(i){let e=Date.now(),t=new Date(i.timestamp).getTime();return!!(i.consumed&&e-t>6e4||e-t>i.ttl||i.status==="failed")}c(x,"shouldCleanupCache");var E={TIMEOUT:8e3,CACHE_TTL:3e5,CLEANUP_INTERVAL:6e4,MAX_CACHE_SIZE:1e3,ENABLE_ONE_TIME_CACHE:!0};var Q=class{static{c(this,"CacheLifecycleManager")}logger;cleanupInterval;statistics;lastCleanupTime;constructor(e){this.logger=e,this.statistics=this.initializeStatistics(),this.lastCleanupTime=new Date().toISOString()}initializeStatistics(){return{totalEntries:0,pendingTasks:0,completedTasks:0,failedTasks:0,consumedEntries:0,cacheHitRate:0,lastCleanupTime:new Date().toISOString(),memoryUsage:0}}startAutoCleanup(){if(this.cleanupInterval){this.logger.warn("[CacheLifecycle] \u81EA\u52A8\u6E05\u7406\u5B9A\u65F6\u5668\u5DF2\u7ECF\u5728\u8FD0\u884C");return}this.cleanupInterval=setInterval(()=>{this.performCleanup().catch(e=>{this.logger.error(`[CacheLifecycle] \u81EA\u52A8\u6E05\u7406\u5931\u8D25: ${e}`)})},E.CLEANUP_INTERVAL),this.logger.debug(`[CacheLifecycle] \u542F\u52A8\u81EA\u52A8\u6E05\u7406\u5B9A\u65F6\u5668\uFF0C\u95F4\u9694: ${E.CLEANUP_INTERVAL}ms`)}stopAutoCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0,this.logger.info("[CacheLifecycle] \u505C\u6B62\u81EA\u52A8\u6E05\u7406\u5B9A\u65F6\u5668"))}createCacheEntry(e,t,r,o="pending",n){let s={result:r,timestamp:new Date().toISOString(),ttl:E.CACHE_TTL,status:o,consumed:!1,taskId:n,retryCount:0};return this.logger.debug(`[CacheLifecycle] \u521B\u5EFA\u7F13\u5B58\u6761\u76EE: ${e}, \u72B6\u6001: ${o}`),s}updateCacheStatus(e,t,r,o,n){if(!e.customMCPResults||!e.customMCPResults[t])return this.logger.warn(`[CacheLifecycle] \u7F13\u5B58\u6761\u76EE\u4E0D\u5B58\u5728: ${t}`),!1;let s=e.customMCPResults[t],a=s.status;return this.logStateTransition(t,a,r),s.status=r,s.timestamp=new Date().toISOString(),o&&(s.result=o),n&&r==="failed"&&(s.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${n}`}]},s.consumed=!0),r==="completed"&&(s.consumed=!1),this.logger.debug(`[CacheLifecycle] \u66F4\u65B0\u7F13\u5B58\u72B6\u6001: ${t} ${a} -> ${r}`),!0}markAsConsumed(e,t){if(!e.customMCPResults||!e.customMCPResults[t])return!1;let r=e.customMCPResults[t];return r.consumed?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u5DF2\u6807\u8BB0\u4E3A\u6D88\u8D39: ${t}`),!0):(r.consumed=!0,r.timestamp=new Date().toISOString(),this.logStateTransition(t,r.status,"consumed"),this.logger.debug(`[CacheLifecycle] \u6807\u8BB0\u7F13\u5B58\u4E3A\u5DF2\u6D88\u8D39: ${t}`),!0)}isCacheAvailable(e,t){if(!e.customMCPResults||!e.customMCPResults[t])return!1;let r=e.customMCPResults[t];return L(r.timestamp,r.ttl)?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u5DF2\u8FC7\u671F: ${t}`),!1):r.consumed?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u5DF2\u6D88\u8D39: ${t}`),!1):r.status!=="completed"?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u72B6\u6001\u672A\u5B8C\u6210: ${t}, \u72B6\u6001: ${r.status}`),!1):!0}async performCleanup(){try{this.logger.debug("[CacheLifecycle] \u6267\u884C\u7F13\u5B58\u6E05\u7406"),this.lastCleanupTime=new Date().toISOString()}catch(e){throw this.logger.error(`[CacheLifecycle] \u6E05\u7406\u5931\u8D25: ${e}`),e}}cleanupCacheEntries(e,t){if(!e.customMCPResults)return{cleaned:0,total:0};let r=Object.entries(e.customMCPResults),o=0,n=t||r.map(([s])=>s);for(let s of n){let a=e.customMCPResults[s];a&&x(a)&&(delete e.customMCPResults[s],o++,this.logger.debug(`[CacheLifecycle] \u6E05\u7406\u7F13\u5B58\u6761\u76EE: ${s}`))}return this.logger.info(`[CacheLifecycle] \u6E05\u7406\u5B8C\u6210: ${o}/${n.length}`),{cleaned:o,total:n.length}}cleanupExpiredCache(e){if(!e.customMCPResults)return{cleaned:0,total:0};let t=Object.entries(e.customMCPResults),r=0;for(let[o,n]of t)L(n.timestamp,n.ttl)&&(delete e.customMCPResults[o],r++,this.logger.debug(`[CacheLifecycle] \u6E05\u7406\u8FC7\u671F\u7F13\u5B58: ${o}`));return r>0&&this.logger.info(`[CacheLifecycle] \u6E05\u7406\u8FC7\u671F\u7F13\u5B58: ${r}/${t.length}`),{cleaned:r,total:t.length}}cleanupConsumedCache(e){if(!e.customMCPResults)return{cleaned:0,total:0};let t=Object.entries(e.customMCPResults),r=0,o=Date.now();for(let[n,s]of t)if(s.consumed){let a=new Date(s.timestamp).getTime();o-a>6e4&&(delete e.customMCPResults[n],r++,this.logger.debug(`[CacheLifecycle] \u6E05\u7406\u5DF2\u6D88\u8D39\u7F13\u5B58: ${n}`))}return r>0&&this.logger.info(`[CacheLifecycle] \u6E05\u7406\u5DF2\u6D88\u8D39\u7F13\u5B58: ${r}/${t.length}`),{cleaned:r,total:t.length}}updateStatistics(e){if(!e.customMCPResults){this.statistics=this.initializeStatistics();return}let t=Object.values(e.customMCPResults);this.statistics.totalEntries=t.length,this.statistics.pendingTasks=t.filter(n=>n.status==="pending").length,this.statistics.completedTasks=t.filter(n=>n.status==="completed").length,this.statistics.failedTasks=t.filter(n=>n.status==="failed").length,this.statistics.consumedEntries=t.filter(n=>n.consumed).length;let r=this.statistics.completedTasks,o=this.statistics.consumedEntries;this.statistics.cacheHitRate=r>0?o/r*100:0,this.statistics.lastCleanupTime=this.lastCleanupTime,this.statistics.memoryUsage=JSON.stringify(e.customMCPResults).length}getStatistics(){return{...this.statistics}}validateCacheIntegrity(e){let t=[];if(!e.customMCPResults)return{isValid:!0,issues:[]};for(let[r,o]of Object.entries(e.customMCPResults))(!o.timestamp||!o.ttl||!o.status)&&t.push(`\u7F13\u5B58\u6761\u76EE\u7F3A\u5C11\u5FC5\u9700\u5B57\u6BB5: ${r}`),Number.isNaN(new Date(o.timestamp).getTime())&&t.push(`\u65E0\u6548\u7684\u65F6\u95F4\u6233\u683C\u5F0F: ${r}`),["pending","completed","failed"].includes(o.status)||t.push(`\u65E0\u6548\u7684\u72B6\u6001\u503C: ${r}, \u72B6\u6001: ${o.status}`),L(o.timestamp,o.ttl)&&t.push(`\u7F13\u5B58\u6761\u76EE\u5DF2\u8FC7\u671F: ${r}`);return{isValid:t.length===0,issues:t}}logStateTransition(e,t,r){let o={from:t,to:r,reason:this.getTransitionReason(t,r),timestamp:new Date().toISOString()};this.logger.debug(`[CacheLifecycle] \u72B6\u6001\u8F6C\u6362: ${e} ${t} -> ${r} (${o.reason})`)}getTransitionReason(e,t){return{"pending->completed":"\u4EFB\u52A1\u6267\u884C\u6210\u529F","pending->failed":"\u4EFB\u52A1\u6267\u884C\u5931\u8D25","completed->consumed":"\u7ED3\u679C\u88AB\u6D88\u8D39","failed->consumed":"\u5931\u8D25\u7ED3\u679C\u88AB\u5904\u7406","consumed->deleted":"\u7F13\u5B58\u88AB\u6E05\u7406"}[`${e}->${t}`]||"\u72B6\u6001\u66F4\u65B0"}cleanup(){this.stopAutoCleanup(),this.logger.info("[CacheLifecycle] \u6E05\u7406\u8D44\u6E90\u5B8C\u6210")}};var Y=class{static{c(this,"TaskStateManager")}logger;activeTasks;taskHistory;constructor(e){this.logger=e,this.activeTasks=new Map,this.taskHistory=[]}generateTaskId(e,t){let r=Date.now(),o=Math.random().toString(36).substring(2,11),n=`${e}_${r}_${o}`;return this.logger.debug(`[TaskState] \u751F\u6210\u4EFB\u52A1ID: ${n}`),n}validateTaskId(e){let r=/^[a-zA-Z0-9_-]+_\d+_[a-zA-Z0-9]+$/.test(e);return r||this.logger.warn(`[TaskState] \u65E0\u6548\u7684\u4EFB\u52A1ID\u683C\u5F0F: ${e}`),r}extractToolName(e){if(!this.validateTaskId(e))return null;let t=e.split("_");if(t.length<3)return null;let r=t.findIndex(n=>/^\d+$/.test(n));return r<=0?null:t.slice(0,r).join("_")}createTask(e,t,r,o="pending"){if(this.activeTasks.has(e))throw new Error(`\u4EFB\u52A1\u5DF2\u5B58\u5728: ${e}`);let n={taskId:e,toolName:t,arguments:r,status:o,startTime:new Date().toISOString()};return this.activeTasks.set(e,n),this.recordStateTransition(e,"none",o,"\u521B\u5EFA\u65B0\u4EFB\u52A1"),this.logger.info(`[TaskState] \u521B\u5EFA\u4EFB\u52A1: ${e}, \u5DE5\u5177: ${t}, \u72B6\u6001: ${o}`),n}updateTaskStatus(e,t,r,o){let n=this.activeTasks.get(e);if(!n)return this.logger.warn(`[TaskState] \u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`),!1;let s=n.status;return n.status=t,(t==="completed"||t==="failed")&&(n.endTime=new Date().toISOString()),r&&(n.result=r),o&&(n.error=o),this.recordStateTransition(e,s,t,this.getStatusChangeReason(s,t,o)),this.logger.info(`[TaskState] \u66F4\u65B0\u4EFB\u52A1\u72B6\u6001: ${e} ${s} -> ${t}`),!0}markTaskAsPending(e,t,r){let o=this.activeTasks.get(e);return o?this.updateTaskStatus(e,"pending"):o=this.createTask(e,t,r,"pending"),o}markTaskAsCompleted(e,t){return this.updateTaskStatus(e,"completed",t)}markTaskAsFailed(e,t){return this.updateTaskStatus(e,"failed",void 0,t)}markTaskAsConsumed(e){return this.updateTaskStatus(e,"consumed")}getTask(e){return this.activeTasks.get(e)||null}hasTask(e){return this.activeTasks.has(e)}getTaskStatus(e){let t=this.activeTasks.get(e);return t?t.status:null}getTasksByStatus(e){return Array.from(this.activeTasks.values()).filter(t=>t.status===e)}getTasksByTool(e){return Array.from(this.activeTasks.values()).filter(t=>t.toolName===e)}getTaskExecutionTime(e){let t=this.activeTasks.get(e);if(!t||!t.endTime)return null;let r=new Date(t.startTime).getTime();return new Date(t.endTime).getTime()-r}isTaskTimeout(e,t=8e3){let r=this.activeTasks.get(e);if(!r)return!1;let o=new Date(r.startTime).getTime();return Date.now()-o>t}getTimeoutTasks(e=8e3){let t=Date.now();return Array.from(this.activeTasks.values()).filter(r=>{let o=new Date(r.startTime).getTime();return t-o>e&&r.status==="pending"})}removeTask(e){let t=this.activeTasks.get(e);return t?(this.recordStateTransition(e,t.status,"deleted","\u4EFB\u52A1\u88AB\u79FB\u9664"),this.activeTasks.delete(e),this.logger.info(`[TaskState] \u79FB\u9664\u4EFB\u52A1: ${e}`),!0):!1}cleanupCompletedTasks(e=3e5){let t=Date.now(),r=0;for(let[o,n]of this.activeTasks.entries())if(n.status==="completed"||n.status==="failed"){let s=n.endTime?new Date(n.endTime).getTime():t;t-s>e&&(this.removeTask(o),r++)}return r>0&&this.logger.info(`[TaskState] \u6E05\u7406\u5DF2\u5B8C\u6210\u4EFB\u52A1: ${r}\u4E2A`),r}getTaskStatistics(){let e=Array.from(this.activeTasks.values()),t=e.length,r=e.filter(g=>g.status==="pending").length,o=e.filter(g=>g.status==="completed").length,n=e.filter(g=>g.status==="failed").length,s=e.filter(g=>g.status==="consumed").length,a=e.filter(g=>g.status==="completed"&&g.endTime),u=a.length>0?a.reduce((g,p)=>{let m=this.getTaskExecutionTime(p.taskId)||0;return g+m},0)/a.length:0;return{total:t,pending:r,completed:o,failed:n,consumed:s,averageExecutionTime:u}}getTaskHistory(e){return e?this.taskHistory.filter(t=>t.taskId===e):[...this.taskHistory]}recordStateTransition(e,t,r,o){let n={from:t,to:r,reason:o,timestamp:new Date().toISOString(),taskId:e};this.taskHistory.push(n),this.taskHistory.length>1e3&&(this.taskHistory=this.taskHistory.slice(-500))}getStatusChangeReason(e,t,r){if(r)return`\u6267\u884C\u5931\u8D25: ${r}`;let o={"none->pending":"\u4EFB\u52A1\u5F00\u59CB\u6267\u884C","pending->completed":"\u4EFB\u52A1\u6267\u884C\u6210\u529F","pending->failed":"\u4EFB\u52A1\u6267\u884C\u5931\u8D25","completed->consumed":"\u7ED3\u679C\u88AB\u6D88\u8D39","failed->consumed":"\u5931\u8D25\u7ED3\u679C\u88AB\u5904\u7406","consumed->deleted":"\u4EFB\u52A1\u88AB\u6E05\u7406"},n=`${e}->${t}`;return o[n]||"\u72B6\u6001\u66F4\u65B0"}validateTaskIntegrity(){let e=[];for(let[t,r]of this.activeTasks.entries())(!r.taskId||!r.toolName||!r.status||!r.startTime)&&e.push(`\u4EFB\u52A1\u7F3A\u5C11\u5FC5\u9700\u5B57\u6BB5: ${t}`),Number.isNaN(new Date(r.startTime).getTime())&&e.push(`\u65E0\u6548\u7684\u5F00\u59CB\u65F6\u95F4: ${t}`),r.endTime&&Number.isNaN(new Date(r.endTime).getTime())&&e.push(`\u65E0\u6548\u7684\u7ED3\u675F\u65F6\u95F4: ${t}`),r.status==="completed"&&!r.endTime&&e.push(`\u5DF2\u5B8C\u6210\u4EFB\u52A1\u7F3A\u5C11\u7ED3\u675F\u65F6\u95F4: ${t}`),r.status==="failed"&&!r.error&&e.push(`\u5931\u8D25\u4EFB\u52A1\u7F3A\u5C11\u9519\u8BEF\u4FE1\u606F: ${t}`);return{isValid:e.length===0,issues:e}}restartStalledTasks(e=3e4){let t=this.getTimeoutTasks(e),r=0;for(let o of t){this.logger.warn(`[TaskState] \u68C0\u6D4B\u5230\u505C\u6EDE\u4EFB\u52A1: ${o.taskId}`),this.markTaskAsFailed(o.taskId,"\u4EFB\u52A1\u6267\u884C\u8D85\u65F6");let n=this.generateTaskId(o.toolName,o.arguments);this.createTask(n,o.toolName,o.arguments,"pending"),r++}return r>0&&this.logger.info(`[TaskState] \u91CD\u542F\u505C\u6EDE\u4EFB\u52A1: ${r}\u4E2A`),r}cleanup(){this.activeTasks.clear(),this.taskHistory=[],this.logger.info("[TaskState] \u6E05\u7406\u4EFB\u52A1\u72B6\u6001\u7BA1\u7406\u5668\u8D44\u6E90")}};var J=class i extends Error{static{c(this,"TimeoutError")}name="TimeoutError";constructor(e){super(e),this.name="TimeoutError",Error.captureStackTrace(this,i)}toJSON(){return{name:this.name,message:this.message,stack:this.stack}}};function $e(i,e){return{content:[{type:"text",text:e?Ye(e,i):xe(i)}],isError:!1,taskId:i,status:"timeout",message:"\u5DE5\u5177\u8C03\u7528\u8D85\u65F6\uFF0C\u6B63\u5728\u540E\u53F0\u5904\u7406\u4E2D",nextAction:"\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6216\u7B49\u5F85\u4EFB\u52A1\u5B8C\u6210"}}c($e,"createTimeoutResponse");function Ye(i,e){let t={coze_workflow:`\u23F1\uFE0F \u6263\u5B50\u5DE5\u4F5C\u6D41\u6267\u884C\u8D85\u65F6\uFF0C\u6B63\u5728\u540E\u53F0\u5904\u7406\u4E2D...
4
-
5
- \u{1F4CB} \u4EFB\u52A1\u4FE1\u606F\uFF1A
6
- - \u4EFB\u52A1ID: ${e}
7
- - \u5DE5\u5177\u7C7B\u578B: \u6263\u5B50\u5DE5\u4F5C\u6D41
8
- - \u72B6\u6001: \u5904\u7406\u4E2D
9
- - \u5EFA\u8BAE: \u8BF7\u7B49\u5F8530-60\u79D2\u540E\u91CD\u8BD5\u67E5\u8BE2
10
-
11
- \u{1F504} \u540E\u7EED\u64CD\u4F5C\uFF1A
12
- 1. \u4F7F\u7528\u76F8\u540C\u53C2\u6570\u91CD\u65B0\u8C03\u7528\u5DE5\u5177
13
- 2. \u7CFB\u7EDF\u4F1A\u81EA\u52A8\u8FD4\u56DE\u5DF2\u5B8C\u6210\u7684\u4EFB\u52A1\u7ED3\u679C
14
- 3. \u590D\u6742\u5DE5\u4F5C\u6D41\u53EF\u80FD\u9700\u8981\u66F4\u957F\u65F6\u95F4\u5904\u7406`,default:xe(e)};return t[i]||t.default}c(Ye,"getToolSpecificTimeoutMessage");function xe(i){return`\u23F1\uFE0F \u5DE5\u5177\u8C03\u7528\u8D85\u65F6\uFF0C\u6B63\u5728\u540E\u53F0\u5904\u7406\u4E2D...
15
-
16
- \u{1F4CB} \u4EFB\u52A1\u4FE1\u606F\uFF1A
17
- - \u4EFB\u52A1ID: ${i}
18
- - \u72B6\u6001: \u5904\u7406\u4E2D
19
- - \u5EFA\u8BAE: \u8BF7\u7B49\u5F8530\u79D2\u540E\u91CD\u8BD5\u67E5\u8BE2
20
-
21
- \u{1F504} \u540E\u7EED\u64CD\u4F5C\uFF1A
22
- 1. \u4F7F\u7528\u76F8\u540C\u7684\u53C2\u6570\u91CD\u65B0\u8C03\u7528\u5DE5\u5177
23
- 2. \u7CFB\u7EDF\u4F1A\u81EA\u52A8\u8FD4\u56DE\u5DF2\u5B8C\u6210\u7684\u4EFB\u52A1\u7ED3\u679C
24
- 3. \u5982\u679C\u957F\u65F6\u95F4\u672A\u5B8C\u6210\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458`}c(xe,"getDefaultTimeoutMessage");import{createHash as Ze}from"crypto";import{existsSync as V,mkdirSync as Xe,readFileSync as ke,renameSync as et,writeFileSync as Ie}from"fs";import{dirname as tt,resolve as Ae}from"path";import{Hono as Sr}from"hono";import rt from"dayjs";var F=class{static{c(this,"MCPCacheManager")}cachePath;logger;CACHE_VERSION="1.0.0";CACHE_ENTRY_VERSION="1.0.0";cleanupInterval;CLEANUP_INTERVAL=6e4;constructor(e){this.logger=l,this.cachePath=e||this.getCacheFilePath(),this.startCleanupTimer()}formatTimestamp(){return rt().format("YYYY-MM-DD HH:mm:ss")}getCacheFilePath(){try{let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return Ae(e,"xiaozhi.cache.json")}catch{let t=process.env.XIAOZHI_CONFIG_DIR||"/tmp";return Ae(t,"xiaozhi.cache.json")}}async ensureCacheFile(){try{if(!V(this.cachePath)){let e=tt(this.cachePath);V(e)||(Xe(e,{recursive:!0}),this.logger.debug(`[CacheManager] \u5DF2\u521B\u5EFA\u7F13\u5B58\u76EE\u5F55: ${e}`)),this.logger.debug("[CacheManager] \u7F13\u5B58\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u521B\u5EFA\u521D\u59CB\u7F13\u5B58\u6587\u4EF6");let t=await this.createInitialCache();await this.saveCache(t),this.logger.info(`[CacheManager] \u5DF2\u521B\u5EFA\u7F13\u5B58\u6587\u4EF6: ${this.cachePath}`)}}catch(e){this.logger.warn(`[CacheManager] \u521B\u5EFA\u7F13\u5B58\u6587\u4EF6\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async createInitialCache(){let e=this.formatTimestamp();return{version:this.CACHE_VERSION,mcpServers:{},metadata:{lastGlobalUpdate:e,totalWrites:0,createdAt:e}}}async writeCacheEntry(e,t,r){try{this.logger.debug(`[CacheManager] \u5F00\u59CB\u5199\u5165\u7F13\u5B58: ${e}`),await this.ensureCacheFile();let o=await this.loadExistingCache(),n=this.generateConfigHash(r),s={tools:t.map(a=>({name:a.name,description:a.description||"",inputSchema:a.inputSchema})),lastUpdated:this.formatTimestamp(),serverConfig:{...r},configHash:n,version:this.CACHE_ENTRY_VERSION};o.mcpServers[e]=s,o.metadata.lastGlobalUpdate=this.formatTimestamp(),o.metadata.totalWrites+=1,await this.saveCache(o),this.logger.debug(`[CacheManager] \u7F13\u5B58\u5199\u5165\u6210\u529F: ${e}, \u5DE5\u5177\u6570\u91CF: ${t.length}`)}catch(o){this.logger.warn(`[CacheManager] \u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e}, \u9519\u8BEF: ${o instanceof Error?o.message:String(o)}`)}}async loadExistingCache(){try{if(!V(this.cachePath))return await this.createInitialCache();let e=ke(this.cachePath,"utf8"),t=JSON.parse(e);return this.validateCacheStructure(t)?t:(this.logger.warn("[CacheManager] \u7F13\u5B58\u6587\u4EF6\u7ED3\u6784\u65E0\u6548\uFF0C\u91CD\u65B0\u521B\u5EFA"),await this.createInitialCache())}catch(e){return this.logger.warn(`[CacheManager] \u52A0\u8F7D\u7F13\u5B58\u5931\u8D25\uFF0C\u521B\u5EFA\u65B0\u7F13\u5B58: ${e instanceof Error?e.message:String(e)}`),await this.createInitialCache()}}async saveCache(e){let t=JSON.stringify(e,null,2);await this.atomicWrite(this.cachePath,t)}async atomicWrite(e,t){let r=`${e}.tmp`;try{Ie(r,t,"utf8"),et(r,e)}catch(o){try{V(r)&&Ie(r,"","utf8")}catch{}throw o}}generateConfigHash(e){try{return Ze("sha256").update(JSON.stringify(e)).digest("hex")}catch(t){return this.logger.warn(`[CacheManager] \u751F\u6210\u914D\u7F6E\u54C8\u5E0C\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),""}}validateCacheStructure(e){try{return e&&typeof e=="object"&&typeof e.version=="string"&&typeof e.mcpServers=="object"&&e.metadata&&typeof e.metadata=="object"&&typeof e.metadata.lastGlobalUpdate=="string"&&typeof e.metadata.totalWrites=="number"&&typeof e.metadata.createdAt=="string"}catch{return!1}}async getStats(){try{let e=await this.loadExistingCache();return{totalWrites:e.metadata.totalWrites,lastUpdate:e.metadata.lastGlobalUpdate,serverCount:Object.keys(e.mcpServers).length,cacheFileSize:V(this.cachePath)?ke(this.cachePath,"utf8").length:0}}catch(e){return this.logger.warn(`[CacheManager] \u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),null}}getFilePath(){return this.cachePath}async getAllCachedTools(){try{let e=await this.loadExistingCache(),t=[];for(let[r,o]of Object.entries(e.mcpServers))for(let n of o.tools)t.push({...n,name:`${r}__${n.name}`});return this.logger.debug(`[CacheManager] \u83B7\u53D6\u5230\u6240\u6709\u7F13\u5B58\u5DE5\u5177\uFF0C\u5171 ${t.length} \u4E2A`),t}catch(e){return this.logger.warn(`[CacheManager] \u83B7\u53D6\u6240\u6709\u7F13\u5B58\u5DE5\u5177\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),[]}}async writeCustomMCPResult(e,t,r,o="completed",n,s=3e5){try{let a=await this.loadExtendedCache(),u=w(e,t),g={result:r,timestamp:new Date().toISOString(),ttl:s,status:o,consumed:!1,taskId:n,retryCount:0};a.customMCPResults||(a.customMCPResults={}),a.customMCPResults[u]=g,await this.saveExtendedCache(a),this.logger.debug(`[CacheManager] \u5199\u5165CustomMCP\u7ED3\u679C\u7F13\u5B58: ${e}, \u72B6\u6001: ${o}`)}catch(a){this.logger.warn(`[CacheManager] \u5199\u5165CustomMCP\u7ED3\u679C\u7F13\u5B58\u5931\u8D25: ${a instanceof Error?a.message:String(a)}`)}}async readCustomMCPResult(e,t){try{let r=await this.loadExtendedCache(),o=w(e,t);if(!r.customMCPResults||!r.customMCPResults[o])return null;let n=r.customMCPResults[o],s=Date.now(),a=new Date(n.timestamp).getTime();return s-a>n.ttl?(this.logger.debug(`[CacheManager] \u7F13\u5B58\u5DF2\u8FC7\u671F: ${e}`),null):n}catch(r){return this.logger.warn(`[CacheManager] \u8BFB\u53D6CustomMCP\u7ED3\u679C\u7F13\u5B58\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),null}}async updateCustomMCPStatus(e,t,r,o,n){try{let s=await this.loadExtendedCache(),a=w(e,t);if(!s.customMCPResults||!s.customMCPResults[a])return!1;let u=s.customMCPResults[a],g=u.status;return u.status=r,u.timestamp=new Date().toISOString(),o&&(u.result=o),n&&r==="failed"&&(u.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${n}`}]},u.consumed=!0),r==="completed"&&(u.consumed=!1),await this.saveExtendedCache(s),this.logger.debug(`[CacheManager] \u66F4\u65B0\u7F13\u5B58\u72B6\u6001: ${e} ${g} -> ${r}`),!0}catch(s){return this.logger.warn(`[CacheManager] \u66F4\u65B0CustomMCP\u7F13\u5B58\u72B6\u6001\u5931\u8D25: ${s instanceof Error?s.message:String(s)}`),!1}}async markCustomMCPAsConsumed(e,t){try{let r=await this.loadExtendedCache(),o=w(e,t);if(!r.customMCPResults||!r.customMCPResults[o])return!1;let n=r.customMCPResults[o];return n.consumed||(n.consumed=!0,n.timestamp=new Date().toISOString(),await this.saveExtendedCache(r),this.logger.debug(`[CacheManager] \u6807\u8BB0\u7F13\u5B58\u4E3A\u5DF2\u6D88\u8D39: ${e}`)),!0}catch(r){return this.logger.warn(`[CacheManager] \u6807\u8BB0CustomMCP\u7F13\u5B58\u4E3A\u5DF2\u6D88\u8D39\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),!1}}async deleteCustomMCPResult(e,t){try{let r=await this.loadExtendedCache(),o=w(e,t);return!r.customMCPResults||!r.customMCPResults[o]?!1:(delete r.customMCPResults[o],await this.saveExtendedCache(r),this.logger.debug(`[CacheManager] \u5220\u9664\u7F13\u5B58\u6761\u76EE: ${e}`),!0)}catch(r){return this.logger.warn(`[CacheManager] \u5220\u9664CustomMCP\u7F13\u5B58\u6761\u76EE\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),!1}}async cleanupCustomMCPResults(){try{let e=await this.loadExtendedCache();if(!e.customMCPResults)return{cleaned:0,total:0};let t=Object.entries(e.customMCPResults),r=0;for(let[o,n]of t)x(n)&&(delete e.customMCPResults[o],r++);return r>0&&(await this.saveExtendedCache(e),this.logger.info(`[CacheManager] \u6E05\u7406CustomMCP\u7F13\u5B58: ${r}/${t.length}`)),{cleaned:r,total:t.length}}catch(e){return this.logger.warn(`[CacheManager] \u6E05\u7406CustomMCP\u7F13\u5B58\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),{cleaned:0,total:0}}}async getCustomMCPStatistics(){try{let e=await this.loadExtendedCache();if(!e.customMCPResults)return{totalEntries:0,pendingTasks:0,completedTasks:0,failedTasks:0,consumedEntries:0,cacheHitRate:0,lastCleanupTime:new Date().toISOString(),memoryUsage:0};let t=Object.values(e.customMCPResults),r=t.length,o=t.filter(p=>p.status==="pending").length,n=t.filter(p=>p.status==="completed").length,s=t.filter(p=>p.status==="failed").length,a=t.filter(p=>p.consumed).length,u=n>0?a/n*100:0,g=JSON.stringify(e.customMCPResults).length;return{totalEntries:r,pendingTasks:o,completedTasks:n,failedTasks:s,consumedEntries:a,cacheHitRate:u,lastCleanupTime:new Date().toISOString(),memoryUsage:g}}catch(e){return this.logger.warn(`[CacheManager] \u83B7\u53D6CustomMCP\u7F13\u5B58\u7EDF\u8BA1\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),{totalEntries:0,pendingTasks:0,completedTasks:0,failedTasks:0,consumedEntries:0,cacheHitRate:0,lastCleanupTime:new Date().toISOString(),memoryUsage:0}}}async loadExtendedCache(){try{return await this.loadExistingCache()}catch(e){return this.logger.warn(`[CacheManager] \u52A0\u8F7D\u6269\u5C55\u7F13\u5B58\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),{version:this.CACHE_VERSION,mcpServers:{},metadata:{lastGlobalUpdate:this.formatTimestamp(),totalWrites:0,createdAt:this.formatTimestamp()},customMCPResults:{}}}}async saveExtendedCache(e){await this.saveCache(e)}startCleanupTimer(){this.cleanupInterval=setInterval(()=>{this.cleanupCustomMCPResults().catch(e=>{this.logger.warn(`[CacheManager] \u81EA\u52A8\u6E05\u7406\u5931\u8D25: ${e}`)})},this.CLEANUP_INTERVAL),this.logger.debug(`[CacheManager] \u542F\u52A8\u6E05\u7406\u5B9A\u65F6\u5668\uFF0C\u95F4\u9694: ${this.CLEANUP_INTERVAL}ms`)}stopCleanupTimer(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0,this.logger.debug("[CacheManager] \u505C\u6B62\u6E05\u7406\u5B9A\u65F6\u5668"))}cleanup(){this.stopCleanupTimer(),this.logger.debug("[CacheManager] \u6E05\u7406\u8D44\u6E90\u5B8C\u6210")}};var Z=class{static{c(this,"CustomMCPHandler")}logger;tools=new Map;cacheManager;cacheLifecycleManager;taskStateManager;mcpServiceManager;TIMEOUT=E.TIMEOUT;CACHE_TTL=E.CACHE_TTL;CLEANUP_INTERVAL=E.CLEANUP_INTERVAL;cleanupTimer;activeTasks=new Map;eventBus=b();constructor(e,t){this.logger=l,this.cacheManager=e||new F,this.mcpServiceManager=t,this.cacheLifecycleManager=new Q(this.logger),this.taskStateManager=new Y(this.logger),this.startCleanupTimer(),this.cacheLifecycleManager.startAutoCleanup(),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("config:updated",async e=>{await this.handleConfigUpdated(e)})}async handleConfigUpdated(e){this.logger.debug("[CustomMCP] \u68C0\u6D4B\u5230\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u662F\u5426\u9700\u8981\u91CD\u65B0\u521D\u59CB\u5316");try{e.type==="customMCP"?(this.logger.debug("[CustomMCP] customMCP \u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0C\u91CD\u65B0\u521D\u59CB\u5316\u5904\u7406\u5668"),await this.reinitialize()):e.type==="serverTools"&&(this.logger.debug("[CustomMCP] serverTools \u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0C\u91CD\u65B0\u521D\u59CB\u5316\u5904\u7406\u5668"),await this.reinitialize())}catch(t){this.logger.error("[CustomMCP] \u914D\u7F6E\u66F4\u65B0\u5904\u7406\u5931\u8D25:",t)}}async reinitialize(){try{this.logger.debug("[CustomMCP] \u5F00\u59CB\u91CD\u65B0\u521D\u59CB\u5316\u5904\u7406\u5668"),this.tools.clear();let e=f.getCustomMCPTools();for(let t of e)this.tools.set(t.name,t),this.logger.debug(`[CustomMCP] \u91CD\u65B0\u52A0\u8F7D\u5DE5\u5177: ${t.name} (${t.handler.type})`);this.logger.debug(`[CustomMCP] \u91CD\u65B0\u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.tools.size} \u4E2A\u5DE5\u5177`)}catch(e){throw this.logger.error("[CustomMCP] \u91CD\u65B0\u521D\u59CB\u5316\u5931\u8D25:",e),e}}initialize(e){this.logger.debug("[CustomMCP] \u521D\u59CB\u5316 CustomMCP \u5904\u7406\u5668...");try{let t=e||f.getCustomMCPTools();this.tools.clear();for(let r of t)this.tools.set(r.name,r),this.logger.debug(`[CustomMCP] \u5DF2\u52A0\u8F7D\u5DE5\u5177: ${r.name} (${r.handler.type})`);this.logger.debug(`[CustomMCP] \u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.tools.size} \u4E2A\u5DE5\u5177`)}catch(t){throw this.logger.error("[CustomMCP] \u521D\u59CB\u5316\u5931\u8D25:",t),t}}getTools(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,inputSchema:Me(e.inputSchema)}))}hasTool(e){return this.tools.has(e)}getToolCount(){return this.tools.size}getToolNames(){return Array.from(this.tools.keys())}async callTool(e,t,r){if(!this.tools.get(e))throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);let n=await this.getCompletedResult(e,t);if(n)return this.logger.debug(`[CustomMCP] \u8FD4\u56DE\u5DF2\u5B8C\u6210\u7684\u4EFB\u52A1\u7ED3\u679C: ${e}`),await this.clearConsumedCache(e,t),n;try{let s=await Promise.race([this.executeToolWithBackgroundProcessing(e,t),this.createTimeoutPromise(e,t)]);return await this.cacheResult(e,t,s),s}catch(s){if(s instanceof J){let a=await this.generateTaskId(e,t);return this.logger.info(`[CustomMCP] \u5DE5\u5177\u8D85\u65F6\uFF0C\u8FD4\u56DE\u53CB\u597D\u63D0\u793A: ${e}, taskId: ${a}`),$e(a,e)}throw s}}async executeToolWithBackgroundProcessing(e,t){let r=this.tools.get(e);if(!r)throw new Error(`\u5DE5\u5177\u4E0D\u5B58\u5728: ${e}`);let o=await this.generateTaskId(e,t);await this.markTaskAsPending(o,e,t);try{let n=await this.callToolByType(r,t);return await this.markTaskAsCompleted(o,n),n}catch(n){let s=n instanceof Error?n:new Error(String(n));throw await this.markTaskAsFailed(o,s),n}}async createTimeoutPromise(e,t){return new Promise((r,o)=>{setTimeout(()=>{o(new J(`\u5DE5\u5177\u8C03\u7528\u8D85\u65F6: ${e}`))},this.TIMEOUT)})}async getCompletedResult(e,t){try{let r=this.generateCacheKey(e,t),o=await this.loadExtendedCache();if(!o.customMCPResults||!o.customMCPResults[r])return null;let n=o.customMCPResults[r];return n.status==="completed"&&!n.consumed&&!L(n.timestamp,n.ttl)?n.result:null}catch(r){return this.logger.warn(`[CustomMCP] \u83B7\u53D6\u7F13\u5B58\u5931\u8D25: ${r}`),null}}async callToolByType(e,t){switch(e.handler.type){case"proxy":return await this.callProxyTool(e,t);case"function":return await this.callFunctionTool(e,t);case"http":return await this.callHttpTool(e,t);case"script":return await this.callScriptTool(e,t);case"chain":return await this.callChainTool(e,t);case"mcp":try{return await this.forwardToMCPServiceManager(e,t)}catch(r){this.logger.error(`[CustomMCP] MCP \u7C7B\u578B\u5DE5\u5177\u8DEF\u7531\u5931\u8D25: ${e.name}`,r);let o=r instanceof Error?r.message:"MCP \u7C7B\u578B\u5DE5\u5177\u8DEF\u7531\u9519\u8BEF";return{content:[{type:"text",text:o.includes("MCPServiceManager \u672A\u521D\u59CB\u5316")?o:"\u5185\u90E8\u9519\u8BEF\uFF1AMCP \u7C7B\u578B\u5DE5\u5177\u8DEF\u7531\u9519\u8BEF"}],isError:!0}}default:{let r=e.handler.type;throw new Error(`\u4E0D\u652F\u6301\u7684\u5904\u7406\u5668\u7C7B\u578B: ${r}`)}}}async forwardToMCPServiceManager(e,t){if(!this.mcpServiceManager)throw this.logger.error(`[CustomMCP] MCPServiceManager \u672A\u521D\u59CB\u5316\uFF0C\u65E0\u6CD5\u8F6C\u53D1\u5DE5\u5177 ${e.name} \u7684\u8C03\u7528`),new Error("MCPServiceManager \u672A\u521D\u59CB\u5316");let r=e.handler;this.logger.info(`[CustomMCP] \u8F6C\u53D1MCP\u5DE5\u5177\u8C03\u7528: ${e.name}`,{serviceName:r.config.serviceName,toolName:r.config.toolName});try{let o=await this.mcpServiceManager.callTool(r.config.toolName,t);return this.logger.info(`[CustomMCP] MCP\u5DE5\u5177\u8F6C\u53D1\u6210\u529F: ${e.name}`),o}catch(o){return this.logger.error(`[CustomMCP] MCP\u5DE5\u5177\u8F6C\u53D1\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`MCP\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async callProxyTool(e,t){let r=e.handler;if(this.logger.info(`[CustomMCP] \u8C03\u7528\u4EE3\u7406\u5DE5\u5177: ${e.name}`,{platform:r.platform,config:r.config}),r.platform==="coze")return await this.callCozeWorkflow(e,t);throw new Error(`\u4E0D\u652F\u6301\u7684\u4EE3\u7406\u5E73\u53F0: ${r.platform}`)}async callCozeWorkflow(e,t){let o=e.handler.config;this.logger.info(`[CustomMCP] \u8C03\u7528 Coze \u5DE5\u4F5C\u6D41: ${e.name}`,{workflow_id:o.workflow_id,bot_id:o.bot_id});try{let n=this.buildCozeRequest(o,t),s=await this.sendCozeRequest(o,n);return this.logger.info(`[CustomMCP] Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u6210\u529F: ${e.name}`,{response:s}),this.processCozeResponse(e.name,s)}catch(n){return this.logger.error(`[CustomMCP] Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}buildCozeRequest(e,t){return{workflow_id:e.workflow_id,parameters:{...t}}}async sendCozeRequest(e,t){let r=e.base_url||"https://api.coze.cn",o="",n=f.getConfig().platforms?.coze?.token;if(!n)throw new Error("Coze Token \u914D\u7F6E\u4E0D\u5B58\u5728");if(e.workflow_id)o="/v1/workflow/run",t.workflow_id=e.workflow_id;else if(e.bot_id)o="/v3/chat",t.bot_id=e.bot_id;else throw new Error("Coze \u914D\u7F6E\u5FC5\u987B\u63D0\u4F9B workflow_id \u6216 bot_id");let s=`${r}${o}`,a=e.timeout||3e5,u={"Content-Type":"application/json",Authorization:`Bearer ${n}`,...e.headers};this.logger.debug(`[CustomMCP] \u53D1\u9001 Coze \u8BF7\u6C42\u5230: ${s}`,{headers:{...u},body:t});let g=new AbortController,p=setTimeout(()=>g.abort(),a);try{let m=await fetch(s,{method:"POST",headers:u,body:JSON.stringify(t)});if(clearTimeout(p),!m.ok){let T=await m.text();throw new Error(`Coze API \u8BF7\u6C42\u5931\u8D25 (${m.status}): ${T}`)}let S=await m.json();return this.logger.debug("[CustomMCP] Coze API \u54CD\u5E94:",S),S}catch(m){throw clearTimeout(p),m instanceof Error&&m.name==="AbortError"?new Error(`Coze API \u8BF7\u6C42\u8D85\u65F6 (${a}ms)`):m}}processCozeResponse(e,t){try{return t.data?{content:[{type:"text",text:t.data}],isError:!1}:{content:[{type:"text",text:JSON.stringify(t,null,2)}],isError:!1}}catch(r){return this.logger.error(`[CustomMCP] \u5904\u7406 Coze \u54CD\u5E94\u5931\u8D25: ${e}`,r),{content:[{type:"text",text:`\u5904\u7406\u54CD\u5E94\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async callFunctionTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528\u51FD\u6570\u5DE5\u5177: ${e.name}`,{module:r.module,function:r.function});try{let o=await this.loadModule(r.module),n=this.getFunction(o,r.function),s=await this.executeFunction(n,t,r);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s,null,2)}],isError:!1}}catch(o){return this.logger.error(`[CustomMCP] \u51FD\u6570\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`\u51FD\u6570\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async loadModule(e){try{let t=e;return!e.startsWith("/")&&!e.startsWith("file://")&&(t=new URL(e,`file://${process.cwd()}/`).href),this.logger.debug(`[CustomMCP] \u52A0\u8F7D\u6A21\u5757: ${t}`),await import(t)}catch(t){throw new Error(`\u65E0\u6CD5\u52A0\u8F7D\u6A21\u5757 ${e}: ${t instanceof Error?t.message:String(t)}`)}}getFunction(e,t){let r;if(e.default&&typeof e.default=="function"){if(t==="default")r=e.default;else if(typeof e.default=="object"&&e.default!==null&&t in e.default){let o=e.default[t];typeof o=="function"&&(r=o)}}if(!r&&t in e&&typeof e[t]=="function"&&(r=e[t]),!r)throw new Error(`\u5728\u6A21\u5757\u4E2D\u627E\u4E0D\u5230\u51FD\u6570: ${t}`);return r}async executeFunction(e,t,r){let o=r.timeout||3e4,n={...r.context,logger:this.logger,arguments:t},s=Promise.resolve().then(()=>e.length>1?e(t,n):e(t)),a=new Promise((u,g)=>{setTimeout(()=>g(new Error(`\u51FD\u6570\u6267\u884C\u8D85\u65F6 (${o}ms)`)),o)});return Promise.race([s,a])}async callHttpTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528 HTTP \u5DE5\u5177: ${e.name}`,{url:r.url,method:r.method||"POST"});try{let{url:o,requestOptions:n}=this.buildHttpRequest(r,t),s=await this.sendHttpRequest(o,n,r);return this.processHttpResponse(e.name,s,r)}catch(o){return this.logger.error(`[CustomMCP] HTTP \u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`HTTP \u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}buildHttpRequest(e,t){let r=e.method||"POST",o={"Content-Type":"application/json","User-Agent":"xiaozhi-client/1.0",...e.headers};if(e.auth)switch(e.auth.type){case"bearer":e.auth.token&&(o.Authorization=`Bearer ${e.auth.token}`);break;case"basic":if(e.auth.username&&e.auth.password){let u=btoa(`${e.auth.username}:${e.auth.password}`);o.Authorization=`Basic ${u}`}break;case"api_key":e.auth.api_key&&e.auth.api_key_header&&(o[e.auth.api_key_header]=e.auth.api_key);break}let n,s=e.url;if(r!=="GET")e.body_template?n=this.replaceTemplateVariables(e.body_template,t):n=JSON.stringify(t);else{let u=new URLSearchParams;for(let[p,m]of Object.entries(t))m!=null&&u.append(p,String(m));let g=u.toString();g&&(s+=(s.includes("?")?"&":"?")+g)}return{url:s,requestOptions:{method:r,headers:o,body:n}}}async sendHttpRequest(e,t,r){let o=r.timeout||3e4,n=r.retry_count||0,s=r.retry_delay||1e3,a=null;for(let u=0;u<=n;u++){try{this.logger.debug(`[CustomMCP] \u53D1\u9001 HTTP \u8BF7\u6C42 (\u5C1D\u8BD5 ${u+1}/${n+1}): ${e}`,{method:t.method,headers:t.headers});let g=new AbortController,p=setTimeout(()=>g.abort(),o),m=await fetch(e,{...t,signal:g.signal});if(clearTimeout(p),m.ok||u===n)return m;this.logger.warn(`[CustomMCP] HTTP \u8BF7\u6C42\u5931\u8D25 (${m.status}), \u5C06\u5728 ${s}ms \u540E\u91CD\u8BD5`),a=new Error(`HTTP \u8BF7\u6C42\u5931\u8D25: ${m.status} ${m.statusText}`)}catch(g){if(a=g instanceof Error?g:new Error(String(g)),g instanceof Error&&g.name==="AbortError"&&(a=new Error(`HTTP \u8BF7\u6C42\u8D85\u65F6 (${o}ms)`)),this.logger.warn(`[CustomMCP] HTTP \u8BF7\u6C42\u5F02\u5E38 (\u5C1D\u8BD5 ${u+1}/${n+1}):`,a.message),u===n)throw a}u<n&&await new Promise(g=>setTimeout(g,s))}throw a||new Error("HTTP \u8BF7\u6C42\u5931\u8D25")}async processHttpResponse(e,t,r){try{let o=t.headers.get("content-type")||"",n;if(o.includes("application/json")?n=await t.json():n=await t.text(),!t.ok)return{content:[{type:"text",text:`HTTP \u8BF7\u6C42\u5931\u8D25 (${t.status}): ${typeof n=="string"?n:JSON.stringify(n)}`}],isError:!0};let s=n;if(r.response_mapping){let a=this.extractResponseData(n,r.response_mapping);a!==void 0&&(s=a)}return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s,null,2)}],isError:!1}}catch(o){return this.logger.error(`[CustomMCP] \u5904\u7406 HTTP \u54CD\u5E94\u5931\u8D25: ${e}`,o),{content:[{type:"text",text:`\u5904\u7406\u54CD\u5E94\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}replaceTemplateVariables(e,t){let r=e;for(let[o,n]of Object.entries(t)){let s=`{{${o}}}`,a=typeof n=="string"?n:JSON.stringify(n);r=r.replace(new RegExp(s.replace(/[{}]/g,"\\$&"),"g"),a)}return r}extractResponseData(e,t){if(!t)return e;let r=c((o,n)=>{if(!n)return o;let s=n.split("."),a=o;for(let u of s)if(a&&typeof a=="object"&&a!==null&&u in a)a=a[u];else return;return a},"extractByPath");if(t.success_path){let o=r(e,t.success_path);if(o!==void 0)return t.data_path?r(o,t.data_path):o}if(t.data_path){let o=r(e,t.data_path);if(o!==void 0)return o}return e}async callScriptTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528\u811A\u672C\u5DE5\u5177: ${e.name}`,{script:r.script.substring(0,100)+(r.script.length>100?"...":""),interpreter:r.interpreter||"node"});try{let o=await this.executeScript(r,t);return{content:[{type:"text",text:typeof o=="string"?o:JSON.stringify(o,null,2)}],isError:!1}}catch(o){return this.logger.error(`[CustomMCP] \u811A\u672C\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`\u811A\u672C\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async executeScript(e,t){let{spawn:r}=await import("child_process"),{promisify:o}=await import("util"),n=await import("fs/promises"),s=await import("path"),a=await import("os"),u=e.timeout||3e4,g=e.interpreter||"node",p,m=!1;try{if(e.script.includes(`
25
- `)||e.script.length>200){let P=await n.mkdtemp(s.join(a.tmpdir(),"xiaozhi-script-")),k=this.getScriptExtension(g);p=s.join(P,`script${k}`),await n.writeFile(p,e.script,"utf8"),m=!0}else{p=e.script;try{await n.access(p)}catch{throw new Error(`\u811A\u672C\u6587\u4EF6\u4E0D\u5B58\u5728: ${p}`)}}let S={...process.env,...e.env,XIAOZHI_ARGUMENTS:JSON.stringify(t)},T=this.buildScriptCommand(g,p);return this.logger.debug(`[CustomMCP] \u6267\u884C\u811A\u672C\u547D\u4EE4: ${T.join(" ")}`),new Promise((P,k)=>{let I=r(T[0],T.slice(1),{env:S,stdio:["pipe","pipe","pipe"]}),ve="",Te="";I.stdout?.on("data",$=>{ve+=$.toString()}),I.stderr?.on("data",$=>{Te+=$.toString()});let Se=setTimeout(()=>{I.kill("SIGTERM"),k(new Error(`\u811A\u672C\u6267\u884C\u8D85\u65F6 (${u}ms)`))},u);I.on("close",$=>{clearTimeout(Se),$===0?P(ve.trim()):k(new Error(`\u811A\u672C\u6267\u884C\u5931\u8D25 (\u9000\u51FA\u7801: ${$}): ${Te.trim()}`))}),I.on("error",$=>{clearTimeout(Se),k(new Error(`\u811A\u672C\u6267\u884C\u9519\u8BEF: ${$.message}`))}),t&&Object.keys(t).length>0&&(I.stdin?.write(JSON.stringify(t)),I.stdin?.end())})}finally{if(m&&p)try{await n.unlink(p),await n.rmdir(s.dirname(p))}catch{}}}getScriptExtension(e){switch(e){case"node":return".js";case"python":return".py";case"bash":return".sh";default:return".txt"}}buildScriptCommand(e,t){switch(e){case"node":return["node",t];case"python":return["python3",t];case"bash":return["bash",t];default:throw new Error(`\u4E0D\u652F\u6301\u7684\u811A\u672C\u89E3\u91CA\u5668: ${e}`)}}async callChainTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528\u94FE\u5F0F\u5DE5\u5177: ${e.name}`,{tools:r.tools,mode:r.mode,error_handling:r.error_handling});try{let o;r.mode==="sequential"?o=await this.executeSequentialChain(r,t):o=await this.executeParallelChain(r,t);let n=o.flatMap(a=>a.content),s=o.some(a=>a.isError);return{content:n,isError:s}}catch(o){return this.logger.error(`[CustomMCP] \u94FE\u5F0F\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`\u94FE\u5F0F\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}delay(e){return new Promise(t=>setTimeout(t,e))}getToolInfo(e){return this.tools.get(e)}async executeSequentialChain(e,t){let r=[],o=t;for(let n of e.tools)try{this.logger.debug(`[CustomMCP] \u6267\u884C\u94FE\u5F0F\u5DE5\u5177\u4E2D\u7684: ${n}`);let s=await this.callToolRecursive(n,o);if(r.push(s),s.isError){if(e.error_handling==="stop")break;if(e.error_handling==="retry"){this.logger.warn(`[CustomMCP] \u5DE5\u5177 ${n} \u6267\u884C\u5931\u8D25\uFF0C\u5C1D\u8BD5\u91CD\u8BD5`);let a=await this.callToolRecursive(n,o);if(r[r.length-1]=a,a.isError)break}}if(!s.isError&&s.content.length>0){let a=s.content.filter(u=>u.type==="text").map(u=>u.text).join(`
26
- `);if(a)try{o=JSON.parse(a)}catch{o={input:a,...t}}}}catch(s){let a={content:[{type:"text",text:`\u5DE5\u5177 ${n} \u6267\u884C\u5F02\u5E38: ${s instanceof Error?s.message:String(s)}`}],isError:!0};if(r.push(a),e.error_handling==="stop")break}return r}async executeParallelChain(e,t){let r=e.tools.map(async o=>{try{return this.logger.debug(`[CustomMCP] \u5E76\u884C\u6267\u884C\u94FE\u5F0F\u5DE5\u5177\u4E2D\u7684: ${o}`),await this.callToolRecursive(o,t)}catch(n){return{content:[{type:"text",text:`\u5DE5\u5177 ${o} \u6267\u884C\u5F02\u5E38: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}});return Promise.all(r)}async callToolRecursive(e,t){if(this.tools.get(e))return this.callTool(e,t);throw new Error(`\u94FE\u5F0F\u5DE5\u5177\u4E2D\u5F15\u7528\u7684\u5DE5\u5177 ${e} \u4E0D\u5B58\u5728\u4E8E\u5F53\u524D CustomMCP \u5DE5\u5177\u96C6\u4E2D`)}async clearConsumedCache(e,t){try{let r=this.generateCacheKey(e,t),o=await this.loadExtendedCache();if(o.customMCPResults?.[r]){o.customMCPResults[r].consumed=!0;let n=o.customMCPResults[r];x(n)&&delete o.customMCPResults[r],await this.saveCache(o),this.logger.debug(`[CustomMCP] \u6E05\u7406\u5DF2\u6D88\u8D39\u7F13\u5B58: ${r}`)}}catch(r){this.logger.warn(`[CustomMCP] \u6E05\u7406\u7F13\u5B58\u5931\u8D25: ${r}`)}}async generateTaskId(e,t){return this.taskStateManager.generateTaskId(e,t)}async markTaskAsPending(e,t,r){try{let o=this.generateCacheKey(t,r),n={result:{content:[{type:"text",text:"\u5904\u7406\u4E2D..."}]},timestamp:new Date().toISOString(),ttl:this.CACHE_TTL,status:"pending",consumed:!1,taskId:e,retryCount:0};await this.updateCacheWithResult(o,n),this.taskStateManager.markTaskAsPending(e,t,r),this.activeTasks.set(e,{taskId:e,status:"pending",startTime:Date.now()}),this.logger.debug(`[CustomMCP] \u6807\u8BB0\u4EFB\u52A1\u4E3A\u5904\u7406\u4E2D: ${e}`)}catch(o){this.logger.warn(`[CustomMCP] \u6807\u8BB0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${o}`)}}async markTaskAsCompleted(e,t){try{let r=this.activeTasks.get(e);r&&(r.status="completed",r.endTime=new Date().toISOString(),r.result=t);let o=await this.loadExtendedCache();for(let[n,s]of Object.entries(o.customMCPResults||{})){let a=s;if(a.taskId===e){a.status="completed",a.result=t,a.timestamp=new Date().toISOString(),a.consumed=!1,(o.customMCPResults||{})[n]=a;break}}await this.saveCache(o),this.taskStateManager.markTaskAsCompleted(e,t),this.logger.debug(`[CustomMCP] \u6807\u8BB0\u4EFB\u52A1\u4E3A\u5DF2\u5B8C\u6210: ${e}`)}catch(r){this.logger.warn(`[CustomMCP] \u66F4\u65B0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${r}`)}}async markTaskAsFailed(e,t){try{let r=await this.loadExtendedCache();for(let[n,s]of Object.entries(r.customMCPResults||{})){let a=s;if(a.taskId===e){a.status="failed",a.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${t.message}`}]},a.timestamp=new Date().toISOString(),a.consumed=!0,(r.customMCPResults||{})[n]=a;break}}await this.saveCache(r),this.taskStateManager.markTaskAsFailed(e,t.message);let o=this.activeTasks.get(e);o&&(o.status="failed",o.endTime=new Date().toISOString(),o.error=t.message),this.logger.debug(`[CustomMCP] \u6807\u8BB0\u4EFB\u52A1\u4E3A\u5931\u8D25: ${e}`)}catch(r){this.logger.warn(`[CustomMCP] \u66F4\u65B0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${r}`)}}startCleanupTimer(){this.cleanupTimer=setInterval(()=>{this.cleanupExpiredCache().catch(e=>{this.logger.warn(`[CustomMCP] \u7F13\u5B58\u6E05\u7406\u5931\u8D25: ${e}`)})},this.CLEANUP_INTERVAL),this.logger.debug(`[CustomMCP] \u542F\u52A8\u7F13\u5B58\u6E05\u7406\u5B9A\u65F6\u5668\uFF0C\u95F4\u9694: ${this.CLEANUP_INTERVAL}ms`)}async cleanupExpiredCache(){try{let e=await this.loadExtendedCache(),t=!1,r=0;for(let[o,n]of Object.entries(e.customMCPResults||{})){let s=n;x(s)&&(e.customMCPResults?.[o]&&delete e.customMCPResults[o],t=!0,r++,s.taskId&&this.activeTasks.delete(s.taskId))}t&&(await this.saveCache(e),this.logger.debug(`[CustomMCP] \u6E05\u7406\u8FC7\u671F\u7F13\u5B58\u5B8C\u6210\uFF0C\u6E05\u7406\u4E86 ${r} \u4E2A\u6761\u76EE`))}catch(e){this.logger.warn(`[CustomMCP] \u6E05\u7406\u8FC7\u671F\u7F13\u5B58\u5931\u8D25: ${e}`)}}generateCacheKey(e,t){return w(e,t)}async loadExtendedCache(){try{return await this.cacheManager.loadExistingCache()}catch{return{version:"1.0.0",mcpServers:{},metadata:{lastGlobalUpdate:new Date().toISOString(),totalWrites:0,createdAt:new Date().toISOString()},customMCPResults:{}}}}async updateCacheWithResult(e,t){try{let r=await this.loadExtendedCache();r.customMCPResults||(r.customMCPResults={}),r.customMCPResults[e]=t,await this.saveCache(r)}catch(r){this.logger.warn(`[CustomMCP] \u66F4\u65B0\u7F13\u5B58\u5931\u8D25: ${r}`)}}async cacheResult(e,t,r){try{let o=this.generateCacheKey(e,t),n={result:r,timestamp:new Date().toISOString(),ttl:this.CACHE_TTL,status:"completed",consumed:!1,retryCount:0};await this.updateCacheWithResult(o,n),this.logger.debug(`[CustomMCP] \u7F13\u5B58\u5DE5\u5177\u7ED3\u679C: ${e}`)}catch(o){this.logger.warn(`[CustomMCP] \u7F13\u5B58\u7ED3\u679C\u5931\u8D25: ${o}`)}}async saveCache(e){try{await this.cacheManager.saveCache(e)}catch(t){this.logger.warn(`[CustomMCP] \u4FDD\u5B58\u7F13\u5B58\u5931\u8D25: ${t}`)}}stopCleanupTimer(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0,this.logger.info("[CustomMCP] \u505C\u6B62\u7F13\u5B58\u6E05\u7406\u5B9A\u65F6\u5668"))}cleanup(){this.logger.info("[CustomMCP] \u6E05\u7406 CustomMCP \u5904\u7406\u5668\u8D44\u6E90"),this.stopCleanupTimer(),this.cacheLifecycleManager.stopAutoCleanup(),this.cacheLifecycleManager.cleanup(),this.taskStateManager.cleanup(),this.cacheManager.cleanup(),this.tools.clear(),this.activeTasks.clear()}getCacheLifecycleManager(){return this.cacheLifecycleManager}getTaskStateManager(){return this.taskStateManager}async getCacheStatistics(){return this.cacheManager.getCustomMCPStatistics()}getTaskStatistics(){return this.taskStateManager.getTaskStatistics()}getTaskStatus(e){return this.taskStateManager.getTaskStatus(e)}validateTaskId(e){return this.taskStateManager.validateTaskId(e)}restartStalledTasks(e=3e4){return this.taskStateManager.restartStalledTasks(e)}async manualCleanupCache(){return this.cacheManager.cleanupCustomMCPResults()}async validateSystemIntegrity(){let e=await this.cacheManager.loadExtendedCache(),t=this.cacheLifecycleManager.validateCacheIntegrity(e),r=this.taskStateManager.validateTaskIntegrity();return{cacheValid:t.isValid,taskValid:r.isValid,issues:[...t.issues,...r.issues]}}};var X=class{static{c(this,"ToolSyncManager")}configManager;logger;syncLocks=new Map;eventBus=b();constructor(e,t=l){this.configManager=e,this.logger=t.withTag("ToolSync"),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("config:updated",async e=>{await this.handleConfigUpdated(e)}),this.eventBus.onEvent("mcp:server:added",async e=>{await this.handleMCPServerAdded(e)}),this.eventBus.onEvent("mcp:server:removed",async e=>{await this.handleMCPServerRemoved(e)})}async handleConfigUpdated(e){this.logger.debug("\u68C0\u6D4B\u5230\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u5DE5\u5177\u540C\u6B65\u72B6\u6001");try{e.type==="customMCP"?this.logger.debug("customMCP\u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0CCustomMCPHandler\u5C06\u81EA\u52A8\u5904\u7406"):e.type==="serverTools"&&e.serviceName?await this.handleServerToolsConfigUpdated(e.serviceName):await this.handleGeneralConfigUpdated()}catch(t){this.logger.error("\u914D\u7F6E\u66F4\u65B0\u540E\u7684\u5DE5\u5177\u540C\u6B65\u5931\u8D25:",t)}}async handleServerToolsConfigUpdated(e){this.logger.debug(`\u5904\u7406\u670D\u52A1 ${e} \u7684serverTools\u914D\u7F6E\u66F4\u65B0`);try{this.eventBus.emitEvent("tool-sync:server-tools-updated",{serviceName:e,timestamp:new Date})}catch(t){this.logger.error(`\u5904\u7406\u670D\u52A1 ${e} \u914D\u7F6E\u66F4\u65B0\u5931\u8D25:`,t)}}async handleGeneralConfigUpdated(){this.logger.info("\u5904\u7406\u901A\u7528\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u6240\u6709\u670D\u52A1\u540C\u6B65\u72B6\u6001");try{this.eventBus.emitEvent("tool-sync:general-config-updated",{timestamp:new Date})}catch(e){this.logger.error("\u5904\u7406\u901A\u7528\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",e)}}async handleMCPServerAdded(e){this.logger.info(`\u5904\u7406MCP\u670D\u52A1\u6DFB\u52A0\u4E8B\u4EF6: ${e.serverName}`);try{setTimeout(async()=>{await this.triggerServiceToolSync(e.serverName)},1e3)}catch(t){this.logger.error(`\u5904\u7406\u670D\u52A1 ${e.serverName} \u6DFB\u52A0\u4E8B\u4EF6\u5931\u8D25:`,t)}}async triggerServiceToolSync(e){this.logger.info(`\u89E6\u53D1\u670D\u52A1 ${e} \u7684\u5DE5\u5177\u540C\u6B65`);try{this.eventBus.emitEvent("tool-sync:request-service-tools",{serviceName:e,timestamp:new Date})}catch(t){this.logger.error(`\u89E6\u53D1\u670D\u52A1 ${e} \u5DE5\u5177\u540C\u6B65\u5931\u8D25:`,t)}}async handleMCPServerRemoved(e){this.logger.info(`\u5904\u7406MCP\u670D\u52A1\u79FB\u9664\u4E8B\u4EF6: ${e.serverName}`);try{await this.removeServiceToolsFromCustomMCP(e.serverName,e.affectedTools)}catch(t){this.logger.error(`\u5904\u7406\u670D\u52A1 ${e.serverName} \u79FB\u9664\u4E8B\u4EF6\u5931\u8D25:`,t)}}async removeServiceToolsFromCustomMCP(e,t){this.logger.info(`\u4ECEcustomMCP\u4E2D\u79FB\u9664\u670D\u52A1 ${e} \u7684\u5DE5\u5177`);try{let r=this.configManager.getCustomMCPTools(),o=r.filter(s=>!s.name.startsWith(`${e}__`));if(o.length===r.length){this.logger.debug(`\u670D\u52A1 ${e} \u7684\u5DE5\u5177\u4E0D\u5728customMCP\u4E2D\uFF0C\u65E0\u9700\u79FB\u9664`);return}await this.configManager.updateCustomMCPTools(o);let n=r.length-o.length;this.logger.info(`\u6210\u529F\u4ECEcustomMCP\u4E2D\u79FB\u9664\u670D\u52A1 ${e} \u7684 ${n} \u4E2A\u5DE5\u5177`),this.eventBus.emitEvent("tool-sync:service-tools-removed",{serviceName:e,removedCount:n,timestamp:new Date})}catch(r){throw this.logger.error(`\u79FB\u9664\u670D\u52A1 ${e} \u5DE5\u5177\u5931\u8D25:`,r),r}}async syncToolsAfterConnection(e,t){if(this.syncLocks.has(e)){this.logger.debug(`\u670D\u52A1 ${e} \u6B63\u5728\u540C\u6B65\u4E2D\uFF0C\u8DF3\u8FC7`);return}let r=this.doSyncTools(e,t).finally(()=>{this.syncLocks.delete(e)});this.syncLocks.set(e,r),await r}async doSyncTools(e,t){try{this.logger.info(`\u5F00\u59CB\u540C\u6B65\u670D\u52A1 ${e} \u7684\u5DE5\u5177`);let r=this.configManager.getServerToolsConfig(e);if(!r){this.logger.debug(`\u670D\u52A1 ${e} \u65E0 mcpServerConfig \u914D\u7F6E\uFF0C\u8DF3\u8FC7\u540C\u6B65`);return}let o=this.getEnabledTools(r,t);if(o.length===0){this.logger.debug(`\u670D\u52A1 ${e} \u65E0\u542F\u7528\u5DE5\u5177\uFF0C\u8DF3\u8FC7\u540C\u6B65`);return}let n=this.configManager.getCustomMCPTools(),s=new Set(n.map(u=>u.name)),a=o.filter(u=>!s.has(`${e}__${u.name}`));if(a.length===0){this.logger.info(`\u670D\u52A1 ${e} \u7684\u542F\u7528\u5DE5\u5177\u5DF2\u5B58\u5728\u4E8E customMCP \u4E2D\uFF0C\u8DF3\u8FC7\u540C\u6B65`);return}await this.addToolsToCustomMCP(e,a),this.logger.info(`\u6210\u529F\u540C\u6B65\u670D\u52A1 ${e} \u7684 ${a.length} \u4E2A\u5DE5\u5177\u5230 customMCP`)}catch(r){this.logger.error(`\u540C\u6B65\u670D\u52A1 ${e} \u5DE5\u5177\u5931\u8D25:`,r),this.recordSyncError(e,r)}}getEnabledTools(e,t){let r=[];for(let o of t){let n=e[o.name];n&&n.enable!==!1&&r.push(o)}return r}async addToolsToCustomMCP(e,t){let r=t.map(o=>({name:`${e}__${o.name}`,description:o.description||"",inputSchema:o.inputSchema||{},handler:{type:"mcp",config:{serviceName:e,toolName:o.name}}}));await this.configManager.addCustomMCPTools(r),await this.syncToolStats(e,t)}recordSyncError(e,t){let r={serviceName:e,error:t instanceof Error?t.message:String(t),timestamp:new Date().toISOString(),type:t instanceof Error?t.constructor.name:"UnknownError"};this.logger.error("\u540C\u6B65\u9519\u8BEF\u8BB0\u5F55:",r)}getSyncLocks(){return Array.from(this.syncLocks.keys())}clearSyncLocks(){this.syncLocks.clear(),this.logger.debug("\u5DF2\u6E05\u7406\u6240\u6709\u540C\u6B65\u9501")}async syncToolStats(e,t){try{let r=this.configManager.getServerToolsConfig(e);if(!r){this.logger.debug(`\u670D\u52A1 ${e} \u65E0 mcpServerConfig \u914D\u7F6E\uFF0C\u8DF3\u8FC7\u7EDF\u8BA1\u4FE1\u606F\u540C\u6B65`);return}let o=this.configManager.getCustomMCPTools(),n=new Map(o.map(s=>[s.name,s]));for(let s of t){let a=`${e}__${s.name}`,u=n.get(a),g=r[s.name];if(u&&g&&(!u.stats||!u.stats.usageCount&&!u.stats.lastUsedTime)){let p={};g.usageCount!==void 0&&(p.usageCount=g.usageCount),g.lastUsedTime&&(p.lastUsedTime=g.lastUsedTime),Object.keys(p).length>0&&(await this.updateCustomMCPToolStats(a,p),this.logger.debug(`\u5DF2\u540C\u6B65\u5DE5\u5177 ${a} \u7684\u7EDF\u8BA1\u4FE1\u606F: ${JSON.stringify(p)}`))}}}catch(r){this.logger.error(`\u540C\u6B65\u670D\u52A1 ${e} \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,r instanceof Error?r.message:String(r))}}async updateCustomMCPToolStats(e,t){try{let r=this.configManager.getCustomMCPTools(),o=r.findIndex(a=>a.name===e);if(o===-1){this.logger.warn(`\u5DE5\u5177 ${e} \u4E0D\u5B58\u5728\u4E8E customMCP \u4E2D`);return}let n=[...r],s=n[o];s.stats||(s.stats={}),t.usageCount!==void 0&&(s.stats.usageCount=t.usageCount),t.lastUsedTime!==void 0&&(s.stats.lastUsedTime=t.lastUsedTime),await this.configManager.updateCustomMCPTools(n)}catch(r){throw this.logger.error(`\u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,r instanceof Error?r.message:String(r)),r}}};import*as U from"fs";import*as N from"path";import{realpathSync as ot}from"fs";import{tmpdir as nt}from"os";import d from"path";import{fileURLToPath as Ne}from"url";var he={NAME:"xiaozhi-mcp-service",DEFAULT_PORT:3e3,DEFAULT_WEB_UI_PORT:9999,PID_FILE:"xiaozhi.pid",LOG_FILE:"xiaozhi.log"},z={FILE_NAMES:["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"],DEFAULT_FILE:"xiaozhi.config.default.json",DIR_ENV_VAR:"XIAOZHI_CONFIG_DIR"},G={WORK_DIR:".xiaozhi",TEMPLATES_DIR:"templates",LOGS_DIR:"logs"},Le={GENERAL_ERROR:"GENERAL_ERROR",CONFIG_ERROR:"CONFIG_ERROR",SERVICE_ERROR:"SERVICE_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",FILE_ERROR:"FILE_ERROR",PROCESS_ERROR:"PROCESS_ERROR",NETWORK_ERROR:"NETWORK_ERROR",PERMISSION_ERROR:"PERMISSION_ERROR"};import C from"fs";import y from"path";var de=class i extends Error{constructor(t,r,o=1,n){super(t);this.code=r;this.exitCode=o;this.suggestions=n;this.name="CLIError",Error.captureStackTrace&&Error.captureStackTrace(this,i)}static{c(this,"CLIError")}static withSuggestions(t,r,o){return new i(t,r,1,o)}};var h=class i extends de{static{c(this,"FileError")}constructor(e,t,r){let o=t?`${e}: ${t}`:e;super(o,Le.FILE_ERROR,1,r),this.name="FileError"}static notFound(e){return new i("\u6587\u4EF6\u4E0D\u5B58\u5728",e,["\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E"])}static permissionDenied(e){return new i("\u6743\u9650\u4E0D\u8DB3",e,["\u68C0\u67E5\u6587\u4EF6\u6743\u9650\u6216\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"])}static alreadyExists(e){return new i("\u6587\u4EF6\u5DF2\u5B58\u5728",e,["\u4F7F\u7528\u4E0D\u540C\u7684\u6587\u4EF6\u540D\u6216\u5220\u9664\u73B0\u6709\u6587\u4EF6"])}};var _=class i{static{c(this,"FileUtils")}static exists(e){try{return C.existsSync(e)}catch{return!1}}static ensureDir(e){try{C.existsSync(e)||C.mkdirSync(e,{recursive:!0})}catch{throw new h("\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55",e)}}static readFile(e,t="utf8"){try{if(!i.exists(e))throw h.notFound(e);return C.readFileSync(e,t)}catch(r){throw r instanceof h?r:new h("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6",e)}}static writeFile(e,t,r){try{if(!r?.overwrite&&i.exists(e))throw h.alreadyExists(e);let o=y.dirname(e);i.ensureDir(o),C.writeFileSync(e,t,"utf8")}catch(o){throw o instanceof h?o:new h("\u65E0\u6CD5\u5199\u5165\u6587\u4EF6",e)}}static copyFile(e,t,r){try{if(!i.exists(e))throw h.notFound(e);if(!r?.overwrite&&i.exists(t))throw h.alreadyExists(t);let o=y.dirname(t);i.ensureDir(o),C.copyFileSync(e,t)}catch(o){throw o instanceof h?o:new h("\u65E0\u6CD5\u590D\u5236\u6587\u4EF6",e)}}static deleteFile(e){try{i.exists(e)&&C.unlinkSync(e)}catch{throw new h("\u65E0\u6CD5\u5220\u9664\u6587\u4EF6",e)}}static copyDirectory(e,t,r={}){try{if(!i.exists(e))throw h.notFound(e);i.ensureDir(t);let o=C.readdirSync(e);for(let n of o){if(r.exclude?.includes(n))continue;let s=y.join(e,n),a=y.join(t,n);C.statSync(s).isDirectory()?r.recursive!==!1&&i.copyDirectory(s,a,r):i.copyFile(s,a,{overwrite:r.overwrite})}}catch(o){throw o instanceof h?o:new h("\u65E0\u6CD5\u590D\u5236\u76EE\u5F55",e)}}static deleteDirectory(e,t={}){try{i.exists(e)&&C.rmSync(e,{recursive:t.recursive??!0,force:!0})}catch{throw new h("\u65E0\u6CD5\u5220\u9664\u76EE\u5F55",e)}}static getFileInfo(e){try{if(!i.exists(e))throw h.notFound(e);let t=C.statSync(e);return{size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory(),mtime:t.mtime,ctime:t.ctime}}catch(t){throw t instanceof h?t:new h("\u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F",e)}}static listDirectory(e,t={}){try{if(!i.exists(e))throw h.notFound(e);let r=C.readdirSync(e),o=[];for(let n of r){if(!t.includeHidden&&n.startsWith("."))continue;let s=y.join(e,n);if(o.push(s),t.recursive&&C.statSync(s).isDirectory()){let a=i.listDirectory(s,t);o=o.concat(a)}}return o}catch(r){throw r instanceof h?r:new h("\u65E0\u6CD5\u5217\u51FA\u76EE\u5F55\u5185\u5BB9",e)}}static createTempFile(e="xiaozhi-",t=".tmp"){let r=process.env.TMPDIR||process.env.TEMP||"/tmp",o=Date.now(),n=Math.random().toString(36).substring(2),s=`${e}${o}-${n}${t}`;return y.join(r,s)}static checkPermissions(e,t=C.constants.R_OK|C.constants.W_OK){try{return C.accessSync(e,t),!0}catch{return!1}}static getExtension(e){return y.extname(e).toLowerCase()}static getBaseName(e){return y.basename(e,y.extname(e))}static normalizePath(e){return y.normalize(e)}static resolvePath(e,t){return t?y.resolve(t,e):y.resolve(e)}};var ee=class i{static{c(this,"PathUtils")}static getPidFile(){let e=process.env[z.DIR_ENV_VAR]||process.cwd();return d.join(e,`.${he.NAME}.pid`)}static getLogFile(e){let t=e||process.cwd();return d.join(t,he.LOG_FILE)}static getConfigDir(){return process.env[z.DIR_ENV_VAR]||process.cwd()}static getWorkDir(){let e=i.getConfigDir();return d.join(e,G.WORK_DIR)}static getTemplatesDir(){let e=Ne(import.meta.url),t=d.dirname(e);return[d.join(t,G.TEMPLATES_DIR),d.join(t,"..","..","..",G.TEMPLATES_DIR),d.join(t,"..","..","..","..",G.TEMPLATES_DIR)]}static findTemplatesDir(){let e=i.getTemplatesDir();for(let t of e)if(_.exists(t))return t;return null}static getTemplatePath(e){let t=i.findTemplatesDir();if(!t)return null;let r=d.join(t,e);return _.exists(r)?r:null}static getScriptDir(){let e=Ne(import.meta.url);return d.dirname(e)}static getProjectRoot(){let e=i.getScriptDir();return d.join(e,"..","..","..")}static getDistDir(){let e=i.getProjectRoot();return d.join(e,"dist")}static getRelativePath(e){let t=i.getProjectRoot();return d.relative(t,e)}static resolveConfigPath(e){let t=i.getConfigDir();if(e)return d.join(t,`xiaozhi.config.${e}`);for(let r of z.FILE_NAMES){let o=d.join(t,r);if(_.exists(o))return o}return d.join(t,z.FILE_NAMES[2])}static getDefaultConfigPath(){let e=i.getProjectRoot();return d.join(e,z.DEFAULT_FILE)}static validatePath(e){return!d.normalize(e).includes("..")}static ensurePathWithin(e,t){let r=d.resolve(t,e),o=d.resolve(t);if(!r.startsWith(o))throw new Error(`\u8DEF\u5F84 ${e} \u8D85\u51FA\u4E86\u5141\u8BB8\u7684\u8303\u56F4`);return r}static getExecutablePath(e){let t=process.argv[1];if(!t)return d.join(process.cwd(),`${e}.js`);let r;try{r=ot(t)}catch{r=t}let o=d.dirname(r);return d.join(o,`${e}.js`)}static getMcpServerProxyPath(){return i.getExecutablePath("mcpServerProxy")}static getWebServerStandalonePath(){return i.getExecutablePath("WebServerStandalone")}static createSafePath(...e){let t=d.join(...e),r=d.normalize(t);if(r.includes("..")||r.includes("~"))throw new Error(`\u4E0D\u5B89\u5168\u7684\u8DEF\u5F84: ${r}`);return r}static getTempDir(){return process.env.TMPDIR||process.env.TEMP||nt()}static getHomeDir(){return process.env.HOME||process.env.USERPROFILE||""}};import te from"pino";var re=class{static{c(this,"ToolCallLogger")}pinoLogger;maxRecords;logFilePath;constructor(e,t){if(this.maxRecords=e.maxRecords??100,e.logFilePath)this.logFilePath=N.resolve(N.normalize(e.logFilePath));else{let r=t||ee.getTempDir();this.logFilePath=N.join(N.normalize(r),"tool-calls.jsonl")}this.pinoLogger=this.createPinoLogger(this.logFilePath),l.debug(`ToolCallLogger \u521D\u59CB\u5316: maxRecords=${this.maxRecords}, path=${this.logFilePath}`)}createPinoLogger(e){let t=[];t.push({level:"info",stream:{write:c(r=>{try{let o=JSON.parse(r),n=this.formatConsoleMessage(o);l.info(`[\u5DE5\u5177\u8C03\u7528] ${n}`)}catch{l.info(`[\u5DE5\u5177\u8C03\u7528] ${r.trim()}`)}},"write")}});try{t.push({level:"info",stream:te.destination({dest:e,sync:!0,append:!0,mkdir:!0})})}catch(r){l.error("\u65E0\u6CD5\u521B\u5EFA\u5DE5\u5177\u8C03\u7528\u65E5\u5FD7\u6587\u4EF6:",r)}return te({level:"info",timestamp:te.stdTimeFunctions?.isoTime||(()=>`,"time":${Date.now()}`),formatters:{level:c((r,o)=>({level:o}),"level")},base:null},te.multistream(t,{dedupe:!0}))}formatConsoleMessage(e){let t=e.toolName||"\u672A\u77E5\u5DE5\u5177",r=e.success!==!1,o=e.duration?` (${e.duration}ms)`:"";return`${r?"\u2705":"\u274C"} ${t}${o}`}async cleanupOldRecords(){try{if(!U.existsSync(this.logFilePath))return;let t=U.readFileSync(this.logFilePath,"utf8").trim().split(`
27
- `).filter(s=>s.trim()!=="");if(t.length<=this.maxRecords)return;let r=t.length-this.maxRecords+1,o=t.slice(r),n=o.join(`
28
- `)+(o.length>0?`
29
- `:"");U.writeFileSync(this.logFilePath,n,"utf8"),l.debug(`\u5DF2\u6E05\u7406 ${r} \u6761\u65E7\u7684\u5DE5\u5177\u8C03\u7528\u8BB0\u5F55\uFF0C\u4FDD\u7559\u6700\u65B0 ${this.maxRecords} \u6761`)}catch(e){l.error("\u6E05\u7406\u65E7\u5DE5\u5177\u8C03\u7528\u8BB0\u5F55\u5931\u8D25:",e)}}async recordToolCall(e){try{await this.cleanupOldRecords(),this.pinoLogger.info(e,e.toolName)}catch(t){l.error("\u8BB0\u5F55\u5DE5\u5177\u8C03\u7528\u5931\u8D25:",t)}}getLogFilePath(){return this.logFilePath}getMaxRecords(){return this.maxRecords}};var oe=class{static{c(this,"MCPMessageHandler")}logger;serviceManager;constructor(e){this.serviceManager=e,this.logger=l}async handleMessage(e){this.logger.debug(`\u5904\u7406 MCP \u6D88\u606F: ${e.method}`,e);try{let t=e.id===void 0;switch(e.method){case"initialize":return await this.handleInitialize(e.params,e.id);case"notifications/initialized":return await this.handleInitializedNotification(e.params);case"tools/list":return await this.handleToolsList(e.id);case"tools/call":return await this.handleToolCall(e.params,e.id);case"resources/list":return await this.handleResourcesList(e.id);case"prompts/list":return await this.handlePromptsList(e.id);case"ping":return await this.handlePing(e.id);default:if(t)return this.logger.warn(`\u6536\u5230\u672A\u77E5\u7684\u901A\u77E5\u6D88\u606F: ${e.method}`,e),null;throw new Error(`\u672A\u77E5\u7684\u65B9\u6CD5: ${e.method}`)}}catch(t){return this.logger.error(`\u5904\u7406\u6D88\u606F\u65F6\u51FA\u9519: ${e.method}`,t),e.id===void 0?null:this.createErrorResponse(t,e.id)}}async handleInitialize(e,t){this.logger.debug("\u5904\u7406 initialize \u8BF7\u6C42",e);let r=["2024-11-05","2025-06-18"],o=e.protocolVersion,n=r.includes(o)?o:"2024-11-05";return this.logger.debug(`\u534F\u8BAE\u7248\u672C\u534F\u5546: \u5BA2\u6237\u7AEF=${o}, \u670D\u52A1\u5668\u54CD\u5E94=${n}`),{jsonrpc:"2.0",result:{serverInfo:{name:"xiaozhi-mcp-server",version:"1.0.0"},capabilities:{tools:{},logging:{}},protocolVersion:n},id:t!==void 0?t:1}}async handleInitializedNotification(e){return this.logger.debug("\u6536\u5230 initialized \u901A\u77E5\uFF0C\u5BA2\u6237\u7AEF\u521D\u59CB\u5316\u5B8C\u6210",e),null}async handleToolsList(e){this.logger.debug("\u5904\u7406 tools/list \u8BF7\u6C42");try{return{jsonrpc:"2.0",result:{tools:this.serviceManager.getAllTools().map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema}))},id:e!==void 0?e:1}}catch(t){throw this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25",t),t}}async handleToolCall(e,t){try{if(!e.name)throw new Error("\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");let r=await this.serviceManager.callTool(e.name,e.arguments||{});return{jsonrpc:"2.0",result:{content:r.content,isError:r.isError||!1},id:t!==void 0?t:1}}catch(r){throw this.logger.error(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,r),r}}async handlePing(e){return this.logger.debug("\u5904\u7406 ping \u8BF7\u6C42"),{jsonrpc:"2.0",result:{status:"ok",timestamp:new Date().toISOString()},id:e!==void 0?e:1}}async handleResourcesList(e){this.logger.debug("\u5904\u7406 resources/list \u8BF7\u6C42");let t=[];return this.logger.debug(`\u8FD4\u56DE ${t.length} \u4E2A\u8D44\u6E90`),{jsonrpc:"2.0",result:{resources:t},id:e!==void 0?e:1}}async handlePromptsList(e){this.logger.debug("\u5904\u7406 prompts/list \u8BF7\u6C42");let t=[];return this.logger.debug(`\u8FD4\u56DE ${t.length} \u4E2A\u63D0\u793A\u6A21\u677F`),{jsonrpc:"2.0",result:{prompts:t},id:e!==void 0?e:1}}createErrorResponse(e,t){let r=-32603;return e.message.includes("\u672A\u627E\u5230\u5DE5\u5177")||e.message.includes("\u672A\u77E5\u7684\u65B9\u6CD5")?r=-32601:(e.message.includes("\u53C2\u6570")||e.message.includes("\u4E0D\u80FD\u4E3A\u7A7A"))&&(r=-32602),{jsonrpc:"2.0",error:{code:r,message:e.message,data:{stack:e.stack}},id:t!==void 0?t:1}}getServiceManager(){return this.serviceManager}};var D=class{static{c(this,"TransportAdapter")}messageHandler;connectionId;config;state="disconnected";constructor(e,t){this.messageHandler=e,this.config=t,this.connectionId=this.generateConnectionId()}async handleIncomingMessage(e){try{let t=await this.messageHandler.handleMessage(e);t!==null&&await this.sendMessage(t)}catch(t){let r=this.createErrorResponse(t,e.id);await this.sendMessage(r)}}createErrorResponse(e,t){let r=-32603;return e.message.includes("\u672A\u627E\u5230\u5DE5\u5177")||e.message.includes("\u672A\u77E5\u7684\u65B9\u6CD5")?r=-32601:(e.message.includes("\u53C2\u6570")||e.message.includes("\u4E0D\u80FD\u4E3A\u7A7A"))&&(r=-32602),{jsonrpc:"2.0",error:{code:r,message:e.message,data:{stack:e.stack}},id:t}}generateConnectionId(){let e=Date.now(),t=Math.random().toString(36).substr(2,9);return`${this.config.name}_${e}_${t}`}getConnectionId(){return this.connectionId}getState(){return this.state}setState(e){let t=this.state;this.state=e,t!==e&&this.onStateChange(t,e)}onStateChange(e,t){}getConfig(){return{...this.config}}getMessageHandler(){return this.messageHandler}parseMessage(e){try{let t=JSON.parse(e.trim());return!t.jsonrpc||t.jsonrpc!=="2.0"||!t.method?null:t}catch{return null}}serializeMessage(e){try{return JSON.stringify(e)}catch(t){let r=t instanceof Error?t.message:String(t);throw new Error(`\u6D88\u606F\u5E8F\u5217\u5316\u5931\u8D25: ${r}`)}}validateMessage(e){if(!e||typeof e!="object")return!1;let t=e;return!(t.jsonrpc!=="2.0"||t.method&&typeof t.method!="string"||!t.method&&!t.result&&!t.error)}createTimeoutPromise(e,t){return Promise.race([e,new Promise((r,o)=>{setTimeout(()=>{o(new Error(`\u64CD\u4F5C\u8D85\u65F6: ${t}ms`))},t)})])}};var W=class extends D{static{c(this,"StdioAdapter")}messageBuffer="";isRunning=!1;encoding;bufferSize;constructor(e,t={name:"stdio"}){super(e,t),this.encoding=t.encoding||"utf8",this.bufferSize=t.bufferSize||1024*1024}async initialize(){try{process.stdin.setEncoding(this.encoding),this.setupProcessHandlers(),this.setState("connecting")}catch(e){throw this.setState("error"),e}}async start(){if(!this.isRunning)try{this.isRunning=!0,this.setupStdioHandlers(),this.setState("connected")}catch(e){throw this.setState("error"),this.isRunning=!1,e}}async stop(){if(this.isRunning)try{this.isRunning=!1,this.removeStdioHandlers(),this.setState("disconnected")}catch(e){throw e}}async sendMessage(e){try{let t=this.serializeMessage(e);process.stdout.write(`${t}
30
- `)}catch(t){throw t}}setupStdioHandlers(){process.stdin.on("data",this.handleStdinData.bind(this)),process.stdin.on("end",this.handleStdinEnd.bind(this)),process.stdin.on("error",this.handleStdinError.bind(this))}removeStdioHandlers(){process.stdin.removeListener("data",this.handleStdinData.bind(this)),process.stdin.removeListener("end",this.handleStdinEnd.bind(this)),process.stdin.removeListener("error",this.handleStdinError.bind(this))}async handleStdinData(e){try{if(this.messageBuffer+=e.toString(),this.messageBuffer.length>this.bufferSize){this.messageBuffer="";return}let t=this.messageBuffer.split(`
31
- `);this.messageBuffer=t.pop()||"";for(let r of t){let o=r.trim();o&&await this.processMessageLine(o)}}catch{}}async processMessageLine(e){try{let t=this.parseMessage(e);t&&await this.handleIncomingMessage(t)}catch{let r=`parse-error-${Date.now()}`;try{let n=JSON.parse(e.trim());n&&(typeof n.id=="string"||typeof n.id=="number")&&(r=n.id)}catch{}let o={jsonrpc:"2.0",error:{code:-32700,message:"\u89E3\u6790\u9519\u8BEF",data:{originalLine:e.substring(0,100)}},id:r};await this.sendMessage(o)}}handleStdinEnd(){this.stop().catch(e=>{})}handleStdinError(e){this.setState("error")}setupProcessHandlers(){let e=c(()=>{this.stop().finally(()=>{process.exit(0)})},"handleExit");process.on("SIGINT",e),process.on("SIGTERM",e),process.on("uncaughtException",t=>{this.setState("error")}),process.on("unhandledRejection",(t,r)=>{})}getStatus(){return{isRunning:this.isRunning,bufferSize:this.messageBuffer.length,encoding:this.encoding,connectionId:this.connectionId,state:this.state}}clearBuffer(){this.messageBuffer=""}};import Lo,{WebSocketServer as No}from"ws";var ne=class extends it{static{c(this,"MCPServiceManager")}services=new Map;configs={};tools=new Map;customMCPHandler;cacheManager;toolSyncManager;eventBus=b();toolCallLogger;retryTimers=new Map;failedServices=new Set;transportAdapters=new Map;messageHandler;isRunning=!1;config;constructor(e){super(),e&&this.isUnifiedServerConfig(e)?(this.config={name:"MCPServiceManager",enableLogging:!0,logLevel:"info",...e},this.configs=e.configs||{}):(this.config={name:"MCPServiceManager",enableLogging:!0,logLevel:"info"},this.configs=e||{});let r=process.env.NODE_ENV==="test"||process.env.VITEST==="true"?`/tmp/xiaozhi-test-${Date.now()}-${Math.random().toString(36).substring(2,11)}/xiaozhi.cache.json`:void 0;this.cacheManager=new F(r),this.customMCPHandler=new Z,this.toolSyncManager=new X(f);let o=f.getToolCallLogConfig(),n=f.getConfigDir();this.toolCallLogger=new re(o,n),this.setupEventListeners(),this.messageHandler=new oe(this)}setupEventListeners(){this.eventBus.onEvent("mcp:service:connected",async e=>{await this.handleServiceConnected(e)}),this.eventBus.onEvent("mcp:service:disconnected",async e=>{await this.handleServiceDisconnected(e)}),this.eventBus.onEvent("mcp:service:connection:failed",async e=>{await this.handleServiceConnectionFailed(e)}),this.eventBus.onEvent("tool-sync:server-tools-updated",async e=>{await this.handleServerToolsUpdated(e)}),this.eventBus.onEvent("tool-sync:general-config-updated",async e=>{await this.handleGeneralConfigUpdated(e)})}async handleServiceConnected(e){try{let t=this.services.get(e.serviceName);if(t){let r=t.getTools();this.toolSyncManager&&await this.toolSyncManager.syncToolsAfterConnection(e.serviceName,r),await this.refreshCustomMCPHandlerPublic()}}catch{}}async handleServiceDisconnected(e){try{await this.refreshToolsCache(),await this.refreshCustomMCPHandlerPublic()}catch{}}async handleServiceConnectionFailed(e){try{await this.refreshCustomMCPHandlerPublic()}catch{}}async handleServerToolsUpdated(e){try{let t=this.services.get(e.serviceName);if(t?.isConnected()){let r=t.getTools();this.toolSyncManager&&await this.toolSyncManager.syncToolsAfterConnection(e.serviceName,r),await this.refreshCustomMCPHandlerPublic()}}catch{}}async handleGeneralConfigUpdated(e){try{for(let[t,r]of this.services)if(r.isConnected()){let o=r.getTools();this.toolSyncManager&&await this.toolSyncManager.syncToolsAfterConnection(t,o)}await this.refreshCustomMCPHandlerPublic()}catch{}}async startAllServices(){try{this.customMCPHandler.initialize()}catch{}let e=Object.entries(this.configs);if(e.length===0)return;let t=e.map(async([a])=>{try{return await this.startService(a),{serviceName:a,success:!0,error:null}}catch(u){return{serviceName:a,success:!1,error:u instanceof Error?u.message:String(u)}}}),r=await Promise.allSettled(t),o=0,n=0,s=[];for(let a of r)a.status==="fulfilled"?a.value.success?o++:(n++,s.push(a.value.serviceName)):n++;s.length>0&&e.length,s.length>0&&this.scheduleFailedServicesRetry(s)}async startService(e){let t=this.configs[e];if(!t)throw new Error(`\u672A\u627E\u5230\u670D\u52A1\u914D\u7F6E: ${e}`);try{this.services.has(e)&&await this.stopService(e);let r=new se(t);await r.connect(),this.services.set(e,r),await this.refreshToolsCache();let o=r.getTools()}catch(r){throw this.services.delete(e),r}}async stopService(e){let t=this.services.get(e);if(t)try{await t.disconnect(),this.services.delete(e),await this.refreshToolsCache()}catch(r){throw r}}async refreshToolsCache(){this.tools.clear();for(let[e,t]of this.services)if(t.isConnected()){let r=t.getTools(),o=this.configs[e];o&&this.cacheManager.writeCacheEntry(e,r,o).then(()=>{}).catch(n=>{});for(let n of r){let s=`${e}__${n.name}`;this.tools.set(s,{serviceName:e,originalName:n.name,tool:n})}}await this.syncToolsConfigToFile()}getAllTools(){let e=[];for(let[r,o]of this.services)try{if(o.isConnected()){let n=o.getTools();for(let s of n)try{if(!f.isToolEnabled(r,s.name))continue;let u=`${r}__${s.name}`;e.push({name:u,description:s.description||"",inputSchema:s.inputSchema,serviceName:r,originalName:s.name})}catch{}}}catch{}let t=[];try{t=this.customMCPHandler.getTools()}catch{t=[]}for(let r of t)try{e.push({name:r.name,description:r.description||"",inputSchema:r.inputSchema,serviceName:this.getServiceNameForTool(r),originalName:r.name})}catch{}return e}getServiceNameForTool(e){return e.handler?.type==="mcp"&&e.handler.config?.serviceName||"customMCP"}getLogServerName(e){if(!e?.handler)return"custom";switch(e.handler.type){case"mcp":return e.handler.config?.serviceName||"customMCP";case"coze":return"coze";case"dify":return"dify";case"n8n":return"n8n";default:return"custom"}}getOriginalToolName(e,t,r){return t?t.handler?.type==="mcp"&&t.handler.config?.toolName||e:r?.originalName||e}async callTool(e,t){let r=Date.now(),o="unknown",n=e;try{let s;if(this.customMCPHandler.hasTool(e)){let a=this.customMCPHandler.getToolInfo(e);a&&(o=this.getLogServerName(a),n=this.getOriginalToolName(e,a)),a?.handler?.type==="mcp"?(s=await this.callMCPTool(e,a.handler.config,t),this.updateToolStatsSafe(e,a.handler.config.serviceName,a.handler.config.toolName,!0)):(s=await this.customMCPHandler.callTool(e,t),this.updateToolStatsSafe(e,"customMCP",e,!0))}else{let a=this.tools.get(e);if(!a)throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);o=a.serviceName,n=a.originalName;let u=this.services.get(a.serviceName);if(!u)throw new Error(`\u670D\u52A1 ${a.serviceName} \u4E0D\u53EF\u7528`);if(!u.isConnected())throw new Error(`\u670D\u52A1 ${a.serviceName} \u672A\u8FDE\u63A5`);s=await u.callTool(a.originalName,t||{}),this.updateToolStatsSafe(e,a.serviceName,a.originalName,!0)}return this.toolCallLogger.recordToolCall({toolName:n,serverName:o,arguments:t,result:s,success:s.isError!==!0,duration:Date.now()-r}),s}catch(s){if(this.toolCallLogger.recordToolCall({toolName:n,serverName:o,arguments:t,result:null,success:!1,duration:Date.now()-r,error:s instanceof Error?s.message:String(s)}),this.customMCPHandler.hasTool(e)){let a=this.customMCPHandler.getToolInfo(e);a?.handler?.type==="mcp"?this.updateToolStatsSafe(e,a.handler.config.serviceName,a.handler.config.toolName,!1):this.updateToolStatsSafe(e,"customMCP",e,!1)}else{let a=this.tools.get(e);a&&this.updateToolStatsSafe(e,a.serviceName,a.originalName,!1)}throw s}}async updateToolStats(e,t,r,o){try{let n=new Date().toISOString();o?(await this.updateCustomMCPToolStats(e,n),t!=="customMCP"&&await this.updateMCPServerToolStats(t,r,n)):(await this.updateCustomMCPToolLastUsedTime(e,n),t!=="customMCP"&&await this.updateMCPServerToolLastUsedTime(t,r,n))}catch(n){throw n}}async updateToolStatsSafe(e,t,r,o){try{await this.updateToolStats(e,t,r,o)}catch{let s=o?"\u7EDF\u8BA1\u4FE1\u606F":"\u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F"}}async updateCustomMCPToolStats(e,t){try{await f.updateToolUsageStatsWithLock(e,!0)}catch(r){throw r}}async updateCustomMCPToolLastUsedTime(e,t){try{await f.updateToolUsageStatsWithLock(e,!1)}catch(r){throw r}}async updateMCPServerToolStats(e,t,r){try{await f.updateMCPServerToolStatsWithLock(e,t,r,!0)}catch(o){throw o}}async updateMCPServerToolLastUsedTime(e,t,r){try{await f.updateMCPServerToolStatsWithLock(e,t,r,!1)}catch(o){throw o}}async callMCPTool(e,t,r){let{serviceName:o,toolName:n}=t,s=this.services.get(o);if(!s)throw new Error(`\u670D\u52A1 ${o} \u4E0D\u53EF\u7528`);if(!s.isConnected())throw new Error(`\u670D\u52A1 ${o} \u672A\u8FDE\u63A5`);try{return await s.callTool(n,r||{})}catch(a){throw a}}hasTool(e){return this.customMCPHandler.hasTool(e)?!0:this.tools.has(e)}async stopAllServices(){this.stopAllServiceRetries();for(let[e,t]of this.services)try{await t.disconnect()}catch{}try{this.customMCPHandler.cleanup()}catch{}try{f.clearAllStatsUpdateLocks()}catch{}this.services.clear(),this.tools.clear()}getStatus(){return this.getUnifiedStatus()}getStatsUpdateInfo(){try{let e=f.getStatsUpdateLocks();return{activeLocks:e,totalLocks:e.length}}catch{return{activeLocks:[],totalLocks:0}}}getService(e){return this.services.get(e)}getConnectedServices(){let e=[];for(let[t,r]of this.services)r.isConnected()&&e.push(t);return e}async refreshCustomMCPHandler(){try{await this.customMCPHandler.reinitialize()}catch(e){throw e}}async refreshCustomMCPHandlerPublic(){return this.refreshCustomMCPHandler()}getAllServices(){return new Map(this.services)}getCustomMCPHandler(){return this.customMCPHandler}hasCustomMCPTool(e){try{return this.customMCPHandler.hasTool(e)}catch{return!1}}getCustomMCPTools(){try{return this.customMCPHandler.getTools()}catch{return[]}}isModelScopeService(e){return e.url?be(e.url):!1}handleModelScopeAuth(e,t){if(e.headers?.Authorization)return;let o=f.getModelScopeApiKey();if(o){t.apiKey=o;return}let n=e.url||"\u672A\u77E5",s=e.name||"\u672A\u77E5";throw new Error(`ModelScope \u670D\u52A1 "${s}" \u9700\u8981\u8BA4\u8BC1\u4FE1\u606F\uFF0C\u4F46\u672A\u627E\u5230\u6709\u6548\u7684\u8BA4\u8BC1\u914D\u7F6E\u3002\u670D\u52A1 URL: ${n}\u8BF7\u9009\u62E9\u4EE5\u4E0B\u4EFB\u4E00\u65B9\u5F0F\u914D\u7F6E\u8BA4\u8BC1\uFF1A1. \u5728\u670D\u52A1\u914D\u7F6E\u4E2D\u6DFB\u52A0 headers.Authorization2. \u6216\u8005\u5728\u5168\u5C40\u914D\u7F6E\u4E2D\u8BBE\u7F6E modelscope.apiKey3. \u6216\u8005\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF MODELSCOPE_API_TOKEN\u83B7\u53D6 ModelScope API Key: https://modelscope.cn/my?myInfo=true`)}enhanceServiceConfig(e){let t={...e};try{return this.isModelScopeService(e)&&this.handleModelScopeAuth(e,t),t}catch(r){throw r}}addServiceConfig(e,t){let r,o;if(typeof e=="string"&&t)o=e,r=t;else if(typeof e=="object")o=e.name,r=e;else throw new Error("Invalid arguments for addServiceConfig");let n=this.enhanceServiceConfig(r);this.configs[o]=n}updateServiceConfig(e,t){let r=this.enhanceServiceConfig(t);this.configs[e]=r}removeServiceConfig(e){delete this.configs[e]}async syncToolsConfigToFile(){try{let e=f.getMcpServerConfig();for(let[t,r]of this.services){if(!r.isConnected())continue;let o=r.getTools();if(o.length===0)continue;let n=e[t]?.tools||{},s={};for(let m of o){let S=n[m.name];S?s[m.name]={...S,description:m.description||S.description||""}:s[m.name]={description:m.description||"",enable:!0}}let a=o.map(m=>m.name),g=Object.keys(n).filter(m=>!a.includes(m));if(g.length>0,this.hasToolsConfigChanged(n,s)){f.updateServerToolsConfig(t,s);let m=Object.keys(s).filter(T=>!n[T]),S=Object.keys(s).filter(T=>{let P=n[T],k=s[T];return P&&P.description!==k.description});m.length>0,S.length>0,g.length>0}}}catch{}}hasToolsConfigChanged(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!0;let n=o.filter(a=>!r.includes(a)),s=r.filter(a=>!o.includes(a));if(n.length>0||s.length>0)return!0;for(let a of r){let u=e[a],g=t[a];if(u.description!==g.description)return!0}return!1}scheduleFailedServicesRetry(e){if(e.length===0)return;let t=3e4;for(let r of e)this.failedServices.add(r),this.scheduleServiceRetry(r,t)}scheduleServiceRetry(e,t){let r=this.retryTimers.get(e);r&&(clearTimeout(r),this.retryTimers.delete(e));let o=setTimeout(async()=>{this.retryTimers.delete(e),await this.retryFailedService(e)},t);this.retryTimers.set(e,o)}async retryFailedService(e){if(this.failedServices.has(e))try{await this.startService(e),this.failedServices.delete(e);try{await this.refreshCustomMCPHandlerPublic()}catch{}}catch{let r=this.getRetryDelay(e),o=Math.min(r*2,3e5);this.scheduleServiceRetry(e,o)}}getRetryDelay(e){return 3e4+e.split("").reduce((r,o)=>r+o.charCodeAt(0),0)%6e4}stopServiceRetry(e){let t=this.retryTimers.get(e);t&&(clearTimeout(t),this.retryTimers.delete(e)),this.failedServices.delete(e)}stopAllServiceRetries(){for(let[e,t]of this.retryTimers)clearTimeout(t);this.retryTimers.clear(),this.failedServices.clear()}getFailedServices(){return Array.from(this.failedServices)}isServiceFailed(e){return this.failedServices.has(e)}getRetryStats(){return{failedServices:Array.from(this.failedServices),activeRetries:Array.from(this.retryTimers.keys()),totalFailed:this.failedServices.size,totalActiveRetries:this.retryTimers.size}}async registerTransport(e,t){if(this.transportAdapters.has(e))throw new Error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u5DF2\u5B58\u5728`);try{await t.initialize(),this.transportAdapters.set(e,t),this.emit("transportRegistered",{name:e,adapter:t})}catch(r){throw r}}async startTransports(){let e=[],t=[];for(let[r,o]of this.transportAdapters)try{await o.start(),e.push(r)}catch{t.push(r)}if(e.length===0&&t.length>0){let r=`\u6240\u6709\u4F20\u8F93\u9002\u914D\u5668\u542F\u52A8\u5931\u8D25\uFF0C\u5931\u8D25\u7684\u9002\u914D\u5668: ${t.join(", ")}`;throw new Error(r)}t.length>0}async stopTransports(){try{for(let[e,t]of this.transportAdapters)try{await t.stop()}catch{}}catch(e){throw e}}getTransportAdapters(){return new Map(this.transportAdapters)}getMessageHandler(){return this.messageHandler}async start(){if(this.isRunning)throw new Error("\u670D\u52A1\u5668\u5DF2\u5728\u8FD0\u884C");try{await this.startAllServices(),await this.startTransports(),this.isRunning=!0,this.emit("started")}catch(e){throw e}}async stop(){if(this.isRunning)try{await this.stopTransports(),await this.stopAllServices(),this.isRunning=!1,this.emit("stopped")}catch(e){throw e}}getAllConnections(){let e=[];for(let[t,r]of this.services)r.isConnected()&&e.push({id:`service-${t}`,name:t,state:"connected"});for(let[t,r]of this.transportAdapters)e.push({id:r.getConnectionId(),name:t,state:r.getState()});return e}getActiveConnectionCount(){return this.getAllConnections().filter(e=>e.state==="connected").length}getUnifiedStatus(){let e=this.getServiceManagerStatus();return{isRunning:this.isRunning,serviceStatus:e,transportCount:this.getTransportAdapters().size,activeConnections:this.getActiveConnectionCount(),config:this.config,services:e.services,totalTools:e.totalTools,availableTools:e.availableTools}}getServiceManagerStatus(){let e=0,t=[];try{e=this.customMCPHandler.getToolCount(),t=this.customMCPHandler.getToolNames()}catch{e=0,t=[]}let r=this.tools.size+e,n=[...Array.from(this.tools.keys()),...t],s={services:{},totalTools:r,availableTools:n};for(let[a,u]of this.services){let g=u.getStatus();s.services[a]={connected:g.connected,clientName:`xiaozhi-${a}-client`}}return e>0&&(s.services.customMCP={connected:!0,clientName:"xiaozhi-customMCP-handler"}),s}isServerRunning(){return this.isRunning}isUnifiedServerConfig(e){return e!==null&&typeof e=="object"&&"configs"in e}async routeMessage(e){let t=await this.messageHandler.handleMessage(e);return t===null?null:{jsonrpc:"2.0",method:"response",params:t,id:t.id}}async initialize(){await this.start()}getToolRegistry(){return this}getConnectionManager(){return this}};import{Client as Tt}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as at}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as ct}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as lt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{EventSource as ut}from"eventsource";typeof global<"u"&&!global.EventSource&&(global.EventSource=ut);function gt(i){switch(i.type){case"stdio":return mt(i);case"sse":return pt(i);case"streamable-http":return ht(i);default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}c(gt,"createTransport");function mt(i){if(!i.command)throw new Error("stdio transport \u9700\u8981 command \u914D\u7F6E");return new ct({command:i.command,args:i.args||[],env:i.env})}c(mt,"createStdioTransport");function pt(i){if(!i.url)throw new Error("SSE transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=dt(i);return new at(e,t)}c(pt,"createSSETransport");function ht(i){if(!i.url)throw new Error("StreamableHTTP transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=ft(i);return new lt(e,t)}c(ht,"createStreamableHTTPTransport");function dt(i){let e={};return i.apiKey?e.requestInit={headers:{Authorization:`Bearer ${i.apiKey}`,...i.headers}}:i.headers&&(e.requestInit={headers:i.headers}),e}c(dt,"createSSEOptions");function ft(i){let e={};return i.apiKey?e.requestInit={headers:{Authorization:`Bearer ${i.apiKey}`,...i.headers}}:i.headers&&(e.requestInit={headers:i.headers}),e}c(ft,"createStreamableHTTPOptions");function Ct(i){if(!i.name||typeof i.name!="string")throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(i.type&&!Object.values(O).includes(i.type))throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`);if(!i.type)throw new Error("\u4F20\u8F93\u7C7B\u578B\u672A\u8BBE\u7F6E\uFF0C\u8FD9\u5E94\u8BE5\u5728 inferTransportType \u4E2D\u5904\u7406");switch(i.type){case"stdio":if(!i.command)throw new Error("stdio \u7C7B\u578B\u9700\u8981 command \u5B57\u6BB5");break;case"sse":if(i.url===void 0||i.url===null)throw new Error(`${i.type} \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5`);break;case"streamable-http":if(i.url===void 0||i.url===null)throw new Error(`${i.type} \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5`);break;default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}c(Ct,"validateConfig");function vt(){return["stdio","sse","streamable-http"]}c(vt,"getSupportedTypes");var Ce={create:gt,validateConfig:Ct,getSupportedTypes:vt};var se=class{static{c(this,"MCPService")}config;client=null;transport=null;tools=new Map;connectionState="disconnected";connectionTimeout=null;initialized=!1;eventBus=b();constructor(e){this.config=Pe(e),this.validateConfig()}validateConfig(){Ce.validateConfig(this.config)}async connect(){if(this.connectionState==="connecting")throw new Error("\u8FDE\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u8FDE\u63A5\u5B8C\u6210");return this.cleanupConnection(),this.attemptConnection()}async attemptConnection(){return this.connectionState="connecting",new Promise((e,t)=>{this.connectionTimeout=setTimeout(()=>{let r=new Error(`\u8FDE\u63A5\u8D85\u65F6 (${this.config.timeout||1e4}ms)`);this.handleConnectionError(r),t(r)},this.config.timeout||1e4);try{this.client=new Tt({name:`xiaozhi-${this.config.name}-client`,version:"1.0.0"},{capabilities:{tools:{}}}),this.transport=Ce.create(this.config),this.client.connect(this.transport).then(async()=>{this.handleConnectionSuccess(),await this.refreshTools(),this.eventBus.emitEvent("mcp:service:connected",{serviceName:this.config.name,tools:this.getTools(),connectionTime:new Date}),e()}).catch(r=>{this.handleConnectionError(r),t(r)})}catch(r){this.handleConnectionError(r),t(r)}})}handleConnectionSuccess(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.connectionState="connected",this.initialized=!0}handleConnectionError(e){this.connectionState="disconnected",this.initialized=!1,this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.cleanupConnection(),this.eventBus.emitEvent("mcp:service:connection:failed",{serviceName:this.config.name,error:e,attempt:0})}cleanupConnection(){if(this.client){try{this.client.close().catch(()=>{})}catch{}this.client=null}this.transport=null,this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.initialized=!1}async refreshTools(){if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");try{let t=(await this.client.listTools()).tools||[];this.tools.clear();for(let r of t)this.tools.set(r.name,r)}catch(e){throw e}}async disconnect(){this.cleanupConnection(),this.connectionState="disconnected",this.eventBus.emitEvent("mcp:service:disconnected",{serviceName:this.config.name,reason:"\u624B\u52A8\u65AD\u5F00",disconnectionTime:new Date})}getTools(){return Array.from(this.tools.values())}async callTool(e,t){if(!this.client)throw new Error(`\u670D\u52A1 ${this.config.name} \u672A\u8FDE\u63A5`);if(!this.tools.has(e))throw new Error(`\u5DE5\u5177 ${e} \u5728\u670D\u52A1 ${this.config.name} \u4E2D\u4E0D\u5B58\u5728`);try{return await this.client.callTool({name:e,arguments:t||{}})}catch(r){throw r}}getConfig(){return this.config}getStatus(){return{name:this.config.name,connected:this.connectionState==="connected",initialized:this.initialized,transportType:this.config.type||"streamable-http",toolCount:this.tools.size,connectionState:this.connectionState}}isConnected(){return this.connectionState==="connected"&&this.initialized}};var De=R.env.XIAOZHI_CONFIG_DIR||R.cwd();l.initLogFile(De);l.enableFileLogging(!0);l.info(`\u65E5\u5FD7\u6587\u4EF6\u5DF2\u521D\u59CB\u5316: ${De}/xiaozhi.log`);async function St(){try{l.info("\u542F\u52A8 MCP \u670D\u52A1\u5668\u4EE3\u7406"),await Mt();let i=new ne;await i.start();let e=new W(i.getMessageHandler(),{name:"mcp-proxy",encoding:"utf8"});await i.registerTransport("stdio",e),l.info("MCP \u670D\u52A1\u5668\u4EE3\u7406\u542F\u52A8\u6210\u529F"),R.on("SIGINT",async()=>{l.info("\u6536\u5230 SIGINT \u4FE1\u53F7\uFF0C\u6B63\u5728\u5173\u95ED\u670D\u52A1\u7BA1\u7406\u5668"),await i.stop(),R.exit(0)}),R.on("SIGTERM",async()=>{l.info("\u6536\u5230 SIGTERM \u4FE1\u53F7\uFF0C\u6B63\u5728\u5173\u95ED\u670D\u52A1\u7BA1\u7406\u5668"),await i.stop(),R.exit(0)})}catch(i){l.error("\u542F\u52A8 MCP \u670D\u52A1\u5668\u4EE3\u7406\u5931\u8D25:",i),R.exit(1)}}c(St,"main");async function Mt(){try{if(l.info("\u52A0\u8F7D MCP \u670D\u52A1\u5668\u914D\u7F6E"),!f.configExists()){l.warn("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u5C06\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E");return}let i=f.getConfig();l.info(`\u5DF2\u52A0\u8F7D\u914D\u7F6E\uFF0C\u5305\u542B ${Object.keys(i.mcpServers||{}).length} \u4E2A MCP \u670D\u52A1\u5668`)}catch(i){throw l.error("\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25:",i),i}}c(Mt,"loadConfiguration");import.meta.url===`file://${R.argv[1]}`&&St().catch(i=>{l.error("MCP \u670D\u52A1\u5668\u4EE3\u7406\u542F\u52A8\u5931\u8D25:",i),R.exit(1)});export{St as main};
32
- //# sourceMappingURL=mcpServerProxy.js.map