xiaozhi-client 1.7.2 → 1.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
var ot=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var an=Object.getOwnPropertyNames;var cn=Object.prototype.hasOwnProperty;var c=(i,e)=>ot(i,"name",{value:e,configurable:!0});var m=(i,e)=>()=>(i&&(e=i(i=0)),e);var F=(i,e)=>{for(var t in e)ot(i,t,{get:e[t],enumerable:!0})},ln=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of an(e))!cn.call(i,o)&&o!==t&&ot(i,o,{get:()=>e[o],enumerable:!(r=sn(e,o))||r.enumerable});return i};var ee=i=>ln(ot({},"__esModule",{value:!0}),i);import*as N from"fs";import*as q from"path";import Ue from"chalk";import Re from"pino";import{z as gn}from"zod";function un(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}`}function Dr(i="info"){return new Ie(i)}function pn(){return nt||(nt=new Ie("info")),nt}function Nr(i){nt=i}var hn,Ie,nt,g,S=m(()=>{"use strict";hn=gn.enum(["fatal","error","warn","info","debug","trace"]);c(un,"formatDateTime");Ie=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=hn.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:Re.destination({dest:this.logFilePath,sync:!1,append:!0,mkdir:!0})}),e.length===0&&e.push({level:this.logLevel,stream:Re.destination({dest:"/dev/null"})}),Re({level:this.logLevel,timestamp:Re.stdTimeFunctions?.isoTime||(()=>`,"time":${Date.now()}`),formatters:{level:c((t,r)=>({level:r}),"level")},base:null,serializers:{err:Re.stdSerializers?.err||(t=>t)}},Re.multistream(e,{dedupe:!0}))}createOptimizedConsoleStream(){let e=new Map([[20,{name:"DEBUG",color:Ue.gray}],[30,{name:"INFO",color:Ue.blue}],[40,{name:"WARN",color:Ue.yellow}],[50,{name:"ERROR",color:Ue.red}],[60,{name:"FATAL",color:Ue.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):console&&typeof console.error=="function"&&console.error(e.trim())}catch{}}formatConsoleMessageOptimized(e,t){let r=un(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(l=>typeof l=="object"?JSON.stringify(l):String(l)).join(" ");s=`${s} ${a}`}return`[${r}] ${n} ${s}`}initLogFile(e){this.logFilePath=q.join(e,"xiaozhi.log"),this.rotateLogFileIfNeeded(),N.existsSync(this.logFilePath)||N.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?{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||!N.existsSync(this.logFilePath)))try{N.statSync(this.logFilePath).size>this.maxLogFileSize&&this.rotateLogFile()}catch{}}rotateLogFile(){if(this.logFilePath)try{let e=q.dirname(this.logFilePath),t=q.basename(this.logFilePath,".log");for(let o=this.maxLogFiles-1;o>=1;o--){let n=q.join(e,`${t}.${o}.log`),s=q.join(e,`${t}.${o+1}.log`);N.existsSync(n)&&(o===this.maxLogFiles-1?N.unlinkSync(n):N.renameSync(n,s))}let r=q.join(e,`${t}.1.log`);N.renameSync(this.logFilePath,r)}catch{}}cleanupOldLogs(){if(this.logFilePath)try{let e=q.dirname(this.logFilePath),t=q.basename(this.logFilePath,".log");for(let r=this.maxLogFiles+1;r<=this.maxLogFiles+10;r++){let o=q.join(e,`${t}.${r}.log`);N.existsSync(o)&&N.unlinkSync(o)}}catch{}}setLogFileOptions(e,t){this.maxLogFileSize=e,this.maxLogFiles=t}withTag(e){return this}close(){}},nt=null;c(Dr,"createLogger");c(pn,"getLogger");c(Nr,"setGlobalLogger");g=pn()});function dn(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")}function Kt(i,e){if(!e||typeof e!="object")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u5FC5\u987B\u662F\u4E00\u4E2A\u5BF9\u8C61`};try{switch(dn(e)){case"stdio":if(!e.command||typeof e.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(e.args))return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4`};if(e.env&&typeof e.env!="object")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61`};break;case"sse":if(e.type!=="sse")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 type \u5B57\u6BB5\u5FC5\u987B\u662F "sse"`};if(!e.url||typeof e.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`};break;case"streamable-http":if(!e.url||typeof e.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(e.type&&e.type!=="streamable-http")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 type \u5B57\u6BB5\u5982\u679C\u5B58\u5728\uFF0C\u5FC5\u987B\u662F "streamable-http"`};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"}`}}}var _r=m(()=>{"use strict";c(dn,"getMcpServerCommunicationType");c(Kt,"validateMcpServerConfig")});import{copyFileSync as mn,existsSync as st,readFileSync as fn,writeFileSync as Cn}from"fs";import{dirname as vn,resolve as Ce}from"path";import{fileURLToPath as Sn}from"url";import*as it from"comment-json";import Lr from"dayjs";import Zt from"json5";import*as zr from"json5-writer";var Hr,Yt,Qt,d,Y=m(()=>{"use strict";S();_r();Hr=vn(Sn(import.meta.url)),Yt={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},Qt=class i{static{c(this,"ConfigManager")}static instance;defaultConfigPath;config=null;currentConfigPath=null;json5Writer=null;statsUpdateLocks=new Map;statsUpdateLockTimeouts=new Map;STATS_UPDATE_TIMEOUT=5e3;constructor(){let e=[Ce(Hr,"templates","default","xiaozhi.config.json"),Ce(Hr,"..","templates","default","xiaozhi.config.json"),Ce(process.cwd(),"templates","default","xiaozhi.config.json")];this.defaultConfigPath=e.find(t=>st(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=Ce(e,r);if(st(o))return o}return Ce(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=Ce(e,r);if(st(o))return!0}return!1}initConfig(e="json"){if(!st(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=Ce(t,r);mn(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=fn(e,"utf8").replace(/^\uFEFF/,""),n;switch(t){case"json5":n=Zt.parse(o),this.json5Writer=zr.load(o);break;case"jsonc":n=it.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)){if(t.mcpEndpoint.length===0)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");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=Kt(r,o);if(!n.valid)throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A${n.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)){if(e.length===0)throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");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")}else if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\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`);if(r.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");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=Kt(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.getConfig();if(!t.mcpServers[e])throw new Error(`\u670D\u52A1 ${e} \u4E0D\u5B58\u5728`);let r={...t.mcpServers};delete r[e];let o={...t,mcpServers:r};this.saveConfig(o)}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)}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),g.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()):(console.warn("\u6CA1\u6709 json5Writer \u5B9E\u4F8B\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F"),o=Zt.stringify(e,null,2))}catch(n){console.warn("\u4F7F\u7528 json5-writer \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F:",n),o=Zt.stringify(e,null,2)}break;case"jsonc":try{o=it.stringify(e,null,2)}catch(n){console.warn("\u4F7F\u7528 comment-json \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON \u683C\u5F0F:",n),o=JSON.stringify(e,null,2)}break;default:o=JSON.stringify(e,null,2);break}Cn(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??Yt.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??Yt.heartbeatTimeout,reconnectInterval:t.reconnectInterval??Yt.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)]),g.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),g.debug(`CustomMCP \u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${o}`)}}catch(o){if(typeof t=="string"&&r){let n=e,s=t;g.error(`\u66F4\u65B0\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${n}/${s}): ${o instanceof Error?o.message:String(o)}`)}else{let n=e;g.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 g.warn(`CustomMCP \u5DE5\u5177\u7F3A\u5C11\u6709\u6548\u7684 name \u5B57\u6BB5: ${JSON.stringify(t)}`),!1;if(!t.description||typeof t.description!="string")return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 description \u5B57\u6BB5`),!1;if(!t.inputSchema||typeof t.inputSchema!="object")return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 inputSchema \u5B57\u6BB5`),!1;if(!t.handler||typeof t.handler!="object")return g.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 g.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;if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(t.name))return g.warn(`CustomMCP \u5DE5\u5177\u540D\u79F0 ${t.name} \u683C\u5F0F\u65E0\u6548\uFF0C\u5FC5\u987B\u4EE5\u5B57\u6BCD\u5F00\u5934\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF`),!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 g.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"?(g.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?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 Coze \u5904\u7406\u5668\u5FC5\u987B\u63D0\u4F9B workflow_id \u6216 bot_id`),!1):!0:(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u5E73\u53F0: ${t.platform}`),!1):(g.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 g.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 g.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)?(g.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"?(g.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"?(g.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"?(g.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)?(g.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?(g.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:(g.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):(g.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"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11 config \u5B57\u6BB5`),!1):!t.config.serviceName||typeof t.config.serviceName!="string"?(g.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"?(g.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 g.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),g.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),g.info(`\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),g.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),g.info(`\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),g.info(`\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),console.log("\u5DF2\u901A\u8FC7 WebSocket \u5E7F\u64AD\u914D\u7F6E\u66F4\u65B0"))}catch(t){console.warn("\u901A\u77E5 Web \u754C\u9762\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",t instanceof Error?t.message:String(t))}}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,l=s.lastUsedTime;o&&(s.usageCount=a+1),(!l||new Date(r)>new Date(l))&&(s.lastUsedTime=Lr(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 b=e;o=`${b}__${t}`,n=r,a=`${b}/${t}`}else o=e,n=t,s=r||!0,a=o;let l=this.getCustomMCPTools(),h=l.findIndex(b=>b.name===o);if(h===-1)return;let u=[...l],p=u[h];p.stats||(p.stats={});let C=p.stats.usageCount||0,T=p.stats.lastUsedTime;s&&(p.stats.usageCount=C+1),(!T||new Date(n)>new Date(T))&&(p.stats.lastUsedTime=Lr(n).format("YYYY-MM-DD HH:mm:ss")),await this.updateCustomMCPTools(u)}catch(o){if(typeof r=="string"){let n=e,s=t;g.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;g.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 g.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)),g.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),g.debug(`\u5DE5\u5177 ${e} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(o){throw g.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),g.debug(`MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(s){throw g.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&&g.info(`\u5DF2\u6E05\u7406 ${e} \u4E2A\u7EDF\u8BA1\u66F4\u65B0\u9501`)}getStatsUpdateLocks(){return Array.from(this.statsUpdateLocks.keys())}},d=Qt.getInstance()});var er,$e,Fe,y,tr,We=m(()=>{"use strict";er={NAME:"xiaozhi-mcp-service",DEFAULT_PORT:3e3,DEFAULT_WEB_UI_PORT:9999,PID_FILE:"xiaozhi.pid",LOG_FILE:"xiaozhi.log"},$e={FILE_NAMES:["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"],DEFAULT_FILE:"xiaozhi.config.default.json",DIR_ENV_VAR:"XIAOZHI_CONFIG_DIR"},Fe={WORK_DIR:".xiaozhi",TEMPLATES_DIR:"templates",LOGS_DIR:"logs"},y={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"},tr={PROCESS_STOP:3e3,SERVICE_START:1e4,NETWORK_REQUEST:5e3,FILE_OPERATION:2e3}});var yn,Tn,at,jr=m(()=>{"use strict";We();yn={[y.CONFIG_ERROR]:'\u8FD0\u884C "xiaozhi --help" \u67E5\u770B\u914D\u7F6E\u76F8\u5173\u547D\u4EE4',[y.SERVICE_ERROR]:'\u8FD0\u884C "xiaozhi status" \u68C0\u67E5\u670D\u52A1\u72B6\u6001',[y.VALIDATION_ERROR]:"\u68C0\u67E5\u8F93\u5165\u53C2\u6570\u662F\u5426\u6B63\u786E",[y.FILE_ERROR]:"\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u548C\u6743\u9650",[y.PROCESS_ERROR]:"\u68C0\u67E5\u8FDB\u7A0B\u72B6\u6001\u548C\u6743\u9650",[y.NETWORK_ERROR]:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C\u9632\u706B\u5899\u8BBE\u7F6E",[y.PERMISSION_ERROR]:"\u5C1D\u8BD5\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"},Tn={config_not_found:['\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6',"\u68C0\u67E5\u5F53\u524D\u76EE\u5F55\u662F\u5426\u4E3A\u9879\u76EE\u6839\u76EE\u5F55","\u8BBE\u7F6E XIAOZHI_CONFIG_DIR \u73AF\u5883\u53D8\u91CF\u6307\u5B9A\u914D\u7F6E\u76EE\u5F55"],service_port_occupied:["\u68C0\u67E5\u7AEF\u53E3\u662F\u5426\u88AB\u5176\u4ED6\u7A0B\u5E8F\u5360\u7528",'\u4F7F\u7528 "lsof -i :\u7AEF\u53E3\u53F7" \u67E5\u770B\u7AEF\u53E3\u4F7F\u7528\u60C5\u51B5',"\u66F4\u6539\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u7AEF\u53E3\u8BBE\u7F6E"],permission_denied:["\u68C0\u67E5\u6587\u4EF6\u548C\u76EE\u5F55\u6743\u9650","\u4F7F\u7528 sudo \u6216\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C","\u786E\u4FDD\u5F53\u524D\u7528\u6237\u6709\u8DB3\u591F\u7684\u6743\u9650"],service_start_failed:["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u662F\u5426\u6B63\u786E","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F","\u786E\u4FDD\u6240\u6709\u4F9D\u8D56\u670D\u52A1\u6B63\u5E38\u8FD0\u884C"]},at=class{static{c(this,"ERROR_MESSAGES")}static getHelpMessage(e){return yn[e]}static getSolutions(e){return Tn[e]||[]}static formatError(e,t){return`${t?`[${t}] `:""}${e.message}`}static getFriendlyMessage(e){return{[y.CONFIG_ERROR]:"\u914D\u7F6E\u6587\u4EF6\u76F8\u5173\u9519\u8BEF",[y.SERVICE_ERROR]:"\u670D\u52A1\u8FD0\u884C\u76F8\u5173\u9519\u8BEF",[y.VALIDATION_ERROR]:"\u8F93\u5165\u9A8C\u8BC1\u9519\u8BEF",[y.FILE_ERROR]:"\u6587\u4EF6\u64CD\u4F5C\u9519\u8BEF",[y.PROCESS_ERROR]:"\u8FDB\u7A0B\u7BA1\u7406\u9519\u8BEF",[y.NETWORK_ERROR]:"\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF",[y.PERMISSION_ERROR]:"\u6743\u9650\u4E0D\u8DB3\u9519\u8BEF"}[e]||"\u672A\u77E5\u9519\u8BEF"}static isRecoverable(e){return[y.NETWORK_ERROR,y.FILE_ERROR,y.SERVICE_ERROR].includes(e)}static getSeverity(e){return{[y.VALIDATION_ERROR]:"low",[y.FILE_ERROR]:"medium",[y.CONFIG_ERROR]:"medium",[y.NETWORK_ERROR]:"medium",[y.SERVICE_ERROR]:"high",[y.PROCESS_ERROR]:"high",[y.PERMISSION_ERROR]:"critical"}[e]||"medium"}}});var _,ve,I,E,v,le,te=m(()=>{"use strict";We();_=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)}},ve=class i extends _{static{c(this,"ConfigError")}constructor(e,t){super(e,y.CONFIG_ERROR,1,t),this.name="ConfigError"}static configNotFound(){return new i("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728",['\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6'])}static invalidFormat(e){return new i(`\u65E0\u6548\u7684\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F: ${e}`,["\u652F\u6301\u7684\u683C\u5F0F: json, json5, jsonc"])}},I=class i extends _{static{c(this,"ServiceError")}constructor(e,t){super(e,y.SERVICE_ERROR,1,t),this.name="ServiceError"}static alreadyRunning(e){return new i(`\u670D\u52A1\u5DF2\u7ECF\u5728\u8FD0\u884C (PID: ${e})`,['\u8BF7\u5148\u8FD0\u884C "xiaozhi stop" \u505C\u6B62\u73B0\u6709\u670D\u52A1','\u6216\u8005\u4F7F\u7528 "xiaozhi restart" \u91CD\u542F\u670D\u52A1'])}static autoRestarting(e){return new i(`\u68C0\u6D4B\u5230\u670D\u52A1\u5DF2\u5728\u8FD0\u884C (PID: ${e})\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u542F...`,["\u5982\u679C\u4E0D\u5E0C\u671B\u81EA\u52A8\u91CD\u542F\uFF0C\u8BF7\u4F7F\u7528 xiaozhi stop \u624B\u52A8\u505C\u6B62\u670D\u52A1"])}static notRunning(){return new i("\u670D\u52A1\u672A\u8FD0\u884C",['\u8BF7\u8FD0\u884C "xiaozhi start" \u542F\u52A8\u670D\u52A1'])}static startFailed(e){return new i(`\u670D\u52A1\u542F\u52A8\u5931\u8D25: ${e}`,["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u662F\u5426\u6B63\u786E","\u786E\u4FDD\u7AEF\u53E3\u672A\u88AB\u5360\u7528","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u4FE1\u606F"])}},E=class i extends _{static{c(this,"ValidationError")}constructor(e,t){super(`\u9A8C\u8BC1\u5931\u8D25: ${t} - ${e}`,y.VALIDATION_ERROR,1),this.name="ValidationError"}static invalidPort(e){return new i(`\u7AEF\u53E3\u53F7\u5FC5\u987B\u5728 1-65535 \u8303\u56F4\u5185\uFF0C\u5F53\u524D\u503C: ${e}`,"port")}static requiredField(e){return new i("\u5FC5\u586B\u5B57\u6BB5\u4E0D\u80FD\u4E3A\u7A7A",e)}},v=class i extends _{static{c(this,"FileError")}constructor(e,t,r){let o=t?`${e}: ${t}`:e;super(o,y.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"])}},le=class i extends _{static{c(this,"ProcessError")}constructor(e,t,r){let o=t?`${e} (PID: ${t})`:e;super(o,y.PROCESS_ERROR,1,r),this.name="ProcessError"}static killFailed(e){return new i("\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B",e,["\u8FDB\u7A0B\u53EF\u80FD\u5DF2\u7ECF\u505C\u6B62\u6216\u6743\u9650\u4E0D\u8DB3"])}static notFound(e){return new i("\u8FDB\u7A0B\u4E0D\u5B58\u5728",e)}}});import H from"chalk";var re,rr=m(()=>{"use strict";jr();te();re=class i{static{c(this,"ErrorHandler")}static handle(e){e instanceof _?i.handleCLIError(e):i.handleUnknownError(e),process.exit(1)}static handleCLIError(e){if(console.error(H.red(`\u274C \u9519\u8BEF: ${e.message}`)),process.env.DEBUG&&console.error(H.gray(`\u9519\u8BEF\u7801: ${e.code}`)),e.suggestions&&e.suggestions.length>0){console.log(H.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of e.suggestions)console.log(H.gray(` ${r}`))}let t=at.getHelpMessage(e.code);t&&console.log(H.blue(`\u2139\uFE0F ${t}`))}static handleUnknownError(e){console.error(H.red(`\u274C \u672A\u77E5\u9519\u8BEF: ${e.message}`)),process.env.DEBUG||process.env.NODE_ENV==="development"?(console.error(H.gray("\u5806\u6808\u4FE1\u606F:")),console.error(H.gray(e.stack))):console.log(H.yellow("\u{1F4A1} \u63D0\u793A: \u8BBE\u7F6E DEBUG=1 \u73AF\u5883\u53D8\u91CF\u67E5\u770B\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F"))}static async handleAsync(e,t){try{return await e()}catch(r){throw r instanceof _?r:r instanceof Error?new _(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new _(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static handleSync(e,t){try{return e()}catch(r){throw r instanceof _?r:r instanceof Error?new _(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new _(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static warn(e,t){if(console.warn(H.yellow(`\u26A0\uFE0F \u8B66\u544A: ${e}`)),t&&t.length>0){console.log(H.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of t)console.log(H.gray(` ${r}`))}}static info(e){console.log(H.blue(`\u2139\uFE0F ${e}`))}static success(e){console.log(H.green(`\u2705 ${e}`))}}});import k from"fs";import G from"path";var M,Ve=m(()=>{"use strict";te();M=class i{static{c(this,"FileUtils")}static exists(e){try{return k.existsSync(e)}catch{return!1}}static ensureDir(e){try{k.existsSync(e)||k.mkdirSync(e,{recursive:!0})}catch{throw new v("\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55",e)}}static readFile(e,t="utf8"){try{if(!i.exists(e))throw v.notFound(e);return k.readFileSync(e,t)}catch(r){throw r instanceof v?r:new v("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6",e)}}static writeFile(e,t,r){try{if(!r?.overwrite&&i.exists(e))throw v.alreadyExists(e);let o=G.dirname(e);i.ensureDir(o),k.writeFileSync(e,t,"utf8")}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u5199\u5165\u6587\u4EF6",e)}}static copyFile(e,t,r){try{if(!i.exists(e))throw v.notFound(e);if(!r?.overwrite&&i.exists(t))throw v.alreadyExists(t);let o=G.dirname(t);i.ensureDir(o),k.copyFileSync(e,t)}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u590D\u5236\u6587\u4EF6",e)}}static deleteFile(e){try{i.exists(e)&&k.unlinkSync(e)}catch{throw new v("\u65E0\u6CD5\u5220\u9664\u6587\u4EF6",e)}}static copyDirectory(e,t,r={}){try{if(!i.exists(e))throw v.notFound(e);i.ensureDir(t);let o=k.readdirSync(e);for(let n of o){if(r.exclude?.includes(n))continue;let s=G.join(e,n),a=G.join(t,n);k.statSync(s).isDirectory()?r.recursive!==!1&&i.copyDirectory(s,a,r):i.copyFile(s,a,{overwrite:r.overwrite})}}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u590D\u5236\u76EE\u5F55",e)}}static deleteDirectory(e,t={}){try{i.exists(e)&&k.rmSync(e,{recursive:t.recursive??!0,force:!0})}catch{throw new v("\u65E0\u6CD5\u5220\u9664\u76EE\u5F55",e)}}static getFileInfo(e){try{if(!i.exists(e))throw v.notFound(e);let t=k.statSync(e);return{size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory(),mtime:t.mtime,ctime:t.ctime}}catch(t){throw t instanceof v?t:new v("\u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F",e)}}static listDirectory(e,t={}){try{if(!i.exists(e))throw v.notFound(e);let r=k.readdirSync(e),o=[];for(let n of r){if(!t.includeHidden&&n.startsWith("."))continue;let s=G.join(e,n);if(o.push(s),t.recursive&&k.statSync(s).isDirectory()){let a=i.listDirectory(s,t);o=o.concat(a)}}return o}catch(r){throw r instanceof v?r:new v("\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 G.join(r,s)}static checkPermissions(e,t=k.constants.R_OK|k.constants.W_OK){try{return k.accessSync(e,t),!0}catch{return!1}}static getExtension(e){return G.extname(e).toLowerCase()}static getBaseName(e){return G.basename(e,G.extname(e))}static normalizePath(e){return G.normalize(e)}static resolvePath(e,t){return t?G.resolve(t,e):G.resolve(e)}}});var xe,or=m(()=>{"use strict";xe=class{static{c(this,"FormatUtils")}static formatUptime(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),o=Math.floor(r/60),n=Math.floor(o/24);return n>0?`${n}\u5929 ${o%24}\u5C0F\u65F6 ${r%60}\u5206\u949F`:o>0?`${o}\u5C0F\u65F6 ${r%60}\u5206\u949F`:r>0?`${r}\u5206\u949F ${t%60}\u79D2`:`${t}\u79D2`}static formatFileSize(e){let t=["B","KB","MB","GB","TB"],r=e,o=0;for(;r>=1024&&o<t.length-1;)r/=1024,o++;return`${r.toFixed(o===0?0:1)} ${t[o]}`}static formatTimestamp(e,t="full"){let r=new Date(e);switch(t){case"date":return r.toLocaleDateString("zh-CN");case"time":return r.toLocaleTimeString("zh-CN");default:return r.toLocaleString("zh-CN")}}static formatPid(e){return`PID: ${e}`}static formatPort(e){return`\u7AEF\u53E3: ${e}`}static formatUrl(e,t,r,o){let n=`${e}://${t}:${r}`;return o?`${n}${o}`:n}static formatConfigPair(e,t){return typeof t=="object"?`${e}: ${JSON.stringify(t,null,2)}`:`${e}: ${t}`}static formatError(e,t=!1){let r=`\u9519\u8BEF: ${e.message}`;return t&&e.stack&&(r+=`
|
|
3
|
+
`)}catch{this.safeWrite(t)}},"write")}}safeWrite(e){try{process.stderr&&typeof process.stderr.write=="function"?process.stderr.write(e):console&&typeof console.error=="function"&&console.error(e.trim())}catch{}}formatConsoleMessageOptimized(e,t){let r=un(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(l=>typeof l=="object"?JSON.stringify(l):String(l)).join(" ");s=`${s} ${a}`}return`[${r}] ${n} ${s}`}initLogFile(e){this.logFilePath=q.join(e,"xiaozhi.log"),this.rotateLogFileIfNeeded(),N.existsSync(this.logFilePath)||N.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?{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||!N.existsSync(this.logFilePath)))try{N.statSync(this.logFilePath).size>this.maxLogFileSize&&this.rotateLogFile()}catch{}}rotateLogFile(){if(this.logFilePath)try{let e=q.dirname(this.logFilePath),t=q.basename(this.logFilePath,".log");for(let o=this.maxLogFiles-1;o>=1;o--){let n=q.join(e,`${t}.${o}.log`),s=q.join(e,`${t}.${o+1}.log`);N.existsSync(n)&&(o===this.maxLogFiles-1?N.unlinkSync(n):N.renameSync(n,s))}let r=q.join(e,`${t}.1.log`);N.renameSync(this.logFilePath,r)}catch{}}cleanupOldLogs(){if(this.logFilePath)try{let e=q.dirname(this.logFilePath),t=q.basename(this.logFilePath,".log");for(let r=this.maxLogFiles+1;r<=this.maxLogFiles+10;r++){let o=q.join(e,`${t}.${r}.log`);N.existsSync(o)&&N.unlinkSync(o)}}catch{}}setLogFileOptions(e,t){this.maxLogFileSize=e,this.maxLogFiles=t}withTag(e){return this}close(){}},nt=null;c(Dr,"createLogger");c(pn,"getLogger");c(Nr,"setGlobalLogger");g=pn()});function dn(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")}function Kt(i,e){if(!e||typeof e!="object")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u5FC5\u987B\u662F\u4E00\u4E2A\u5BF9\u8C61`};try{switch(dn(e)){case"stdio":if(!e.command||typeof e.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(e.args))return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4`};if(e.env&&typeof e.env!="object")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61`};break;case"sse":if(e.type!=="sse")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 type \u5B57\u6BB5\u5FC5\u987B\u662F "sse"`};if(!e.url||typeof e.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`};break;case"streamable-http":if(!e.url||typeof e.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(e.type&&e.type!=="streamable-http")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 type \u5B57\u6BB5\u5982\u679C\u5B58\u5728\uFF0C\u5FC5\u987B\u662F "streamable-http"`};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"}`}}}var _r=m(()=>{"use strict";c(dn,"getMcpServerCommunicationType");c(Kt,"validateMcpServerConfig")});import{copyFileSync as mn,existsSync as st,readFileSync as fn,writeFileSync as Cn}from"fs";import{dirname as vn,resolve as Ce}from"path";import{fileURLToPath as Sn}from"url";import*as it from"comment-json";import Lr from"dayjs";import Zt from"json5";import*as zr from"json5-writer";var Hr,Yt,Qt,d,Y=m(()=>{"use strict";S();_r();Hr=vn(Sn(import.meta.url)),Yt={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},Qt=class i{static{c(this,"ConfigManager")}static instance;defaultConfigPath;config=null;currentConfigPath=null;json5Writer=null;statsUpdateLocks=new Map;statsUpdateLockTimeouts=new Map;STATS_UPDATE_TIMEOUT=5e3;constructor(){let e=[Ce(Hr,"templates","default","xiaozhi.config.json"),Ce(Hr,"..","templates","default","xiaozhi.config.json"),Ce(process.cwd(),"templates","default","xiaozhi.config.json")];this.defaultConfigPath=e.find(t=>st(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=Ce(e,r);if(st(o))return o}return Ce(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=Ce(e,r);if(st(o))return!0}return!1}initConfig(e="json"){if(!st(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=Ce(t,r);mn(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=fn(e,"utf8").replace(/^\uFEFF/,""),n;switch(t){case"json5":n=Zt.parse(o),this.json5Writer=zr.load(o);break;case"jsonc":n=it.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)){if(t.mcpEndpoint.length===0)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");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=Kt(r,o);if(!n.valid)throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A${n.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)){if(e.length===0)throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");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")}else if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\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`);if(r.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");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=Kt(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.getConfig();if(!t.mcpServers[e])throw new Error(`\u670D\u52A1 ${e} \u4E0D\u5B58\u5728`);let r={...t.mcpServers};delete r[e];let o={...t,mcpServers:r};this.saveConfig(o)}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)}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),g.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()):(console.warn("\u6CA1\u6709 json5Writer \u5B9E\u4F8B\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F"),o=Zt.stringify(e,null,2))}catch(n){console.warn("\u4F7F\u7528 json5-writer \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F:",n),o=Zt.stringify(e,null,2)}break;case"jsonc":try{o=it.stringify(e,null,2)}catch(n){console.warn("\u4F7F\u7528 comment-json \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON \u683C\u5F0F:",n),o=JSON.stringify(e,null,2)}break;default:o=JSON.stringify(e,null,2);break}Cn(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??Yt.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??Yt.heartbeatTimeout,reconnectInterval:t.reconnectInterval??Yt.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)]),g.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),g.debug(`CustomMCP \u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${o}`)}}catch(o){if(typeof t=="string"&&r){let n=e,s=t;g.error(`\u66F4\u65B0\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${n}/${s}): ${o instanceof Error?o.message:String(o)}`)}else{let n=e;g.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 g.warn(`CustomMCP \u5DE5\u5177\u7F3A\u5C11\u6709\u6548\u7684 name \u5B57\u6BB5: ${JSON.stringify(t)}`),!1;if(!t.description||typeof t.description!="string")return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 description \u5B57\u6BB5`),!1;if(!t.inputSchema||typeof t.inputSchema!="object")return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 inputSchema \u5B57\u6BB5`),!1;if(!t.handler||typeof t.handler!="object")return g.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 g.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 g.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"?(g.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?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 Coze \u5904\u7406\u5668\u5FC5\u987B\u63D0\u4F9B workflow_id \u6216 bot_id`),!1):!0:(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u5E73\u53F0: ${t.platform}`),!1):(g.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 g.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 g.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)?(g.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"?(g.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"?(g.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"?(g.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)?(g.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?(g.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:(g.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):(g.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"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11 config \u5B57\u6BB5`),!1):!t.config.serviceName||typeof t.config.serviceName!="string"?(g.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"?(g.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 g.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),g.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),g.info(`\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),g.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),g.info(`\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),g.info(`\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),console.log("\u5DF2\u901A\u8FC7 WebSocket \u5E7F\u64AD\u914D\u7F6E\u66F4\u65B0"))}catch(t){console.warn("\u901A\u77E5 Web \u754C\u9762\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",t instanceof Error?t.message:String(t))}}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,l=s.lastUsedTime;o&&(s.usageCount=a+1),(!l||new Date(r)>new Date(l))&&(s.lastUsedTime=Lr(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 b=e;o=`${b}__${t}`,n=r,a=`${b}/${t}`}else o=e,n=t,s=r||!0,a=o;let l=this.getCustomMCPTools(),h=l.findIndex(b=>b.name===o);if(h===-1)return;let u=[...l],p=u[h];p.stats||(p.stats={});let C=p.stats.usageCount||0,T=p.stats.lastUsedTime;s&&(p.stats.usageCount=C+1),(!T||new Date(n)>new Date(T))&&(p.stats.lastUsedTime=Lr(n).format("YYYY-MM-DD HH:mm:ss")),await this.updateCustomMCPTools(u)}catch(o){if(typeof r=="string"){let n=e,s=t;g.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;g.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 g.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)),g.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),g.debug(`\u5DE5\u5177 ${e} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(o){throw g.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),g.debug(`MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(s){throw g.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&&g.info(`\u5DF2\u6E05\u7406 ${e} \u4E2A\u7EDF\u8BA1\u66F4\u65B0\u9501`)}getStatsUpdateLocks(){return Array.from(this.statsUpdateLocks.keys())}},d=Qt.getInstance()});var er,$e,Fe,y,tr,We=m(()=>{"use strict";er={NAME:"xiaozhi-mcp-service",DEFAULT_PORT:3e3,DEFAULT_WEB_UI_PORT:9999,PID_FILE:"xiaozhi.pid",LOG_FILE:"xiaozhi.log"},$e={FILE_NAMES:["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"],DEFAULT_FILE:"xiaozhi.config.default.json",DIR_ENV_VAR:"XIAOZHI_CONFIG_DIR"},Fe={WORK_DIR:".xiaozhi",TEMPLATES_DIR:"templates",LOGS_DIR:"logs"},y={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"},tr={PROCESS_STOP:3e3,SERVICE_START:1e4,NETWORK_REQUEST:5e3,FILE_OPERATION:2e3}});var yn,Tn,at,jr=m(()=>{"use strict";We();yn={[y.CONFIG_ERROR]:'\u8FD0\u884C "xiaozhi --help" \u67E5\u770B\u914D\u7F6E\u76F8\u5173\u547D\u4EE4',[y.SERVICE_ERROR]:'\u8FD0\u884C "xiaozhi status" \u68C0\u67E5\u670D\u52A1\u72B6\u6001',[y.VALIDATION_ERROR]:"\u68C0\u67E5\u8F93\u5165\u53C2\u6570\u662F\u5426\u6B63\u786E",[y.FILE_ERROR]:"\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u548C\u6743\u9650",[y.PROCESS_ERROR]:"\u68C0\u67E5\u8FDB\u7A0B\u72B6\u6001\u548C\u6743\u9650",[y.NETWORK_ERROR]:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C\u9632\u706B\u5899\u8BBE\u7F6E",[y.PERMISSION_ERROR]:"\u5C1D\u8BD5\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"},Tn={config_not_found:['\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6',"\u68C0\u67E5\u5F53\u524D\u76EE\u5F55\u662F\u5426\u4E3A\u9879\u76EE\u6839\u76EE\u5F55","\u8BBE\u7F6E XIAOZHI_CONFIG_DIR \u73AF\u5883\u53D8\u91CF\u6307\u5B9A\u914D\u7F6E\u76EE\u5F55"],service_port_occupied:["\u68C0\u67E5\u7AEF\u53E3\u662F\u5426\u88AB\u5176\u4ED6\u7A0B\u5E8F\u5360\u7528",'\u4F7F\u7528 "lsof -i :\u7AEF\u53E3\u53F7" \u67E5\u770B\u7AEF\u53E3\u4F7F\u7528\u60C5\u51B5',"\u66F4\u6539\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u7AEF\u53E3\u8BBE\u7F6E"],permission_denied:["\u68C0\u67E5\u6587\u4EF6\u548C\u76EE\u5F55\u6743\u9650","\u4F7F\u7528 sudo \u6216\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C","\u786E\u4FDD\u5F53\u524D\u7528\u6237\u6709\u8DB3\u591F\u7684\u6743\u9650"],service_start_failed:["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u662F\u5426\u6B63\u786E","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F","\u786E\u4FDD\u6240\u6709\u4F9D\u8D56\u670D\u52A1\u6B63\u5E38\u8FD0\u884C"]},at=class{static{c(this,"ERROR_MESSAGES")}static getHelpMessage(e){return yn[e]}static getSolutions(e){return Tn[e]||[]}static formatError(e,t){return`${t?`[${t}] `:""}${e.message}`}static getFriendlyMessage(e){return{[y.CONFIG_ERROR]:"\u914D\u7F6E\u6587\u4EF6\u76F8\u5173\u9519\u8BEF",[y.SERVICE_ERROR]:"\u670D\u52A1\u8FD0\u884C\u76F8\u5173\u9519\u8BEF",[y.VALIDATION_ERROR]:"\u8F93\u5165\u9A8C\u8BC1\u9519\u8BEF",[y.FILE_ERROR]:"\u6587\u4EF6\u64CD\u4F5C\u9519\u8BEF",[y.PROCESS_ERROR]:"\u8FDB\u7A0B\u7BA1\u7406\u9519\u8BEF",[y.NETWORK_ERROR]:"\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF",[y.PERMISSION_ERROR]:"\u6743\u9650\u4E0D\u8DB3\u9519\u8BEF"}[e]||"\u672A\u77E5\u9519\u8BEF"}static isRecoverable(e){return[y.NETWORK_ERROR,y.FILE_ERROR,y.SERVICE_ERROR].includes(e)}static getSeverity(e){return{[y.VALIDATION_ERROR]:"low",[y.FILE_ERROR]:"medium",[y.CONFIG_ERROR]:"medium",[y.NETWORK_ERROR]:"medium",[y.SERVICE_ERROR]:"high",[y.PROCESS_ERROR]:"high",[y.PERMISSION_ERROR]:"critical"}[e]||"medium"}}});var _,ve,I,E,v,le,te=m(()=>{"use strict";We();_=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)}},ve=class i extends _{static{c(this,"ConfigError")}constructor(e,t){super(e,y.CONFIG_ERROR,1,t),this.name="ConfigError"}static configNotFound(){return new i("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728",['\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6'])}static invalidFormat(e){return new i(`\u65E0\u6548\u7684\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F: ${e}`,["\u652F\u6301\u7684\u683C\u5F0F: json, json5, jsonc"])}},I=class i extends _{static{c(this,"ServiceError")}constructor(e,t){super(e,y.SERVICE_ERROR,1,t),this.name="ServiceError"}static alreadyRunning(e){return new i(`\u670D\u52A1\u5DF2\u7ECF\u5728\u8FD0\u884C (PID: ${e})`,['\u8BF7\u5148\u8FD0\u884C "xiaozhi stop" \u505C\u6B62\u73B0\u6709\u670D\u52A1','\u6216\u8005\u4F7F\u7528 "xiaozhi restart" \u91CD\u542F\u670D\u52A1'])}static autoRestarting(e){return new i(`\u68C0\u6D4B\u5230\u670D\u52A1\u5DF2\u5728\u8FD0\u884C (PID: ${e})\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u542F...`,["\u5982\u679C\u4E0D\u5E0C\u671B\u81EA\u52A8\u91CD\u542F\uFF0C\u8BF7\u4F7F\u7528 xiaozhi stop \u624B\u52A8\u505C\u6B62\u670D\u52A1"])}static notRunning(){return new i("\u670D\u52A1\u672A\u8FD0\u884C",['\u8BF7\u8FD0\u884C "xiaozhi start" \u542F\u52A8\u670D\u52A1'])}static startFailed(e){return new i(`\u670D\u52A1\u542F\u52A8\u5931\u8D25: ${e}`,["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u662F\u5426\u6B63\u786E","\u786E\u4FDD\u7AEF\u53E3\u672A\u88AB\u5360\u7528","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u4FE1\u606F"])}},E=class i extends _{static{c(this,"ValidationError")}constructor(e,t){super(`\u9A8C\u8BC1\u5931\u8D25: ${t} - ${e}`,y.VALIDATION_ERROR,1),this.name="ValidationError"}static invalidPort(e){return new i(`\u7AEF\u53E3\u53F7\u5FC5\u987B\u5728 1-65535 \u8303\u56F4\u5185\uFF0C\u5F53\u524D\u503C: ${e}`,"port")}static requiredField(e){return new i("\u5FC5\u586B\u5B57\u6BB5\u4E0D\u80FD\u4E3A\u7A7A",e)}},v=class i extends _{static{c(this,"FileError")}constructor(e,t,r){let o=t?`${e}: ${t}`:e;super(o,y.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"])}},le=class i extends _{static{c(this,"ProcessError")}constructor(e,t,r){let o=t?`${e} (PID: ${t})`:e;super(o,y.PROCESS_ERROR,1,r),this.name="ProcessError"}static killFailed(e){return new i("\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B",e,["\u8FDB\u7A0B\u53EF\u80FD\u5DF2\u7ECF\u505C\u6B62\u6216\u6743\u9650\u4E0D\u8DB3"])}static notFound(e){return new i("\u8FDB\u7A0B\u4E0D\u5B58\u5728",e)}}});import H from"chalk";var re,rr=m(()=>{"use strict";jr();te();re=class i{static{c(this,"ErrorHandler")}static handle(e){e instanceof _?i.handleCLIError(e):i.handleUnknownError(e),process.exit(1)}static handleCLIError(e){if(console.error(H.red(`\u274C \u9519\u8BEF: ${e.message}`)),process.env.DEBUG&&console.error(H.gray(`\u9519\u8BEF\u7801: ${e.code}`)),e.suggestions&&e.suggestions.length>0){console.log(H.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of e.suggestions)console.log(H.gray(` ${r}`))}let t=at.getHelpMessage(e.code);t&&console.log(H.blue(`\u2139\uFE0F ${t}`))}static handleUnknownError(e){console.error(H.red(`\u274C \u672A\u77E5\u9519\u8BEF: ${e.message}`)),process.env.DEBUG||process.env.NODE_ENV==="development"?(console.error(H.gray("\u5806\u6808\u4FE1\u606F:")),console.error(H.gray(e.stack))):console.log(H.yellow("\u{1F4A1} \u63D0\u793A: \u8BBE\u7F6E DEBUG=1 \u73AF\u5883\u53D8\u91CF\u67E5\u770B\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F"))}static async handleAsync(e,t){try{return await e()}catch(r){throw r instanceof _?r:r instanceof Error?new _(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new _(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static handleSync(e,t){try{return e()}catch(r){throw r instanceof _?r:r instanceof Error?new _(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new _(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static warn(e,t){if(console.warn(H.yellow(`\u26A0\uFE0F \u8B66\u544A: ${e}`)),t&&t.length>0){console.log(H.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of t)console.log(H.gray(` ${r}`))}}static info(e){console.log(H.blue(`\u2139\uFE0F ${e}`))}static success(e){console.log(H.green(`\u2705 ${e}`))}}});import k from"fs";import G from"path";var M,Ve=m(()=>{"use strict";te();M=class i{static{c(this,"FileUtils")}static exists(e){try{return k.existsSync(e)}catch{return!1}}static ensureDir(e){try{k.existsSync(e)||k.mkdirSync(e,{recursive:!0})}catch{throw new v("\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55",e)}}static readFile(e,t="utf8"){try{if(!i.exists(e))throw v.notFound(e);return k.readFileSync(e,t)}catch(r){throw r instanceof v?r:new v("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6",e)}}static writeFile(e,t,r){try{if(!r?.overwrite&&i.exists(e))throw v.alreadyExists(e);let o=G.dirname(e);i.ensureDir(o),k.writeFileSync(e,t,"utf8")}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u5199\u5165\u6587\u4EF6",e)}}static copyFile(e,t,r){try{if(!i.exists(e))throw v.notFound(e);if(!r?.overwrite&&i.exists(t))throw v.alreadyExists(t);let o=G.dirname(t);i.ensureDir(o),k.copyFileSync(e,t)}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u590D\u5236\u6587\u4EF6",e)}}static deleteFile(e){try{i.exists(e)&&k.unlinkSync(e)}catch{throw new v("\u65E0\u6CD5\u5220\u9664\u6587\u4EF6",e)}}static copyDirectory(e,t,r={}){try{if(!i.exists(e))throw v.notFound(e);i.ensureDir(t);let o=k.readdirSync(e);for(let n of o){if(r.exclude?.includes(n))continue;let s=G.join(e,n),a=G.join(t,n);k.statSync(s).isDirectory()?r.recursive!==!1&&i.copyDirectory(s,a,r):i.copyFile(s,a,{overwrite:r.overwrite})}}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u590D\u5236\u76EE\u5F55",e)}}static deleteDirectory(e,t={}){try{i.exists(e)&&k.rmSync(e,{recursive:t.recursive??!0,force:!0})}catch{throw new v("\u65E0\u6CD5\u5220\u9664\u76EE\u5F55",e)}}static getFileInfo(e){try{if(!i.exists(e))throw v.notFound(e);let t=k.statSync(e);return{size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory(),mtime:t.mtime,ctime:t.ctime}}catch(t){throw t instanceof v?t:new v("\u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F",e)}}static listDirectory(e,t={}){try{if(!i.exists(e))throw v.notFound(e);let r=k.readdirSync(e),o=[];for(let n of r){if(!t.includeHidden&&n.startsWith("."))continue;let s=G.join(e,n);if(o.push(s),t.recursive&&k.statSync(s).isDirectory()){let a=i.listDirectory(s,t);o=o.concat(a)}}return o}catch(r){throw r instanceof v?r:new v("\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 G.join(r,s)}static checkPermissions(e,t=k.constants.R_OK|k.constants.W_OK){try{return k.accessSync(e,t),!0}catch{return!1}}static getExtension(e){return G.extname(e).toLowerCase()}static getBaseName(e){return G.basename(e,G.extname(e))}static normalizePath(e){return G.normalize(e)}static resolvePath(e,t){return t?G.resolve(t,e):G.resolve(e)}}});var xe,or=m(()=>{"use strict";xe=class{static{c(this,"FormatUtils")}static formatUptime(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),o=Math.floor(r/60),n=Math.floor(o/24);return n>0?`${n}\u5929 ${o%24}\u5C0F\u65F6 ${r%60}\u5206\u949F`:o>0?`${o}\u5C0F\u65F6 ${r%60}\u5206\u949F`:r>0?`${r}\u5206\u949F ${t%60}\u79D2`:`${t}\u79D2`}static formatFileSize(e){let t=["B","KB","MB","GB","TB"],r=e,o=0;for(;r>=1024&&o<t.length-1;)r/=1024,o++;return`${r.toFixed(o===0?0:1)} ${t[o]}`}static formatTimestamp(e,t="full"){let r=new Date(e);switch(t){case"date":return r.toLocaleDateString("zh-CN");case"time":return r.toLocaleTimeString("zh-CN");default:return r.toLocaleString("zh-CN")}}static formatPid(e){return`PID: ${e}`}static formatPort(e){return`\u7AEF\u53E3: ${e}`}static formatUrl(e,t,r,o){let n=`${e}://${t}:${r}`;return o?`${n}${o}`:n}static formatConfigPair(e,t){return typeof t=="object"?`${e}: ${JSON.stringify(t,null,2)}`:`${e}: ${t}`}static formatError(e,t=!1){let r=`\u9519\u8BEF: ${e.message}`;return t&&e.stack&&(r+=`
|
|
4
4
|
\u5806\u6808\u4FE1\u606F:
|
|
5
5
|
${e.stack}`),r}static formatList(e,t="\u2022"){return e.map(r=>`${t} ${r}`).join(`
|
|
6
6
|
`)}static formatTable(e){if(e.length===0)return"";let t=Object.keys(e[0]),r=t.map(a=>Math.max(a.length,...e.map(l=>String(l[a]).length))),o=t.map((a,l)=>a.padEnd(r[l])).join(" | "),n=r.map(a=>"-".repeat(a)).join("-|-"),s=e.map(a=>t.map((l,h)=>String(a[l]).padEnd(r[h])).join(" | "));return[o,n,...s].join(`
|
|
@@ -35,7 +35,7 @@ data: /messages?sessionId=${o}
|
|
|
35
35
|
2. \u7CFB\u7EDF\u4F1A\u81EA\u52A8\u8FD4\u56DE\u5DF2\u5B8C\u6210\u7684\u4EFB\u52A1\u7ED3\u679C
|
|
36
36
|
3. \u5982\u679C\u957F\u65F6\u95F4\u672A\u5B8C\u6210\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458`}var Je,ro=m(()=>{"use strict";Je=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}}};c(eo,"createTimeoutResponse");c(bn,"getToolSpecificTimeoutMessage");c(to,"getDefaultTimeoutMessage")});import{createHash as Rn}from"crypto";import{existsSync as Xe,mkdirSync as In,readFileSync as oo,renameSync as $n,writeFileSync as no}from"fs";import{dirname as xn,resolve as so}from"path";import On from"dayjs";var ge,Ct=m(()=>{"use strict";S();dt();ge=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=g,this.cachePath=e||this.getCacheFilePath(),this.startCleanupTimer()}formatTimestamp(){return On().format("YYYY-MM-DD HH:mm:ss")}getCacheFilePath(){try{let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return so(e,"xiaozhi.cache.json")}catch{let t=process.env.XIAOZHI_CONFIG_DIR||"/tmp";return so(t,"xiaozhi.cache.json")}}async ensureCacheFile(){try{if(!Xe(this.cachePath)){let e=xn(this.cachePath);Xe(e)||(In(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.info(`[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(!Xe(this.cachePath))return await this.createInitialCache();let e=oo(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{no(r,t,"utf8"),$n(r,e)}catch(o){try{Xe(r)&&no(r,"","utf8")}catch{}throw o}}generateConfigHash(e){try{return Rn("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:Xe(this.cachePath)?oo(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(),l=de(e,t),h={result:r,timestamp:new Date().toISOString(),ttl:s,status:o,consumed:!1,taskId:n,retryCount:0};a.customMCPResults||(a.customMCPResults={}),a.customMCPResults[l]=h,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=de(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=de(e,t);if(!s.customMCPResults||!s.customMCPResults[a])return!1;let l=s.customMCPResults[a],h=l.status;return l.status=r,l.timestamp=new Date().toISOString(),o&&(l.result=o),n&&r==="failed"&&(l.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${n}`}]},l.consumed=!0),r==="completed"&&(l.consumed=!1),await this.saveExtendedCache(s),this.logger.debug(`[CacheManager] \u66F4\u65B0\u7F13\u5B58\u72B6\u6001: ${e} ${h} -> ${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=de(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=de(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)Se(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(u=>u.status==="pending").length,n=t.filter(u=>u.status==="completed").length,s=t.filter(u=>u.status==="failed").length,a=t.filter(u=>u.consumed).length,l=n>0?a/n*100:0,h=JSON.stringify(e.customMCPResults).length;return{totalEntries:r,pendingTasks:o,completedTasks:n,failedTasks:s,consumedEntries:a,cacheHitRate:l,lastCleanupTime:new Date().toISOString(),memoryUsage:h}}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 vt,io=m(()=>{"use strict";S();Y();Yr();Qr();dt();ro();Ct();vt=class{static{c(this,"CustomMCPHandler")}logger;tools=new Map;cacheManager;cacheLifecycleManager;taskStateManager;TIMEOUT=me.TIMEOUT;CACHE_TTL=me.CACHE_TTL;CLEANUP_INTERVAL=me.CLEANUP_INTERVAL;cleanupTimer;activeTasks=new Map;constructor(e){this.logger=g,this.cacheManager=e||new ge,this.cacheLifecycleManager=new mt(this.logger),this.taskStateManager=new ft(this.logger),this.startCleanupTimer(),this.cacheLifecycleManager.startAutoCleanup()}initialize(e){this.logger.info("[CustomMCP] \u521D\u59CB\u5316 CustomMCP \u5904\u7406\u5668...");try{let t=e||d.getCustomMCPTools();this.tools.clear();for(let r of t)this.tools.set(r.name,r),this.logger.info(`[CustomMCP] \u5DF2\u52A0\u8F7D\u5DE5\u5177: ${r.name} (${r.handler.type})`);this.logger.info(`[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: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){let o=this.tools.get(e);if(!o)throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);this.logger.info(`[CustomMCP] \u8C03\u7528\u5DE5\u5177: ${e}`,{handler:o.handler.type,arguments:t});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 Je){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}`),eo(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){throw await this.markTaskAsFailed(o,n),n}}async createTimeoutPromise(e,t){return new Promise((r,o)=>{setTimeout(()=>{o(new Je(`\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&&!ke(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":return this.logger.error(`MCP \u7C7B\u578B\u5DE5\u5177 ${e.name} \u4E0D\u5E94\u8BE5\u7531 CustomMCPHandler \u5904\u7406`),{content:[{type:"text",text:"\u5185\u90E8\u9519\u8BEF\uFF1AMCP \u7C7B\u578B\u5DE5\u5177\u8DEF\u7531\u9519\u8BEF"}],isError:!0};default:throw new Error(`\u4E0D\u652F\u6301\u7684\u5904\u7406\u5668\u7C7B\u578B: ${e.handler.type}`)}}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=d.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,l={"Content-Type":"application/json",Authorization:`Bearer ${n}`,...e.headers};this.logger.debug(`[CustomMCP] \u53D1\u9001 Coze \u8BF7\u6C42\u5230: ${s}`,{headers:{...l},body:t});let h=new AbortController,u=setTimeout(()=>h.abort(),a);try{let p=await fetch(s,{method:"POST",headers:l,body:JSON.stringify(t)});if(clearTimeout(u),!p.ok){let T=await p.text();throw new Error(`Coze API \u8BF7\u6C42\u5931\u8D25 (${p.status}): ${T}`)}let C=await p.json();return this.logger.debug("[CustomMCP] Coze API \u54CD\u5E94:",C),C}catch(p){throw clearTimeout(u),p instanceof Error&&p.name==="AbortError"?new Error(`Coze API \u8BF7\u6C42\u8D85\u65F6 (${a}ms)`):p}}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"&&(t==="default"?r=e.default:e.default[t]&&typeof e.default[t]=="function"&&(r=e.default[t])),!r&&e[t]&&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((l,h)=>{setTimeout(()=>h(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 l=btoa(`${e.auth.username}:${e.auth.password}`);o.Authorization=`Basic ${l}`}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 l=new URLSearchParams;for(let[u,p]of Object.entries(t))p!=null&&l.append(u,String(p));let h=l.toString();h&&(s+=(s.includes("?")?"&":"?")+h)}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 l=0;l<=n;l++){try{this.logger.debug(`[CustomMCP] \u53D1\u9001 HTTP \u8BF7\u6C42 (\u5C1D\u8BD5 ${l+1}/${n+1}): ${e}`,{method:t.method,headers:t.headers});let h=new AbortController,u=setTimeout(()=>h.abort(),o),p=await fetch(e,{...t,signal:h.signal});if(clearTimeout(u),p.ok||l===n)return p;this.logger.warn(`[CustomMCP] HTTP \u8BF7\u6C42\u5931\u8D25 (${p.status}), \u5C06\u5728 ${s}ms \u540E\u91CD\u8BD5`),a=new Error(`HTTP \u8BF7\u6C42\u5931\u8D25: ${p.status} ${p.statusText}`)}catch(h){if(a=h instanceof Error?h:new Error(String(h)),h instanceof Error&&h.name==="AbortError"&&(a=new Error(`HTTP \u8BF7\u6C42\u8D85\u65F6 (${o}ms)`)),this.logger.warn(`[CustomMCP] HTTP \u8BF7\u6C42\u5F02\u5E38 (\u5C1D\u8BD5 ${l+1}/${n+1}):`,a.message),l===n)throw a}l<n&&await new Promise(h=>setTimeout(h,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;return r.response_mapping&&(s=this.extractResponseData(n,r.response_mapping)),{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 l of s)if(a&&typeof a=="object"&&l in a)a=a[l];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"),l=e.timeout||3e4,h=e.interpreter||"node",u,p=!1;try{if(e.script.includes(`
|
|
37
37
|
`)||e.script.length>200){let b=await n.mkdtemp(s.join(a.tmpdir(),"xiaozhi-script-")),B=this.getScriptExtension(h);u=s.join(b,`script${B}`),await n.writeFile(u,e.script,"utf8"),p=!0}else{u=e.script;try{await n.access(u)}catch{throw new Error(`\u811A\u672C\u6587\u4EF6\u4E0D\u5B58\u5728: ${u}`)}}let C={...process.env,...e.env,XIAOZHI_ARGUMENTS:JSON.stringify(t)},T=this.buildScriptCommand(h,u);return this.logger.debug(`[CustomMCP] \u6267\u884C\u811A\u672C\u547D\u4EE4: ${T.join(" ")}`),new Promise((b,B)=>{let Z=r(T[0],T.slice(1),{env:C,stdio:["pipe","pipe","pipe"]}),$="",tt="";Z.stdout?.on("data",ue=>{$+=ue.toString()}),Z.stderr?.on("data",ue=>{tt+=ue.toString()});let rt=setTimeout(()=>{Z.kill("SIGTERM"),B(new Error(`\u811A\u672C\u6267\u884C\u8D85\u65F6 (${l}ms)`))},l);Z.on("close",ue=>{clearTimeout(rt),ue===0?b($.trim()):B(new Error(`\u811A\u672C\u6267\u884C\u5931\u8D25 (\u9000\u51FA\u7801: ${ue}): ${tt.trim()}`))}),Z.on("error",ue=>{clearTimeout(rt),B(new Error(`\u811A\u672C\u6267\u884C\u9519\u8BEF: ${ue.message}`))}),t&&Object.keys(t).length>0&&(Z.stdin?.write(JSON.stringify(t)),Z.stdin?.end())})}finally{if(p&&u)try{await n.unlink(u),await n.rmdir(s.dirname(u))}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(l=>l.type==="text").map(l=>l.text).join(`
|
|
38
|
-
`);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];Se(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||{}))if(s.taskId===e){s.status="completed",s.result=t,s.timestamp=new Date().toISOString(),s.consumed=!1;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||{}))if(s.taskId===e){s.status="failed",s.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${t.message}`}]},s.timestamp=new Date().toISOString(),s.consumed=!0;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.info(`[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||{}))Se(n)&&(e.customMCPResults?.[o]&&delete e.customMCPResults[o],t=!0,r++,n.taskId&&this.activeTasks.delete(n.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 de(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]}}}});import{SSEClientTransport as ao}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as An}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as kn}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{EventSource as Dn}from"eventsource";function Nn(){return g}function _n(i){switch(Nn().info(`[TransportFactory] \u521B\u5EFA ${i.type} transport for ${i.name}`),i.type){case"stdio":return Ln(i);case"sse":return Hn(i);case"modelscope-sse":return zn(i);case"streamable-http":return jn(i);default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function Ln(i){if(!i.command)throw new Error("stdio transport \u9700\u8981 command \u914D\u7F6E");return new An({command:i.command,args:i.args||[],env:i.env})}function Hn(i){if(!i.url)throw new Error("SSE transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=Un(i);return new ao(e,t)}function zn(i){if(!i.url)throw new Error("ModelScope SSE transport \u9700\u8981 URL \u914D\u7F6E");if(!i.apiKey)throw new Error("ModelScope SSE transport \u9700\u8981 apiKey \u914D\u7F6E");let e=new URL(i.url),t=Fn(i);return new ao(e,t)}function jn(i){if(!i.url)throw new Error("StreamableHTTP transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=Wn(i);return new kn(e,t)}function Un(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function Fn(i){let e=i.apiKey;return i.customSSEOptions?i.customSSEOptions:{eventSourceInit:{fetch:c(async(t,r)=>{let o={...r?.headers,Authorization:`Bearer ${e}`};return fetch(t,{...r,headers:o})},"fetch")},requestInit:{headers:{Authorization:`Bearer ${e}`,...i.headers}}}}function Wn(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function Vn(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)throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B type \u5B57\u6BB5");switch(i.type){case"stdio":if(!i.command)throw new Error("stdio \u7C7B\u578B\u9700\u8981 command \u5B57\u6BB5");break;case"sse":case"streamable-http":if(!i.url)throw new Error(`${i.type} \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5`);break;case"modelscope-sse":if(!i.url)throw new Error("modelscope-sse \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5");if(!i.apiKey)throw new Error("modelscope-sse \u7C7B\u578B\u9700\u8981 apiKey \u5B57\u6BB5\u3002\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E modelscope.apiKey \u6216\u786E\u4FDD\u670D\u52A1\u914D\u7F6E\u5305\u542B apiKey");break;default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function Bn(){return["stdio","sse","modelscope-sse","streamable-http"]}var cr,co=m(()=>{"use strict";S();St();typeof global<"u"&&!global.EventSource&&(global.EventSource=Dn);c(Nn,"getLogger");c(_n,"createTransport");c(Ln,"createStdioTransport");c(Hn,"createSSETransport");c(zn,"createModelScopeSSETransport");c(jn,"createStreamableHTTPTransport");c(Un,"createSSEOptions");c(Fn,"createModelScopeSSEOptions");c(Wn,"createStreamableHTTPOptions");c(Vn,"validateConfig");c(Bn,"getSupportedTypes");cr={create:_n,validateConfig:Vn,getSupportedTypes:Bn}});import{Client as qn}from"@modelcontextprotocol/sdk/client/index.js";var Ke,yt,St=m(()=>{"use strict";S();co();Ke=(o=>(o.STDIO="stdio",o.SSE="sse",o.STREAMABLE_HTTP="streamable-http",o.MODELSCOPE_SSE="modelscope-sse",o))(Ke||{}),yt=class{static{c(this,"MCPService")}config;client=null;transport=null;tools=new Map;connectionState="disconnected";reconnectOptions;reconnectState;logger;connectionTimeout=null;initialized=!1;pingOptions;pingTimer=null;pingFailureCount=0;lastPingTime=null;isPinging=!1;constructor(e,t){this.config=e,this.logger=g,this.validateConfig(),this.reconnectOptions={enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:1e4,jitter:!0,...t?.reconnect,...e.reconnect},this.pingOptions={enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3,...e.ping},this.reconnectState={attempts:0,nextInterval:this.reconnectOptions.initialInterval,timer:null,lastError:null,isManualDisconnect:!1}}logWithTag(e,t,...r){let o=`[MCP-${this.config.name}] ${t}`;this.logger[e](o,...r)}validateConfig(){cr.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.reconnectState.isManualDisconnect=!1,this.attemptConnection()}async attemptConnection(){return this.connectionState="connecting",this.logWithTag("info",`\u6B63\u5728\u8FDE\u63A5 MCP \u670D\u52A1: ${this.config.name} (\u5C1D\u8BD5 ${this.reconnectState.attempts+1}/${this.reconnectOptions.maxAttempts})`),new Promise((e,t)=>{this.connectionTimeout=setTimeout(()=>{let r=new Error(`\u8FDE\u63A5\u8D85\u65F6 (${this.reconnectOptions.timeout}ms)`);this.handleConnectionError(r),t(r)},this.reconnectOptions.timeout);try{this.client=new qn({name:`xiaozhi-${this.config.name}-client`,version:"1.0.0"},{capabilities:{tools:{}}}),this.transport=cr.create(this.config),this.client.connect(this.transport).then(async()=>{this.handleConnectionSuccess(),await this.refreshTools(),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,this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.lastError=null,this.resetPingState(),this.logWithTag("info",`MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5\u5DF2\u5EFA\u7ACB`),this.startPingMonitoring()}handleConnectionError(e){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.reconnectState.lastError=e,this.logger.error(`MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5\u9519\u8BEF:`,e.message),this.cleanupConnection(),this.shouldReconnect()?this.scheduleReconnect():(this.connectionState="failed",this.logger.warn(`${this.config.name} \u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8FDE\u6B21\u6570 (${this.reconnectOptions.maxAttempts})\uFF0C\u505C\u6B62\u91CD\u8FDE`))}shouldReconnect(){return this.reconnectOptions.enabled&&this.reconnectState.attempts<this.reconnectOptions.maxAttempts&&!this.reconnectState.isManualDisconnect}scheduleReconnect(){this.connectionState="reconnecting",this.reconnectState.attempts++,this.calculateNextInterval(),this.logger.info(`${this.config.name} \u5C06\u5728 ${this.reconnectState.nextInterval}ms \u540E\u8FDB\u884C\u7B2C ${this.reconnectState.attempts} \u6B21\u91CD\u8FDE`),this.reconnectState.timer&&clearTimeout(this.reconnectState.timer),this.reconnectState.timer=setTimeout(async()=>{try{await this.attemptConnection()}catch{}},this.reconnectState.nextInterval)}calculateNextInterval(){let e;switch(this.reconnectOptions.backoffStrategy){case"fixed":e=this.reconnectOptions.initialInterval;break;case"linear":e=this.reconnectOptions.initialInterval+this.reconnectState.attempts*this.reconnectOptions.backoffMultiplier*1e3;break;case"exponential":e=this.reconnectOptions.initialInterval*this.reconnectOptions.backoffMultiplier**(this.reconnectState.attempts-1);break;default:e=this.reconnectOptions.initialInterval}if(e=Math.min(e,this.reconnectOptions.maxInterval),this.reconnectOptions.jitter){let t=e*.1,r=(Math.random()-.5)*2*t;e+=r}this.reconnectState.nextInterval=Math.max(e,1e3)}cleanupConnection(){if(this.stopPingMonitoring(),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}stopReconnect(){this.reconnectState.timer&&(clearTimeout(this.reconnectState.timer),this.reconnectState.timer=null)}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);this.logger.info(`${this.config.name} \u670D\u52A1\u52A0\u8F7D\u4E86 ${t.length} \u4E2A\u5DE5\u5177: ${t.map(r=>r.name).join(", ")}`)}catch(e){throw this.logger.error(`${this.config.name} \u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25:`,e instanceof Error?e.message:String(e)),e}}async disconnect(){this.logger.info(`\u4E3B\u52A8\u65AD\u5F00 MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5`),this.reconnectState.isManualDisconnect=!0,this.stopPingMonitoring(),this.stopReconnect(),this.cleanupConnection(),this.connectionState="disconnected"}async reconnect(){this.logger.info(`\u624B\u52A8\u91CD\u8FDE MCP \u670D\u52A1 ${this.config.name}`),this.stopReconnect(),this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.isManualDisconnect=!1,this.cleanupConnection(),await this.connect()}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`);this.logger.info(`\u8C03\u7528 ${this.config.name} \u670D\u52A1\u7684\u5DE5\u5177 ${e}\uFF0C\u53C2\u6570:`,JSON.stringify(t));try{let r=await this.client.callTool({name:e,arguments:t||{}});return this.logger.info(`\u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F\uFF0C\u7ED3\u679C:`,`${JSON.stringify(r).substring(0,500)}...`),r}catch(r){throw this.logger.error(`\u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,r instanceof Error?r.message:String(r)),r}}getConfig(){return this.config}getStatus(){return{name:this.config.name,connected:this.connectionState==="connected",initialized:this.initialized,transportType:this.config.type,toolCount:this.tools.size,lastError:this.reconnectState.lastError?.message,reconnectAttempts:this.reconnectState.attempts,connectionState:this.connectionState,pingEnabled:this.pingOptions.enabled,lastPingTime:this.lastPingTime||void 0,pingFailureCount:this.pingFailureCount,isPinging:this.isPinging}}isConnected(){return this.connectionState==="connected"&&this.initialized}enableReconnect(){this.reconnectOptions.enabled=!0,this.logger.info(`${this.config.name} \u81EA\u52A8\u91CD\u8FDE\u5DF2\u542F\u7528`)}disableReconnect(){this.reconnectOptions.enabled=!1,this.stopReconnect(),this.logger.info(`${this.config.name} \u81EA\u52A8\u91CD\u8FDE\u5DF2\u7981\u7528`)}updateReconnectOptions(e){this.reconnectOptions={...this.reconnectOptions,...e},this.logger.info(`${this.config.name} \u91CD\u8FDE\u914D\u7F6E\u5DF2\u66F4\u65B0`,e)}getReconnectOptions(){return{...this.reconnectOptions}}resetReconnectState(){this.stopReconnect(),this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.lastError=null,this.logger.info(`${this.config.name} \u91CD\u8FDE\u72B6\u6001\u5DF2\u91CD\u7F6E`)}startPingMonitoring(){!this.pingOptions.enabled||this.pingTimer||!this.isConnected()||(this.logger.info(`${this.config.name} \u542F\u52A8ping\u76D1\u63A7\uFF0C\u95F4\u9694: ${this.pingOptions.interval}ms`),setTimeout(()=>{this.isConnected()&&!this.pingTimer&&(this.pingTimer=setInterval(()=>{this.performPing()},this.pingOptions.interval))},this.pingOptions.startDelay))}stopPingMonitoring(){this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null,this.logger.debug(`${this.config.name} \u505C\u6B62ping\u76D1\u63A7`))}async performPing(){if(!this.client||this.isPinging||!this.isConnected())return;this.isPinging=!0;let e=performance.now();try{this.logger.debug(`${this.config.name} \u53D1\u9001ping\u8BF7\u6C42\uFF08\u901A\u8FC7listTools\u68C0\u6D4B\u8FDE\u63A5\uFF09`);let t=this.client.listTools(),r=new Promise((n,s)=>{setTimeout(()=>{s(new Error(`Ping\u8D85\u65F6 (${this.pingOptions.timeout}ms)`))},this.pingOptions.timeout)});await Promise.race([t,r]);let o=performance.now()-e;this.handlePingSuccess(o)}catch(t){let r=performance.now()-e;this.handlePingFailure(t,r)}finally{this.isPinging=!1}}handlePingSuccess(e){this.pingFailureCount=0,this.lastPingTime=new Date,this.logger.debug(`${this.config.name} ping\u6210\u529F\uFF0C\u5EF6\u8FDF: ${e.toFixed(2)}ms`)}handlePingFailure(e,t){if(this.pingFailureCount++,this.logger.warn(`${this.config.name} ping\u5931\u8D25 (${this.pingFailureCount}/${this.pingOptions.maxFailures})\uFF0C\u5EF6\u8FDF: ${t.toFixed(2)}ms\uFF0C\u9519\u8BEF: ${e.message}`),this.pingFailureCount>=this.pingOptions.maxFailures){this.logger.error(`${this.config.name} \u8FDE\u7EEDping\u5931\u8D25\u8FBE\u5230\u9608\u503C\uFF0C\u89E6\u53D1\u91CD\u8FDE\u673A\u5236`),this.stopPingMonitoring();let r=new Error(`Ping\u68C0\u6D4B\u5931\u8D25\uFF0C\u8FDE\u7EED\u5931\u8D25${this.pingFailureCount}\u6B21\uFF0C\u8FDE\u63A5\u53EF\u80FD\u5DF2\u65AD\u5F00`);this.handleConnectionError(r)}}resetPingState(){this.pingFailureCount=0,this.lastPingTime=null,this.isPinging=!1}enablePing(){this.pingOptions.enabled=!0,this.logger.info(`${this.config.name} ping\u76D1\u63A7\u5DF2\u542F\u7528`),this.isConnected()&&this.startPingMonitoring()}disablePing(){this.pingOptions.enabled=!1,this.stopPingMonitoring(),this.logger.info(`${this.config.name} ping\u76D1\u63A7\u5DF2\u7981\u7528`)}updatePingOptions(e){let t=this.pingOptions.enabled;this.pingOptions={...this.pingOptions,...e},this.logger.info(`${this.config.name} ping\u914D\u7F6E\u5DF2\u66F4\u65B0`,e),t!==this.pingOptions.enabled&&(this.pingOptions.enabled&&this.isConnected()?this.startPingMonitoring():this.pingOptions.enabled||this.stopPingMonitoring())}getPingOptions(){return{...this.pingOptions}}}});var Tt,lo=m(()=>{"use strict";S();Tt=class{static{c(this,"ToolSyncManager")}configManager;logger;syncLocks=new Map;constructor(e,t=g){this.configManager=e,this.logger=t.withTag("ToolSync")}async syncToolsAfterConnection(e,t){if(this.syncLocks.has(e)){this.logger.debug(`\u670D\u52A1 ${e} \u6B63\u5728\u540C\u6B65\u4E2D\uFF0C\u8DF3\u8FC7`);return}if(this.configManager.getCustomMCPConfig()){this.logger.debug("\u5DF2\u5B58\u5728 customMCP \u505C\u6B62\u540C\u6B65");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(l=>l.name)),a=o.filter(l=>!s.has(`${e}__${l.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}`,l=n.get(a),h=r[s.name];if(l&&h&&(!l.stats||!l.stats.usageCount&&!l.stats.lastUsedTime)){let u={};h.usageCount!==void 0&&(u.usageCount=h.usageCount),h.lastUsedTime&&(u.lastUsedTime=h.lastUsedTime),Object.keys(u).length>0&&(await this.updateCustomMCPToolStats(a,u),this.logger.debug(`\u5DF2\u540C\u6B65\u5DE5\u5177 ${a} \u7684\u7EDF\u8BA1\u4FE1\u606F: ${JSON.stringify(u)}`))}}}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}}}});var Ze,go,lr=m(()=>{"use strict";S();Y();io();Ct();St();lo();Ze=class{static{c(this,"MCPServiceManager")}services=new Map;configs={};logger;tools=new Map;customMCPHandler;cacheManager;toolSyncManager;constructor(e){this.logger=g,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 ge(r),this.customMCPHandler=new vt,this.toolSyncManager=new Tt(d,this.logger)}async startAllServices(){this.logger.info("[MCPManager] \u6B63\u5728\u542F\u52A8\u6240\u6709 MCP \u670D\u52A1...");try{this.customMCPHandler.initialize(),this.logger.info("[MCPManager] CustomMCP \u5904\u7406\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(t){this.logger.error("[MCPManager] CustomMCP \u5904\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",t)}let e=Object.entries(this.configs);if(e.length===0){this.logger.warn("[MCPManager] \u6CA1\u6709\u914D\u7F6E\u4EFB\u4F55 MCP \u670D\u52A1\uFF0C\u8BF7\u4F7F\u7528 addServiceConfig() \u6DFB\u52A0\u670D\u52A1\u914D\u7F6E");return}for(let[t]of e)await this.startService(t);this.logger.info("[MCPManager] \u6240\u6709 MCP \u670D\u52A1\u542F\u52A8\u5B8C\u6210")}async startService(e){this.logger.info(`[MCPManager] \u542F\u52A8 MCP \u670D\u52A1: ${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 yt(t);await r.connect(),this.services.set(e,r),await this.refreshToolsCache();let o=r.getTools();await this.toolSyncManager.syncToolsAfterConnection(e,o),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u542F\u52A8\u6210\u529F\uFF0C\u52A0\u8F7D\u4E86 ${o.length} \u4E2A\u5DE5\u5177:`,o.map(n=>n.name).join(", "))}catch(r){throw this.logger.error(`[MCPManager] \u542F\u52A8 ${e} \u670D\u52A1\u5931\u8D25:`,r.message),r}}async stopService(e){this.logger.info(`[MCPManager] \u505C\u6B62 MCP \u670D\u52A1: ${e}`);let t=this.services.get(e);if(!t){this.logger.warn(`[MCPManager] \u670D\u52A1 ${e} \u4E0D\u5B58\u5728\u6216\u672A\u542F\u52A8`);return}try{await t.disconnect(),this.services.delete(e),await this.refreshToolsCache(),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u5DF2\u505C\u6B62`)}catch(r){throw this.logger.error(`[MCPManager] \u505C\u6B62 ${e} \u670D\u52A1\u5931\u8D25:`,r.message),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(()=>{this.logger.debug(`[MCPManager] \u5DF2\u5C06 ${e} \u5DE5\u5177\u5217\u8868\u5199\u5165\u7F13\u5B58`)}).catch(n=>{this.logger.warn(`[MCPManager] \u5199\u5165\u7F13\u5B58\u5931\u8D25: ${e}, \u9519\u8BEF: ${n instanceof Error?n.message:String(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=[];if(d.getCustomMCPConfig()!==null){this.logger.info("[MCPManager] \u68C0\u6D4B\u5230\u65B0\u7248\u672C\u914D\u7F6E\uFF0C\u4F7F\u7528 customMCP \u5DE5\u5177\u5217\u8868");try{let r=this.customMCPHandler.getTools();for(let o of r)e.push({name:o.name,description:o.description||"",inputSchema:o.inputSchema,serviceName:this.getServiceNameForTool(o),originalName:o.name});this.logger.info(`[MCPManager] \u65B0\u7248\u672C\u914D\u7F6E\u8FD4\u56DE ${e.length} \u4E2A\u5DE5\u5177 (\u4EC5\u6765\u81EA customMCP.tools)`)}catch(r){this.logger.error("[MCPManager] \u83B7\u53D6 customMCP \u5DE5\u5177\u5931\u8D25:",r)}}else{this.logger.info("[MCPManager] \u68C0\u6D4B\u5230\u8001\u7248\u672C\u914D\u7F6E\uFF0C\u4F7F\u7528\u517C\u5BB9\u6A21\u5F0F\u5904\u7406");let r=new Set;try{let o=this.customMCPHandler.getTools();for(let n of o){let s=n.name;r.has(s)||(r.add(s),e.push({name:s,description:n.description||"",inputSchema:n.inputSchema,serviceName:"customMCP",originalName:n.name}))}o.length>0&&this.logger.info(`[MCPManager] \u6DFB\u52A0\u4E86 ${o.length} \u4E2A customMCP \u5DE5\u5177`)}catch(o){this.logger.error("[MCPManager] \u83B7\u53D6 CustomMCP \u5DE5\u5177\u5931\u8D25:",o)}for(let[o,n]of this.tools){if(r.has(o))continue;d.isToolEnabled(n.serviceName,n.originalName)&&(r.add(o),e.push({name:o,description:n.tool.description||"",inputSchema:n.tool.inputSchema,serviceName:n.serviceName,originalName:n.originalName}))}this.logger.info(`[MCPManager] \u8001\u7248\u672C\u914D\u7F6E\u8FD4\u56DE\u603B\u8BA1 ${e.length} \u4E2A\u5DE5\u5177 (customMCP \u4F18\u5148\uFF0C\u53BB\u91CD\u540E\u603B\u6570)`)}return e}getServiceNameForTool(e){return e.handler?.type==="mcp"?e.handler.config.serviceName:"customMCP"}async callTool(e,t){if(this.logger.info(`[MCPManager] \u8C03\u7528\u5DE5\u5177: ${e}\uFF0C\u53C2\u6570:`,t),this.customMCPHandler.hasTool(e)){let n=this.customMCPHandler.getToolInfo(e);if(n?.handler?.type==="mcp")try{let s=await this.callMCPTool(e,n.handler.config,t);return this.updateToolStats(e,n.handler.config.serviceName,n.handler.config.toolName,!0).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),s}catch(s){throw this.updateToolStatsForFailedCall(e,n.handler.config.serviceName,n.handler.config.toolName,s).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),s}try{let s=await this.customMCPHandler.callTool(e,t);return this.updateToolStats(e,"customMCP",e,!0).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),this.logger.info(`[MCPManager] CustomMCP \u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F`),s}catch(s){throw this.updateToolStatsForFailedCall(e,"customMCP",e,s).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),this.logger.error(`[MCPManager] CustomMCP \u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,s.message),s}}let r=this.tools.get(e);if(!r)throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);let o=this.services.get(r.serviceName);if(!o)throw new Error(`\u670D\u52A1 ${r.serviceName} \u4E0D\u53EF\u7528`);if(!o.isConnected())throw new Error(`\u670D\u52A1 ${r.serviceName} \u672A\u8FDE\u63A5`);try{let n=await o.callTool(r.originalName,t||{});return this.updateToolStats(e,r.serviceName,r.originalName,!0).catch(s=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,s)}),this.logger.info(`[MCPManager] \u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F\uFF0C\u7ED3\u679C:`,n),n}catch(n){throw this.updateToolStatsForFailedCall(e,r.serviceName,r.originalName,n).catch(s=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,s)}),this.logger.error(`[MCPManager] \u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,n.message),n}}async updateToolStats(e,t,r,o){try{if(!o)return;let n=new Date().toISOString();await this.updateCustomMCPToolStats(e,n),t!=="customMCP"&&await this.updateMCPServerToolStats(t,r,n),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u4FE1\u606F`)}catch(n){throw this.logger.error(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,n),n}}async updateToolStatsForFailedCall(e,t,r,o){try{let n=new Date().toISOString();await this.updateCustomMCPToolLastUsedTime(e,n),t!=="customMCP"&&await this.updateMCPServerToolLastUsedTime(t,r,n),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0\u5DE5\u5177 ${e} \u7684\u5931\u8D25\u8C03\u7528\u7EDF\u8BA1\u4FE1\u606F`)}catch(n){throw this.logger.error(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u8C03\u7528\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,n),n}}async updateCustomMCPToolStats(e,t){try{await d.updateToolUsageStatsWithLock(e,!0),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u4F7F\u7528\u7EDF\u8BA1`)}catch(r){throw this.logger.error(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u7EDF\u8BA1\u5931\u8D25:`,r),r}}async updateCustomMCPToolLastUsedTime(e,t){try{await d.updateToolUsageStatsWithLock(e,!1),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u6700\u540E\u4F7F\u7528\u65F6\u95F4`)}catch(r){throw this.logger.error(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u6700\u540E\u4F7F\u7528\u65F6\u95F4\u5931\u8D25:`,r),r}}async updateMCPServerToolStats(e,t,r){try{await d.updateMCPServerToolStatsWithLock(e,t,r,!0),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1`)}catch(o){throw this.logger.error(`[MCPManager] \u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u5931\u8D25:`,o),o}}async updateMCPServerToolLastUsedTime(e,t,r){try{await d.updateMCPServerToolStatsWithLock(e,t,r,!1),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u6700\u540E\u4F7F\u7528\u65F6\u95F4`)}catch(o){throw this.logger.error(`[MCPManager] \u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u6700\u540E\u4F7F\u7528\u65F6\u95F4\u5931\u8D25:`,o),o}}async callMCPTool(e,t,r){let{serviceName:o,toolName:n}=t;this.logger.info(`[MCPManager] \u8C03\u7528 MCP \u540C\u6B65\u5DE5\u5177 ${e} -> ${o}.${n}`);let 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{let a=await s.callTool(n,r||{});return this.logger.info(`[MCPManager] MCP \u540C\u6B65\u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F`),a}catch(a){throw this.logger.error(`[MCPManager] MCP \u540C\u6B65\u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,a.message),a}}hasTool(e){return this.customMCPHandler.hasTool(e)?!0:this.tools.has(e)}async stopAllServices(){this.logger.info("[MCPManager] \u6B63\u5728\u505C\u6B62\u6240\u6709 MCP \u670D\u52A1...");for(let[e,t]of this.services)try{await t.disconnect(),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u5DF2\u505C\u6B62`)}catch(r){this.logger.error(`[MCPManager] \u505C\u6B62 ${e} \u670D\u52A1\u5931\u8D25:`,r.message)}try{this.customMCPHandler.cleanup(),this.logger.info("[MCPManager] CustomMCP \u5904\u7406\u5668\u5DF2\u6E05\u7406")}catch(e){this.logger.error("[MCPManager] CustomMCP \u5904\u7406\u5668\u6E05\u7406\u5931\u8D25:",e)}try{d.clearAllStatsUpdateLocks(),this.logger.info("[MCPManager] \u7EDF\u8BA1\u66F4\u65B0\u9501\u5DF2\u6E05\u7406")}catch(e){this.logger.error("[MCPManager] \u6E05\u7406\u7EDF\u8BA1\u66F4\u65B0\u9501\u5931\u8D25:",e)}this.services.clear(),this.tools.clear(),this.logger.info("[MCPManager] \u6240\u6709 MCP \u670D\u52A1\u5DF2\u505C\u6B62")}getStatus(){let e=this.customMCPHandler.getToolCount(),t=this.tools.size+e,r=Array.from(this.tools.keys()),o=this.customMCPHandler.getToolNames(),n=[...r,...o],s={services:{},totalTools:t,availableTools:n};for(let[a,l]of this.services){let h=l.getStatus();s.services[a]={connected:h.connected,clientName:`xiaozhi-${a}-client`}}return e>0&&(s.services.customMCP={connected:!0,clientName:"xiaozhi-customMCP-handler"}),s}getStatsUpdateInfo(){try{let e=d.getStatsUpdateLocks();return{activeLocks:e,totalLocks:e.length}}catch(e){return this.logger.warn("[MCPManager] \u83B7\u53D6\u7EDF\u8BA1\u66F4\u65B0\u76D1\u63A7\u4FE1\u606F\u5931\u8D25:",e),{activeLocks:[],totalLocks:0}}}getService(e){return this.services.get(e)}getAllServices(){return new Map(this.services)}getCustomMCPHandler(){return this.customMCPHandler}hasCustomMCPTool(e){return this.customMCPHandler.hasTool(e)}getCustomMCPTools(){return this.customMCPHandler.getTools()}enhanceServiceConfig(e){let t={...e};try{if(e.type==="modelscope-sse"){let r=d.getModelScopeApiKey();if(r)t.apiKey=r,this.logger.info(`[MCPManager] \u4E3A ${e.name} \u670D\u52A1\u6DFB\u52A0 ModelScope API Key`);else throw this.logger.warn(`[MCPManager] ${e.name} \u670D\u52A1\u9700\u8981 ModelScope API Key\uFF0C\u4F46\u672A\u5728\u914D\u7F6E\u4E2D\u627E\u5230`),new Error(`ModelScope SSE \u670D\u52A1 ${e.name} \u9700\u8981 API Key\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E modelscope.apiKey`)}return t}catch(r){throw this.logger.error(`[MCPManager] \u914D\u7F6E\u589E\u5F3A\u5931\u8D25: ${e.name}`,r),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,this.logger.info(`[MCPManager] \u5DF2\u6DFB\u52A0\u670D\u52A1\u914D\u7F6E: ${o}`)}updateServiceConfig(e,t){let r=this.enhanceServiceConfig(t);this.configs[e]=r,this.logger.info(`[MCPManager] \u5DF2\u66F4\u65B0\u5E76\u589E\u5F3A\u670D\u52A1\u914D\u7F6E: ${e}`)}removeServiceConfig(e){delete this.configs[e],this.logger.info(`[MCPManager] \u5DF2\u79FB\u9664\u670D\u52A1\u914D\u7F6E: ${e}`)}async syncToolsConfigToFile(){try{this.logger.debug("[MCPManager] \u5F00\u59CB\u540C\u6B65\u5DE5\u5177\u914D\u7F6E\u5230\u914D\u7F6E\u6587\u4EF6");let e=d.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 p of o){let C=n[p.name];C?s[p.name]={...C,description:p.description||C.description||""}:s[p.name]={description:p.description||"",enable:!0}}let a=o.map(p=>p.name),h=Object.keys(n).filter(p=>!a.includes(p));if(h.length>0&&this.logger.info(`[MCPManager] \u68C0\u6D4B\u5230\u670D\u52A1 ${t} \u79FB\u9664\u4E86 ${h.length} \u4E2A\u5DE5\u5177: ${h.join(", ")}`),this.hasToolsConfigChanged(n,s)){d.updateServerToolsConfig(t,s);let p=Object.keys(s).filter(T=>!n[T]),C=Object.keys(s).filter(T=>{let b=n[T],B=s[T];return b&&b.description!==B.description});this.logger.info(`[MCPManager] \u5DF2\u540C\u6B65\u670D\u52A1 ${t} \u7684\u5DE5\u5177\u914D\u7F6E:`),p.length>0&&this.logger.info(` - \u65B0\u589E\u5DE5\u5177: ${p.join(", ")}`),C.length>0&&this.logger.info(` - \u66F4\u65B0\u5DE5\u5177: ${C.join(", ")}`),h.length>0&&this.logger.info(` - \u79FB\u9664\u5DE5\u5177: ${h.join(", ")}`)}}this.logger.debug("[MCPManager] \u5DE5\u5177\u914D\u7F6E\u540C\u6B65\u5B8C\u6210")}catch(e){this.logger.error("[MCPManager] \u540C\u6B65\u5DE5\u5177\u914D\u7F6E\u5230\u914D\u7F6E\u6587\u4EF6\u5931\u8D25:",e)}}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 l=e[a],h=t[a];if(l.description!==h.description)return!0}return!1}},go=Ze});var De,gr=m(()=>{"use strict";S();De=class{static{c(this,"MCPMessageHandler")}logger;serviceManager;constructor(e){this.serviceManager=e,this.logger=g}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.info("\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.info(`\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.info("\u6536\u5230 initialized \u901A\u77E5\uFF0C\u5BA2\u6237\u7AEF\u521D\u59CB\u5316\u5B8C\u6210",e),null}async handleToolsList(e){this.logger.info("\u5904\u7406 tools/list \u8BF7\u6C42");try{let r=this.serviceManager.getAllTools().map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema}));return this.logger.info(`\u8FD4\u56DE ${r.length} \u4E2A\u5DE5\u5177`),{jsonrpc:"2.0",result:{tools:r},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){this.logger.info(`\u5904\u7406 tools/call \u8BF7\u6C42: ${e.name}`,e);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 this.logger.info(`\u5DE5\u5177 ${e.name} \u8C03\u7528\u6210\u529F`),{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.info("\u5904\u7406 resources/list \u8BF7\u6C42");let t=[];return this.logger.info(`\u8FD4\u56DE ${t.length} \u4E2A\u8D44\u6E90`),{jsonrpc:"2.0",result:{resources:t},id:e!==void 0?e:1}}async handlePromptsList(e){this.logger.info("\u5904\u7406 prompts/list \u8BF7\u6C42");let t=[];return this.logger.info(`\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}}});import{EventEmitter as ho}from"events";var hr,ur,Et,uo=m(()=>{"use strict";S();lr();Ge();gr();hr=class{static{c(this,"ToolRegistry")}serviceManager;logger;constructor(e){this.serviceManager=e,this.logger=g}async initialize(){this.logger.info("\u521D\u59CB\u5316\u5DE5\u5177\u6CE8\u518C\u8868")}getAllTools(){return this.serviceManager.getAllTools().map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema,serviceName:e.serviceName,originalName:e.originalName}))}findTool(e){return this.getAllTools().find(r=>r.name===e)||null}hasTool(e){return this.findTool(e)!==null}},ur=class extends ho{static{c(this,"ConnectionManager")}connections=new Map;logger;constructor(){super(),this.logger=g}async initialize(){this.logger.info("\u521D\u59CB\u5316\u8FDE\u63A5\u7BA1\u7406\u5668")}registerConnection(e,t,r){let o={id:e,transportName:t,state:r,connectedAt:new Date,lastActivity:new Date};this.connections.set(e,o),this.emit("connectionRegistered",o),this.logger.debug(`\u8FDE\u63A5\u5DF2\u6CE8\u518C: ${e} (${t})`)}updateConnectionState(e,t){let r=this.connections.get(e);r&&(r.state=t,r.lastActivity=new Date,this.emit("connectionStateChanged",r),this.logger.debug(`\u8FDE\u63A5\u72B6\u6001\u66F4\u65B0: ${e} -> ${t}`))}removeConnection(e){let t=this.connections.get(e);t&&(this.connections.delete(e),this.emit("connectionRemoved",t),this.logger.debug(`\u8FDE\u63A5\u5DF2\u79FB\u9664: ${e}`))}getAllConnections(){return Array.from(this.connections.values())}getActiveConnectionCount(){return Array.from(this.connections.values()).filter(e=>e.state==="connected").length}async closeAllConnections(){this.logger.info("\u5173\u95ED\u6240\u6709\u8FDE\u63A5"),this.connections.clear(),this.emit("allConnectionsClosed")}},Et=class extends ho{static{c(this,"UnifiedMCPServer")}serviceManager;messageHandler;transportAdapters=new Map;toolRegistry;connectionManager;isRunning=!1;logger;config;constructor(e={}){super(),this.config={name:"UnifiedMCPServer",enableLogging:!0,logLevel:"info",maxConnections:100,connectionTimeout:3e4,...e},this.logger=g,this.serviceManager=new Ze,this.messageHandler=new De(this.serviceManager),this.toolRegistry=new hr(this.serviceManager),this.connectionManager=new ur,this.setupEventListeners()}setupEventListeners(){this.connectionManager.on("connectionRegistered",e=>{this.emit("connectionRegistered",e)}),this.connectionManager.on("connectionStateChanged",e=>{this.emit("connectionStateChanged",e)}),this.connectionManager.on("connectionRemoved",e=>{this.emit("connectionRemoved",e)})}async initialize(){this.logger.info("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{await this.serviceManager.startAllServices(),await this.toolRegistry.initialize(),await this.connectionManager.initialize(),this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210"),this.emit("initialized")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5931\u8D25",e),e}}async registerTransport(e,t){if(this.transportAdapters.has(e))throw new Error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u5DF2\u5B58\u5728`);this.logger.info(`\u6CE8\u518C\u4F20\u8F93\u9002\u914D\u5668: ${e}`);try{await t.initialize(),this.transportAdapters.set(e,t),this.connectionManager.registerConnection(t.getConnectionId(),e,t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u6CE8\u518C\u6210\u529F`),this.emit("transportRegistered",{name:e,adapter:t})}catch(r){throw this.logger.error(`\u6CE8\u518C\u4F20\u8F93\u9002\u914D\u5668 ${e} \u5931\u8D25`,r),r}}async start(){if(this.isRunning)throw new Error("\u670D\u52A1\u5668\u5DF2\u5728\u8FD0\u884C");this.logger.info("\u542F\u52A8\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{for(let[e,t]of this.transportAdapters)try{await t.start(),this.connectionManager.updateConnectionState(t.getConnectionId(),t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u542F\u52A8\u6210\u529F`)}catch(r){throw this.logger.error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u542F\u52A8\u5931\u8D25`,r),r}this.isRunning=!0,this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F"),this.emit("started")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u542F\u52A8\u5931\u8D25",e),e}}async stop(){if(this.isRunning){this.logger.info("\u505C\u6B62\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{for(let[e,t]of this.transportAdapters)try{await t.stop(),this.connectionManager.updateConnectionState(t.getConnectionId(),t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u505C\u6B62\u6210\u529F`)}catch(r){this.logger.error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u505C\u6B62\u5931\u8D25`,r)}await this.connectionManager.closeAllConnections(),await this.serviceManager.stopAllServices(),this.isRunning=!1,this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u505C\u6B62\u6210\u529F"),this.emit("stopped")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u505C\u6B62\u5931\u8D25",e),e}}}getServiceManager(){return this.serviceManager}getToolRegistry(){return this.toolRegistry}getConnectionManager(){return this.connectionManager}getMessageHandler(){return this.messageHandler}getStatus(){return{isRunning:this.isRunning,transportCount:this.transportAdapters.size,activeConnections:this.connectionManager.getActiveConnectionCount(),toolCount:this.toolRegistry.getAllTools().length,config:this.config}}getTransportAdapters(){return new Map(this.transportAdapters)}isServerRunning(){return this.isRunning}}});async function po(i={name:"http"}){g.info("\u521B\u5EFA HTTP \u6A21\u5F0F\u670D\u52A1\u5668");let e=new Et;await e.initialize();let t=e.getMessageHandler(),r=new pt(t,i);return await e.registerTransport("http",r),g.info("HTTP \u6A21\u5F0F\u670D\u52A1\u5668\u521B\u5EFA\u6210\u529F"),e}var mo=m(()=>{"use strict";S();Xr();Kr();Zr();uo();c(po,"createHTTPServer")});var fo={};F(fo,{MCPServer:()=>pr});import{EventEmitter as Gn}from"events";var D,pr,Co=m(()=>{"use strict";S();ut();Y();mo();D=new Ie,pr=class extends Gn{static{c(this,"MCPServer")}unifiedServer=null;proxyMCPServer=null;port;isStarted=!1;constructor(e=3e3){super(),this.port=e}async initializeUnifiedServer(){if(!this.unifiedServer){D.info("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{let e={name:"http",port:this.port,host:"0.0.0.0",enableSSE:!0,enableRPC:!0};this.unifiedServer=await po(e),this.unifiedServer.on("started",()=>this.emit("started")),this.unifiedServer.on("stopped",()=>this.emit("stopped")),this.unifiedServer.on("connectionRegistered",t=>{this.emit("connectionRegistered",t)}),D.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw D.error("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u5931\u8D25",e),e}}}async initializeMCPClient(){try{let e=null;try{d.configExists()&&(e=d.getMcpEndpoints().find(r=>r&&!r.includes("<\u8BF7\u586B\u5199"))||null)}catch(t){D.warn("\u4ECE\u914D\u7F6E\u4E2D\u8BFB\u53D6\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25:",t)}e?(this.proxyMCPServer=new pe(e),this.unifiedServer&&this.proxyMCPServer.setServiceManager(this.unifiedServer.getServiceManager()),await this.proxyMCPServer.connect(),D.info("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F")):D.info("\u672A\u914D\u7F6E\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u8DF3\u8FC7\u8FDE\u63A5")}catch(e){D.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}}async start(){if(this.isStarted){D.warn("\u670D\u52A1\u5668\u5DF2\u542F\u52A8");return}try{D.info("\u542F\u52A8 MCP \u670D\u52A1\u5668"),await this.initializeUnifiedServer(),this.unifiedServer&&await this.unifiedServer.start(),this.initializeMCPClient().catch(e=>{D.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}),this.isStarted=!0,this.emit("started"),D.info("MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F")}catch(e){throw D.error("\u542F\u52A8 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}async stop(){if(!this.isStarted){D.warn("\u670D\u52A1\u5668\u672A\u542F\u52A8");return}try{D.info("\u505C\u6B62 MCP \u670D\u52A1\u5668"),this.unifiedServer&&await this.unifiedServer.stop(),this.proxyMCPServer&&(this.proxyMCPServer.disconnect(),this.proxyMCPServer=null),this.isStarted=!1,this.emit("stopped"),D.info("MCP \u670D\u52A1\u5668\u5DF2\u505C\u6B62")}catch(e){throw D.error("\u505C\u6B62 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}getServiceManager(){return this.unifiedServer?.getServiceManager()||null}getMessageHandler(){return this.unifiedServer?.getMessageHandler()||null}getStatus(){return this.unifiedServer?{...this.unifiedServer.getStatus(),port:this.port,mode:"mcp-server",proxyConnected:this.proxyMCPServer!==null}:{isRunning:!1,port:this.port,mode:"mcp-server"}}isRunning(){return this.isStarted&&(this.unifiedServer?.isServerRunning()||!1)}}});import{isAbsolute as Jn,resolve as Xn}from"path";function vo(i,e){Mt.debug(`\u8F6C\u6362\u914D\u7F6E: ${i}`,e);try{if(!i||typeof i!="string")throw new L("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!e||typeof e!="object")throw new L("\u914D\u7F6E\u5BF9\u8C61\u4E0D\u80FD\u4E3A\u7A7A",i);let t=Kn(i,e);return ss(t),Mt.info(`\u914D\u7F6E\u8F6C\u6362\u6210\u529F: ${i} -> ${t.type}`),t}catch(t){throw Mt.error(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${i}`,t),t instanceof L?t:new L(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,i)}}function Kn(i,e){if(ts(e))return Zn(i,e);if(rs(e))return Yn(i,e);if(os(e))return Qn(i,e);throw new L("\u65E0\u6CD5\u8BC6\u522B\u7684\u914D\u7F6E\u7C7B\u578B",i)}function Zn(i,e){if(!e.command)throw new L("\u672C\u5730\u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5",i);let t=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),r=(e.args||[]).map(o=>{if(es(o)){let n=Xn(t,o);return Mt.debug(`\u89E3\u6790\u76F8\u5BF9\u8DEF\u5F84: ${o} -> ${n}`),n}return o});return{name:i,type:"stdio",command:e.command,args:r,env:e.env,reconnect:{enabled:!0,maxAttempts:5,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:1e4,jitter:!0},ping:{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3},timeout:3e4}}function Yn(i,e){if(!e.url)throw new L("SSE \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);let t=ns(e.url),r={name:i,type:t?"modelscope-sse":"sse",url:e.url,reconnect:{enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:15e3,jitter:!0},ping:{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3},timeout:3e4};return t&&(r.modelScopeAuth=!0),r}function Qn(i,e){if(!e.url)throw new L("Streamable HTTP \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);return{name:i,type:"streamable-http",url:e.url,reconnect:{enabled:!0,maxAttempts:5,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:15e3,jitter:!0},ping:{enabled:!1,interval:6e4,timeout:1e4,maxFailures:3,startDelay:1e4},timeout:3e4}}function es(i){return Jn(i)?!1:!!(i.startsWith("./")||i.startsWith("../")||/\.(js|py|ts|mjs|cjs)$/i.test(i))}function ts(i){return"command"in i&&typeof i.command=="string"}function rs(i){return"type"in i&&i.type==="sse"&&"url"in i}function os(i){return"url"in i&&(!("type"in i)||i.type==="streamable-http")}function ns(i){return i.includes("modelscope.net")||i.includes("modelscope.cn")}function ss(i){if(!i.name||typeof i.name!="string")throw new L("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(!Object.values(Ke).includes(i.type))throw new L(`\u65E0\u6548\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`);switch(i.type){case"stdio":if(!i.command)throw new L("STDIO \u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5");break;case"sse":case"modelscope-sse":case"streamable-http":if(!i.url)throw new L(`${i.type} \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5`);break;default:throw new L(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}var Mt,L,So=m(()=>{"use strict";S();St();Mt=g.withTag("ConfigAdapter"),L=class extends Error{constructor(t,r){super(t);this.configName=r;this.name="ConfigValidationError"}static{c(this,"ConfigValidationError")}};c(vo,"convertLegacyToNew");c(Kn,"convertByConfigType");c(Zn,"convertLocalConfig");c(Yn,"convertSSEConfig");c(Qn,"convertStreamableHTTPConfig");c(es,"isRelativePath");c(ts,"isLocalConfig");c(rs,"isSSEConfig");c(os,"isStreamableHTTPConfig");c(ns,"isModelScopeURL");c(ss,"validateNewConfig")});async function is(){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),new go}async function yo(){if(se&&z==="initialized")return se;if(Q&&z==="initializing")return Q;z==="failed"&&dr(),z="initializing",Q=is();try{return se=await Q,z="initialized",Ne=`mcp-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,Ye=null,console.log(`\u2705 MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${Ne}`),se}catch(i){throw z="failed",Ye=i,Q=null,console.error("\u274C MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",i.message),i}}async function To(){if(z==="cleanup"){console.log("\u26A0\uFE0F MCPServiceManager \u5355\u4F8B\u5DF2\u5728\u6E05\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u91CD\u590D\u6E05\u7406");return}console.log("\u{1F9F9} \u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B\u8D44\u6E90..."),z="cleanup";try{if(Q){try{await(await Q).stopAllServices()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}Q=null}se&&(await se.stopAllServices(),se=null),z="not_initialized",Ye=null,Ne=null,console.log("\u2705 MCPServiceManager \u5355\u4F8B\u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(i){throw console.error("\u274C MCPServiceManager \u5355\u4F8B\u6E05\u7406\u5931\u8D25:",i.message),dr(),i}}function dr(){console.log("\u{1F504} \u91CD\u7F6E MCPServiceManager \u5355\u4F8B\u72B6\u6001"),se=null,Q=null,z="not_initialized",Ye=null,Ne=null}function as(){return z==="initialized"&&se!==null}function cs(){return{state:z,initializationTime:Ne?new Date:void 0,lastError:Ye||void 0,instanceId:Ne||void 0}}async function ls(){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),await To(),yo()}function gs(){return se}async function hs(){if(z==="initialized")return!0;if(z==="initializing"&&Q)try{return await Q,!0}catch{return!1}return!1}var se,Q,z,Ye,Ne,V,Pt=m(()=>{"use strict";lr();se=null,Q=null,z="not_initialized",Ye=null,Ne=null;c(is,"createInstance");c(yo,"getInstance");c(To,"cleanup");c(dr,"reset");c(as,"isInitialized");c(cs,"getStatus");c(ls,"forceReinitialize");c(gs,"getCurrentInstance");c(hs,"waitForInitialization");V={getInstance:yo,cleanup:To,reset:dr,isInitialized:as,getStatus:cs,forceReinitialize:ls,getCurrentInstance:gs,waitForInitialization:hs};process.on("exit",()=>{V.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B..."),V.reset())});process.on("uncaughtException",async i=>{console.error("\u{1F4A5} \u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u6E05\u7406 MCPServiceManager \u5355\u4F8B:",i);try{await V.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}});process.on("unhandledRejection",async i=>{console.error("\u{1F4A5} \u672A\u5904\u7406\u7684Promise\u62D2\u7EDD\uFF0C\u6E05\u7406 MCPServiceManager \u5355\u4F8B:",i);try{await V.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as us}from"events";var Eo,ps,wt,Mo=m(()=>{"use strict";S();ut();Eo=(o=>(o.EXPONENTIAL_BACKOFF="exponential_backoff",o.LINEAR_BACKOFF="linear_backoff",o.FIXED_INTERVAL="fixed_interval",o.ADAPTIVE="adaptive",o))(Eo||{}),ps={healthCheckInterval:3e4,reconnectInterval:5e3,maxReconnectAttempts:10,loadBalanceStrategy:"round-robin",connectionTimeout:1e4,reconnectStrategy:"exponential_backoff",maxReconnectDelay:3e4,reconnectBackoffMultiplier:2,jitterEnabled:!0},wt=class extends us{static{c(this,"XiaozhiConnectionManager")}connections=new Map;connectionStates=new Map;mcpServiceManager=null;logger;isInitialized=!1;isConnecting=!1;options;healthCheckInterval=null;reconnectTimers=new Map;roundRobinIndex=0;lastSelectedEndpoint=null;performanceMetrics={connectionStartTime:0,totalConnectionTime:0,averageConnectionTime:0,connectionCount:0,memoryUsage:{initial:0,current:0,peak:0},prewarmedConnections:new Set};constructor(e){super(),this.logger=g,this.options={...ps,...e},this.logger.info("[XiaozhiConnectionManager] \u5B9E\u4F8B\u5DF2\u521B\u5EFA"),this.logger.debug("[XiaozhiConnectionManager] \u914D\u7F6E\u9009\u9879:",this.options)}async initialize(e,t){if(this.isInitialized){this.logger.warn("XiaozhiConnectionManager \u5DF2\u7ECF\u521D\u59CB\u5316\uFF0C\u8DF3\u8FC7\u91CD\u590D\u521D\u59CB\u5316");return}this.logger.info(`\u5F00\u59CB\u521D\u59CB\u5316 XiaozhiConnectionManager\uFF0C\u7AEF\u70B9\u6570\u91CF: ${e.length}`);try{this.validateInitializeParams(e,t),await this.cleanup();for(let r of e)await this.createConnection(r,t);this.isInitialized=!0,this.performanceMetrics.memoryUsage.initial=process.memoryUsage().heapUsed,this.performanceMetrics.memoryUsage.current=this.performanceMetrics.memoryUsage.initial,this.performanceMetrics.memoryUsage.peak=this.performanceMetrics.memoryUsage.initial,this.logger.info(`XiaozhiConnectionManager \u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u7BA1\u7406 ${this.connections.size} \u4E2A\u8FDE\u63A5`)}catch(r){throw this.logger.error("XiaozhiConnectionManager \u521D\u59CB\u5316\u5931\u8D25:",r),await this.cleanup(),r}}async connect(){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 initialize()");if(this.isConnecting){this.logger.warn("\u8FDE\u63A5\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");return}this.isConnecting=!0,this.performanceMetrics.connectionStartTime=Date.now(),this.logger.info(`\u5F00\u59CB\u8FDE\u63A5\u6240\u6709\u7AEF\u70B9\uFF0C\u603B\u6570: ${this.connections.size}`);try{let e=[];for(let[s,a]of this.connections)e.push(this.connectSingleEndpoint(s,a));let t=await Promise.allSettled(e),r=t.filter(s=>s.status==="fulfilled").length,o=t.length-r,n=Date.now()-this.performanceMetrics.connectionStartTime;if(this.performanceMetrics.totalConnectionTime+=n,this.performanceMetrics.connectionCount++,this.performanceMetrics.averageConnectionTime=this.performanceMetrics.totalConnectionTime/this.performanceMetrics.connectionCount,this.logger.info(`\u8FDE\u63A5\u5B8C\u6210 - \u6210\u529F: ${r}, \u5931\u8D25: ${o}, \u8017\u65F6: ${n}ms`),r===0)throw new Error("\u6240\u6709\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25");this.startHealthCheck()}finally{this.isConnecting=!1}}async disconnect(){this.logger.info("\u5F00\u59CB\u65AD\u5F00\u6240\u6709\u8FDE\u63A5"),this.stopHealthCheck(),this.clearAllReconnectTimers();let e=[];for(let[t,r]of this.connections)e.push(this.disconnectSingleEndpoint(t,r));await Promise.allSettled(e),this.logger.info("\u6240\u6709\u8FDE\u63A5\u5DF2\u65AD\u5F00")}async addEndpoint(e){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316");if(this.connections.has(e)){this.logger.warn(`\u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728\uFF0C\u8DF3\u8FC7\u6DFB\u52A0`);return}this.logger.info(`\u52A8\u6001\u6DFB\u52A0\u7AEF\u70B9: ${e}`);try{let t=this.getCurrentTools();if(await this.createConnection(e,t),this.isAnyConnected()){let r=this.connections.get(e);await this.connectSingleEndpoint(e,r)}this.logger.info(`\u7AEF\u70B9 ${e} \u6DFB\u52A0\u6210\u529F`)}catch(t){throw this.logger.error(`\u6DFB\u52A0\u7AEF\u70B9 ${e} \u5931\u8D25:`,t),this.connections.delete(e),this.connectionStates.delete(e),t}}async removeEndpoint(e){if(!this.connections.has(e)){this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u79FB\u9664`);return}this.logger.info(`\u52A8\u6001\u79FB\u9664\u7AEF\u70B9: ${e}`);try{let t=this.connections.get(e);await this.disconnectSingleEndpoint(e,t),this.connections.delete(e),this.connectionStates.delete(e);let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e)),this.logger.info(`\u7AEF\u70B9 ${e} \u79FB\u9664\u6210\u529F`)}catch(t){throw this.logger.error(`\u79FB\u9664\u7AEF\u70B9 ${e} \u5931\u8D25:`,t),t}}getHealthyConnections(){let e=[];for(let[t,r]of this.connections){let o=this.connectionStates.get(t);o?.connected&&o.healthScore>50&&e.push(r)}return e}getConnectionStatus(){return Array.from(this.connectionStates.values())}isAnyConnected(){for(let e of this.connectionStates.values())if(e.connected)return!0;return!1}setServiceManager(e){this.mcpServiceManager=e,this.logger.info("\u5DF2\u8BBE\u7F6E MCPServiceManager"),this.connections.size>0&&this.syncToolsToAllConnections()}setHealthCheckEnabled(e,t){let r=this.connectionStates.get(e);r?(r.healthCheckEnabled=t,this.logger.info(`\u7AEF\u70B9 ${e} \u5065\u5EB7\u68C0\u67E5\u5DF2${t?"\u542F\u7528":"\u7981\u7528"}`)):this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u8BBE\u7F6E\u5065\u5EB7\u68C0\u67E5\u72B6\u6001`)}getHealthCheckStats(){let e={};for(let[t,r]of this.connectionStates){let o=r.totalRequests>0?r.successfulRequests/r.totalRequests*100:0;e[t]={endpoint:t,healthScore:r.healthScore,successRate:Math.round(o*100)/100,averageResponseTime:r.responseTime||0,consecutiveFailures:r.consecutiveFailures,lastHealthCheck:r.lastHealthCheck,lastSuccessTime:r.lastSuccessTime}}return e}async triggerHealthCheck(){this.logger.info("\u624B\u52A8\u89E6\u53D1\u5065\u5EB7\u68C0\u67E5"),await this.performHealthCheck()}async triggerReconnect(e){let t=this.connectionStates.get(e);if(!t)throw new Error(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(t.connected){this.logger.warn(`\u7AEF\u70B9 ${e} \u5DF2\u8FDE\u63A5\uFF0C\u65E0\u9700\u91CD\u8FDE`);return}this.logger.info(`\u624B\u52A8\u89E6\u53D1\u91CD\u8FDE: ${e}`);let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e)),await this.performReconnect(e)}stopReconnect(e){let t=this.connectionStates.get(e);if(!t){this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);return}let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e),t.isReconnecting=!1,t.nextReconnectTime=void 0,this.logger.info(`\u5DF2\u505C\u6B62\u7AEF\u70B9 ${e} \u7684\u91CD\u8FDE`))}stopAllReconnects(){this.logger.info("\u505C\u6B62\u6240\u6709\u7AEF\u70B9\u7684\u91CD\u8FDE");for(let[e]of this.reconnectTimers)this.stopReconnect(e)}getReconnectStats(){let e={};for(let[t,r]of this.connectionStates)e[t]={endpoint:t,reconnectAttempts:r.reconnectAttempts,isReconnecting:r.isReconnecting,nextReconnectTime:r.nextReconnectTime,lastReconnectAttempt:r.lastReconnectAttempt,reconnectDelay:r.reconnectDelay,errorType:r.errorType,recentReconnectHistory:r.reconnectHistory.slice(-5)};return e}validateEndpoints(e){let t=[],r=[];for(let o of e){if(!o||typeof o!="string"){r.push(o);continue}if(!o.startsWith("ws://")&&!o.startsWith("wss://")){r.push(o);continue}try{new URL(o),t.push(o)}catch{r.push(o)}}return{valid:t,invalid:r}}validateOptions(e){let t=[];if(e.healthCheckInterval!==void 0&&(typeof e.healthCheckInterval!="number"||e.healthCheckInterval<1e3)&&t.push("healthCheckInterval \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.reconnectInterval!==void 0&&(typeof e.reconnectInterval!="number"||e.reconnectInterval<100)&&t.push("reconnectInterval \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 100 \u7684\u6570\u5B57"),e.maxReconnectAttempts!==void 0&&(typeof e.maxReconnectAttempts!="number"||e.maxReconnectAttempts<0)&&t.push("maxReconnectAttempts \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 0 \u7684\u6570\u5B57"),e.connectionTimeout!==void 0&&(typeof e.connectionTimeout!="number"||e.connectionTimeout<1e3)&&t.push("connectionTimeout \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.maxReconnectDelay!==void 0&&(typeof e.maxReconnectDelay!="number"||e.maxReconnectDelay<1e3)&&t.push("maxReconnectDelay \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.reconnectBackoffMultiplier!==void 0&&(typeof e.reconnectBackoffMultiplier!="number"||e.reconnectBackoffMultiplier<1)&&t.push("reconnectBackoffMultiplier \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6570\u5B57"),e.loadBalanceStrategy!==void 0){let r=["round-robin","random","health-based"];r.includes(e.loadBalanceStrategy)||t.push(`loadBalanceStrategy \u5FC5\u987B\u662F\u4EE5\u4E0B\u503C\u4E4B\u4E00: ${r.join(", ")}`)}if(e.reconnectStrategy!==void 0){let r=Object.values(Eo);r.includes(e.reconnectStrategy)||t.push(`reconnectStrategy \u5FC5\u987B\u662F\u4EE5\u4E0B\u503C\u4E4B\u4E00: ${r.join(", ")}`)}return{valid:t.length===0,errors:t}}async updateEndpoints(e,t=[]){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316");this.logger.info(`\u66F4\u65B0\u7AEF\u70B9\u914D\u7F6E\uFF0C\u65B0\u7AEF\u70B9\u6570\u91CF: ${e.length}`);let{valid:r,invalid:o}=this.validateEndpoints(e);if(o.length>0&&this.logger.warn(`\u53D1\u73B0\u65E0\u6548\u7AEF\u70B9: ${o.join(", ")}`),r.length===0)throw new Error("\u6CA1\u6709\u6709\u6548\u7684\u7AEF\u70B9");let n=Array.from(this.connections.keys()),s=r.filter(h=>!n.includes(h)),a=n.filter(h=>!r.includes(h)),l=n.filter(h=>r.includes(h));this.logger.info(`\u7AEF\u70B9\u53D8\u66F4 - \u6DFB\u52A0: ${s.length}, \u79FB\u9664: ${a.length}, \u4FDD\u6301: ${l.length}`);try{for(let u of a)await this.removeEndpoint(u);for(let u of s)await this.addEndpoint(u);let h={type:s.length>0&&a.length>0?"endpoints_updated":s.length>0?"endpoints_added":"endpoints_removed",data:{added:s.length>0?s:void 0,removed:a.length>0?a:void 0,updated:s.length>0&&a.length>0?r:void 0},timestamp:new Date};this.emit("configChange",h),this.logger.info("\u7AEF\u70B9\u914D\u7F6E\u66F4\u65B0\u5B8C\u6210")}catch(h){throw this.logger.error("\u7AEF\u70B9\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",h),h}}updateOptions(e){this.logger.info("\u66F4\u65B0\u8FDE\u63A5\u9009\u9879");let{valid:t,errors:r}=this.validateOptions(e);if(!t)throw new Error(`\u65E0\u6548\u7684\u8FDE\u63A5\u9009\u9879: ${r.join(", ")}`);let o={...this.options};this.options={...this.options,...e};let n={type:"options_updated",data:{oldOptions:o,newOptions:e},timestamp:new Date};this.emit("configChange",n),this.logger.info("\u8FDE\u63A5\u9009\u9879\u66F4\u65B0\u5B8C\u6210"),this.logger.debug("\u65B0\u7684\u914D\u7F6E\u9009\u9879:",this.options)}getCurrentConfig(){return{endpoints:Array.from(this.connections.keys()),options:{...this.options}}}async reloadConfig(e){this.logger.info("\u5F00\u59CB\u70ED\u91CD\u8F7D\u914D\u7F6E");try{e.options&&this.updateOptions(e.options),e.endpoints&&await this.updateEndpoints(e.endpoints,e.tools||[]),this.logger.info("\u914D\u7F6E\u70ED\u91CD\u8F7D\u5B8C\u6210")}catch(t){throw this.logger.error("\u914D\u7F6E\u70ED\u91CD\u8F7D\u5931\u8D25:",t),t}}selectBestConnection(e=[]){let t=this.getHealthyConnections();if(t.length===0)return this.logger.warn("\u6CA1\u6709\u5065\u5EB7\u7684\u8FDE\u63A5\u53EF\u7528"),null;let r=t.filter(n=>{let s=this.getEndpointByConnection(n);return s&&!e.includes(s)});if(r.length===0)return this.logger.warn("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5\uFF08\u6392\u9664\u6307\u5B9A\u7AEF\u70B9\u540E\uFF09"),null;let o;switch(this.options.loadBalanceStrategy){case"round-robin":o=this.selectRoundRobin(r);break;case"random":o=this.selectRandom(r);break;case"health-based":o=this.selectHealthBased(r);break;default:o=this.selectRoundRobin(r)}return this.lastSelectedEndpoint=this.getEndpointByConnection(o),o}selectRoundRobin(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=e[this.roundRobinIndex%e.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%e.length,t}selectRandom(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=Math.floor(Math.random()*e.length);return e[t]}selectHealthBased(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=e.map(n=>{let s=this.getEndpointByConnection(n),a=s?this.connectionStates.get(s):null;return{connection:n,endpoint:s,healthScore:a?.healthScore||0,responseTime:a?.responseTime||Number.POSITIVE_INFINITY,successRate:a&&a.totalRequests>0?a.successfulRequests/a.totalRequests*100:0}});t.sort((n,s)=>n.healthScore!==s.healthScore?s.healthScore-n.healthScore:n.successRate!==s.successRate?s.successRate-n.successRate:n.responseTime-s.responseTime);let r=t.reduce((n,s)=>n+(s.healthScore+1),0),o=Math.random()*r;for(let n of t)if(o-=n.healthScore+1,o<=0)return n.connection;return t[0].connection}getEndpointByConnection(e){for(let[t,r]of this.connections)if(r===e)return t;return null}getLoadBalanceStats(){let e=this.getHealthyConnections(),t={};for(let[r,o]of this.connectionStates){let n=o.totalRequests>0?o.successfulRequests/o.totalRequests*100:0,s=o.healthScore+1;t[r]={healthScore:o.healthScore,responseTime:o.responseTime||0,successRate:Math.round(n*100)/100,weight:s}}return{strategy:this.options.loadBalanceStrategy,totalConnections:this.connections.size,healthyConnections:e.length,lastSelectedEndpoint:this.lastSelectedEndpoint,roundRobinIndex:this.roundRobinIndex,connectionWeights:t}}setLoadBalanceStrategy(e){let t=this.options.loadBalanceStrategy;this.options.loadBalanceStrategy=e,e==="round-robin"&&(this.roundRobinIndex=0),this.logger.info(`\u8D1F\u8F7D\u5747\u8861\u7B56\u7565\u5DF2\u4ECE ${t} \u5207\u6362\u5230 ${e}`);let r={type:"options_updated",data:{oldOptions:{loadBalanceStrategy:t},newOptions:{loadBalanceStrategy:e}},timestamp:new Date};this.emit("configChange",r)}async performFailover(e){this.logger.warn(`\u6267\u884C\u6545\u969C\u8F6C\u79FB\uFF0C\u5931\u8D25\u7AEF\u70B9: ${e}`);let t=this.selectBestConnection([e]);if(!t)return this.logger.error("\u6545\u969C\u8F6C\u79FB\u5931\u8D25\uFF1A\u6CA1\u6709\u53EF\u7528\u7684\u5907\u7528\u8FDE\u63A5"),null;let r=this.getEndpointByConnection(t);return this.logger.info(`\u6545\u969C\u8F6C\u79FB\u6210\u529F\uFF0C\u5207\u6362\u5230\u7AEF\u70B9: ${r}`),t}async prewarmConnections(e=[]){let t=e.length>0?e:Array.from(this.connections.keys());this.logger.info(`\u5F00\u59CB\u9884\u70ED\u8FDE\u63A5\uFF0C\u7AEF\u70B9\u6570\u91CF: ${t.length}`);let r=t.map(async o=>{if(this.performanceMetrics.prewarmedConnections.has(o)){this.logger.debug(`\u7AEF\u70B9 ${o} \u5DF2\u9884\u70ED\uFF0C\u8DF3\u8FC7`);return}try{this.connections.get(o)&&(await this.performHealthCheck(),this.performanceMetrics.prewarmedConnections.add(o),this.logger.debug(`\u7AEF\u70B9 ${o} \u9884\u70ED\u5B8C\u6210`))}catch(n){this.logger.warn(`\u7AEF\u70B9 ${o} \u9884\u70ED\u5931\u8D25:`,n)}});await Promise.all(r),this.logger.info(`\u8FDE\u63A5\u9884\u70ED\u5B8C\u6210\uFF0C\u6210\u529F\u9884\u70ED ${this.performanceMetrics.prewarmedConnections.size} \u4E2A\u7AEF\u70B9`)}updatePerformanceMetrics(){let e=process.memoryUsage().heapUsed;this.performanceMetrics.memoryUsage.current=e,e>this.performanceMetrics.memoryUsage.peak&&(this.performanceMetrics.memoryUsage.peak=e)}getPerformanceMetrics(){this.updatePerformanceMetrics();let e=this.performanceMetrics.memoryUsage.current-this.performanceMetrics.memoryUsage.initial,t=this.performanceMetrics.memoryUsage.initial>0?e/this.performanceMetrics.memoryUsage.initial*100:0;return{connectionTime:{total:this.performanceMetrics.totalConnectionTime,average:this.performanceMetrics.averageConnectionTime,count:this.performanceMetrics.connectionCount},memoryUsage:{initial:this.performanceMetrics.memoryUsage.initial,current:this.performanceMetrics.memoryUsage.current,peak:this.performanceMetrics.memoryUsage.peak,growth:e,growthPercentage:Math.round(t*100)/100},prewarmedConnections:this.performanceMetrics.prewarmedConnections.size,totalConnections:this.connections.size,healthyConnections:this.getHealthyConnections().length}}optimizeMemoryUsage(){this.logger.info("\u5F00\u59CB\u5185\u5B58\u4F18\u5316");for(let[,e]of this.connectionStates)if(e.reconnectHistory&&e.reconnectHistory.length>10&&(e.reconnectHistory=e.reconnectHistory.slice(-10)),e.totalRequests>1e4){let t=e.successfulRequests/e.totalRequests;e.totalRequests=1e3,e.successfulRequests=Math.round(t*1e3)}global.gc&&global.gc(),this.updatePerformanceMetrics(),this.logger.info("\u5185\u5B58\u4F18\u5316\u5B8C\u6210")}async cleanup(){this.logger.info("\u5F00\u59CB\u6E05\u7406 XiaozhiConnectionManager \u8D44\u6E90");try{await this.disconnect(),this.connections.clear(),this.connectionStates.clear(),this.isInitialized=!1,this.isConnecting=!1,this.roundRobinIndex=0,this.lastSelectedEndpoint=null,this.logger.info("XiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(e){throw this.logger.error("XiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5931\u8D25:",e),e}}validateInitializeParams(e,t){if(!Array.isArray(e)||e.length===0)throw new Error("\u7AEF\u70B9\u5217\u8868\u4E0D\u80FD\u4E3A\u7A7A");if(!Array.isArray(t))throw new Error("\u5DE5\u5177\u5217\u8868\u5FC5\u987B\u662F\u6570\u7EC4");for(let r of e){if(!r||typeof r!="string")throw new Error(`\u65E0\u6548\u7684\u7AEF\u70B9\u5730\u5740: ${r}`);if(!r.startsWith("ws://")&&!r.startsWith("wss://"))throw new Error(`\u7AEF\u70B9\u5730\u5740\u5FC5\u987B\u662F WebSocket URL: ${r}`)}}async createConnection(e,t){this.logger.debug(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B: ${e}`);try{let r=new pe(e);this.mcpServiceManager&&r.setServiceManager(this.mcpServiceManager),this.connections.set(e,r),this.connectionStates.set(e,{endpoint:e,connected:!1,initialized:!1,reconnectAttempts:0,healthScore:100,consecutiveFailures:0,totalRequests:0,successfulRequests:0,healthCheckEnabled:!0,isReconnecting:!1,reconnectDelay:this.options.reconnectInterval,reconnectHistory:[]}),this.logger.debug(`\u8FDE\u63A5\u5B9E\u4F8B\u521B\u5EFA\u6210\u529F: ${e}`)}catch(r){throw this.logger.error(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B\u5931\u8D25 ${e}:`,r),r}}async connectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(!r)throw new Error(`\u7AEF\u70B9\u72B6\u6001\u4E0D\u5B58\u5728: ${e}`);this.logger.debug(`\u8FDE\u63A5\u7AEF\u70B9: ${e}`);try{r.connected=!1,r.initialized=!1,await t.connect(),r.connected=!0,r.initialized=!0,r.lastConnected=new Date,r.lastError=void 0,r.reconnectAttempts=0,r.healthScore=100,this.logger.info(`\u7AEF\u70B9\u8FDE\u63A5\u6210\u529F: ${e}`)}catch(o){throw r.connected=!1,r.initialized=!1,r.lastError=o instanceof Error?o.message:String(o),r.reconnectAttempts++,r.healthScore=Math.max(0,r.healthScore-20),this.logger.error(`\u7AEF\u70B9\u8FDE\u63A5\u5931\u8D25 ${e}:`,o),this.scheduleReconnect(e),o}}async disconnectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(r){this.logger.debug(`\u65AD\u5F00\u7AEF\u70B9: ${e}`);try{t.disconnect(),r.connected=!1,r.initialized=!1,this.logger.debug(`\u7AEF\u70B9\u65AD\u5F00\u6210\u529F: ${e}`)}catch(o){this.logger.error(`\u7AEF\u70B9\u65AD\u5F00\u5931\u8D25 ${e}:`,o),r.connected=!1,r.initialized=!1}}}getCurrentTools(){if(!this.mcpServiceManager)return[];try{return this.mcpServiceManager.getAllTools()}catch(e){return this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25:",e),[]}}syncToolsToAllConnections(){if(this.mcpServiceManager){this.logger.debug("\u540C\u6B65\u5DE5\u5177\u5230\u6240\u6709\u8FDE\u63A5");for(let[e,t]of this.connections)try{t.setServiceManager(this.mcpServiceManager),this.logger.debug(`\u5DE5\u5177\u540C\u6B65\u6210\u529F: ${e}`)}catch(r){this.logger.error(`\u5DE5\u5177\u540C\u6B65\u5931\u8D25 ${e}:`,r)}}}startHealthCheck(){this.healthCheckInterval||(this.logger.debug(`\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\uFF0C\u95F4\u9694: ${this.options.healthCheckInterval}ms`),this.healthCheckInterval=setInterval(()=>{this.performHealthCheck()},this.options.healthCheckInterval))}stopHealthCheck(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null,this.logger.debug("\u5065\u5EB7\u68C0\u67E5\u5DF2\u505C\u6B62"))}async performHealthCheck(){this.logger.debug("\u6267\u884C\u5065\u5EB7\u68C0\u67E5");let e=[];for(let[t,r]of this.connectionStates)r.healthCheckEnabled&&e.push(this.performSingleHealthCheck(t,r));await Promise.allSettled(e)}async performSingleHealthCheck(e,t){let r=Date.now();t.lastHealthCheck=new Date,t.totalRequests++;try{let o=this.connections.get(e);if(!o)throw new Error(`\u8FDE\u63A5\u5B9E\u4F8B\u4E0D\u5B58\u5728: ${e}`);await this.checkConnectionHealth(o,e);let n=Date.now()-r;this.handleHealthCheckSuccess(t,n)}catch(o){let n=Date.now()-r;this.handleHealthCheckFailure(t,o,n)}}async checkConnectionHealth(e,t){if(!e)throw new Error("\u8FDE\u63A5\u5B9E\u4F8B\u4E0D\u5B58\u5728");if(await new Promise(o=>setTimeout(o,10)),!this.connectionStates.get(t)?.connected)throw new Error("\u8FDE\u63A5\u5DF2\u65AD\u5F00")}handleHealthCheckSuccess(e,t){e.successfulRequests++,e.consecutiveFailures=0,e.responseTime=t,e.lastSuccessTime=new Date,this.updateHealthScore(e,!0,t),this.logger.debug(`\u5065\u5EB7\u68C0\u67E5\u6210\u529F: ${e.endpoint}, \u54CD\u5E94\u65F6\u95F4: ${t}ms, \u5065\u5EB7\u5EA6: ${e.healthScore}`)}handleHealthCheckFailure(e,t,r){e.consecutiveFailures++,e.responseTime=r,e.lastError=t.message,this.updateHealthScore(e,!1,r),this.logger.warn(`\u5065\u5EB7\u68C0\u67E5\u5931\u8D25: ${e.endpoint}, \u9519\u8BEF: ${t.message}, \u8FDE\u7EED\u5931\u8D25: ${e.consecutiveFailures}, \u5065\u5EB7\u5EA6: ${e.healthScore}`),e.consecutiveFailures>=3&&e.connected&&this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8FDE\u7EED\u5931\u8D25 ${e.consecutiveFailures} \u6B21\uFF0C\u53EF\u80FD\u9700\u8981\u91CD\u8FDE`)}updateHealthScore(e,t,r){let o=e.healthScore;if(t){let n=5;r<100?n=10:r<500?n=7:r<1e3?n=5:n=2,e.healthScore=Math.min(100,o+n)}else{let n=15;e.consecutiveFailures>=5?n=30:e.consecutiveFailures>=3&&(n=20),e.healthScore=Math.max(0,o-n)}if(e.totalRequests>0){let n=e.successfulRequests/e.totalRequests;n<.5?e.healthScore=Math.max(0,e.healthScore-10):n>.9&&(e.healthScore=Math.min(100,e.healthScore+5))}}classifyConnectionError(e){let t=e.message.toLowerCase();return t.includes("timeout")||t.includes("timed out")?"timeout_error":t.includes("network")||t.includes("connection refused")||t.includes("econnrefused")||t.includes("enotfound")?"network_error":t.includes("auth")||t.includes("unauthorized")||t.includes("forbidden")||t.includes("401")||t.includes("403")?"authentication_error":t.includes("server")||t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")?"server_error":"unknown_error"}calculateReconnectDelay(e){let t=this.options.reconnectInterval,r=this.options.maxReconnectDelay,o=this.options.reconnectBackoffMultiplier,n=e.reconnectAttempts,s;switch(this.options.reconnectStrategy){case"fixed_interval":s=t;break;case"linear_backoff":s=t*(n+1);break;case"exponential_backoff":s=t*o**n;break;case"adaptive":s=this.calculateAdaptiveDelay(e,t,o,n);break;default:s=t*o**n}if(s=Math.min(s,r),this.options.jitterEnabled){let a=s*.1*Math.random();s+=a}return Math.round(s)}calculateAdaptiveDelay(e,t,r,o){let n=t;switch(e.errorType){case"network_error":n=t*r**o;break;case"authentication_error":n=t*r**o*2;break;case"server_error":n=t*(1+o);break;case"timeout_error":n=t*(1+o*.5);break;default:n=t*r**o}if(e.reconnectHistory.length>0){let s=e.reconnectHistory.slice(-5),a=s.filter(l=>l.success).length/s.length;a<.2?n*=1.5:a>.8&&(n*=.8)}return n}shouldReconnect(e){return e.reconnectAttempts>=this.options.maxReconnectAttempts?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8FDE\u6B21\u6570 ${this.options.maxReconnectAttempts}`),!1):e.errorType==="authentication_error"&&e.reconnectAttempts>=3?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8BA4\u8BC1\u9519\u8BEF\uFF0C\u505C\u6B62\u91CD\u8FDE`),!1):e.consecutiveFailures>=10?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8FDE\u7EED\u5931\u8D25\u6B21\u6570\u8FC7\u591A\uFF0C\u505C\u6B62\u91CD\u8FDE`),!1):!0}scheduleReconnect(e){let t=this.connectionStates.get(e);if(!t)return;if(t.lastError&&(t.errorType=this.classifyConnectionError(new Error(t.lastError))),!this.shouldReconnect(t)){t.isReconnecting=!1;return}let r=this.reconnectTimers.get(e);r&&clearTimeout(r);let o=this.calculateReconnectDelay(t);t.reconnectDelay=o,t.isReconnecting=!0,t.nextReconnectTime=new Date(Date.now()+o),this.logger.info(`\u5B89\u6392\u91CD\u8FDE ${e}\uFF0C\u5EF6\u8FDF: ${o}ms\uFF0C\u5C1D\u8BD5\u6B21\u6570: ${t.reconnectAttempts+1}\uFF0C\u9519\u8BEF\u7C7B\u578B: ${t.errorType}`);let n=setTimeout(async()=>{this.reconnectTimers.delete(e),await this.performReconnect(e)},o);this.reconnectTimers.set(e,n)}async performReconnect(e){let t=this.connectionStates.get(e),r=this.connections.get(e);if(!(!t||!r)){t.lastReconnectAttempt=new Date,t.isReconnecting=!0,this.logger.info(`\u5F00\u59CB\u91CD\u8FDE ${e}\uFF0C\u7B2C ${t.reconnectAttempts+1} \u6B21\u5C1D\u8BD5`);try{await this.connectSingleEndpoint(e,r),t.isReconnecting=!1,t.reconnectHistory.push({timestamp:new Date,success:!0,delay:t.reconnectDelay}),this.logger.info(`\u91CD\u8FDE\u6210\u529F ${e}`)}catch(o){t.isReconnecting=!1,t.reconnectHistory.push({timestamp:new Date,success:!1,error:o instanceof Error?o.message:String(o),delay:t.reconnectDelay}),this.logger.error(`\u91CD\u8FDE\u5931\u8D25 ${e}:`,o),this.scheduleReconnect(e)}t.reconnectHistory.length>20&&(t.reconnectHistory=t.reconnectHistory.slice(-20))}}clearAllReconnectTimers(){for(let[,e]of this.reconnectTimers)clearTimeout(e);this.reconnectTimers.clear()}}});async function ds(i){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 XiaozhiConnectionManager \u5355\u4F8B..."),new wt(i)}async function Po(i){if(ie&&j==="initialized")return ie;if(X&&j==="initializing")return X;j==="failed"&&mr(),j="initializing",X=ds(i);try{return ie=await X,j="initialized",_e=`xiaozhi-connection-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,Qe=null,console.log(`\u2705 XiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${_e}`),ie}catch(e){throw j="failed",Qe=e,X=null,console.error("\u274C XiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",e.message),e}}async function wo(){if(j==="cleanup"){console.log("\u26A0\uFE0F XiaozhiConnectionManager \u5355\u4F8B\u5DF2\u5728\u6E05\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u91CD\u590D\u6E05\u7406");return}console.log("\u{1F9F9} \u6B63\u5728\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90..."),j="cleanup";try{if(X){try{await(await X).cleanup()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}X=null}ie&&(await ie.cleanup(),ie=null),j="not_initialized",Qe=null,_e=null,console.log("\u2705 XiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(i){throw console.error("\u274C XiaozhiConnectionManager \u5355\u4F8B\u6E05\u7406\u5931\u8D25:",i.message),mr(),i}}function mr(){console.log("\u{1F504} \u91CD\u7F6E XiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001..."),X&&(X=null),ie=null,j="not_initialized",Qe=null,_e=null,console.log("\u2705 XiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001\u5DF2\u91CD\u7F6E")}function ms(){return j==="initialized"&&ie!==null}function fs(){return{state:j,initializationTime:_e?new Date:void 0,lastError:Qe||void 0,instanceId:_e||void 0}}async function Cs(i){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 XiaozhiConnectionManager \u5355\u4F8B..."),await wo(),Po(i)}function vs(){return ie}async function Ss(){if(j==="initialized")return!0;if(j==="initializing"&&X)try{return await X,!0}catch{return!1}return!1}var ie,X,j,Qe,_e,Le,bo=m(()=>{"use strict";Mo();ie=null,X=null,j="not_initialized",Qe=null,_e=null;c(ds,"createInstance");c(Po,"getInstance");c(wo,"cleanup");c(mr,"reset");c(ms,"isInitialized");c(fs,"getStatus");c(Cs,"forceReinitialize");c(vs,"getCurrentInstance");c(Ss,"waitForInitialization");Le={getInstance:Po,cleanup:wo,reset:mr,isInitialized:ms,getStatus:fs,forceReinitialize:Cs,getCurrentInstance:vs,waitForInitialization:Ss};process.on("exit",()=>{Le.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B..."),Le.reset())});process.on("uncaughtException",async i=>{console.error("\u{1F4A5} \u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B:",i);try{await Le.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}});process.on("unhandledRejection",async i=>{console.error("\u{1F4A5} \u672A\u5904\u7406\u7684Promise\u62D2\u7EDD\uFF0C\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B:",i);try{await Le.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as ys}from"events";function K(){return He||(He=new fr),He}function Ro(){He&&(He.destroy(),He=null)}var fr,He,ye=m(()=>{"use strict";S();fr=class extends ys{static{c(this,"EventBus")}logger;eventStats=new Map;maxListeners=50;constructor(){super(),this.logger=g.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),this.emit(e,t)}catch(r){return this.logger.error(`\u53D1\u5C04\u4E8B\u4EF6\u5931\u8D25: ${e}`,r),!1}}onEvent(e,t){return this.logger.debug(`\u6DFB\u52A0\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.on(e,t)}onceEvent(e,t){return this.logger.debug(`\u6DFB\u52A0\u4E00\u6B21\u6027\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.once(e,t)}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")}},He=null;c(K,"getEventBus");c(Ro,"destroyEventBus")});var ae,et=m(()=>{"use strict";S();Y();ye();ae=class{static{c(this,"ConfigService")}logger;eventBus;constructor(){this.logger=g.withTag("ConfigService"),this.eventBus=K()}async getConfig(){try{let e=d.getConfig();return this.logger.debug("\u83B7\u53D6\u914D\u7F6E\u6210\u529F"),e}catch(e){throw this.logger.error("\u83B7\u53D6\u914D\u7F6E\u5931\u8D25:",e),this.eventBus.emitEvent("config:error",{error:e instanceof Error?e:new Error(String(e)),operation:"getConfig"}),e}}async updateConfig(e,t="unknown"){try{this.logger.info(`\u5F00\u59CB\u66F4\u65B0\u914D\u7F6E\uFF0C\u6765\u6E90: ${t}`),this.validateConfig(e),e.mcpEndpoint!==d.getMcpEndpoint()&&d.updateMcpEndpoint(e.mcpEndpoint);let r=d.getMcpServers();for(let[o,n]of Object.entries(e.mcpServers))JSON.stringify(r[o])!==JSON.stringify(n)&&d.updateMcpServer(o,n);for(let o of Object.keys(r))o in e.mcpServers||(d.removeMcpServer(o),d.removeServerToolsConfig(o));if(e.connection&&d.updateConnectionConfig(e.connection),e.modelscope&&d.updateModelScopeConfig(e.modelscope),e.webUI&&d.updateWebUIConfig(e.webUI),e.mcpServerConfig)for(let[o,n]of Object.entries(e.mcpServerConfig))for(let[s,a]of Object.entries(n.tools))d.setToolEnabled(o,s,a.enable);if(e?.platforms)for(let[o,n]of Object.entries(e.platforms))d.updatePlatformConfig(o,n);this.logger.info("\u914D\u7F6E\u66F4\u65B0\u6210\u529F"),this.eventBus.emitEvent("config:updated",{config:e,source:t})}catch(r){throw this.logger.error("\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",r),this.eventBus.emitEvent("config:error",{error:r instanceof Error?r:new Error(String(r)),operation:"updateConfig"}),r}}getMcpEndpoint(){try{return d.getMcpEndpoint()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",e),e}}getMcpEndpoints(){try{return d.getMcpEndpoints()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",e),e}}getMcpServers(){try{return d.getMcpServers()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",e),e}}getConnectionConfig(){try{return d.getConnectionConfig()}catch(e){throw this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",e),e}}getWebUIPort(){try{return d.getWebUIPort()||9999}catch(e){return this.logger.error("\u83B7\u53D6 Web UI \u7AEF\u53E3\u5931\u8D25:",e),9999}}validateConfig(e){if(!e||typeof e!="object")throw new Error("\u914D\u7F6E\u5FC5\u987B\u662F\u6709\u6548\u7684\u5BF9\u8C61");if(!e.mcpEndpoint)throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B mcpEndpoint");if(!e.mcpServers||typeof e.mcpServers!="object")throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 mcpServers")}configExists(){return d.configExists()}async reloadConfig(){try{this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E"),d.reloadConfig();let e=await this.getConfig();return this.eventBus.emitEvent("config:updated",{config:e,source:"reload"}),e}catch(e){throw this.logger.error("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25:",e),this.eventBus.emitEvent("config:error",{error:e instanceof Error?e:new Error(String(e)),operation:"reloadConfig"}),e}}getConfigPath(){return d.getConfigPath()}}});var bt,Io=m(()=>{"use strict";S();et();bt=class{static{c(this,"ConfigApiHandler")}logger;configService;constructor(){this.logger=g.withTag("ConfigApiHandler"),this.configService=new ae}createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async getConfig(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u914D\u7F6E\u8BF7\u6C42");let t=await this.configService.getConfig();return this.logger.info("\u83B7\u53D6\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async updateConfig(e){try{this.logger.debug("\u5904\u7406\u66F4\u65B0\u914D\u7F6E\u8BF7\u6C42");let t=await e.req.json();if(!t||typeof t!="object"){let r=this.createErrorResponse("INVALID_REQUEST_BODY","\u8BF7\u6C42\u4F53\u5FC5\u987B\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61");return e.json(r,400)}return await this.configService.updateConfig(t,"http-api"),this.logger.info("\u914D\u7F6E\u66F4\u65B0\u6210\u529F"),e.json(this.createSuccessResponse(null,"\u914D\u7F6E\u66F4\u65B0\u6210\u529F"))}catch(t){this.logger.error("\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_UPDATE_ERROR",t instanceof Error?t.message:"\u914D\u7F6E\u66F4\u65B0\u5931\u8D25");return e.json(r,400)}}async getMcpEndpoint(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u7AEF\u70B9\u8BF7\u6C42");let t=this.configService.getMcpEndpoint();return this.logger.debug("\u83B7\u53D6 MCP \u7AEF\u70B9\u6210\u529F"),e.json(this.createSuccessResponse({endpoint:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_ENDPOINT_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25");return e.json(r,500)}}async getMcpEndpoints(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u8BF7\u6C42");let t=this.configService.getMcpEndpoints();return this.logger.debug("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u6210\u529F"),e.json(this.createSuccessResponse({endpoints:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_ENDPOINTS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25");return e.json(r,500)}}async getMcpServers(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u8BF7\u6C42");let t=this.configService.getMcpServers();return this.logger.debug("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse({servers:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_SERVERS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async getConnectionConfig(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u8BF7\u6C42");let t=this.configService.getConnectionConfig();return this.logger.debug("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse({connection:t}))}catch(t){this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONNECTION_CONFIG_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async reloadConfig(e){try{this.logger.info("\u5904\u7406\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u8BF7\u6C42");let t=await this.configService.reloadConfig();return this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(t,"\u914D\u7F6E\u91CD\u65B0\u52A0\u8F7D\u6210\u529F"))}catch(t){this.logger.error("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_RELOAD_ERROR",t instanceof Error?t.message:"\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async getConfigPath(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u8BF7\u6C42");let t=this.configService.getConfigPath();return this.logger.debug("\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u6210\u529F"),e.json(this.createSuccessResponse({path:t}))}catch(t){this.logger.error("\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_PATH_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25");return e.json(r,500)}}async checkConfigExists(e){try{this.logger.debug("\u5904\u7406\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u8BF7\u6C42");let t=this.configService.configExists();return this.logger.debug(`\u914D\u7F6E\u5B58\u5728\u68C0\u67E5\u7ED3\u679C: ${t}`),e.json(this.createSuccessResponse({exists:t}))}catch(t){this.logger.error("\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_EXISTS_CHECK_ERROR",t instanceof Error?t.message:"\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u5931\u8D25");return e.json(r,500)}}}});async function Ts(i,e=3,t=1e3){for(let r=1;r<=e;r++)try{return await i()}catch(o){if(r===e)throw o;let n=t*2**(r-1);g.warn(`\u6263\u5B50 API \u8C03\u7528\u5931\u8D25\uFF0C${n}ms \u540E\u91CD\u8BD5 (${r}/${e})`,o),await new Promise(s=>setTimeout(s,n))}throw new Error("Max retry attempts exceeded")}function Es(i,e){let t=i.status;return t===401?new ce("\u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6263\u5B50 API Token \u914D\u7F6E","AUTH_FAILED",401,e):t===429?new ce("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED",429,e):t>=500?new ce("\u6263\u5B50\u670D\u52A1\u5668\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","SERVER_ERROR",t,e):new ce(e?.msg||`API \u8C03\u7528\u5931\u8D25: ${i.statusText}`,"API_ERROR",t,e)}var Cr,ce,Rt,$o=m(()=>{"use strict";S();Cr=class{static{c(this,"CozeApiCache")}cache=new Map;TTL={workspaces:1800*1e3,workflows:300*1e3};set(e,t,r){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:this.TTL[r]})}get(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(e){if(!e){this.cache.clear();return}for(let t of this.cache.keys())t.includes(e)&&this.cache.delete(t)}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}},ce=class extends Error{static{c(this,"CozeApiErrorImpl")}code;statusCode;response;constructor(e,t,r,o){super(e),this.name="CozeApiError",this.code=t,this.statusCode=r,this.response=o}};c(Ts,"retryWithBackoff");c(Es,"handleCozeApiError");Rt=class{static{c(this,"CozeApiService")}cache=new Cr;token;API_BASE_URL="https://api.coze.cn";TIMEOUT=1e4;RETRY_ATTEMPTS=3;constructor(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("\u6263\u5B50 API Token \u4E0D\u80FD\u4E3A\u7A7A");this.token=e.trim()}async getWorkspaces(){let e="workspaces",t=this.cache.get(e);if(t)return g.debug("\u4ECE\u7F13\u5B58\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868"),t;g.info("\u83B7\u53D6\u6263\u5B50\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868");let r=await this.request("/v1/workspaces");if(r.code!==0)throw new ce(r.msg||"\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25","API_ERROR",void 0,r);let o=r.data.workspaces;return this.cache.set(e,o,"workspaces"),g.info(`\u6210\u529F\u83B7\u53D6 ${o.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),o}async getWorkflows(e){let{workspace_id:t,page_num:r=1,page_size:o=20}=e;if(!t||typeof t!="string")throw new Error("\u5DE5\u4F5C\u7A7A\u95F4ID\u4E0D\u80FD\u4E3A\u7A7A");let n=`workflows:${t}:${r}:${o}`,s=this.cache.get(n);if(s)return g.debug(`\u4ECE\u7F13\u5B58\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868: ${t}`),s;g.info(`\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684\u5DE5\u4F5C\u6D41\u5217\u8868 (\u9875\u7801: ${r}, \u6BCF\u9875: ${o})`);let a=new URLSearchParams({workspace_id:t,page_num:r.toString(),page_size:o.toString(),workflow_mode:"workflow"}),l=await this.request(`/v1/workflows?${a}`);if(l.code!==0)throw new ce(l.msg||"\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25","API_ERROR",void 0,l);let h={items:l.data.items,hasMore:l.data.has_more};return this.cache.set(n,h,"workflows"),g.info(`\u6210\u529F\u83B7\u53D6 ${h.items.length} \u4E2A\u5DE5\u4F5C\u6D41\uFF0ChasMore: ${h.hasMore}`),h}async request(e){return Ts(async()=>{let t=`${this.API_BASE_URL}${e}`;g.debug(`\u53D1\u8D77\u6263\u5B50 API \u8BF7\u6C42: ${t}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.TIMEOUT);try{let n=await fetch(t,{headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},signal:r.signal});clearTimeout(o);let s;try{s=await n.json()}catch(a){throw g.error("\u89E3\u6790\u54CD\u5E94 JSON \u5931\u8D25:",a),new ce("\u54CD\u5E94\u6570\u636E\u683C\u5F0F\u9519\u8BEF","PARSE_ERROR",n.status)}if(!n.ok)throw Es(n,s);return s}catch(n){throw clearTimeout(o),n instanceof Error&&n.name==="AbortError"?new ce(`\u8BF7\u6C42\u8D85\u65F6 (${this.TIMEOUT}ms)`,"TIMEOUT",void 0):n}},this.RETRY_ATTEMPTS)}clearCache(e){this.cache.clear(e),g.info(`\u6E05\u9664\u6263\u5B50 API \u7F13\u5B58${e?` (\u6A21\u5F0F: ${e})`:""}`)}getCacheStats(){return this.cache.getStats()}}});function It(i,e){return{success:!0,data:i,message:e}}function A(i,e,t){return{success:!1,message:i,error:e?{code:e,details:t}:void 0}}function $t(){let i=d.getCozeToken();if(!i)throw new Error("\u6263\u5B50 API Token \u672A\u914D\u7F6E\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E platforms.coze.token");return new Rt(i)}var Te,xo=m(()=>{"use strict";S();Y();$o();c(It,"createSuccessResponse");c(A,"createErrorResponse");c($t,"getCozeApiService");Te=class{static{c(this,"CozeApiHandler")}static async getWorkspaces(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=await $t().getWorkspaces();return g.info(`\u6210\u529F\u83B7\u53D6 ${r.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),e.json(It({workspaces:r}))}catch(t){return g.error("\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25:",t),t instanceof Error&&t.code==="AUTH_FAILED"?e.json(A("\u6263\u5B50 API \u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 Token \u914D\u7F6E","AUTH_FAILED"),401):t instanceof Error&&t.code==="RATE_LIMITED"?e.json(A("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(A("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async getWorkflows(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let t=e.req.query("workspace_id"),r=Number.parseInt(e.req.query("page_num")||"1",10),o=Number.parseInt(e.req.query("page_size")||"20",10);if(!t)return g.warn("\u7F3A\u5C11 workspace_id \u53C2\u6570"),e.json(A("\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570: workspace_id","MISSING_PARAMETER"),400);if(r<1||r>1e3)return e.json(A("page_num \u5FC5\u987B\u5728 1-1000 \u4E4B\u95F4","INVALID_PARAMETER"),400);if(o<1||o>100)return e.json(A("page_size \u5FC5\u987B\u5728 1-100 \u4E4B\u95F4","INVALID_PARAMETER"),400);let n={workspace_id:t,page_num:r,page_size:o},a=await $t().getWorkflows(n);g.info(`\u6210\u529F\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684 ${a.items.length} \u4E2A\u5DE5\u4F5C\u6D41`);let l=d.getCustomMCPTools(),h=a.items.map(u=>{let p=l.find(C=>C.handler.type==="proxy"&&C.handler.platform==="coze"&&C.handler.config.workflow_id===u.workflow_id);return{...u,isAddedAsTool:!!p,toolName:p?.name||null}});return g.info(`\u5DE5\u4F5C\u6D41\u5DE5\u5177\u72B6\u6001\u68C0\u67E5\u5B8C\u6210\uFF0C\u5171 ${h.filter(u=>u.isAddedAsTool).length} \u4E2A\u5DE5\u4F5C\u6D41\u5DF2\u6DFB\u52A0\u4E3A\u5DE5\u5177`),e.json(It({items:h,has_more:a.hasMore,page_num:r,page_size:o,total_count:a.items.length}))}catch(t){return g.error("\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25:",t),t instanceof Error&&t.code==="AUTH_FAILED"?e.json(A("\u6263\u5B50 API \u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 Token \u914D\u7F6E","AUTH_FAILED"),401):t instanceof Error&&t.code==="RATE_LIMITED"?e.json(A("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(A("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async clearCache(e){try{if(g.info("\u5904\u7406\u6E05\u9664\u6263\u5B50 API \u7F13\u5B58\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let t=e.req.query("pattern"),r=$t(),o=r.getCacheStats();r.clearCache(t);let n=r.getCacheStats();return g.info(`\u7F13\u5B58\u6E05\u9664\u5B8C\u6210\uFF0C\u6E05\u9664\u524D: ${o.size} \u9879\uFF0C\u6E05\u9664\u540E: ${n.size} \u9879`),e.json(It({cleared:o.size-n.size,remaining:n.size,pattern:t||"all"},"\u7F13\u5B58\u6E05\u9664\u6210\u529F"))}catch(t){return g.error("\u6E05\u9664\u7F13\u5B58\u5931\u8D25:",t),e.json(A(t instanceof Error?t.message:"\u6E05\u9664\u7F13\u5B58\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async getCacheStats(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=$t().getCacheStats();return e.json(It(r))}catch(t){return g.error("\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:",t),e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}}});var xt,Oo=m(()=>{"use strict";S();et();xt=class{static{c(this,"HeartbeatHandler")}logger;statusService;notificationService;configService;constructor(e,t){this.logger=g.withTag("HeartbeatHandler"),this.statusService=e,this.notificationService=t,this.configService=new ae}async handleClientStatus(e,t,r){try{this.logger.debug(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0: ${r}`,t.data);let o={...t.data,lastHeartbeat:Date.now()};this.statusService.updateClientInfo(o,`websocket-${r}`),await this.sendLatestConfig(e,r),this.logger.debug(`\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u6210\u529F: ${r}`)}catch(o){this.logger.error(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25: ${r}`,o),this.sendError(e,"CLIENT_STATUS_ERROR",o instanceof Error?o.message:"\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25")}}async sendLatestConfig(e,t){try{let o={type:"configUpdate",data:await this.configService.getConfig(),timestamp:Date.now()};e.send(JSON.stringify(o)),this.logger.debug(`\u6700\u65B0\u914D\u7F6E\u5DF2\u53D1\u9001\u7ED9\u5BA2\u6237\u7AEF: ${t}`)}catch(r){this.logger.error(`\u53D1\u9001\u6700\u65B0\u914D\u7F6E\u5931\u8D25: ${t}`,r)}}sendError(e,t,r){try{let o={type:"error",error:{code:t,message:r,timestamp:Date.now()}};e.send(JSON.stringify(o))}catch(o){this.logger.error("\u53D1\u9001\u9519\u8BEF\u6D88\u606F\u5931\u8D25:",o)}}checkHeartbeatTimeout(){let e=this.statusService.getLastHeartbeat(),t=Date.now();e&&t-e>35e3&&(this.logger.warn("\u5BA2\u6237\u7AEF\u5FC3\u8DF3\u8D85\u65F6\uFF0C\u6807\u8BB0\u4E3A\u65AD\u5F00\u8FDE\u63A5"),this.statusService.updateClientInfo({status:"disconnected"},"heartbeat-timeout"))}startHeartbeatMonitoring(){return this.logger.info("\u542F\u52A8\u5FC3\u8DF3\u76D1\u63A7"),setInterval(()=>{this.checkHeartbeatTimeout(),this.cleanupDisconnectedClients()},1e4)}cleanupDisconnectedClients(){try{this.notificationService.cleanupDisconnectedClients()}catch(e){this.logger.error("\u6E05\u7406\u65AD\u5F00\u8FDE\u63A5\u7684\u5BA2\u6237\u7AEF\u5931\u8D25:",e)}}stopHeartbeatMonitoring(e){this.logger.info("\u505C\u6B62\u5FC3\u8DF3\u76D1\u63A7"),clearInterval(e)}getHeartbeatStats(){return{lastHeartbeat:this.statusService.getLastHeartbeat(),isConnected:this.statusService.isClientConnected(),clientStats:this.notificationService.getClientStats()}}handleClientConnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5EFA\u7ACB: ${e}`),this.statusService.updateClientInfo({status:"connected",lastHeartbeat:Date.now()},`websocket-connect-${e}`)}handleClientDisconnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u65AD\u5F00: ${e}`),this.statusService.updateClientInfo({status:"disconnected"},`websocket-disconnect-${e}`)}sendHeartbeatResponse(e,t){try{let r={type:"heartbeatResponse",data:{timestamp:Date.now(),status:"ok"}};e.send(JSON.stringify(r)),this.logger.debug(`\u5FC3\u8DF3\u54CD\u5E94\u5DF2\u53D1\u9001: ${t}`)}catch(r){this.logger.error(`\u53D1\u9001\u5FC3\u8DF3\u54CD\u5E94\u5931\u8D25: ${t}`,r)}}validateHeartbeatMessage(e){return e&&typeof e=="object"&&e.type==="clientStatus"&&e.data&&typeof e.data=="object"}}});import{randomUUID as Ms}from"crypto";var Ot,Ao=m(()=>{"use strict";S();gr();Pt();Ot=class{static{c(this,"MCPRouteHandler")}logger;mcpMessageHandler=null;clients=new Map;config;metrics;cleanupInterval=null;startTime;constructor(e={}){this.logger=g.withTag("MCPRouteHandler"),this.config={maxClients:e.maxClients??100,connectionTimeout:e.connectionTimeout??3e5,heartbeatInterval:e.heartbeatInterval??3e4,maxMessageSize:e.maxMessageSize??1024*1024,enableMetrics:e.enableMetrics??!0},this.metrics={totalConnections:0,activeConnections:0,totalMessages:0,errorCount:0,averageResponseTime:0,uptime:0},this.startTime=new Date,this.startCleanupTask(),this.logger.info("MCPRouteHandler \u521D\u59CB\u5316\u5B8C\u6210",{maxClients:this.config.maxClients,connectionTimeout:this.config.connectionTimeout,heartbeatInterval:this.config.heartbeatInterval})}startCleanupTask(){this.cleanupInterval=setInterval(()=>{this.cleanupStaleConnections(),this.updateMetrics()},6e4)}stopCleanupTask(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}cleanupStaleConnections(){let e=new Date,t=[];for(let[r,o]of this.clients.entries())(e.getTime()-o.lastActivity.getTime()>this.config.connectionTimeout||!o.isAlive)&&t.push(r);for(let r of t)this.logger.info(`\u6E05\u7406\u8FC7\u671F\u8FDE\u63A5: ${r}`),this.handleClientDisconnect(r,"cleanup");t.length>0&&this.logger.info(`\u6E05\u7406\u4E86 ${t.length} \u4E2A\u8FC7\u671F\u8FDE\u63A5`)}updateMetrics(){this.config.enableMetrics&&(this.metrics.activeConnections=this.clients.size,this.metrics.uptime=Date.now()-this.startTime.getTime(),this.logger.debug("\u8FDE\u63A5\u7EDF\u8BA1",{activeConnections:this.metrics.activeConnections,totalConnections:this.metrics.totalConnections,totalMessages:this.metrics.totalMessages,errorCount:this.metrics.errorCount}))}async initializeMessageHandler(){if(!this.mcpMessageHandler)try{let e=await V.getInstance();this.mcpMessageHandler=new De(e),this.logger.info("MCP \u6D88\u606F\u5904\u7406\u5668\u521D\u59CB\u5316\u6210\u529F")}catch(e){throw this.logger.error("MCP \u6D88\u606F\u5904\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",e),this.metrics.errorCount++,e}}async handlePost(e){let t=Date.now(),r=null;try{this.logger.debug("\u5904\u7406 MCP POST \u8BF7\u6C42");let o=e.req.query("sessionId");if(o)return await this.handleSSEMessage(e,o);let n=e.req.header("content-length");if(n&&Number.parseInt(n)>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Request too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);if(!e.req.header("content-type")?.includes("application/json"))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Content-Type must be application/json",null);let a=e.req.header("mcp-protocol-version")||e.req.header("MCP-Protocol-Version")||e.req.header("Mcp-Protocol-Version"),l=["2024-11-05","2025-06-18"];a&&!l.includes(a)&&this.logger.warn(`\u4E0D\u652F\u6301\u7684 MCP \u534F\u8BAE\u7248\u672C: ${a}\uFF0C\u652F\u6301\u7684\u7248\u672C: ${l.join(", ")}`);let h;try{let C=await e.req.text();if(C.length>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);h=JSON.parse(C),r=h.id||null}catch{return this.metrics.errorCount++,this.createErrorResponse(-32700,"Parse error: Invalid JSON",null)}if(!this.validateMessage(h))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Message does not conform to JSON-RPC 2.0",r);await this.initializeMessageHandler();let u=await this.mcpMessageHandler.handleMessage(h);this.metrics.totalMessages++;let p=Date.now()-t;return this.metrics.averageResponseTime=(this.metrics.averageResponseTime*(this.metrics.totalMessages-1)+p)/this.metrics.totalMessages,this.logger.debug("MCP POST \u8BF7\u6C42\u5904\u7406\u6210\u529F",{method:h.method,messageId:r,responseTime:p,isNotification:u===null}),u===null?new Response(null,{status:204,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":p.toString()}}):e.json(u,200,{"Content-Type":"application/json","MCP-Protocol-Version":"2024-11-05","X-Response-Time":p.toString()})}catch(o){this.metrics.errorCount++;let n=Date.now()-t;this.logger.error("\u5904\u7406 MCP POST \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:o instanceof Error?o.message:String(o),messageId:r,responseTime:n,stack:o instanceof Error?o.stack:void 0});let s=o instanceof Error?o.message:String(o);return this.createErrorResponse(-32603,`Internal error: ${s}`,r)}}async handleSSEMessage(e,t){let r=Date.now(),o=null;try{this.logger.debug(`\u5904\u7406 SSE \u6D88\u606F (\u4F1A\u8BDD: ${t})`);let n=this.clients.get(t);if(!n)return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Invalid or missing sessionId",null);n.lastActivity=new Date;let s=e.req.header("content-length");if(s&&Number.parseInt(s)>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);let a;try{let u=await e.req.text();if(u.length>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);a=JSON.parse(u),o=a.id||null}catch{return this.metrics.errorCount++,this.createErrorResponse(-32700,"Parse error: Invalid JSON",null)}if(!this.validateMessage(a))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Message does not conform to JSON-RPC 2.0",o);await this.initializeMessageHandler();let l=await this.mcpMessageHandler.handleMessage(a);if(n.messageCount++,this.metrics.totalMessages++,l!==null&&n.writer&&n.isAlive)try{await this.sendSSEEvent(n.writer,"message",JSON.stringify(l))}catch(u){this.logger.warn(`SSE \u5199\u5165\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${t}`,u),n.isAlive=!1}let h=Date.now()-r;return this.logger.debug(`SSE \u6D88\u606F\u5904\u7406\u5B8C\u6210 (\u4F1A\u8BDD: ${t})`,{method:a.method,messageId:o,responseTime:h,messageCount:n.messageCount,isNotification:l===null}),new Response(null,{status:202,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":h.toString()}})}catch(n){this.metrics.errorCount++;let s=Date.now()-r;this.logger.error(`\u5904\u7406 SSE \u6D88\u606F\u65F6\u51FA\u9519 (\u4F1A\u8BDD: ${t}):`,{error:n instanceof Error?n.message:String(n),messageId:o,responseTime:s,stack:n instanceof Error?n.stack:void 0});let a=n instanceof Error?n.message:String(n);return this.createErrorResponse(-32603,`Internal error: ${a}`,o)}}async handleGet(e){try{if(this.logger.debug("\u5904\u7406 MCP GET \u8BF7\u6C42\uFF08SSE \u8FDE\u63A5\uFF09"),this.clients.size>=this.config.maxClients)return this.metrics.errorCount++,e.json({jsonrpc:"2.0",error:{code:-32e3,message:"Server busy: Maximum client connections reached",data:{maxClients:this.config.maxClients}},id:null},503);let t=Date.now().toString(),r=Ms(),o=new Date,n=e.req.header("user-agent"),s=e.req.header("x-forwarded-for")||e.req.header("x-real-ip")||"unknown";this.logger.info(`SSE \u5BA2\u6237\u7AEF\u8FDE\u63A5: ${t} (\u4F1A\u8BDD: ${r})`,{userAgent:n,remoteAddress:s});let{readable:a,writable:l}=new TransformStream,h=l.getWriter(),u=new AbortController,p={id:t,sessionId:r,response:new Response(a),connectedAt:o,lastActivity:o,writer:h,abortController:u,isAlive:!0,messageCount:0,userAgent:n,remoteAddress:s};this.clients.set(r,p),this.metrics.totalConnections++,this.metrics.activeConnections=this.clients.size;try{await this.sendSSEEvent(h,"connected",JSON.stringify({sessionId:r,endpoint:`/mcp?sessionId=${r}`,timestamp:o.toISOString(),protocolVersion:"2024-11-05"}))}catch(b){this.logger.error(`\u521D\u59CB SSE \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25: ${r}`,b),p.isAlive=!1}this.startHeartbeat(p);let C=new Response(a,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no","MCP-Protocol-Version":"2024-11-05","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type, MCP-Protocol-Version"}}),T=c(()=>{this.handleClientDisconnect(r,t)},"handleDisconnect");return e.req.raw.signal?.addEventListener("abort",T),u.signal.addEventListener("abort",T),C}catch(t){return this.metrics.errorCount++,this.logger.error("\u5904\u7406 MCP GET \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),e.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"},id:null},500)}}startHeartbeat(e){e.heartbeatInterval&&clearInterval(e.heartbeatInterval),e.heartbeatInterval=setInterval(async()=>{if(!e.isAlive||!e.writer){this.stopHeartbeat(e);return}try{await this.sendSSEEvent(e.writer,"heartbeat",JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId})),this.logger.debug(`\u5FC3\u8DF3\u53D1\u9001\u6210\u529F: ${e.sessionId}`)}catch(t){this.logger.warn(`\u5FC3\u8DF3\u53D1\u9001\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${e.sessionId}`,t),e.isAlive=!1,this.stopHeartbeat(e)}},this.config.heartbeatInterval)}stopHeartbeat(e){e.heartbeatInterval&&(clearInterval(e.heartbeatInterval),e.heartbeatInterval=void 0)}async sendSSEEvent(e,t,r){try{let o=`event: ${t}
|
|
38
|
+
`);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];Se(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||{}))if(s.taskId===e){s.status="completed",s.result=t,s.timestamp=new Date().toISOString(),s.consumed=!1;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||{}))if(s.taskId===e){s.status="failed",s.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${t.message}`}]},s.timestamp=new Date().toISOString(),s.consumed=!0;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.info(`[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||{}))Se(n)&&(e.customMCPResults?.[o]&&delete e.customMCPResults[o],t=!0,r++,n.taskId&&this.activeTasks.delete(n.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 de(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]}}}});import{SSEClientTransport as ao}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as An}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as kn}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{EventSource as Dn}from"eventsource";function Nn(){return g}function _n(i){switch(Nn().info(`[TransportFactory] \u521B\u5EFA ${i.type} transport for ${i.name}`),i.type){case"stdio":return Ln(i);case"sse":return Hn(i);case"modelscope-sse":return zn(i);case"streamable-http":return jn(i);default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function Ln(i){if(!i.command)throw new Error("stdio transport \u9700\u8981 command \u914D\u7F6E");return new An({command:i.command,args:i.args||[],env:i.env})}function Hn(i){if(!i.url)throw new Error("SSE transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=Un(i);return new ao(e,t)}function zn(i){if(!i.url)throw new Error("ModelScope SSE transport \u9700\u8981 URL \u914D\u7F6E");if(!i.apiKey)throw new Error("ModelScope SSE transport \u9700\u8981 apiKey \u914D\u7F6E");let e=new URL(i.url),t=Fn(i);return new ao(e,t)}function jn(i){if(!i.url)throw new Error("StreamableHTTP transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=Wn(i);return new kn(e,t)}function Un(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function Fn(i){let e=i.apiKey;return i.customSSEOptions?i.customSSEOptions:{eventSourceInit:{fetch:c(async(t,r)=>{let o={...r?.headers,Authorization:`Bearer ${e}`};return fetch(t,{...r,headers:o})},"fetch")},requestInit:{headers:{Authorization:`Bearer ${e}`,...i.headers}}}}function Wn(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function Vn(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)throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B type \u5B57\u6BB5");switch(i.type){case"stdio":if(!i.command)throw new Error("stdio \u7C7B\u578B\u9700\u8981 command \u5B57\u6BB5");break;case"sse":case"streamable-http":if(!i.url)throw new Error(`${i.type} \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5`);break;case"modelscope-sse":if(!i.url)throw new Error("modelscope-sse \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5");if(!i.apiKey)throw new Error("modelscope-sse \u7C7B\u578B\u9700\u8981 apiKey \u5B57\u6BB5\u3002\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E modelscope.apiKey \u6216\u786E\u4FDD\u670D\u52A1\u914D\u7F6E\u5305\u542B apiKey");break;default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function Bn(){return["stdio","sse","modelscope-sse","streamable-http"]}var cr,co=m(()=>{"use strict";S();St();typeof global<"u"&&!global.EventSource&&(global.EventSource=Dn);c(Nn,"getLogger");c(_n,"createTransport");c(Ln,"createStdioTransport");c(Hn,"createSSETransport");c(zn,"createModelScopeSSETransport");c(jn,"createStreamableHTTPTransport");c(Un,"createSSEOptions");c(Fn,"createModelScopeSSEOptions");c(Wn,"createStreamableHTTPOptions");c(Vn,"validateConfig");c(Bn,"getSupportedTypes");cr={create:_n,validateConfig:Vn,getSupportedTypes:Bn}});import{Client as qn}from"@modelcontextprotocol/sdk/client/index.js";var Ke,yt,St=m(()=>{"use strict";S();co();Ke=(o=>(o.STDIO="stdio",o.SSE="sse",o.STREAMABLE_HTTP="streamable-http",o.MODELSCOPE_SSE="modelscope-sse",o))(Ke||{}),yt=class{static{c(this,"MCPService")}config;client=null;transport=null;tools=new Map;connectionState="disconnected";reconnectOptions;reconnectState;logger;connectionTimeout=null;initialized=!1;pingOptions;pingTimer=null;pingFailureCount=0;lastPingTime=null;isPinging=!1;constructor(e,t){this.config=e,this.logger=g,this.validateConfig(),this.reconnectOptions={enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:1e4,jitter:!0,...t?.reconnect,...e.reconnect},this.pingOptions={enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3,...e.ping},this.reconnectState={attempts:0,nextInterval:this.reconnectOptions.initialInterval,timer:null,lastError:null,isManualDisconnect:!1}}logWithTag(e,t,...r){let o=`[MCP-${this.config.name}] ${t}`;this.logger[e](o,...r)}validateConfig(){cr.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.reconnectState.isManualDisconnect=!1,this.attemptConnection()}async attemptConnection(){return this.connectionState="connecting",this.logWithTag("info",`\u6B63\u5728\u8FDE\u63A5 MCP \u670D\u52A1: ${this.config.name} (\u5C1D\u8BD5 ${this.reconnectState.attempts+1}/${this.reconnectOptions.maxAttempts})`),new Promise((e,t)=>{this.connectionTimeout=setTimeout(()=>{let r=new Error(`\u8FDE\u63A5\u8D85\u65F6 (${this.reconnectOptions.timeout}ms)`);this.handleConnectionError(r),t(r)},this.reconnectOptions.timeout);try{this.client=new qn({name:`xiaozhi-${this.config.name}-client`,version:"1.0.0"},{capabilities:{tools:{}}}),this.transport=cr.create(this.config),this.client.connect(this.transport).then(async()=>{this.handleConnectionSuccess(),await this.refreshTools(),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,this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.lastError=null,this.resetPingState(),this.logWithTag("info",`MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5\u5DF2\u5EFA\u7ACB`),this.startPingMonitoring()}handleConnectionError(e){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.reconnectState.lastError=e,this.logger.error(`MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5\u9519\u8BEF:`,e.message),this.cleanupConnection(),this.shouldReconnect()?this.scheduleReconnect():(this.connectionState="failed",this.logger.warn(`${this.config.name} \u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8FDE\u6B21\u6570 (${this.reconnectOptions.maxAttempts})\uFF0C\u505C\u6B62\u91CD\u8FDE`))}shouldReconnect(){return this.reconnectOptions.enabled&&this.reconnectState.attempts<this.reconnectOptions.maxAttempts&&!this.reconnectState.isManualDisconnect}scheduleReconnect(){this.connectionState="reconnecting",this.reconnectState.attempts++,this.calculateNextInterval(),this.logger.info(`${this.config.name} \u5C06\u5728 ${this.reconnectState.nextInterval}ms \u540E\u8FDB\u884C\u7B2C ${this.reconnectState.attempts} \u6B21\u91CD\u8FDE`),this.reconnectState.timer&&clearTimeout(this.reconnectState.timer),this.reconnectState.timer=setTimeout(async()=>{try{await this.attemptConnection()}catch{}},this.reconnectState.nextInterval)}calculateNextInterval(){let e;switch(this.reconnectOptions.backoffStrategy){case"fixed":e=this.reconnectOptions.initialInterval;break;case"linear":e=this.reconnectOptions.initialInterval+this.reconnectState.attempts*this.reconnectOptions.backoffMultiplier*1e3;break;case"exponential":e=this.reconnectOptions.initialInterval*this.reconnectOptions.backoffMultiplier**(this.reconnectState.attempts-1);break;default:e=this.reconnectOptions.initialInterval}if(e=Math.min(e,this.reconnectOptions.maxInterval),this.reconnectOptions.jitter){let t=e*.1,r=(Math.random()-.5)*2*t;e+=r}this.reconnectState.nextInterval=Math.max(e,1e3)}cleanupConnection(){if(this.stopPingMonitoring(),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}stopReconnect(){this.reconnectState.timer&&(clearTimeout(this.reconnectState.timer),this.reconnectState.timer=null)}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);this.logger.info(`${this.config.name} \u670D\u52A1\u52A0\u8F7D\u4E86 ${t.length} \u4E2A\u5DE5\u5177: ${t.map(r=>r.name).join(", ")}`)}catch(e){throw this.logger.error(`${this.config.name} \u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25:`,e instanceof Error?e.message:String(e)),e}}async disconnect(){this.logger.info(`\u4E3B\u52A8\u65AD\u5F00 MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5`),this.reconnectState.isManualDisconnect=!0,this.stopPingMonitoring(),this.stopReconnect(),this.cleanupConnection(),this.connectionState="disconnected"}async reconnect(){this.logger.info(`\u624B\u52A8\u91CD\u8FDE MCP \u670D\u52A1 ${this.config.name}`),this.stopReconnect(),this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.isManualDisconnect=!1,this.cleanupConnection(),await this.connect()}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`);this.logger.info(`\u8C03\u7528 ${this.config.name} \u670D\u52A1\u7684\u5DE5\u5177 ${e}\uFF0C\u53C2\u6570:`,JSON.stringify(t));try{let r=await this.client.callTool({name:e,arguments:t||{}});return this.logger.info(`\u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F\uFF0C\u7ED3\u679C:`,`${JSON.stringify(r).substring(0,500)}...`),r}catch(r){throw this.logger.error(`\u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,r instanceof Error?r.message:String(r)),r}}getConfig(){return this.config}getStatus(){return{name:this.config.name,connected:this.connectionState==="connected",initialized:this.initialized,transportType:this.config.type,toolCount:this.tools.size,lastError:this.reconnectState.lastError?.message,reconnectAttempts:this.reconnectState.attempts,connectionState:this.connectionState,pingEnabled:this.pingOptions.enabled,lastPingTime:this.lastPingTime||void 0,pingFailureCount:this.pingFailureCount,isPinging:this.isPinging}}isConnected(){return this.connectionState==="connected"&&this.initialized}enableReconnect(){this.reconnectOptions.enabled=!0,this.logger.info(`${this.config.name} \u81EA\u52A8\u91CD\u8FDE\u5DF2\u542F\u7528`)}disableReconnect(){this.reconnectOptions.enabled=!1,this.stopReconnect(),this.logger.info(`${this.config.name} \u81EA\u52A8\u91CD\u8FDE\u5DF2\u7981\u7528`)}updateReconnectOptions(e){this.reconnectOptions={...this.reconnectOptions,...e},this.logger.info(`${this.config.name} \u91CD\u8FDE\u914D\u7F6E\u5DF2\u66F4\u65B0`,e)}getReconnectOptions(){return{...this.reconnectOptions}}resetReconnectState(){this.stopReconnect(),this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.lastError=null,this.logger.info(`${this.config.name} \u91CD\u8FDE\u72B6\u6001\u5DF2\u91CD\u7F6E`)}startPingMonitoring(){!this.pingOptions.enabled||this.pingTimer||!this.isConnected()||(this.logger.info(`${this.config.name} \u542F\u52A8ping\u76D1\u63A7\uFF0C\u95F4\u9694: ${this.pingOptions.interval}ms`),setTimeout(()=>{this.isConnected()&&!this.pingTimer&&(this.pingTimer=setInterval(()=>{this.performPing()},this.pingOptions.interval))},this.pingOptions.startDelay))}stopPingMonitoring(){this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null,this.logger.debug(`${this.config.name} \u505C\u6B62ping\u76D1\u63A7`))}async performPing(){if(!this.client||this.isPinging||!this.isConnected())return;this.isPinging=!0;let e=performance.now();try{this.logger.debug(`${this.config.name} \u53D1\u9001ping\u8BF7\u6C42\uFF08\u901A\u8FC7listTools\u68C0\u6D4B\u8FDE\u63A5\uFF09`);let t=this.client.listTools(),r=new Promise((n,s)=>{setTimeout(()=>{s(new Error(`Ping\u8D85\u65F6 (${this.pingOptions.timeout}ms)`))},this.pingOptions.timeout)});await Promise.race([t,r]);let o=performance.now()-e;this.handlePingSuccess(o)}catch(t){let r=performance.now()-e;this.handlePingFailure(t,r)}finally{this.isPinging=!1}}handlePingSuccess(e){this.pingFailureCount=0,this.lastPingTime=new Date,this.logger.debug(`${this.config.name} ping\u6210\u529F\uFF0C\u5EF6\u8FDF: ${e.toFixed(2)}ms`)}handlePingFailure(e,t){if(this.pingFailureCount++,this.logger.warn(`${this.config.name} ping\u5931\u8D25 (${this.pingFailureCount}/${this.pingOptions.maxFailures})\uFF0C\u5EF6\u8FDF: ${t.toFixed(2)}ms\uFF0C\u9519\u8BEF: ${e.message}`),this.pingFailureCount>=this.pingOptions.maxFailures){this.logger.error(`${this.config.name} \u8FDE\u7EEDping\u5931\u8D25\u8FBE\u5230\u9608\u503C\uFF0C\u89E6\u53D1\u91CD\u8FDE\u673A\u5236`),this.stopPingMonitoring();let r=new Error(`Ping\u68C0\u6D4B\u5931\u8D25\uFF0C\u8FDE\u7EED\u5931\u8D25${this.pingFailureCount}\u6B21\uFF0C\u8FDE\u63A5\u53EF\u80FD\u5DF2\u65AD\u5F00`);this.handleConnectionError(r)}}resetPingState(){this.pingFailureCount=0,this.lastPingTime=null,this.isPinging=!1}enablePing(){this.pingOptions.enabled=!0,this.logger.info(`${this.config.name} ping\u76D1\u63A7\u5DF2\u542F\u7528`),this.isConnected()&&this.startPingMonitoring()}disablePing(){this.pingOptions.enabled=!1,this.stopPingMonitoring(),this.logger.info(`${this.config.name} ping\u76D1\u63A7\u5DF2\u7981\u7528`)}updatePingOptions(e){let t=this.pingOptions.enabled;this.pingOptions={...this.pingOptions,...e},this.logger.info(`${this.config.name} ping\u914D\u7F6E\u5DF2\u66F4\u65B0`,e),t!==this.pingOptions.enabled&&(this.pingOptions.enabled&&this.isConnected()?this.startPingMonitoring():this.pingOptions.enabled||this.stopPingMonitoring())}getPingOptions(){return{...this.pingOptions}}}});var Tt,lo=m(()=>{"use strict";S();Tt=class{static{c(this,"ToolSyncManager")}configManager;logger;syncLocks=new Map;constructor(e,t=g){this.configManager=e,this.logger=t.withTag("ToolSync")}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(l=>l.name)),a=o.filter(l=>!s.has(`${e}__${l.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}`,l=n.get(a),h=r[s.name];if(l&&h&&(!l.stats||!l.stats.usageCount&&!l.stats.lastUsedTime)){let u={};h.usageCount!==void 0&&(u.usageCount=h.usageCount),h.lastUsedTime&&(u.lastUsedTime=h.lastUsedTime),Object.keys(u).length>0&&(await this.updateCustomMCPToolStats(a,u),this.logger.debug(`\u5DF2\u540C\u6B65\u5DE5\u5177 ${a} \u7684\u7EDF\u8BA1\u4FE1\u606F: ${JSON.stringify(u)}`))}}}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}}}});var Ze,go,lr=m(()=>{"use strict";S();Y();io();Ct();St();lo();Ze=class{static{c(this,"MCPServiceManager")}services=new Map;configs={};logger;tools=new Map;customMCPHandler;cacheManager;toolSyncManager;constructor(e){this.logger=g,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 ge(r),this.customMCPHandler=new vt,this.toolSyncManager=new Tt(d,this.logger)}async startAllServices(){this.logger.info("[MCPManager] \u6B63\u5728\u542F\u52A8\u6240\u6709 MCP \u670D\u52A1...");try{this.customMCPHandler.initialize(),this.logger.info("[MCPManager] CustomMCP \u5904\u7406\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(t){this.logger.error("[MCPManager] CustomMCP \u5904\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",t)}let e=Object.entries(this.configs);if(e.length===0){this.logger.warn("[MCPManager] \u6CA1\u6709\u914D\u7F6E\u4EFB\u4F55 MCP \u670D\u52A1\uFF0C\u8BF7\u4F7F\u7528 addServiceConfig() \u6DFB\u52A0\u670D\u52A1\u914D\u7F6E");return}for(let[t]of e)await this.startService(t);this.logger.info("[MCPManager] \u6240\u6709 MCP \u670D\u52A1\u542F\u52A8\u5B8C\u6210")}async startService(e){this.logger.info(`[MCPManager] \u542F\u52A8 MCP \u670D\u52A1: ${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 yt(t);await r.connect(),this.services.set(e,r),await this.refreshToolsCache();let o=r.getTools();await this.toolSyncManager.syncToolsAfterConnection(e,o),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u542F\u52A8\u6210\u529F\uFF0C\u52A0\u8F7D\u4E86 ${o.length} \u4E2A\u5DE5\u5177:`,o.map(n=>n.name).join(", "))}catch(r){throw this.logger.error(`[MCPManager] \u542F\u52A8 ${e} \u670D\u52A1\u5931\u8D25:`,r.message),r}}async stopService(e){this.logger.info(`[MCPManager] \u505C\u6B62 MCP \u670D\u52A1: ${e}`);let t=this.services.get(e);if(!t){this.logger.warn(`[MCPManager] \u670D\u52A1 ${e} \u4E0D\u5B58\u5728\u6216\u672A\u542F\u52A8`);return}try{await t.disconnect(),this.services.delete(e),await this.refreshToolsCache(),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u5DF2\u505C\u6B62`)}catch(r){throw this.logger.error(`[MCPManager] \u505C\u6B62 ${e} \u670D\u52A1\u5931\u8D25:`,r.message),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(()=>{this.logger.debug(`[MCPManager] \u5DF2\u5C06 ${e} \u5DE5\u5177\u5217\u8868\u5199\u5165\u7F13\u5B58`)}).catch(n=>{this.logger.warn(`[MCPManager] \u5199\u5165\u7F13\u5B58\u5931\u8D25: ${e}, \u9519\u8BEF: ${n instanceof Error?n.message:String(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=[];if(d.getCustomMCPConfig()!==null){this.logger.info("[MCPManager] \u68C0\u6D4B\u5230\u65B0\u7248\u672C\u914D\u7F6E\uFF0C\u4F7F\u7528 customMCP \u5DE5\u5177\u5217\u8868");try{let r=this.customMCPHandler.getTools();for(let o of r)e.push({name:o.name,description:o.description||"",inputSchema:o.inputSchema,serviceName:this.getServiceNameForTool(o),originalName:o.name});this.logger.info(`[MCPManager] \u65B0\u7248\u672C\u914D\u7F6E\u8FD4\u56DE ${e.length} \u4E2A\u5DE5\u5177 (\u4EC5\u6765\u81EA customMCP.tools)`)}catch(r){this.logger.error("[MCPManager] \u83B7\u53D6 customMCP \u5DE5\u5177\u5931\u8D25:",r)}}else{this.logger.info("[MCPManager] \u68C0\u6D4B\u5230\u8001\u7248\u672C\u914D\u7F6E\uFF0C\u4F7F\u7528\u517C\u5BB9\u6A21\u5F0F\u5904\u7406");let r=new Set;try{let o=this.customMCPHandler.getTools();for(let n of o){let s=n.name;r.has(s)||(r.add(s),e.push({name:s,description:n.description||"",inputSchema:n.inputSchema,serviceName:"customMCP",originalName:n.name}))}o.length>0&&this.logger.info(`[MCPManager] \u6DFB\u52A0\u4E86 ${o.length} \u4E2A customMCP \u5DE5\u5177`)}catch(o){this.logger.error("[MCPManager] \u83B7\u53D6 CustomMCP \u5DE5\u5177\u5931\u8D25:",o)}for(let[o,n]of this.tools){if(r.has(o))continue;d.isToolEnabled(n.serviceName,n.originalName)&&(r.add(o),e.push({name:o,description:n.tool.description||"",inputSchema:n.tool.inputSchema,serviceName:n.serviceName,originalName:n.originalName}))}this.logger.info(`[MCPManager] \u8001\u7248\u672C\u914D\u7F6E\u8FD4\u56DE\u603B\u8BA1 ${e.length} \u4E2A\u5DE5\u5177 (customMCP \u4F18\u5148\uFF0C\u53BB\u91CD\u540E\u603B\u6570)`)}return e}getServiceNameForTool(e){return e.handler?.type==="mcp"?e.handler.config.serviceName:"customMCP"}async callTool(e,t){if(this.logger.info(`[MCPManager] \u8C03\u7528\u5DE5\u5177: ${e}\uFF0C\u53C2\u6570:`,t),this.customMCPHandler.hasTool(e)){let n=this.customMCPHandler.getToolInfo(e);if(n?.handler?.type==="mcp")try{let s=await this.callMCPTool(e,n.handler.config,t);return this.updateToolStats(e,n.handler.config.serviceName,n.handler.config.toolName,!0).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),s}catch(s){throw this.updateToolStatsForFailedCall(e,n.handler.config.serviceName,n.handler.config.toolName,s).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),s}try{let s=await this.customMCPHandler.callTool(e,t);return this.updateToolStats(e,"customMCP",e,!0).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),this.logger.info(`[MCPManager] CustomMCP \u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F`),s}catch(s){throw this.updateToolStatsForFailedCall(e,"customMCP",e,s).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),this.logger.error(`[MCPManager] CustomMCP \u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,s.message),s}}let r=this.tools.get(e);if(!r)throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);let o=this.services.get(r.serviceName);if(!o)throw new Error(`\u670D\u52A1 ${r.serviceName} \u4E0D\u53EF\u7528`);if(!o.isConnected())throw new Error(`\u670D\u52A1 ${r.serviceName} \u672A\u8FDE\u63A5`);try{let n=await o.callTool(r.originalName,t||{});return this.updateToolStats(e,r.serviceName,r.originalName,!0).catch(s=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,s)}),this.logger.info(`[MCPManager] \u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F\uFF0C\u7ED3\u679C:`,n),n}catch(n){throw this.updateToolStatsForFailedCall(e,r.serviceName,r.originalName,n).catch(s=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,s)}),this.logger.error(`[MCPManager] \u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,n.message),n}}async updateToolStats(e,t,r,o){try{if(!o)return;let n=new Date().toISOString();await this.updateCustomMCPToolStats(e,n),t!=="customMCP"&&await this.updateMCPServerToolStats(t,r,n),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u4FE1\u606F`)}catch(n){throw this.logger.error(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,n),n}}async updateToolStatsForFailedCall(e,t,r,o){try{let n=new Date().toISOString();await this.updateCustomMCPToolLastUsedTime(e,n),t!=="customMCP"&&await this.updateMCPServerToolLastUsedTime(t,r,n),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0\u5DE5\u5177 ${e} \u7684\u5931\u8D25\u8C03\u7528\u7EDF\u8BA1\u4FE1\u606F`)}catch(n){throw this.logger.error(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u8C03\u7528\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,n),n}}async updateCustomMCPToolStats(e,t){try{await d.updateToolUsageStatsWithLock(e,!0),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u4F7F\u7528\u7EDF\u8BA1`)}catch(r){throw this.logger.error(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u7EDF\u8BA1\u5931\u8D25:`,r),r}}async updateCustomMCPToolLastUsedTime(e,t){try{await d.updateToolUsageStatsWithLock(e,!1),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u6700\u540E\u4F7F\u7528\u65F6\u95F4`)}catch(r){throw this.logger.error(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u6700\u540E\u4F7F\u7528\u65F6\u95F4\u5931\u8D25:`,r),r}}async updateMCPServerToolStats(e,t,r){try{await d.updateMCPServerToolStatsWithLock(e,t,r,!0),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1`)}catch(o){throw this.logger.error(`[MCPManager] \u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u5931\u8D25:`,o),o}}async updateMCPServerToolLastUsedTime(e,t,r){try{await d.updateMCPServerToolStatsWithLock(e,t,r,!1),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u6700\u540E\u4F7F\u7528\u65F6\u95F4`)}catch(o){throw this.logger.error(`[MCPManager] \u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u6700\u540E\u4F7F\u7528\u65F6\u95F4\u5931\u8D25:`,o),o}}async callMCPTool(e,t,r){let{serviceName:o,toolName:n}=t;this.logger.info(`[MCPManager] \u8C03\u7528 MCP \u540C\u6B65\u5DE5\u5177 ${e} -> ${o}.${n}`);let 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{let a=await s.callTool(n,r||{});return this.logger.info(`[MCPManager] MCP \u540C\u6B65\u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F`),a}catch(a){throw this.logger.error(`[MCPManager] MCP \u540C\u6B65\u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,a.message),a}}hasTool(e){return this.customMCPHandler.hasTool(e)?!0:this.tools.has(e)}async stopAllServices(){this.logger.info("[MCPManager] \u6B63\u5728\u505C\u6B62\u6240\u6709 MCP \u670D\u52A1...");for(let[e,t]of this.services)try{await t.disconnect(),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u5DF2\u505C\u6B62`)}catch(r){this.logger.error(`[MCPManager] \u505C\u6B62 ${e} \u670D\u52A1\u5931\u8D25:`,r.message)}try{this.customMCPHandler.cleanup(),this.logger.info("[MCPManager] CustomMCP \u5904\u7406\u5668\u5DF2\u6E05\u7406")}catch(e){this.logger.error("[MCPManager] CustomMCP \u5904\u7406\u5668\u6E05\u7406\u5931\u8D25:",e)}try{d.clearAllStatsUpdateLocks(),this.logger.info("[MCPManager] \u7EDF\u8BA1\u66F4\u65B0\u9501\u5DF2\u6E05\u7406")}catch(e){this.logger.error("[MCPManager] \u6E05\u7406\u7EDF\u8BA1\u66F4\u65B0\u9501\u5931\u8D25:",e)}this.services.clear(),this.tools.clear(),this.logger.info("[MCPManager] \u6240\u6709 MCP \u670D\u52A1\u5DF2\u505C\u6B62")}getStatus(){let e=this.customMCPHandler.getToolCount(),t=this.tools.size+e,r=Array.from(this.tools.keys()),o=this.customMCPHandler.getToolNames(),n=[...r,...o],s={services:{},totalTools:t,availableTools:n};for(let[a,l]of this.services){let h=l.getStatus();s.services[a]={connected:h.connected,clientName:`xiaozhi-${a}-client`}}return e>0&&(s.services.customMCP={connected:!0,clientName:"xiaozhi-customMCP-handler"}),s}getStatsUpdateInfo(){try{let e=d.getStatsUpdateLocks();return{activeLocks:e,totalLocks:e.length}}catch(e){return this.logger.warn("[MCPManager] \u83B7\u53D6\u7EDF\u8BA1\u66F4\u65B0\u76D1\u63A7\u4FE1\u606F\u5931\u8D25:",e),{activeLocks:[],totalLocks:0}}}getService(e){return this.services.get(e)}getAllServices(){return new Map(this.services)}getCustomMCPHandler(){return this.customMCPHandler}hasCustomMCPTool(e){return this.customMCPHandler.hasTool(e)}getCustomMCPTools(){return this.customMCPHandler.getTools()}enhanceServiceConfig(e){let t={...e};try{if(e.type==="modelscope-sse"){let r=d.getModelScopeApiKey();if(r)t.apiKey=r,this.logger.info(`[MCPManager] \u4E3A ${e.name} \u670D\u52A1\u6DFB\u52A0 ModelScope API Key`);else throw this.logger.warn(`[MCPManager] ${e.name} \u670D\u52A1\u9700\u8981 ModelScope API Key\uFF0C\u4F46\u672A\u5728\u914D\u7F6E\u4E2D\u627E\u5230`),new Error(`ModelScope SSE \u670D\u52A1 ${e.name} \u9700\u8981 API Key\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E modelscope.apiKey`)}return t}catch(r){throw this.logger.error(`[MCPManager] \u914D\u7F6E\u589E\u5F3A\u5931\u8D25: ${e.name}`,r),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,this.logger.info(`[MCPManager] \u5DF2\u6DFB\u52A0\u670D\u52A1\u914D\u7F6E: ${o}`)}updateServiceConfig(e,t){let r=this.enhanceServiceConfig(t);this.configs[e]=r,this.logger.info(`[MCPManager] \u5DF2\u66F4\u65B0\u5E76\u589E\u5F3A\u670D\u52A1\u914D\u7F6E: ${e}`)}removeServiceConfig(e){delete this.configs[e],this.logger.info(`[MCPManager] \u5DF2\u79FB\u9664\u670D\u52A1\u914D\u7F6E: ${e}`)}async syncToolsConfigToFile(){try{this.logger.debug("[MCPManager] \u5F00\u59CB\u540C\u6B65\u5DE5\u5177\u914D\u7F6E\u5230\u914D\u7F6E\u6587\u4EF6");let e=d.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 p of o){let C=n[p.name];C?s[p.name]={...C,description:p.description||C.description||""}:s[p.name]={description:p.description||"",enable:!0}}let a=o.map(p=>p.name),h=Object.keys(n).filter(p=>!a.includes(p));if(h.length>0&&this.logger.info(`[MCPManager] \u68C0\u6D4B\u5230\u670D\u52A1 ${t} \u79FB\u9664\u4E86 ${h.length} \u4E2A\u5DE5\u5177: ${h.join(", ")}`),this.hasToolsConfigChanged(n,s)){d.updateServerToolsConfig(t,s);let p=Object.keys(s).filter(T=>!n[T]),C=Object.keys(s).filter(T=>{let b=n[T],B=s[T];return b&&b.description!==B.description});this.logger.info(`[MCPManager] \u5DF2\u540C\u6B65\u670D\u52A1 ${t} \u7684\u5DE5\u5177\u914D\u7F6E:`),p.length>0&&this.logger.info(` - \u65B0\u589E\u5DE5\u5177: ${p.join(", ")}`),C.length>0&&this.logger.info(` - \u66F4\u65B0\u5DE5\u5177: ${C.join(", ")}`),h.length>0&&this.logger.info(` - \u79FB\u9664\u5DE5\u5177: ${h.join(", ")}`)}}this.logger.debug("[MCPManager] \u5DE5\u5177\u914D\u7F6E\u540C\u6B65\u5B8C\u6210")}catch(e){this.logger.error("[MCPManager] \u540C\u6B65\u5DE5\u5177\u914D\u7F6E\u5230\u914D\u7F6E\u6587\u4EF6\u5931\u8D25:",e)}}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 l=e[a],h=t[a];if(l.description!==h.description)return!0}return!1}},go=Ze});var De,gr=m(()=>{"use strict";S();De=class{static{c(this,"MCPMessageHandler")}logger;serviceManager;constructor(e){this.serviceManager=e,this.logger=g}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.info("\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.info(`\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.info("\u6536\u5230 initialized \u901A\u77E5\uFF0C\u5BA2\u6237\u7AEF\u521D\u59CB\u5316\u5B8C\u6210",e),null}async handleToolsList(e){this.logger.info("\u5904\u7406 tools/list \u8BF7\u6C42");try{let r=this.serviceManager.getAllTools().map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema}));return this.logger.info(`\u8FD4\u56DE ${r.length} \u4E2A\u5DE5\u5177`),{jsonrpc:"2.0",result:{tools:r},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){this.logger.info(`\u5904\u7406 tools/call \u8BF7\u6C42: ${e.name}`,e);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 this.logger.info(`\u5DE5\u5177 ${e.name} \u8C03\u7528\u6210\u529F`),{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.info("\u5904\u7406 resources/list \u8BF7\u6C42");let t=[];return this.logger.info(`\u8FD4\u56DE ${t.length} \u4E2A\u8D44\u6E90`),{jsonrpc:"2.0",result:{resources:t},id:e!==void 0?e:1}}async handlePromptsList(e){this.logger.info("\u5904\u7406 prompts/list \u8BF7\u6C42");let t=[];return this.logger.info(`\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}}});import{EventEmitter as ho}from"events";var hr,ur,Et,uo=m(()=>{"use strict";S();lr();Ge();gr();hr=class{static{c(this,"ToolRegistry")}serviceManager;logger;constructor(e){this.serviceManager=e,this.logger=g}async initialize(){this.logger.info("\u521D\u59CB\u5316\u5DE5\u5177\u6CE8\u518C\u8868")}getAllTools(){return this.serviceManager.getAllTools().map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema,serviceName:e.serviceName,originalName:e.originalName}))}findTool(e){return this.getAllTools().find(r=>r.name===e)||null}hasTool(e){return this.findTool(e)!==null}},ur=class extends ho{static{c(this,"ConnectionManager")}connections=new Map;logger;constructor(){super(),this.logger=g}async initialize(){this.logger.info("\u521D\u59CB\u5316\u8FDE\u63A5\u7BA1\u7406\u5668")}registerConnection(e,t,r){let o={id:e,transportName:t,state:r,connectedAt:new Date,lastActivity:new Date};this.connections.set(e,o),this.emit("connectionRegistered",o),this.logger.debug(`\u8FDE\u63A5\u5DF2\u6CE8\u518C: ${e} (${t})`)}updateConnectionState(e,t){let r=this.connections.get(e);r&&(r.state=t,r.lastActivity=new Date,this.emit("connectionStateChanged",r),this.logger.debug(`\u8FDE\u63A5\u72B6\u6001\u66F4\u65B0: ${e} -> ${t}`))}removeConnection(e){let t=this.connections.get(e);t&&(this.connections.delete(e),this.emit("connectionRemoved",t),this.logger.debug(`\u8FDE\u63A5\u5DF2\u79FB\u9664: ${e}`))}getAllConnections(){return Array.from(this.connections.values())}getActiveConnectionCount(){return Array.from(this.connections.values()).filter(e=>e.state==="connected").length}async closeAllConnections(){this.logger.info("\u5173\u95ED\u6240\u6709\u8FDE\u63A5"),this.connections.clear(),this.emit("allConnectionsClosed")}},Et=class extends ho{static{c(this,"UnifiedMCPServer")}serviceManager;messageHandler;transportAdapters=new Map;toolRegistry;connectionManager;isRunning=!1;logger;config;constructor(e={}){super(),this.config={name:"UnifiedMCPServer",enableLogging:!0,logLevel:"info",maxConnections:100,connectionTimeout:3e4,...e},this.logger=g,this.serviceManager=new Ze,this.messageHandler=new De(this.serviceManager),this.toolRegistry=new hr(this.serviceManager),this.connectionManager=new ur,this.setupEventListeners()}setupEventListeners(){this.connectionManager.on("connectionRegistered",e=>{this.emit("connectionRegistered",e)}),this.connectionManager.on("connectionStateChanged",e=>{this.emit("connectionStateChanged",e)}),this.connectionManager.on("connectionRemoved",e=>{this.emit("connectionRemoved",e)})}async initialize(){this.logger.info("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{await this.serviceManager.startAllServices(),await this.toolRegistry.initialize(),await this.connectionManager.initialize(),this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210"),this.emit("initialized")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5931\u8D25",e),e}}async registerTransport(e,t){if(this.transportAdapters.has(e))throw new Error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u5DF2\u5B58\u5728`);this.logger.info(`\u6CE8\u518C\u4F20\u8F93\u9002\u914D\u5668: ${e}`);try{await t.initialize(),this.transportAdapters.set(e,t),this.connectionManager.registerConnection(t.getConnectionId(),e,t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u6CE8\u518C\u6210\u529F`),this.emit("transportRegistered",{name:e,adapter:t})}catch(r){throw this.logger.error(`\u6CE8\u518C\u4F20\u8F93\u9002\u914D\u5668 ${e} \u5931\u8D25`,r),r}}async start(){if(this.isRunning)throw new Error("\u670D\u52A1\u5668\u5DF2\u5728\u8FD0\u884C");this.logger.info("\u542F\u52A8\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{for(let[e,t]of this.transportAdapters)try{await t.start(),this.connectionManager.updateConnectionState(t.getConnectionId(),t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u542F\u52A8\u6210\u529F`)}catch(r){throw this.logger.error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u542F\u52A8\u5931\u8D25`,r),r}this.isRunning=!0,this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F"),this.emit("started")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u542F\u52A8\u5931\u8D25",e),e}}async stop(){if(this.isRunning){this.logger.info("\u505C\u6B62\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{for(let[e,t]of this.transportAdapters)try{await t.stop(),this.connectionManager.updateConnectionState(t.getConnectionId(),t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u505C\u6B62\u6210\u529F`)}catch(r){this.logger.error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u505C\u6B62\u5931\u8D25`,r)}await this.connectionManager.closeAllConnections(),await this.serviceManager.stopAllServices(),this.isRunning=!1,this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u505C\u6B62\u6210\u529F"),this.emit("stopped")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u505C\u6B62\u5931\u8D25",e),e}}}getServiceManager(){return this.serviceManager}getToolRegistry(){return this.toolRegistry}getConnectionManager(){return this.connectionManager}getMessageHandler(){return this.messageHandler}getStatus(){return{isRunning:this.isRunning,transportCount:this.transportAdapters.size,activeConnections:this.connectionManager.getActiveConnectionCount(),toolCount:this.toolRegistry.getAllTools().length,config:this.config}}getTransportAdapters(){return new Map(this.transportAdapters)}isServerRunning(){return this.isRunning}}});async function po(i={name:"http"}){g.info("\u521B\u5EFA HTTP \u6A21\u5F0F\u670D\u52A1\u5668");let e=new Et;await e.initialize();let t=e.getMessageHandler(),r=new pt(t,i);return await e.registerTransport("http",r),g.info("HTTP \u6A21\u5F0F\u670D\u52A1\u5668\u521B\u5EFA\u6210\u529F"),e}var mo=m(()=>{"use strict";S();Xr();Kr();Zr();uo();c(po,"createHTTPServer")});var fo={};F(fo,{MCPServer:()=>pr});import{EventEmitter as Gn}from"events";var D,pr,Co=m(()=>{"use strict";S();ut();Y();mo();D=new Ie,pr=class extends Gn{static{c(this,"MCPServer")}unifiedServer=null;proxyMCPServer=null;port;isStarted=!1;constructor(e=3e3){super(),this.port=e}async initializeUnifiedServer(){if(!this.unifiedServer){D.info("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{let e={name:"http",port:this.port,host:"0.0.0.0",enableSSE:!0,enableRPC:!0};this.unifiedServer=await po(e),this.unifiedServer.on("started",()=>this.emit("started")),this.unifiedServer.on("stopped",()=>this.emit("stopped")),this.unifiedServer.on("connectionRegistered",t=>{this.emit("connectionRegistered",t)}),D.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw D.error("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u5931\u8D25",e),e}}}async initializeMCPClient(){try{let e=null;try{d.configExists()&&(e=d.getMcpEndpoints().find(r=>r&&!r.includes("<\u8BF7\u586B\u5199"))||null)}catch(t){D.warn("\u4ECE\u914D\u7F6E\u4E2D\u8BFB\u53D6\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25:",t)}e?(this.proxyMCPServer=new pe(e),this.unifiedServer&&this.proxyMCPServer.setServiceManager(this.unifiedServer.getServiceManager()),await this.proxyMCPServer.connect(),D.info("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F")):D.info("\u672A\u914D\u7F6E\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u8DF3\u8FC7\u8FDE\u63A5")}catch(e){D.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}}async start(){if(this.isStarted){D.warn("\u670D\u52A1\u5668\u5DF2\u542F\u52A8");return}try{D.info("\u542F\u52A8 MCP \u670D\u52A1\u5668"),await this.initializeUnifiedServer(),this.unifiedServer&&await this.unifiedServer.start(),this.initializeMCPClient().catch(e=>{D.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}),this.isStarted=!0,this.emit("started"),D.info("MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F")}catch(e){throw D.error("\u542F\u52A8 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}async stop(){if(!this.isStarted){D.warn("\u670D\u52A1\u5668\u672A\u542F\u52A8");return}try{D.info("\u505C\u6B62 MCP \u670D\u52A1\u5668"),this.unifiedServer&&await this.unifiedServer.stop(),this.proxyMCPServer&&(this.proxyMCPServer.disconnect(),this.proxyMCPServer=null),this.isStarted=!1,this.emit("stopped"),D.info("MCP \u670D\u52A1\u5668\u5DF2\u505C\u6B62")}catch(e){throw D.error("\u505C\u6B62 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}getServiceManager(){return this.unifiedServer?.getServiceManager()||null}getMessageHandler(){return this.unifiedServer?.getMessageHandler()||null}getStatus(){return this.unifiedServer?{...this.unifiedServer.getStatus(),port:this.port,mode:"mcp-server",proxyConnected:this.proxyMCPServer!==null}:{isRunning:!1,port:this.port,mode:"mcp-server"}}isRunning(){return this.isStarted&&(this.unifiedServer?.isServerRunning()||!1)}}});import{isAbsolute as Jn,resolve as Xn}from"path";function vo(i,e){Mt.debug(`\u8F6C\u6362\u914D\u7F6E: ${i}`,e);try{if(!i||typeof i!="string")throw new L("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!e||typeof e!="object")throw new L("\u914D\u7F6E\u5BF9\u8C61\u4E0D\u80FD\u4E3A\u7A7A",i);let t=Kn(i,e);return ss(t),Mt.info(`\u914D\u7F6E\u8F6C\u6362\u6210\u529F: ${i} -> ${t.type}`),t}catch(t){throw Mt.error(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${i}`,t),t instanceof L?t:new L(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,i)}}function Kn(i,e){if(ts(e))return Zn(i,e);if(rs(e))return Yn(i,e);if(os(e))return Qn(i,e);throw new L("\u65E0\u6CD5\u8BC6\u522B\u7684\u914D\u7F6E\u7C7B\u578B",i)}function Zn(i,e){if(!e.command)throw new L("\u672C\u5730\u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5",i);let t=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),r=(e.args||[]).map(o=>{if(es(o)){let n=Xn(t,o);return Mt.debug(`\u89E3\u6790\u76F8\u5BF9\u8DEF\u5F84: ${o} -> ${n}`),n}return o});return{name:i,type:"stdio",command:e.command,args:r,env:e.env,reconnect:{enabled:!0,maxAttempts:5,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:1e4,jitter:!0},ping:{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3},timeout:3e4}}function Yn(i,e){if(!e.url)throw new L("SSE \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);let t=ns(e.url),r={name:i,type:t?"modelscope-sse":"sse",url:e.url,reconnect:{enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:15e3,jitter:!0},ping:{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3},timeout:3e4};return t&&(r.modelScopeAuth=!0),r}function Qn(i,e){if(!e.url)throw new L("Streamable HTTP \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);return{name:i,type:"streamable-http",url:e.url,reconnect:{enabled:!0,maxAttempts:5,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:15e3,jitter:!0},ping:{enabled:!1,interval:6e4,timeout:1e4,maxFailures:3,startDelay:1e4},timeout:3e4}}function es(i){return Jn(i)?!1:!!(i.startsWith("./")||i.startsWith("../")||/\.(js|py|ts|mjs|cjs)$/i.test(i))}function ts(i){return"command"in i&&typeof i.command=="string"}function rs(i){return"type"in i&&i.type==="sse"&&"url"in i}function os(i){return"url"in i&&(!("type"in i)||i.type==="streamable-http")}function ns(i){return i.includes("modelscope.net")||i.includes("modelscope.cn")}function ss(i){if(!i.name||typeof i.name!="string")throw new L("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(!Object.values(Ke).includes(i.type))throw new L(`\u65E0\u6548\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`);switch(i.type){case"stdio":if(!i.command)throw new L("STDIO \u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5");break;case"sse":case"modelscope-sse":case"streamable-http":if(!i.url)throw new L(`${i.type} \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5`);break;default:throw new L(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}var Mt,L,So=m(()=>{"use strict";S();St();Mt=g.withTag("ConfigAdapter"),L=class extends Error{constructor(t,r){super(t);this.configName=r;this.name="ConfigValidationError"}static{c(this,"ConfigValidationError")}};c(vo,"convertLegacyToNew");c(Kn,"convertByConfigType");c(Zn,"convertLocalConfig");c(Yn,"convertSSEConfig");c(Qn,"convertStreamableHTTPConfig");c(es,"isRelativePath");c(ts,"isLocalConfig");c(rs,"isSSEConfig");c(os,"isStreamableHTTPConfig");c(ns,"isModelScopeURL");c(ss,"validateNewConfig")});async function is(){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),new go}async function yo(){if(se&&z==="initialized")return se;if(Q&&z==="initializing")return Q;z==="failed"&&dr(),z="initializing",Q=is();try{return se=await Q,z="initialized",Ne=`mcp-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,Ye=null,console.log(`\u2705 MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${Ne}`),se}catch(i){throw z="failed",Ye=i,Q=null,console.error("\u274C MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",i.message),i}}async function To(){if(z==="cleanup"){console.log("\u26A0\uFE0F MCPServiceManager \u5355\u4F8B\u5DF2\u5728\u6E05\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u91CD\u590D\u6E05\u7406");return}console.log("\u{1F9F9} \u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B\u8D44\u6E90..."),z="cleanup";try{if(Q){try{await(await Q).stopAllServices()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}Q=null}se&&(await se.stopAllServices(),se=null),z="not_initialized",Ye=null,Ne=null,console.log("\u2705 MCPServiceManager \u5355\u4F8B\u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(i){throw console.error("\u274C MCPServiceManager \u5355\u4F8B\u6E05\u7406\u5931\u8D25:",i.message),dr(),i}}function dr(){console.log("\u{1F504} \u91CD\u7F6E MCPServiceManager \u5355\u4F8B\u72B6\u6001"),se=null,Q=null,z="not_initialized",Ye=null,Ne=null}function as(){return z==="initialized"&&se!==null}function cs(){return{state:z,initializationTime:Ne?new Date:void 0,lastError:Ye||void 0,instanceId:Ne||void 0}}async function ls(){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),await To(),yo()}function gs(){return se}async function hs(){if(z==="initialized")return!0;if(z==="initializing"&&Q)try{return await Q,!0}catch{return!1}return!1}var se,Q,z,Ye,Ne,V,Pt=m(()=>{"use strict";lr();se=null,Q=null,z="not_initialized",Ye=null,Ne=null;c(is,"createInstance");c(yo,"getInstance");c(To,"cleanup");c(dr,"reset");c(as,"isInitialized");c(cs,"getStatus");c(ls,"forceReinitialize");c(gs,"getCurrentInstance");c(hs,"waitForInitialization");V={getInstance:yo,cleanup:To,reset:dr,isInitialized:as,getStatus:cs,forceReinitialize:ls,getCurrentInstance:gs,waitForInitialization:hs};process.on("exit",()=>{V.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B..."),V.reset())});process.on("uncaughtException",async i=>{console.error("\u{1F4A5} \u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u6E05\u7406 MCPServiceManager \u5355\u4F8B:",i);try{await V.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}});process.on("unhandledRejection",async i=>{console.error("\u{1F4A5} \u672A\u5904\u7406\u7684Promise\u62D2\u7EDD\uFF0C\u6E05\u7406 MCPServiceManager \u5355\u4F8B:",i);try{await V.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as us}from"events";var Eo,ps,wt,Mo=m(()=>{"use strict";S();ut();Eo=(o=>(o.EXPONENTIAL_BACKOFF="exponential_backoff",o.LINEAR_BACKOFF="linear_backoff",o.FIXED_INTERVAL="fixed_interval",o.ADAPTIVE="adaptive",o))(Eo||{}),ps={healthCheckInterval:3e4,reconnectInterval:5e3,maxReconnectAttempts:10,loadBalanceStrategy:"round-robin",connectionTimeout:1e4,reconnectStrategy:"exponential_backoff",maxReconnectDelay:3e4,reconnectBackoffMultiplier:2,jitterEnabled:!0},wt=class extends us{static{c(this,"XiaozhiConnectionManager")}connections=new Map;connectionStates=new Map;mcpServiceManager=null;logger;isInitialized=!1;isConnecting=!1;options;healthCheckInterval=null;reconnectTimers=new Map;roundRobinIndex=0;lastSelectedEndpoint=null;performanceMetrics={connectionStartTime:0,totalConnectionTime:0,averageConnectionTime:0,connectionCount:0,memoryUsage:{initial:0,current:0,peak:0},prewarmedConnections:new Set};constructor(e){super(),this.logger=g,this.options={...ps,...e},this.logger.info("[XiaozhiConnectionManager] \u5B9E\u4F8B\u5DF2\u521B\u5EFA"),this.logger.debug("[XiaozhiConnectionManager] \u914D\u7F6E\u9009\u9879:",this.options)}async initialize(e,t){if(this.isInitialized){this.logger.warn("XiaozhiConnectionManager \u5DF2\u7ECF\u521D\u59CB\u5316\uFF0C\u8DF3\u8FC7\u91CD\u590D\u521D\u59CB\u5316");return}this.logger.info(`\u5F00\u59CB\u521D\u59CB\u5316 XiaozhiConnectionManager\uFF0C\u7AEF\u70B9\u6570\u91CF: ${e.length}`);try{this.validateInitializeParams(e,t),await this.cleanup();for(let r of e)await this.createConnection(r,t);this.isInitialized=!0,this.performanceMetrics.memoryUsage.initial=process.memoryUsage().heapUsed,this.performanceMetrics.memoryUsage.current=this.performanceMetrics.memoryUsage.initial,this.performanceMetrics.memoryUsage.peak=this.performanceMetrics.memoryUsage.initial,this.logger.info(`XiaozhiConnectionManager \u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u7BA1\u7406 ${this.connections.size} \u4E2A\u8FDE\u63A5`)}catch(r){throw this.logger.error("XiaozhiConnectionManager \u521D\u59CB\u5316\u5931\u8D25:",r),await this.cleanup(),r}}async connect(){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 initialize()");if(this.isConnecting){this.logger.warn("\u8FDE\u63A5\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");return}this.isConnecting=!0,this.performanceMetrics.connectionStartTime=Date.now(),this.logger.info(`\u5F00\u59CB\u8FDE\u63A5\u6240\u6709\u7AEF\u70B9\uFF0C\u603B\u6570: ${this.connections.size}`);try{let e=[];for(let[s,a]of this.connections)e.push(this.connectSingleEndpoint(s,a));let t=await Promise.allSettled(e),r=t.filter(s=>s.status==="fulfilled").length,o=t.length-r,n=Date.now()-this.performanceMetrics.connectionStartTime;if(this.performanceMetrics.totalConnectionTime+=n,this.performanceMetrics.connectionCount++,this.performanceMetrics.averageConnectionTime=this.performanceMetrics.totalConnectionTime/this.performanceMetrics.connectionCount,this.logger.info(`\u8FDE\u63A5\u5B8C\u6210 - \u6210\u529F: ${r}, \u5931\u8D25: ${o}, \u8017\u65F6: ${n}ms`),r===0)throw new Error("\u6240\u6709\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25");this.startHealthCheck()}finally{this.isConnecting=!1}}async disconnect(){this.logger.info("\u5F00\u59CB\u65AD\u5F00\u6240\u6709\u8FDE\u63A5"),this.stopHealthCheck(),this.clearAllReconnectTimers();let e=[];for(let[t,r]of this.connections)e.push(this.disconnectSingleEndpoint(t,r));await Promise.allSettled(e),this.logger.info("\u6240\u6709\u8FDE\u63A5\u5DF2\u65AD\u5F00")}async addEndpoint(e){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316");if(this.connections.has(e)){this.logger.warn(`\u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728\uFF0C\u8DF3\u8FC7\u6DFB\u52A0`);return}this.logger.info(`\u52A8\u6001\u6DFB\u52A0\u7AEF\u70B9: ${e}`);try{let t=this.getCurrentTools();if(await this.createConnection(e,t),this.isAnyConnected()){let r=this.connections.get(e);await this.connectSingleEndpoint(e,r)}this.logger.info(`\u7AEF\u70B9 ${e} \u6DFB\u52A0\u6210\u529F`)}catch(t){throw this.logger.error(`\u6DFB\u52A0\u7AEF\u70B9 ${e} \u5931\u8D25:`,t),this.connections.delete(e),this.connectionStates.delete(e),t}}async removeEndpoint(e){if(!this.connections.has(e)){this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u79FB\u9664`);return}this.logger.info(`\u52A8\u6001\u79FB\u9664\u7AEF\u70B9: ${e}`);try{let t=this.connections.get(e);await this.disconnectSingleEndpoint(e,t),this.connections.delete(e),this.connectionStates.delete(e);let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e)),this.logger.info(`\u7AEF\u70B9 ${e} \u79FB\u9664\u6210\u529F`)}catch(t){throw this.logger.error(`\u79FB\u9664\u7AEF\u70B9 ${e} \u5931\u8D25:`,t),t}}getHealthyConnections(){let e=[];for(let[t,r]of this.connections){let o=this.connectionStates.get(t);o?.connected&&o.healthScore>50&&e.push(r)}return e}getConnectionStatus(){return Array.from(this.connectionStates.values())}isAnyConnected(){for(let e of this.connectionStates.values())if(e.connected)return!0;return!1}setServiceManager(e){this.mcpServiceManager=e,this.logger.info("\u5DF2\u8BBE\u7F6E MCPServiceManager"),this.connections.size>0&&this.syncToolsToAllConnections()}setHealthCheckEnabled(e,t){let r=this.connectionStates.get(e);r?(r.healthCheckEnabled=t,this.logger.info(`\u7AEF\u70B9 ${e} \u5065\u5EB7\u68C0\u67E5\u5DF2${t?"\u542F\u7528":"\u7981\u7528"}`)):this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u8BBE\u7F6E\u5065\u5EB7\u68C0\u67E5\u72B6\u6001`)}getHealthCheckStats(){let e={};for(let[t,r]of this.connectionStates){let o=r.totalRequests>0?r.successfulRequests/r.totalRequests*100:0;e[t]={endpoint:t,healthScore:r.healthScore,successRate:Math.round(o*100)/100,averageResponseTime:r.responseTime||0,consecutiveFailures:r.consecutiveFailures,lastHealthCheck:r.lastHealthCheck,lastSuccessTime:r.lastSuccessTime}}return e}async triggerHealthCheck(){this.logger.info("\u624B\u52A8\u89E6\u53D1\u5065\u5EB7\u68C0\u67E5"),await this.performHealthCheck()}async triggerReconnect(e){let t=this.connectionStates.get(e);if(!t)throw new Error(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(t.connected){this.logger.warn(`\u7AEF\u70B9 ${e} \u5DF2\u8FDE\u63A5\uFF0C\u65E0\u9700\u91CD\u8FDE`);return}this.logger.info(`\u624B\u52A8\u89E6\u53D1\u91CD\u8FDE: ${e}`);let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e)),await this.performReconnect(e)}stopReconnect(e){let t=this.connectionStates.get(e);if(!t){this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);return}let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e),t.isReconnecting=!1,t.nextReconnectTime=void 0,this.logger.info(`\u5DF2\u505C\u6B62\u7AEF\u70B9 ${e} \u7684\u91CD\u8FDE`))}stopAllReconnects(){this.logger.info("\u505C\u6B62\u6240\u6709\u7AEF\u70B9\u7684\u91CD\u8FDE");for(let[e]of this.reconnectTimers)this.stopReconnect(e)}getReconnectStats(){let e={};for(let[t,r]of this.connectionStates)e[t]={endpoint:t,reconnectAttempts:r.reconnectAttempts,isReconnecting:r.isReconnecting,nextReconnectTime:r.nextReconnectTime,lastReconnectAttempt:r.lastReconnectAttempt,reconnectDelay:r.reconnectDelay,errorType:r.errorType,recentReconnectHistory:r.reconnectHistory.slice(-5)};return e}validateEndpoints(e){let t=[],r=[];for(let o of e){if(!o||typeof o!="string"){r.push(o);continue}if(!o.startsWith("ws://")&&!o.startsWith("wss://")){r.push(o);continue}try{new URL(o),t.push(o)}catch{r.push(o)}}return{valid:t,invalid:r}}validateOptions(e){let t=[];if(e.healthCheckInterval!==void 0&&(typeof e.healthCheckInterval!="number"||e.healthCheckInterval<1e3)&&t.push("healthCheckInterval \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.reconnectInterval!==void 0&&(typeof e.reconnectInterval!="number"||e.reconnectInterval<100)&&t.push("reconnectInterval \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 100 \u7684\u6570\u5B57"),e.maxReconnectAttempts!==void 0&&(typeof e.maxReconnectAttempts!="number"||e.maxReconnectAttempts<0)&&t.push("maxReconnectAttempts \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 0 \u7684\u6570\u5B57"),e.connectionTimeout!==void 0&&(typeof e.connectionTimeout!="number"||e.connectionTimeout<1e3)&&t.push("connectionTimeout \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.maxReconnectDelay!==void 0&&(typeof e.maxReconnectDelay!="number"||e.maxReconnectDelay<1e3)&&t.push("maxReconnectDelay \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.reconnectBackoffMultiplier!==void 0&&(typeof e.reconnectBackoffMultiplier!="number"||e.reconnectBackoffMultiplier<1)&&t.push("reconnectBackoffMultiplier \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6570\u5B57"),e.loadBalanceStrategy!==void 0){let r=["round-robin","random","health-based"];r.includes(e.loadBalanceStrategy)||t.push(`loadBalanceStrategy \u5FC5\u987B\u662F\u4EE5\u4E0B\u503C\u4E4B\u4E00: ${r.join(", ")}`)}if(e.reconnectStrategy!==void 0){let r=Object.values(Eo);r.includes(e.reconnectStrategy)||t.push(`reconnectStrategy \u5FC5\u987B\u662F\u4EE5\u4E0B\u503C\u4E4B\u4E00: ${r.join(", ")}`)}return{valid:t.length===0,errors:t}}async updateEndpoints(e,t=[]){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316");this.logger.info(`\u66F4\u65B0\u7AEF\u70B9\u914D\u7F6E\uFF0C\u65B0\u7AEF\u70B9\u6570\u91CF: ${e.length}`);let{valid:r,invalid:o}=this.validateEndpoints(e);if(o.length>0&&this.logger.warn(`\u53D1\u73B0\u65E0\u6548\u7AEF\u70B9: ${o.join(", ")}`),r.length===0)throw new Error("\u6CA1\u6709\u6709\u6548\u7684\u7AEF\u70B9");let n=Array.from(this.connections.keys()),s=r.filter(h=>!n.includes(h)),a=n.filter(h=>!r.includes(h)),l=n.filter(h=>r.includes(h));this.logger.info(`\u7AEF\u70B9\u53D8\u66F4 - \u6DFB\u52A0: ${s.length}, \u79FB\u9664: ${a.length}, \u4FDD\u6301: ${l.length}`);try{for(let u of a)await this.removeEndpoint(u);for(let u of s)await this.addEndpoint(u);let h={type:s.length>0&&a.length>0?"endpoints_updated":s.length>0?"endpoints_added":"endpoints_removed",data:{added:s.length>0?s:void 0,removed:a.length>0?a:void 0,updated:s.length>0&&a.length>0?r:void 0},timestamp:new Date};this.emit("configChange",h),this.logger.info("\u7AEF\u70B9\u914D\u7F6E\u66F4\u65B0\u5B8C\u6210")}catch(h){throw this.logger.error("\u7AEF\u70B9\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",h),h}}updateOptions(e){this.logger.info("\u66F4\u65B0\u8FDE\u63A5\u9009\u9879");let{valid:t,errors:r}=this.validateOptions(e);if(!t)throw new Error(`\u65E0\u6548\u7684\u8FDE\u63A5\u9009\u9879: ${r.join(", ")}`);let o={...this.options};this.options={...this.options,...e};let n={type:"options_updated",data:{oldOptions:o,newOptions:e},timestamp:new Date};this.emit("configChange",n),this.logger.info("\u8FDE\u63A5\u9009\u9879\u66F4\u65B0\u5B8C\u6210"),this.logger.debug("\u65B0\u7684\u914D\u7F6E\u9009\u9879:",this.options)}getCurrentConfig(){return{endpoints:Array.from(this.connections.keys()),options:{...this.options}}}async reloadConfig(e){this.logger.info("\u5F00\u59CB\u70ED\u91CD\u8F7D\u914D\u7F6E");try{e.options&&this.updateOptions(e.options),e.endpoints&&await this.updateEndpoints(e.endpoints,e.tools||[]),this.logger.info("\u914D\u7F6E\u70ED\u91CD\u8F7D\u5B8C\u6210")}catch(t){throw this.logger.error("\u914D\u7F6E\u70ED\u91CD\u8F7D\u5931\u8D25:",t),t}}selectBestConnection(e=[]){let t=this.getHealthyConnections();if(t.length===0)return this.logger.warn("\u6CA1\u6709\u5065\u5EB7\u7684\u8FDE\u63A5\u53EF\u7528"),null;let r=t.filter(n=>{let s=this.getEndpointByConnection(n);return s&&!e.includes(s)});if(r.length===0)return this.logger.warn("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5\uFF08\u6392\u9664\u6307\u5B9A\u7AEF\u70B9\u540E\uFF09"),null;let o;switch(this.options.loadBalanceStrategy){case"round-robin":o=this.selectRoundRobin(r);break;case"random":o=this.selectRandom(r);break;case"health-based":o=this.selectHealthBased(r);break;default:o=this.selectRoundRobin(r)}return this.lastSelectedEndpoint=this.getEndpointByConnection(o),o}selectRoundRobin(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=e[this.roundRobinIndex%e.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%e.length,t}selectRandom(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=Math.floor(Math.random()*e.length);return e[t]}selectHealthBased(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=e.map(n=>{let s=this.getEndpointByConnection(n),a=s?this.connectionStates.get(s):null;return{connection:n,endpoint:s,healthScore:a?.healthScore||0,responseTime:a?.responseTime||Number.POSITIVE_INFINITY,successRate:a&&a.totalRequests>0?a.successfulRequests/a.totalRequests*100:0}});t.sort((n,s)=>n.healthScore!==s.healthScore?s.healthScore-n.healthScore:n.successRate!==s.successRate?s.successRate-n.successRate:n.responseTime-s.responseTime);let r=t.reduce((n,s)=>n+(s.healthScore+1),0),o=Math.random()*r;for(let n of t)if(o-=n.healthScore+1,o<=0)return n.connection;return t[0].connection}getEndpointByConnection(e){for(let[t,r]of this.connections)if(r===e)return t;return null}getLoadBalanceStats(){let e=this.getHealthyConnections(),t={};for(let[r,o]of this.connectionStates){let n=o.totalRequests>0?o.successfulRequests/o.totalRequests*100:0,s=o.healthScore+1;t[r]={healthScore:o.healthScore,responseTime:o.responseTime||0,successRate:Math.round(n*100)/100,weight:s}}return{strategy:this.options.loadBalanceStrategy,totalConnections:this.connections.size,healthyConnections:e.length,lastSelectedEndpoint:this.lastSelectedEndpoint,roundRobinIndex:this.roundRobinIndex,connectionWeights:t}}setLoadBalanceStrategy(e){let t=this.options.loadBalanceStrategy;this.options.loadBalanceStrategy=e,e==="round-robin"&&(this.roundRobinIndex=0),this.logger.info(`\u8D1F\u8F7D\u5747\u8861\u7B56\u7565\u5DF2\u4ECE ${t} \u5207\u6362\u5230 ${e}`);let r={type:"options_updated",data:{oldOptions:{loadBalanceStrategy:t},newOptions:{loadBalanceStrategy:e}},timestamp:new Date};this.emit("configChange",r)}async performFailover(e){this.logger.warn(`\u6267\u884C\u6545\u969C\u8F6C\u79FB\uFF0C\u5931\u8D25\u7AEF\u70B9: ${e}`);let t=this.selectBestConnection([e]);if(!t)return this.logger.error("\u6545\u969C\u8F6C\u79FB\u5931\u8D25\uFF1A\u6CA1\u6709\u53EF\u7528\u7684\u5907\u7528\u8FDE\u63A5"),null;let r=this.getEndpointByConnection(t);return this.logger.info(`\u6545\u969C\u8F6C\u79FB\u6210\u529F\uFF0C\u5207\u6362\u5230\u7AEF\u70B9: ${r}`),t}async prewarmConnections(e=[]){let t=e.length>0?e:Array.from(this.connections.keys());this.logger.info(`\u5F00\u59CB\u9884\u70ED\u8FDE\u63A5\uFF0C\u7AEF\u70B9\u6570\u91CF: ${t.length}`);let r=t.map(async o=>{if(this.performanceMetrics.prewarmedConnections.has(o)){this.logger.debug(`\u7AEF\u70B9 ${o} \u5DF2\u9884\u70ED\uFF0C\u8DF3\u8FC7`);return}try{this.connections.get(o)&&(await this.performHealthCheck(),this.performanceMetrics.prewarmedConnections.add(o),this.logger.debug(`\u7AEF\u70B9 ${o} \u9884\u70ED\u5B8C\u6210`))}catch(n){this.logger.warn(`\u7AEF\u70B9 ${o} \u9884\u70ED\u5931\u8D25:`,n)}});await Promise.all(r),this.logger.info(`\u8FDE\u63A5\u9884\u70ED\u5B8C\u6210\uFF0C\u6210\u529F\u9884\u70ED ${this.performanceMetrics.prewarmedConnections.size} \u4E2A\u7AEF\u70B9`)}updatePerformanceMetrics(){let e=process.memoryUsage().heapUsed;this.performanceMetrics.memoryUsage.current=e,e>this.performanceMetrics.memoryUsage.peak&&(this.performanceMetrics.memoryUsage.peak=e)}getPerformanceMetrics(){this.updatePerformanceMetrics();let e=this.performanceMetrics.memoryUsage.current-this.performanceMetrics.memoryUsage.initial,t=this.performanceMetrics.memoryUsage.initial>0?e/this.performanceMetrics.memoryUsage.initial*100:0;return{connectionTime:{total:this.performanceMetrics.totalConnectionTime,average:this.performanceMetrics.averageConnectionTime,count:this.performanceMetrics.connectionCount},memoryUsage:{initial:this.performanceMetrics.memoryUsage.initial,current:this.performanceMetrics.memoryUsage.current,peak:this.performanceMetrics.memoryUsage.peak,growth:e,growthPercentage:Math.round(t*100)/100},prewarmedConnections:this.performanceMetrics.prewarmedConnections.size,totalConnections:this.connections.size,healthyConnections:this.getHealthyConnections().length}}optimizeMemoryUsage(){this.logger.info("\u5F00\u59CB\u5185\u5B58\u4F18\u5316");for(let[,e]of this.connectionStates)if(e.reconnectHistory&&e.reconnectHistory.length>10&&(e.reconnectHistory=e.reconnectHistory.slice(-10)),e.totalRequests>1e4){let t=e.successfulRequests/e.totalRequests;e.totalRequests=1e3,e.successfulRequests=Math.round(t*1e3)}global.gc&&global.gc(),this.updatePerformanceMetrics(),this.logger.info("\u5185\u5B58\u4F18\u5316\u5B8C\u6210")}async cleanup(){this.logger.info("\u5F00\u59CB\u6E05\u7406 XiaozhiConnectionManager \u8D44\u6E90");try{await this.disconnect(),this.connections.clear(),this.connectionStates.clear(),this.isInitialized=!1,this.isConnecting=!1,this.roundRobinIndex=0,this.lastSelectedEndpoint=null,this.logger.info("XiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(e){throw this.logger.error("XiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5931\u8D25:",e),e}}validateInitializeParams(e,t){if(!Array.isArray(e)||e.length===0)throw new Error("\u7AEF\u70B9\u5217\u8868\u4E0D\u80FD\u4E3A\u7A7A");if(!Array.isArray(t))throw new Error("\u5DE5\u5177\u5217\u8868\u5FC5\u987B\u662F\u6570\u7EC4");for(let r of e){if(!r||typeof r!="string")throw new Error(`\u65E0\u6548\u7684\u7AEF\u70B9\u5730\u5740: ${r}`);if(!r.startsWith("ws://")&&!r.startsWith("wss://"))throw new Error(`\u7AEF\u70B9\u5730\u5740\u5FC5\u987B\u662F WebSocket URL: ${r}`)}}async createConnection(e,t){this.logger.debug(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B: ${e}`);try{let r=new pe(e);this.mcpServiceManager&&r.setServiceManager(this.mcpServiceManager),this.connections.set(e,r),this.connectionStates.set(e,{endpoint:e,connected:!1,initialized:!1,reconnectAttempts:0,healthScore:100,consecutiveFailures:0,totalRequests:0,successfulRequests:0,healthCheckEnabled:!0,isReconnecting:!1,reconnectDelay:this.options.reconnectInterval,reconnectHistory:[]}),this.logger.debug(`\u8FDE\u63A5\u5B9E\u4F8B\u521B\u5EFA\u6210\u529F: ${e}`)}catch(r){throw this.logger.error(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B\u5931\u8D25 ${e}:`,r),r}}async connectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(!r)throw new Error(`\u7AEF\u70B9\u72B6\u6001\u4E0D\u5B58\u5728: ${e}`);this.logger.debug(`\u8FDE\u63A5\u7AEF\u70B9: ${e}`);try{r.connected=!1,r.initialized=!1,await t.connect(),r.connected=!0,r.initialized=!0,r.lastConnected=new Date,r.lastError=void 0,r.reconnectAttempts=0,r.healthScore=100,this.logger.info(`\u7AEF\u70B9\u8FDE\u63A5\u6210\u529F: ${e}`)}catch(o){throw r.connected=!1,r.initialized=!1,r.lastError=o instanceof Error?o.message:String(o),r.reconnectAttempts++,r.healthScore=Math.max(0,r.healthScore-20),this.logger.error(`\u7AEF\u70B9\u8FDE\u63A5\u5931\u8D25 ${e}:`,o),this.scheduleReconnect(e),o}}async disconnectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(r){this.logger.debug(`\u65AD\u5F00\u7AEF\u70B9: ${e}`);try{t.disconnect(),r.connected=!1,r.initialized=!1,this.logger.debug(`\u7AEF\u70B9\u65AD\u5F00\u6210\u529F: ${e}`)}catch(o){this.logger.error(`\u7AEF\u70B9\u65AD\u5F00\u5931\u8D25 ${e}:`,o),r.connected=!1,r.initialized=!1}}}getCurrentTools(){if(!this.mcpServiceManager)return[];try{return this.mcpServiceManager.getAllTools()}catch(e){return this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25:",e),[]}}syncToolsToAllConnections(){if(this.mcpServiceManager){this.logger.debug("\u540C\u6B65\u5DE5\u5177\u5230\u6240\u6709\u8FDE\u63A5");for(let[e,t]of this.connections)try{t.setServiceManager(this.mcpServiceManager),this.logger.debug(`\u5DE5\u5177\u540C\u6B65\u6210\u529F: ${e}`)}catch(r){this.logger.error(`\u5DE5\u5177\u540C\u6B65\u5931\u8D25 ${e}:`,r)}}}startHealthCheck(){this.healthCheckInterval||(this.logger.debug(`\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\uFF0C\u95F4\u9694: ${this.options.healthCheckInterval}ms`),this.healthCheckInterval=setInterval(()=>{this.performHealthCheck()},this.options.healthCheckInterval))}stopHealthCheck(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null,this.logger.debug("\u5065\u5EB7\u68C0\u67E5\u5DF2\u505C\u6B62"))}async performHealthCheck(){this.logger.debug("\u6267\u884C\u5065\u5EB7\u68C0\u67E5");let e=[];for(let[t,r]of this.connectionStates)r.healthCheckEnabled&&e.push(this.performSingleHealthCheck(t,r));await Promise.allSettled(e)}async performSingleHealthCheck(e,t){let r=Date.now();t.lastHealthCheck=new Date,t.totalRequests++;try{let o=this.connections.get(e);if(!o)throw new Error(`\u8FDE\u63A5\u5B9E\u4F8B\u4E0D\u5B58\u5728: ${e}`);await this.checkConnectionHealth(o,e);let n=Date.now()-r;this.handleHealthCheckSuccess(t,n)}catch(o){let n=Date.now()-r;this.handleHealthCheckFailure(t,o,n)}}async checkConnectionHealth(e,t){if(!e)throw new Error("\u8FDE\u63A5\u5B9E\u4F8B\u4E0D\u5B58\u5728");if(await new Promise(o=>setTimeout(o,10)),!this.connectionStates.get(t)?.connected)throw new Error("\u8FDE\u63A5\u5DF2\u65AD\u5F00")}handleHealthCheckSuccess(e,t){e.successfulRequests++,e.consecutiveFailures=0,e.responseTime=t,e.lastSuccessTime=new Date,this.updateHealthScore(e,!0,t),this.logger.debug(`\u5065\u5EB7\u68C0\u67E5\u6210\u529F: ${e.endpoint}, \u54CD\u5E94\u65F6\u95F4: ${t}ms, \u5065\u5EB7\u5EA6: ${e.healthScore}`)}handleHealthCheckFailure(e,t,r){e.consecutiveFailures++,e.responseTime=r,e.lastError=t.message,this.updateHealthScore(e,!1,r),this.logger.warn(`\u5065\u5EB7\u68C0\u67E5\u5931\u8D25: ${e.endpoint}, \u9519\u8BEF: ${t.message}, \u8FDE\u7EED\u5931\u8D25: ${e.consecutiveFailures}, \u5065\u5EB7\u5EA6: ${e.healthScore}`),e.consecutiveFailures>=3&&e.connected&&this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8FDE\u7EED\u5931\u8D25 ${e.consecutiveFailures} \u6B21\uFF0C\u53EF\u80FD\u9700\u8981\u91CD\u8FDE`)}updateHealthScore(e,t,r){let o=e.healthScore;if(t){let n=5;r<100?n=10:r<500?n=7:r<1e3?n=5:n=2,e.healthScore=Math.min(100,o+n)}else{let n=15;e.consecutiveFailures>=5?n=30:e.consecutiveFailures>=3&&(n=20),e.healthScore=Math.max(0,o-n)}if(e.totalRequests>0){let n=e.successfulRequests/e.totalRequests;n<.5?e.healthScore=Math.max(0,e.healthScore-10):n>.9&&(e.healthScore=Math.min(100,e.healthScore+5))}}classifyConnectionError(e){let t=e.message.toLowerCase();return t.includes("timeout")||t.includes("timed out")?"timeout_error":t.includes("network")||t.includes("connection refused")||t.includes("econnrefused")||t.includes("enotfound")?"network_error":t.includes("auth")||t.includes("unauthorized")||t.includes("forbidden")||t.includes("401")||t.includes("403")?"authentication_error":t.includes("server")||t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")?"server_error":"unknown_error"}calculateReconnectDelay(e){let t=this.options.reconnectInterval,r=this.options.maxReconnectDelay,o=this.options.reconnectBackoffMultiplier,n=e.reconnectAttempts,s;switch(this.options.reconnectStrategy){case"fixed_interval":s=t;break;case"linear_backoff":s=t*(n+1);break;case"exponential_backoff":s=t*o**n;break;case"adaptive":s=this.calculateAdaptiveDelay(e,t,o,n);break;default:s=t*o**n}if(s=Math.min(s,r),this.options.jitterEnabled){let a=s*.1*Math.random();s+=a}return Math.round(s)}calculateAdaptiveDelay(e,t,r,o){let n=t;switch(e.errorType){case"network_error":n=t*r**o;break;case"authentication_error":n=t*r**o*2;break;case"server_error":n=t*(1+o);break;case"timeout_error":n=t*(1+o*.5);break;default:n=t*r**o}if(e.reconnectHistory.length>0){let s=e.reconnectHistory.slice(-5),a=s.filter(l=>l.success).length/s.length;a<.2?n*=1.5:a>.8&&(n*=.8)}return n}shouldReconnect(e){return e.reconnectAttempts>=this.options.maxReconnectAttempts?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8FDE\u6B21\u6570 ${this.options.maxReconnectAttempts}`),!1):e.errorType==="authentication_error"&&e.reconnectAttempts>=3?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8BA4\u8BC1\u9519\u8BEF\uFF0C\u505C\u6B62\u91CD\u8FDE`),!1):e.consecutiveFailures>=10?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8FDE\u7EED\u5931\u8D25\u6B21\u6570\u8FC7\u591A\uFF0C\u505C\u6B62\u91CD\u8FDE`),!1):!0}scheduleReconnect(e){let t=this.connectionStates.get(e);if(!t)return;if(t.lastError&&(t.errorType=this.classifyConnectionError(new Error(t.lastError))),!this.shouldReconnect(t)){t.isReconnecting=!1;return}let r=this.reconnectTimers.get(e);r&&clearTimeout(r);let o=this.calculateReconnectDelay(t);t.reconnectDelay=o,t.isReconnecting=!0,t.nextReconnectTime=new Date(Date.now()+o),this.logger.info(`\u5B89\u6392\u91CD\u8FDE ${e}\uFF0C\u5EF6\u8FDF: ${o}ms\uFF0C\u5C1D\u8BD5\u6B21\u6570: ${t.reconnectAttempts+1}\uFF0C\u9519\u8BEF\u7C7B\u578B: ${t.errorType}`);let n=setTimeout(async()=>{this.reconnectTimers.delete(e),await this.performReconnect(e)},o);this.reconnectTimers.set(e,n)}async performReconnect(e){let t=this.connectionStates.get(e),r=this.connections.get(e);if(!(!t||!r)){t.lastReconnectAttempt=new Date,t.isReconnecting=!0,this.logger.info(`\u5F00\u59CB\u91CD\u8FDE ${e}\uFF0C\u7B2C ${t.reconnectAttempts+1} \u6B21\u5C1D\u8BD5`);try{await this.connectSingleEndpoint(e,r),t.isReconnecting=!1,t.reconnectHistory.push({timestamp:new Date,success:!0,delay:t.reconnectDelay}),this.logger.info(`\u91CD\u8FDE\u6210\u529F ${e}`)}catch(o){t.isReconnecting=!1,t.reconnectHistory.push({timestamp:new Date,success:!1,error:o instanceof Error?o.message:String(o),delay:t.reconnectDelay}),this.logger.error(`\u91CD\u8FDE\u5931\u8D25 ${e}:`,o),this.scheduleReconnect(e)}t.reconnectHistory.length>20&&(t.reconnectHistory=t.reconnectHistory.slice(-20))}}clearAllReconnectTimers(){for(let[,e]of this.reconnectTimers)clearTimeout(e);this.reconnectTimers.clear()}}});async function ds(i){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 XiaozhiConnectionManager \u5355\u4F8B..."),new wt(i)}async function Po(i){if(ie&&j==="initialized")return ie;if(X&&j==="initializing")return X;j==="failed"&&mr(),j="initializing",X=ds(i);try{return ie=await X,j="initialized",_e=`xiaozhi-connection-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,Qe=null,console.log(`\u2705 XiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${_e}`),ie}catch(e){throw j="failed",Qe=e,X=null,console.error("\u274C XiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",e.message),e}}async function wo(){if(j==="cleanup"){console.log("\u26A0\uFE0F XiaozhiConnectionManager \u5355\u4F8B\u5DF2\u5728\u6E05\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u91CD\u590D\u6E05\u7406");return}console.log("\u{1F9F9} \u6B63\u5728\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90..."),j="cleanup";try{if(X){try{await(await X).cleanup()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}X=null}ie&&(await ie.cleanup(),ie=null),j="not_initialized",Qe=null,_e=null,console.log("\u2705 XiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(i){throw console.error("\u274C XiaozhiConnectionManager \u5355\u4F8B\u6E05\u7406\u5931\u8D25:",i.message),mr(),i}}function mr(){console.log("\u{1F504} \u91CD\u7F6E XiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001..."),X&&(X=null),ie=null,j="not_initialized",Qe=null,_e=null,console.log("\u2705 XiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001\u5DF2\u91CD\u7F6E")}function ms(){return j==="initialized"&&ie!==null}function fs(){return{state:j,initializationTime:_e?new Date:void 0,lastError:Qe||void 0,instanceId:_e||void 0}}async function Cs(i){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 XiaozhiConnectionManager \u5355\u4F8B..."),await wo(),Po(i)}function vs(){return ie}async function Ss(){if(j==="initialized")return!0;if(j==="initializing"&&X)try{return await X,!0}catch{return!1}return!1}var ie,X,j,Qe,_e,Le,bo=m(()=>{"use strict";Mo();ie=null,X=null,j="not_initialized",Qe=null,_e=null;c(ds,"createInstance");c(Po,"getInstance");c(wo,"cleanup");c(mr,"reset");c(ms,"isInitialized");c(fs,"getStatus");c(Cs,"forceReinitialize");c(vs,"getCurrentInstance");c(Ss,"waitForInitialization");Le={getInstance:Po,cleanup:wo,reset:mr,isInitialized:ms,getStatus:fs,forceReinitialize:Cs,getCurrentInstance:vs,waitForInitialization:Ss};process.on("exit",()=>{Le.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B..."),Le.reset())});process.on("uncaughtException",async i=>{console.error("\u{1F4A5} \u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B:",i);try{await Le.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}});process.on("unhandledRejection",async i=>{console.error("\u{1F4A5} \u672A\u5904\u7406\u7684Promise\u62D2\u7EDD\uFF0C\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B:",i);try{await Le.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as ys}from"events";function K(){return He||(He=new fr),He}function Ro(){He&&(He.destroy(),He=null)}var fr,He,ye=m(()=>{"use strict";S();fr=class extends ys{static{c(this,"EventBus")}logger;eventStats=new Map;maxListeners=50;constructor(){super(),this.logger=g.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),this.emit(e,t)}catch(r){return this.logger.error(`\u53D1\u5C04\u4E8B\u4EF6\u5931\u8D25: ${e}`,r),!1}}onEvent(e,t){return this.logger.debug(`\u6DFB\u52A0\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.on(e,t)}onceEvent(e,t){return this.logger.debug(`\u6DFB\u52A0\u4E00\u6B21\u6027\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.once(e,t)}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")}},He=null;c(K,"getEventBus");c(Ro,"destroyEventBus")});var ae,et=m(()=>{"use strict";S();Y();ye();ae=class{static{c(this,"ConfigService")}logger;eventBus;constructor(){this.logger=g.withTag("ConfigService"),this.eventBus=K()}async getConfig(){try{let e=d.getConfig();return this.logger.debug("\u83B7\u53D6\u914D\u7F6E\u6210\u529F"),e}catch(e){throw this.logger.error("\u83B7\u53D6\u914D\u7F6E\u5931\u8D25:",e),this.eventBus.emitEvent("config:error",{error:e instanceof Error?e:new Error(String(e)),operation:"getConfig"}),e}}async updateConfig(e,t="unknown"){try{this.logger.info(`\u5F00\u59CB\u66F4\u65B0\u914D\u7F6E\uFF0C\u6765\u6E90: ${t}`),this.validateConfig(e),e.mcpEndpoint!==d.getMcpEndpoint()&&d.updateMcpEndpoint(e.mcpEndpoint);let r=d.getMcpServers();for(let[o,n]of Object.entries(e.mcpServers))JSON.stringify(r[o])!==JSON.stringify(n)&&d.updateMcpServer(o,n);for(let o of Object.keys(r))o in e.mcpServers||(d.removeMcpServer(o),d.removeServerToolsConfig(o));if(e.connection&&d.updateConnectionConfig(e.connection),e.modelscope&&d.updateModelScopeConfig(e.modelscope),e.webUI&&d.updateWebUIConfig(e.webUI),e.mcpServerConfig)for(let[o,n]of Object.entries(e.mcpServerConfig))for(let[s,a]of Object.entries(n.tools))d.setToolEnabled(o,s,a.enable);if(e?.platforms)for(let[o,n]of Object.entries(e.platforms))d.updatePlatformConfig(o,n);this.logger.info("\u914D\u7F6E\u66F4\u65B0\u6210\u529F"),this.eventBus.emitEvent("config:updated",{config:e,source:t})}catch(r){throw this.logger.error("\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",r),this.eventBus.emitEvent("config:error",{error:r instanceof Error?r:new Error(String(r)),operation:"updateConfig"}),r}}getMcpEndpoint(){try{return d.getMcpEndpoint()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",e),e}}getMcpEndpoints(){try{return d.getMcpEndpoints()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",e),e}}getMcpServers(){try{return d.getMcpServers()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",e),e}}getConnectionConfig(){try{return d.getConnectionConfig()}catch(e){throw this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",e),e}}getWebUIPort(){try{return d.getWebUIPort()||9999}catch(e){return this.logger.error("\u83B7\u53D6 Web UI \u7AEF\u53E3\u5931\u8D25:",e),9999}}validateConfig(e){if(!e||typeof e!="object")throw new Error("\u914D\u7F6E\u5FC5\u987B\u662F\u6709\u6548\u7684\u5BF9\u8C61");if(!e.mcpEndpoint)throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B mcpEndpoint");if(!e.mcpServers||typeof e.mcpServers!="object")throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 mcpServers")}configExists(){return d.configExists()}async reloadConfig(){try{this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E"),d.reloadConfig();let e=await this.getConfig();return this.eventBus.emitEvent("config:updated",{config:e,source:"reload"}),e}catch(e){throw this.logger.error("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25:",e),this.eventBus.emitEvent("config:error",{error:e instanceof Error?e:new Error(String(e)),operation:"reloadConfig"}),e}}getConfigPath(){return d.getConfigPath()}}});var bt,Io=m(()=>{"use strict";S();et();bt=class{static{c(this,"ConfigApiHandler")}logger;configService;constructor(){this.logger=g.withTag("ConfigApiHandler"),this.configService=new ae}createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async getConfig(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u914D\u7F6E\u8BF7\u6C42");let t=await this.configService.getConfig();return this.logger.info("\u83B7\u53D6\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async updateConfig(e){try{this.logger.debug("\u5904\u7406\u66F4\u65B0\u914D\u7F6E\u8BF7\u6C42");let t=await e.req.json();if(!t||typeof t!="object"){let r=this.createErrorResponse("INVALID_REQUEST_BODY","\u8BF7\u6C42\u4F53\u5FC5\u987B\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61");return e.json(r,400)}return await this.configService.updateConfig(t,"http-api"),this.logger.info("\u914D\u7F6E\u66F4\u65B0\u6210\u529F"),e.json(this.createSuccessResponse(null,"\u914D\u7F6E\u66F4\u65B0\u6210\u529F"))}catch(t){this.logger.error("\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_UPDATE_ERROR",t instanceof Error?t.message:"\u914D\u7F6E\u66F4\u65B0\u5931\u8D25");return e.json(r,400)}}async getMcpEndpoint(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u7AEF\u70B9\u8BF7\u6C42");let t=this.configService.getMcpEndpoint();return this.logger.debug("\u83B7\u53D6 MCP \u7AEF\u70B9\u6210\u529F"),e.json(this.createSuccessResponse({endpoint:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_ENDPOINT_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25");return e.json(r,500)}}async getMcpEndpoints(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u8BF7\u6C42");let t=this.configService.getMcpEndpoints();return this.logger.debug("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u6210\u529F"),e.json(this.createSuccessResponse({endpoints:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_ENDPOINTS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25");return e.json(r,500)}}async getMcpServers(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u8BF7\u6C42");let t=this.configService.getMcpServers();return this.logger.debug("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse({servers:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_SERVERS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async getConnectionConfig(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u8BF7\u6C42");let t=this.configService.getConnectionConfig();return this.logger.debug("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse({connection:t}))}catch(t){this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONNECTION_CONFIG_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async reloadConfig(e){try{this.logger.info("\u5904\u7406\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u8BF7\u6C42");let t=await this.configService.reloadConfig();return this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(t,"\u914D\u7F6E\u91CD\u65B0\u52A0\u8F7D\u6210\u529F"))}catch(t){this.logger.error("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_RELOAD_ERROR",t instanceof Error?t.message:"\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async getConfigPath(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u8BF7\u6C42");let t=this.configService.getConfigPath();return this.logger.debug("\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u6210\u529F"),e.json(this.createSuccessResponse({path:t}))}catch(t){this.logger.error("\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_PATH_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25");return e.json(r,500)}}async checkConfigExists(e){try{this.logger.debug("\u5904\u7406\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u8BF7\u6C42");let t=this.configService.configExists();return this.logger.debug(`\u914D\u7F6E\u5B58\u5728\u68C0\u67E5\u7ED3\u679C: ${t}`),e.json(this.createSuccessResponse({exists:t}))}catch(t){this.logger.error("\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_EXISTS_CHECK_ERROR",t instanceof Error?t.message:"\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u5931\u8D25");return e.json(r,500)}}}});async function Ts(i,e=3,t=1e3){for(let r=1;r<=e;r++)try{return await i()}catch(o){if(r===e)throw o;let n=t*2**(r-1);g.warn(`\u6263\u5B50 API \u8C03\u7528\u5931\u8D25\uFF0C${n}ms \u540E\u91CD\u8BD5 (${r}/${e})`,o),await new Promise(s=>setTimeout(s,n))}throw new Error("Max retry attempts exceeded")}function Es(i,e){let t=i.status;return t===401?new ce("\u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6263\u5B50 API Token \u914D\u7F6E","AUTH_FAILED",401,e):t===429?new ce("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED",429,e):t>=500?new ce("\u6263\u5B50\u670D\u52A1\u5668\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","SERVER_ERROR",t,e):new ce(e?.msg||`API \u8C03\u7528\u5931\u8D25: ${i.statusText}`,"API_ERROR",t,e)}var Cr,ce,Rt,$o=m(()=>{"use strict";S();Cr=class{static{c(this,"CozeApiCache")}cache=new Map;TTL={workspaces:1800*1e3,workflows:300*1e3};set(e,t,r){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:this.TTL[r]})}get(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(e){if(!e){this.cache.clear();return}for(let t of this.cache.keys())t.includes(e)&&this.cache.delete(t)}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}},ce=class extends Error{static{c(this,"CozeApiErrorImpl")}code;statusCode;response;constructor(e,t,r,o){super(e),this.name="CozeApiError",this.code=t,this.statusCode=r,this.response=o}};c(Ts,"retryWithBackoff");c(Es,"handleCozeApiError");Rt=class{static{c(this,"CozeApiService")}cache=new Cr;token;API_BASE_URL="https://api.coze.cn";TIMEOUT=1e4;RETRY_ATTEMPTS=3;constructor(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("\u6263\u5B50 API Token \u4E0D\u80FD\u4E3A\u7A7A");this.token=e.trim()}async getWorkspaces(){let e="workspaces",t=this.cache.get(e);if(t)return g.debug("\u4ECE\u7F13\u5B58\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868"),t;g.info("\u83B7\u53D6\u6263\u5B50\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868");let r=await this.request("/v1/workspaces");if(r.code!==0)throw new ce(r.msg||"\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25","API_ERROR",void 0,r);let o=r.data.workspaces;return this.cache.set(e,o,"workspaces"),g.info(`\u6210\u529F\u83B7\u53D6 ${o.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),o}async getWorkflows(e){let{workspace_id:t,page_num:r=1,page_size:o=20}=e;if(!t||typeof t!="string")throw new Error("\u5DE5\u4F5C\u7A7A\u95F4ID\u4E0D\u80FD\u4E3A\u7A7A");let n=`workflows:${t}:${r}:${o}`,s=this.cache.get(n);if(s)return g.debug(`\u4ECE\u7F13\u5B58\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868: ${t}`),s;g.info(`\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684\u5DE5\u4F5C\u6D41\u5217\u8868 (\u9875\u7801: ${r}, \u6BCF\u9875: ${o})`);let a=new URLSearchParams({workspace_id:t,page_num:r.toString(),page_size:o.toString(),workflow_mode:"workflow"}),l=await this.request(`/v1/workflows?${a}`);if(l.code!==0)throw new ce(l.msg||"\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25","API_ERROR",void 0,l);let h={items:l.data.items,hasMore:l.data.has_more};return this.cache.set(n,h,"workflows"),g.info(`\u6210\u529F\u83B7\u53D6 ${h.items.length} \u4E2A\u5DE5\u4F5C\u6D41\uFF0ChasMore: ${h.hasMore}`),h}async request(e){return Ts(async()=>{let t=`${this.API_BASE_URL}${e}`;g.debug(`\u53D1\u8D77\u6263\u5B50 API \u8BF7\u6C42: ${t}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.TIMEOUT);try{let n=await fetch(t,{headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},signal:r.signal});clearTimeout(o);let s;try{s=await n.json()}catch(a){throw g.error("\u89E3\u6790\u54CD\u5E94 JSON \u5931\u8D25:",a),new ce("\u54CD\u5E94\u6570\u636E\u683C\u5F0F\u9519\u8BEF","PARSE_ERROR",n.status)}if(!n.ok)throw Es(n,s);return s}catch(n){throw clearTimeout(o),n instanceof Error&&n.name==="AbortError"?new ce(`\u8BF7\u6C42\u8D85\u65F6 (${this.TIMEOUT}ms)`,"TIMEOUT",void 0):n}},this.RETRY_ATTEMPTS)}clearCache(e){this.cache.clear(e),g.info(`\u6E05\u9664\u6263\u5B50 API \u7F13\u5B58${e?` (\u6A21\u5F0F: ${e})`:""}`)}getCacheStats(){return this.cache.getStats()}}});function It(i,e){return{success:!0,data:i,message:e}}function A(i,e,t){return{success:!1,message:i,error:e?{code:e,details:t}:void 0}}function $t(){let i=d.getCozeToken();if(!i)throw new Error("\u6263\u5B50 API Token \u672A\u914D\u7F6E\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E platforms.coze.token");return new Rt(i)}var Te,xo=m(()=>{"use strict";S();Y();$o();c(It,"createSuccessResponse");c(A,"createErrorResponse");c($t,"getCozeApiService");Te=class{static{c(this,"CozeApiHandler")}static async getWorkspaces(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=await $t().getWorkspaces();return g.info(`\u6210\u529F\u83B7\u53D6 ${r.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),e.json(It({workspaces:r}))}catch(t){return g.error("\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25:",t),t instanceof Error&&t.code==="AUTH_FAILED"?e.json(A("\u6263\u5B50 API \u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 Token \u914D\u7F6E","AUTH_FAILED"),401):t instanceof Error&&t.code==="RATE_LIMITED"?e.json(A("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(A("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async getWorkflows(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let t=e.req.query("workspace_id"),r=Number.parseInt(e.req.query("page_num")||"1",10),o=Number.parseInt(e.req.query("page_size")||"20",10);if(!t)return g.warn("\u7F3A\u5C11 workspace_id \u53C2\u6570"),e.json(A("\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570: workspace_id","MISSING_PARAMETER"),400);if(r<1||r>1e3)return e.json(A("page_num \u5FC5\u987B\u5728 1-1000 \u4E4B\u95F4","INVALID_PARAMETER"),400);if(o<1||o>100)return e.json(A("page_size \u5FC5\u987B\u5728 1-100 \u4E4B\u95F4","INVALID_PARAMETER"),400);let n={workspace_id:t,page_num:r,page_size:o},a=await $t().getWorkflows(n);g.info(`\u6210\u529F\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684 ${a.items.length} \u4E2A\u5DE5\u4F5C\u6D41`);let l=d.getCustomMCPTools(),h=a.items.map(u=>{let p=l.find(C=>C.handler.type==="proxy"&&C.handler.platform==="coze"&&C.handler.config.workflow_id===u.workflow_id);return{...u,isAddedAsTool:!!p,toolName:p?.name||null}});return g.info(`\u5DE5\u4F5C\u6D41\u5DE5\u5177\u72B6\u6001\u68C0\u67E5\u5B8C\u6210\uFF0C\u5171 ${h.filter(u=>u.isAddedAsTool).length} \u4E2A\u5DE5\u4F5C\u6D41\u5DF2\u6DFB\u52A0\u4E3A\u5DE5\u5177`),e.json(It({items:h,has_more:a.hasMore,page_num:r,page_size:o,total_count:a.items.length}))}catch(t){return g.error("\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25:",t),t instanceof Error&&t.code==="AUTH_FAILED"?e.json(A("\u6263\u5B50 API \u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 Token \u914D\u7F6E","AUTH_FAILED"),401):t instanceof Error&&t.code==="RATE_LIMITED"?e.json(A("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(A("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async clearCache(e){try{if(g.info("\u5904\u7406\u6E05\u9664\u6263\u5B50 API \u7F13\u5B58\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let t=e.req.query("pattern"),r=$t(),o=r.getCacheStats();r.clearCache(t);let n=r.getCacheStats();return g.info(`\u7F13\u5B58\u6E05\u9664\u5B8C\u6210\uFF0C\u6E05\u9664\u524D: ${o.size} \u9879\uFF0C\u6E05\u9664\u540E: ${n.size} \u9879`),e.json(It({cleared:o.size-n.size,remaining:n.size,pattern:t||"all"},"\u7F13\u5B58\u6E05\u9664\u6210\u529F"))}catch(t){return g.error("\u6E05\u9664\u7F13\u5B58\u5931\u8D25:",t),e.json(A(t instanceof Error?t.message:"\u6E05\u9664\u7F13\u5B58\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async getCacheStats(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=$t().getCacheStats();return e.json(It(r))}catch(t){return g.error("\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:",t),e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}}});var xt,Oo=m(()=>{"use strict";S();et();xt=class{static{c(this,"HeartbeatHandler")}logger;statusService;notificationService;configService;constructor(e,t){this.logger=g.withTag("HeartbeatHandler"),this.statusService=e,this.notificationService=t,this.configService=new ae}async handleClientStatus(e,t,r){try{this.logger.debug(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0: ${r}`,t.data);let o={...t.data,lastHeartbeat:Date.now()};this.statusService.updateClientInfo(o,`websocket-${r}`),await this.sendLatestConfig(e,r),this.logger.debug(`\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u6210\u529F: ${r}`)}catch(o){this.logger.error(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25: ${r}`,o),this.sendError(e,"CLIENT_STATUS_ERROR",o instanceof Error?o.message:"\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25")}}async sendLatestConfig(e,t){try{let o={type:"configUpdate",data:await this.configService.getConfig(),timestamp:Date.now()};e.send(JSON.stringify(o)),this.logger.debug(`\u6700\u65B0\u914D\u7F6E\u5DF2\u53D1\u9001\u7ED9\u5BA2\u6237\u7AEF: ${t}`)}catch(r){this.logger.error(`\u53D1\u9001\u6700\u65B0\u914D\u7F6E\u5931\u8D25: ${t}`,r)}}sendError(e,t,r){try{let o={type:"error",error:{code:t,message:r,timestamp:Date.now()}};e.send(JSON.stringify(o))}catch(o){this.logger.error("\u53D1\u9001\u9519\u8BEF\u6D88\u606F\u5931\u8D25:",o)}}checkHeartbeatTimeout(){let e=this.statusService.getLastHeartbeat(),t=Date.now();e&&t-e>35e3&&(this.logger.warn("\u5BA2\u6237\u7AEF\u5FC3\u8DF3\u8D85\u65F6\uFF0C\u6807\u8BB0\u4E3A\u65AD\u5F00\u8FDE\u63A5"),this.statusService.updateClientInfo({status:"disconnected"},"heartbeat-timeout"))}startHeartbeatMonitoring(){return this.logger.info("\u542F\u52A8\u5FC3\u8DF3\u76D1\u63A7"),setInterval(()=>{this.checkHeartbeatTimeout(),this.cleanupDisconnectedClients()},1e4)}cleanupDisconnectedClients(){try{this.notificationService.cleanupDisconnectedClients()}catch(e){this.logger.error("\u6E05\u7406\u65AD\u5F00\u8FDE\u63A5\u7684\u5BA2\u6237\u7AEF\u5931\u8D25:",e)}}stopHeartbeatMonitoring(e){this.logger.info("\u505C\u6B62\u5FC3\u8DF3\u76D1\u63A7"),clearInterval(e)}getHeartbeatStats(){return{lastHeartbeat:this.statusService.getLastHeartbeat(),isConnected:this.statusService.isClientConnected(),clientStats:this.notificationService.getClientStats()}}handleClientConnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5EFA\u7ACB: ${e}`),this.statusService.updateClientInfo({status:"connected",lastHeartbeat:Date.now()},`websocket-connect-${e}`)}handleClientDisconnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u65AD\u5F00: ${e}`),this.statusService.updateClientInfo({status:"disconnected"},`websocket-disconnect-${e}`)}sendHeartbeatResponse(e,t){try{let r={type:"heartbeatResponse",data:{timestamp:Date.now(),status:"ok"}};e.send(JSON.stringify(r)),this.logger.debug(`\u5FC3\u8DF3\u54CD\u5E94\u5DF2\u53D1\u9001: ${t}`)}catch(r){this.logger.error(`\u53D1\u9001\u5FC3\u8DF3\u54CD\u5E94\u5931\u8D25: ${t}`,r)}}validateHeartbeatMessage(e){return e&&typeof e=="object"&&e.type==="clientStatus"&&e.data&&typeof e.data=="object"}}});import{randomUUID as Ms}from"crypto";var Ot,Ao=m(()=>{"use strict";S();gr();Pt();Ot=class{static{c(this,"MCPRouteHandler")}logger;mcpMessageHandler=null;clients=new Map;config;metrics;cleanupInterval=null;startTime;constructor(e={}){this.logger=g.withTag("MCPRouteHandler"),this.config={maxClients:e.maxClients??100,connectionTimeout:e.connectionTimeout??3e5,heartbeatInterval:e.heartbeatInterval??3e4,maxMessageSize:e.maxMessageSize??1024*1024,enableMetrics:e.enableMetrics??!0},this.metrics={totalConnections:0,activeConnections:0,totalMessages:0,errorCount:0,averageResponseTime:0,uptime:0},this.startTime=new Date,this.startCleanupTask(),this.logger.info("MCPRouteHandler \u521D\u59CB\u5316\u5B8C\u6210",{maxClients:this.config.maxClients,connectionTimeout:this.config.connectionTimeout,heartbeatInterval:this.config.heartbeatInterval})}startCleanupTask(){this.cleanupInterval=setInterval(()=>{this.cleanupStaleConnections(),this.updateMetrics()},6e4)}stopCleanupTask(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}cleanupStaleConnections(){let e=new Date,t=[];for(let[r,o]of this.clients.entries())(e.getTime()-o.lastActivity.getTime()>this.config.connectionTimeout||!o.isAlive)&&t.push(r);for(let r of t)this.logger.info(`\u6E05\u7406\u8FC7\u671F\u8FDE\u63A5: ${r}`),this.handleClientDisconnect(r,"cleanup");t.length>0&&this.logger.info(`\u6E05\u7406\u4E86 ${t.length} \u4E2A\u8FC7\u671F\u8FDE\u63A5`)}updateMetrics(){this.config.enableMetrics&&(this.metrics.activeConnections=this.clients.size,this.metrics.uptime=Date.now()-this.startTime.getTime(),this.logger.debug("\u8FDE\u63A5\u7EDF\u8BA1",{activeConnections:this.metrics.activeConnections,totalConnections:this.metrics.totalConnections,totalMessages:this.metrics.totalMessages,errorCount:this.metrics.errorCount}))}async initializeMessageHandler(){if(!this.mcpMessageHandler)try{let e=await V.getInstance();this.mcpMessageHandler=new De(e),this.logger.info("MCP \u6D88\u606F\u5904\u7406\u5668\u521D\u59CB\u5316\u6210\u529F")}catch(e){throw this.logger.error("MCP \u6D88\u606F\u5904\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",e),this.metrics.errorCount++,e}}async handlePost(e){let t=Date.now(),r=null;try{this.logger.debug("\u5904\u7406 MCP POST \u8BF7\u6C42");let o=e.req.query("sessionId");if(o)return await this.handleSSEMessage(e,o);let n=e.req.header("content-length");if(n&&Number.parseInt(n)>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Request too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);if(!e.req.header("content-type")?.includes("application/json"))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Content-Type must be application/json",null);let a=e.req.header("mcp-protocol-version")||e.req.header("MCP-Protocol-Version")||e.req.header("Mcp-Protocol-Version"),l=["2024-11-05","2025-06-18"];a&&!l.includes(a)&&this.logger.warn(`\u4E0D\u652F\u6301\u7684 MCP \u534F\u8BAE\u7248\u672C: ${a}\uFF0C\u652F\u6301\u7684\u7248\u672C: ${l.join(", ")}`);let h;try{let C=await e.req.text();if(C.length>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);h=JSON.parse(C),r=h.id||null}catch{return this.metrics.errorCount++,this.createErrorResponse(-32700,"Parse error: Invalid JSON",null)}if(!this.validateMessage(h))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Message does not conform to JSON-RPC 2.0",r);await this.initializeMessageHandler();let u=await this.mcpMessageHandler.handleMessage(h);this.metrics.totalMessages++;let p=Date.now()-t;return this.metrics.averageResponseTime=(this.metrics.averageResponseTime*(this.metrics.totalMessages-1)+p)/this.metrics.totalMessages,this.logger.debug("MCP POST \u8BF7\u6C42\u5904\u7406\u6210\u529F",{method:h.method,messageId:r,responseTime:p,isNotification:u===null}),u===null?new Response(null,{status:204,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":p.toString()}}):e.json(u,200,{"Content-Type":"application/json","MCP-Protocol-Version":"2024-11-05","X-Response-Time":p.toString()})}catch(o){this.metrics.errorCount++;let n=Date.now()-t;this.logger.error("\u5904\u7406 MCP POST \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:o instanceof Error?o.message:String(o),messageId:r,responseTime:n,stack:o instanceof Error?o.stack:void 0});let s=o instanceof Error?o.message:String(o);return this.createErrorResponse(-32603,`Internal error: ${s}`,r)}}async handleSSEMessage(e,t){let r=Date.now(),o=null;try{this.logger.debug(`\u5904\u7406 SSE \u6D88\u606F (\u4F1A\u8BDD: ${t})`);let n=this.clients.get(t);if(!n)return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Invalid or missing sessionId",null);n.lastActivity=new Date;let s=e.req.header("content-length");if(s&&Number.parseInt(s)>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);let a;try{let u=await e.req.text();if(u.length>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);a=JSON.parse(u),o=a.id||null}catch{return this.metrics.errorCount++,this.createErrorResponse(-32700,"Parse error: Invalid JSON",null)}if(!this.validateMessage(a))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Message does not conform to JSON-RPC 2.0",o);await this.initializeMessageHandler();let l=await this.mcpMessageHandler.handleMessage(a);if(n.messageCount++,this.metrics.totalMessages++,l!==null&&n.writer&&n.isAlive)try{await this.sendSSEEvent(n.writer,"message",JSON.stringify(l))}catch(u){this.logger.warn(`SSE \u5199\u5165\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${t}`,u),n.isAlive=!1}let h=Date.now()-r;return this.logger.debug(`SSE \u6D88\u606F\u5904\u7406\u5B8C\u6210 (\u4F1A\u8BDD: ${t})`,{method:a.method,messageId:o,responseTime:h,messageCount:n.messageCount,isNotification:l===null}),new Response(null,{status:202,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":h.toString()}})}catch(n){this.metrics.errorCount++;let s=Date.now()-r;this.logger.error(`\u5904\u7406 SSE \u6D88\u606F\u65F6\u51FA\u9519 (\u4F1A\u8BDD: ${t}):`,{error:n instanceof Error?n.message:String(n),messageId:o,responseTime:s,stack:n instanceof Error?n.stack:void 0});let a=n instanceof Error?n.message:String(n);return this.createErrorResponse(-32603,`Internal error: ${a}`,o)}}async handleGet(e){try{if(this.logger.debug("\u5904\u7406 MCP GET \u8BF7\u6C42\uFF08SSE \u8FDE\u63A5\uFF09"),this.clients.size>=this.config.maxClients)return this.metrics.errorCount++,e.json({jsonrpc:"2.0",error:{code:-32e3,message:"Server busy: Maximum client connections reached",data:{maxClients:this.config.maxClients}},id:null},503);let t=Date.now().toString(),r=Ms(),o=new Date,n=e.req.header("user-agent"),s=e.req.header("x-forwarded-for")||e.req.header("x-real-ip")||"unknown";this.logger.info(`SSE \u5BA2\u6237\u7AEF\u8FDE\u63A5: ${t} (\u4F1A\u8BDD: ${r})`,{userAgent:n,remoteAddress:s});let{readable:a,writable:l}=new TransformStream,h=l.getWriter(),u=new AbortController,p={id:t,sessionId:r,response:new Response(a),connectedAt:o,lastActivity:o,writer:h,abortController:u,isAlive:!0,messageCount:0,userAgent:n,remoteAddress:s};this.clients.set(r,p),this.metrics.totalConnections++,this.metrics.activeConnections=this.clients.size;try{await this.sendSSEEvent(h,"connected",JSON.stringify({sessionId:r,endpoint:`/mcp?sessionId=${r}`,timestamp:o.toISOString(),protocolVersion:"2024-11-05"}))}catch(b){this.logger.error(`\u521D\u59CB SSE \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25: ${r}`,b),p.isAlive=!1}this.startHeartbeat(p);let C=new Response(a,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no","MCP-Protocol-Version":"2024-11-05","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type, MCP-Protocol-Version"}}),T=c(()=>{this.handleClientDisconnect(r,t)},"handleDisconnect");return e.req.raw.signal?.addEventListener("abort",T),u.signal.addEventListener("abort",T),C}catch(t){return this.metrics.errorCount++,this.logger.error("\u5904\u7406 MCP GET \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),e.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"},id:null},500)}}startHeartbeat(e){e.heartbeatInterval&&clearInterval(e.heartbeatInterval),e.heartbeatInterval=setInterval(async()=>{if(!e.isAlive||!e.writer){this.stopHeartbeat(e);return}try{await this.sendSSEEvent(e.writer,"heartbeat",JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId})),this.logger.debug(`\u5FC3\u8DF3\u53D1\u9001\u6210\u529F: ${e.sessionId}`)}catch(t){this.logger.warn(`\u5FC3\u8DF3\u53D1\u9001\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${e.sessionId}`,t),e.isAlive=!1,this.stopHeartbeat(e)}},this.config.heartbeatInterval)}stopHeartbeat(e){e.heartbeatInterval&&(clearInterval(e.heartbeatInterval),e.heartbeatInterval=void 0)}async sendSSEEvent(e,t,r){try{let o=`event: ${t}
|
|
39
39
|
data: ${r}
|
|
40
40
|
|
|
41
41
|
`;await e.write(new TextEncoder().encode(o))}catch(o){throw this.logger.error("\u53D1\u9001 SSE \u4E8B\u4EF6\u5931\u8D25:",o),o}}handleClientDisconnect(e,t){let r=this.clients.get(e);if(!r)return;let o=Date.now()-r.connectedAt.getTime();this.logger.info(`SSE \u5BA2\u6237\u7AEF\u65AD\u5F00\u8FDE\u63A5: ${r.id} (\u4F1A\u8BDD: ${e})`,{reason:t,duration:o,messageCount:r.messageCount,userAgent:r.userAgent,remoteAddress:r.remoteAddress}),this.stopHeartbeat(r),r.abortController&&r.abortController.abort();try{r.writer&&r.writer.close()}catch(n){this.logger.debug("\u5173\u95ED SSE writer \u65F6\u51FA\u9519:",n)}this.clients.delete(e),this.metrics.activeConnections=this.clients.size}validateMessage(e){return!e||typeof e!="object"?(this.logger.debug("\u6D88\u606F\u9A8C\u8BC1\u5931\u8D25: \u4E0D\u662F\u5BF9\u8C61"),!1):e.jsonrpc!=="2.0"?(this.logger.debug("\u6D88\u606F\u9A8C\u8BC1\u5931\u8D25: jsonrpc \u7248\u672C\u4E0D\u6B63\u786E",{jsonrpc:e.jsonrpc}),!1):!e.method||typeof e.method!="string"?(this.logger.debug("\u6D88\u606F\u9A8C\u8BC1\u5931\u8D25: method \u5B57\u6BB5\u65E0\u6548",{method:e.method}),!1):e.id!==void 0&&typeof e.id!="string"&&typeof e.id!="number"&&e.id!==null?(this.logger.debug("\u6D88\u606F\u9A8C\u8BC1\u5931\u8D25: id \u5B57\u6BB5\u7C7B\u578B\u65E0\u6548",{id:e.id}),!1):e.params!==void 0&&typeof e.params!="object"?(this.logger.debug("\u6D88\u606F\u9A8C\u8BC1\u5931\u8D25: params \u5B57\u6BB5\u7C7B\u578B\u65E0\u6548",{params:e.params}),!1):!0}createErrorResponse(e,t,r){let o={jsonrpc:"2.0",error:{code:e,message:t},id:r};return new Response(JSON.stringify(o),{status:400,headers:{"Content-Type":"application/json","MCP-Protocol-Version":"2024-11-05"}})}getStatus(){return{connectedClients:this.clients.size,maxClients:this.config.maxClients,isInitialized:this.mcpMessageHandler!==null,metrics:this.config.enableMetrics?this.metrics:void 0,config:{maxClients:this.config.maxClients,connectionTimeout:this.config.connectionTimeout,heartbeatInterval:this.config.heartbeatInterval,maxMessageSize:this.config.maxMessageSize}}}getDetailedStatus(){let e=Array.from(this.clients.values()).map(t=>({id:t.id,sessionId:t.sessionId,connectedAt:t.connectedAt.toISOString(),lastActivity:t.lastActivity.toISOString(),messageCount:t.messageCount,isAlive:t.isAlive,userAgent:t.userAgent,remoteAddress:t.remoteAddress}));return{...this.getStatus(),clients:e,startTime:this.startTime.toISOString()}}async broadcastMessage(e,t){let r=JSON.stringify(t),o=[];for(let[n,s]of this.clients.entries()){if(!s.isAlive||!s.writer){o.push(n);continue}try{await this.sendSSEEvent(s.writer,e,r)}catch(a){this.logger.warn(`\u5E7F\u64AD\u6D88\u606F\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${n}`,a),s.isAlive=!1,o.push(n)}}for(let n of o)this.handleClientDisconnect(n,"broadcast-failed")}destroy(){this.logger.info("\u6B63\u5728\u9500\u6BC1 MCPRouteHandler"),this.stopCleanupTask();for(let[e]of this.clients.entries())this.handleClientDisconnect(e,"server-shutdown");this.mcpMessageHandler=null,this.logger.info("MCPRouteHandler \u9500\u6BC1\u5B8C\u6210")}}});var At,ko=m(()=>{"use strict";S();et();ye();At=class{static{c(this,"RealtimeNotificationHandler")}logger;notificationService;configService;statusService;eventBus;constructor(e,t){this.logger=g.withTag("RealtimeNotificationHandler"),this.notificationService=e,this.configService=new ae,this.statusService=t,this.eventBus=K()}async handleMessage(e,t,r){try{switch(this.logger.debug(`\u5904\u7406 WebSocket \u6D88\u606F: ${t.type}`,{clientId:r}),this.eventBus.emitEvent("websocket:message:received",{type:t.type,data:t.data,clientId:r}),t.type){case"getConfig":await this.handleGetConfig(e,r);break;case"updateConfig":await this.handleUpdateConfig(e,t.data,r);break;case"getStatus":await this.handleGetStatus(e,r);break;case"restartService":await this.handleRestartService(e,r);break;default:this.logger.warn(`\u672A\u77E5\u7684 WebSocket \u6D88\u606F\u7C7B\u578B: ${t.type}`,{clientId:r}),this.sendError(e,"UNKNOWN_MESSAGE_TYPE",`\u672A\u77E5\u7684\u6D88\u606F\u7C7B\u578B: ${t.type}`)}}catch(o){this.logger.error(`\u5904\u7406 WebSocket \u6D88\u606F\u5931\u8D25: ${t.type}`,o),this.sendError(e,"MESSAGE_PROCESSING_ERROR",o instanceof Error?o.message:"\u6D88\u606F\u5904\u7406\u5931\u8D25")}}async handleGetConfig(e,t){this.logDeprecationWarning("WebSocket getConfig","GET /api/config");try{let r=await this.configService.getConfig();this.logger.debug("WebSocket: getConfig \u8BF7\u6C42\u5904\u7406\u6210\u529F",{clientId:t}),e.send(JSON.stringify({type:"config",data:r}))}catch(r){this.logger.error("WebSocket: getConfig \u8BF7\u6C42\u5904\u7406\u5931\u8D25",r),this.sendError(e,"CONFIG_READ_ERROR",r instanceof Error?r.message:"\u83B7\u53D6\u914D\u7F6E\u5931\u8D25")}}async handleUpdateConfig(e,t,r){this.logDeprecationWarning("WebSocket updateConfig","PUT /api/config");try{await this.configService.updateConfig(t,`websocket-${r}`),this.logger.debug("WebSocket: updateConfig \u8BF7\u6C42\u5904\u7406\u6210\u529F",{clientId:r})}catch(o){this.logger.error("WebSocket: updateConfig \u8BF7\u6C42\u5904\u7406\u5931\u8D25",o),this.sendError(e,"CONFIG_UPDATE_ERROR",o instanceof Error?o.message:"\u914D\u7F6E\u66F4\u65B0\u5931\u8D25")}}async handleGetStatus(e,t){this.logDeprecationWarning("WebSocket getStatus","GET /api/status");try{let r=this.statusService.getFullStatus();e.send(JSON.stringify({type:"status",data:r.client})),this.logger.debug("WebSocket: getStatus \u8BF7\u6C42\u5904\u7406\u6210\u529F",{clientId:t})}catch(r){this.logger.error("WebSocket: getStatus \u8BF7\u6C42\u5904\u7406\u5931\u8D25",r),this.sendError(e,"STATUS_READ_ERROR",r instanceof Error?r.message:"\u83B7\u53D6\u72B6\u6001\u5931\u8D25")}}async handleRestartService(e,t){this.logDeprecationWarning("WebSocket restartService","POST /api/services/restart");try{this.logger.info("WebSocket: \u6536\u5230\u670D\u52A1\u91CD\u542F\u8BF7\u6C42",{clientId:t}),this.eventBus.emitEvent("service:restart:requested",{source:`websocket-${t}`}),this.statusService.updateRestartStatus("restarting")}catch(r){this.logger.error("WebSocket: \u5904\u7406\u91CD\u542F\u8BF7\u6C42\u5931\u8D25",r),this.sendError(e,"RESTART_REQUEST_ERROR",r instanceof Error?r.message:"\u5904\u7406\u91CD\u542F\u8BF7\u6C42\u5931\u8D25")}}sendError(e,t,r){try{let o={type:"error",error:{code:t,message:r,timestamp:Date.now()}};e.send(JSON.stringify(o))}catch(o){this.logger.error("\u53D1\u9001\u9519\u8BEF\u6D88\u606F\u5931\u8D25:",o)}}logDeprecationWarning(e,t){this.logger.warn(`[DEPRECATED] ${e} \u529F\u80FD\u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u4F7F\u7528 ${t} \u66FF\u4EE3`)}async sendInitialData(e,t){try{this.logger.debug("\u53D1\u9001\u521D\u59CB\u6570\u636E\u7ED9\u5BA2\u6237\u7AEF",{clientId:t});let r=await this.configService.getConfig();e.send(JSON.stringify({type:"configUpdate",data:r}));let o=this.statusService.getFullStatus();e.send(JSON.stringify({type:"statusUpdate",data:o.client})),o.restart&&e.send(JSON.stringify({type:"restartStatus",data:o.restart})),this.logger.debug("\u521D\u59CB\u6570\u636E\u53D1\u9001\u5B8C\u6210",{clientId:t})}catch(r){this.logger.error("\u53D1\u9001\u521D\u59CB\u6570\u636E\u5931\u8D25:",r),this.sendError(e,"INITIAL_DATA_ERROR",r instanceof Error?r.message:"\u53D1\u9001\u521D\u59CB\u6570\u636E\u5931\u8D25")}}handleClientDisconnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u65AD\u5F00\u8FDE\u63A5: ${e}`),this.notificationService.unregisterClient(e)}handleClientConnect(e,t){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5: ${t}`),this.notificationService.registerClient(t,e)}}});import{spawn as kt}from"child_process";var Dt,Do=m(()=>{"use strict";S();vr();ye();Dt=class{static{c(this,"ServiceApiHandler")}logger;statusService;eventBus;constructor(e){this.logger=g.withTag("ServiceApiHandler"),this.statusService=e,this.eventBus=K()}createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async restartService(e){try{return this.logger.info("\u5904\u7406\u670D\u52A1\u91CD\u542F\u8BF7\u6C42"),this.eventBus.emitEvent("service:restart:requested",{source:"http-api"}),this.statusService.updateRestartStatus("restarting"),setTimeout(async()=>{try{await this.executeRestart(),setTimeout(()=>{this.statusService.updateRestartStatus("completed")},5e3)}catch(t){this.logger.error("\u670D\u52A1\u91CD\u542F\u5931\u8D25:",t),this.statusService.updateRestartStatus("failed",t instanceof Error?t.message:"\u672A\u77E5\u9519\u8BEF")}},500),e.json(this.createSuccessResponse(null,"\u91CD\u542F\u8BF7\u6C42\u5DF2\u63A5\u6536"))}catch(t){this.logger.error("\u5904\u7406\u91CD\u542F\u8BF7\u6C42\u5931\u8D25:",t);let r=this.createErrorResponse("RESTART_REQUEST_ERROR",t instanceof Error?t.message:"\u5904\u7406\u91CD\u542F\u8BF7\u6C42\u5931\u8D25");return e.json(r,500)}}async executeRestart(){this.logger.info("\u6B63\u5728\u91CD\u542F MCP \u670D\u52A1...");try{let r=await(await Ee()).get("serviceManager").getStatus();if(!r.running){this.logger.warn("MCP \u670D\u52A1\u672A\u8FD0\u884C\uFF0C\u5C1D\u8BD5\u542F\u52A8\u670D\u52A1"),kt("xiaozhi",["start","--daemon"],{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u542F\u52A8\u547D\u4EE4\u5DF2\u53D1\u9001");return}let o=r.mode==="daemon",n=["restart"];o&&n.push("--daemon"),kt("xiaozhi",n,{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u91CD\u542F\u547D\u4EE4\u5DF2\u53D1\u9001")}catch(e){throw this.logger.error("\u91CD\u542F\u670D\u52A1\u5931\u8D25:",e),e}}async stopService(e){try{return this.logger.info("\u5904\u7406\u670D\u52A1\u505C\u6B62\u8BF7\u6C42"),kt("xiaozhi",["stop"],{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u505C\u6B62\u547D\u4EE4\u5DF2\u53D1\u9001"),e.json(this.createSuccessResponse(null,"\u505C\u6B62\u8BF7\u6C42\u5DF2\u63A5\u6536"))}catch(t){this.logger.error("\u5904\u7406\u505C\u6B62\u8BF7\u6C42\u5931\u8D25:",t);let r=this.createErrorResponse("STOP_REQUEST_ERROR",t instanceof Error?t.message:"\u5904\u7406\u505C\u6B62\u8BF7\u6C42\u5931\u8D25");return e.json(r,500)}}async startService(e){try{return this.logger.info("\u5904\u7406\u670D\u52A1\u542F\u52A8\u8BF7\u6C42"),kt("xiaozhi",["start","--daemon"],{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u542F\u52A8\u547D\u4EE4\u5DF2\u53D1\u9001"),e.json(this.createSuccessResponse(null,"\u542F\u52A8\u8BF7\u6C42\u5DF2\u63A5\u6536"))}catch(t){this.logger.error("\u5904\u7406\u542F\u52A8\u8BF7\u6C42\u5931\u8D25:",t);let r=this.createErrorResponse("START_REQUEST_ERROR",t instanceof Error?t.message:"\u5904\u7406\u542F\u52A8\u8BF7\u6C42\u5931\u8D25");return e.json(r,500)}}async getServiceStatus(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u8BF7\u6C42");let o=await(await Ee()).get("serviceManager").getStatus();return this.logger.debug("\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(o))}catch(t){this.logger.error("\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("SERVICE_STATUS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}async getServiceHealth(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u8BF7\u6C42");let t={status:"healthy",timestamp:Date.now(),uptime:process.uptime(),memory:process.memoryUsage(),version:process.version};return this.logger.debug("\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("SERVICE_HEALTH_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}}});import{existsSync as Nt}from"fs";import{readFile as Ps}from"fs/promises";import{dirname as ws,join as fe}from"path";import{fileURLToPath as bs}from"url";var _t,No=m(()=>{"use strict";S();_t=class{static{c(this,"StaticFileHandler")}logger;webPath=null;constructor(){this.logger=g.withTag("StaticFileHandler"),this.initializeWebPath()}initializeWebPath(){try{let e=ws(bs(import.meta.url));this.logger.debug(`\u5F53\u524D\u6587\u4EF6\u76EE\u5F55: ${e}`);let t=[fe(e,"..","..","web","dist"),fe(e,"..","web","dist"),fe(e,"..","..","web"),fe(e,"..","web"),fe(e,"..","..","..","web","dist"),fe(e,"..","..","..","web")];this.webPath=t.find(r=>{let o=Nt(r);return this.logger.debug(`\u68C0\u67E5\u8DEF\u5F84 ${r}: ${o?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}`),o})||null,this.webPath?this.logger.info(`\u9759\u6001\u6587\u4EF6\u670D\u52A1\u8DEF\u5F84: ${this.webPath}`):(this.logger.warn("\u672A\u627E\u5230\u9759\u6001\u6587\u4EF6\u76EE\u5F55"),this.logger.debug("\u5C1D\u8BD5\u7684\u8DEF\u5F84:",t))}catch(e){this.logger.error("\u521D\u59CB\u5316\u9759\u6001\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25:",e)}}async handleStaticFile(e){let t=new URL(e.req.url).pathname;try{if(this.logger.debug(`\u5904\u7406\u9759\u6001\u6587\u4EF6\u8BF7\u6C42: ${t}`),!this.webPath)return this.createErrorPage(e,"\u627E\u4E0D\u5230\u524D\u7AEF\u8D44\u6E90\u6587\u4EF6");let r=t;if(r==="/"&&(r="/index.html"),r.includes(".."))return this.logger.warn(`\u8DEF\u5F84\u904D\u5386\u653B\u51FB\u5C1D\u8BD5: ${r}`),e.text("Forbidden",403);let o=fe(this.webPath,r);if(!Nt(o)){let s=fe(this.webPath,"index.html");return Nt(s)?(this.logger.debug(`SPA \u56DE\u9000\u5230 index.html: ${t}`),this.serveFile(e,s,"text/html")):(this.logger.debug(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`),e.text("Not Found",404))}let n=this.getContentType(o);return this.logger.debug(`\u670D\u52A1\u9759\u6001\u6587\u4EF6: ${o}, Content-Type: ${n}`),this.serveFile(e,o,n)}catch(r){return this.logger.error(`\u670D\u52A1\u9759\u6001\u6587\u4EF6\u9519\u8BEF (${t}):`,r),e.text("Internal Server Error",500)}}async serveFile(e,t,r){try{let o=await Ps(t);return r.startsWith("text/")||r.includes("javascript")||r.includes("json")?e.text(o.toString(),200,{"Content-Type":r}):e.body(new Uint8Array(o),200,{"Content-Type":r})}catch(o){throw this.logger.error(`\u8BFB\u53D6\u6587\u4EF6\u5931\u8D25: ${t}`,o),o}}getContentType(e){let t=e.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",js:"application/javascript",mjs:"application/javascript",css:"text/css",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",eot:"application/vnd.ms-fontobject",pdf:"application/pdf",txt:"text/plain",xml:"application/xml",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}createErrorPage(e,t){let r=`
|