xiaozhi-client 1.7.7 → 1.7.8

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,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- var ct=Object.defineProperty;var hn=Object.getOwnPropertyDescriptor;var un=Object.getOwnPropertyNames;var pn=Object.prototype.hasOwnProperty;var c=(i,e)=>ct(i,"name",{value:e,configurable:!0});var m=(i,e)=>()=>(i&&(e=i(i=0)),e);var B=(i,e)=>{for(var t in e)ct(i,t,{get:e[t],enumerable:!0})},dn=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of un(e))!pn.call(i,o)&&o!==t&&ct(i,o,{get:()=>e[o],enumerable:!(r=hn(e,o))||r.enumerable});return i};var oe=i=>dn(ct({},"__esModule",{value:!0}),i);import*as H from"fs";import*as X from"path";import Be from"chalk";import $e from"pino";import{z as mn}from"zod";function Cn(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 vn(){return Ge||(Ge=new qe(jr)),Ge}function zr(i){jr=i,Ge&&Ge.setLevel(i)}var fn,qe,Ge,jr,g,y=m(()=>{"use strict";fn=mn.enum(["fatal","error","warn","info","debug","trace"]);c(Cn,"formatDateTime");qe=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=fn.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:$e.destination({dest:this.logFilePath,sync:!1,append:!0,mkdir:!0})}),e.length===0&&e.push({level:this.logLevel,stream:$e.destination({dest:"/dev/null"})}),$e({level:this.logLevel,timestamp:$e.stdTimeFunctions?.isoTime||(()=>`,"time":${Date.now()}`),formatters:{level:c((t,r)=>({level:r}),"level")},base:null,serializers:{err:$e.stdSerializers?.err||(t=>t)}},$e.multistream(e,{dedupe:!0}))}createOptimizedConsoleStream(){let e=new Map([[20,{name:"DEBUG",color:Be.gray}],[30,{name:"INFO",color:Be.blue}],[40,{name:"WARN",color:Be.yellow}],[50,{name:"ERROR",color:Be.red}],[60,{name:"FATAL",color:Be.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=Cn(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=X.join(e,"xiaozhi.log"),this.rotateLogFileIfNeeded(),H.existsSync(this.logFilePath)||H.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||!H.existsSync(this.logFilePath)))try{H.statSync(this.logFilePath).size>this.maxLogFileSize&&this.rotateLogFile()}catch{}}rotateLogFile(){if(this.logFilePath)try{let e=X.dirname(this.logFilePath),t=X.basename(this.logFilePath,".log");for(let o=this.maxLogFiles-1;o>=1;o--){let n=X.join(e,`${t}.${o}.log`),s=X.join(e,`${t}.${o+1}.log`);H.existsSync(n)&&(o===this.maxLogFiles-1?H.unlinkSync(n):H.renameSync(n,s))}let r=X.join(e,`${t}.1.log`);H.renameSync(this.logFilePath,r)}catch{}}cleanupOldLogs(){if(this.logFilePath)try{let e=X.dirname(this.logFilePath),t=X.basename(this.logFilePath,".log");for(let r=this.maxLogFiles+1;r<=this.maxLogFiles+10;r++){let o=X.join(e,`${t}.${r}.log`);H.existsSync(o)&&H.unlinkSync(o)}}catch{}}setLogFileOptions(e,t){this.maxLogFileSize=e,this.maxLogFiles=t}withTag(e){return this}close(){}setLevel(e){this.logLevel=this.validateLogLevel(e),this.pinoInstance=this.createPinoInstance()}getLevel(){return this.logLevel}},Ge=null,jr="info";c(vn,"getLogger");c(zr,"setGlobalLogLevel");g=vn()});import{EventEmitter as Sn}from"events";function I(){return xe||(xe=new er),xe}function Ur(){xe&&(xe.destroy(),xe=null)}var er,xe,K=m(()=>{"use strict";y();er=class extends Sn{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")}},xe=null;c(I,"getEventBus");c(Ur,"destroyEventBus")});function yn(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 tr(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(yn(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"}`}}}function v(i){return`${i.slice(0,30)}...${i.slice(-10)}`}var lt=m(()=>{"use strict";c(yn,"getMcpServerCommunicationType");c(tr,"validateMcpServerConfig");c(v,"sliceEndpoint")});import{copyFileSync as Tn,existsSync as gt,readFileSync as En,writeFileSync as Mn}from"fs";import{dirname as Pn,resolve as ye}from"path";import{fileURLToPath as wn}from"url";import*as ht from"comment-json";import Fr from"dayjs";import rr from"json5";import*as Vr from"json5-writer";var Wr,or,nr,u,Z=m(()=>{"use strict";y();K();lt();Wr=Pn(wn(import.meta.url)),or={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},nr=class i{static{c(this,"ConfigManager")}static instance;defaultConfigPath;config=null;currentConfigPath=null;json5Writer=null;eventBus=I();statsUpdateLocks=new Map;statsUpdateLockTimeouts=new Map;STATS_UPDATE_TIMEOUT=5e3;constructor(){let e=[ye(Wr,"templates","default","xiaozhi.config.json"),ye(Wr,"..","templates","default","xiaozhi.config.json"),ye(process.cwd(),"templates","default","xiaozhi.config.json")];this.defaultConfigPath=e.find(t=>gt(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=ye(e,r);if(gt(o))return o}return ye(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=ye(e,r);if(gt(o))return!0}return!1}initConfig(e="json"){if(!gt(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=ye(t,r);Tn(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=En(e,"utf8").replace(/^\uFEFF/,""),n;switch(t){case"json5":n=rr.parse(o),this.json5Writer=Vr.load(o);break;case"jsonc":n=ht.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=tr(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")}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=tr(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),this.eventBus.emitEvent("config:updated",{type:"serverTools",serviceName:e,timestamp:new Date})}removeServerToolsConfig(e){let r={...this.getConfig()};r.mcpServerConfig&&(delete r.mcpServerConfig[e],this.saveConfig(r))}cleanupInvalidServerToolsConfig(){let e=this.getMutableConfig();if(!e.mcpServerConfig)return;let t=Object.keys(e.mcpServers),o=Object.keys(e.mcpServerConfig).filter(n=>!t.includes(n));if(o.length>0){for(let n of o)delete e.mcpServerConfig[n];this.saveConfig(e),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=rr.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=rr.stringify(e,null,2)}break;case"jsonc":try{o=ht.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}Mn(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??or.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??or.heartbeatTimeout,reconnectInterval:t.reconnectInterval??or.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),this.eventBus.emitEvent("config:updated",{type:"customMCP",timestamp:new Date}),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),this.eventBus.emitEvent("config:updated",{type:"customMCP",timestamp:new Date}),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=Fr(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 R=e;o=`${R}__${t}`,n=r,a=`${R}/${t}`}else o=e,n=t,s=r||!0,a=o;let l=this.getCustomMCPTools(),h=l.findIndex(R=>R.name===o);if(h===-1)return;let p=[...l],d=p[h];d.stats||(d.stats={});let C=d.stats.usageCount||0,E=d.stats.lastUsedTime;s&&(d.stats.usageCount=C+1),(!E||new Date(n)>new Date(E))&&(d.stats.lastUsedTime=Fr(n).format("YYYY-MM-DD HH:mm:ss")),await this.updateCustomMCPTools(p)}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())}},u=nr.getInstance()});var sr,Oe,Je,T,ir,Xe=m(()=>{"use strict";sr={NAME:"xiaozhi-mcp-service",DEFAULT_PORT:3e3,DEFAULT_WEB_UI_PORT:9999,PID_FILE:"xiaozhi.pid",LOG_FILE:"xiaozhi.log"},Oe={FILE_NAMES:["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"],DEFAULT_FILE:"xiaozhi.config.default.json",DIR_ENV_VAR:"XIAOZHI_CONFIG_DIR"},Je={WORK_DIR:".xiaozhi",TEMPLATES_DIR:"templates",LOGS_DIR:"logs"},T={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"},ir={PROCESS_STOP:3e3,SERVICE_START:1e4,NETWORK_REQUEST:5e3,FILE_OPERATION:2e3}});var bn,Rn,ut,Br=m(()=>{"use strict";Xe();bn={[T.CONFIG_ERROR]:'\u8FD0\u884C "xiaozhi --help" \u67E5\u770B\u914D\u7F6E\u76F8\u5173\u547D\u4EE4',[T.SERVICE_ERROR]:'\u8FD0\u884C "xiaozhi status" \u68C0\u67E5\u670D\u52A1\u72B6\u6001',[T.VALIDATION_ERROR]:"\u68C0\u67E5\u8F93\u5165\u53C2\u6570\u662F\u5426\u6B63\u786E",[T.FILE_ERROR]:"\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u548C\u6743\u9650",[T.PROCESS_ERROR]:"\u68C0\u67E5\u8FDB\u7A0B\u72B6\u6001\u548C\u6743\u9650",[T.NETWORK_ERROR]:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C\u9632\u706B\u5899\u8BBE\u7F6E",[T.PERMISSION_ERROR]:"\u5C1D\u8BD5\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"},Rn={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"]},ut=class{static{c(this,"ERROR_MESSAGES")}static getHelpMessage(e){return bn[e]}static getSolutions(e){return Rn[e]||[]}static formatError(e,t){return`${t?`[${t}] `:""}${e.message}`}static getFriendlyMessage(e){return{[T.CONFIG_ERROR]:"\u914D\u7F6E\u6587\u4EF6\u76F8\u5173\u9519\u8BEF",[T.SERVICE_ERROR]:"\u670D\u52A1\u8FD0\u884C\u76F8\u5173\u9519\u8BEF",[T.VALIDATION_ERROR]:"\u8F93\u5165\u9A8C\u8BC1\u9519\u8BEF",[T.FILE_ERROR]:"\u6587\u4EF6\u64CD\u4F5C\u9519\u8BEF",[T.PROCESS_ERROR]:"\u8FDB\u7A0B\u7BA1\u7406\u9519\u8BEF",[T.NETWORK_ERROR]:"\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF",[T.PERMISSION_ERROR]:"\u6743\u9650\u4E0D\u8DB3\u9519\u8BEF"}[e]||"\u672A\u77E5\u9519\u8BEF"}static isRecoverable(e){return[T.NETWORK_ERROR,T.FILE_ERROR,T.SERVICE_ERROR].includes(e)}static getSeverity(e){return{[T.VALIDATION_ERROR]:"low",[T.FILE_ERROR]:"medium",[T.CONFIG_ERROR]:"medium",[T.NETWORK_ERROR]:"medium",[T.SERVICE_ERROR]:"high",[T.PROCESS_ERROR]:"high",[T.PERMISSION_ERROR]:"critical"}[e]||"medium"}}});var j,Te,x,M,S,ue,ne=m(()=>{"use strict";Xe();j=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)}},Te=class i extends j{static{c(this,"ConfigError")}constructor(e,t){super(e,T.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"])}},x=class i extends j{static{c(this,"ServiceError")}constructor(e,t){super(e,T.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"])}},M=class i extends j{static{c(this,"ValidationError")}constructor(e,t){super(`\u9A8C\u8BC1\u5931\u8D25: ${t} - ${e}`,T.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)}},S=class i extends j{static{c(this,"FileError")}constructor(e,t,r){let o=t?`${e}: ${t}`:e;super(o,T.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"])}},ue=class i extends j{static{c(this,"ProcessError")}constructor(e,t,r){let o=t?`${e} (PID: ${t})`:e;super(o,T.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 z from"chalk";var se,ar=m(()=>{"use strict";Br();ne();se=class i{static{c(this,"ErrorHandler")}static handle(e){e instanceof j?i.handleCLIError(e):i.handleUnknownError(e),process.exit(1)}static handleCLIError(e){if(console.error(z.red(`\u274C \u9519\u8BEF: ${e.message}`)),process.env.DEBUG&&console.error(z.gray(`\u9519\u8BEF\u7801: ${e.code}`)),e.suggestions&&e.suggestions.length>0){console.log(z.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of e.suggestions)console.log(z.gray(` ${r}`))}let t=ut.getHelpMessage(e.code);t&&console.log(z.blue(`\u2139\uFE0F ${t}`))}static handleUnknownError(e){console.error(z.red(`\u274C \u672A\u77E5\u9519\u8BEF: ${e.message}`)),process.env.DEBUG||process.env.NODE_ENV==="development"?(console.error(z.gray("\u5806\u6808\u4FE1\u606F:")),console.error(z.gray(e.stack))):console.log(z.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 j?r:r instanceof Error?new j(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new j(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static handleSync(e,t){try{return e()}catch(r){throw r instanceof j?r:r instanceof Error?new j(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new j(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static warn(e,t){if(console.warn(z.yellow(`\u26A0\uFE0F \u8B66\u544A: ${e}`)),t&&t.length>0){console.log(z.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of t)console.log(z.gray(` ${r}`))}}static info(e){console.log(z.blue(`\u2139\uFE0F ${e}`))}static success(e){console.log(z.green(`\u2705 ${e}`))}}});import _ from"fs";import Y from"path";var P,Ke=m(()=>{"use strict";ne();P=class i{static{c(this,"FileUtils")}static exists(e){try{return _.existsSync(e)}catch{return!1}}static ensureDir(e){try{_.existsSync(e)||_.mkdirSync(e,{recursive:!0})}catch{throw new S("\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55",e)}}static readFile(e,t="utf8"){try{if(!i.exists(e))throw S.notFound(e);return _.readFileSync(e,t)}catch(r){throw r instanceof S?r:new S("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6",e)}}static writeFile(e,t,r){try{if(!r?.overwrite&&i.exists(e))throw S.alreadyExists(e);let o=Y.dirname(e);i.ensureDir(o),_.writeFileSync(e,t,"utf8")}catch(o){throw o instanceof S?o:new S("\u65E0\u6CD5\u5199\u5165\u6587\u4EF6",e)}}static copyFile(e,t,r){try{if(!i.exists(e))throw S.notFound(e);if(!r?.overwrite&&i.exists(t))throw S.alreadyExists(t);let o=Y.dirname(t);i.ensureDir(o),_.copyFileSync(e,t)}catch(o){throw o instanceof S?o:new S("\u65E0\u6CD5\u590D\u5236\u6587\u4EF6",e)}}static deleteFile(e){try{i.exists(e)&&_.unlinkSync(e)}catch{throw new S("\u65E0\u6CD5\u5220\u9664\u6587\u4EF6",e)}}static copyDirectory(e,t,r={}){try{if(!i.exists(e))throw S.notFound(e);i.ensureDir(t);let o=_.readdirSync(e);for(let n of o){if(r.exclude?.includes(n))continue;let s=Y.join(e,n),a=Y.join(t,n);_.statSync(s).isDirectory()?r.recursive!==!1&&i.copyDirectory(s,a,r):i.copyFile(s,a,{overwrite:r.overwrite})}}catch(o){throw o instanceof S?o:new S("\u65E0\u6CD5\u590D\u5236\u76EE\u5F55",e)}}static deleteDirectory(e,t={}){try{i.exists(e)&&_.rmSync(e,{recursive:t.recursive??!0,force:!0})}catch{throw new S("\u65E0\u6CD5\u5220\u9664\u76EE\u5F55",e)}}static getFileInfo(e){try{if(!i.exists(e))throw S.notFound(e);let t=_.statSync(e);return{size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory(),mtime:t.mtime,ctime:t.ctime}}catch(t){throw t instanceof S?t:new S("\u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F",e)}}static listDirectory(e,t={}){try{if(!i.exists(e))throw S.notFound(e);let r=_.readdirSync(e),o=[];for(let n of r){if(!t.includeHidden&&n.startsWith("."))continue;let s=Y.join(e,n);if(o.push(s),t.recursive&&_.statSync(s).isDirectory()){let a=i.listDirectory(s,t);o=o.concat(a)}}return o}catch(r){throw r instanceof S?r:new S("\u65E0\u6CD5\u5217\u51FA\u76EE\u5F55\u5185\u5BB9",e)}}static createTempFile(e="xiaozhi-",t=".tmp"){let r=process.env.TMPDIR||process.env.TEMP||"/tmp",o=Date.now(),n=Math.random().toString(36).substring(2),s=`${e}${o}-${n}${t}`;return Y.join(r,s)}static checkPermissions(e,t=_.constants.R_OK|_.constants.W_OK){try{return _.accessSync(e,t),!0}catch{return!1}}static getExtension(e){return Y.extname(e).toLowerCase()}static getBaseName(e){return Y.basename(e,Y.extname(e))}static normalizePath(e){return Y.normalize(e)}static resolvePath(e,t){return t?Y.resolve(t,e):Y.resolve(e)}}});var Ae,cr=m(()=>{"use strict";Ae=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+=`
2
+ var lt=Object.defineProperty;var ho=Object.getOwnPropertyDescriptor;var uo=Object.getOwnPropertyNames;var mo=Object.prototype.hasOwnProperty;var c=(i,e)=>lt(i,"name",{value:e,configurable:!0});var m=(i,e)=>()=>(i&&(e=i(i=0)),e);var G=(i,e)=>{for(var t in e)lt(i,t,{get:e[t],enumerable:!0})},fo=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of uo(e))!mo.call(i,n)&&n!==t&&lt(i,n,{get:()=>e[n],enumerable:!(r=ho(e,n))||r.enumerable});return i};var ne=i=>fo(lt({},"__esModule",{value:!0}),i);import*as j from"fs";import*as Z from"path";import Ge from"chalk";import xe from"pino";import{z as Co}from"zod";function So(i){let e=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),r=String(i.getDate()).padStart(2,"0"),n=String(i.getHours()).padStart(2,"0"),o=String(i.getMinutes()).padStart(2,"0"),s=String(i.getSeconds()).padStart(2,"0");return`${e}-${t}-${r} ${n}:${o}:${s}`}function yo(){return qe||(qe=new Je(zr)),qe}function Ur(i){zr=i,qe&&qe.setLevel(i)}var vo,Je,qe,zr,p,y=m(()=>{"use strict";vo=Co.enum(["fatal","error","warn","info","debug","trace"]);c(So,"formatDateTime");Je=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=vo.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:xe.destination({dest:this.logFilePath,sync:!1,append:!0,mkdir:!0})}),e.length===0&&e.push({level:this.logLevel,stream:xe.destination({dest:"/dev/null"})}),xe({level:this.logLevel,timestamp:xe.stdTimeFunctions?.isoTime||(()=>`,"time":${Date.now()}`),formatters:{level:c((t,r)=>({level:r}),"level")},base:null,serializers:{err:xe.stdSerializers?.err||(t=>t)}},xe.multistream(e,{dedupe:!0}))}createOptimizedConsoleStream(){let e=new Map([[20,{name:"DEBUG",color:Ge.gray}],[30,{name:"INFO",color:Ge.blue}],[40,{name:"WARN",color:Ge.yellow}],[50,{name:"ERROR",color:Ge.red}],[60,{name:"FATAL",color:Ge.red}]]);return{write:c(t=>{try{let r=JSON.parse(t),n=this.formatConsoleMessageOptimized(r,e);this.safeWrite(`${n}
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=So(new Date),n=t.get(e.level)||{name:"UNKNOWN",color:c(a=>a,"color")},o=n.color(`[${n.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}] ${o} ${s}`}initLogFile(e){this.logFilePath=Z.join(e,"xiaozhi.log"),this.rotateLogFileIfNeeded(),j.existsSync(this.logFilePath)||j.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(n=>n instanceof Error?{message:n.message,stack:n.stack,name:n.name,cause:n.cause}:n);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,n]of Object.entries(t))n instanceof Error&&(t[r]={message:n.message,stack:n.stack,name:n.name,cause:n.cause});return t}rotateLogFileIfNeeded(){if(!(!this.logFilePath||!j.existsSync(this.logFilePath)))try{j.statSync(this.logFilePath).size>this.maxLogFileSize&&this.rotateLogFile()}catch{}}rotateLogFile(){if(this.logFilePath)try{let e=Z.dirname(this.logFilePath),t=Z.basename(this.logFilePath,".log");for(let n=this.maxLogFiles-1;n>=1;n--){let o=Z.join(e,`${t}.${n}.log`),s=Z.join(e,`${t}.${n+1}.log`);j.existsSync(o)&&(n===this.maxLogFiles-1?j.unlinkSync(o):j.renameSync(o,s))}let r=Z.join(e,`${t}.1.log`);j.renameSync(this.logFilePath,r)}catch{}}cleanupOldLogs(){if(this.logFilePath)try{let e=Z.dirname(this.logFilePath),t=Z.basename(this.logFilePath,".log");for(let r=this.maxLogFiles+1;r<=this.maxLogFiles+10;r++){let n=Z.join(e,`${t}.${r}.log`);j.existsSync(n)&&j.unlinkSync(n)}}catch{}}setLogFileOptions(e,t){this.maxLogFileSize=e,this.maxLogFiles=t}withTag(e){return this}close(){}setLevel(e){this.logLevel=this.validateLogLevel(e),this.pinoInstance=this.createPinoInstance()}getLevel(){return this.logLevel}},qe=null,zr="info";c(yo,"getLogger");c(Ur,"setGlobalLogLevel");p=yo()});import{EventEmitter as Eo}from"events";function M(){return Oe||(Oe=new tr),Oe}function Fr(){Oe&&(Oe.destroy(),Oe=null)}var tr,Oe,z=m(()=>{"use strict";y();tr=class extends Eo{static{c(this,"EventBus")}logger;eventStats=new Map;maxListeners=50;constructor(){super(),this.logger=p.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")}},Oe=null;c(M,"getEventBus");c(Fr,"destroyEventBus")});function To(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 rr(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(To(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"}`}}}function C(i){return`${i.slice(0,30)}...${i.slice(-10)}`}var gt=m(()=>{"use strict";c(To,"getMcpServerCommunicationType");c(rr,"validateMcpServerConfig");c(C,"sliceEndpoint")});import{copyFileSync as Mo,existsSync as pt,readFileSync as Po,writeFileSync as wo}from"fs";import{dirname as bo,resolve as Ee}from"path";import{fileURLToPath as Ro}from"url";import*as ht from"comment-json";import Wr from"dayjs";import nr from"json5";import*as Br from"json5-writer";var Vr,or,sr,h,q=m(()=>{"use strict";y();z();gt();Vr=bo(Ro(import.meta.url)),or={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},sr=class i{static{c(this,"ConfigManager")}static instance;defaultConfigPath;config=null;currentConfigPath=null;json5Writer=null;eventBus=M();statsUpdateLocks=new Map;statsUpdateLockTimeouts=new Map;STATS_UPDATE_TIMEOUT=5e3;constructor(){let e=[Ee(Vr,"templates","default","xiaozhi.config.json"),Ee(Vr,"..","templates","default","xiaozhi.config.json"),Ee(process.cwd(),"templates","default","xiaozhi.config.json")];this.defaultConfigPath=e.find(t=>pt(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 n=Ee(e,r);if(pt(n))return n}return Ee(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 n=Ee(e,r);if(pt(n))return!0}return!1}initConfig(e="json"){if(!pt(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}`,n=Ee(t,r);Mo(this.defaultConfigPath,n),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),n=Po(e,"utf8").replace(/^\uFEFF/,""),o;switch(t){case"json5":o=nr.parse(n),this.json5Writer=Br.load(n);break;case"jsonc":o=ht.parse(n);break;default:o=JSON.parse(n);break}return this.validateConfig(o),o}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,n]of Object.entries(t.mcpServers)){if(!n||typeof n!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${r} \u65E0\u6548`);let o=rr(r,n);if(!o.valid)throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A${o.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")}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 n=[...r,e];t.mcpEndpoint=n,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 o=r.filter(s=>s!==e);t.mcpEndpoint=o,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=rr(e,t);if(!r.valid)throw new Error(r.error||"\u670D\u52A1\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");let n=this.getMutableConfig();n.mcpServers[e]=t,this.saveConfig(n)}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 n={...t,mcpServers:r};this.saveConfig(n)}updateServerToolsConfig(e,t){let r=this.getMutableConfig();r.mcpServerConfig||(r.mcpServerConfig={}),Object.keys(t).length===0?delete r.mcpServerConfig[e]:r.mcpServerConfig[e]={tools:t},this.saveConfig(r),this.eventBus.emitEvent("config:updated",{type:"serverTools",serviceName:e,timestamp:new Date})}removeServerToolsConfig(e){let r={...this.getConfig()};r.mcpServerConfig&&(delete r.mcpServerConfig[e],this.saveConfig(r))}cleanupInvalidServerToolsConfig(){let e=this.getMutableConfig();if(!e.mcpServerConfig)return;let t=Object.keys(e.mcpServers),n=Object.keys(e.mcpServerConfig).filter(o=>!t.includes(o));if(n.length>0){for(let o of n)delete e.mcpServerConfig[o];this.saveConfig(e),p.info(`\u5DF2\u6E05\u7406 ${n.length} \u4E2A\u65E0\u6548\u7684\u670D\u52A1\u5DE5\u5177\u914D\u7F6E: ${n.join(", ")}`)}}setToolEnabled(e,t,r,n){let o=this.getMutableConfig();o.mcpServerConfig||(o.mcpServerConfig={}),o.mcpServerConfig[e]||(o.mcpServerConfig[e]={tools:{}}),o.mcpServerConfig[e].tools[t]={...o.mcpServerConfig[e].tools[t],enable:r,...n&&{description:n}},this.saveConfig(o)}saveConfig(e){try{this.validateConfig(e);let t;this.currentConfigPath?t=this.currentConfigPath:(t=this.getConfigFilePath(),this.currentConfigPath=t);let r=this.getConfigFileFormat(t),n;switch(r){case"json5":try{this.json5Writer?(this.json5Writer.write(e),n=this.json5Writer.toSource()):(console.warn("\u6CA1\u6709 json5Writer \u5B9E\u4F8B\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F"),n=nr.stringify(e,null,2))}catch(o){console.warn("\u4F7F\u7528 json5-writer \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F:",o),n=nr.stringify(e,null,2)}break;case"jsonc":try{n=ht.stringify(e,null,2)}catch(o){console.warn("\u4F7F\u7528 comment-json \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON \u683C\u5F0F:",o),n=JSON.stringify(e,null,2)}break;default:n=JSON.stringify(e,null,2);break}wo(t,n,"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??or.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??or.heartbeatTimeout,reconnectInterval:t.reconnectInterval??or.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 n=e,o=t,s=r;await Promise.all([this._updateMCPServerToolStats(n,o,s),this.updateCustomMCPToolStats(n,o,s)]),p.debug(`\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${n}/${o}`)}else{let n=e,o=t,s=new Date().toISOString();await this.updateCustomMCPToolStats(n,s,o),p.debug(`CustomMCP \u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${n}`)}}catch(n){if(typeof t=="string"&&r){let o=e,s=t;p.error(`\u66F4\u65B0\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${o}/${s}): ${n instanceof Error?n.message:String(n)}`)}else{let o=e;p.error(`\u66F4\u65B0 CustomMCP \u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${o}): ${n instanceof Error?n.message:String(n)}`)}}}async updateMCPServerToolStats(e,t,r,n=!0){await this._updateMCPServerToolStats(e,t,r,n)}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 p.warn(`CustomMCP \u5DE5\u5177\u7F3A\u5C11\u6709\u6548\u7684 name \u5B57\u6BB5: ${JSON.stringify(t)}`),!1;if(!t.description||typeof t.description!="string")return p.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 description \u5B57\u6BB5`),!1;if(!t.inputSchema||typeof t.inputSchema!="object")return p.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 inputSchema \u5B57\u6BB5`),!1;if(!t.handler||typeof t.handler!="object")return p.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 p.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 p.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"?(p.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?(p.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 Coze \u5904\u7406\u5668\u5FC5\u987B\u63D0\u4F9B workflow_id \u6216 bot_id`),!1):!0:(p.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u5E73\u53F0: ${t.platform}`),!1):(p.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 p.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 p.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)?(p.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"?(p.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"?(p.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"?(p.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)?(p.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?(p.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:(p.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):(p.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"?(p.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11 config \u5B57\u6BB5`),!1):!t.config.serviceName||typeof t.config.serviceName!="string"?(p.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"?(p.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 p.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(n=>n.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),p.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(o=>o.name)),n=e.filter(o=>!r.has(o.name));if(n.length>0){if(!this.validateCustomMCPTools(n))throw new Error("\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");t.customMCP.tools.push(...n),this.saveConfig(t),this.eventBus.emitEvent("config:updated",{type:"customMCP",timestamp:new Date}),p.info(`\u6210\u529F\u6279\u91CF\u6DFB\u52A0 ${n.length} \u4E2A\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${n.map(o=>o.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(n=>n.name===e);if(r===-1)throw new Error(`\u5DE5\u5177 "${e}" \u4E0D\u5B58\u5728`);t.customMCP.tools.splice(r,1),this.saveConfig(t),p.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 n=r.customMCP.tools.findIndex(o=>o.name===e);if(n===-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[n]=t,this.saveConfig(r),p.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),this.eventBus.emitEvent("config:updated",{type:"customMCP",timestamp:new Date}),p.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,n=!0){let o=this.getMutableConfig();o.mcpServerConfig||(o.mcpServerConfig={}),o.mcpServerConfig[e]||(o.mcpServerConfig[e]={tools:{}}),o.mcpServerConfig[e].tools[t]||(o.mcpServerConfig[e].tools[t]={enable:!0});let s=o.mcpServerConfig[e].tools[t],a=s.usageCount||0,l=s.lastUsedTime;n&&(s.usageCount=a+1),(!l||new Date(r)>new Date(l))&&(s.lastUsedTime=Wr(r).format("YYYY-MM-DD HH:mm:ss")),this.saveConfig(o)}async updateCustomMCPToolStats(e,t,r){try{let n,o,s=!0,a;if(typeof r=="string"){let I=e;n=`${I}__${t}`,o=r,a=`${I}/${t}`}else n=e,o=t,s=r||!0,a=n;let l=this.getCustomMCPTools(),g=l.findIndex(I=>I.name===n);if(g===-1)return;let u=[...l],d=u[g];d.stats||(d.stats={});let v=d.stats.usageCount||0,T=d.stats.lastUsedTime;s&&(d.stats.usageCount=v+1),(!T||new Date(o)>new Date(T))&&(d.stats.lastUsedTime=Wr(o).format("YYYY-MM-DD HH:mm:ss")),await this.updateCustomMCPTools(u)}catch(n){if(typeof r=="string"){let o=e,s=t;p.error(`\u66F4\u65B0 customMCP \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25 (${o}/${s}): ${n instanceof Error?n.message:String(n)}`)}else{let o=e;p.error(`\u66F4\u65B0 customMCP \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25 (${o}): ${n instanceof Error?n.message:String(n)}`)}}}async acquireStatsUpdateLock(e){if(this.statsUpdateLocks.has(e))return p.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(n=>{});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)),p.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),p.debug(`\u5DE5\u5177 ${e} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(n){throw p.error(`\u5DE5\u5177 ${e} \u7EDF\u8BA1\u66F4\u65B0\u5931\u8D25:`,n),n}finally{this.releaseStatsUpdateLock(r)}}async updateMCPServerToolStatsWithLock(e,t,r,n=!0){let o=`mcpserver_${e}_${t}`;if(await this.acquireStatsUpdateLock(o))try{await this.updateMCPServerToolStats(e,t,r,n),p.debug(`MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(s){throw p.error(`MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u66F4\u65B0\u5931\u8D25:`,s),s}finally{this.releaseStatsUpdateLock(o)}}clearAllStatsUpdateLocks(){let e=this.statsUpdateLocks.size;this.statsUpdateLocks.clear();for(let t of this.statsUpdateLockTimeouts.values())clearTimeout(t);this.statsUpdateLockTimeouts.clear(),e>0&&p.info(`\u5DF2\u6E05\u7406 ${e} \u4E2A\u7EDF\u8BA1\u66F4\u65B0\u9501`)}getStatsUpdateLocks(){return Array.from(this.statsUpdateLocks.keys())}},h=sr.getInstance()});var ir,Ae,Xe,E,ar,Ke=m(()=>{"use strict";ir={NAME:"xiaozhi-mcp-service",DEFAULT_PORT:3e3,DEFAULT_WEB_UI_PORT:9999,PID_FILE:"xiaozhi.pid",LOG_FILE:"xiaozhi.log"},Ae={FILE_NAMES:["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"],DEFAULT_FILE:"xiaozhi.config.default.json",DIR_ENV_VAR:"XIAOZHI_CONFIG_DIR"},Xe={WORK_DIR:".xiaozhi",TEMPLATES_DIR:"templates",LOGS_DIR:"logs"},E={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"},ar={PROCESS_STOP:3e3,SERVICE_START:1e4,NETWORK_REQUEST:5e3,FILE_OPERATION:2e3}});var Io,$o,ut,Gr=m(()=>{"use strict";Ke();Io={[E.CONFIG_ERROR]:'\u8FD0\u884C "xiaozhi --help" \u67E5\u770B\u914D\u7F6E\u76F8\u5173\u547D\u4EE4',[E.SERVICE_ERROR]:'\u8FD0\u884C "xiaozhi status" \u68C0\u67E5\u670D\u52A1\u72B6\u6001',[E.VALIDATION_ERROR]:"\u68C0\u67E5\u8F93\u5165\u53C2\u6570\u662F\u5426\u6B63\u786E",[E.FILE_ERROR]:"\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u548C\u6743\u9650",[E.PROCESS_ERROR]:"\u68C0\u67E5\u8FDB\u7A0B\u72B6\u6001\u548C\u6743\u9650",[E.NETWORK_ERROR]:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C\u9632\u706B\u5899\u8BBE\u7F6E",[E.PERMISSION_ERROR]:"\u5C1D\u8BD5\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"},$o={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"]},ut=class{static{c(this,"ERROR_MESSAGES")}static getHelpMessage(e){return Io[e]}static getSolutions(e){return $o[e]||[]}static formatError(e,t){return`${t?`[${t}] `:""}${e.message}`}static getFriendlyMessage(e){return{[E.CONFIG_ERROR]:"\u914D\u7F6E\u6587\u4EF6\u76F8\u5173\u9519\u8BEF",[E.SERVICE_ERROR]:"\u670D\u52A1\u8FD0\u884C\u76F8\u5173\u9519\u8BEF",[E.VALIDATION_ERROR]:"\u8F93\u5165\u9A8C\u8BC1\u9519\u8BEF",[E.FILE_ERROR]:"\u6587\u4EF6\u64CD\u4F5C\u9519\u8BEF",[E.PROCESS_ERROR]:"\u8FDB\u7A0B\u7BA1\u7406\u9519\u8BEF",[E.NETWORK_ERROR]:"\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF",[E.PERMISSION_ERROR]:"\u6743\u9650\u4E0D\u8DB3\u9519\u8BEF"}[e]||"\u672A\u77E5\u9519\u8BEF"}static isRecoverable(e){return[E.NETWORK_ERROR,E.FILE_ERROR,E.SERVICE_ERROR].includes(e)}static getSeverity(e){return{[E.VALIDATION_ERROR]:"low",[E.FILE_ERROR]:"medium",[E.CONFIG_ERROR]:"medium",[E.NETWORK_ERROR]:"medium",[E.SERVICE_ERROR]:"high",[E.PROCESS_ERROR]:"high",[E.PERMISSION_ERROR]:"critical"}[e]||"medium"}}});var H,Te,x,P,S,he,oe=m(()=>{"use strict";Ke();H=class i extends Error{constructor(t,r,n=1,o){super(t);this.code=r;this.exitCode=n;this.suggestions=o;this.name="CLIError",Error.captureStackTrace&&Error.captureStackTrace(this,i)}static{c(this,"CLIError")}static withSuggestions(t,r,n){return new i(t,r,1,n)}},Te=class i extends H{static{c(this,"ConfigError")}constructor(e,t){super(e,E.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"])}},x=class i extends H{static{c(this,"ServiceError")}constructor(e,t){super(e,E.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"])}},P=class i extends H{static{c(this,"ValidationError")}constructor(e,t){super(`\u9A8C\u8BC1\u5931\u8D25: ${t} - ${e}`,E.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)}},S=class i extends H{static{c(this,"FileError")}constructor(e,t,r){let n=t?`${e}: ${t}`:e;super(n,E.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"])}},he=class i extends H{static{c(this,"ProcessError")}constructor(e,t,r){let n=t?`${e} (PID: ${t})`:e;super(n,E.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 U from"chalk";var se,cr=m(()=>{"use strict";Gr();oe();se=class i{static{c(this,"ErrorHandler")}static handle(e){e instanceof H?i.handleCLIError(e):i.handleUnknownError(e),process.exit(1)}static handleCLIError(e){if(console.error(U.red(`\u274C \u9519\u8BEF: ${e.message}`)),process.env.DEBUG&&console.error(U.gray(`\u9519\u8BEF\u7801: ${e.code}`)),e.suggestions&&e.suggestions.length>0){console.log(U.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of e.suggestions)console.log(U.gray(` ${r}`))}let t=ut.getHelpMessage(e.code);t&&console.log(U.blue(`\u2139\uFE0F ${t}`))}static handleUnknownError(e){console.error(U.red(`\u274C \u672A\u77E5\u9519\u8BEF: ${e.message}`)),process.env.DEBUG||process.env.NODE_ENV==="development"?(console.error(U.gray("\u5806\u6808\u4FE1\u606F:")),console.error(U.gray(e.stack))):console.log(U.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 H?r:r instanceof Error?new H(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new H(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static handleSync(e,t){try{return e()}catch(r){throw r instanceof H?r:r instanceof Error?new H(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new H(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static warn(e,t){if(console.warn(U.yellow(`\u26A0\uFE0F \u8B66\u544A: ${e}`)),t&&t.length>0){console.log(U.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of t)console.log(U.gray(` ${r}`))}}static info(e){console.log(U.blue(`\u2139\uFE0F ${e}`))}static success(e){console.log(U.green(`\u2705 ${e}`))}}});import _ from"fs";import Y from"path";var w,Ze=m(()=>{"use strict";oe();w=class i{static{c(this,"FileUtils")}static exists(e){try{return _.existsSync(e)}catch{return!1}}static ensureDir(e){try{_.existsSync(e)||_.mkdirSync(e,{recursive:!0})}catch{throw new S("\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55",e)}}static readFile(e,t="utf8"){try{if(!i.exists(e))throw S.notFound(e);return _.readFileSync(e,t)}catch(r){throw r instanceof S?r:new S("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6",e)}}static writeFile(e,t,r){try{if(!r?.overwrite&&i.exists(e))throw S.alreadyExists(e);let n=Y.dirname(e);i.ensureDir(n),_.writeFileSync(e,t,"utf8")}catch(n){throw n instanceof S?n:new S("\u65E0\u6CD5\u5199\u5165\u6587\u4EF6",e)}}static copyFile(e,t,r){try{if(!i.exists(e))throw S.notFound(e);if(!r?.overwrite&&i.exists(t))throw S.alreadyExists(t);let n=Y.dirname(t);i.ensureDir(n),_.copyFileSync(e,t)}catch(n){throw n instanceof S?n:new S("\u65E0\u6CD5\u590D\u5236\u6587\u4EF6",e)}}static deleteFile(e){try{i.exists(e)&&_.unlinkSync(e)}catch{throw new S("\u65E0\u6CD5\u5220\u9664\u6587\u4EF6",e)}}static copyDirectory(e,t,r={}){try{if(!i.exists(e))throw S.notFound(e);i.ensureDir(t);let n=_.readdirSync(e);for(let o of n){if(r.exclude?.includes(o))continue;let s=Y.join(e,o),a=Y.join(t,o);_.statSync(s).isDirectory()?r.recursive!==!1&&i.copyDirectory(s,a,r):i.copyFile(s,a,{overwrite:r.overwrite})}}catch(n){throw n instanceof S?n:new S("\u65E0\u6CD5\u590D\u5236\u76EE\u5F55",e)}}static deleteDirectory(e,t={}){try{i.exists(e)&&_.rmSync(e,{recursive:t.recursive??!0,force:!0})}catch{throw new S("\u65E0\u6CD5\u5220\u9664\u76EE\u5F55",e)}}static getFileInfo(e){try{if(!i.exists(e))throw S.notFound(e);let t=_.statSync(e);return{size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory(),mtime:t.mtime,ctime:t.ctime}}catch(t){throw t instanceof S?t:new S("\u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F",e)}}static listDirectory(e,t={}){try{if(!i.exists(e))throw S.notFound(e);let r=_.readdirSync(e),n=[];for(let o of r){if(!t.includeHidden&&o.startsWith("."))continue;let s=Y.join(e,o);if(n.push(s),t.recursive&&_.statSync(s).isDirectory()){let a=i.listDirectory(s,t);n=n.concat(a)}}return n}catch(r){throw r instanceof S?r:new S("\u65E0\u6CD5\u5217\u51FA\u76EE\u5F55\u5185\u5BB9",e)}}static createTempFile(e="xiaozhi-",t=".tmp"){let r=process.env.TMPDIR||process.env.TEMP||"/tmp",n=Date.now(),o=Math.random().toString(36).substring(2),s=`${e}${n}-${o}${t}`;return Y.join(r,s)}static checkPermissions(e,t=_.constants.R_OK|_.constants.W_OK){try{return _.accessSync(e,t),!0}catch{return!1}}static getExtension(e){return Y.extname(e).toLowerCase()}static getBaseName(e){return Y.basename(e,Y.extname(e))}static normalizePath(e){return Y.normalize(e)}static resolvePath(e,t){return t?Y.resolve(t,e):Y.resolve(e)}}});var Ne,lr=m(()=>{"use strict";Ne=class{static{c(this,"FormatUtils")}static formatUptime(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),n=Math.floor(r/60),o=Math.floor(n/24);return o>0?`${o}\u5929 ${n%24}\u5C0F\u65F6 ${r%60}\u5206\u949F`:n>0?`${n}\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,n=0;for(;r>=1024&&n<t.length-1;)r/=1024,n++;return`${r.toFixed(n===0?0:1)} ${t[n]}`}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,n){let o=`${e}://${t}:${r}`;return n?`${o}${n}`:o}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
- `)}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(`
7
- `)}static formatProgressBar(e,t,r=20){let o=Math.min(e/t,1),n=Math.floor(o*r),s=r-n,a="\u2588".repeat(n)+"\u2591".repeat(s),l=Math.floor(o*100);return`[${a}] ${l}% (${e}/${t})`}static formatCommandArgs(e,t){let r=t.map(o=>o.includes(" ")?`"${o}"`:o);return`${e} ${r.join(" ")}`}static truncateText(e,t,r="..."){return e.length<=t?e:e.substring(0,t-r.length)+r}static formatJson(e,t=2){try{return JSON.stringify(e,null,t)}catch{return String(e)}}static formatBoolean(e,t="\u662F",r="\u5426"){return e?t:r}}});import{realpathSync as In}from"fs";import{tmpdir as $n}from"os";import w from"path";import{fileURLToPath as Gr}from"url";var $,ke=m(()=>{"use strict";Xe();Ke();$=class i{static{c(this,"PathUtils")}static getPidFile(){let e=process.env[Oe.DIR_ENV_VAR]||process.cwd();return w.join(e,`.${sr.NAME}.pid`)}static getLogFile(e){let t=e||process.cwd();return w.join(t,sr.LOG_FILE)}static getConfigDir(){return process.env[Oe.DIR_ENV_VAR]||process.cwd()}static getWorkDir(){let e=i.getConfigDir();return w.join(e,Je.WORK_DIR)}static getTemplatesDir(){let e=Gr(import.meta.url),t=w.dirname(e);return[w.join(t,Je.TEMPLATES_DIR),w.join(t,"..","..","..",Je.TEMPLATES_DIR),w.join(t,"..","..","..","..",Je.TEMPLATES_DIR)]}static findTemplatesDir(){let e=i.getTemplatesDir();for(let t of e)if(P.exists(t))return t;return null}static getTemplatePath(e){let t=i.findTemplatesDir();if(!t)return null;let r=w.join(t,e);return P.exists(r)?r:null}static getScriptDir(){let e=Gr(import.meta.url);return w.dirname(e)}static getProjectRoot(){let e=i.getScriptDir();return w.join(e,"..","..","..")}static getDistDir(){let e=i.getProjectRoot();return w.join(e,"dist")}static getRelativePath(e){let t=i.getProjectRoot();return w.relative(t,e)}static resolveConfigPath(e){let t=i.getConfigDir();if(e)return w.join(t,`xiaozhi.config.${e}`);for(let r of Oe.FILE_NAMES){let o=w.join(t,r);if(P.exists(o))return o}return w.join(t,Oe.FILE_NAMES[2])}static getDefaultConfigPath(){let e=i.getProjectRoot();return w.join(e,Oe.DEFAULT_FILE)}static validatePath(e){return!w.normalize(e).includes("..")}static ensurePathWithin(e,t){let r=w.resolve(t,e),o=w.resolve(t);if(!r.startsWith(o))throw new Error(`\u8DEF\u5F84 ${e} \u8D85\u51FA\u4E86\u5141\u8BB8\u7684\u8303\u56F4`);return r}static getExecutablePath(e){let t=process.argv[1];if(!t)return w.join(process.cwd(),`${e}.js`);let r;try{r=In(t)}catch{r=t}let o=w.dirname(r);return w.join(o,`${e}.js`)}static getMcpServerProxyPath(){return i.getExecutablePath("mcpServerProxy")}static getWebServerStandalonePath(){return i.getExecutablePath("WebServerStandalone")}static createSafePath(...e){let t=w.join(...e),r=w.normalize(t);if(r.includes("..")||r.includes("~"))throw new Error(`\u4E0D\u5B89\u5168\u7684\u8DEF\u5F84: ${r}`);return r}static getTempDir(){return process.env.TMPDIR||process.env.TEMP||$n()}static getHomeDir(){return process.env.HOME||process.env.USERPROFILE||""}}});import{execSync as qr}from"child_process";var G,Ze=m(()=>{"use strict";Xe();ne();G=class i{static{c(this,"PlatformUtils")}static getCurrentPlatform(){return process.platform}static isWindows(){return process.platform==="win32"}static isMacOS(){return process.platform==="darwin"}static isLinux(){return process.platform==="linux"}static isUnixLike(){return!i.isWindows()}static isXiaozhiProcess(e){try{if(process.env.XIAOZHI_CONTAINER==="true"||process.env.NODE_ENV==="test")return process.kill(e,0),!0;try{let t="";return i.isWindows()?t=qr(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{encoding:"utf8",timeout:ir.PROCESS_STOP}).toLowerCase():t=qr(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:ir.PROCESS_STOP}).toLowerCase(),t.includes("node")||t.includes("xiaozhi")}catch{return process.kill(e,0),!0}}catch{return!1}}static async killProcess(e,t="SIGTERM"){try{process.kill(e,t);let r=0,o=30;for(;r<o;){await new Promise(n=>setTimeout(n,100));try{process.kill(e,0),r++}catch{return}}try{process.kill(e,0),process.kill(e,"SIGKILL"),await new Promise(n=>setTimeout(n,500))}catch{}}catch(r){throw new ue(`\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B: ${r instanceof Error?r.message:String(r)}`,e)}}static processExists(e){try{return process.kill(e,0),!0}catch{return!1}}static getSystemInfo(){return{platform:i.getCurrentPlatform(),arch:process.arch,nodeVersion:process.version,isContainer:process.env.XIAOZHI_CONTAINER==="true"}}static getEnvVar(e,t){return process.env[e]||t}static setEnvVar(e,t){process.env[e]=t}static isContainerEnvironment(){return process.env.XIAOZHI_CONTAINER==="true"}static isTestEnvironment(){return process.env.NODE_ENV==="test"}static isDevelopmentEnvironment(){return process.env.NODE_ENV==="development"}static getTailCommand(e){return i.isWindows()?{command:"powershell",args:["-Command",`Get-Content -Path "${e}" -Wait`]}:{command:"tail",args:["-f",e]}}}});var Q,pt=m(()=>{"use strict";ne();Q=class i{static{c(this,"Validation")}static validatePort(e){if(!Number.isInteger(e)||e<1||e>65535)throw M.invalidPort(e)}static validateConfigFormat(e){let t=["json","json5","jsonc"];if(!t.includes(e))throw new M(`\u65E0\u6548\u7684\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F: ${e}\uFF0C\u652F\u6301\u7684\u683C\u5F0F: ${t.join(", ")}`,"format");return e}static validateRequired(e,t){if(e==null||e==="")throw M.requiredField(t)}static validateStringLength(e,t,r={}){if(r.min!==void 0&&e.length<r.min)throw new M(`\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E ${r.min} \u4E2A\u5B57\u7B26\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t);if(r.max!==void 0&&e.length>r.max)throw new M(`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${r.max} \u4E2A\u5B57\u7B26\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t)}static validateUrl(e,t="url"){try{new URL(e)}catch{throw new M(`\u65E0\u6548\u7684 URL \u683C\u5F0F: ${e}`,t)}}static validateWebSocketUrl(e,t="websocket_url"){i.validateUrl(e,t);let r=new URL(e);if(!["ws:","wss:"].includes(r.protocol))throw new M(`WebSocket URL \u5FC5\u987B\u4F7F\u7528 ws:// \u6216 wss:// \u534F\u8BAE\uFF0C\u5F53\u524D\u534F\u8BAE: ${r.protocol}`,t)}static validateHttpUrl(e,t="http_url"){i.validateUrl(e,t);let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new M(`HTTP URL \u5FC5\u987B\u4F7F\u7528 http:// \u6216 https:// \u534F\u8BAE\uFF0C\u5F53\u524D\u534F\u8BAE: ${r.protocol}`,t)}static validateProjectName(e){i.validateRequired(e,"projectName"),i.validateStringLength(e,"projectName",{min:1,max:100});let t=/[<>:"/\\|?*]/,r=e.split("").some(o=>o.charCodeAt(0)<32);if(t.test(e)||r)throw new M('\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u5305\u542B\u4EE5\u4E0B\u5B57\u7B26: < > : " / \\ | ? * \u4EE5\u53CA\u63A7\u5236\u5B57\u7B26',"projectName");if(e.startsWith("."))throw new M("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4EE5\u70B9\u5F00\u5934","projectName")}static validateTemplateName(e){if(i.validateRequired(e,"templateName"),i.validateStringLength(e,"templateName",{min:1,max:50}),!/^[a-zA-Z0-9_-]+$/.test(e))throw new M("\u6A21\u677F\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\u548C\u4E0B\u5212\u7EBF","templateName")}static validateEnvVarName(e){if(i.validateRequired(e,"envVarName"),!/^[A-Z_][A-Z0-9_]*$/.test(e))throw new M("\u73AF\u5883\u53D8\u91CF\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5927\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u4EE5\u6570\u5B57\u5F00\u5934","envVarName")}static validateJson(e,t="json"){try{return JSON.parse(e)}catch(r){throw new M(`\u65E0\u6548\u7684 JSON \u683C\u5F0F: ${r instanceof Error?r.message:String(r)}`,t)}}static validateNumberRange(e,t,r={}){if(r.min!==void 0&&e<r.min)throw new M(`\u503C\u4E0D\u80FD\u5C0F\u4E8E ${r.min}\uFF0C\u5F53\u524D\u503C: ${e}`,t);if(r.max!==void 0&&e>r.max)throw new M(`\u503C\u4E0D\u80FD\u5927\u4E8E ${r.max}\uFF0C\u5F53\u524D\u503C: ${e}`,t)}static validateArrayLength(e,t,r={}){if(r.min!==void 0&&e.length<r.min)throw new M(`\u6570\u7EC4\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E ${r.min}\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t);if(r.max!==void 0&&e.length>r.max)throw new M(`\u6570\u7EC4\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${r.max}\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t)}static validateObjectProperties(e,t,r="object"){for(let o of t)if(!(o in e))throw new M(`\u7F3A\u5C11\u5FC5\u9700\u7684\u5C5E\u6027: ${o}`,r)}static validateEnum(e,t,r){if(!t.includes(e))throw new M(`\u65E0\u6548\u7684\u503C: ${e}\uFF0C\u6709\u6548\u503C: ${t.join(", ")}`,r);return e}static validateRegex(e,t="regex"){try{return new RegExp(e)}catch(r){throw new M(`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${r instanceof Error?r.message:String(r)}`,t)}}}});import dt from"fs";import ie from"path";import{fileURLToPath as Jr}from"url";var me,lr=m(()=>{"use strict";ne();me=class i{static{c(this,"VersionUtils")}static cachedVersion=null;static getVersion(){if(i.cachedVersion)return i.cachedVersion;try{let e=Jr(import.meta.url),t=ie.dirname(e),r=[ie.join(t,"package.json"),ie.join(t,"..","package.json"),ie.join(t,"..","..","..","package.json"),ie.join(t,"..","..","..","..","package.json")];for(let o of r)if(dt.existsSync(o)){let n=JSON.parse(dt.readFileSync(o,"utf8"));if(n.version)return i.cachedVersion=n.version,n.version}return i.cachedVersion="unknown","unknown"}catch(e){return console.warn("\u65E0\u6CD5\u4ECE package.json \u8BFB\u53D6\u7248\u672C\u4FE1\u606F:",e),i.cachedVersion="unknown","unknown"}}static getVersionInfo(){try{let e=Jr(import.meta.url),t=ie.dirname(e),r=[ie.join(t,"package.json"),ie.join(t,"..","package.json"),ie.join(t,"..","..","..","package.json"),ie.join(t,"..","..","..","..","package.json")];for(let o of r)if(dt.existsSync(o)){let n=JSON.parse(dt.readFileSync(o,"utf8"));return{version:n.version||"unknown",name:n.name,description:n.description,author:n.author}}return{version:"unknown"}}catch{throw new S("\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C\u4FE1\u606F","package.json")}}static compareVersions(e,t){let r=e.split(".").map(Number),o=t.split(".").map(Number),n=Math.max(r.length,o.length);for(let s=0;s<n;s++){let a=r[s]||0,l=o[s]||0;if(a>l)return 1;if(a<l)return-1}return 0}static isValidVersion(e){return/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?$/.test(e)}static clearCache(){i.cachedVersion=null}}});var Xr={};B(Xr,{ProcessManagerImpl:()=>Ye});var Ye,gr=m(()=>{"use strict";ne();Ke();cr();ke();Ze();Ye=class{static{c(this,"ProcessManagerImpl")}getPidFilePath(){return $.getPidFile()}readPidFile(){try{let e=this.getPidFilePath();if(!P.exists(e))return null;let t=P.readFile(e).trim(),[r,o,n]=t.split("|"),s=Number.parseInt(r),a=Number.parseInt(o);return Number.isNaN(s)||Number.isNaN(a)?(this.cleanupPidFile(),null):{pid:s,startTime:a,mode:n||"foreground"}}catch{return this.cleanupPidFile(),null}}writePidFile(e,t){try{let r=`${e}|${Date.now()}|${t}`,o=this.getPidFilePath();P.writeFile(o,r,{overwrite:!0})}catch{throw new S("\u65E0\u6CD5\u5199\u5165 PID \u6587\u4EF6",this.getPidFilePath())}}isXiaozhiProcess(e){return G.isXiaozhiProcess(e)}getServiceStatus(){try{let e=this.readPidFile();if(!e)return{running:!1};if(!this.isXiaozhiProcess(e.pid))return this.cleanupPidFile(),{running:!1};let t=Ae.formatUptime(Date.now()-e.startTime);return{running:!0,pid:e.pid,uptime:t,mode:e.mode}}catch{return{running:!1}}}savePidInfo(e,t){this.writePidFile(e,t)}async killProcess(e){try{await G.killProcess(e)}catch(t){throw new ue(`\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B: ${t instanceof Error?t.message:String(t)}`,e)}}async gracefulKillProcess(e){try{process.kill(e,"SIGTERM");let t=0,r=30;for(;t<r;){await new Promise(o=>setTimeout(o,100));try{process.kill(e,0),t++}catch{return}}try{process.kill(e,0),process.kill(e,"SIGKILL"),await new Promise(o=>setTimeout(o,500))}catch{}}catch(t){throw new ue(`\u65E0\u6CD5\u505C\u6B62\u8FDB\u7A0B: ${t instanceof Error?t.message:String(t)}`,e)}}cleanupPidFile(){try{let e=this.getPidFilePath();P.exists(e)&&P.deleteFile(e)}catch(e){console.warn("\u6E05\u7406 PID \u6587\u4EF6\u5931\u8D25:",e)}}processExists(e){return G.processExists(e)}cleanupContainerState(){if(G.isContainerEnvironment())try{this.cleanupPidFile()}catch{}}getProcessInfo(e){let t=this.processExists(e),r=t?this.isXiaozhiProcess(e):!1;return{exists:t,isXiaozhi:r}}validatePidFile(){try{return this.readPidFile()!==null}catch{return!1}}}});var Zr={};B(Zr,{DaemonManagerImpl:()=>hr});import{spawn as Kr}from"child_process";import mt from"fs";var hr,Yr=m(()=>{"use strict";ne();ke();Ze();hr=class{constructor(e,t){this.processManager=e;this.logger=t}static{c(this,"DaemonManagerImpl")}currentDaemon=null;async startDaemon(e,t={}){try{let r=this.processManager.getServiceStatus();if(r.running)throw x.alreadyRunning(r.pid);let o=await this.spawnDaemonProcess(e,t);this.currentDaemon=o,this.processManager.savePidInfo(o.pid,"daemon"),await this.setupLogging(o,t.logFileName||"xiaozhi.log"),this.setupEventHandlers(o),o.unref(),this.logger.info(`\u5B88\u62A4\u8FDB\u7A0B\u5DF2\u542F\u52A8 (PID: ${o.pid})`)}catch(r){throw new x(`\u542F\u52A8\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}async stopDaemon(){try{let e=this.processManager.getServiceStatus();if(!e.running)throw x.notRunning();await this.processManager.gracefulKillProcess(e.pid),this.processManager.cleanupPidFile(),this.currentDaemon=null,this.logger.info("\u5B88\u62A4\u8FDB\u7A0B\u5DF2\u505C\u6B62")}catch(e){throw new x(`\u505C\u6B62\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async restartDaemon(e,t={}){try{this.processManager.getServiceStatus().running&&(await this.stopDaemon(),await new Promise(o=>setTimeout(o,1e3))),await this.startDaemon(e,t)}catch(r){throw new x(`\u91CD\u542F\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}getDaemonStatus(){return this.processManager.getServiceStatus()}async attachToLogs(e="xiaozhi.log"){try{let t=$.getLogFile();if(!mt.existsSync(t))throw new x("\u65E5\u5FD7\u6587\u4EF6\u4E0D\u5B58\u5728");let{command:r,args:o}=G.getTailCommand(t),n=Kr(r,o,{stdio:"inherit"});process.on("SIGINT",()=>{console.log(`
8
- \u65AD\u5F00\u8FDE\u63A5\uFF0C\u670D\u52A1\u7EE7\u7EED\u5728\u540E\u53F0\u8FD0\u884C`),n.kill(),process.exit(0)}),n.on("exit",()=>{process.exit(0)}),n.on("error",s=>{throw new x(`\u8FDE\u63A5\u65E5\u5FD7\u5931\u8D25: ${s.message}`)})}catch(t){throw new x(`\u8FDE\u63A5\u65E5\u5FD7\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}async spawnDaemonProcess(e,t){let o=[$.getWebServerStandalonePath()];t.openBrowser&&o.push("--open-browser");let n={...process.env,XIAOZHI_CONFIG_DIR:$.getConfigDir(),XIAOZHI_DAEMON:"true",...t.env},s=Kr("node",o,{detached:!0,stdio:["ignore","pipe","pipe"],env:n,cwd:t.cwd||process.cwd()});if(!s.pid)throw new ue("\u65E0\u6CD5\u542F\u52A8\u5B88\u62A4\u8FDB\u7A0B",0);return s}async setupLogging(e,t){try{let r=$.getLogFile(),n=(await import("path")).dirname(r);mt.existsSync(n)||mt.mkdirSync(n,{recursive:!0});let s=mt.createWriteStream(r,{flags:"a"});e.stdout?.pipe(s),e.stderr?.pipe(s);let a=new Date().toISOString();s.write(`
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))),n=t.map((a,l)=>a.padEnd(r[l])).join(" | "),o=r.map(a=>"-".repeat(a)).join("-|-"),s=e.map(a=>t.map((l,g)=>String(a[l]).padEnd(r[g])).join(" | "));return[n,o,...s].join(`
7
+ `)}static formatProgressBar(e,t,r=20){let n=Math.min(e/t,1),o=Math.floor(n*r),s=r-o,a="\u2588".repeat(o)+"\u2591".repeat(s),l=Math.floor(n*100);return`[${a}] ${l}% (${e}/${t})`}static formatCommandArgs(e,t){let r=t.map(n=>n.includes(" ")?`"${n}"`:n);return`${e} ${r.join(" ")}`}static truncateText(e,t,r="..."){return e.length<=t?e:e.substring(0,t-r.length)+r}static formatJson(e,t=2){try{return JSON.stringify(e,null,t)}catch{return String(e)}}static formatBoolean(e,t="\u662F",r="\u5426"){return e?t:r}}});import{realpathSync as xo}from"fs";import{tmpdir as Oo}from"os";import b from"path";import{fileURLToPath as qr}from"url";var $,De=m(()=>{"use strict";Ke();Ze();$=class i{static{c(this,"PathUtils")}static getPidFile(){let e=process.env[Ae.DIR_ENV_VAR]||process.cwd();return b.join(e,`.${ir.NAME}.pid`)}static getLogFile(e){let t=e||process.cwd();return b.join(t,ir.LOG_FILE)}static getConfigDir(){return process.env[Ae.DIR_ENV_VAR]||process.cwd()}static getWorkDir(){let e=i.getConfigDir();return b.join(e,Xe.WORK_DIR)}static getTemplatesDir(){let e=qr(import.meta.url),t=b.dirname(e);return[b.join(t,Xe.TEMPLATES_DIR),b.join(t,"..","..","..",Xe.TEMPLATES_DIR),b.join(t,"..","..","..","..",Xe.TEMPLATES_DIR)]}static findTemplatesDir(){let e=i.getTemplatesDir();for(let t of e)if(w.exists(t))return t;return null}static getTemplatePath(e){let t=i.findTemplatesDir();if(!t)return null;let r=b.join(t,e);return w.exists(r)?r:null}static getScriptDir(){let e=qr(import.meta.url);return b.dirname(e)}static getProjectRoot(){let e=i.getScriptDir();return b.join(e,"..","..","..")}static getDistDir(){let e=i.getProjectRoot();return b.join(e,"dist")}static getRelativePath(e){let t=i.getProjectRoot();return b.relative(t,e)}static resolveConfigPath(e){let t=i.getConfigDir();if(e)return b.join(t,`xiaozhi.config.${e}`);for(let r of Ae.FILE_NAMES){let n=b.join(t,r);if(w.exists(n))return n}return b.join(t,Ae.FILE_NAMES[2])}static getDefaultConfigPath(){let e=i.getProjectRoot();return b.join(e,Ae.DEFAULT_FILE)}static validatePath(e){return!b.normalize(e).includes("..")}static ensurePathWithin(e,t){let r=b.resolve(t,e),n=b.resolve(t);if(!r.startsWith(n))throw new Error(`\u8DEF\u5F84 ${e} \u8D85\u51FA\u4E86\u5141\u8BB8\u7684\u8303\u56F4`);return r}static getExecutablePath(e){let t=process.argv[1];if(!t)return b.join(process.cwd(),`${e}.js`);let r;try{r=xo(t)}catch{r=t}let n=b.dirname(r);return b.join(n,`${e}.js`)}static getMcpServerProxyPath(){return i.getExecutablePath("mcpServerProxy")}static getWebServerStandalonePath(){return i.getExecutablePath("WebServerStandalone")}static createSafePath(...e){let t=b.join(...e),r=b.normalize(t);if(r.includes("..")||r.includes("~"))throw new Error(`\u4E0D\u5B89\u5168\u7684\u8DEF\u5F84: ${r}`);return r}static getTempDir(){return process.env.TMPDIR||process.env.TEMP||Oo()}static getHomeDir(){return process.env.HOME||process.env.USERPROFILE||""}}});import{execSync as Jr}from"child_process";var J,Ye=m(()=>{"use strict";Ke();oe();J=class i{static{c(this,"PlatformUtils")}static getCurrentPlatform(){return process.platform}static isWindows(){return process.platform==="win32"}static isMacOS(){return process.platform==="darwin"}static isLinux(){return process.platform==="linux"}static isUnixLike(){return!i.isWindows()}static isXiaozhiProcess(e){try{if(process.env.XIAOZHI_CONTAINER==="true"||process.env.NODE_ENV==="test")return process.kill(e,0),!0;try{let t="";return i.isWindows()?t=Jr(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{encoding:"utf8",timeout:ar.PROCESS_STOP}).toLowerCase():t=Jr(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:ar.PROCESS_STOP}).toLowerCase(),t.includes("node")||t.includes("xiaozhi")}catch{return process.kill(e,0),!0}}catch{return!1}}static async killProcess(e,t="SIGTERM"){try{process.kill(e,t);let r=0,n=30;for(;r<n;){await new Promise(o=>setTimeout(o,100));try{process.kill(e,0),r++}catch{return}}try{process.kill(e,0),process.kill(e,"SIGKILL"),await new Promise(o=>setTimeout(o,500))}catch{}}catch(r){throw new he(`\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B: ${r instanceof Error?r.message:String(r)}`,e)}}static processExists(e){try{return process.kill(e,0),!0}catch{return!1}}static getSystemInfo(){return{platform:i.getCurrentPlatform(),arch:process.arch,nodeVersion:process.version,isContainer:process.env.XIAOZHI_CONTAINER==="true"}}static getEnvVar(e,t){return process.env[e]||t}static setEnvVar(e,t){process.env[e]=t}static isContainerEnvironment(){return process.env.XIAOZHI_CONTAINER==="true"}static isTestEnvironment(){return process.env.NODE_ENV==="test"}static isDevelopmentEnvironment(){return process.env.NODE_ENV==="development"}static getTailCommand(e){return i.isWindows()?{command:"powershell",args:["-Command",`Get-Content -Path "${e}" -Wait`]}:{command:"tail",args:["-f",e]}}}});var Q,dt=m(()=>{"use strict";oe();Q=class i{static{c(this,"Validation")}static validatePort(e){if(!Number.isInteger(e)||e<1||e>65535)throw P.invalidPort(e)}static validateConfigFormat(e){let t=["json","json5","jsonc"];if(!t.includes(e))throw new P(`\u65E0\u6548\u7684\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F: ${e}\uFF0C\u652F\u6301\u7684\u683C\u5F0F: ${t.join(", ")}`,"format");return e}static validateRequired(e,t){if(e==null||e==="")throw P.requiredField(t)}static validateStringLength(e,t,r={}){if(r.min!==void 0&&e.length<r.min)throw new P(`\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E ${r.min} \u4E2A\u5B57\u7B26\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t);if(r.max!==void 0&&e.length>r.max)throw new P(`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${r.max} \u4E2A\u5B57\u7B26\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t)}static validateUrl(e,t="url"){try{new URL(e)}catch{throw new P(`\u65E0\u6548\u7684 URL \u683C\u5F0F: ${e}`,t)}}static validateWebSocketUrl(e,t="websocket_url"){i.validateUrl(e,t);let r=new URL(e);if(!["ws:","wss:"].includes(r.protocol))throw new P(`WebSocket URL \u5FC5\u987B\u4F7F\u7528 ws:// \u6216 wss:// \u534F\u8BAE\uFF0C\u5F53\u524D\u534F\u8BAE: ${r.protocol}`,t)}static validateHttpUrl(e,t="http_url"){i.validateUrl(e,t);let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new P(`HTTP URL \u5FC5\u987B\u4F7F\u7528 http:// \u6216 https:// \u534F\u8BAE\uFF0C\u5F53\u524D\u534F\u8BAE: ${r.protocol}`,t)}static validateProjectName(e){i.validateRequired(e,"projectName"),i.validateStringLength(e,"projectName",{min:1,max:100});let t=/[<>:"/\\|?*]/,r=e.split("").some(n=>n.charCodeAt(0)<32);if(t.test(e)||r)throw new P('\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u5305\u542B\u4EE5\u4E0B\u5B57\u7B26: < > : " / \\ | ? * \u4EE5\u53CA\u63A7\u5236\u5B57\u7B26',"projectName");if(e.startsWith("."))throw new P("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4EE5\u70B9\u5F00\u5934","projectName")}static validateTemplateName(e){if(i.validateRequired(e,"templateName"),i.validateStringLength(e,"templateName",{min:1,max:50}),!/^[a-zA-Z0-9_-]+$/.test(e))throw new P("\u6A21\u677F\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\u548C\u4E0B\u5212\u7EBF","templateName")}static validateEnvVarName(e){if(i.validateRequired(e,"envVarName"),!/^[A-Z_][A-Z0-9_]*$/.test(e))throw new P("\u73AF\u5883\u53D8\u91CF\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5927\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u4EE5\u6570\u5B57\u5F00\u5934","envVarName")}static validateJson(e,t="json"){try{return JSON.parse(e)}catch(r){throw new P(`\u65E0\u6548\u7684 JSON \u683C\u5F0F: ${r instanceof Error?r.message:String(r)}`,t)}}static validateNumberRange(e,t,r={}){if(r.min!==void 0&&e<r.min)throw new P(`\u503C\u4E0D\u80FD\u5C0F\u4E8E ${r.min}\uFF0C\u5F53\u524D\u503C: ${e}`,t);if(r.max!==void 0&&e>r.max)throw new P(`\u503C\u4E0D\u80FD\u5927\u4E8E ${r.max}\uFF0C\u5F53\u524D\u503C: ${e}`,t)}static validateArrayLength(e,t,r={}){if(r.min!==void 0&&e.length<r.min)throw new P(`\u6570\u7EC4\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E ${r.min}\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t);if(r.max!==void 0&&e.length>r.max)throw new P(`\u6570\u7EC4\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${r.max}\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t)}static validateObjectProperties(e,t,r="object"){for(let n of t)if(!(n in e))throw new P(`\u7F3A\u5C11\u5FC5\u9700\u7684\u5C5E\u6027: ${n}`,r)}static validateEnum(e,t,r){if(!t.includes(e))throw new P(`\u65E0\u6548\u7684\u503C: ${e}\uFF0C\u6709\u6548\u503C: ${t.join(", ")}`,r);return e}static validateRegex(e,t="regex"){try{return new RegExp(e)}catch(r){throw new P(`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${r instanceof Error?r.message:String(r)}`,t)}}}});import mt from"fs";import ie from"path";import{fileURLToPath as Xr}from"url";var fe,gr=m(()=>{"use strict";oe();fe=class i{static{c(this,"VersionUtils")}static cachedVersion=null;static getVersion(){if(i.cachedVersion)return i.cachedVersion;try{let e=Xr(import.meta.url),t=ie.dirname(e),r=[ie.join(t,"package.json"),ie.join(t,"..","package.json"),ie.join(t,"..","..","..","package.json"),ie.join(t,"..","..","..","..","package.json")];for(let n of r)if(mt.existsSync(n)){let o=JSON.parse(mt.readFileSync(n,"utf8"));if(o.version)return i.cachedVersion=o.version,o.version}return i.cachedVersion="unknown","unknown"}catch(e){return console.warn("\u65E0\u6CD5\u4ECE package.json \u8BFB\u53D6\u7248\u672C\u4FE1\u606F:",e),i.cachedVersion="unknown","unknown"}}static getVersionInfo(){try{let e=Xr(import.meta.url),t=ie.dirname(e),r=[ie.join(t,"package.json"),ie.join(t,"..","package.json"),ie.join(t,"..","..","..","package.json"),ie.join(t,"..","..","..","..","package.json")];for(let n of r)if(mt.existsSync(n)){let o=JSON.parse(mt.readFileSync(n,"utf8"));return{version:o.version||"unknown",name:o.name,description:o.description,author:o.author}}return{version:"unknown"}}catch{throw new S("\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C\u4FE1\u606F","package.json")}}static compareVersions(e,t){let r=e.split(".").map(Number),n=t.split(".").map(Number),o=Math.max(r.length,n.length);for(let s=0;s<o;s++){let a=r[s]||0,l=n[s]||0;if(a>l)return 1;if(a<l)return-1}return 0}static isValidVersion(e){return/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?$/.test(e)}static clearCache(){i.cachedVersion=null}}});var Kr={};G(Kr,{ProcessManagerImpl:()=>Qe});var Qe,pr=m(()=>{"use strict";oe();Ze();lr();De();Ye();Qe=class{static{c(this,"ProcessManagerImpl")}getPidFilePath(){return $.getPidFile()}readPidFile(){try{let e=this.getPidFilePath();if(!w.exists(e))return null;let t=w.readFile(e).trim(),[r,n,o]=t.split("|"),s=Number.parseInt(r),a=Number.parseInt(n);return Number.isNaN(s)||Number.isNaN(a)?(this.cleanupPidFile(),null):{pid:s,startTime:a,mode:o||"foreground"}}catch{return this.cleanupPidFile(),null}}writePidFile(e,t){try{let r=`${e}|${Date.now()}|${t}`,n=this.getPidFilePath();w.writeFile(n,r,{overwrite:!0})}catch{throw new S("\u65E0\u6CD5\u5199\u5165 PID \u6587\u4EF6",this.getPidFilePath())}}isXiaozhiProcess(e){return J.isXiaozhiProcess(e)}getServiceStatus(){try{let e=this.readPidFile();if(!e)return{running:!1};if(!this.isXiaozhiProcess(e.pid))return this.cleanupPidFile(),{running:!1};let t=Ne.formatUptime(Date.now()-e.startTime);return{running:!0,pid:e.pid,uptime:t,mode:e.mode}}catch{return{running:!1}}}savePidInfo(e,t){this.writePidFile(e,t)}async killProcess(e){try{await J.killProcess(e)}catch(t){throw new he(`\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B: ${t instanceof Error?t.message:String(t)}`,e)}}async gracefulKillProcess(e){try{process.kill(e,"SIGTERM");let t=0,r=30;for(;t<r;){await new Promise(n=>setTimeout(n,100));try{process.kill(e,0),t++}catch{return}}try{process.kill(e,0),process.kill(e,"SIGKILL"),await new Promise(n=>setTimeout(n,500))}catch{}}catch(t){throw new he(`\u65E0\u6CD5\u505C\u6B62\u8FDB\u7A0B: ${t instanceof Error?t.message:String(t)}`,e)}}cleanupPidFile(){try{let e=this.getPidFilePath();w.exists(e)&&w.deleteFile(e)}catch(e){console.warn("\u6E05\u7406 PID \u6587\u4EF6\u5931\u8D25:",e)}}processExists(e){return J.processExists(e)}cleanupContainerState(){if(J.isContainerEnvironment())try{this.cleanupPidFile()}catch{}}getProcessInfo(e){let t=this.processExists(e),r=t?this.isXiaozhiProcess(e):!1;return{exists:t,isXiaozhi:r}}validatePidFile(){try{return this.readPidFile()!==null}catch{return!1}}}});var Yr={};G(Yr,{DaemonManagerImpl:()=>hr});import{spawn as Zr}from"child_process";import ft from"fs";var hr,Qr=m(()=>{"use strict";oe();De();Ye();hr=class{constructor(e,t){this.processManager=e;this.logger=t}static{c(this,"DaemonManagerImpl")}currentDaemon=null;async startDaemon(e,t={}){try{let r=this.processManager.getServiceStatus();if(r.running)throw x.alreadyRunning(r.pid);let n=await this.spawnDaemonProcess(e,t);this.currentDaemon=n,this.processManager.savePidInfo(n.pid,"daemon"),await this.setupLogging(n,t.logFileName||"xiaozhi.log"),this.setupEventHandlers(n),n.unref(),this.logger.info(`\u5B88\u62A4\u8FDB\u7A0B\u5DF2\u542F\u52A8 (PID: ${n.pid})`)}catch(r){throw new x(`\u542F\u52A8\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}async stopDaemon(){try{let e=this.processManager.getServiceStatus();if(!e.running)throw x.notRunning();await this.processManager.gracefulKillProcess(e.pid),this.processManager.cleanupPidFile(),this.currentDaemon=null,this.logger.info("\u5B88\u62A4\u8FDB\u7A0B\u5DF2\u505C\u6B62")}catch(e){throw new x(`\u505C\u6B62\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async restartDaemon(e,t={}){try{this.processManager.getServiceStatus().running&&(await this.stopDaemon(),await new Promise(n=>setTimeout(n,1e3))),await this.startDaemon(e,t)}catch(r){throw new x(`\u91CD\u542F\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}getDaemonStatus(){return this.processManager.getServiceStatus()}async attachToLogs(e="xiaozhi.log"){try{let t=$.getLogFile();if(!ft.existsSync(t))throw new x("\u65E5\u5FD7\u6587\u4EF6\u4E0D\u5B58\u5728");let{command:r,args:n}=J.getTailCommand(t),o=Zr(r,n,{stdio:"inherit"});process.on("SIGINT",()=>{console.log(`
8
+ \u65AD\u5F00\u8FDE\u63A5\uFF0C\u670D\u52A1\u7EE7\u7EED\u5728\u540E\u53F0\u8FD0\u884C`),o.kill(),process.exit(0)}),o.on("exit",()=>{process.exit(0)}),o.on("error",s=>{throw new x(`\u8FDE\u63A5\u65E5\u5FD7\u5931\u8D25: ${s.message}`)})}catch(t){throw new x(`\u8FDE\u63A5\u65E5\u5FD7\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}async spawnDaemonProcess(e,t){let n=[$.getWebServerStandalonePath()];t.openBrowser&&n.push("--open-browser");let o={...process.env,XIAOZHI_CONFIG_DIR:$.getConfigDir(),XIAOZHI_DAEMON:"true",...t.env},s=Zr("node",n,{detached:!0,stdio:["ignore","pipe","pipe"],env:o,cwd:t.cwd||process.cwd()});if(!s.pid)throw new he("\u65E0\u6CD5\u542F\u52A8\u5B88\u62A4\u8FDB\u7A0B",0);return s}async setupLogging(e,t){try{let r=$.getLogFile(),o=(await import("path")).dirname(r);ft.existsSync(o)||ft.mkdirSync(o,{recursive:!0});let s=ft.createWriteStream(r,{flags:"a"});e.stdout?.pipe(s),e.stderr?.pipe(s);let a=new Date().toISOString();s.write(`
9
9
  [${a}] \u5B88\u62A4\u8FDB\u7A0B\u542F\u52A8 (PID: ${e.pid})
10
- `)}catch(r){this.logger.warn(`\u8BBE\u7F6E\u65E5\u5FD7\u91CD\u5B9A\u5411\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}setupEventHandlers(e){e.on("exit",(t,r)=>{t!==0&&t!==null?this.logger.error(`\u5B88\u62A4\u8FDB\u7A0B\u5F02\u5E38\u9000\u51FA (\u4EE3\u7801: ${t}, \u4FE1\u53F7: ${r})`):this.logger.info("\u5B88\u62A4\u8FDB\u7A0B\u6B63\u5E38\u9000\u51FA"),this.processManager.cleanupPidFile(),this.currentDaemon=null}),e.on("error",t=>{this.logger.error(`\u5B88\u62A4\u8FDB\u7A0B\u9519\u8BEF: ${t.message}`),this.processManager.cleanupPidFile(),this.currentDaemon=null}),e.on("disconnect",()=>{this.logger.info("\u5B88\u62A4\u8FDB\u7A0B\u65AD\u5F00\u8FDE\u63A5")})}async checkHealth(){try{let e=this.getDaemonStatus();if(!e.running||!e.pid)return!1;let t=this.processManager.getProcessInfo(e.pid);return t.exists&&t.isXiaozhi}catch{return!1}}getCurrentDaemon(){return this.currentDaemon}cleanup(){if(this.currentDaemon){try{this.currentDaemon.kill("SIGTERM")}catch(e){this.logger.warn(`\u6E05\u7406\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}this.currentDaemon=null}}}});import ae from"ws";var D,fe,ft=m(()=>{"use strict";y();lt();D=class extends Error{constructor(t,r,o){super(r);this.code=t;this.data=o;this.name="ToolCallError"}static{c(this,"ToolCallError")}},fe=class{static{c(this,"ProxyMCPServer")}endpointUrl;ws=null;logger;connectionStatus=!1;serverInitialized=!1;tools=new Map;connectionState="disconnected";reconnectOptions;reconnectState={attempts:0,nextInterval:0,timer:null,lastError:null,isManualDisconnect:!1};connectionTimeout=null;performanceMetrics={totalCalls:0,successfulCalls:0,failedCalls:0,averageResponseTime:0,minResponseTime:Number.MAX_VALUE,maxResponseTime:0,successRate:0,lastUpdated:new Date};callRecords=[];maxCallRecords=100;retryConfig={maxAttempts:3,initialDelay:1e3,maxDelay:1e4,backoffMultiplier:2,retryableErrors:[-32001,-32002]};toolCallConfig={timeout:3e4,retryAttempts:3,retryDelay:1e3};constructor(e,t){this.endpointUrl=e,this.logger=g,this.reconnectOptions={enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:1e4,jitter:!0,...t?.reconnect},this.reconnectState.nextInterval=this.reconnectOptions.initialInterval}setServiceManager(e){this.serviceManager=e,this.logger.info("\u5DF2\u8BBE\u7F6E MCPServiceManager"),this.syncToolsFromServiceManager()}syncToolsFromServiceManager(){let e=this.serviceManager;if(!e){this.logger.debug("MCPServiceManager \u672A\u8BBE\u7F6E\uFF0C\u8DF3\u8FC7\u5DE5\u5177\u540C\u6B65");return}try{let t=e.getAllTools(),r=new Map;for(let o of t)r.set(o.name,{name:o.name,description:o.description,inputSchema:o.inputSchema});this.tools=r,this.logger.info(`\u5DF2\u4ECE MCPServiceManager \u540C\u6B65 ${this.tools.size} \u4E2A\u5DE5\u5177`)}catch(t){this.logger.error(`\u540C\u6B65\u5DE5\u5177\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}addTool(e,t){return this.validateTool(e,t),this.tools.set(e,t),this.logger.debug(`\u5DE5\u5177 '${e}' \u5DF2\u6DFB\u52A0`),this}addTools(e){for(let[t,r]of Object.entries(e))this.addTool(t,r);return this}removeTool(e){return this.tools.delete(e)?this.logger.debug(`\u5DE5\u5177 '${e}' \u5DF2\u79FB\u9664`):this.logger.warn(`\u5C1D\u8BD5\u79FB\u9664\u4E0D\u5B58\u5728\u7684\u5DE5\u5177: '${e}'`),this}getTools(){try{this.syncToolsFromServiceManager()}catch{}return Array.from(this.tools.values())}hasTool(e){return this.tools.has(e)}validateTool(e,t){if(!e||typeof e!="string"||e.trim()==="")throw new Error("\u5DE5\u5177\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(this.tools.has(e))throw new Error(`\u5DE5\u5177 '${e}' \u5DF2\u5B58\u5728`);if(!t||typeof t!="object")throw new Error("\u5DE5\u5177\u5FC5\u987B\u662F\u6709\u6548\u7684\u5BF9\u8C61");if(!t.name||typeof t.name!="string")throw new Error("\u5DE5\u5177\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 'name' \u5B57\u6BB5");if(!t.description||typeof t.description!="string")throw new Error("\u5DE5\u5177\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 'description' \u5B57\u6BB5");if(!t.inputSchema||typeof t.inputSchema!="object")throw new Error("\u5DE5\u5177\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 'inputSchema' \u5B57\u6BB5");if(!t.inputSchema.type||!t.inputSchema.properties)throw new Error("\u5DE5\u5177\u7684 inputSchema \u5FC5\u987B\u5305\u542B 'type' \u548C 'properties' \u5B57\u6BB5")}async connect(){if(this.tools.size===0)throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u5DE5\u5177\u3002\u8BF7\u5728\u8FDE\u63A5\u524D\u81F3\u5C11\u6DFB\u52A0\u4E00\u4E2A\u5DE5\u5177\u3002");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.logger.info(`\u6B63\u5728\u8FDE\u63A5\u5C0F\u667A\u63A5\u5165\u70B9: ${v(this.endpointUrl)} (\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),this.ws=new ae(this.endpointUrl),this.ws.on("open",()=>{this.handleConnectionSuccess(),e()}),this.ws.on("message",r=>{try{let o=JSON.parse(r.toString());this.handleMessage(o)}catch(o){this.logger.error("MCP \u6D88\u606F\u89E3\u6790\u9519\u8BEF:",o)}}),this.ws.on("close",(r,o)=>{this.handleConnectionClose(r,o.toString())}),this.ws.on("error",r=>{this.handleConnectionError(r),t(r)})})}handleConnectionSuccess(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.connectionStatus=!0,this.connectionState="connected",this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.lastError=null,this.logger.info("MCP WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB")}handleConnectionError(e){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.reconnectState.lastError=e,this.logger.error("MCP WebSocket \u9519\u8BEF:",e.message),this.cleanupConnection()}handleConnectionClose(e,t){if(this.connectionStatus=!1,this.serverInitialized=!1,this.logger.info(`\u5C0F\u667A\u8FDE\u63A5\u5DF2\u5173\u95ED (\u4EE3\u7801: ${e}, \u539F\u56E0: ${t})`),this.reconnectState.isManualDisconnect){this.connectionState="disconnected";return}this.shouldReconnect()?this.scheduleReconnect():(this.connectionState="failed",this.logger.warn(`\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(`\u5C06\u5728 ${Math.floor(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.ws){this.ws.removeAllListeners();try{this.ws.readyState===ae.OPEN?this.ws.close(1e3,"Cleaning up connection"):this.ws.readyState===ae.CONNECTING&&this.ws.terminate()}catch(e){this.logger.debug("WebSocket \u5173\u95ED\u65F6\u51FA\u73B0\u9519\u8BEF\uFF08\u5DF2\u5FFD\u7565\uFF09:",e)}this.ws=null}this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.connectionStatus=!1,this.serverInitialized=!1}stopReconnect(){this.reconnectState.timer&&(clearTimeout(this.reconnectState.timer),this.reconnectState.timer=null)}handleMessage(e){this.logger.debug("\u6536\u5230 MCP \u6D88\u606F:",JSON.stringify(e,null,2)),e.method&&this.handleServerRequest(e)}handleServerRequest(e){switch(e.method){case"initialize":case"notifications/initialized":this.sendResponse(e.id,{protocolVersion:"2024-11-05",capabilities:{tools:{listChanged:!0},logging:{}},serverInfo:{name:"xiaozhi-mcp-server",version:"1.0.0"}}),this.serverInitialized=!0,this.logger.info("MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210");break;case"tools/list":{let t=this.getTools();this.sendResponse(e.id,{tools:t}),this.logger.debug(`MCP \u5DE5\u5177\u5217\u8868\u5DF2\u53D1\u9001 (${t.length}\u4E2A\u5DE5\u5177)`);break}case"tools/call":{this.handleToolCall(e).catch(t=>{this.logger.error("\u5904\u7406\u5DE5\u5177\u8C03\u7528\u65F6\u53D1\u751F\u672A\u6355\u83B7\u9519\u8BEF:",t)});break}case"ping":this.sendResponse(e.id,{}),this.logger.debug("\u56DE\u5E94 MCP ping \u6D88\u606F");break;default:this.logger.warn(`\u672A\u77E5\u7684 MCP \u8BF7\u6C42: ${e.method}`)}}sendResponse(e,t){if(this.logger.debug(`\u5C1D\u8BD5\u53D1\u9001\u54CD\u5E94: id=${e}, isConnected=${this.connectionStatus}, wsReadyState=${this.ws?.readyState}`),this.connectionStatus&&this.ws?.readyState===ae.OPEN){let r={jsonrpc:"2.0",id:e,result:t};try{this.ws.send(JSON.stringify(r)),this.logger.info(`\u54CD\u5E94\u5DF2\u53D1\u9001: id=${e}`,{responseSize:JSON.stringify(r).length})}catch(o){this.logger.error(`\u53D1\u9001\u54CD\u5E94\u5931\u8D25: id=${e}`,o)}}else this.logger.error(`\u65E0\u6CD5\u53D1\u9001\u54CD\u5E94: id=${e}, \u8FDE\u63A5\u72B6\u6001\u68C0\u67E5\u5931\u8D25`,{isConnected:this.connectionStatus,wsReadyState:this.ws?.readyState,wsReadyStateText:this.ws?.readyState===ae.OPEN?"OPEN":this.ws?.readyState===ae.CONNECTING?"CONNECTING":this.ws?.readyState===ae.CLOSING?"CLOSING":this.ws?.readyState===ae.CLOSED?"CLOSED":"UNKNOWN"}),(!this.connectionStatus||this.ws?.readyState!==ae.OPEN)&&(this.logger.warn(`\u5C1D\u8BD5\u91CD\u65B0\u8FDE\u63A5\u4EE5\u53D1\u9001\u54CD\u5E94: id=${e}`),this.scheduleReconnect())}getStatus(){return{connected:this.connectionStatus,initialized:this.serverInitialized,url:this.endpointUrl,availableTools:this.tools.size,connectionState:this.connectionState,reconnectAttempts:this.reconnectState.attempts,lastError:this.reconnectState.lastError?.message||null}}isConnected(){return this.connectionStatus}disconnect(){this.logger.info("\u4E3B\u52A8\u65AD\u5F00 \u5C0F\u667A\u8FDE\u63A5"),this.reconnectState.isManualDisconnect=!0,this.stopReconnect(),this.cleanupConnection(),this.connectionState="disconnected"}async reconnect(){this.logger.info("\u624B\u52A8\u91CD\u8FDE\u5C0F\u667A\u63A5\u5165\u70B9"),this.stopReconnect(),this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.isManualDisconnect=!1,this.cleanupConnection(),await this.connect()}enableReconnect(){this.reconnectOptions.enabled=!0,this.logger.info("\u81EA\u52A8\u91CD\u8FDE\u5DF2\u542F\u7528")}disableReconnect(){this.reconnectOptions.enabled=!1,this.stopReconnect(),this.logger.info("\u81EA\u52A8\u91CD\u8FDE\u5DF2\u7981\u7528")}updateReconnectOptions(e){this.reconnectOptions={...this.reconnectOptions,...e},this.logger.info("\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("\u91CD\u8FDE\u72B6\u6001\u5DF2\u91CD\u7F6E")}async handleToolCall(e){if(e.id===void 0||e.id===null)throw new D(-32602,"\u8BF7\u6C42 ID \u4E0D\u80FD\u4E3A\u7A7A");let t=e.id,r=null;try{let o=this.validateToolCallParams(e.params);r=this.recordCallStart(o.name,t),this.logger.info(`\u5F00\u59CB\u5904\u7406\u5DE5\u5177\u8C03\u7528: ${o.name}`,{requestId:t,toolName:o.name,hasArguments:!!o.arguments});let n=this.serviceManager;if(!n)throw new D(-32001,"MCPServiceManager \u672A\u8BBE\u7F6E");let s=await this.executeToolWithRetry(n,o.name,o.arguments||{});this.sendResponse(t,{content:s.content||[{type:"text",text:JSON.stringify(s)}],isError:s.isError||!1}),r&&this.recordCallEnd(r,!0),this.logger.info(`\u5DE5\u5177\u8C03\u7528\u6210\u529F: ${o.name}`,{requestId:t,duration:r?.duration?`${r.duration}ms`:"unknown"})}catch(o){if(r){let n=o instanceof D?o.code:-32e3,s=o instanceof Error?o.message:"\u672A\u77E5\u9519\u8BEF";this.recordCallEnd(r,!1,n,s)}this.handleToolCallError(o,t,r?.duration||0)}}validateToolCallParams(e){if(!e||typeof e!="object")throw new D(-32602,"\u8BF7\u6C42\u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61");if(!e.name||typeof e.name!="string")throw new D(-32602,"\u5DE5\u5177\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(e.arguments!==void 0&&(typeof e.arguments!="object"||Array.isArray(e.arguments)))throw new D(-32602,"\u5DE5\u5177\u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61");return{name:e.name,arguments:e.arguments}}async executeToolWithRetry(e,t,r){let o=null;for(let n=1;n<=this.retryConfig.maxAttempts;n++)try{return await this.executeToolWithTimeout(e,t,r,this.toolCallConfig.timeout)}catch(s){if(s instanceof D?o=s:o=new D(-32e3,s instanceof Error?s.message:"\u672A\u77E5\u9519\u8BEF"),this.retryConfig.retryableErrors.includes(o.code)&&n<this.retryConfig.maxAttempts){let a=Math.min(this.retryConfig.initialDelay*this.retryConfig.backoffMultiplier**(n-1),this.retryConfig.maxDelay);this.logger.warn(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25\uFF0C\u5C06\u5728 ${a}ms \u540E\u91CD\u8BD5 (${n}/${this.retryConfig.maxAttempts})`,{toolName:t,error:o.message,attempt:n,delay:a}),await new Promise(l=>setTimeout(l,a));continue}break}throw o}async executeToolWithTimeout(e,t,r,o=3e4){return new Promise((n,s)=>{let a=setTimeout(()=>{s(new D(-32002,`\u5DE5\u5177\u8C03\u7528\u8D85\u65F6 (${o}ms): ${t}`))},o);e.callTool(t,r).then(l=>{clearTimeout(a),n(l)}).catch(l=>{clearTimeout(a),l.message?.includes("\u672A\u627E\u5230\u5DE5\u5177")?s(new D(-32601,`\u5DE5\u5177\u4E0D\u5B58\u5728: ${t}`)):l.message?.includes("\u670D\u52A1")&&l.message?.includes("\u4E0D\u53EF\u7528")?s(new D(-32001,l.message)):l.message?.includes("\u6682\u65F6\u4E0D\u53EF\u7528")?s(new D(-32001,l.message)):l.message?.includes("\u6301\u7EED\u4E0D\u53EF\u7528")?s(new D(-32001,l.message)):s(new D(-32e3,`\u5DE5\u5177\u6267\u884C\u5931\u8D25: ${l.message}`))})})}handleToolCallError(e,t,r){let o;e instanceof D?o={code:e.code,message:e.message,data:e.data}:o={code:-32e3,message:e?.message||"\u672A\u77E5\u9519\u8BEF",data:{originalError:e?.toString()||"null"}},this.sendErrorResponse(t,o),this.logger.error("\u5DE5\u5177\u8C03\u7528\u5931\u8D25",{requestId:t,duration:`${r}ms`,error:o})}sendErrorResponse(e,t){if(this.connectionStatus&&this.ws?.readyState===ae.OPEN){let r={jsonrpc:"2.0",id:e,error:t};this.ws.send(JSON.stringify(r)),this.logger.debug("\u5DF2\u53D1\u9001\u9519\u8BEF\u54CD\u5E94:",r)}}recordCallStart(e,t){let r={id:String(t),toolName:e,startTime:new Date,success:!1};return this.callRecords.push(r),this.callRecords.length>this.maxCallRecords&&this.callRecords.shift(),r}recordCallEnd(e,t,r,o){e.endTime=new Date,e.duration=e.endTime.getTime()-e.startTime.getTime(),e.success=t,e.errorCode=r,e.errorMessage=o,this.updatePerformanceMetrics(e)}updatePerformanceMetrics(e){if(this.performanceMetrics.totalCalls++,e.success?this.performanceMetrics.successfulCalls++:this.performanceMetrics.failedCalls++,e.duration!==void 0){e.duration<this.performanceMetrics.minResponseTime&&(this.performanceMetrics.minResponseTime=e.duration),e.duration>this.performanceMetrics.maxResponseTime&&(this.performanceMetrics.maxResponseTime=e.duration);let t=this.callRecords.filter(o=>o.duration!==void 0).reduce((o,n)=>o+(n.duration||0),0),r=this.callRecords.filter(o=>o.duration!==void 0).length;this.performanceMetrics.averageResponseTime=r>0?t/r:0}this.performanceMetrics.successRate=this.performanceMetrics.totalCalls>0?this.performanceMetrics.successfulCalls/this.performanceMetrics.totalCalls*100:0,this.performanceMetrics.lastUpdated=new Date}getPerformanceMetrics(){return{...this.performanceMetrics}}getCallRecords(e){let t=[...this.callRecords].reverse();return e?t.slice(0,e):t}resetPerformanceMetrics(){this.performanceMetrics={totalCalls:0,successfulCalls:0,failedCalls:0,averageResponseTime:0,minResponseTime:Number.MAX_VALUE,maxResponseTime:0,successRate:0,lastUpdated:new Date},this.callRecords=[]}updateToolCallConfig(e){this.toolCallConfig={...this.toolCallConfig,...e},this.logger.info("\u5DE5\u5177\u8C03\u7528\u914D\u7F6E\u5DF2\u66F4\u65B0",this.toolCallConfig)}updateRetryConfig(e){this.retryConfig={...this.retryConfig,...e},this.logger.info("\u91CD\u8BD5\u914D\u7F6E\u5DF2\u66F4\u65B0",this.retryConfig)}getConfiguration(){return{toolCall:{...this.toolCallConfig},retry:{...this.retryConfig}}}getEnhancedStatus(){return{connected:this.connectionStatus,initialized:this.serverInitialized,url:this.endpointUrl,availableTools:this.tools.size,connectionState:this.connectionState,reconnectAttempts:this.reconnectState.attempts,lastError:this.reconnectState.lastError?.message||null,performance:this.getPerformanceMetrics(),configuration:this.getConfiguration()}}}});var De,Qe=m(()=>{"use strict";y();De=class{static{c(this,"TransportAdapter")}logger;messageHandler;connectionId;config;state="disconnected";constructor(e,t){this.messageHandler=e,this.config=t,this.connectionId=this.generateConnectionId(),this.logger=g}async handleIncomingMessage(e){try{this.logger.debug(`\u5904\u7406\u63A5\u6536\u5230\u7684\u6D88\u606F: ${e.method}`,e);let t=await this.messageHandler.handleMessage(e);t!==null?(this.logger.debug("\u53D1\u9001\u54CD\u5E94\u6D88\u606F:",t),await this.sendMessage(t)):this.logger.debug("\u6536\u5230\u901A\u77E5\u6D88\u606F\uFF0C\u65E0\u9700\u54CD\u5E94")}catch(t){this.logger.error(`\u5904\u7406\u6D88\u606F\u65F6\u51FA\u9519: ${e.method}`,t);let r=this.createErrorResponse(t,e.id);await this.sendMessage(r)}}createErrorResponse(e,t){let r=-32603;return e.message.includes("\u672A\u627E\u5230\u5DE5\u5177")||e.message.includes("\u672A\u77E5\u7684\u65B9\u6CD5")?r=-32601:(e.message.includes("\u53C2\u6570")||e.message.includes("\u4E0D\u80FD\u4E3A\u7A7A"))&&(r=-32602),{jsonrpc:"2.0",error:{code:r,message:e.message,data:{stack:e.stack}},id:t||null}}generateConnectionId(){let e=Date.now(),t=Math.random().toString(36).substr(2,9);return`${this.config.name}_${e}_${t}`}getConnectionId(){return this.connectionId}getState(){return this.state}setState(e){let t=this.state;this.state=e,t!==e&&(this.logger.info(`\u8FDE\u63A5\u72B6\u6001\u53D8\u66F4: ${t} -> ${e}`),this.onStateChange(t,e))}onStateChange(e,t){}getConfig(){return{...this.config}}getMessageHandler(){return this.messageHandler}parseMessage(e){try{let t=JSON.parse(e.trim());return!t.jsonrpc||t.jsonrpc!=="2.0"?(this.logger.warn("\u6536\u5230\u975E JSON-RPC 2.0 \u683C\u5F0F\u7684\u6D88\u606F",t),null):t.method?t:(this.logger.warn("\u6536\u5230\u6CA1\u6709 method \u5B57\u6BB5\u7684\u6D88\u606F",t),null)}catch(t){return this.logger.error("\u89E3\u6790 JSON \u6D88\u606F\u5931\u8D25",{data:e,error:t}),null}}serializeMessage(e){try{return JSON.stringify(e)}catch(t){this.logger.error("\u5E8F\u5217\u5316\u6D88\u606F\u5931\u8D25",{message:e,error:t});let r=t instanceof Error?t.message:String(t);throw new Error(`\u6D88\u606F\u5E8F\u5217\u5316\u5931\u8D25: ${r}`)}}validateMessage(e){return!(!e||typeof e!="object"||e.jsonrpc!=="2.0"||e.method&&typeof e.method!="string"||!e.method&&!e.result&&!e.error)}createTimeoutPromise(e,t){return Promise.race([e,new Promise((r,o)=>{setTimeout(()=>{o(new Error(`\u64CD\u4F5C\u8D85\u65F6: ${t}ms`))},t)})])}}});import{randomUUID as xn}from"crypto";import ur from"express";var Ct,Qr=m(()=>{"use strict";Qe();Ct=class extends De{static{c(this,"HTTPAdapter")}app;server=null;clients=new Map;port;host;enableSSE;enableRPC;corsOrigin;maxClients;constructor(e,t={name:"http"}){super(e,t),console.warn("[\u5DF2\u5E9F\u5F03] HTTPAdapter \u5C06\u5728 v2.0.0 \u4E2D\u79FB\u9664\u3002\u8BF7\u4F7F\u7528 WebServer \u7684 /mcp \u7AEF\u70B9\u66FF\u4EE3\u3002"),this.port=t.port||3e3,this.host=t.host||"0.0.0.0",this.enableSSE=t.enableSSE!==!1,this.enableRPC=t.enableRPC!==!1,this.corsOrigin=t.corsOrigin||"*",this.maxClients=t.maxClients!==void 0?t.maxClients:100,this.app=ur(),this.setupMiddleware()}async initialize(){this.logger.info("\u521D\u59CB\u5316 HTTP \u9002\u914D\u5668");try{this.setupRoutes(),this.setState("connecting"),this.logger.info("HTTP \u9002\u914D\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw this.logger.error("HTTP \u9002\u914D\u5668\u521D\u59CB\u5316\u5931\u8D25",e),this.setState("error"),e}}async start(){if(this.server){this.logger.warn("HTTP \u670D\u52A1\u5668\u5DF2\u5728\u8FD0\u884C");return}return this.logger.info(`\u542F\u52A8 HTTP \u670D\u52A1\u5668\u5728 ${this.host}:${this.port}`),new Promise((e,t)=>{this.server=this.app.listen(this.port,this.host,()=>{this.setState("connected"),this.logger.info("HTTP \u9002\u914D\u5668\u542F\u52A8\u6210\u529F"),this.logger.info(`- RPC \u7AEF\u70B9: http://${this.host}:${this.port}/rpc`),this.enableSSE&&(this.logger.info(`- SSE \u7AEF\u70B9: http://${this.host}:${this.port}/sse`),this.logger.info(`- \u6D88\u606F\u7AEF\u70B9: http://${this.host}:${this.port}/messages`)),e()}),this.server?.on("error",r=>{this.logger.error("HTTP \u670D\u52A1\u5668\u9519\u8BEF",r),this.setState("error"),t(r)})})}async stop(){if(this.server)return this.logger.info("\u505C\u6B62 HTTP \u670D\u52A1\u5668"),new Promise(e=>{for(let t of this.clients.values())t.response.end();this.clients.clear(),this.server.close(()=>{this.server=null,this.setState("disconnected"),this.logger.info("HTTP \u670D\u52A1\u5668\u5DF2\u505C\u6B62"),e()})})}async sendMessage(e){this.clients.size>0&&this.broadcastToClients(e)}setupMiddleware(){this.app.use(ur.json({limit:"10mb"})),this.app.use(ur.urlencoded({extended:!0})),this.app.use((e,t,r)=>{t.header("Access-Control-Allow-Origin",this.corsOrigin),t.header("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.header("Access-Control-Allow-Headers","Content-Type, Accept"),t.header("Cache-Control","no-cache"),r()}),this.app.use((e,t,r)=>{this.logger.debug(`${e.method} ${e.path}`,{query:e.query,headers:e.headers}),r()})}setupRoutes(){this.enableSSE&&(this.app.get("/sse",this.handleSSE.bind(this)),this.app.post("/messages",this.handleMessages.bind(this))),this.enableRPC&&this.app.post("/rpc",this.handleRPC.bind(this)),this.app.get("/status",this.handleStatus.bind(this)),this.app.get("/health",this.handleHealth.bind(this))}handleSSE(e,t){if(this.clients.size>=this.maxClients){t.status(503).json({error:"\u670D\u52A1\u5668\u7E41\u5FD9\uFF0C\u5BA2\u6237\u7AEF\u8FDE\u63A5\u6570\u5DF2\u8FBE\u4E0A\u9650",maxClients:this.maxClients});return}let r=Date.now().toString(),o=xn();t.setHeader("Content-Type","text/event-stream"),t.setHeader("Cache-Control","no-cache, no-transform"),t.setHeader("Connection","keep-alive"),t.setHeader("X-Accel-Buffering","no");let n={id:r,sessionId:o,response:t,connectedAt:new Date};this.clients.set(o,n),this.logger.info(`SSE \u5BA2\u6237\u7AEF\u5DF2\u8FDE\u63A5: ${r} (\u4F1A\u8BDD: ${o})`),t.write(`event: endpoint
11
- data: /messages?sessionId=${o}
10
+ `)}catch(r){this.logger.warn(`\u8BBE\u7F6E\u65E5\u5FD7\u91CD\u5B9A\u5411\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}setupEventHandlers(e){e.on("exit",(t,r)=>{t!==0&&t!==null?this.logger.error(`\u5B88\u62A4\u8FDB\u7A0B\u5F02\u5E38\u9000\u51FA (\u4EE3\u7801: ${t}, \u4FE1\u53F7: ${r})`):this.logger.info("\u5B88\u62A4\u8FDB\u7A0B\u6B63\u5E38\u9000\u51FA"),this.processManager.cleanupPidFile(),this.currentDaemon=null}),e.on("error",t=>{this.logger.error(`\u5B88\u62A4\u8FDB\u7A0B\u9519\u8BEF: ${t.message}`),this.processManager.cleanupPidFile(),this.currentDaemon=null}),e.on("disconnect",()=>{this.logger.info("\u5B88\u62A4\u8FDB\u7A0B\u65AD\u5F00\u8FDE\u63A5")})}async checkHealth(){try{let e=this.getDaemonStatus();if(!e.running||!e.pid)return!1;let t=this.processManager.getProcessInfo(e.pid);return t.exists&&t.isXiaozhi}catch{return!1}}getCurrentDaemon(){return this.currentDaemon}cleanup(){if(this.currentDaemon){try{this.currentDaemon.kill("SIGTERM")}catch(e){this.logger.warn(`\u6E05\u7406\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}this.currentDaemon=null}}}});import ae from"ws";var D,Ce,Ct=m(()=>{"use strict";y();gt();D=class extends Error{constructor(t,r,n){super(r);this.code=t;this.data=n;this.name="ToolCallError"}static{c(this,"ToolCallError")}},Ce=class{static{c(this,"ProxyMCPServer")}endpointUrl;ws=null;logger;connectionStatus=!1;serverInitialized=!1;tools=new Map;connectionState="disconnected";reconnectOptions;reconnectState={attempts:0,nextInterval:0,timer:null,lastError:null,isManualDisconnect:!1};connectionTimeout=null;performanceMetrics={totalCalls:0,successfulCalls:0,failedCalls:0,averageResponseTime:0,minResponseTime:Number.MAX_VALUE,maxResponseTime:0,successRate:0,lastUpdated:new Date};callRecords=[];maxCallRecords=100;retryConfig={maxAttempts:3,initialDelay:1e3,maxDelay:1e4,backoffMultiplier:2,retryableErrors:[-32001,-32002]};toolCallConfig={timeout:3e4,retryAttempts:3,retryDelay:1e3};constructor(e,t){this.endpointUrl=e,this.logger=p,this.reconnectOptions={enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:1e4,jitter:!0,...t?.reconnect},this.reconnectState.nextInterval=this.reconnectOptions.initialInterval}setServiceManager(e){this.serviceManager=e,this.logger.info("\u5DF2\u8BBE\u7F6E MCPServiceManager"),this.syncToolsFromServiceManager()}syncToolsFromServiceManager(){let e=this.serviceManager;if(!e){this.logger.debug("MCPServiceManager \u672A\u8BBE\u7F6E\uFF0C\u8DF3\u8FC7\u5DE5\u5177\u540C\u6B65");return}try{let t=e.getAllTools(),r=new Map;for(let n of t)r.set(n.name,{name:n.name,description:n.description,inputSchema:n.inputSchema});this.tools=r,this.logger.info(`\u5DF2\u4ECE MCPServiceManager \u540C\u6B65 ${this.tools.size} \u4E2A\u5DE5\u5177`)}catch(t){this.logger.error(`\u540C\u6B65\u5DE5\u5177\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}addTool(e,t){return this.validateTool(e,t),this.tools.set(e,t),this.logger.debug(`\u5DE5\u5177 '${e}' \u5DF2\u6DFB\u52A0`),this}addTools(e){for(let[t,r]of Object.entries(e))this.addTool(t,r);return this}removeTool(e){return this.tools.delete(e)?this.logger.debug(`\u5DE5\u5177 '${e}' \u5DF2\u79FB\u9664`):this.logger.warn(`\u5C1D\u8BD5\u79FB\u9664\u4E0D\u5B58\u5728\u7684\u5DE5\u5177: '${e}'`),this}getTools(){try{this.syncToolsFromServiceManager()}catch{}return Array.from(this.tools.values())}hasTool(e){return this.tools.has(e)}validateTool(e,t){if(!e||typeof e!="string"||e.trim()==="")throw new Error("\u5DE5\u5177\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(this.tools.has(e))throw new Error(`\u5DE5\u5177 '${e}' \u5DF2\u5B58\u5728`);if(!t||typeof t!="object")throw new Error("\u5DE5\u5177\u5FC5\u987B\u662F\u6709\u6548\u7684\u5BF9\u8C61");if(!t.name||typeof t.name!="string")throw new Error("\u5DE5\u5177\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 'name' \u5B57\u6BB5");if(!t.description||typeof t.description!="string")throw new Error("\u5DE5\u5177\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 'description' \u5B57\u6BB5");if(!t.inputSchema||typeof t.inputSchema!="object")throw new Error("\u5DE5\u5177\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 'inputSchema' \u5B57\u6BB5");if(!t.inputSchema.type||!t.inputSchema.properties)throw new Error("\u5DE5\u5177\u7684 inputSchema \u5FC5\u987B\u5305\u542B 'type' \u548C 'properties' \u5B57\u6BB5")}async connect(){if(this.tools.size===0)throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u5DE5\u5177\u3002\u8BF7\u5728\u8FDE\u63A5\u524D\u81F3\u5C11\u6DFB\u52A0\u4E00\u4E2A\u5DE5\u5177\u3002");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.logger.info(`\u6B63\u5728\u8FDE\u63A5\u5C0F\u667A\u63A5\u5165\u70B9: ${C(this.endpointUrl)} (\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),this.ws=new ae(this.endpointUrl),this.ws.on("open",()=>{this.handleConnectionSuccess(),e()}),this.ws.on("message",r=>{try{let n=JSON.parse(r.toString());this.handleMessage(n)}catch(n){this.logger.error("MCP \u6D88\u606F\u89E3\u6790\u9519\u8BEF:",n)}}),this.ws.on("close",(r,n)=>{this.handleConnectionClose(r,n.toString())}),this.ws.on("error",r=>{this.handleConnectionError(r),t(r)})})}handleConnectionSuccess(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.connectionStatus=!0,this.connectionState="connected",this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.lastError=null,this.logger.info("MCP WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB")}handleConnectionError(e){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.reconnectState.lastError=e,this.logger.error("MCP WebSocket \u9519\u8BEF:",e.message),this.cleanupConnection()}handleConnectionClose(e,t){if(this.connectionStatus=!1,this.serverInitialized=!1,this.logger.info(`\u5C0F\u667A\u8FDE\u63A5\u5DF2\u5173\u95ED (\u4EE3\u7801: ${e}, \u539F\u56E0: ${t})`),this.reconnectState.isManualDisconnect){this.connectionState="disconnected";return}this.shouldReconnect()?this.scheduleReconnect():(this.connectionState="failed",this.logger.warn(`\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(`\u5C06\u5728 ${Math.floor(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.ws){this.ws.removeAllListeners();try{this.ws.readyState===ae.OPEN?this.ws.close(1e3,"Cleaning up connection"):this.ws.readyState===ae.CONNECTING&&this.ws.terminate()}catch(e){this.logger.debug("WebSocket \u5173\u95ED\u65F6\u51FA\u73B0\u9519\u8BEF\uFF08\u5DF2\u5FFD\u7565\uFF09:",e)}this.ws=null}this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.connectionStatus=!1,this.serverInitialized=!1}stopReconnect(){this.reconnectState.timer&&(clearTimeout(this.reconnectState.timer),this.reconnectState.timer=null)}handleMessage(e){this.logger.debug("\u6536\u5230 MCP \u6D88\u606F:",JSON.stringify(e,null,2)),e.method&&this.handleServerRequest(e)}handleServerRequest(e){switch(e.method){case"initialize":case"notifications/initialized":this.sendResponse(e.id,{protocolVersion:"2024-11-05",capabilities:{tools:{listChanged:!0},logging:{}},serverInfo:{name:"xiaozhi-mcp-server",version:"1.0.0"}}),this.serverInitialized=!0,this.logger.info("MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210");break;case"tools/list":{let t=this.getTools();this.sendResponse(e.id,{tools:t}),this.logger.debug(`MCP \u5DE5\u5177\u5217\u8868\u5DF2\u53D1\u9001 (${t.length}\u4E2A\u5DE5\u5177)`);break}case"tools/call":{this.handleToolCall(e).catch(t=>{this.logger.error("\u5904\u7406\u5DE5\u5177\u8C03\u7528\u65F6\u53D1\u751F\u672A\u6355\u83B7\u9519\u8BEF:",t)});break}case"ping":this.sendResponse(e.id,{}),this.logger.debug("\u56DE\u5E94 MCP ping \u6D88\u606F");break;default:this.logger.warn(`\u672A\u77E5\u7684 MCP \u8BF7\u6C42: ${e.method}`)}}sendResponse(e,t){if(this.logger.debug(`\u5C1D\u8BD5\u53D1\u9001\u54CD\u5E94: id=${e}, isConnected=${this.connectionStatus}, wsReadyState=${this.ws?.readyState}`),this.connectionStatus&&this.ws?.readyState===ae.OPEN){let r={jsonrpc:"2.0",id:e,result:t};try{this.ws.send(JSON.stringify(r)),this.logger.info(`\u54CD\u5E94\u5DF2\u53D1\u9001: id=${e}`,{responseSize:JSON.stringify(r).length})}catch(n){this.logger.error(`\u53D1\u9001\u54CD\u5E94\u5931\u8D25: id=${e}`,n)}}else this.logger.error(`\u65E0\u6CD5\u53D1\u9001\u54CD\u5E94: id=${e}, \u8FDE\u63A5\u72B6\u6001\u68C0\u67E5\u5931\u8D25`,{isConnected:this.connectionStatus,wsReadyState:this.ws?.readyState,wsReadyStateText:this.ws?.readyState===ae.OPEN?"OPEN":this.ws?.readyState===ae.CONNECTING?"CONNECTING":this.ws?.readyState===ae.CLOSING?"CLOSING":this.ws?.readyState===ae.CLOSED?"CLOSED":"UNKNOWN"}),(!this.connectionStatus||this.ws?.readyState!==ae.OPEN)&&(this.logger.warn(`\u5C1D\u8BD5\u91CD\u65B0\u8FDE\u63A5\u4EE5\u53D1\u9001\u54CD\u5E94: id=${e}`),this.scheduleReconnect())}getStatus(){return{connected:this.connectionStatus,initialized:this.serverInitialized,url:this.endpointUrl,availableTools:this.tools.size,connectionState:this.connectionState,reconnectAttempts:this.reconnectState.attempts,lastError:this.reconnectState.lastError?.message||null}}isConnected(){return this.connectionStatus}disconnect(){this.logger.info("\u4E3B\u52A8\u65AD\u5F00 \u5C0F\u667A\u8FDE\u63A5"),this.reconnectState.isManualDisconnect=!0,this.stopReconnect(),this.cleanupConnection(),this.connectionState="disconnected"}async reconnect(){this.logger.info("\u624B\u52A8\u91CD\u8FDE\u5C0F\u667A\u63A5\u5165\u70B9"),this.stopReconnect(),this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.isManualDisconnect=!1,this.cleanupConnection(),await this.connect()}enableReconnect(){this.reconnectOptions.enabled=!0,this.logger.info("\u81EA\u52A8\u91CD\u8FDE\u5DF2\u542F\u7528")}disableReconnect(){this.reconnectOptions.enabled=!1,this.stopReconnect(),this.logger.info("\u81EA\u52A8\u91CD\u8FDE\u5DF2\u7981\u7528")}updateReconnectOptions(e){this.reconnectOptions={...this.reconnectOptions,...e},this.logger.info("\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("\u91CD\u8FDE\u72B6\u6001\u5DF2\u91CD\u7F6E")}async handleToolCall(e){if(e.id===void 0||e.id===null)throw new D(-32602,"\u8BF7\u6C42 ID \u4E0D\u80FD\u4E3A\u7A7A");let t=e.id,r=null;try{let n=this.validateToolCallParams(e.params);r=this.recordCallStart(n.name,t),this.logger.info(`\u5F00\u59CB\u5904\u7406\u5DE5\u5177\u8C03\u7528: ${n.name}`,{requestId:t,toolName:n.name,hasArguments:!!n.arguments});let o=this.serviceManager;if(!o)throw new D(-32001,"MCPServiceManager \u672A\u8BBE\u7F6E");let s=await this.executeToolWithRetry(o,n.name,n.arguments||{});this.sendResponse(t,{content:s.content||[{type:"text",text:JSON.stringify(s)}],isError:s.isError||!1}),r&&this.recordCallEnd(r,!0),this.logger.info(`\u5DE5\u5177\u8C03\u7528\u6210\u529F: ${n.name}`,{requestId:t,duration:r?.duration?`${r.duration}ms`:"unknown"})}catch(n){if(r){let o=n instanceof D?n.code:-32e3,s=n instanceof Error?n.message:"\u672A\u77E5\u9519\u8BEF";this.recordCallEnd(r,!1,o,s)}this.handleToolCallError(n,t,r?.duration||0)}}validateToolCallParams(e){if(!e||typeof e!="object")throw new D(-32602,"\u8BF7\u6C42\u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61");if(!e.name||typeof e.name!="string")throw new D(-32602,"\u5DE5\u5177\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(e.arguments!==void 0&&(typeof e.arguments!="object"||Array.isArray(e.arguments)))throw new D(-32602,"\u5DE5\u5177\u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61");return{name:e.name,arguments:e.arguments}}async executeToolWithRetry(e,t,r){let n=null;for(let o=1;o<=this.retryConfig.maxAttempts;o++)try{return await this.executeToolWithTimeout(e,t,r,this.toolCallConfig.timeout)}catch(s){if(s instanceof D?n=s:n=new D(-32e3,s instanceof Error?s.message:"\u672A\u77E5\u9519\u8BEF"),this.retryConfig.retryableErrors.includes(n.code)&&o<this.retryConfig.maxAttempts){let a=Math.min(this.retryConfig.initialDelay*this.retryConfig.backoffMultiplier**(o-1),this.retryConfig.maxDelay);this.logger.warn(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25\uFF0C\u5C06\u5728 ${a}ms \u540E\u91CD\u8BD5 (${o}/${this.retryConfig.maxAttempts})`,{toolName:t,error:n.message,attempt:o,delay:a}),await new Promise(l=>setTimeout(l,a));continue}break}throw n}async executeToolWithTimeout(e,t,r,n=3e4){return new Promise((o,s)=>{let a=setTimeout(()=>{s(new D(-32002,`\u5DE5\u5177\u8C03\u7528\u8D85\u65F6 (${n}ms): ${t}`))},n);e.callTool(t,r).then(l=>{clearTimeout(a),o(l)}).catch(l=>{clearTimeout(a),l.message?.includes("\u672A\u627E\u5230\u5DE5\u5177")?s(new D(-32601,`\u5DE5\u5177\u4E0D\u5B58\u5728: ${t}`)):l.message?.includes("\u670D\u52A1")&&l.message?.includes("\u4E0D\u53EF\u7528")?s(new D(-32001,l.message)):l.message?.includes("\u6682\u65F6\u4E0D\u53EF\u7528")?s(new D(-32001,l.message)):l.message?.includes("\u6301\u7EED\u4E0D\u53EF\u7528")?s(new D(-32001,l.message)):s(new D(-32e3,`\u5DE5\u5177\u6267\u884C\u5931\u8D25: ${l.message}`))})})}handleToolCallError(e,t,r){let n;e instanceof D?n={code:e.code,message:e.message,data:e.data}:n={code:-32e3,message:e?.message||"\u672A\u77E5\u9519\u8BEF",data:{originalError:e?.toString()||"null"}},this.sendErrorResponse(t,n),this.logger.error("\u5DE5\u5177\u8C03\u7528\u5931\u8D25",{requestId:t,duration:`${r}ms`,error:n})}sendErrorResponse(e,t){if(this.connectionStatus&&this.ws?.readyState===ae.OPEN){let r={jsonrpc:"2.0",id:e,error:t};this.ws.send(JSON.stringify(r)),this.logger.debug("\u5DF2\u53D1\u9001\u9519\u8BEF\u54CD\u5E94:",r)}}recordCallStart(e,t){let r={id:String(t),toolName:e,startTime:new Date,success:!1};return this.callRecords.push(r),this.callRecords.length>this.maxCallRecords&&this.callRecords.shift(),r}recordCallEnd(e,t,r,n){e.endTime=new Date,e.duration=e.endTime.getTime()-e.startTime.getTime(),e.success=t,e.errorCode=r,e.errorMessage=n,this.updatePerformanceMetrics(e)}updatePerformanceMetrics(e){if(this.performanceMetrics.totalCalls++,e.success?this.performanceMetrics.successfulCalls++:this.performanceMetrics.failedCalls++,e.duration!==void 0){e.duration<this.performanceMetrics.minResponseTime&&(this.performanceMetrics.minResponseTime=e.duration),e.duration>this.performanceMetrics.maxResponseTime&&(this.performanceMetrics.maxResponseTime=e.duration);let t=this.callRecords.filter(n=>n.duration!==void 0).reduce((n,o)=>n+(o.duration||0),0),r=this.callRecords.filter(n=>n.duration!==void 0).length;this.performanceMetrics.averageResponseTime=r>0?t/r:0}this.performanceMetrics.successRate=this.performanceMetrics.totalCalls>0?this.performanceMetrics.successfulCalls/this.performanceMetrics.totalCalls*100:0,this.performanceMetrics.lastUpdated=new Date}getPerformanceMetrics(){return{...this.performanceMetrics}}getCallRecords(e){let t=[...this.callRecords].reverse();return e?t.slice(0,e):t}resetPerformanceMetrics(){this.performanceMetrics={totalCalls:0,successfulCalls:0,failedCalls:0,averageResponseTime:0,minResponseTime:Number.MAX_VALUE,maxResponseTime:0,successRate:0,lastUpdated:new Date},this.callRecords=[]}updateToolCallConfig(e){this.toolCallConfig={...this.toolCallConfig,...e},this.logger.info("\u5DE5\u5177\u8C03\u7528\u914D\u7F6E\u5DF2\u66F4\u65B0",this.toolCallConfig)}updateRetryConfig(e){this.retryConfig={...this.retryConfig,...e},this.logger.info("\u91CD\u8BD5\u914D\u7F6E\u5DF2\u66F4\u65B0",this.retryConfig)}getConfiguration(){return{toolCall:{...this.toolCallConfig},retry:{...this.retryConfig}}}getEnhancedStatus(){return{connected:this.connectionStatus,initialized:this.serverInitialized,url:this.endpointUrl,availableTools:this.tools.size,connectionState:this.connectionState,reconnectAttempts:this.reconnectState.attempts,lastError:this.reconnectState.lastError?.message||null,performance:this.getPerformanceMetrics(),configuration:this.getConfiguration()}}}});var ke,et=m(()=>{"use strict";y();ke=class{static{c(this,"TransportAdapter")}logger;messageHandler;connectionId;config;state="disconnected";constructor(e,t){this.messageHandler=e,this.config=t,this.connectionId=this.generateConnectionId(),this.logger=p}async handleIncomingMessage(e){try{this.logger.debug(`\u5904\u7406\u63A5\u6536\u5230\u7684\u6D88\u606F: ${e.method}`,e);let t=await this.messageHandler.handleMessage(e);t!==null?(this.logger.debug("\u53D1\u9001\u54CD\u5E94\u6D88\u606F:",t),await this.sendMessage(t)):this.logger.debug("\u6536\u5230\u901A\u77E5\u6D88\u606F\uFF0C\u65E0\u9700\u54CD\u5E94")}catch(t){this.logger.error(`\u5904\u7406\u6D88\u606F\u65F6\u51FA\u9519: ${e.method}`,t);let r=this.createErrorResponse(t,e.id);await this.sendMessage(r)}}createErrorResponse(e,t){let r=-32603;return e.message.includes("\u672A\u627E\u5230\u5DE5\u5177")||e.message.includes("\u672A\u77E5\u7684\u65B9\u6CD5")?r=-32601:(e.message.includes("\u53C2\u6570")||e.message.includes("\u4E0D\u80FD\u4E3A\u7A7A"))&&(r=-32602),{jsonrpc:"2.0",error:{code:r,message:e.message,data:{stack:e.stack}},id:t||null}}generateConnectionId(){let e=Date.now(),t=Math.random().toString(36).substr(2,9);return`${this.config.name}_${e}_${t}`}getConnectionId(){return this.connectionId}getState(){return this.state}setState(e){let t=this.state;this.state=e,t!==e&&(this.logger.info(`\u8FDE\u63A5\u72B6\u6001\u53D8\u66F4: ${t} -> ${e}`),this.onStateChange(t,e))}onStateChange(e,t){}getConfig(){return{...this.config}}getMessageHandler(){return this.messageHandler}parseMessage(e){try{let t=JSON.parse(e.trim());return!t.jsonrpc||t.jsonrpc!=="2.0"?(this.logger.warn("\u6536\u5230\u975E JSON-RPC 2.0 \u683C\u5F0F\u7684\u6D88\u606F",t),null):t.method?t:(this.logger.warn("\u6536\u5230\u6CA1\u6709 method \u5B57\u6BB5\u7684\u6D88\u606F",t),null)}catch(t){return this.logger.error("\u89E3\u6790 JSON \u6D88\u606F\u5931\u8D25",{data:e,error:t}),null}}serializeMessage(e){try{return JSON.stringify(e)}catch(t){this.logger.error("\u5E8F\u5217\u5316\u6D88\u606F\u5931\u8D25",{message:e,error:t});let r=t instanceof Error?t.message:String(t);throw new Error(`\u6D88\u606F\u5E8F\u5217\u5316\u5931\u8D25: ${r}`)}}validateMessage(e){return!(!e||typeof e!="object"||e.jsonrpc!=="2.0"||e.method&&typeof e.method!="string"||!e.method&&!e.result&&!e.error)}createTimeoutPromise(e,t){return Promise.race([e,new Promise((r,n)=>{setTimeout(()=>{n(new Error(`\u64CD\u4F5C\u8D85\u65F6: ${t}ms`))},t)})])}}});import{randomUUID as Ao}from"crypto";import ur from"express";var vt,en=m(()=>{"use strict";et();vt=class extends ke{static{c(this,"HTTPAdapter")}app;server=null;clients=new Map;port;host;enableSSE;enableRPC;corsOrigin;maxClients;constructor(e,t={name:"http"}){super(e,t),console.warn("[\u5DF2\u5E9F\u5F03] HTTPAdapter \u5C06\u5728 v2.0.0 \u4E2D\u79FB\u9664\u3002\u8BF7\u4F7F\u7528 WebServer \u7684 /mcp \u7AEF\u70B9\u66FF\u4EE3\u3002"),this.port=t.port||3e3,this.host=t.host||"0.0.0.0",this.enableSSE=t.enableSSE!==!1,this.enableRPC=t.enableRPC!==!1,this.corsOrigin=t.corsOrigin||"*",this.maxClients=t.maxClients!==void 0?t.maxClients:100,this.app=ur(),this.setupMiddleware()}async initialize(){this.logger.info("\u521D\u59CB\u5316 HTTP \u9002\u914D\u5668");try{this.setupRoutes(),this.setState("connecting"),this.logger.info("HTTP \u9002\u914D\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw this.logger.error("HTTP \u9002\u914D\u5668\u521D\u59CB\u5316\u5931\u8D25",e),this.setState("error"),e}}async start(){if(this.server){this.logger.warn("HTTP \u670D\u52A1\u5668\u5DF2\u5728\u8FD0\u884C");return}return this.logger.info(`\u542F\u52A8 HTTP \u670D\u52A1\u5668\u5728 ${this.host}:${this.port}`),new Promise((e,t)=>{this.server=this.app.listen(this.port,this.host,()=>{this.setState("connected"),this.logger.info("HTTP \u9002\u914D\u5668\u542F\u52A8\u6210\u529F"),this.logger.info(`- RPC \u7AEF\u70B9: http://${this.host}:${this.port}/rpc`),this.enableSSE&&(this.logger.info(`- SSE \u7AEF\u70B9: http://${this.host}:${this.port}/sse`),this.logger.info(`- \u6D88\u606F\u7AEF\u70B9: http://${this.host}:${this.port}/messages`)),e()}),this.server?.on("error",r=>{this.logger.error("HTTP \u670D\u52A1\u5668\u9519\u8BEF",r),this.setState("error"),t(r)})})}async stop(){if(this.server)return this.logger.info("\u505C\u6B62 HTTP \u670D\u52A1\u5668"),new Promise(e=>{for(let t of this.clients.values())t.response.end();this.clients.clear(),this.server.close(()=>{this.server=null,this.setState("disconnected"),this.logger.info("HTTP \u670D\u52A1\u5668\u5DF2\u505C\u6B62"),e()})})}async sendMessage(e){this.clients.size>0&&this.broadcastToClients(e)}setupMiddleware(){this.app.use(ur.json({limit:"10mb"})),this.app.use(ur.urlencoded({extended:!0})),this.app.use((e,t,r)=>{t.header("Access-Control-Allow-Origin",this.corsOrigin),t.header("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.header("Access-Control-Allow-Headers","Content-Type, Accept"),t.header("Cache-Control","no-cache"),r()}),this.app.use((e,t,r)=>{this.logger.debug(`${e.method} ${e.path}`,{query:e.query,headers:e.headers}),r()})}setupRoutes(){this.enableSSE&&(this.app.get("/sse",this.handleSSE.bind(this)),this.app.post("/messages",this.handleMessages.bind(this))),this.enableRPC&&this.app.post("/rpc",this.handleRPC.bind(this)),this.app.get("/status",this.handleStatus.bind(this)),this.app.get("/health",this.handleHealth.bind(this))}handleSSE(e,t){if(this.clients.size>=this.maxClients){t.status(503).json({error:"\u670D\u52A1\u5668\u7E41\u5FD9\uFF0C\u5BA2\u6237\u7AEF\u8FDE\u63A5\u6570\u5DF2\u8FBE\u4E0A\u9650",maxClients:this.maxClients});return}let r=Date.now().toString(),n=Ao();t.setHeader("Content-Type","text/event-stream"),t.setHeader("Cache-Control","no-cache, no-transform"),t.setHeader("Connection","keep-alive"),t.setHeader("X-Accel-Buffering","no");let o={id:r,sessionId:n,response:t,connectedAt:new Date};this.clients.set(n,o),this.logger.info(`SSE \u5BA2\u6237\u7AEF\u5DF2\u8FDE\u63A5: ${r} (\u4F1A\u8BDD: ${n})`),t.write(`event: endpoint
11
+ data: /messages?sessionId=${n}
12
12
 
13
- `),e.on("close",()=>{this.clients.delete(o),this.logger.info(`SSE \u5BA2\u6237\u7AEF\u5DF2\u65AD\u5F00\u8FDE\u63A5: ${r} (\u4F1A\u8BDD: ${o})`)}),e.on("error",s=>{this.logger.error(`SSE \u5BA2\u6237\u7AEF\u8FDE\u63A5\u9519\u8BEF: ${r}`,s),this.clients.delete(o)})}async handleMessages(e,t){try{let r=e.query.sessionId,o=e.body;if(this.logger.debug(`\u6536\u5230 SSE \u6D88\u606F (\u4F1A\u8BDD: ${r}):`,o),!r||!this.clients.has(r)){t.status(400).json({jsonrpc:"2.0",error:{code:-32600,message:"\u65E0\u6548\u6216\u7F3A\u5C11 sessionId"},id:o.id});return}let n=await this.messageHandler.handleMessage(o);this.logger.debug("SSE \u6D88\u606F\u5904\u7406\u54CD\u5E94:",n);let s=this.clients.get(r);s&&n!==null&&this.sendToClient(s,n),t.status(202).send()}catch(r){this.logger.error("\u5904\u7406 SSE \u6D88\u606F\u65F6\u51FA\u9519",r),t.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:r.message}})}}async handleRPC(e,t){try{let r=e.body;this.logger.debug("\u6536\u5230 RPC \u6D88\u606F:",r);let o=await this.messageHandler.handleMessage(r);t.json(o)}catch(r){this.logger.error("\u5904\u7406 RPC \u6D88\u606F\u65F6\u51FA\u9519",r),t.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:r.message},id:e.body?.id||null})}}handleStatus(e,t){t.json({status:"ok",mode:"mcp-server",serviceManager:"running",clients:this.clients.size,tools:0,maxClients:this.maxClients,enableSSE:this.enableSSE,enableRPC:this.enableRPC,uptime:process.uptime()})}handleHealth(e,t){t.json({status:"ok",mode:"mcp-server",timestamp:new Date().toISOString()})}sendToClient(e,t){try{let r=this.serializeMessage(t);e.response.write(`data: ${r}
13
+ `),e.on("close",()=>{this.clients.delete(n),this.logger.info(`SSE \u5BA2\u6237\u7AEF\u5DF2\u65AD\u5F00\u8FDE\u63A5: ${r} (\u4F1A\u8BDD: ${n})`)}),e.on("error",s=>{this.logger.error(`SSE \u5BA2\u6237\u7AEF\u8FDE\u63A5\u9519\u8BEF: ${r}`,s),this.clients.delete(n)})}async handleMessages(e,t){try{let r=e.query.sessionId,n=e.body;if(this.logger.debug(`\u6536\u5230 SSE \u6D88\u606F (\u4F1A\u8BDD: ${r}):`,n),!r||!this.clients.has(r)){t.status(400).json({jsonrpc:"2.0",error:{code:-32600,message:"\u65E0\u6548\u6216\u7F3A\u5C11 sessionId"},id:n.id});return}let o=await this.messageHandler.handleMessage(n);this.logger.debug("SSE \u6D88\u606F\u5904\u7406\u54CD\u5E94:",o);let s=this.clients.get(r);s&&o!==null&&this.sendToClient(s,o),t.status(202).send()}catch(r){this.logger.error("\u5904\u7406 SSE \u6D88\u606F\u65F6\u51FA\u9519",r),t.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:r.message}})}}async handleRPC(e,t){try{let r=e.body;this.logger.debug("\u6536\u5230 RPC \u6D88\u606F:",r);let n=await this.messageHandler.handleMessage(r);t.json(n)}catch(r){this.logger.error("\u5904\u7406 RPC \u6D88\u606F\u65F6\u51FA\u9519",r),t.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:r.message},id:e.body?.id||null})}}handleStatus(e,t){t.json({status:"ok",mode:"mcp-server",serviceManager:"running",clients:this.clients.size,tools:0,maxClients:this.maxClients,enableSSE:this.enableSSE,enableRPC:this.enableRPC,uptime:process.uptime()})}handleHealth(e,t){t.json({status:"ok",mode:"mcp-server",timestamp:new Date().toISOString()})}sendToClient(e,t){try{let r=this.serializeMessage(t);e.response.write(`data: ${r}
14
14
 
15
- `),this.logger.debug(`\u6D88\u606F\u5DF2\u53D1\u9001\u5230\u5BA2\u6237\u7AEF ${e.id}`,{sessionId:e.sessionId,messageId:t.id})}catch(r){this.logger.error(`\u5411\u5BA2\u6237\u7AEF ${e.id} \u53D1\u9001\u6D88\u606F\u5931\u8D25`,r),this.clients.delete(e.sessionId)}}broadcastToClients(e){for(let t of this.clients.values())this.sendToClient(t,e)}getStatus(){return{isRunning:this.server!==null,port:this.port,host:this.host,clientCount:this.clients.size,maxClients:this.maxClients,enableSSE:this.enableSSE,enableRPC:this.enableRPC,connectionId:this.connectionId,state:this.state}}getClients(){return Array.from(this.clients.values()).map(e=>({id:e.id,sessionId:e.sessionId,connectedAt:e.connectedAt}))}}});var eo=m(()=>{"use strict";Qe()});import xa,{WebSocketServer as Oa}from"ws";var to=m(()=>{"use strict";Qe()});import{createHash as On}from"crypto";function Ce(i,e){let t=On("md5").update(JSON.stringify(e||{})).digest("hex");return`${i}_${t}`}function Ne(i,e){let t=new Date(i).getTime();return Date.now()-t>e}function Ee(i){let e=Date.now(),t=new Date(i.timestamp).getTime();return!!(i.consumed&&e-t>6e4||e-t>i.ttl||i.status==="failed")}var ve,vt=m(()=>{"use strict";c(Ce,"generateCacheKey");c(Ne,"isCacheExpired");c(Ee,"shouldCleanupCache");ve={TIMEOUT:8e3,CACHE_TTL:3e5,CLEANUP_INTERVAL:6e4,MAX_CACHE_SIZE:1e3,ENABLE_ONE_TIME_CACHE:!0}});var St,ro=m(()=>{"use strict";vt();St=class{static{c(this,"CacheLifecycleManager")}logger;cleanupInterval;statistics;lastCleanupTime;constructor(e){this.logger=e,this.statistics=this.initializeStatistics(),this.lastCleanupTime=new Date().toISOString()}initializeStatistics(){return{totalEntries:0,pendingTasks:0,completedTasks:0,failedTasks:0,consumedEntries:0,cacheHitRate:0,lastCleanupTime:new Date().toISOString(),memoryUsage:0}}startAutoCleanup(){if(this.cleanupInterval){this.logger.warn("[CacheLifecycle] \u81EA\u52A8\u6E05\u7406\u5B9A\u65F6\u5668\u5DF2\u7ECF\u5728\u8FD0\u884C");return}this.cleanupInterval=setInterval(()=>{this.performCleanup().catch(e=>{this.logger.error(`[CacheLifecycle] \u81EA\u52A8\u6E05\u7406\u5931\u8D25: ${e}`)})},ve.CLEANUP_INTERVAL),this.logger.info(`[CacheLifecycle] \u542F\u52A8\u81EA\u52A8\u6E05\u7406\u5B9A\u65F6\u5668\uFF0C\u95F4\u9694: ${ve.CLEANUP_INTERVAL}ms`)}stopAutoCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0,this.logger.info("[CacheLifecycle] \u505C\u6B62\u81EA\u52A8\u6E05\u7406\u5B9A\u65F6\u5668"))}createCacheEntry(e,t,r,o="pending",n){let s={result:r,timestamp:new Date().toISOString(),ttl:ve.CACHE_TTL,status:o,consumed:!1,taskId:n,retryCount:0};return this.logger.debug(`[CacheLifecycle] \u521B\u5EFA\u7F13\u5B58\u6761\u76EE: ${e}, \u72B6\u6001: ${o}`),s}updateCacheStatus(e,t,r,o,n){if(!e.customMCPResults||!e.customMCPResults[t])return this.logger.warn(`[CacheLifecycle] \u7F13\u5B58\u6761\u76EE\u4E0D\u5B58\u5728: ${t}`),!1;let s=e.customMCPResults[t],a=s.status;return this.logStateTransition(t,a,r),s.status=r,s.timestamp=new Date().toISOString(),o&&(s.result=o),n&&r==="failed"&&(s.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${n}`}]},s.consumed=!0),r==="completed"&&(s.consumed=!1),this.logger.debug(`[CacheLifecycle] \u66F4\u65B0\u7F13\u5B58\u72B6\u6001: ${t} ${a} -> ${r}`),!0}markAsConsumed(e,t){if(!e.customMCPResults||!e.customMCPResults[t])return!1;let r=e.customMCPResults[t];return r.consumed?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u5DF2\u6807\u8BB0\u4E3A\u6D88\u8D39: ${t}`),!0):(r.consumed=!0,r.timestamp=new Date().toISOString(),this.logStateTransition(t,r.status,"consumed"),this.logger.debug(`[CacheLifecycle] \u6807\u8BB0\u7F13\u5B58\u4E3A\u5DF2\u6D88\u8D39: ${t}`),!0)}isCacheAvailable(e,t){if(!e.customMCPResults||!e.customMCPResults[t])return!1;let r=e.customMCPResults[t];return Ne(r.timestamp,r.ttl)?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u5DF2\u8FC7\u671F: ${t}`),!1):r.consumed?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u5DF2\u6D88\u8D39: ${t}`),!1):r.status!=="completed"?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u72B6\u6001\u672A\u5B8C\u6210: ${t}, \u72B6\u6001: ${r.status}`),!1):!0}async performCleanup(){try{this.logger.debug("[CacheLifecycle] \u6267\u884C\u7F13\u5B58\u6E05\u7406"),this.lastCleanupTime=new Date().toISOString()}catch(e){throw this.logger.error(`[CacheLifecycle] \u6E05\u7406\u5931\u8D25: ${e}`),e}}cleanupCacheEntries(e,t){if(!e.customMCPResults)return{cleaned:0,total:0};let r=Object.entries(e.customMCPResults),o=0,n=t||r.map(([s])=>s);for(let s of n){let a=e.customMCPResults[s];a&&Ee(a)&&(delete e.customMCPResults[s],o++,this.logger.debug(`[CacheLifecycle] \u6E05\u7406\u7F13\u5B58\u6761\u76EE: ${s}`))}return this.logger.info(`[CacheLifecycle] \u6E05\u7406\u5B8C\u6210: ${o}/${n.length}`),{cleaned:o,total:n.length}}cleanupExpiredCache(e){if(!e.customMCPResults)return{cleaned:0,total:0};let t=Object.entries(e.customMCPResults),r=0;for(let[o,n]of t)Ne(n.timestamp,n.ttl)&&(delete e.customMCPResults[o],r++,this.logger.debug(`[CacheLifecycle] \u6E05\u7406\u8FC7\u671F\u7F13\u5B58: ${o}`));return r>0&&this.logger.info(`[CacheLifecycle] \u6E05\u7406\u8FC7\u671F\u7F13\u5B58: ${r}/${t.length}`),{cleaned:r,total:t.length}}cleanupConsumedCache(e){if(!e.customMCPResults)return{cleaned:0,total:0};let t=Object.entries(e.customMCPResults),r=0,o=Date.now();for(let[n,s]of t)if(s.consumed){let a=new Date(s.timestamp).getTime();o-a>6e4&&(delete e.customMCPResults[n],r++,this.logger.debug(`[CacheLifecycle] \u6E05\u7406\u5DF2\u6D88\u8D39\u7F13\u5B58: ${n}`))}return r>0&&this.logger.info(`[CacheLifecycle] \u6E05\u7406\u5DF2\u6D88\u8D39\u7F13\u5B58: ${r}/${t.length}`),{cleaned:r,total:t.length}}updateStatistics(e){if(!e.customMCPResults){this.statistics=this.initializeStatistics();return}let t=Object.values(e.customMCPResults);this.statistics.totalEntries=t.length,this.statistics.pendingTasks=t.filter(n=>n.status==="pending").length,this.statistics.completedTasks=t.filter(n=>n.status==="completed").length,this.statistics.failedTasks=t.filter(n=>n.status==="failed").length,this.statistics.consumedEntries=t.filter(n=>n.consumed).length;let r=this.statistics.completedTasks,o=this.statistics.consumedEntries;this.statistics.cacheHitRate=r>0?o/r*100:0,this.statistics.lastCleanupTime=this.lastCleanupTime,this.statistics.memoryUsage=JSON.stringify(e.customMCPResults).length}getStatistics(){return{...this.statistics}}validateCacheIntegrity(e){let t=[];if(!e.customMCPResults)return{isValid:!0,issues:[]};for(let[r,o]of Object.entries(e.customMCPResults))(!o.timestamp||!o.ttl||!o.status)&&t.push(`\u7F13\u5B58\u6761\u76EE\u7F3A\u5C11\u5FC5\u9700\u5B57\u6BB5: ${r}`),Number.isNaN(new Date(o.timestamp).getTime())&&t.push(`\u65E0\u6548\u7684\u65F6\u95F4\u6233\u683C\u5F0F: ${r}`),["pending","completed","failed"].includes(o.status)||t.push(`\u65E0\u6548\u7684\u72B6\u6001\u503C: ${r}, \u72B6\u6001: ${o.status}`),Ne(o.timestamp,o.ttl)&&t.push(`\u7F13\u5B58\u6761\u76EE\u5DF2\u8FC7\u671F: ${r}`);return{isValid:t.length===0,issues:t}}logStateTransition(e,t,r){let o={from:t,to:r,reason:this.getTransitionReason(t,r),timestamp:new Date().toISOString()};this.logger.debug(`[CacheLifecycle] \u72B6\u6001\u8F6C\u6362: ${e} ${t} -> ${r} (${o.reason})`)}getTransitionReason(e,t){return{"pending->completed":"\u4EFB\u52A1\u6267\u884C\u6210\u529F","pending->failed":"\u4EFB\u52A1\u6267\u884C\u5931\u8D25","completed->consumed":"\u7ED3\u679C\u88AB\u6D88\u8D39","failed->consumed":"\u5931\u8D25\u7ED3\u679C\u88AB\u5904\u7406","consumed->deleted":"\u7F13\u5B58\u88AB\u6E05\u7406"}[`${e}->${t}`]||"\u72B6\u6001\u66F4\u65B0"}cleanup(){this.stopAutoCleanup(),this.logger.info("[CacheLifecycle] \u6E05\u7406\u8D44\u6E90\u5B8C\u6210")}}});var yt,oo=m(()=>{"use strict";yt=class{static{c(this,"TaskStateManager")}logger;activeTasks;taskHistory;constructor(e){this.logger=e,this.activeTasks=new Map,this.taskHistory=[]}generateTaskId(e,t){let r=Date.now(),o=Math.random().toString(36).substring(2,11),n=`${e}_${r}_${o}`;return this.logger.debug(`[TaskState] \u751F\u6210\u4EFB\u52A1ID: ${n}`),n}validateTaskId(e){let r=/^[a-zA-Z0-9_-]+_\d+_[a-zA-Z0-9]+$/.test(e);return r||this.logger.warn(`[TaskState] \u65E0\u6548\u7684\u4EFB\u52A1ID\u683C\u5F0F: ${e}`),r}extractToolName(e){if(!this.validateTaskId(e))return null;let t=e.split("_");if(t.length<3)return null;let r=t.findIndex(n=>/^\d+$/.test(n));return r<=0?null:t.slice(0,r).join("_")}createTask(e,t,r,o="pending"){if(this.activeTasks.has(e))throw new Error(`\u4EFB\u52A1\u5DF2\u5B58\u5728: ${e}`);let n={taskId:e,toolName:t,arguments:r,status:o,startTime:new Date().toISOString()};return this.activeTasks.set(e,n),this.recordStateTransition(e,"none",o,"\u521B\u5EFA\u65B0\u4EFB\u52A1"),this.logger.info(`[TaskState] \u521B\u5EFA\u4EFB\u52A1: ${e}, \u5DE5\u5177: ${t}, \u72B6\u6001: ${o}`),n}updateTaskStatus(e,t,r,o){let n=this.activeTasks.get(e);if(!n)return this.logger.warn(`[TaskState] \u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`),!1;let s=n.status;return n.status=t,(t==="completed"||t==="failed")&&(n.endTime=new Date().toISOString()),r&&(n.result=r),o&&(n.error=o),this.recordStateTransition(e,s,t,this.getStatusChangeReason(s,t,o)),this.logger.info(`[TaskState] \u66F4\u65B0\u4EFB\u52A1\u72B6\u6001: ${e} ${s} -> ${t}`),!0}markTaskAsPending(e,t,r){let o=this.activeTasks.get(e);return o?this.updateTaskStatus(e,"pending"):o=this.createTask(e,t,r,"pending"),o}markTaskAsCompleted(e,t){return this.updateTaskStatus(e,"completed",t)}markTaskAsFailed(e,t){return this.updateTaskStatus(e,"failed",void 0,t)}markTaskAsConsumed(e){return this.updateTaskStatus(e,"consumed")}getTask(e){return this.activeTasks.get(e)||null}hasTask(e){return this.activeTasks.has(e)}getTaskStatus(e){let t=this.activeTasks.get(e);return t?t.status:null}getTasksByStatus(e){return Array.from(this.activeTasks.values()).filter(t=>t.status===e)}getTasksByTool(e){return Array.from(this.activeTasks.values()).filter(t=>t.toolName===e)}getTaskExecutionTime(e){let t=this.activeTasks.get(e);if(!t||!t.endTime)return null;let r=new Date(t.startTime).getTime();return new Date(t.endTime).getTime()-r}isTaskTimeout(e,t=8e3){let r=this.activeTasks.get(e);if(!r)return!1;let o=new Date(r.startTime).getTime();return Date.now()-o>t}getTimeoutTasks(e=8e3){let t=Date.now();return Array.from(this.activeTasks.values()).filter(r=>{let o=new Date(r.startTime).getTime();return t-o>e&&r.status==="pending"})}removeTask(e){let t=this.activeTasks.get(e);return t?(this.recordStateTransition(e,t.status,"deleted","\u4EFB\u52A1\u88AB\u79FB\u9664"),this.activeTasks.delete(e),this.logger.info(`[TaskState] \u79FB\u9664\u4EFB\u52A1: ${e}`),!0):!1}cleanupCompletedTasks(e=3e5){let t=Date.now(),r=0;for(let[o,n]of this.activeTasks.entries())if(n.status==="completed"||n.status==="failed"){let s=n.endTime?new Date(n.endTime).getTime():t;t-s>e&&(this.removeTask(o),r++)}return r>0&&this.logger.info(`[TaskState] \u6E05\u7406\u5DF2\u5B8C\u6210\u4EFB\u52A1: ${r}\u4E2A`),r}getTaskStatistics(){let e=Array.from(this.activeTasks.values()),t=e.length,r=e.filter(h=>h.status==="pending").length,o=e.filter(h=>h.status==="completed").length,n=e.filter(h=>h.status==="failed").length,s=e.filter(h=>h.status==="consumed").length,a=e.filter(h=>h.status==="completed"&&h.endTime),l=a.length>0?a.reduce((h,p)=>{let d=this.getTaskExecutionTime(p.taskId)||0;return h+d},0)/a.length:0;return{total:t,pending:r,completed:o,failed:n,consumed:s,averageExecutionTime:l}}getTaskHistory(e){return e?this.taskHistory.filter(t=>t.taskId===e):[...this.taskHistory]}recordStateTransition(e,t,r,o){let n={from:t,to:r,reason:o,timestamp:new Date().toISOString(),taskId:e};this.taskHistory.push(n),this.taskHistory.length>1e3&&(this.taskHistory=this.taskHistory.slice(-500))}getStatusChangeReason(e,t,r){if(r)return`\u6267\u884C\u5931\u8D25: ${r}`;let o={"none->pending":"\u4EFB\u52A1\u5F00\u59CB\u6267\u884C","pending->completed":"\u4EFB\u52A1\u6267\u884C\u6210\u529F","pending->failed":"\u4EFB\u52A1\u6267\u884C\u5931\u8D25","completed->consumed":"\u7ED3\u679C\u88AB\u6D88\u8D39","failed->consumed":"\u5931\u8D25\u7ED3\u679C\u88AB\u5904\u7406","consumed->deleted":"\u4EFB\u52A1\u88AB\u6E05\u7406"},n=`${e}->${t}`;return o[n]||"\u72B6\u6001\u66F4\u65B0"}validateTaskIntegrity(){let e=[];for(let[t,r]of this.activeTasks.entries())(!r.taskId||!r.toolName||!r.status||!r.startTime)&&e.push(`\u4EFB\u52A1\u7F3A\u5C11\u5FC5\u9700\u5B57\u6BB5: ${t}`),Number.isNaN(new Date(r.startTime).getTime())&&e.push(`\u65E0\u6548\u7684\u5F00\u59CB\u65F6\u95F4: ${t}`),r.endTime&&Number.isNaN(new Date(r.endTime).getTime())&&e.push(`\u65E0\u6548\u7684\u7ED3\u675F\u65F6\u95F4: ${t}`),r.status==="completed"&&!r.endTime&&e.push(`\u5DF2\u5B8C\u6210\u4EFB\u52A1\u7F3A\u5C11\u7ED3\u675F\u65F6\u95F4: ${t}`),r.status==="failed"&&!r.error&&e.push(`\u5931\u8D25\u4EFB\u52A1\u7F3A\u5C11\u9519\u8BEF\u4FE1\u606F: ${t}`);return{isValid:e.length===0,issues:e}}restartStalledTasks(e=3e4){let t=this.getTimeoutTasks(e),r=0;for(let o of t){this.logger.warn(`[TaskState] \u68C0\u6D4B\u5230\u505C\u6EDE\u4EFB\u52A1: ${o.taskId}`),this.markTaskAsFailed(o.taskId,"\u4EFB\u52A1\u6267\u884C\u8D85\u65F6");let n=this.generateTaskId(o.toolName,o.arguments);this.createTask(n,o.toolName,o.arguments,"pending"),r++}return r>0&&this.logger.info(`[TaskState] \u91CD\u542F\u505C\u6EDE\u4EFB\u52A1: ${r}\u4E2A`),r}cleanup(){this.activeTasks.clear(),this.taskHistory=[],this.logger.info("[TaskState] \u6E05\u7406\u4EFB\u52A1\u72B6\u6001\u7BA1\u7406\u5668\u8D44\u6E90")}}});function no(i,e){return{content:[{type:"text",text:e?An(e,i):so(i)}],isError:!1,taskId:i,status:"timeout",message:"\u5DE5\u5177\u8C03\u7528\u8D85\u65F6\uFF0C\u6B63\u5728\u540E\u53F0\u5904\u7406\u4E2D",nextAction:"\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6216\u7B49\u5F85\u4EFB\u52A1\u5B8C\u6210"}}function An(i,e){let t={coze_workflow:`\u23F1\uFE0F \u6263\u5B50\u5DE5\u4F5C\u6D41\u6267\u884C\u8D85\u65F6\uFF0C\u6B63\u5728\u540E\u53F0\u5904\u7406\u4E2D...
15
+ `),this.logger.debug(`\u6D88\u606F\u5DF2\u53D1\u9001\u5230\u5BA2\u6237\u7AEF ${e.id}`,{sessionId:e.sessionId,messageId:t.id})}catch(r){this.logger.error(`\u5411\u5BA2\u6237\u7AEF ${e.id} \u53D1\u9001\u6D88\u606F\u5931\u8D25`,r),this.clients.delete(e.sessionId)}}broadcastToClients(e){for(let t of this.clients.values())this.sendToClient(t,e)}getStatus(){return{isRunning:this.server!==null,port:this.port,host:this.host,clientCount:this.clients.size,maxClients:this.maxClients,enableSSE:this.enableSSE,enableRPC:this.enableRPC,connectionId:this.connectionId,state:this.state}}getClients(){return Array.from(this.clients.values()).map(e=>({id:e.id,sessionId:e.sessionId,connectedAt:e.connectedAt}))}}});var tn=m(()=>{"use strict";et()});import Aa,{WebSocketServer as Na}from"ws";var rn=m(()=>{"use strict";et()});import{createHash as No}from"crypto";function ve(i,e){let t=No("md5").update(JSON.stringify(e||{})).digest("hex");return`${i}_${t}`}function _e(i,e){let t=new Date(i).getTime();return Date.now()-t>e}function Me(i){let e=Date.now(),t=new Date(i.timestamp).getTime();return!!(i.consumed&&e-t>6e4||e-t>i.ttl||i.status==="failed")}var Se,St=m(()=>{"use strict";c(ve,"generateCacheKey");c(_e,"isCacheExpired");c(Me,"shouldCleanupCache");Se={TIMEOUT:8e3,CACHE_TTL:3e5,CLEANUP_INTERVAL:6e4,MAX_CACHE_SIZE:1e3,ENABLE_ONE_TIME_CACHE:!0}});var yt,nn=m(()=>{"use strict";St();yt=class{static{c(this,"CacheLifecycleManager")}logger;cleanupInterval;statistics;lastCleanupTime;constructor(e){this.logger=e,this.statistics=this.initializeStatistics(),this.lastCleanupTime=new Date().toISOString()}initializeStatistics(){return{totalEntries:0,pendingTasks:0,completedTasks:0,failedTasks:0,consumedEntries:0,cacheHitRate:0,lastCleanupTime:new Date().toISOString(),memoryUsage:0}}startAutoCleanup(){if(this.cleanupInterval){this.logger.warn("[CacheLifecycle] \u81EA\u52A8\u6E05\u7406\u5B9A\u65F6\u5668\u5DF2\u7ECF\u5728\u8FD0\u884C");return}this.cleanupInterval=setInterval(()=>{this.performCleanup().catch(e=>{this.logger.error(`[CacheLifecycle] \u81EA\u52A8\u6E05\u7406\u5931\u8D25: ${e}`)})},Se.CLEANUP_INTERVAL),this.logger.info(`[CacheLifecycle] \u542F\u52A8\u81EA\u52A8\u6E05\u7406\u5B9A\u65F6\u5668\uFF0C\u95F4\u9694: ${Se.CLEANUP_INTERVAL}ms`)}stopAutoCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0,this.logger.info("[CacheLifecycle] \u505C\u6B62\u81EA\u52A8\u6E05\u7406\u5B9A\u65F6\u5668"))}createCacheEntry(e,t,r,n="pending",o){let s={result:r,timestamp:new Date().toISOString(),ttl:Se.CACHE_TTL,status:n,consumed:!1,taskId:o,retryCount:0};return this.logger.debug(`[CacheLifecycle] \u521B\u5EFA\u7F13\u5B58\u6761\u76EE: ${e}, \u72B6\u6001: ${n}`),s}updateCacheStatus(e,t,r,n,o){if(!e.customMCPResults||!e.customMCPResults[t])return this.logger.warn(`[CacheLifecycle] \u7F13\u5B58\u6761\u76EE\u4E0D\u5B58\u5728: ${t}`),!1;let s=e.customMCPResults[t],a=s.status;return this.logStateTransition(t,a,r),s.status=r,s.timestamp=new Date().toISOString(),n&&(s.result=n),o&&r==="failed"&&(s.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${o}`}]},s.consumed=!0),r==="completed"&&(s.consumed=!1),this.logger.debug(`[CacheLifecycle] \u66F4\u65B0\u7F13\u5B58\u72B6\u6001: ${t} ${a} -> ${r}`),!0}markAsConsumed(e,t){if(!e.customMCPResults||!e.customMCPResults[t])return!1;let r=e.customMCPResults[t];return r.consumed?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u5DF2\u6807\u8BB0\u4E3A\u6D88\u8D39: ${t}`),!0):(r.consumed=!0,r.timestamp=new Date().toISOString(),this.logStateTransition(t,r.status,"consumed"),this.logger.debug(`[CacheLifecycle] \u6807\u8BB0\u7F13\u5B58\u4E3A\u5DF2\u6D88\u8D39: ${t}`),!0)}isCacheAvailable(e,t){if(!e.customMCPResults||!e.customMCPResults[t])return!1;let r=e.customMCPResults[t];return _e(r.timestamp,r.ttl)?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u5DF2\u8FC7\u671F: ${t}`),!1):r.consumed?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u5DF2\u6D88\u8D39: ${t}`),!1):r.status!=="completed"?(this.logger.debug(`[CacheLifecycle] \u7F13\u5B58\u72B6\u6001\u672A\u5B8C\u6210: ${t}, \u72B6\u6001: ${r.status}`),!1):!0}async performCleanup(){try{this.logger.debug("[CacheLifecycle] \u6267\u884C\u7F13\u5B58\u6E05\u7406"),this.lastCleanupTime=new Date().toISOString()}catch(e){throw this.logger.error(`[CacheLifecycle] \u6E05\u7406\u5931\u8D25: ${e}`),e}}cleanupCacheEntries(e,t){if(!e.customMCPResults)return{cleaned:0,total:0};let r=Object.entries(e.customMCPResults),n=0,o=t||r.map(([s])=>s);for(let s of o){let a=e.customMCPResults[s];a&&Me(a)&&(delete e.customMCPResults[s],n++,this.logger.debug(`[CacheLifecycle] \u6E05\u7406\u7F13\u5B58\u6761\u76EE: ${s}`))}return this.logger.info(`[CacheLifecycle] \u6E05\u7406\u5B8C\u6210: ${n}/${o.length}`),{cleaned:n,total:o.length}}cleanupExpiredCache(e){if(!e.customMCPResults)return{cleaned:0,total:0};let t=Object.entries(e.customMCPResults),r=0;for(let[n,o]of t)_e(o.timestamp,o.ttl)&&(delete e.customMCPResults[n],r++,this.logger.debug(`[CacheLifecycle] \u6E05\u7406\u8FC7\u671F\u7F13\u5B58: ${n}`));return r>0&&this.logger.info(`[CacheLifecycle] \u6E05\u7406\u8FC7\u671F\u7F13\u5B58: ${r}/${t.length}`),{cleaned:r,total:t.length}}cleanupConsumedCache(e){if(!e.customMCPResults)return{cleaned:0,total:0};let t=Object.entries(e.customMCPResults),r=0,n=Date.now();for(let[o,s]of t)if(s.consumed){let a=new Date(s.timestamp).getTime();n-a>6e4&&(delete e.customMCPResults[o],r++,this.logger.debug(`[CacheLifecycle] \u6E05\u7406\u5DF2\u6D88\u8D39\u7F13\u5B58: ${o}`))}return r>0&&this.logger.info(`[CacheLifecycle] \u6E05\u7406\u5DF2\u6D88\u8D39\u7F13\u5B58: ${r}/${t.length}`),{cleaned:r,total:t.length}}updateStatistics(e){if(!e.customMCPResults){this.statistics=this.initializeStatistics();return}let t=Object.values(e.customMCPResults);this.statistics.totalEntries=t.length,this.statistics.pendingTasks=t.filter(o=>o.status==="pending").length,this.statistics.completedTasks=t.filter(o=>o.status==="completed").length,this.statistics.failedTasks=t.filter(o=>o.status==="failed").length,this.statistics.consumedEntries=t.filter(o=>o.consumed).length;let r=this.statistics.completedTasks,n=this.statistics.consumedEntries;this.statistics.cacheHitRate=r>0?n/r*100:0,this.statistics.lastCleanupTime=this.lastCleanupTime,this.statistics.memoryUsage=JSON.stringify(e.customMCPResults).length}getStatistics(){return{...this.statistics}}validateCacheIntegrity(e){let t=[];if(!e.customMCPResults)return{isValid:!0,issues:[]};for(let[r,n]of Object.entries(e.customMCPResults))(!n.timestamp||!n.ttl||!n.status)&&t.push(`\u7F13\u5B58\u6761\u76EE\u7F3A\u5C11\u5FC5\u9700\u5B57\u6BB5: ${r}`),Number.isNaN(new Date(n.timestamp).getTime())&&t.push(`\u65E0\u6548\u7684\u65F6\u95F4\u6233\u683C\u5F0F: ${r}`),["pending","completed","failed"].includes(n.status)||t.push(`\u65E0\u6548\u7684\u72B6\u6001\u503C: ${r}, \u72B6\u6001: ${n.status}`),_e(n.timestamp,n.ttl)&&t.push(`\u7F13\u5B58\u6761\u76EE\u5DF2\u8FC7\u671F: ${r}`);return{isValid:t.length===0,issues:t}}logStateTransition(e,t,r){let n={from:t,to:r,reason:this.getTransitionReason(t,r),timestamp:new Date().toISOString()};this.logger.debug(`[CacheLifecycle] \u72B6\u6001\u8F6C\u6362: ${e} ${t} -> ${r} (${n.reason})`)}getTransitionReason(e,t){return{"pending->completed":"\u4EFB\u52A1\u6267\u884C\u6210\u529F","pending->failed":"\u4EFB\u52A1\u6267\u884C\u5931\u8D25","completed->consumed":"\u7ED3\u679C\u88AB\u6D88\u8D39","failed->consumed":"\u5931\u8D25\u7ED3\u679C\u88AB\u5904\u7406","consumed->deleted":"\u7F13\u5B58\u88AB\u6E05\u7406"}[`${e}->${t}`]||"\u72B6\u6001\u66F4\u65B0"}cleanup(){this.stopAutoCleanup(),this.logger.info("[CacheLifecycle] \u6E05\u7406\u8D44\u6E90\u5B8C\u6210")}}});var Et,on=m(()=>{"use strict";Et=class{static{c(this,"TaskStateManager")}logger;activeTasks;taskHistory;constructor(e){this.logger=e,this.activeTasks=new Map,this.taskHistory=[]}generateTaskId(e,t){let r=Date.now(),n=Math.random().toString(36).substring(2,11),o=`${e}_${r}_${n}`;return this.logger.debug(`[TaskState] \u751F\u6210\u4EFB\u52A1ID: ${o}`),o}validateTaskId(e){let r=/^[a-zA-Z0-9_-]+_\d+_[a-zA-Z0-9]+$/.test(e);return r||this.logger.warn(`[TaskState] \u65E0\u6548\u7684\u4EFB\u52A1ID\u683C\u5F0F: ${e}`),r}extractToolName(e){if(!this.validateTaskId(e))return null;let t=e.split("_");if(t.length<3)return null;let r=t.findIndex(o=>/^\d+$/.test(o));return r<=0?null:t.slice(0,r).join("_")}createTask(e,t,r,n="pending"){if(this.activeTasks.has(e))throw new Error(`\u4EFB\u52A1\u5DF2\u5B58\u5728: ${e}`);let o={taskId:e,toolName:t,arguments:r,status:n,startTime:new Date().toISOString()};return this.activeTasks.set(e,o),this.recordStateTransition(e,"none",n,"\u521B\u5EFA\u65B0\u4EFB\u52A1"),this.logger.info(`[TaskState] \u521B\u5EFA\u4EFB\u52A1: ${e}, \u5DE5\u5177: ${t}, \u72B6\u6001: ${n}`),o}updateTaskStatus(e,t,r,n){let o=this.activeTasks.get(e);if(!o)return this.logger.warn(`[TaskState] \u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`),!1;let s=o.status;return o.status=t,(t==="completed"||t==="failed")&&(o.endTime=new Date().toISOString()),r&&(o.result=r),n&&(o.error=n),this.recordStateTransition(e,s,t,this.getStatusChangeReason(s,t,n)),this.logger.info(`[TaskState] \u66F4\u65B0\u4EFB\u52A1\u72B6\u6001: ${e} ${s} -> ${t}`),!0}markTaskAsPending(e,t,r){let n=this.activeTasks.get(e);return n?this.updateTaskStatus(e,"pending"):n=this.createTask(e,t,r,"pending"),n}markTaskAsCompleted(e,t){return this.updateTaskStatus(e,"completed",t)}markTaskAsFailed(e,t){return this.updateTaskStatus(e,"failed",void 0,t)}markTaskAsConsumed(e){return this.updateTaskStatus(e,"consumed")}getTask(e){return this.activeTasks.get(e)||null}hasTask(e){return this.activeTasks.has(e)}getTaskStatus(e){let t=this.activeTasks.get(e);return t?t.status:null}getTasksByStatus(e){return Array.from(this.activeTasks.values()).filter(t=>t.status===e)}getTasksByTool(e){return Array.from(this.activeTasks.values()).filter(t=>t.toolName===e)}getTaskExecutionTime(e){let t=this.activeTasks.get(e);if(!t||!t.endTime)return null;let r=new Date(t.startTime).getTime();return new Date(t.endTime).getTime()-r}isTaskTimeout(e,t=8e3){let r=this.activeTasks.get(e);if(!r)return!1;let n=new Date(r.startTime).getTime();return Date.now()-n>t}getTimeoutTasks(e=8e3){let t=Date.now();return Array.from(this.activeTasks.values()).filter(r=>{let n=new Date(r.startTime).getTime();return t-n>e&&r.status==="pending"})}removeTask(e){let t=this.activeTasks.get(e);return t?(this.recordStateTransition(e,t.status,"deleted","\u4EFB\u52A1\u88AB\u79FB\u9664"),this.activeTasks.delete(e),this.logger.info(`[TaskState] \u79FB\u9664\u4EFB\u52A1: ${e}`),!0):!1}cleanupCompletedTasks(e=3e5){let t=Date.now(),r=0;for(let[n,o]of this.activeTasks.entries())if(o.status==="completed"||o.status==="failed"){let s=o.endTime?new Date(o.endTime).getTime():t;t-s>e&&(this.removeTask(n),r++)}return r>0&&this.logger.info(`[TaskState] \u6E05\u7406\u5DF2\u5B8C\u6210\u4EFB\u52A1: ${r}\u4E2A`),r}getTaskStatistics(){let e=Array.from(this.activeTasks.values()),t=e.length,r=e.filter(g=>g.status==="pending").length,n=e.filter(g=>g.status==="completed").length,o=e.filter(g=>g.status==="failed").length,s=e.filter(g=>g.status==="consumed").length,a=e.filter(g=>g.status==="completed"&&g.endTime),l=a.length>0?a.reduce((g,u)=>{let d=this.getTaskExecutionTime(u.taskId)||0;return g+d},0)/a.length:0;return{total:t,pending:r,completed:n,failed:o,consumed:s,averageExecutionTime:l}}getTaskHistory(e){return e?this.taskHistory.filter(t=>t.taskId===e):[...this.taskHistory]}recordStateTransition(e,t,r,n){let o={from:t,to:r,reason:n,timestamp:new Date().toISOString(),taskId:e};this.taskHistory.push(o),this.taskHistory.length>1e3&&(this.taskHistory=this.taskHistory.slice(-500))}getStatusChangeReason(e,t,r){if(r)return`\u6267\u884C\u5931\u8D25: ${r}`;let n={"none->pending":"\u4EFB\u52A1\u5F00\u59CB\u6267\u884C","pending->completed":"\u4EFB\u52A1\u6267\u884C\u6210\u529F","pending->failed":"\u4EFB\u52A1\u6267\u884C\u5931\u8D25","completed->consumed":"\u7ED3\u679C\u88AB\u6D88\u8D39","failed->consumed":"\u5931\u8D25\u7ED3\u679C\u88AB\u5904\u7406","consumed->deleted":"\u4EFB\u52A1\u88AB\u6E05\u7406"},o=`${e}->${t}`;return n[o]||"\u72B6\u6001\u66F4\u65B0"}validateTaskIntegrity(){let e=[];for(let[t,r]of this.activeTasks.entries())(!r.taskId||!r.toolName||!r.status||!r.startTime)&&e.push(`\u4EFB\u52A1\u7F3A\u5C11\u5FC5\u9700\u5B57\u6BB5: ${t}`),Number.isNaN(new Date(r.startTime).getTime())&&e.push(`\u65E0\u6548\u7684\u5F00\u59CB\u65F6\u95F4: ${t}`),r.endTime&&Number.isNaN(new Date(r.endTime).getTime())&&e.push(`\u65E0\u6548\u7684\u7ED3\u675F\u65F6\u95F4: ${t}`),r.status==="completed"&&!r.endTime&&e.push(`\u5DF2\u5B8C\u6210\u4EFB\u52A1\u7F3A\u5C11\u7ED3\u675F\u65F6\u95F4: ${t}`),r.status==="failed"&&!r.error&&e.push(`\u5931\u8D25\u4EFB\u52A1\u7F3A\u5C11\u9519\u8BEF\u4FE1\u606F: ${t}`);return{isValid:e.length===0,issues:e}}restartStalledTasks(e=3e4){let t=this.getTimeoutTasks(e),r=0;for(let n of t){this.logger.warn(`[TaskState] \u68C0\u6D4B\u5230\u505C\u6EDE\u4EFB\u52A1: ${n.taskId}`),this.markTaskAsFailed(n.taskId,"\u4EFB\u52A1\u6267\u884C\u8D85\u65F6");let o=this.generateTaskId(n.toolName,n.arguments);this.createTask(o,n.toolName,n.arguments,"pending"),r++}return r>0&&this.logger.info(`[TaskState] \u91CD\u542F\u505C\u6EDE\u4EFB\u52A1: ${r}\u4E2A`),r}cleanup(){this.activeTasks.clear(),this.taskHistory=[],this.logger.info("[TaskState] \u6E05\u7406\u4EFB\u52A1\u72B6\u6001\u7BA1\u7406\u5668\u8D44\u6E90")}}});function sn(i,e){return{content:[{type:"text",text:e?Do(e,i):an(i)}],isError:!1,taskId:i,status:"timeout",message:"\u5DE5\u5177\u8C03\u7528\u8D85\u65F6\uFF0C\u6B63\u5728\u540E\u53F0\u5904\u7406\u4E2D",nextAction:"\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6216\u7B49\u5F85\u4EFB\u52A1\u5B8C\u6210"}}function Do(i,e){let t={coze_workflow:`\u23F1\uFE0F \u6263\u5B50\u5DE5\u4F5C\u6D41\u6267\u884C\u8D85\u65F6\uFF0C\u6B63\u5728\u540E\u53F0\u5904\u7406\u4E2D...
16
16
 
17
17
  \u{1F4CB} \u4EFB\u52A1\u4FE1\u606F\uFF1A
18
18
  - \u4EFB\u52A1ID: ${e}
@@ -23,7 +23,7 @@ data: /messages?sessionId=${o}
23
23
  \u{1F504} \u540E\u7EED\u64CD\u4F5C\uFF1A
24
24
  1. \u4F7F\u7528\u76F8\u540C\u53C2\u6570\u91CD\u65B0\u8C03\u7528\u5DE5\u5177
25
25
  2. \u7CFB\u7EDF\u4F1A\u81EA\u52A8\u8FD4\u56DE\u5DF2\u5B8C\u6210\u7684\u4EFB\u52A1\u7ED3\u679C
26
- 3. \u590D\u6742\u5DE5\u4F5C\u6D41\u53EF\u80FD\u9700\u8981\u66F4\u957F\u65F6\u95F4\u5904\u7406`,default:so(e)};return t[i]||t.default}function so(i){return`\u23F1\uFE0F \u5DE5\u5177\u8C03\u7528\u8D85\u65F6\uFF0C\u6B63\u5728\u540E\u53F0\u5904\u7406\u4E2D...
26
+ 3. \u590D\u6742\u5DE5\u4F5C\u6D41\u53EF\u80FD\u9700\u8981\u66F4\u957F\u65F6\u95F4\u5904\u7406`,default:an(e)};return t[i]||t.default}function an(i){return`\u23F1\uFE0F \u5DE5\u5177\u8C03\u7528\u8D85\u65F6\uFF0C\u6B63\u5728\u540E\u53F0\u5904\u7406\u4E2D...
27
27
 
28
28
  \u{1F4CB} \u4EFB\u52A1\u4FE1\u606F\uFF1A
29
29
  - \u4EFB\u52A1ID: ${i}
@@ -33,12 +33,12 @@ data: /messages?sessionId=${o}
33
33
  \u{1F504} \u540E\u7EED\u64CD\u4F5C\uFF1A
34
34
  1. \u4F7F\u7528\u76F8\u540C\u7684\u53C2\u6570\u91CD\u65B0\u8C03\u7528\u5DE5\u5177
35
35
  2. \u7CFB\u7EDF\u4F1A\u81EA\u52A8\u8FD4\u56DE\u5DF2\u5B8C\u6210\u7684\u4EFB\u52A1\u7ED3\u679C
36
- 3. \u5982\u679C\u957F\u65F6\u95F4\u672A\u5B8C\u6210\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458`}var et,io=m(()=>{"use strict";et=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(no,"createTimeoutResponse");c(An,"getToolSpecificTimeoutMessage");c(so,"getDefaultTimeoutMessage")});import{createHash as kn}from"crypto";import{existsSync as tt,mkdirSync as Dn,readFileSync as ao,renameSync as Nn,writeFileSync as co}from"fs";import{dirname as _n,resolve as lo}from"path";import Ln from"dayjs";var pe,Tt=m(()=>{"use strict";y();vt();pe=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 Ln().format("YYYY-MM-DD HH:mm:ss")}getCacheFilePath(){try{let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return lo(e,"xiaozhi.cache.json")}catch{let t=process.env.XIAOZHI_CONFIG_DIR||"/tmp";return lo(t,"xiaozhi.cache.json")}}async ensureCacheFile(){try{if(!tt(this.cachePath)){let e=_n(this.cachePath);tt(e)||(Dn(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(!tt(this.cachePath))return await this.createInitialCache();let e=ao(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{co(r,t,"utf8"),Nn(r,e)}catch(o){try{tt(r)&&co(r,"","utf8")}catch{}throw o}}generateConfigHash(e){try{return kn("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:tt(this.cachePath)?ao(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=Ce(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=Ce(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=Ce(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=Ce(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=Ce(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)Ee(n)&&(delete e.customMCPResults[o],r++);return r>0&&(await this.saveExtendedCache(e),this.logger.info(`[CacheManager] \u6E05\u7406CustomMCP\u7F13\u5B58: ${r}/${t.length}`)),{cleaned:r,total:t.length}}catch(e){return this.logger.warn(`[CacheManager] \u6E05\u7406CustomMCP\u7F13\u5B58\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),{cleaned:0,total:0}}}async getCustomMCPStatistics(){try{let e=await this.loadExtendedCache();if(!e.customMCPResults)return{totalEntries:0,pendingTasks:0,completedTasks:0,failedTasks:0,consumedEntries:0,cacheHitRate:0,lastCleanupTime:new Date().toISOString(),memoryUsage:0};let t=Object.values(e.customMCPResults),r=t.length,o=t.filter(p=>p.status==="pending").length,n=t.filter(p=>p.status==="completed").length,s=t.filter(p=>p.status==="failed").length,a=t.filter(p=>p.consumed).length,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 Et,go=m(()=>{"use strict";y();Z();ro();oo();vt();io();K();Tt();Et=class{static{c(this,"CustomMCPHandler")}logger;tools=new Map;cacheManager;cacheLifecycleManager;taskStateManager;mcpServiceManager;TIMEOUT=ve.TIMEOUT;CACHE_TTL=ve.CACHE_TTL;CLEANUP_INTERVAL=ve.CLEANUP_INTERVAL;cleanupTimer;activeTasks=new Map;eventBus=I();constructor(e,t){this.logger=g,this.cacheManager=e||new pe,this.mcpServiceManager=t,this.cacheLifecycleManager=new St(this.logger),this.taskStateManager=new yt(this.logger),this.startCleanupTimer(),this.cacheLifecycleManager.startAutoCleanup(),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("config:updated",async e=>{await this.handleConfigUpdated(e)})}async handleConfigUpdated(e){this.logger.info("[CustomMCP] \u68C0\u6D4B\u5230\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u662F\u5426\u9700\u8981\u91CD\u65B0\u521D\u59CB\u5316");try{e.type==="customMCP"?(this.logger.info("[CustomMCP] customMCP \u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0C\u91CD\u65B0\u521D\u59CB\u5316\u5904\u7406\u5668"),await this.reinitialize()):e.type==="serverTools"&&(this.logger.info("[CustomMCP] serverTools \u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0C\u91CD\u65B0\u521D\u59CB\u5316\u5904\u7406\u5668"),await this.reinitialize())}catch(t){this.logger.error("[CustomMCP] \u914D\u7F6E\u66F4\u65B0\u5904\u7406\u5931\u8D25:",t)}}async reinitialize(){try{this.logger.info("[CustomMCP] \u5F00\u59CB\u91CD\u65B0\u521D\u59CB\u5316\u5904\u7406\u5668"),this.tools.clear();let e=u.getCustomMCPTools();for(let t of e)this.tools.set(t.name,t),this.logger.info(`[CustomMCP] \u91CD\u65B0\u52A0\u8F7D\u5DE5\u5177: ${t.name} (${t.handler.type})`);this.logger.info(`[CustomMCP] \u91CD\u65B0\u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.tools.size} \u4E2A\u5DE5\u5177`)}catch(e){throw this.logger.error("[CustomMCP] \u91CD\u65B0\u521D\u59CB\u5316\u5931\u8D25:",e),e}}initialize(e){this.logger.info("[CustomMCP] \u521D\u59CB\u5316 CustomMCP \u5904\u7406\u5668...");try{let t=e||u.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 et){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}`),no(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 et(`\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&&!Ne(n.timestamp,n.ttl)?n.result:null}catch(r){return this.logger.warn(`[CustomMCP] \u83B7\u53D6\u7F13\u5B58\u5931\u8D25: ${r}`),null}}async callToolByType(e,t){switch(e.handler.type){case"proxy":return await this.callProxyTool(e,t);case"function":return await this.callFunctionTool(e,t);case"http":return await this.callHttpTool(e,t);case"script":return await this.callScriptTool(e,t);case"chain":return await this.callChainTool(e,t);case"mcp":try{return await this.forwardToMCPServiceManager(e,t)}catch(r){this.logger.error(`[CustomMCP] MCP \u7C7B\u578B\u5DE5\u5177\u8DEF\u7531\u5931\u8D25: ${e.name}`,r);let o=r instanceof Error?r.message:"MCP \u7C7B\u578B\u5DE5\u5177\u8DEF\u7531\u9519\u8BEF";return{content:[{type:"text",text:o.includes("MCPServiceManager \u672A\u521D\u59CB\u5316")?o:"\u5185\u90E8\u9519\u8BEF\uFF1AMCP \u7C7B\u578B\u5DE5\u5177\u8DEF\u7531\u9519\u8BEF"}],isError:!0}}default:throw new Error(`\u4E0D\u652F\u6301\u7684\u5904\u7406\u5668\u7C7B\u578B: ${e.handler.type}`)}}async forwardToMCPServiceManager(e,t){if(!this.mcpServiceManager)throw this.logger.error(`[CustomMCP] MCPServiceManager \u672A\u521D\u59CB\u5316\uFF0C\u65E0\u6CD5\u8F6C\u53D1\u5DE5\u5177 ${e.name} \u7684\u8C03\u7528`),new Error("MCPServiceManager \u672A\u521D\u59CB\u5316");let r=e.handler;this.logger.info(`[CustomMCP] \u8F6C\u53D1MCP\u5DE5\u5177\u8C03\u7528: ${e.name}`,{serviceName:r.config.serviceName,toolName:r.config.toolName});try{let o=await this.mcpServiceManager.callTool(r.config.toolName,t);return this.logger.info(`[CustomMCP] MCP\u5DE5\u5177\u8F6C\u53D1\u6210\u529F: ${e.name}`),o}catch(o){return this.logger.error(`[CustomMCP] MCP\u5DE5\u5177\u8F6C\u53D1\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`MCP\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async callProxyTool(e,t){let r=e.handler;if(this.logger.info(`[CustomMCP] \u8C03\u7528\u4EE3\u7406\u5DE5\u5177: ${e.name}`,{platform:r.platform,config:r.config}),r.platform==="coze")return await this.callCozeWorkflow(e,t);throw new Error(`\u4E0D\u652F\u6301\u7684\u4EE3\u7406\u5E73\u53F0: ${r.platform}`)}async callCozeWorkflow(e,t){let o=e.handler.config;this.logger.info(`[CustomMCP] \u8C03\u7528 Coze \u5DE5\u4F5C\u6D41: ${e.name}`,{workflow_id:o.workflow_id,bot_id:o.bot_id});try{let n=this.buildCozeRequest(o,t),s=await this.sendCozeRequest(o,n);return this.logger.info(`[CustomMCP] Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u6210\u529F: ${e.name}`,{response:s}),this.processCozeResponse(e.name,s)}catch(n){return this.logger.error(`[CustomMCP] Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}buildCozeRequest(e,t){return{workflow_id:e.workflow_id,parameters:{...t}}}async sendCozeRequest(e,t){let r=e.base_url||"https://api.coze.cn",o="",n=u.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,p=setTimeout(()=>h.abort(),a);try{let d=await fetch(s,{method:"POST",headers:l,body:JSON.stringify(t)});if(clearTimeout(p),!d.ok){let E=await d.text();throw new Error(`Coze API \u8BF7\u6C42\u5931\u8D25 (${d.status}): ${E}`)}let C=await d.json();return this.logger.debug("[CustomMCP] Coze API \u54CD\u5E94:",C),C}catch(d){throw clearTimeout(p),d instanceof Error&&d.name==="AbortError"?new Error(`Coze API \u8BF7\u6C42\u8D85\u65F6 (${a}ms)`):d}}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[p,d]of Object.entries(t))d!=null&&l.append(p,String(d));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,p=setTimeout(()=>h.abort(),o),d=await fetch(e,{...t,signal:h.signal});if(clearTimeout(p),d.ok||l===n)return d;this.logger.warn(`[CustomMCP] HTTP \u8BF7\u6C42\u5931\u8D25 (${d.status}), \u5C06\u5728 ${s}ms \u540E\u91CD\u8BD5`),a=new Error(`HTTP \u8BF7\u6C42\u5931\u8D25: ${d.status} ${d.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",p,d=!1;try{if(e.script.includes(`
37
- `)||e.script.length>200){let R=await n.mkdtemp(s.join(a.tmpdir(),"xiaozhi-script-")),J=this.getScriptExtension(h);p=s.join(R,`script${J}`),await n.writeFile(p,e.script,"utf8"),d=!0}else{p=e.script;try{await n.access(p)}catch{throw new Error(`\u811A\u672C\u6587\u4EF6\u4E0D\u5B58\u5728: ${p}`)}}let C={...process.env,...e.env,XIAOZHI_ARGUMENTS:JSON.stringify(t)},E=this.buildScriptCommand(h,p);return this.logger.debug(`[CustomMCP] \u6267\u884C\u811A\u672C\u547D\u4EE4: ${E.join(" ")}`),new Promise((R,J)=>{let V=r(E[0],E.slice(1),{env:C,stdio:["pipe","pipe","pipe"]}),it="",A="";V.stdout?.on("data",re=>{it+=re.toString()}),V.stderr?.on("data",re=>{A+=re.toString()});let at=setTimeout(()=>{V.kill("SIGTERM"),J(new Error(`\u811A\u672C\u6267\u884C\u8D85\u65F6 (${l}ms)`))},l);V.on("close",re=>{clearTimeout(at),re===0?R(it.trim()):J(new Error(`\u811A\u672C\u6267\u884C\u5931\u8D25 (\u9000\u51FA\u7801: ${re}): ${A.trim()}`))}),V.on("error",re=>{clearTimeout(at),J(new Error(`\u811A\u672C\u6267\u884C\u9519\u8BEF: ${re.message}`))}),t&&Object.keys(t).length>0&&(V.stdin?.write(JSON.stringify(t)),V.stdin?.end())})}finally{if(d&&p)try{await n.unlink(p),await n.rmdir(s.dirname(p))}catch{}}}getScriptExtension(e){switch(e){case"node":return".js";case"python":return".py";case"bash":return".sh";default:return".txt"}}buildScriptCommand(e,t){switch(e){case"node":return["node",t];case"python":return["python3",t];case"bash":return["bash",t];default:throw new Error(`\u4E0D\u652F\u6301\u7684\u811A\u672C\u89E3\u91CA\u5668: ${e}`)}}async callChainTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528\u94FE\u5F0F\u5DE5\u5177: ${e.name}`,{tools:r.tools,mode:r.mode,error_handling:r.error_handling});try{let o;r.mode==="sequential"?o=await this.executeSequentialChain(r,t):o=await this.executeParallelChain(r,t);let n=o.flatMap(a=>a.content),s=o.some(a=>a.isError);return{content:n,isError:s}}catch(o){return this.logger.error(`[CustomMCP] \u94FE\u5F0F\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`\u94FE\u5F0F\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}delay(e){return new Promise(t=>setTimeout(t,e))}getToolInfo(e){return this.tools.get(e)}async executeSequentialChain(e,t){let r=[],o=t;for(let n of e.tools)try{this.logger.debug(`[CustomMCP] \u6267\u884C\u94FE\u5F0F\u5DE5\u5177\u4E2D\u7684: ${n}`);let s=await this.callToolRecursive(n,o);if(r.push(s),s.isError){if(e.error_handling==="stop")break;if(e.error_handling==="retry"){this.logger.warn(`[CustomMCP] \u5DE5\u5177 ${n} \u6267\u884C\u5931\u8D25\uFF0C\u5C1D\u8BD5\u91CD\u8BD5`);let a=await this.callToolRecursive(n,o);if(r[r.length-1]=a,a.isError)break}}if(!s.isError&&s.content.length>0){let a=s.content.filter(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];Ee(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||{}))Ee(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 Ce(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 Hn}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as jn}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as zn}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{EventSource as Un}from"eventsource";function Fn(){return g}function Wn(i){switch(Fn().info(`[TransportFactory] \u521B\u5EFA ${i.type} transport for ${i.name}`),i.type){case"stdio":return Vn(i);case"sse":return Bn(i);case"streamable-http":return Gn(i);default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function Vn(i){if(!i.command)throw new Error("stdio transport \u9700\u8981 command \u914D\u7F6E");return new jn({command:i.command,args:i.args||[],env:i.env})}function Bn(i){if(!i.url)throw new Error("SSE transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=qn(i);return new Hn(e,t)}function Gn(i){if(!i.url)throw new Error("StreamableHTTP transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=Jn(i);return new zn(e,t)}function qn(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function Jn(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function Xn(i){if(!i.name||typeof i.name!="string")throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(i.type&&!Object.values(_e).includes(i.type))throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`);if(!i.type)throw new Error("\u4F20\u8F93\u7C7B\u578B\u672A\u8BBE\u7F6E\uFF0C\u8FD9\u5E94\u8BE5\u5728 inferTransportType \u4E2D\u5904\u7406");switch(i.type){case"stdio":if(!i.command)throw new Error("stdio \u7C7B\u578B\u9700\u8981 command \u5B57\u6BB5");break;case"sse":if(i.url===void 0||i.url===null)throw new Error(`${i.type} \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5`);break;case"streamable-http":if(i.url===void 0||i.url===null)throw new Error(`${i.type} \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5`);break;default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function Kn(){return["stdio","sse","streamable-http"]}var dr,ho=m(()=>{"use strict";y();Mt();typeof global<"u"&&!global.EventSource&&(global.EventSource=Un);c(Fn,"getLogger");c(Wn,"createTransport");c(Vn,"createStdioTransport");c(Bn,"createSSETransport");c(Gn,"createStreamableHTTPTransport");c(qn,"createSSEOptions");c(Jn,"createStreamableHTTPOptions");c(Xn,"validateConfig");c(Kn,"getSupportedTypes");dr={create:Wn,validateConfig:Xn,getSupportedTypes:Kn}});import{Client as Zn}from"@modelcontextprotocol/sdk/client/index.js";var _e,Pt,Mt=m(()=>{"use strict";y();K();ho();_e=(r=>(r.STDIO="stdio",r.SSE="sse",r.STREAMABLE_HTTP="streamable-http",r))(_e||{}),Pt=class{static{c(this,"MCPService")}config;client=null;transport=null;tools=new Map;connectionState="disconnected";reconnectOptions;reconnectState;logger;connectionTimeout=null;initialized=!1;eventBus=I();pingOptions;pingTimer=null;pingFailureCount=0;lastPingTime=null;isPinging=!1;constructor(e,t){this.logger=g;let r=this.inferTransportType(e);this.config=r,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)}inferTransportType(e){if(e.type)return e;this.logger.debug(`[MCP-${e.name}] \u81EA\u52A8\u63A8\u65AD\u4F20\u8F93\u7C7B\u578B...`);let t;if(e.command)t="stdio",this.logger.debug(`[MCP-${e.name}] \u68C0\u6D4B\u5230 command \u5B57\u6BB5\uFF0C\u63A8\u65AD\u4E3A stdio \u7C7B\u578B`);else if(e.url!==void 0&&e.url!==null)t=this.inferTransportTypeFromUrl(e.url,e.name);else throw new Error(`\u65E0\u6CD5\u4E3A\u670D\u52A1 ${e.name} \u63A8\u65AD\u4F20\u8F93\u7C7B\u578B\u3002\u8BF7\u663E\u5F0F\u6307\u5B9A type \u5B57\u6BB5\uFF0C\u6216\u63D0\u4F9B command/url \u914D\u7F6E`);return{type:t,...e}}inferTransportTypeFromUrl(e,t){try{let o=new URL(e).pathname;return o.endsWith("/sse")?(this.logger.info(`[MCP-${t}] \u68C0\u6D4B\u5230 URL \u8DEF\u5F84\u4EE5 /sse \u7ED3\u5C3E\uFF0C\u63A8\u65AD\u4E3A sse \u7C7B\u578B`),"sse"):o.endsWith("/mcp")?(this.logger.info(`[MCP-${t}] \u68C0\u6D4B\u5230 URL \u8DEF\u5F84\u4EE5 /mcp \u7ED3\u5C3E\uFF0C\u63A8\u65AD\u4E3A streamable-http \u7C7B\u578B`),"streamable-http"):(this.logger.info(`[MCP-${t}] URL \u8DEF\u5F84 ${o} \u4E0D\u5339\u914D\u7279\u5B9A\u89C4\u5219\uFF0C\u9ED8\u8BA4\u63A8\u65AD\u4E3A streamable-http \u7C7B\u578B`),"streamable-http")}catch(r){return this.logger.warn(`[MCP-${t}] URL \u89E3\u6790\u5931\u8D25\uFF0C\u9ED8\u8BA4\u63A8\u65AD\u4E3A streamable-http \u7C7B\u578B`,r),"streamable-http"}}validateConfig(){dr.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 Zn({name:`xiaozhi-${this.config.name}-client`,version:"1.0.0"},{capabilities:{tools:{}}}),this.transport=dr.create(this.config),this.client.connect(this.transport).then(async()=>{this.handleConnectionSuccess(),await this.refreshTools(),this.eventBus.emitEvent("mcp:service:connected",{serviceName:this.config.name,tools:this.getTools(),connectionTime:new Date}),e()}).catch(r=>{this.handleConnectionError(r),t(r)})}catch(r){this.handleConnectionError(r),t(r)}})}handleConnectionSuccess(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.connectionState="connected",this.initialized=!0,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.connectionState="disconnected",this.initialized=!1,this.reconnectState.lastError=e,this.logger.error(`MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5\u9519\u8BEF:`,e.message),this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.cleanupConnection(),this.eventBus.emitEvent("mcp:service:connection:failed",{serviceName:this.config.name,error:e,attempt:this.reconnectState.attempts}),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",this.eventBus.emitEvent("mcp:service:disconnected",{serviceName:this.config.name,reason:"\u624B\u52A8\u65AD\u5F00",disconnectionTime:new Date})}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 wt,uo=m(()=>{"use strict";y();K();wt=class{static{c(this,"ToolSyncManager")}configManager;logger;syncLocks=new Map;eventBus=I();constructor(e,t=g){this.configManager=e,this.logger=t.withTag("ToolSync"),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("config:updated",async e=>{await this.handleConfigUpdated(e)})}async handleConfigUpdated(e){this.logger.info("\u68C0\u6D4B\u5230\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u5DE5\u5177\u540C\u6B65\u72B6\u6001");try{e.type==="customMCP"?this.logger.debug("customMCP\u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0CCustomMCPHandler\u5C06\u81EA\u52A8\u5904\u7406"):e.type==="serverTools"&&e.serviceName?await this.handleServerToolsConfigUpdated(e.serviceName):await this.handleGeneralConfigUpdated()}catch(t){this.logger.error("\u914D\u7F6E\u66F4\u65B0\u540E\u7684\u5DE5\u5177\u540C\u6B65\u5931\u8D25:",t)}}async handleServerToolsConfigUpdated(e){this.logger.info(`\u5904\u7406\u670D\u52A1 ${e} \u7684serverTools\u914D\u7F6E\u66F4\u65B0`);try{this.eventBus.emitEvent("tool-sync:server-tools-updated",{serviceName:e,timestamp:new Date})}catch(t){this.logger.error(`\u5904\u7406\u670D\u52A1 ${e} \u914D\u7F6E\u66F4\u65B0\u5931\u8D25:`,t)}}async handleGeneralConfigUpdated(){this.logger.info("\u5904\u7406\u901A\u7528\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u6240\u6709\u670D\u52A1\u540C\u6B65\u72B6\u6001");try{this.eventBus.emitEvent("tool-sync:general-config-updated",{timestamp:new Date})}catch(e){this.logger.error("\u5904\u7406\u901A\u7528\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",e)}}async 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 p={};h.usageCount!==void 0&&(p.usageCount=h.usageCount),h.lastUsedTime&&(p.lastUsedTime=h.lastUsedTime),Object.keys(p).length>0&&(await this.updateCustomMCPToolStats(a,p),this.logger.debug(`\u5DF2\u540C\u6B65\u5DE5\u5177 ${a} \u7684\u7EDF\u8BA1\u4FE1\u606F: ${JSON.stringify(p)}`))}}}catch(r){this.logger.error(`\u540C\u6B65\u670D\u52A1 ${e} \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,r instanceof Error?r.message:String(r))}}async updateCustomMCPToolStats(e,t){try{let r=this.configManager.getCustomMCPTools(),o=r.findIndex(a=>a.name===e);if(o===-1){this.logger.warn(`\u5DE5\u5177 ${e} \u4E0D\u5B58\u5728\u4E8E customMCP \u4E2D`);return}let n=[...r],s=n[o];s.stats||(s.stats={}),t.usageCount!==void 0&&(s.stats.usageCount=t.usageCount),t.lastUsedTime!==void 0&&(s.stats.lastUsedTime=t.lastUsedTime),await this.configManager.updateCustomMCPTools(n)}catch(r){throw this.logger.error(`\u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,r instanceof Error?r.message:String(r)),r}}}});var rt,po,mr=m(()=>{"use strict";y();Z();go();K();Tt();Mt();uo();rt=class{static{c(this,"MCPServiceManager")}services=new Map;configs={};logger;tools=new Map;customMCPHandler;cacheManager;toolSyncManager;eventBus=I();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 pe(r),this.customMCPHandler=new Et,this.toolSyncManager=new wt(u,this.logger),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("mcp:service:connected",async e=>{await this.handleServiceConnected(e)}),this.eventBus.onEvent("mcp:service:disconnected",async e=>{await this.handleServiceDisconnected(e)}),this.eventBus.onEvent("mcp:service:connection:failed",async e=>{await this.handleServiceConnectionFailed(e)}),this.eventBus.onEvent("tool-sync:server-tools-updated",async e=>{await this.handleServerToolsUpdated(e)}),this.eventBus.onEvent("tool-sync:general-config-updated",async e=>{await this.handleGeneralConfigUpdated(e)})}async handleServiceConnected(e){this.logger.info(`\u670D\u52A1 ${e.serviceName} \u8FDE\u63A5\u6210\u529F\uFF0C\u5F00\u59CB\u5DE5\u5177\u540C\u6B65`);try{let t=this.services.get(e.serviceName);if(t){let r=t.getTools();this.toolSyncManager&&await this.toolSyncManager.syncToolsAfterConnection(e.serviceName,r),await this.refreshCustomMCPHandlerPublic(),this.logger.info(`\u670D\u52A1 ${e.serviceName} \u5DE5\u5177\u540C\u6B65\u5B8C\u6210`)}}catch(t){this.logger.error(`\u540C\u6B65\u670D\u52A1 ${e.serviceName} \u5DE5\u5177\u5931\u8D25:`,t)}}async handleServiceDisconnected(e){this.logger.info(`\u670D\u52A1 ${e.serviceName} \u65AD\u5F00\u8FDE\u63A5\uFF0C\u539F\u56E0: ${e.reason||"\u672A\u77E5"}`);try{await this.refreshToolsCache(),await this.refreshCustomMCPHandlerPublic(),this.logger.info(`\u670D\u52A1 ${e.serviceName} \u65AD\u5F00\u8FDE\u63A5\u5904\u7406\u5B8C\u6210`)}catch(t){this.logger.error(`\u670D\u52A1 ${e.serviceName} \u65AD\u5F00\u8FDE\u63A5\u5904\u7406\u5931\u8D25:`,t)}}async handleServiceConnectionFailed(e){this.logger.warn(`\u670D\u52A1 ${e.serviceName} \u8FDE\u63A5\u5931\u8D25 (\u5C1D\u8BD5 ${e.attempt})\uFF0C\u9519\u8BEF: ${e.error.message}`);try{await this.refreshCustomMCPHandlerPublic()}catch(t){this.logger.error("\u5237\u65B0CustomMCPHandler\u5931\u8D25:",t)}}async handleServerToolsUpdated(e){this.logger.info(`\u5904\u7406\u670D\u52A1 ${e.serviceName} \u7684serverTools\u914D\u7F6E\u66F4\u65B0`);try{let t=this.services.get(e.serviceName);if(t?.isConnected()){let r=t.getTools();this.toolSyncManager&&await this.toolSyncManager.syncToolsAfterConnection(e.serviceName,r),await this.refreshCustomMCPHandlerPublic(),this.logger.info(`\u670D\u52A1 ${e.serviceName} \u914D\u7F6E\u66F4\u65B0\u540C\u6B65\u5B8C\u6210`)}}catch(t){this.logger.error(`\u5904\u7406\u670D\u52A1 ${e.serviceName} \u914D\u7F6E\u66F4\u65B0\u5931\u8D25:`,t)}}async handleGeneralConfigUpdated(e){this.logger.info("\u5904\u7406\u901A\u7528\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u6240\u6709\u5DF2\u8FDE\u63A5\u670D\u52A1");try{for(let[t,r]of this.services)if(r.isConnected()){let o=r.getTools();this.toolSyncManager&&await this.toolSyncManager.syncToolsAfterConnection(t,o)}await this.refreshCustomMCPHandlerPublic(),this.logger.info("\u901A\u7528\u914D\u7F6E\u66F4\u65B0\u540C\u6B65\u5B8C\u6210")}catch(t){this.logger.error("\u5904\u7406\u901A\u7528\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",t)}}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 Pt(t);await r.connect(),this.services.set(e,r),await this.refreshToolsCache();let o=r.getTools();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=[];for(let[r,o]of this.services)if(o.isConnected()){let n=o.getTools();for(let s of n){if(!u.isToolEnabled(r,s.name))continue;let l=`${r}__${s.name}`;e.push({name:l,description:s.description||"",inputSchema:s.inputSchema,serviceName:r,originalName:s.name})}}let t=[];try{t=this.customMCPHandler.getTools(),this.logger.debug(`[MCPManager] \u6210\u529F\u83B7\u53D6 ${t.length} \u4E2A customMCP \u5DE5\u5177`)}catch(r){this.logger.warn("[MCPManager] \u83B7\u53D6 CustomMCP \u5DE5\u5177\u5931\u8D25\uFF0C\u5C06\u53EA\u8FD4\u56DE\u6807\u51C6 MCP \u5DE5\u5177:",r),t=[]}for(let r of t)e.push({name:r.name,description:r.description||"",inputSchema:r.inputSchema,serviceName:this.getServiceNameForTool(r),originalName:r.name});return this.logger.info(`[MCPManager] \u8FD4\u56DE ${e.length} \u4E2A\u5DE5\u5177 (\u670D\u52A1\u5DE5\u5177: ${e.length-t.length}, customMCP\u5DE5\u5177: ${t.length})`),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 u.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 u.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 u.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 u.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{u.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=0,t=[];try{e=this.customMCPHandler.getToolCount(),t=this.customMCPHandler.getToolNames(),this.logger.debug(`[MCPManager] \u6210\u529F\u83B7\u53D6 customMCP \u72B6\u6001: ${e} \u4E2A\u5DE5\u5177`)}catch(a){this.logger.warn("[MCPManager] \u83B7\u53D6 CustomMCP \u72B6\u6001\u5931\u8D25\uFF0C\u5C06\u53EA\u5305\u542B\u6807\u51C6 MCP \u5DE5\u5177:",a),e=0,t=[]}let r=this.tools.size+e,n=[...Array.from(this.tools.keys()),...t],s={services:{},totalTools:r,availableTools:n};for(let[a,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=u.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)}getConnectedServices(){let e=[];for(let[t,r]of this.services)r.isConnected()&&e.push(t);return e}async refreshCustomMCPHandler(){try{this.logger.info("\u91CD\u65B0\u521D\u59CB\u5316CustomMCPHandler"),await this.customMCPHandler.reinitialize(),this.logger.info("CustomMCPHandler\u91CD\u65B0\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw this.logger.error("CustomMCPHandler\u91CD\u65B0\u521D\u59CB\u5316\u5931\u8D25:",e),e}}async refreshCustomMCPHandlerPublic(){return this.refreshCustomMCPHandler()}getAllServices(){return new Map(this.services)}getCustomMCPHandler(){return this.customMCPHandler}hasCustomMCPTool(e){try{return this.customMCPHandler.hasTool(e)}catch(t){return this.logger.warn(`[MCPManager] \u68C0\u67E5 CustomMCP \u5DE5\u5177 ${e} \u662F\u5426\u5B58\u5728\u5931\u8D25:`,t),!1}}getCustomMCPTools(){try{return this.customMCPHandler.getTools()}catch(e){return this.logger.warn("[MCPManager] \u83B7\u53D6 CustomMCP \u5DE5\u5177\u5217\u8868\u5931\u8D25\uFF0C\u8FD4\u56DE\u7A7A\u6570\u7EC4:",e),[]}}enhanceServiceConfig(e){let t={...e};try{if(e.type==="sse"&&e.url&&e.url.includes("modelscope")){let r=u.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=u.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 d of o){let C=n[d.name];C?s[d.name]={...C,description:d.description||C.description||""}:s[d.name]={description:d.description||"",enable:!0}}let a=o.map(d=>d.name),h=Object.keys(n).filter(d=>!a.includes(d));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)){u.updateServerToolsConfig(t,s);let d=Object.keys(s).filter(E=>!n[E]),C=Object.keys(s).filter(E=>{let R=n[E],J=s[E];return R&&R.description!==J.description});this.logger.info(`[MCPManager] \u5DF2\u540C\u6B65\u670D\u52A1 ${t} \u7684\u5DE5\u5177\u914D\u7F6E:`),d.length>0&&this.logger.info(` - \u65B0\u589E\u5DE5\u5177: ${d.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}},po=rt});var Le,fr=m(()=>{"use strict";y();Le=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 mo}from"events";var Cr,vr,bt,fo=m(()=>{"use strict";y();mr();Qe();fr();Cr=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}},vr=class extends mo{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")}},bt=class extends mo{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 rt,this.messageHandler=new Le(this.serviceManager),this.toolRegistry=new Cr(this.serviceManager),this.connectionManager=new vr,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 Co(i={name:"http"}){g.info("\u521B\u5EFA HTTP \u6A21\u5F0F\u670D\u52A1\u5668");let e=new bt;await e.initialize();let t=e.getMessageHandler(),r=new Ct(t,i);return await e.registerTransport("http",r),g.info("HTTP \u6A21\u5F0F\u670D\u52A1\u5668\u521B\u5EFA\u6210\u529F"),e}var vo=m(()=>{"use strict";y();Qr();eo();to();fo();c(Co,"createHTTPServer")});var So={};B(So,{MCPServer:()=>Sr});import{EventEmitter as Yn}from"events";var L,Sr,yo=m(()=>{"use strict";y();ft();Z();vo();L=new qe,Sr=class extends Yn{static{c(this,"MCPServer")}unifiedServer=null;proxyMCPServer=null;port;isStarted=!1;constructor(e=3e3){super(),this.port=e}async initializeUnifiedServer(){if(!this.unifiedServer){L.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 Co(e),this.unifiedServer.on("started",()=>this.emit("started")),this.unifiedServer.on("stopped",()=>this.emit("stopped")),this.unifiedServer.on("connectionRegistered",t=>{this.emit("connectionRegistered",t)}),L.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw L.error("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u5931\u8D25",e),e}}}async initializeMCPClient(){try{let e=null;try{u.configExists()&&(e=u.getMcpEndpoints().find(r=>r&&!r.includes("<\u8BF7\u586B\u5199"))||null)}catch(t){L.warn("\u4ECE\u914D\u7F6E\u4E2D\u8BFB\u53D6\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25:",t)}e?(this.proxyMCPServer=new fe(e),this.unifiedServer&&this.proxyMCPServer.setServiceManager(this.unifiedServer.getServiceManager()),await this.proxyMCPServer.connect(),L.info("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F")):L.info("\u672A\u914D\u7F6E\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u8DF3\u8FC7\u8FDE\u63A5")}catch(e){L.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}}async start(){if(this.isStarted){L.warn("\u670D\u52A1\u5668\u5DF2\u542F\u52A8");return}try{L.info("\u542F\u52A8 MCP \u670D\u52A1\u5668"),await this.initializeUnifiedServer(),this.unifiedServer&&await this.unifiedServer.start(),this.initializeMCPClient().catch(e=>{L.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}),this.isStarted=!0,this.emit("started"),L.info("MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F")}catch(e){throw L.error("\u542F\u52A8 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}async stop(){if(!this.isStarted){L.warn("\u670D\u52A1\u5668\u672A\u542F\u52A8");return}try{L.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"),L.info("MCP \u670D\u52A1\u5668\u5DF2\u505C\u6B62")}catch(e){throw L.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 Qn,resolve as es}from"path";function Mo(i){try{let t=new URL(i).pathname;return t.endsWith("/sse")?"sse":t.endsWith("/mcp")?"streamable-http":"streamable-http"}catch(e){return He.warn(`URL \u89E3\u6790\u5931\u8D25\uFF0C\u9ED8\u8BA4\u63A8\u65AD\u4E3A streamable-http \u7C7B\u578B: ${i}`,e),"streamable-http"}}function Po(i,e){He.debug(`\u8F6C\u6362\u914D\u7F6E: ${i}`,e);try{if(!i||typeof i!="string")throw new O("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!e||typeof e!="object")throw new O("\u914D\u7F6E\u5BF9\u8C61\u4E0D\u80FD\u4E3A\u7A7A",i);let t=ts(i,e);return is(t),He.info(`\u914D\u7F6E\u8F6C\u6362\u6210\u529F: ${i} -> ${t.type}`),t}catch(t){throw He.error(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${i}`,t),t instanceof O?t:new O(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,i)}}function ts(i,e){if(ns(e))return rs(i,e);if("type"in e)switch(e.type){case"sse":return To(i,e);case"streamable-http":return Eo(i,e);default:throw new O(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${e.type}`,i)}if("url"in e){if(e.url===void 0||e.url===null)throw new O("\u7F51\u7EDC\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 url \u5B57\u6BB5",i);if(Mo(e.url||"")==="sse"){let o={...e,type:"sse"};return To(i,o)}let r={...e,type:"streamable-http"};return Eo(i,r)}throw new O("\u65E0\u6CD5\u8BC6\u522B\u7684\u914D\u7F6E\u7C7B\u578B",i)}function rs(i,e){if(!e.command)throw new O("\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(os(o)){let n=es(t,o);return He.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 To(i,e){if(e.url===void 0||e.url===null)throw new O("SSE \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);let t=e.type==="sse"?"sse":Mo(e.url||""),r=e.url?ss(e.url):!1,o={name:i,type:t,url:e.url,reconnect:{enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:15e3,jitter:!0},ping:t==="sse"?{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3}:{enabled:!1,interval:6e4,timeout:1e4,maxFailures:3,startDelay:1e4},timeout:3e4};return r&&(o.modelScopeAuth=!0),He.info(`[ConfigAdapter] \u670D\u52A1 ${i} URL: ${e.url}\uFF0C\u63A8\u65AD\u7C7B\u578B: ${t}${r?" (ModelScope)":""}`),o}function Eo(i,e){if(e.url===void 0||e.url===null)throw new O("STREAMABLE_HTTP \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);let t=e.url||"";return{name:i,type:"streamable-http",url:t,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 os(i){return Qn(i)?!1:!!(i.startsWith("./")||i.startsWith("../")||/\.(js|py|ts|mjs|cjs)$/i.test(i))}function ns(i){return"command"in i&&typeof i.command=="string"}function ss(i){return i.includes("modelscope.net")||i.includes("modelscope.cn")}function is(i){if(!i.name||typeof i.name!="string")throw new O("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(i.type&&!Object.values(_e).includes(i.type))throw new O(`\u65E0\u6548\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`);if(!i.type)throw new O("\u4F20\u8F93\u7C7B\u578B\u672A\u6307\u5B9A\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E\u6216\u542F\u7528\u81EA\u52A8\u63A8\u65AD");switch(i.type){case"stdio":if(!i.command)throw new O("STDIO \u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5");break;case"sse":if(i.url===void 0||i.url===null)throw new O("SSE \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5");break;case"streamable-http":if(i.url===void 0||i.url===null)throw new O("STREAMABLE_HTTP \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5");break;default:throw new O(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}var He,O,wo=m(()=>{"use strict";y();Mt();He=g.withTag("ConfigAdapter");c(Mo,"inferTransportTypeFromUrl");O=class extends Error{constructor(t,r){super(t);this.configName=r;this.name="ConfigValidationError"}static{c(this,"ConfigValidationError")}};c(Po,"convertLegacyToNew");c(ts,"convertByConfigType");c(rs,"convertLocalConfig");c(To,"convertSSEConfig");c(Eo,"convertStreamableHTTPConfig");c(os,"isRelativePath");c(ns,"isLocalConfig");c(ss,"isModelScopeURL");c(is,"validateNewConfig")});async function as(){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),new po}async function bo(){if(ce&&U==="initialized")return ce;if(te&&U==="initializing")return te;U==="failed"&&yr(),U="initializing",te=as();try{return ce=await te,U="initialized",je=`mcp-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,ot=null,console.log(`\u2705 MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${je}`),ce}catch(i){throw U="failed",ot=i,te=null,console.error("\u274C MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",i.message),i}}async function Ro(){if(U==="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..."),U="cleanup";try{if(te){try{await(await te).stopAllServices()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}te=null}ce&&(await ce.stopAllServices(),ce=null),U="not_initialized",ot=null,je=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),yr(),i}}function yr(){console.log("\u{1F504} \u91CD\u7F6E MCPServiceManager \u5355\u4F8B\u72B6\u6001"),ce=null,te=null,U="not_initialized",ot=null,je=null}function cs(){return U==="initialized"&&ce!==null}function ls(){return{state:U,initializationTime:je?new Date:void 0,lastError:ot||void 0,instanceId:je||void 0}}async function gs(){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),await Ro(),bo()}function hs(){return ce}async function us(){if(U==="initialized")return!0;if(U==="initializing"&&te)try{return await te,!0}catch{return!1}return!1}var ce,te,U,ot,je,q,Rt=m(()=>{"use strict";mr();ce=null,te=null,U="not_initialized",ot=null,je=null;c(as,"createInstance");c(bo,"getInstance");c(Ro,"cleanup");c(yr,"reset");c(cs,"isInitialized");c(ls,"getStatus");c(gs,"forceReinitialize");c(hs,"getCurrentInstance");c(us,"waitForInitialization");q={getInstance:bo,cleanup:Ro,reset:yr,isInitialized:cs,getStatus:ls,forceReinitialize:gs,getCurrentInstance:hs,waitForInitialization:us};process.on("exit",()=>{q.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B..."),q.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 q.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 q.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as ps}from"events";import{z as ze}from"zod";var ds,ms,It,Io=m(()=>{"use strict";y();ft();lt();ds={reconnectInterval:5e3,maxReconnectAttempts:3,connectionTimeout:1e4,errorRecoveryEnabled:!0,errorNotificationEnabled:!0},ms=ze.object({reconnectInterval:ze.number().min(100,"reconnectInterval \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 100 \u7684\u6570\u5B57").optional(),maxReconnectAttempts:ze.number().min(0,"maxReconnectAttempts \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 0 \u7684\u6570\u5B57").optional(),connectionTimeout:ze.number().min(1e3,"connectionTimeout \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57").optional(),errorRecoveryEnabled:ze.boolean().optional(),errorNotificationEnabled:ze.boolean().optional()}).strict(),It=class extends ps{static{c(this,"IndependentXiaozhiConnectionManager")}connections=new Map;connectionStates=new Map;mcpServiceManager=null;logger;isInitialized=!1;isConnecting=!1;options;reconnectTimers=new Map;constructor(e){super(),this.logger=g,this.options={...ds,...e},this.logger.debug("[IndependentXiaozhiConnectionManager] \u5B9E\u4F8B\u5DF2\u521B\u5EFA"),this.logger.debug("[IndependentXiaozhiConnectionManager] \u914D\u7F6E\u9009\u9879:",this.options)}async initialize(e,t){if(!this.isInitialized){this.logger.debug(`\u5F00\u59CB\u521D\u59CB\u5316 IndependentXiaozhiConnectionManager\uFF0C\u5C0F\u667A\u63A5\u5165\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.logger.debug(`IndependentXiaozhiConnectionManager \u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u7BA1\u7406 ${this.connections.size} \u4E2A\u8FDE\u63A5`)}catch(r){throw this.logger.error("IndependentXiaozhiConnectionManager \u521D\u59CB\u5316\u5931\u8D25:",r),await this.cleanup(),r}}}async connect(){if(!this.isInitialized)throw new Error("IndependentXiaozhiConnectionManager \u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 initialize()");if(!this.isConnecting){this.isConnecting=!0,this.logger.debug(`\u5F00\u59CB\u8FDE\u63A5\u6240\u6709\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u603B\u6570: ${this.connections.size}`);try{let e=[];for(let[n,s]of this.connections)e.push(this.connectSingleEndpoint(n,s));let t=await Promise.allSettled(e),r=t.filter(n=>n.status==="fulfilled").length,o=t.length-r;if(this.logger.info(`\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5B8C\u6210 - \u6210\u529F: ${r}, \u5931\u8D25: ${o}`),r===0)throw new Error("\u6240\u6709\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25")}finally{this.isConnecting=!1}}}async disconnect(){this.logger.debug("\u5F00\u59CB\u65AD\u5F00\u6240\u6709\u8FDE\u63A5"),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\u5C0F\u667A\u63A5\u5165\u70B9\u5DF2\u65AD\u5F00\u8FDE\u63A5")}async addEndpoint(e){if(!this.isInitialized)throw new Error("IndependentXiaozhiConnectionManager \u672A\u521D\u59CB\u5316");if(this.connections.has(e)){this.logger.debug(`\u5C0F\u667A\u63A5\u5165\u70B9 ${v(e)} \u5DF2\u5B58\u5728\uFF0C\u8DF3\u8FC7\u6DFB\u52A0`);return}this.logger.debug(`\u52A8\u6001\u6DFB\u52A0\u5C0F\u667A\u63A5\u5165\u70B9: ${v(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(`\u6DFB\u52A0\u63A5\u5165\u70B9\u6210\u529F\uFF1A ${v(e)}`)}catch(t){throw this.logger.error(`\u6DFB\u52A0\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25\uFF1A ${v(e)}`,t),this.connections.delete(e),this.connectionStates.delete(e),t}}async removeEndpoint(e){if(!this.connections.has(e)){this.logger.debug(`\u5C0F\u667A\u63A5\u5165\u70B9 ${v(e)} \u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u79FB\u9664`);return}this.logger.debug(`\u52A8\u6001\u79FB\u9664\u5C0F\u667A\u63A5\u5165\u70B9: ${v(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(`\u79FB\u9664\u5C0F\u667A\u63A5\u5165\u70B9\u6210\u529F\uFF1A${v(e)}`)}catch(t){throw this.logger.error(`\u79FB\u9664\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25\uFF1A ${v(e)}`,t),t}}getEndpoints(){let e=Array.from(this.connections.keys()),t=Array.from(this.connectionStates.keys());return Array.from(new Set([...e,...t]))}async disconnectEndpoint(e){let t=this.connections.get(e);if(!t){this.logger.debug(`\u63A5\u5165\u70B9\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u65AD\u5F00: ${v(e)}`);return}this.logger.info(`\u65AD\u5F00\u8FDE\u63A5\u63A5\u5165\u70B9: ${v(e)}`);try{await this.disconnectSingleEndpoint(e,t)}catch(r){throw this.logger.error(`\u65AD\u5F00\u8FDE\u63A5\u63A5\u5165\u70B9\u5931\u8D25\uFF1A ${v(e)}`,r),r}}async clearEndpoints(){this.logger.debug("\u6E05\u9664\u6240\u6709\u63A5\u5165\u70B9");let e=Array.from(this.connections.keys()).map(t=>this.removeEndpoint(t));await Promise.allSettled(e),this.logger.info("\u6240\u6709\u63A5\u5165\u70B9\u5DF2\u6E05\u9664")}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.debug("\u5DF2\u8BBE\u7F6E MCPServiceManager"),this.connections.size>0&&this.syncToolsToAllConnections()}async triggerReconnect(e){let t=this.connectionStates.get(e);if(!t)throw new Error(`\u5C0F\u667A\u63A5\u5165\u70B9 ${e} \u4E0D\u5B58\u5728`);if(t.connected){this.logger.warn(`\u5C0F\u667A\u63A5\u5165\u70B9 ${v(e)} \u5DF2\u8FDE\u63A5\uFF0C\u65E0\u9700\u91CD\u8FDE`);return}this.logger.info(`\u624B\u52A8\u89E6\u53D1\u91CD\u8FDE: ${v(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(`\u5C0F\u667A\u63A5\u5165\u70B9 ${v(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\u5C0F\u667A\u63A5\u5165\u70B9 ${v(e)} \u7684\u91CD\u8FDE`))}stopAllReconnects(){this.logger.info("\u505C\u6B62\u6240\u6709\u5C0F\u667A\u63A5\u5165\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};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=ms.safeParse(e);return t.success?{valid:!0,errors:[]}:{valid:!1,errors:t.error.errors.map(o=>o.message)}}async updateEndpoints(e,t=[]){if(!this.isInitialized)throw new Error("IndependentXiaozhiConnectionManager \u672A\u521D\u59CB\u5316");this.logger.info(`\u66F4\u65B0\u5C0F\u667A\u63A5\u5165\u70B9\u914D\u7F6E\uFF0C\u65B0\u5C0F\u667A\u63A5\u5165\u70B9\u6570\u91CF: ${e.length}`);let{valid:r,invalid:o}=this.validateEndpoints(e);if(o.length>0&&this.logger.warn(`\u53D1\u73B0\u65E0\u6548\u5C0F\u667A\u63A5\u5165\u70B9: ${o.join(", ")}`),r.length===0)throw new Error("\u6CA1\u6709\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\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(`\u5C0F\u667A\u63A5\u5165\u70B9\u53D8\u66F4 - \u6DFB\u52A0: ${s.length}, \u79FB\u9664: ${a.length}, \u4FDD\u6301: ${l.length}`);try{for(let p of a)await this.removeEndpoint(p);for(let p of s)await this.addEndpoint(p);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("\u5C0F\u667A\u63A5\u5165\u70B9\u914D\u7F6E\u66F4\u65B0\u5B8C\u6210")}catch(h){throw this.logger.error("\u5C0F\u667A\u63A5\u5165\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}}async prewarmConnections(e=[]){let t=e.length>0?e:Array.from(this.connections.keys());this.logger.info(`\u5F00\u59CB\u9884\u70ED\u8FDE\u63A5\uFF0C\u5C0F\u667A\u63A5\u5165\u70B9\u6570\u91CF: ${t.length}`);let r=t.map(async o=>{try{this.connections.get(o)&&this.logger.debug(`\u5C0F\u667A\u63A5\u5165\u70B9 ${v(o)} \u9884\u70ED\u5B8C\u6210`)}catch(n){this.logger.warn(`\u5C0F\u667A\u63A5\u5165\u70B9 ${v(o)} \u9884\u70ED\u5931\u8D25:`,n)}});await Promise.all(r),this.logger.info("\u8FDE\u63A5\u9884\u70ED\u5B8C\u6210")}async cleanup(){this.logger.info("\u5F00\u59CB\u6E05\u7406 IndependentXiaozhiConnectionManager \u8D44\u6E90");try{await this.disconnect(),this.connections.clear(),this.connectionStates.clear(),this.isInitialized=!1,this.isConnecting=!1,this.logger.info("IndependentXiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(e){throw this.logger.error("IndependentXiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5931\u8D25:",e),e}}validateInitializeParams(e,t){if(!Array.isArray(e)||e.length===0)throw new Error("\u5C0F\u667A\u63A5\u5165\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\u5C0F\u667A\u63A5\u5165\u70B9\u5730\u5740: ${r}`);if(!r.startsWith("ws://")&&!r.startsWith("wss://"))throw new Error(`\u5C0F\u667A\u63A5\u5165\u70B9\u5730\u5740\u5FC5\u987B\u662F WebSocket URL: ${r}`)}}async createConnection(e,t){this.logger.debug(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B: ${v(e)}`);try{let r=new fe(e);this.mcpServiceManager&&r.setServiceManager(this.mcpServiceManager),this.connections.set(e,r),this.connectionStates.set(e,{endpoint:e,connected:!1,initialized:!1,isReconnecting:!1,lastReconnectAttempt:void 0,reconnectDelay:this.options.reconnectInterval,reconnectAttempts:0,nextReconnectTime:void 0}),this.logger.debug(`\u8FDE\u63A5\u5B9E\u4F8B\u521B\u5EFA\u6210\u529F: ${v(e)}`)}catch(r){throw this.logger.error(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B\u5931\u8D25 ${v(e)}:`,r),r}}async connectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(!r)throw new Error(`\u5C0F\u667A\u63A5\u5165\u70B9\u72B6\u6001\u4E0D\u5B58\u5728: ${v(e)}`);this.logger.debug(`\u8FDE\u63A5\u5C0F\u667A\u63A5\u5165\u70B9: ${v(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,this.logger.info(`\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F: ${v(e)}`)}catch(o){throw r.connected=!1,r.initialized=!1,r.lastError=o instanceof Error?o.message:String(o),r.reconnectAttempts++,this.logger.error(`\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25 ${v(e)}:`,o),this.scheduleReconnect(e),o}}async disconnectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(r){this.logger.debug(`\u65AD\u5F00\u5C0F\u667A\u63A5\u5165\u70B9: ${v(e)}`);try{t.disconnect(),r.connected=!1,r.initialized=!1,this.logger.debug(`\u5C0F\u667A\u63A5\u5165\u70B9\u65AD\u5F00\u6210\u529F: ${v(e)}`)}catch(o){this.logger.error(`\u5C0F\u667A\u63A5\u5165\u70B9\u65AD\u5F00\u5931\u8D25 ${v(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: ${v(e)}`)}catch(r){this.logger.error(`\u5DE5\u5177\u540C\u6B65\u5931\u8D25 ${v(e)}:`,r)}}}scheduleReconnect(e){let t=this.connectionStates.get(e);if(!t)return;if(t.reconnectAttempts>=this.options.maxReconnectAttempts){this.logger.warn(`\u505C\u6B62\u91CD\u8FDE ${v(e)}: \u8FBE\u5230\u6700\u5927\u91CD\u8FDE\u6B21\u6570`);return}let r=setTimeout(()=>{this.reconnectTimers.delete(e),this.performReconnect(e)},this.options.reconnectInterval);this.reconnectTimers.set(e,r)}async performReconnect(e){let t=this.connectionStates.get(e);if(!t)return;let r=this.connections.get(e);if(!r){this.logger.warn(`\u91CD\u8FDE\u65F6\u627E\u4E0D\u5230\u4EE3\u7406\u670D\u52A1\u5668: ${v(e)}`);return}try{t.isReconnecting=!0,t.lastReconnectAttempt=new Date;try{await r.disconnect()}catch(o){this.logger.debug(`\u65AD\u5F00\u8FDE\u63A5\u5931\u8D25\uFF08\u7EE7\u7EED\u91CD\u8FDE\uFF09: ${v(e)}:`,o)}await r.connect(),t.connected=!0,t.initialized=!0,t.lastConnected=new Date,t.lastError=void 0,t.reconnectAttempts=0,t.isReconnecting=!1,this.logger.info(`\u91CD\u8FDE\u6210\u529F ${v(e)}`)}catch(o){t.connected=!1,t.initialized=!1,t.lastError=o instanceof Error?o.message:String(o),t.reconnectAttempts++,t.isReconnecting=!1,this.logger.error(`\u91CD\u8FDE\u5931\u8D25 ${v(e)}:`,o),this.scheduleReconnect(e)}}clearAllReconnectTimers(){for(let[,e]of this.reconnectTimers)clearTimeout(e);this.reconnectTimers.clear()}}});async function fs(i){if(console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 IndependentXiaozhiConnectionManager \u5355\u4F8B..."),i){let r=["loadBalanceStrategy","reconnectStrategy","maxReconnectDelay","reconnectBackoffMultiplier","jitterEnabled"].filter(o=>o in i);r.length>0&&(console.warn(`\u26A0\uFE0F \u68C0\u6D4B\u5230\u5E9F\u5F03\u7684\u914D\u7F6E\u9009\u9879: ${r.join(", ")}`),console.warn("\u8FD9\u4E9B\u914D\u7F6E\u9879\u5728\u72EC\u7ACB\u67B6\u6784\u4E2D\u5DF2\u88AB\u5FFD\u7565\uFF0C\u5EFA\u8BAE\u4ECE\u914D\u7F6E\u4E2D\u79FB\u9664"))}return new It(i)}async function $o(i){if(le&&F==="initialized")return le;if(ee&&F==="initializing")return ee;F==="failed"&&Tr(),F="initializing",ee=fs(i);try{return le=await ee,F="initialized",Ue=`xiaozhi-connection-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,nt=null,console.log(`\u2705 IndependentXiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${Ue}`),le}catch(e){throw F="failed",nt=e,ee=null,console.error("\u274C IndependentXiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",e.message),e}}async function xo(){if(F==="cleanup"){console.log("\u26A0\uFE0F IndependentXiaozhiConnectionManager \u5355\u4F8B\u5DF2\u5728\u6E05\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u91CD\u590D\u6E05\u7406");return}console.log("\u{1F9F9} \u6B63\u5728\u6E05\u7406 IndependentXiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90..."),F="cleanup";try{if(ee){try{await(await ee).cleanup()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}ee=null}le&&(await le.cleanup(),le=null),F="not_initialized",nt=null,Ue=null,console.log("\u2705 IndependentXiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(i){throw console.error("\u274C IndependentXiaozhiConnectionManager \u5355\u4F8B\u6E05\u7406\u5931\u8D25:",i.message),Tr(),i}}function Tr(){console.log("\u{1F504} \u91CD\u7F6E IndependentXiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001..."),ee&&(ee=null),le=null,F="not_initialized",nt=null,Ue=null,console.log("\u2705 IndependentXiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001\u5DF2\u91CD\u7F6E")}function Cs(){return F==="initialized"&&le!==null}function vs(){return{state:F,initializationTime:Ue?new Date:void 0,lastError:nt||void 0,instanceId:Ue||void 0}}async function Ss(i){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 IndependentXiaozhiConnectionManager \u5355\u4F8B..."),await xo(),$o(i)}function ys(){return le}async function Ts(){if(F==="initialized")return!0;if(F==="initializing"&&ee)try{return await ee,!0}catch{return!1}return!1}var le,ee,F,nt,Ue,Fe,Oo=m(()=>{"use strict";Io();le=null,ee=null,F="not_initialized",nt=null,Ue=null;c(fs,"createInstance");c($o,"getInstance");c(xo,"cleanup");c(Tr,"reset");c(Cs,"isInitialized");c(vs,"getStatus");c(Ss,"forceReinitialize");c(ys,"getCurrentInstance");c(Ts,"waitForInitialization");Fe={getInstance:$o,cleanup:xo,reset:Tr,isInitialized:Cs,getStatus:vs,forceReinitialize:Ss,getCurrentInstance:ys,waitForInitialization:Ts};process.on("exit",()=>{Fe.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 IndependentXiaozhiConnectionManager \u5355\u4F8B..."),Fe.reset())});process.on("uncaughtException",async i=>{console.error("\u{1F4A5} \u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u6E05\u7406 IndependentXiaozhiConnectionManager \u5355\u4F8B:",i);try{await Fe.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 IndependentXiaozhiConnectionManager \u5355\u4F8B:",i);try{await Fe.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});var ge,st=m(()=>{"use strict";y();Z();K();ge=class{static{c(this,"ConfigService")}logger;eventBus;constructor(){this.logger=g.withTag("ConfigService"),this.eventBus=I()}async getConfig(){try{let e=u.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!==u.getMcpEndpoint()&&u.updateMcpEndpoint(e.mcpEndpoint);let r=u.getMcpServers();for(let[o,n]of Object.entries(e.mcpServers))JSON.stringify(r[o])!==JSON.stringify(n)&&u.updateMcpServer(o,n);for(let o of Object.keys(r))o in e.mcpServers||(u.removeMcpServer(o),u.removeServerToolsConfig(o));if(e.connection&&u.updateConnectionConfig(e.connection),e.modelscope&&u.updateModelScopeConfig(e.modelscope),e.webUI&&u.updateWebUIConfig(e.webUI),e.mcpServerConfig)for(let[o,n]of Object.entries(e.mcpServerConfig))for(let[s,a]of Object.entries(n.tools))u.setToolEnabled(o,s,a.enable);if(e?.platforms)for(let[o,n]of Object.entries(e.platforms))u.updatePlatformConfig(o,n);this.logger.info("\u914D\u7F6E\u66F4\u65B0\u6210\u529F"),this.eventBus.emitEvent("config:updated",{type:"config",timestamp:new Date})}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 u.getMcpEndpoint()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",e),e}}getMcpEndpoints(){try{return u.getMcpEndpoints()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",e),e}}getMcpServers(){try{return u.getMcpServers()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",e),e}}getConnectionConfig(){try{return u.getConnectionConfig()}catch(e){throw this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",e),e}}getWebUIPort(){try{return u.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&&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 u.configExists()}async reloadConfig(){try{this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E"),u.reloadConfig();let e=await this.getConfig();return this.eventBus.emitEvent("config:updated",{type:"config",timestamp:new Date}),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 u.getConfigPath()}}});var $t,Ao=m(()=>{"use strict";y();st();$t=class{static{c(this,"ConfigApiHandler")}logger;configService;constructor(){this.logger=g.withTag("ConfigApiHandler"),this.configService=new ge}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 Es(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 Ms(i,e){let t=i.status;return t===401?new he("\u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6263\u5B50 API Token \u914D\u7F6E","AUTH_FAILED",401,e):t===429?new he("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED",429,e):t>=500?new he("\u6263\u5B50\u670D\u52A1\u5668\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","SERVER_ERROR",t,e):new he(e?.msg||`API \u8C03\u7528\u5931\u8D25: ${i.statusText}`,"API_ERROR",t,e)}var Er,he,xt,ko=m(()=>{"use strict";y();Er=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())}}},he=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(Es,"retryWithBackoff");c(Ms,"handleCozeApiError");xt=class{static{c(this,"CozeApiService")}cache=new Er;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 he(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 he(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 Es(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 he("\u54CD\u5E94\u6570\u636E\u683C\u5F0F\u9519\u8BEF","PARSE_ERROR",n.status)}if(!n.ok)throw Ms(n,s);return s}catch(n){throw clearTimeout(o),n instanceof Error&&n.name==="AbortError"?new he(`\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 Ot(i,e){return{success:!0,data:i,message:e}}function N(i,e,t){return{success:!1,message:i,error:e?{code:e,details:t}:void 0}}function At(){let i=u.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 xt(i)}var Me,Do=m(()=>{"use strict";y();Z();ko();c(Ot,"createSuccessResponse");c(N,"createErrorResponse");c(At,"getCozeApiService");Me=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"),!u.isCozeConfigValid())return g.debug("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(N("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=await At().getWorkspaces();return g.info(`\u6210\u529F\u83B7\u53D6 ${r.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),e.json(Ot({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(N("\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(N("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(N("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(N(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"),!u.isCozeConfigValid())return g.debug("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(N("\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(N("\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570: workspace_id","MISSING_PARAMETER"),400);if(r<1||r>1e3)return e.json(N("page_num \u5FC5\u987B\u5728 1-1000 \u4E4B\u95F4","INVALID_PARAMETER"),400);if(o<1||o>100)return e.json(N("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 At().getWorkflows(n);g.info(`\u6210\u529F\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684 ${a.items.length} \u4E2A\u5DE5\u4F5C\u6D41`);let l=u.getCustomMCPTools(),h=a.items.map(p=>{let d=l.find(C=>C.handler.type==="proxy"&&C.handler.platform==="coze"&&C.handler.config.workflow_id===p.workflow_id);return{...p,isAddedAsTool:!!d,toolName:d?.name||null}});return g.info(`\u5DE5\u4F5C\u6D41\u5DE5\u5177\u72B6\u6001\u68C0\u67E5\u5B8C\u6210\uFF0C\u5171 ${h.filter(p=>p.isAddedAsTool).length} \u4E2A\u5DE5\u4F5C\u6D41\u5DF2\u6DFB\u52A0\u4E3A\u5DE5\u5177`),e.json(Ot({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(N("\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(N("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(N("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(N(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"),!u.isCozeConfigValid())return g.debug("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(N("\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=At(),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(Ot({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(N(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"),!u.isCozeConfigValid())return g.debug("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(N("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=At().getCacheStats();return e.json(Ot(r))}catch(t){return g.error("\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:",t),e.json(N(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 kt,No=m(()=>{"use strict";y();st();kt=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 ge}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 Ps}from"crypto";var Dt,_o=m(()=>{"use strict";y();fr();Rt();Dt=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 q.getInstance();this.mcpMessageHandler=new Le(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 p=await this.mcpMessageHandler.handleMessage(h);this.metrics.totalMessages++;let d=Date.now()-t;return this.metrics.averageResponseTime=(this.metrics.averageResponseTime*(this.metrics.totalMessages-1)+d)/this.metrics.totalMessages,this.logger.debug("MCP POST \u8BF7\u6C42\u5904\u7406\u6210\u529F",{method:h.method,messageId:r,responseTime:d,isNotification:p===null}),p===null?new Response(null,{status:204,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":d.toString()}}):e.json(p,200,{"Content-Type":"application/json","MCP-Protocol-Version":"2024-11-05","X-Response-Time":d.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 p=await e.req.text();if(p.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(p),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(p){this.logger.warn(`SSE \u5199\u5165\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${t}`,p),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=Ps(),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(),p=new AbortController,d={id:t,sessionId:r,response:new Response(a),connectedAt:o,lastActivity:o,writer:h,abortController:p,isAlive:!0,messageCount:0,userAgent:n,remoteAddress:s};this.clients.set(r,d),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(R){this.logger.error(`\u521D\u59CB SSE \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25: ${r}`,R),d.isAlive=!1}this.startHeartbeat(d);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"}}),E=c(()=>{this.handleClientDisconnect(r,t)},"handleDisconnect");return e.req.raw.signal?.addEventListener("abort",E),p.signal.addEventListener("abort",E),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}
36
+ 3. \u5982\u679C\u957F\u65F6\u95F4\u672A\u5B8C\u6210\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458`}var tt,cn=m(()=>{"use strict";tt=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(sn,"createTimeoutResponse");c(Do,"getToolSpecificTimeoutMessage");c(an,"getDefaultTimeoutMessage")});import{createHash as ko}from"crypto";import{existsSync as rt,mkdirSync as _o,readFileSync as ln,renameSync as Lo,writeFileSync as gn}from"fs";import{dirname as jo,resolve as pn}from"path";import Ho from"dayjs";var ue,Tt=m(()=>{"use strict";y();St();ue=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=p,this.cachePath=e||this.getCacheFilePath(),this.startCleanupTimer()}formatTimestamp(){return Ho().format("YYYY-MM-DD HH:mm:ss")}getCacheFilePath(){try{let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return pn(e,"xiaozhi.cache.json")}catch{let t=process.env.XIAOZHI_CONFIG_DIR||"/tmp";return pn(t,"xiaozhi.cache.json")}}async ensureCacheFile(){try{if(!rt(this.cachePath)){let e=jo(this.cachePath);rt(e)||(_o(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 n=await this.loadExistingCache(),o=this.generateConfigHash(r),s={tools:t.map(a=>({name:a.name,description:a.description||"",inputSchema:a.inputSchema})),lastUpdated:this.formatTimestamp(),serverConfig:{...r},configHash:o,version:this.CACHE_ENTRY_VERSION};n.mcpServers[e]=s,n.metadata.lastGlobalUpdate=this.formatTimestamp(),n.metadata.totalWrites+=1,await this.saveCache(n),this.logger.info(`[CacheManager] \u7F13\u5B58\u5199\u5165\u6210\u529F: ${e}, \u5DE5\u5177\u6570\u91CF: ${t.length}`)}catch(n){this.logger.warn(`[CacheManager] \u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e}, \u9519\u8BEF: ${n instanceof Error?n.message:String(n)}`)}}async loadExistingCache(){try{if(!rt(this.cachePath))return await this.createInitialCache();let e=ln(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{gn(r,t,"utf8"),Lo(r,e)}catch(n){try{rt(r)&&gn(r,"","utf8")}catch{}throw n}}generateConfigHash(e){try{return ko("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:rt(this.cachePath)?ln(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,n]of Object.entries(e.mcpServers))for(let o of n.tools)t.push({...o,name:`${r}__${o.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,n="completed",o,s=3e5){try{let a=await this.loadExtendedCache(),l=ve(e,t),g={result:r,timestamp:new Date().toISOString(),ttl:s,status:n,consumed:!1,taskId:o,retryCount:0};a.customMCPResults||(a.customMCPResults={}),a.customMCPResults[l]=g,await this.saveExtendedCache(a),this.logger.debug(`[CacheManager] \u5199\u5165CustomMCP\u7ED3\u679C\u7F13\u5B58: ${e}, \u72B6\u6001: ${n}`)}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(),n=ve(e,t);if(!r.customMCPResults||!r.customMCPResults[n])return null;let o=r.customMCPResults[n],s=Date.now(),a=new Date(o.timestamp).getTime();return s-a>o.ttl?(this.logger.debug(`[CacheManager] \u7F13\u5B58\u5DF2\u8FC7\u671F: ${e}`),null):o}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,n,o){try{let s=await this.loadExtendedCache(),a=ve(e,t);if(!s.customMCPResults||!s.customMCPResults[a])return!1;let l=s.customMCPResults[a],g=l.status;return l.status=r,l.timestamp=new Date().toISOString(),n&&(l.result=n),o&&r==="failed"&&(l.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${o}`}]},l.consumed=!0),r==="completed"&&(l.consumed=!1),await this.saveExtendedCache(s),this.logger.debug(`[CacheManager] \u66F4\u65B0\u7F13\u5B58\u72B6\u6001: ${e} ${g} -> ${r}`),!0}catch(s){return this.logger.warn(`[CacheManager] \u66F4\u65B0CustomMCP\u7F13\u5B58\u72B6\u6001\u5931\u8D25: ${s instanceof Error?s.message:String(s)}`),!1}}async markCustomMCPAsConsumed(e,t){try{let r=await this.loadExtendedCache(),n=ve(e,t);if(!r.customMCPResults||!r.customMCPResults[n])return!1;let o=r.customMCPResults[n];return o.consumed||(o.consumed=!0,o.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(),n=ve(e,t);return!r.customMCPResults||!r.customMCPResults[n]?!1:(delete r.customMCPResults[n],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[n,o]of t)Me(o)&&(delete e.customMCPResults[n],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,n=t.filter(u=>u.status==="pending").length,o=t.filter(u=>u.status==="completed").length,s=t.filter(u=>u.status==="failed").length,a=t.filter(u=>u.consumed).length,l=o>0?a/o*100:0,g=JSON.stringify(e.customMCPResults).length;return{totalEntries:r,pendingTasks:n,completedTasks:o,failedTasks:s,consumedEntries:a,cacheHitRate:l,lastCleanupTime:new Date().toISOString(),memoryUsage:g}}catch(e){return this.logger.warn(`[CacheManager] \u83B7\u53D6CustomMCP\u7F13\u5B58\u7EDF\u8BA1\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),{totalEntries:0,pendingTasks:0,completedTasks:0,failedTasks:0,consumedEntries:0,cacheHitRate:0,lastCleanupTime:new Date().toISOString(),memoryUsage:0}}}async loadExtendedCache(){try{return await this.loadExistingCache()}catch(e){return this.logger.warn(`[CacheManager] \u52A0\u8F7D\u6269\u5C55\u7F13\u5B58\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),{version:this.CACHE_VERSION,mcpServers:{},metadata:{lastGlobalUpdate:this.formatTimestamp(),totalWrites:0,createdAt:this.formatTimestamp()},customMCPResults:{}}}}async saveExtendedCache(e){await this.saveCache(e)}startCleanupTimer(){this.cleanupInterval=setInterval(()=>{this.cleanupCustomMCPResults().catch(e=>{this.logger.warn(`[CacheManager] \u81EA\u52A8\u6E05\u7406\u5931\u8D25: ${e}`)})},this.CLEANUP_INTERVAL),this.logger.debug(`[CacheManager] \u542F\u52A8\u6E05\u7406\u5B9A\u65F6\u5668\uFF0C\u95F4\u9694: ${this.CLEANUP_INTERVAL}ms`)}stopCleanupTimer(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0,this.logger.debug("[CacheManager] \u505C\u6B62\u6E05\u7406\u5B9A\u65F6\u5668"))}cleanup(){this.stopCleanupTimer(),this.logger.debug("[CacheManager] \u6E05\u7406\u8D44\u6E90\u5B8C\u6210")}}});var Mt,hn=m(()=>{"use strict";y();q();nn();on();St();cn();z();Tt();Mt=class{static{c(this,"CustomMCPHandler")}logger;tools=new Map;cacheManager;cacheLifecycleManager;taskStateManager;mcpServiceManager;TIMEOUT=Se.TIMEOUT;CACHE_TTL=Se.CACHE_TTL;CLEANUP_INTERVAL=Se.CLEANUP_INTERVAL;cleanupTimer;activeTasks=new Map;eventBus=M();constructor(e,t){this.logger=p,this.cacheManager=e||new ue,this.mcpServiceManager=t,this.cacheLifecycleManager=new yt(this.logger),this.taskStateManager=new Et(this.logger),this.startCleanupTimer(),this.cacheLifecycleManager.startAutoCleanup(),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("config:updated",async e=>{await this.handleConfigUpdated(e)})}async handleConfigUpdated(e){this.logger.info("[CustomMCP] \u68C0\u6D4B\u5230\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u662F\u5426\u9700\u8981\u91CD\u65B0\u521D\u59CB\u5316");try{e.type==="customMCP"?(this.logger.info("[CustomMCP] customMCP \u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0C\u91CD\u65B0\u521D\u59CB\u5316\u5904\u7406\u5668"),await this.reinitialize()):e.type==="serverTools"&&(this.logger.info("[CustomMCP] serverTools \u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0C\u91CD\u65B0\u521D\u59CB\u5316\u5904\u7406\u5668"),await this.reinitialize())}catch(t){this.logger.error("[CustomMCP] \u914D\u7F6E\u66F4\u65B0\u5904\u7406\u5931\u8D25:",t)}}async reinitialize(){try{this.logger.info("[CustomMCP] \u5F00\u59CB\u91CD\u65B0\u521D\u59CB\u5316\u5904\u7406\u5668"),this.tools.clear();let e=h.getCustomMCPTools();for(let t of e)this.tools.set(t.name,t),this.logger.info(`[CustomMCP] \u91CD\u65B0\u52A0\u8F7D\u5DE5\u5177: ${t.name} (${t.handler.type})`);this.logger.info(`[CustomMCP] \u91CD\u65B0\u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.tools.size} \u4E2A\u5DE5\u5177`)}catch(e){throw this.logger.error("[CustomMCP] \u91CD\u65B0\u521D\u59CB\u5316\u5931\u8D25:",e),e}}initialize(e){this.logger.info("[CustomMCP] \u521D\u59CB\u5316 CustomMCP \u5904\u7406\u5668...");try{let t=e||h.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 n=this.tools.get(e);if(!n)throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);this.logger.info(`[CustomMCP] \u8C03\u7528\u5DE5\u5177: ${e}`,{handler:n.handler.type,arguments:t});let o=await this.getCompletedResult(e,t);if(o)return this.logger.debug(`[CustomMCP] \u8FD4\u56DE\u5DF2\u5B8C\u6210\u7684\u4EFB\u52A1\u7ED3\u679C: ${e}`),await this.clearConsumedCache(e,t),o;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 tt){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}`),sn(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 n=await this.generateTaskId(e,t);await this.markTaskAsPending(n,e,t);try{let o=await this.callToolByType(r,t);return await this.markTaskAsCompleted(n,o),o}catch(o){throw await this.markTaskAsFailed(n,o),o}}async createTimeoutPromise(e,t){return new Promise((r,n)=>{setTimeout(()=>{n(new tt(`\u5DE5\u5177\u8C03\u7528\u8D85\u65F6: ${e}`))},this.TIMEOUT)})}async getCompletedResult(e,t){try{let r=this.generateCacheKey(e,t),n=await this.loadExtendedCache();if(!n.customMCPResults||!n.customMCPResults[r])return null;let o=n.customMCPResults[r];return o.status==="completed"&&!o.consumed&&!_e(o.timestamp,o.ttl)?o.result:null}catch(r){return this.logger.warn(`[CustomMCP] \u83B7\u53D6\u7F13\u5B58\u5931\u8D25: ${r}`),null}}async callToolByType(e,t){switch(e.handler.type){case"proxy":return await this.callProxyTool(e,t);case"function":return await this.callFunctionTool(e,t);case"http":return await this.callHttpTool(e,t);case"script":return await this.callScriptTool(e,t);case"chain":return await this.callChainTool(e,t);case"mcp":try{return await this.forwardToMCPServiceManager(e,t)}catch(r){this.logger.error(`[CustomMCP] MCP \u7C7B\u578B\u5DE5\u5177\u8DEF\u7531\u5931\u8D25: ${e.name}`,r);let n=r instanceof Error?r.message:"MCP \u7C7B\u578B\u5DE5\u5177\u8DEF\u7531\u9519\u8BEF";return{content:[{type:"text",text:n.includes("MCPServiceManager \u672A\u521D\u59CB\u5316")?n:"\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 forwardToMCPServiceManager(e,t){if(!this.mcpServiceManager)throw this.logger.error(`[CustomMCP] MCPServiceManager \u672A\u521D\u59CB\u5316\uFF0C\u65E0\u6CD5\u8F6C\u53D1\u5DE5\u5177 ${e.name} \u7684\u8C03\u7528`),new Error("MCPServiceManager \u672A\u521D\u59CB\u5316");let r=e.handler;this.logger.info(`[CustomMCP] \u8F6C\u53D1MCP\u5DE5\u5177\u8C03\u7528: ${e.name}`,{serviceName:r.config.serviceName,toolName:r.config.toolName});try{let n=await this.mcpServiceManager.callTool(r.config.toolName,t);return this.logger.info(`[CustomMCP] MCP\u5DE5\u5177\u8F6C\u53D1\u6210\u529F: ${e.name}`),n}catch(n){return this.logger.error(`[CustomMCP] MCP\u5DE5\u5177\u8F6C\u53D1\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`MCP\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}async callProxyTool(e,t){let r=e.handler;if(this.logger.info(`[CustomMCP] \u8C03\u7528\u4EE3\u7406\u5DE5\u5177: ${e.name}`,{platform:r.platform,config:r.config}),r.platform==="coze")return await this.callCozeWorkflow(e,t);throw new Error(`\u4E0D\u652F\u6301\u7684\u4EE3\u7406\u5E73\u53F0: ${r.platform}`)}async callCozeWorkflow(e,t){let n=e.handler.config;this.logger.info(`[CustomMCP] \u8C03\u7528 Coze \u5DE5\u4F5C\u6D41: ${e.name}`,{workflow_id:n.workflow_id,bot_id:n.bot_id});try{let o=this.buildCozeRequest(n,t),s=await this.sendCozeRequest(n,o);return this.logger.info(`[CustomMCP] Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u6210\u529F: ${e.name}`,{response:s}),this.processCozeResponse(e.name,s)}catch(o){return this.logger.error(`[CustomMCP] Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],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",n="",o=h.getConfig().platforms?.coze?.token;if(!o)throw new Error("Coze Token \u914D\u7F6E\u4E0D\u5B58\u5728");if(e.workflow_id)n="/v1/workflow/run",t.workflow_id=e.workflow_id;else if(e.bot_id)n="/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}${n}`,a=e.timeout||3e5,l={"Content-Type":"application/json",Authorization:`Bearer ${o}`,...e.headers};this.logger.debug(`[CustomMCP] \u53D1\u9001 Coze \u8BF7\u6C42\u5230: ${s}`,{headers:{...l},body:t});let g=new AbortController,u=setTimeout(()=>g.abort(),a);try{let d=await fetch(s,{method:"POST",headers:l,body:JSON.stringify(t)});if(clearTimeout(u),!d.ok){let T=await d.text();throw new Error(`Coze API \u8BF7\u6C42\u5931\u8D25 (${d.status}): ${T}`)}let v=await d.json();return this.logger.debug("[CustomMCP] Coze API \u54CD\u5E94:",v),v}catch(d){throw clearTimeout(u),d instanceof Error&&d.name==="AbortError"?new Error(`Coze API \u8BF7\u6C42\u8D85\u65F6 (${a}ms)`):d}}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 n=await this.loadModule(r.module),o=this.getFunction(n,r.function),s=await this.executeFunction(o,t,r);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s,null,2)}],isError:!1}}catch(n){return this.logger.error(`[CustomMCP] \u51FD\u6570\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`\u51FD\u6570\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],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 n=r.timeout||3e4,o={...r.context,logger:this.logger,arguments:t},s=Promise.resolve().then(()=>e.length>1?e(t,o):e(t)),a=new Promise((l,g)=>{setTimeout(()=>g(new Error(`\u51FD\u6570\u6267\u884C\u8D85\u65F6 (${n}ms)`)),n)});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:n,requestOptions:o}=this.buildHttpRequest(r,t),s=await this.sendHttpRequest(n,o,r);return this.processHttpResponse(e.name,s,r)}catch(n){return this.logger.error(`[CustomMCP] HTTP \u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`HTTP \u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}buildHttpRequest(e,t){let r=e.method||"POST",n={"Content-Type":"application/json","User-Agent":"xiaozhi-client/1.0",...e.headers};if(e.auth)switch(e.auth.type){case"bearer":e.auth.token&&(n.Authorization=`Bearer ${e.auth.token}`);break;case"basic":if(e.auth.username&&e.auth.password){let l=btoa(`${e.auth.username}:${e.auth.password}`);n.Authorization=`Basic ${l}`}break;case"api_key":e.auth.api_key&&e.auth.api_key_header&&(n[e.auth.api_key_header]=e.auth.api_key);break}let o,s=e.url;if(r!=="GET")e.body_template?o=this.replaceTemplateVariables(e.body_template,t):o=JSON.stringify(t);else{let l=new URLSearchParams;for(let[u,d]of Object.entries(t))d!=null&&l.append(u,String(d));let g=l.toString();g&&(s+=(s.includes("?")?"&":"?")+g)}return{url:s,requestOptions:{method:r,headers:n,body:o}}}async sendHttpRequest(e,t,r){let n=r.timeout||3e4,o=r.retry_count||0,s=r.retry_delay||1e3,a=null;for(let l=0;l<=o;l++){try{this.logger.debug(`[CustomMCP] \u53D1\u9001 HTTP \u8BF7\u6C42 (\u5C1D\u8BD5 ${l+1}/${o+1}): ${e}`,{method:t.method,headers:t.headers});let g=new AbortController,u=setTimeout(()=>g.abort(),n),d=await fetch(e,{...t,signal:g.signal});if(clearTimeout(u),d.ok||l===o)return d;this.logger.warn(`[CustomMCP] HTTP \u8BF7\u6C42\u5931\u8D25 (${d.status}), \u5C06\u5728 ${s}ms \u540E\u91CD\u8BD5`),a=new Error(`HTTP \u8BF7\u6C42\u5931\u8D25: ${d.status} ${d.statusText}`)}catch(g){if(a=g instanceof Error?g:new Error(String(g)),g instanceof Error&&g.name==="AbortError"&&(a=new Error(`HTTP \u8BF7\u6C42\u8D85\u65F6 (${n}ms)`)),this.logger.warn(`[CustomMCP] HTTP \u8BF7\u6C42\u5F02\u5E38 (\u5C1D\u8BD5 ${l+1}/${o+1}):`,a.message),l===o)throw a}l<o&&await new Promise(g=>setTimeout(g,s))}throw a||new Error("HTTP \u8BF7\u6C42\u5931\u8D25")}async processHttpResponse(e,t,r){try{let n=t.headers.get("content-type")||"",o;if(n.includes("application/json")?o=await t.json():o=await t.text(),!t.ok)return{content:[{type:"text",text:`HTTP \u8BF7\u6C42\u5931\u8D25 (${t.status}): ${typeof o=="string"?o:JSON.stringify(o)}`}],isError:!0};let s=o;return r.response_mapping&&(s=this.extractResponseData(o,r.response_mapping)),{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s,null,2)}],isError:!1}}catch(n){return this.logger.error(`[CustomMCP] \u5904\u7406 HTTP \u54CD\u5E94\u5931\u8D25: ${e}`,n),{content:[{type:"text",text:`\u5904\u7406\u54CD\u5E94\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}replaceTemplateVariables(e,t){let r=e;for(let[n,o]of Object.entries(t)){let s=`{{${n}}}`,a=typeof o=="string"?o:JSON.stringify(o);r=r.replace(new RegExp(s.replace(/[{}]/g,"\\$&"),"g"),a)}return r}extractResponseData(e,t){if(!t)return e;let r=c((n,o)=>{if(!o)return n;let s=o.split("."),a=n;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 n=r(e,t.success_path);if(n!==void 0)return t.data_path?r(n,t.data_path):n}if(t.data_path){let n=r(e,t.data_path);if(n!==void 0)return n}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 n=await this.executeScript(r,t);return{content:[{type:"text",text:typeof n=="string"?n:JSON.stringify(n,null,2)}],isError:!1}}catch(n){return this.logger.error(`[CustomMCP] \u811A\u672C\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`\u811A\u672C\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}async executeScript(e,t){let{spawn:r}=await import("child_process"),{promisify:n}=await import("util"),o=await import("fs/promises"),s=await import("path"),a=await import("os"),l=e.timeout||3e4,g=e.interpreter||"node",u,d=!1;try{if(e.script.includes(`
37
+ `)||e.script.length>200){let I=await o.mkdtemp(s.join(a.tmpdir(),"xiaozhi-script-")),K=this.getScriptExtension(g);u=s.join(I,`script${K}`),await o.writeFile(u,e.script,"utf8"),d=!0}else{u=e.script;try{await o.access(u)}catch{throw new Error(`\u811A\u672C\u6587\u4EF6\u4E0D\u5B58\u5728: ${u}`)}}let v={...process.env,...e.env,XIAOZHI_ARGUMENTS:JSON.stringify(t)},T=this.buildScriptCommand(g,u);return this.logger.debug(`[CustomMCP] \u6267\u884C\u811A\u672C\u547D\u4EE4: ${T.join(" ")}`),new Promise((I,K)=>{let B=r(T[0],T.slice(1),{env:v,stdio:["pipe","pipe","pipe"]}),at="",A="";B.stdout?.on("data",re=>{at+=re.toString()}),B.stderr?.on("data",re=>{A+=re.toString()});let ct=setTimeout(()=>{B.kill("SIGTERM"),K(new Error(`\u811A\u672C\u6267\u884C\u8D85\u65F6 (${l}ms)`))},l);B.on("close",re=>{clearTimeout(ct),re===0?I(at.trim()):K(new Error(`\u811A\u672C\u6267\u884C\u5931\u8D25 (\u9000\u51FA\u7801: ${re}): ${A.trim()}`))}),B.on("error",re=>{clearTimeout(ct),K(new Error(`\u811A\u672C\u6267\u884C\u9519\u8BEF: ${re.message}`))}),t&&Object.keys(t).length>0&&(B.stdin?.write(JSON.stringify(t)),B.stdin?.end())})}finally{if(d&&u)try{await o.unlink(u),await o.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 n;r.mode==="sequential"?n=await this.executeSequentialChain(r,t):n=await this.executeParallelChain(r,t);let o=n.flatMap(a=>a.content),s=n.some(a=>a.isError);return{content:o,isError:s}}catch(n){return this.logger.error(`[CustomMCP] \u94FE\u5F0F\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`\u94FE\u5F0F\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}delay(e){return new Promise(t=>setTimeout(t,e))}getToolInfo(e){return this.tools.get(e)}async executeSequentialChain(e,t){let r=[],n=t;for(let o of e.tools)try{this.logger.debug(`[CustomMCP] \u6267\u884C\u94FE\u5F0F\u5DE5\u5177\u4E2D\u7684: ${o}`);let s=await this.callToolRecursive(o,n);if(r.push(s),s.isError){if(e.error_handling==="stop")break;if(e.error_handling==="retry"){this.logger.warn(`[CustomMCP] \u5DE5\u5177 ${o} \u6267\u884C\u5931\u8D25\uFF0C\u5C1D\u8BD5\u91CD\u8BD5`);let a=await this.callToolRecursive(o,n);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{n=JSON.parse(a)}catch{n={input:a,...t}}}}catch(s){let a={content:[{type:"text",text:`\u5DE5\u5177 ${o} \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 n=>{try{return this.logger.debug(`[CustomMCP] \u5E76\u884C\u6267\u884C\u94FE\u5F0F\u5DE5\u5177\u4E2D\u7684: ${n}`),await this.callToolRecursive(n,t)}catch(o){return{content:[{type:"text",text:`\u5DE5\u5177 ${n} \u6267\u884C\u5F02\u5E38: ${o instanceof Error?o.message:String(o)}`}],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),n=await this.loadExtendedCache();if(n.customMCPResults?.[r]){n.customMCPResults[r].consumed=!0;let o=n.customMCPResults[r];Me(o)&&delete n.customMCPResults[r],await this.saveCache(n),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 n=this.generateCacheKey(t,r),o={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(n,o),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(n){this.logger.warn(`[CustomMCP] \u6807\u8BB0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${n}`)}}async markTaskAsCompleted(e,t){try{let r=this.activeTasks.get(e);r&&(r.status="completed",r.endTime=new Date().toISOString(),r.result=t);let n=await this.loadExtendedCache();for(let[o,s]of Object.entries(n.customMCPResults||{}))if(s.taskId===e){s.status="completed",s.result=t,s.timestamp=new Date().toISOString(),s.consumed=!1;break}await this.saveCache(n),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[o,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 n=this.activeTasks.get(e);n&&(n.status="failed",n.endTime=new Date().toISOString(),n.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[n,o]of Object.entries(e.customMCPResults||{}))Me(o)&&(e.customMCPResults?.[n]&&delete e.customMCPResults[n],t=!0,r++,o.taskId&&this.activeTasks.delete(o.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 ve(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 n=this.generateCacheKey(e,t),o={result:r,timestamp:new Date().toISOString(),ttl:this.CACHE_TTL,status:"completed",consumed:!1,retryCount:0};await this.updateCacheWithResult(n,o),this.logger.debug(`[CustomMCP] \u7F13\u5B58\u5DE5\u5177\u7ED3\u679C: ${e}`)}catch(n){this.logger.warn(`[CustomMCP] \u7F13\u5B58\u7ED3\u679C\u5931\u8D25: ${n}`)}}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 zo}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as Uo}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Fo}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{EventSource as Wo}from"eventsource";function Vo(){return p}function Bo(i){switch(Vo().info(`[TransportFactory] \u521B\u5EFA ${i.type} transport for ${i.name}`),i.type){case"stdio":return Go(i);case"sse":return qo(i);case"streamable-http":return Jo(i);default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function Go(i){if(!i.command)throw new Error("stdio transport \u9700\u8981 command \u914D\u7F6E");return new Uo({command:i.command,args:i.args||[],env:i.env})}function qo(i){if(!i.url)throw new Error("SSE transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=Xo(i);return new zo(e,t)}function Jo(i){if(!i.url)throw new Error("StreamableHTTP transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=Ko(i);return new Fo(e,t)}function Xo(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function Ko(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function Zo(i){if(!i.name||typeof i.name!="string")throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(i.type&&!Object.values(Le).includes(i.type))throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`);if(!i.type)throw new Error("\u4F20\u8F93\u7C7B\u578B\u672A\u8BBE\u7F6E\uFF0C\u8FD9\u5E94\u8BE5\u5728 inferTransportType \u4E2D\u5904\u7406");switch(i.type){case"stdio":if(!i.command)throw new Error("stdio \u7C7B\u578B\u9700\u8981 command \u5B57\u6BB5");break;case"sse":if(i.url===void 0||i.url===null)throw new Error(`${i.type} \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5`);break;case"streamable-http":if(i.url===void 0||i.url===null)throw new Error(`${i.type} \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5`);break;default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function Yo(){return["stdio","sse","streamable-http"]}var mr,un=m(()=>{"use strict";y();Pt();typeof global<"u"&&!global.EventSource&&(global.EventSource=Wo);c(Vo,"getLogger");c(Bo,"createTransport");c(Go,"createStdioTransport");c(qo,"createSSETransport");c(Jo,"createStreamableHTTPTransport");c(Xo,"createSSEOptions");c(Ko,"createStreamableHTTPOptions");c(Zo,"validateConfig");c(Yo,"getSupportedTypes");mr={create:Bo,validateConfig:Zo,getSupportedTypes:Yo}});import{Client as Qo}from"@modelcontextprotocol/sdk/client/index.js";var Le,wt,Pt=m(()=>{"use strict";y();z();un();Le=(r=>(r.STDIO="stdio",r.SSE="sse",r.STREAMABLE_HTTP="streamable-http",r))(Le||{}),wt=class{static{c(this,"MCPService")}config;client=null;transport=null;tools=new Map;connectionState="disconnected";reconnectOptions;reconnectState;logger;connectionTimeout=null;initialized=!1;eventBus=M();pingOptions;pingTimer=null;pingFailureCount=0;lastPingTime=null;isPinging=!1;constructor(e,t){this.logger=p;let r=this.inferTransportType(e);this.config=r,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 n=`[MCP-${this.config.name}] ${t}`;this.logger[e](n,...r)}inferTransportType(e){if(e.type)return e;this.logger.debug(`[MCP-${e.name}] \u81EA\u52A8\u63A8\u65AD\u4F20\u8F93\u7C7B\u578B...`);let t;if(e.command)t="stdio",this.logger.debug(`[MCP-${e.name}] \u68C0\u6D4B\u5230 command \u5B57\u6BB5\uFF0C\u63A8\u65AD\u4E3A stdio \u7C7B\u578B`);else if(e.url!==void 0&&e.url!==null)t=this.inferTransportTypeFromUrl(e.url,e.name);else throw new Error(`\u65E0\u6CD5\u4E3A\u670D\u52A1 ${e.name} \u63A8\u65AD\u4F20\u8F93\u7C7B\u578B\u3002\u8BF7\u663E\u5F0F\u6307\u5B9A type \u5B57\u6BB5\uFF0C\u6216\u63D0\u4F9B command/url \u914D\u7F6E`);return{type:t,...e}}inferTransportTypeFromUrl(e,t){try{let n=new URL(e).pathname;return n.endsWith("/sse")?(this.logger.info(`[MCP-${t}] \u68C0\u6D4B\u5230 URL \u8DEF\u5F84\u4EE5 /sse \u7ED3\u5C3E\uFF0C\u63A8\u65AD\u4E3A sse \u7C7B\u578B`),"sse"):n.endsWith("/mcp")?(this.logger.info(`[MCP-${t}] \u68C0\u6D4B\u5230 URL \u8DEF\u5F84\u4EE5 /mcp \u7ED3\u5C3E\uFF0C\u63A8\u65AD\u4E3A streamable-http \u7C7B\u578B`),"streamable-http"):(this.logger.info(`[MCP-${t}] URL \u8DEF\u5F84 ${n} \u4E0D\u5339\u914D\u7279\u5B9A\u89C4\u5219\uFF0C\u9ED8\u8BA4\u63A8\u65AD\u4E3A streamable-http \u7C7B\u578B`),"streamable-http")}catch(r){return this.logger.warn(`[MCP-${t}] URL \u89E3\u6790\u5931\u8D25\uFF0C\u9ED8\u8BA4\u63A8\u65AD\u4E3A streamable-http \u7C7B\u578B`,r),"streamable-http"}}validateConfig(){mr.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 Qo({name:`xiaozhi-${this.config.name}-client`,version:"1.0.0"},{capabilities:{tools:{}}}),this.transport=mr.create(this.config),this.client.connect(this.transport).then(async()=>{this.handleConnectionSuccess(),await this.refreshTools(),this.eventBus.emitEvent("mcp:service:connected",{serviceName:this.config.name,tools:this.getTools(),connectionTime:new Date}),e()}).catch(r=>{this.handleConnectionError(r),t(r)})}catch(r){this.handleConnectionError(r),t(r)}})}handleConnectionSuccess(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.connectionState="connected",this.initialized=!0,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.connectionState="disconnected",this.initialized=!1,this.reconnectState.lastError=e,this.logger.error(`MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5\u9519\u8BEF:`,e.message),this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.cleanupConnection(),this.eventBus.emitEvent("mcp:service:connection:failed",{serviceName:this.config.name,error:e,attempt:this.reconnectState.attempts}),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",this.eventBus.emitEvent("mcp:service:disconnected",{serviceName:this.config.name,reason:"\u624B\u52A8\u65AD\u5F00",disconnectionTime:new Date})}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((o,s)=>{setTimeout(()=>{s(new Error(`Ping\u8D85\u65F6 (${this.pingOptions.timeout}ms)`))},this.pingOptions.timeout)});await Promise.race([t,r]);let n=performance.now()-e;this.handlePingSuccess(n)}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 bt,dn=m(()=>{"use strict";y();z();bt=class{static{c(this,"ToolSyncManager")}configManager;logger;syncLocks=new Map;eventBus=M();constructor(e,t=p){this.configManager=e,this.logger=t.withTag("ToolSync"),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("config:updated",async e=>{await this.handleConfigUpdated(e)})}async handleConfigUpdated(e){this.logger.info("\u68C0\u6D4B\u5230\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u5DE5\u5177\u540C\u6B65\u72B6\u6001");try{e.type==="customMCP"?this.logger.debug("customMCP\u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0CCustomMCPHandler\u5C06\u81EA\u52A8\u5904\u7406"):e.type==="serverTools"&&e.serviceName?await this.handleServerToolsConfigUpdated(e.serviceName):await this.handleGeneralConfigUpdated()}catch(t){this.logger.error("\u914D\u7F6E\u66F4\u65B0\u540E\u7684\u5DE5\u5177\u540C\u6B65\u5931\u8D25:",t)}}async handleServerToolsConfigUpdated(e){this.logger.info(`\u5904\u7406\u670D\u52A1 ${e} \u7684serverTools\u914D\u7F6E\u66F4\u65B0`);try{this.eventBus.emitEvent("tool-sync:server-tools-updated",{serviceName:e,timestamp:new Date})}catch(t){this.logger.error(`\u5904\u7406\u670D\u52A1 ${e} \u914D\u7F6E\u66F4\u65B0\u5931\u8D25:`,t)}}async handleGeneralConfigUpdated(){this.logger.info("\u5904\u7406\u901A\u7528\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u6240\u6709\u670D\u52A1\u540C\u6B65\u72B6\u6001");try{this.eventBus.emitEvent("tool-sync:general-config-updated",{timestamp:new Date})}catch(e){this.logger.error("\u5904\u7406\u901A\u7528\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",e)}}async 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 n=this.getEnabledTools(r,t);if(n.length===0){this.logger.debug(`\u670D\u52A1 ${e} \u65E0\u542F\u7528\u5DE5\u5177\uFF0C\u8DF3\u8FC7\u540C\u6B65`);return}let o=this.configManager.getCustomMCPTools(),s=new Set(o.map(l=>l.name)),a=n.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 n of t){let o=e[n.name];o&&o.enable!==!1&&r.push(n)}return r}async addToolsToCustomMCP(e,t){let r=t.map(n=>({name:`${e}__${n.name}`,description:n.description||"",inputSchema:n.inputSchema||{},handler:{type:"mcp",config:{serviceName:e,toolName:n.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 n=this.configManager.getCustomMCPTools(),o=new Map(n.map(s=>[s.name,s]));for(let s of t){let a=`${e}__${s.name}`,l=o.get(a),g=r[s.name];if(l&&g&&(!l.stats||!l.stats.usageCount&&!l.stats.lastUsedTime)){let u={};g.usageCount!==void 0&&(u.usageCount=g.usageCount),g.lastUsedTime&&(u.lastUsedTime=g.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(),n=r.findIndex(a=>a.name===e);if(n===-1){this.logger.warn(`\u5DE5\u5177 ${e} \u4E0D\u5B58\u5728\u4E8E customMCP \u4E2D`);return}let o=[...r],s=o[n];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(o)}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 nt,mn,fr=m(()=>{"use strict";y();q();hn();z();Tt();Pt();dn();nt=class{static{c(this,"MCPServiceManager")}services=new Map;configs={};logger;tools=new Map;customMCPHandler;cacheManager;toolSyncManager;eventBus=M();constructor(e){this.logger=p,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 ue(r),this.customMCPHandler=new Mt,this.toolSyncManager=new bt(h,this.logger),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("mcp:service:connected",async e=>{await this.handleServiceConnected(e)}),this.eventBus.onEvent("mcp:service:disconnected",async e=>{await this.handleServiceDisconnected(e)}),this.eventBus.onEvent("mcp:service:connection:failed",async e=>{await this.handleServiceConnectionFailed(e)}),this.eventBus.onEvent("tool-sync:server-tools-updated",async e=>{await this.handleServerToolsUpdated(e)}),this.eventBus.onEvent("tool-sync:general-config-updated",async e=>{await this.handleGeneralConfigUpdated(e)})}async handleServiceConnected(e){this.logger.info(`\u670D\u52A1 ${e.serviceName} \u8FDE\u63A5\u6210\u529F\uFF0C\u5F00\u59CB\u5DE5\u5177\u540C\u6B65`);try{let t=this.services.get(e.serviceName);if(t){let r=t.getTools();this.toolSyncManager&&await this.toolSyncManager.syncToolsAfterConnection(e.serviceName,r),await this.refreshCustomMCPHandlerPublic(),this.logger.info(`\u670D\u52A1 ${e.serviceName} \u5DE5\u5177\u540C\u6B65\u5B8C\u6210`)}}catch(t){this.logger.error(`\u540C\u6B65\u670D\u52A1 ${e.serviceName} \u5DE5\u5177\u5931\u8D25:`,t)}}async handleServiceDisconnected(e){this.logger.info(`\u670D\u52A1 ${e.serviceName} \u65AD\u5F00\u8FDE\u63A5\uFF0C\u539F\u56E0: ${e.reason||"\u672A\u77E5"}`);try{await this.refreshToolsCache(),await this.refreshCustomMCPHandlerPublic(),this.logger.info(`\u670D\u52A1 ${e.serviceName} \u65AD\u5F00\u8FDE\u63A5\u5904\u7406\u5B8C\u6210`)}catch(t){this.logger.error(`\u670D\u52A1 ${e.serviceName} \u65AD\u5F00\u8FDE\u63A5\u5904\u7406\u5931\u8D25:`,t)}}async handleServiceConnectionFailed(e){this.logger.warn(`\u670D\u52A1 ${e.serviceName} \u8FDE\u63A5\u5931\u8D25 (\u5C1D\u8BD5 ${e.attempt})\uFF0C\u9519\u8BEF: ${e.error.message}`);try{await this.refreshCustomMCPHandlerPublic()}catch(t){this.logger.error("\u5237\u65B0CustomMCPHandler\u5931\u8D25:",t)}}async handleServerToolsUpdated(e){this.logger.info(`\u5904\u7406\u670D\u52A1 ${e.serviceName} \u7684serverTools\u914D\u7F6E\u66F4\u65B0`);try{let t=this.services.get(e.serviceName);if(t?.isConnected()){let r=t.getTools();this.toolSyncManager&&await this.toolSyncManager.syncToolsAfterConnection(e.serviceName,r),await this.refreshCustomMCPHandlerPublic(),this.logger.info(`\u670D\u52A1 ${e.serviceName} \u914D\u7F6E\u66F4\u65B0\u540C\u6B65\u5B8C\u6210`)}}catch(t){this.logger.error(`\u5904\u7406\u670D\u52A1 ${e.serviceName} \u914D\u7F6E\u66F4\u65B0\u5931\u8D25:`,t)}}async handleGeneralConfigUpdated(e){this.logger.info("\u5904\u7406\u901A\u7528\u914D\u7F6E\u66F4\u65B0\uFF0C\u68C0\u67E5\u6240\u6709\u5DF2\u8FDE\u63A5\u670D\u52A1");try{for(let[t,r]of this.services)if(r.isConnected()){let n=r.getTools();this.toolSyncManager&&await this.toolSyncManager.syncToolsAfterConnection(t,n)}await this.refreshCustomMCPHandlerPublic(),this.logger.info("\u901A\u7528\u914D\u7F6E\u66F4\u65B0\u540C\u6B65\u5B8C\u6210")}catch(t){this.logger.error("\u5904\u7406\u901A\u7528\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",t)}}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 wt(t);await r.connect(),this.services.set(e,r),await this.refreshToolsCache();let n=r.getTools();this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u542F\u52A8\u6210\u529F\uFF0C\u52A0\u8F7D\u4E86 ${n.length} \u4E2A\u5DE5\u5177:`,n.map(o=>o.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(),n=this.configs[e];n&&this.cacheManager.writeCacheEntry(e,r,n).then(()=>{this.logger.debug(`[MCPManager] \u5DF2\u5C06 ${e} \u5DE5\u5177\u5217\u8868\u5199\u5165\u7F13\u5B58`)}).catch(o=>{this.logger.warn(`[MCPManager] \u5199\u5165\u7F13\u5B58\u5931\u8D25: ${e}, \u9519\u8BEF: ${o instanceof Error?o.message:String(o)}`)});for(let o of r){let s=`${e}__${o.name}`;this.tools.set(s,{serviceName:e,originalName:o.name,tool:o})}}await this.syncToolsConfigToFile()}getAllTools(){let e=[];for(let[r,n]of this.services)if(n.isConnected()){let o=n.getTools();for(let s of o){if(!h.isToolEnabled(r,s.name))continue;let l=`${r}__${s.name}`;e.push({name:l,description:s.description||"",inputSchema:s.inputSchema,serviceName:r,originalName:s.name})}}let t=[];try{t=this.customMCPHandler.getTools(),this.logger.debug(`[MCPManager] \u6210\u529F\u83B7\u53D6 ${t.length} \u4E2A customMCP \u5DE5\u5177`)}catch(r){this.logger.warn("[MCPManager] \u83B7\u53D6 CustomMCP \u5DE5\u5177\u5931\u8D25\uFF0C\u5C06\u53EA\u8FD4\u56DE\u6807\u51C6 MCP \u5DE5\u5177:",r),t=[]}for(let r of t)e.push({name:r.name,description:r.description||"",inputSchema:r.inputSchema,serviceName:this.getServiceNameForTool(r),originalName:r.name});return this.logger.info(`[MCPManager] \u8FD4\u56DE ${e.length} \u4E2A\u5DE5\u5177 (\u670D\u52A1\u5DE5\u5177: ${e.length-t.length}, customMCP\u5DE5\u5177: ${t.length})`),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 o=this.customMCPHandler.getToolInfo(e);if(o?.handler?.type==="mcp")try{let s=await this.callMCPTool(e,o.handler.config,t);return this.updateToolStats(e,o.handler.config.serviceName,o.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,o.handler.config.serviceName,o.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 n=this.services.get(r.serviceName);if(!n)throw new Error(`\u670D\u52A1 ${r.serviceName} \u4E0D\u53EF\u7528`);if(!n.isConnected())throw new Error(`\u670D\u52A1 ${r.serviceName} \u672A\u8FDE\u63A5`);try{let o=await n.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:`,o),o}catch(o){throw this.updateToolStatsForFailedCall(e,r.serviceName,r.originalName,o).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:`,o.message),o}}async updateToolStats(e,t,r,n){try{if(!n)return;let o=new Date().toISOString();await this.updateCustomMCPToolStats(e,o),t!=="customMCP"&&await this.updateMCPServerToolStats(t,r,o),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u4FE1\u606F`)}catch(o){throw this.logger.error(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,o),o}}async updateToolStatsForFailedCall(e,t,r,n){try{let o=new Date().toISOString();await this.updateCustomMCPToolLastUsedTime(e,o),t!=="customMCP"&&await this.updateMCPServerToolLastUsedTime(t,r,o),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0\u5DE5\u5177 ${e} \u7684\u5931\u8D25\u8C03\u7528\u7EDF\u8BA1\u4FE1\u606F`)}catch(o){throw this.logger.error(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u8C03\u7528\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,o),o}}async updateCustomMCPToolStats(e,t){try{await h.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 h.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 h.updateMCPServerToolStatsWithLock(e,t,r,!0),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1`)}catch(n){throw this.logger.error(`[MCPManager] \u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u5931\u8D25:`,n),n}}async updateMCPServerToolLastUsedTime(e,t,r){try{await h.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(n){throw this.logger.error(`[MCPManager] \u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u6700\u540E\u4F7F\u7528\u65F6\u95F4\u5931\u8D25:`,n),n}}async callMCPTool(e,t,r){let{serviceName:n,toolName:o}=t;this.logger.info(`[MCPManager] \u8C03\u7528 MCP \u540C\u6B65\u5DE5\u5177 ${e} -> ${n}.${o}`);let s=this.services.get(n);if(!s)throw new Error(`\u670D\u52A1 ${n} \u4E0D\u53EF\u7528`);if(!s.isConnected())throw new Error(`\u670D\u52A1 ${n} \u672A\u8FDE\u63A5`);try{let a=await s.callTool(o,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{h.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=0,t=[];try{e=this.customMCPHandler.getToolCount(),t=this.customMCPHandler.getToolNames(),this.logger.debug(`[MCPManager] \u6210\u529F\u83B7\u53D6 customMCP \u72B6\u6001: ${e} \u4E2A\u5DE5\u5177`)}catch(a){this.logger.warn("[MCPManager] \u83B7\u53D6 CustomMCP \u72B6\u6001\u5931\u8D25\uFF0C\u5C06\u53EA\u5305\u542B\u6807\u51C6 MCP \u5DE5\u5177:",a),e=0,t=[]}let r=this.tools.size+e,o=[...Array.from(this.tools.keys()),...t],s={services:{},totalTools:r,availableTools:o};for(let[a,l]of this.services){let g=l.getStatus();s.services[a]={connected:g.connected,clientName:`xiaozhi-${a}-client`}}return e>0&&(s.services.customMCP={connected:!0,clientName:"xiaozhi-customMCP-handler"}),s}getStatsUpdateInfo(){try{let e=h.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)}getConnectedServices(){let e=[];for(let[t,r]of this.services)r.isConnected()&&e.push(t);return e}async refreshCustomMCPHandler(){try{this.logger.info("\u91CD\u65B0\u521D\u59CB\u5316CustomMCPHandler"),await this.customMCPHandler.reinitialize(),this.logger.info("CustomMCPHandler\u91CD\u65B0\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw this.logger.error("CustomMCPHandler\u91CD\u65B0\u521D\u59CB\u5316\u5931\u8D25:",e),e}}async refreshCustomMCPHandlerPublic(){return this.refreshCustomMCPHandler()}getAllServices(){return new Map(this.services)}getCustomMCPHandler(){return this.customMCPHandler}hasCustomMCPTool(e){try{return this.customMCPHandler.hasTool(e)}catch(t){return this.logger.warn(`[MCPManager] \u68C0\u67E5 CustomMCP \u5DE5\u5177 ${e} \u662F\u5426\u5B58\u5728\u5931\u8D25:`,t),!1}}getCustomMCPTools(){try{return this.customMCPHandler.getTools()}catch(e){return this.logger.warn("[MCPManager] \u83B7\u53D6 CustomMCP \u5DE5\u5177\u5217\u8868\u5931\u8D25\uFF0C\u8FD4\u56DE\u7A7A\u6570\u7EC4:",e),[]}}enhanceServiceConfig(e){let t={...e};try{if(e.type==="sse"&&e.url&&e.url.includes("modelscope")){let r=h.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,n;if(typeof e=="string"&&t)n=e,r=t;else if(typeof e=="object")n=e.name,r=e;else throw new Error("Invalid arguments for addServiceConfig");let o=this.enhanceServiceConfig(r);this.configs[n]=o,this.logger.info(`[MCPManager] \u5DF2\u6DFB\u52A0\u670D\u52A1\u914D\u7F6E: ${n}`)}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=h.getMcpServerConfig();for(let[t,r]of this.services){if(!r.isConnected())continue;let n=r.getTools();if(n.length===0)continue;let o=e[t]?.tools||{},s={};for(let d of n){let v=o[d.name];v?s[d.name]={...v,description:d.description||v.description||""}:s[d.name]={description:d.description||"",enable:!0}}let a=n.map(d=>d.name),g=Object.keys(o).filter(d=>!a.includes(d));if(g.length>0&&this.logger.info(`[MCPManager] \u68C0\u6D4B\u5230\u670D\u52A1 ${t} \u79FB\u9664\u4E86 ${g.length} \u4E2A\u5DE5\u5177: ${g.join(", ")}`),this.hasToolsConfigChanged(o,s)){h.updateServerToolsConfig(t,s);let d=Object.keys(s).filter(T=>!o[T]),v=Object.keys(s).filter(T=>{let I=o[T],K=s[T];return I&&I.description!==K.description});this.logger.info(`[MCPManager] \u5DF2\u540C\u6B65\u670D\u52A1 ${t} \u7684\u5DE5\u5177\u914D\u7F6E:`),d.length>0&&this.logger.info(` - \u65B0\u589E\u5DE5\u5177: ${d.join(", ")}`),v.length>0&&this.logger.info(` - \u66F4\u65B0\u5DE5\u5177: ${v.join(", ")}`),g.length>0&&this.logger.info(` - \u79FB\u9664\u5DE5\u5177: ${g.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),n=Object.keys(t);if(r.length!==n.length)return!0;let o=n.filter(a=>!r.includes(a)),s=r.filter(a=>!n.includes(a));if(o.length>0||s.length>0)return!0;for(let a of r){let l=e[a],g=t[a];if(l.description!==g.description)return!0}return!1}},mn=nt});var je,Cr=m(()=>{"use strict";y();je=class{static{c(this,"MCPMessageHandler")}logger;serviceManager;constructor(e){this.serviceManager=e,this.logger=p}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"],n=e.protocolVersion,o=r.includes(n)?n:"2024-11-05";return this.logger.info(`\u534F\u8BAE\u7248\u672C\u534F\u5546: \u5BA2\u6237\u7AEF=${n}, \u670D\u52A1\u5668\u54CD\u5E94=${o}`),{jsonrpc:"2.0",result:{serverInfo:{name:"xiaozhi-mcp-server",version:"1.0.0"},capabilities:{tools:{},logging:{}},protocolVersion:o},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(n=>({name:n.name,description:n.description,inputSchema:n.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 fn}from"events";var vr,Sr,Rt,Cn=m(()=>{"use strict";y();fr();et();Cr();vr=class{static{c(this,"ToolRegistry")}serviceManager;logger;constructor(e){this.serviceManager=e,this.logger=p}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}},Sr=class extends fn{static{c(this,"ConnectionManager")}connections=new Map;logger;constructor(){super(),this.logger=p}async initialize(){this.logger.info("\u521D\u59CB\u5316\u8FDE\u63A5\u7BA1\u7406\u5668")}registerConnection(e,t,r){let n={id:e,transportName:t,state:r,connectedAt:new Date,lastActivity:new Date};this.connections.set(e,n),this.emit("connectionRegistered",n),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")}},Rt=class extends fn{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=p,this.serviceManager=new nt,this.messageHandler=new je(this.serviceManager),this.toolRegistry=new vr(this.serviceManager),this.connectionManager=new Sr,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 vn(i={name:"http"}){p.info("\u521B\u5EFA HTTP \u6A21\u5F0F\u670D\u52A1\u5668");let e=new Rt;await e.initialize();let t=e.getMessageHandler(),r=new vt(t,i);return await e.registerTransport("http",r),p.info("HTTP \u6A21\u5F0F\u670D\u52A1\u5668\u521B\u5EFA\u6210\u529F"),e}var Sn=m(()=>{"use strict";y();en();tn();rn();Cn();c(vn,"createHTTPServer")});var yn={};G(yn,{MCPServer:()=>yr});import{EventEmitter as es}from"events";var L,yr,En=m(()=>{"use strict";y();Ct();q();Sn();L=new Je,yr=class extends es{static{c(this,"MCPServer")}unifiedServer=null;proxyMCPServer=null;port;isStarted=!1;constructor(e=3e3){super(),this.port=e}async initializeUnifiedServer(){if(!this.unifiedServer){L.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 vn(e),this.unifiedServer.on("started",()=>this.emit("started")),this.unifiedServer.on("stopped",()=>this.emit("stopped")),this.unifiedServer.on("connectionRegistered",t=>{this.emit("connectionRegistered",t)}),L.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw L.error("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u5931\u8D25",e),e}}}async initializeMCPClient(){try{let e=null;try{h.configExists()&&(e=h.getMcpEndpoints().find(r=>r&&!r.includes("<\u8BF7\u586B\u5199"))||null)}catch(t){L.warn("\u4ECE\u914D\u7F6E\u4E2D\u8BFB\u53D6\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25:",t)}e?(this.proxyMCPServer=new Ce(e),this.unifiedServer&&this.proxyMCPServer.setServiceManager(this.unifiedServer.getServiceManager()),await this.proxyMCPServer.connect(),L.info("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F")):L.info("\u672A\u914D\u7F6E\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u8DF3\u8FC7\u8FDE\u63A5")}catch(e){L.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}}async start(){if(this.isStarted){L.warn("\u670D\u52A1\u5668\u5DF2\u542F\u52A8");return}try{L.info("\u542F\u52A8 MCP \u670D\u52A1\u5668"),await this.initializeUnifiedServer(),this.unifiedServer&&await this.unifiedServer.start(),this.initializeMCPClient().catch(e=>{L.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}),this.isStarted=!0,this.emit("started"),L.info("MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F")}catch(e){throw L.error("\u542F\u52A8 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}async stop(){if(!this.isStarted){L.warn("\u670D\u52A1\u5668\u672A\u542F\u52A8");return}try{L.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"),L.info("MCP \u670D\u52A1\u5668\u5DF2\u505C\u6B62")}catch(e){throw L.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 ts,resolve as rs}from"path";function Pn(i){try{let t=new URL(i).pathname;return t.endsWith("/sse")?"sse":t.endsWith("/mcp")?"streamable-http":"streamable-http"}catch(e){return He.warn(`URL \u89E3\u6790\u5931\u8D25\uFF0C\u9ED8\u8BA4\u63A8\u65AD\u4E3A streamable-http \u7C7B\u578B: ${i}`,e),"streamable-http"}}function wn(i,e){He.debug(`\u8F6C\u6362\u914D\u7F6E: ${i}`,e);try{if(!i||typeof i!="string")throw new O("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!e||typeof e!="object")throw new O("\u914D\u7F6E\u5BF9\u8C61\u4E0D\u80FD\u4E3A\u7A7A",i);let t=ns(i,e);return cs(t),He.info(`\u914D\u7F6E\u8F6C\u6362\u6210\u529F: ${i} -> ${t.type}`),t}catch(t){throw He.error(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${i}`,t),t instanceof O?t:new O(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,i)}}function ns(i,e){if(is(e))return os(i,e);if("type"in e)switch(e.type){case"sse":return Tn(i,e);case"streamable-http":return Mn(i,e);default:throw new O(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${e.type}`,i)}if("url"in e){if(e.url===void 0||e.url===null)throw new O("\u7F51\u7EDC\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 url \u5B57\u6BB5",i);if(Pn(e.url||"")==="sse"){let n={...e,type:"sse"};return Tn(i,n)}let r={...e,type:"streamable-http"};return Mn(i,r)}throw new O("\u65E0\u6CD5\u8BC6\u522B\u7684\u914D\u7F6E\u7C7B\u578B",i)}function os(i,e){if(!e.command)throw new O("\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(n=>{if(ss(n)){let o=rs(t,n);return He.debug(`\u89E3\u6790\u76F8\u5BF9\u8DEF\u5F84: ${n} -> ${o}`),o}return n});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 Tn(i,e){if(e.url===void 0||e.url===null)throw new O("SSE \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);let t=e.type==="sse"?"sse":Pn(e.url||""),r=e.url?as(e.url):!1,n={name:i,type:t,url:e.url,reconnect:{enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:15e3,jitter:!0},ping:t==="sse"?{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3}:{enabled:!1,interval:6e4,timeout:1e4,maxFailures:3,startDelay:1e4},timeout:3e4};return r&&(n.modelScopeAuth=!0),He.info(`[ConfigAdapter] \u670D\u52A1 ${i} URL: ${e.url}\uFF0C\u63A8\u65AD\u7C7B\u578B: ${t}${r?" (ModelScope)":""}`),n}function Mn(i,e){if(e.url===void 0||e.url===null)throw new O("STREAMABLE_HTTP \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);let t=e.url||"";return{name:i,type:"streamable-http",url:t,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 ss(i){return ts(i)?!1:!!(i.startsWith("./")||i.startsWith("../")||/\.(js|py|ts|mjs|cjs)$/i.test(i))}function is(i){return"command"in i&&typeof i.command=="string"}function as(i){return i.includes("modelscope.net")||i.includes("modelscope.cn")}function cs(i){if(!i.name||typeof i.name!="string")throw new O("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(i.type&&!Object.values(Le).includes(i.type))throw new O(`\u65E0\u6548\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`);if(!i.type)throw new O("\u4F20\u8F93\u7C7B\u578B\u672A\u6307\u5B9A\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E\u6216\u542F\u7528\u81EA\u52A8\u63A8\u65AD");switch(i.type){case"stdio":if(!i.command)throw new O("STDIO \u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5");break;case"sse":if(i.url===void 0||i.url===null)throw new O("SSE \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5");break;case"streamable-http":if(i.url===void 0||i.url===null)throw new O("STREAMABLE_HTTP \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5");break;default:throw new O(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}var He,O,bn=m(()=>{"use strict";y();Pt();He=p.withTag("ConfigAdapter");c(Pn,"inferTransportTypeFromUrl");O=class extends Error{constructor(t,r){super(t);this.configName=r;this.name="ConfigValidationError"}static{c(this,"ConfigValidationError")}};c(wn,"convertLegacyToNew");c(ns,"convertByConfigType");c(os,"convertLocalConfig");c(Tn,"convertSSEConfig");c(Mn,"convertStreamableHTTPConfig");c(ss,"isRelativePath");c(is,"isLocalConfig");c(as,"isModelScopeURL");c(cs,"validateNewConfig")});async function ls(){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),new mn}async function Rn(){if(ce&&F==="initialized")return ce;if(te&&F==="initializing")return te;F==="failed"&&Er(),F="initializing",te=ls();try{return ce=await te,F="initialized",ze=`mcp-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,ot=null,console.log(`\u2705 MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${ze}`),ce}catch(i){throw F="failed",ot=i,te=null,console.error("\u274C MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",i.message),i}}async function In(){if(F==="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..."),F="cleanup";try{if(te){try{await(await te).stopAllServices()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}te=null}ce&&(await ce.stopAllServices(),ce=null),F="not_initialized",ot=null,ze=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),Er(),i}}function Er(){console.log("\u{1F504} \u91CD\u7F6E MCPServiceManager \u5355\u4F8B\u72B6\u6001"),ce=null,te=null,F="not_initialized",ot=null,ze=null}function gs(){return F==="initialized"&&ce!==null}function ps(){return{state:F,initializationTime:ze?new Date:void 0,lastError:ot||void 0,instanceId:ze||void 0}}async function hs(){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),await In(),Rn()}function us(){return ce}async function ds(){if(F==="initialized")return!0;if(F==="initializing"&&te)try{return await te,!0}catch{return!1}return!1}var ce,te,F,ot,ze,X,It=m(()=>{"use strict";fr();ce=null,te=null,F="not_initialized",ot=null,ze=null;c(ls,"createInstance");c(Rn,"getInstance");c(In,"cleanup");c(Er,"reset");c(gs,"isInitialized");c(ps,"getStatus");c(hs,"forceReinitialize");c(us,"getCurrentInstance");c(ds,"waitForInitialization");X={getInstance:Rn,cleanup:In,reset:Er,isInitialized:gs,getStatus:ps,forceReinitialize:hs,getCurrentInstance:us,waitForInitialization:ds};process.on("exit",()=>{X.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B..."),X.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 X.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 X.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as ms}from"events";import{z as Ue}from"zod";var fs,Cs,$t,$n=m(()=>{"use strict";y();Ct();z();gt();fs={reconnectInterval:5e3,maxReconnectAttempts:3,connectionTimeout:1e4,errorRecoveryEnabled:!0,errorNotificationEnabled:!0},Cs=Ue.object({reconnectInterval:Ue.number().min(100,"reconnectInterval \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 100 \u7684\u6570\u5B57").optional(),maxReconnectAttempts:Ue.number().min(0,"maxReconnectAttempts \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 0 \u7684\u6570\u5B57").optional(),connectionTimeout:Ue.number().min(1e3,"connectionTimeout \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57").optional(),errorRecoveryEnabled:Ue.boolean().optional(),errorNotificationEnabled:Ue.boolean().optional()}).strict(),$t=class extends ms{static{c(this,"IndependentXiaozhiConnectionManager")}connections=new Map;connectionStates=new Map;mcpServiceManager=null;configManager;logger;eventBus;isInitialized=!1;isConnecting=!1;options;reconnectTimers=new Map;constructor(e,t){super(),this.configManager=e,this.logger=p,this.eventBus=M(),this.options={...fs,...t},this.logger.debug("[IndependentXiaozhiConnectionManager] \u5B9E\u4F8B\u5DF2\u521B\u5EFA"),this.logger.debug("[IndependentXiaozhiConnectionManager] \u914D\u7F6E\u9009\u9879:",this.options)}async initialize(e,t){if(!this.isInitialized){this.logger.debug(`\u5F00\u59CB\u521D\u59CB\u5316 IndependentXiaozhiConnectionManager\uFF0C\u5C0F\u667A\u63A5\u5165\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.logger.debug(`IndependentXiaozhiConnectionManager \u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u7BA1\u7406 ${this.connections.size} \u4E2A\u8FDE\u63A5`)}catch(r){throw this.logger.error("IndependentXiaozhiConnectionManager \u521D\u59CB\u5316\u5931\u8D25:",r),await this.cleanup(),r}}}async connect(){if(!this.isInitialized)throw new Error("IndependentXiaozhiConnectionManager \u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 initialize()");if(!this.isConnecting){this.isConnecting=!0,this.logger.debug(`\u5F00\u59CB\u8FDE\u63A5\u6240\u6709\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u603B\u6570: ${this.connections.size}`);try{let e=[];for(let[o,s]of this.connections)e.push(this.connectSingleEndpoint(o,s));let t=await Promise.allSettled(e),r=t.filter(o=>o.status==="fulfilled").length,n=t.length-r;if(this.logger.info(`\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5B8C\u6210 - \u6210\u529F: ${r}, \u5931\u8D25: ${n}`),r===0)throw new Error("\u6240\u6709\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25")}finally{this.isConnecting=!1}}}async disconnect(){this.logger.debug("\u5F00\u59CB\u65AD\u5F00\u6240\u6709\u8FDE\u63A5"),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\u5C0F\u667A\u63A5\u5165\u70B9\u5DF2\u65AD\u5F00\u8FDE\u63A5")}async addEndpoint(e){if(!this.isInitialized)throw new Error("IndependentXiaozhiConnectionManager \u672A\u521D\u59CB\u5316");if(this.connections.has(e)){this.logger.debug(`\u5C0F\u667A\u63A5\u5165\u70B9 ${C(e)} \u5DF2\u5B58\u5728\u4E8E\u8FDE\u63A5\u7BA1\u7406\u5668\u4E2D\uFF0C\u8DF3\u8FC7\u6DFB\u52A0`);return}if(this.checkConfigDuplicate(e))throw new Error(`\u63A5\u5165\u70B9 ${C(e)} \u5DF2\u5B58\u5728\u4E8E\u914D\u7F6E\u6587\u4EF6\u4E2D`);this.logger.debug(`\u52A8\u6001\u6DFB\u52A0\u5C0F\u667A\u63A5\u5165\u70B9: ${C(e)}`);try{this.configManager.addMcpEndpoint(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(`\u6DFB\u52A0\u63A5\u5165\u70B9\u6210\u529F\uFF1A ${C(e)}`)}catch(t){try{this.configManager.removeMcpEndpoint(e),this.logger.debug(`\u914D\u7F6E\u6587\u4EF6\u56DE\u6EDA\u6210\u529F: ${C(e)}`)}catch(r){this.logger.error(`\u914D\u7F6E\u6587\u4EF6\u56DE\u6EDA\u5931\u8D25: ${C(e)}`,r)}throw this.connections.delete(e),this.connectionStates.delete(e),this.logger.error(`\u6DFB\u52A0\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25\uFF1A ${C(e)}`,t),t}}catch(t){throw this.logger.error(`\u6DFB\u52A0\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25\uFF08\u914D\u7F6E\u6587\u4EF6\u64CD\u4F5C\uFF09\uFF1A ${C(e)}`,t),t}}async removeEndpoint(e){if(!this.connections.has(e)){this.logger.debug(`\u5C0F\u667A\u63A5\u5165\u70B9 ${C(e)} \u4E0D\u5B58\u5728\u4E8E\u8FDE\u63A5\u7BA1\u7406\u5668\u4E2D\uFF0C\u8DF3\u8FC7\u79FB\u9664`);return}this.logger.debug(`\u52A8\u6001\u79FB\u9664\u5C0F\u667A\u63A5\u5165\u70B9: ${C(e)}`);try{let t=this.connections.get(e);this.configManager.removeMcpEndpoint(e);try{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(`\u79FB\u9664\u5C0F\u667A\u63A5\u5165\u70B9\u6210\u529F\uFF1A${C(e)}`)}catch(r){try{this.configManager.addMcpEndpoint(e),this.logger.debug(`\u914D\u7F6E\u6587\u4EF6\u56DE\u6EDA\u6210\u529F: ${C(e)}`)}catch(n){this.logger.error(`\u914D\u7F6E\u6587\u4EF6\u56DE\u6EDA\u5931\u8D25: ${C(e)}`,n)}throw this.logger.error(`\u79FB\u9664\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25\uFF1A ${C(e)}`,r),r}}catch(t){throw this.logger.error(`\u79FB\u9664\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25\uFF08\u914D\u7F6E\u6587\u4EF6\u64CD\u4F5C\uFF09\uFF1A ${C(e)}`,t),t}}getEndpoints(){let e=Array.from(this.connections.keys()),t=Array.from(this.connectionStates.keys());return Array.from(new Set([...e,...t]))}async disconnectEndpoint(e){let t=this.connections.get(e);if(!t){this.logger.debug(`\u63A5\u5165\u70B9\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u65AD\u5F00: ${C(e)}`);return}this.logger.info(`\u65AD\u5F00\u8FDE\u63A5\u63A5\u5165\u70B9: ${C(e)}`);try{await this.disconnectSingleEndpoint(e,t)}catch(r){throw this.logger.error(`\u65AD\u5F00\u8FDE\u63A5\u63A5\u5165\u70B9\u5931\u8D25\uFF1A ${C(e)}`,r),r}}async clearEndpoints(){this.logger.debug("\u6E05\u9664\u6240\u6709\u63A5\u5165\u70B9");let e=Array.from(this.connections.keys()).map(t=>this.removeEndpoint(t));await Promise.allSettled(e),this.logger.info("\u6240\u6709\u63A5\u5165\u70B9\u5DF2\u6E05\u9664")}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.debug("\u5DF2\u8BBE\u7F6E MCPServiceManager"),this.connections.size>0&&this.syncToolsToAllConnections()}async triggerReconnect(e){let t=this.connectionStates.get(e);if(!t)throw new Error(`\u5C0F\u667A\u63A5\u5165\u70B9 ${e} \u4E0D\u5B58\u5728`);if(t.connected){this.logger.warn(`\u5C0F\u667A\u63A5\u5165\u70B9 ${C(e)} \u5DF2\u8FDE\u63A5\uFF0C\u65E0\u9700\u91CD\u8FDE`);return}this.logger.info(`\u624B\u52A8\u89E6\u53D1\u91CD\u8FDE: ${C(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(`\u5C0F\u667A\u63A5\u5165\u70B9 ${C(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\u5C0F\u667A\u63A5\u5165\u70B9 ${C(e)} \u7684\u91CD\u8FDE`))}stopAllReconnects(){this.logger.info("\u505C\u6B62\u6240\u6709\u5C0F\u667A\u63A5\u5165\u70B9\u7684\u91CD\u8FDE");for(let[e]of this.reconnectTimers)this.stopReconnect(e)}emitEndpointStatusChanged(e,t,r,n,o,s="connection-manager"){this.eventBus.emitEvent("endpoint:status:changed",{endpoint:e,connected:t,operation:r,success:n,message:o,timestamp:Date.now(),source:s})}async connectExistingEndpoint(e){if(!this.isInitialized)throw new Error("IndependentXiaozhiConnectionManager \u672A\u521D\u59CB\u5316");let t=this.connections.get(e);if(!t)throw new Error(`\u63A5\u5165\u70B9 ${C(e)} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u6DFB\u52A0\u63A5\u5165\u70B9`);if(this.connectionStates.get(e)?.connected){this.logger.debug(`\u63A5\u5165\u70B9 ${C(e)} \u5DF2\u8FDE\u63A5\uFF0C\u8DF3\u8FC7\u8FDE\u63A5`);return}this.logger.info(`\u8FDE\u63A5\u5DF2\u5B58\u5728\u7684\u63A5\u5165\u70B9: ${C(e)}`),await this.connectSingleEndpoint(e,t)}async sleep(e){return new Promise(t=>setTimeout(t,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};return e}validateEndpoints(e){let t=[],r=[];for(let n of e){if(!n||typeof n!="string"){r.push(n);continue}if(!n.startsWith("ws://")&&!n.startsWith("wss://")){r.push(n);continue}try{new URL(n),t.push(n)}catch{r.push(n)}}return{valid:t,invalid:r}}validateOptions(e){let t=Cs.safeParse(e);return t.success?{valid:!0,errors:[]}:{valid:!1,errors:t.error.errors.map(n=>n.message)}}async updateEndpoints(e,t=[]){if(!this.isInitialized)throw new Error("IndependentXiaozhiConnectionManager \u672A\u521D\u59CB\u5316");this.logger.info(`\u66F4\u65B0\u5C0F\u667A\u63A5\u5165\u70B9\u914D\u7F6E\uFF0C\u65B0\u5C0F\u667A\u63A5\u5165\u70B9\u6570\u91CF: ${e.length}`);let{valid:r,invalid:n}=this.validateEndpoints(e);if(n.length>0&&this.logger.warn(`\u53D1\u73B0\u65E0\u6548\u5C0F\u667A\u63A5\u5165\u70B9: ${n.join(", ")}`),r.length===0)throw new Error("\u6CA1\u6709\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9");let o=Array.from(this.connections.keys()),s=r.filter(g=>!o.includes(g)),a=o.filter(g=>!r.includes(g)),l=o.filter(g=>r.includes(g));this.logger.info(`\u5C0F\u667A\u63A5\u5165\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 g={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",g),this.logger.info("\u5C0F\u667A\u63A5\u5165\u70B9\u914D\u7F6E\u66F4\u65B0\u5B8C\u6210")}catch(g){throw this.logger.error("\u5C0F\u667A\u63A5\u5165\u70B9\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",g),g}}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 n={...this.options};this.options={...this.options,...e};let o={type:"options_updated",data:{oldOptions:n,newOptions:e},timestamp:new Date};this.emit("configChange",o),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}}async prewarmConnections(e=[]){let t=e.length>0?e:Array.from(this.connections.keys());this.logger.info(`\u5F00\u59CB\u9884\u70ED\u8FDE\u63A5\uFF0C\u5C0F\u667A\u63A5\u5165\u70B9\u6570\u91CF: ${t.length}`);let r=t.map(async n=>{try{this.connections.get(n)&&this.logger.debug(`\u5C0F\u667A\u63A5\u5165\u70B9 ${C(n)} \u9884\u70ED\u5B8C\u6210`)}catch(o){this.logger.warn(`\u5C0F\u667A\u63A5\u5165\u70B9 ${C(n)} \u9884\u70ED\u5931\u8D25:`,o)}});await Promise.all(r),this.logger.info("\u8FDE\u63A5\u9884\u70ED\u5B8C\u6210")}async cleanup(){this.logger.info("\u5F00\u59CB\u6E05\u7406 IndependentXiaozhiConnectionManager \u8D44\u6E90");try{await this.disconnect(),this.connections.clear(),this.connectionStates.clear(),this.isInitialized=!1,this.isConnecting=!1,this.logger.info("IndependentXiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(e){throw this.logger.error("IndependentXiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5931\u8D25:",e),e}}checkConfigDuplicate(e){try{return this.configManager.getMcpEndpoints().includes(e)}catch(t){return this.logger.error(`\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u91CD\u590D\u6027\u5931\u8D25: ${t}`),!0}}validateInitializeParams(e,t){if(!Array.isArray(e)||e.length===0)throw new Error("\u5C0F\u667A\u63A5\u5165\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\u5C0F\u667A\u63A5\u5165\u70B9\u5730\u5740: ${r}`);if(!r.startsWith("ws://")&&!r.startsWith("wss://"))throw new Error(`\u5C0F\u667A\u63A5\u5165\u70B9\u5730\u5740\u5FC5\u987B\u662F WebSocket URL: ${r}`)}}async createConnection(e,t){this.logger.debug(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B: ${C(e)}`);try{let r=new Ce(e);this.mcpServiceManager&&r.setServiceManager(this.mcpServiceManager),this.connections.set(e,r),this.connectionStates.set(e,{endpoint:e,connected:!1,initialized:!1,isReconnecting:!1,lastReconnectAttempt:void 0,reconnectDelay:this.options.reconnectInterval,reconnectAttempts:0,nextReconnectTime:void 0}),this.logger.debug(`\u8FDE\u63A5\u5B9E\u4F8B\u521B\u5EFA\u6210\u529F: ${C(e)}`)}catch(r){throw this.logger.error(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B\u5931\u8D25 ${C(e)}:`,r),r}}async connectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(!r)throw new Error(`\u5C0F\u667A\u63A5\u5165\u70B9\u72B6\u6001\u4E0D\u5B58\u5728: ${C(e)}`);this.logger.debug(`\u8FDE\u63A5\u5C0F\u667A\u63A5\u5165\u70B9: ${C(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,this.emitEndpointStatusChanged(e,!0,"connect",!0,"\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F","connection-manager"),this.logger.info(`\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F: ${C(e)}`)}catch(n){throw r.connected=!1,r.initialized=!1,r.lastError=n instanceof Error?n.message:String(n),r.reconnectAttempts++,this.emitEndpointStatusChanged(e,!1,"connect",!1,n instanceof Error?n.message:"\u8FDE\u63A5\u5931\u8D25","connection-manager"),this.logger.error(`\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25 ${C(e)}:`,n),this.scheduleReconnect(e),n}}async disconnectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(r){this.logger.debug(`\u65AD\u5F00\u5C0F\u667A\u63A5\u5165\u70B9: ${C(e)}`);try{t.disconnect(),r.connected=!1,r.initialized=!1,this.emitEndpointStatusChanged(e,!1,"disconnect",!0,"\u63A5\u5165\u70B9\u65AD\u5F00\u6210\u529F","connection-manager"),this.logger.debug(`\u5C0F\u667A\u63A5\u5165\u70B9\u65AD\u5F00\u6210\u529F: ${C(e)}`)}catch(n){this.logger.error(`\u5C0F\u667A\u63A5\u5165\u70B9\u65AD\u5F00\u5931\u8D25 ${C(e)}:`,n),r.connected=!1,r.initialized=!1,this.emitEndpointStatusChanged(e,!1,"disconnect",!1,n instanceof Error?n.message:"\u65AD\u5F00\u5931\u8D25","connection-manager")}}}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: ${C(e)}`)}catch(r){this.logger.error(`\u5DE5\u5177\u540C\u6B65\u5931\u8D25 ${C(e)}:`,r)}}}scheduleReconnect(e){let t=this.connectionStates.get(e);if(!t)return;if(t.reconnectAttempts>=this.options.maxReconnectAttempts){this.logger.warn(`\u505C\u6B62\u91CD\u8FDE ${C(e)}: \u8FBE\u5230\u6700\u5927\u91CD\u8FDE\u6B21\u6570`);return}let r=setTimeout(()=>{this.reconnectTimers.delete(e),this.performReconnect(e)},this.options.reconnectInterval);this.reconnectTimers.set(e,r)}async performReconnect(e){let t=this.connectionStates.get(e);if(!t)return;let r=this.connections.get(e);if(!r){this.logger.warn(`\u91CD\u8FDE\u65F6\u627E\u4E0D\u5230\u4EE3\u7406\u670D\u52A1\u5668: ${C(e)}`);return}try{t.isReconnecting=!0,t.lastReconnectAttempt=new Date;try{await r.disconnect()}catch(n){this.logger.debug(`\u65AD\u5F00\u8FDE\u63A5\u5931\u8D25\uFF08\u7EE7\u7EED\u91CD\u8FDE\uFF09: ${C(e)}:`,n)}await r.connect(),t.connected=!0,t.initialized=!0,t.lastConnected=new Date,t.lastError=void 0,t.reconnectAttempts=0,t.isReconnecting=!1,this.emitEndpointStatusChanged(e,!0,"reconnect",!0,"\u63A5\u5165\u70B9\u91CD\u8FDE\u6210\u529F","connection-manager"),this.logger.info(`\u91CD\u8FDE\u6210\u529F ${C(e)}`)}catch(n){t.connected=!1,t.initialized=!1,t.lastError=n instanceof Error?n.message:String(n),t.reconnectAttempts++,t.isReconnecting=!1,this.emitEndpointStatusChanged(e,!1,"reconnect",!1,n instanceof Error?n.message:"\u91CD\u8FDE\u5931\u8D25","connection-manager"),this.logger.error(`\u91CD\u8FDE\u5931\u8D25 ${C(e)}:`,n),this.scheduleReconnect(e)}}clearAllReconnectTimers(){for(let[,e]of this.reconnectTimers)clearTimeout(e);this.reconnectTimers.clear()}}});async function vs(i){if(console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 IndependentXiaozhiConnectionManager \u5355\u4F8B..."),i){let r=["loadBalanceStrategy","reconnectStrategy","maxReconnectDelay","reconnectBackoffMultiplier","jitterEnabled"].filter(n=>n in i);r.length>0&&(console.warn(`\u26A0\uFE0F \u68C0\u6D4B\u5230\u5E9F\u5F03\u7684\u914D\u7F6E\u9009\u9879: ${r.join(", ")}`),console.warn("\u8FD9\u4E9B\u914D\u7F6E\u9879\u5728\u72EC\u7ACB\u67B6\u6784\u4E2D\u5DF2\u88AB\u5FFD\u7565\uFF0C\u5EFA\u8BAE\u4ECE\u914D\u7F6E\u4E2D\u79FB\u9664"))}return new $t(h,i)}async function xn(i){if(le&&W==="initialized")return le;if(ee&&W==="initializing")return ee;W==="failed"&&Tr(),W="initializing",ee=vs(i);try{return le=await ee,W="initialized",Fe=`xiaozhi-connection-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,st=null,console.log(`\u2705 IndependentXiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${Fe}`),le}catch(e){throw W="failed",st=e,ee=null,console.error("\u274C IndependentXiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",e.message),e}}async function On(){if(W==="cleanup"){console.log("\u26A0\uFE0F IndependentXiaozhiConnectionManager \u5355\u4F8B\u5DF2\u5728\u6E05\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u91CD\u590D\u6E05\u7406");return}console.log("\u{1F9F9} \u6B63\u5728\u6E05\u7406 IndependentXiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90..."),W="cleanup";try{if(ee){try{await(await ee).cleanup()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}ee=null}le&&(await le.cleanup(),le=null),W="not_initialized",st=null,Fe=null,console.log("\u2705 IndependentXiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(i){throw console.error("\u274C IndependentXiaozhiConnectionManager \u5355\u4F8B\u6E05\u7406\u5931\u8D25:",i.message),Tr(),i}}function Tr(){console.log("\u{1F504} \u91CD\u7F6E IndependentXiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001..."),ee&&(ee=null),le=null,W="not_initialized",st=null,Fe=null,console.log("\u2705 IndependentXiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001\u5DF2\u91CD\u7F6E")}function Ss(){return W==="initialized"&&le!==null}function ys(){return{state:W,initializationTime:Fe?new Date:void 0,lastError:st||void 0,instanceId:Fe||void 0}}async function Es(i){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 IndependentXiaozhiConnectionManager \u5355\u4F8B..."),await On(),xn(i)}function Ts(){return le}async function Ms(){if(W==="initialized")return!0;if(W==="initializing"&&ee)try{return await ee,!0}catch{return!1}return!1}var le,ee,W,st,Fe,We,An=m(()=>{"use strict";q();$n();le=null,ee=null,W="not_initialized",st=null,Fe=null;c(vs,"createInstance");c(xn,"getInstance");c(On,"cleanup");c(Tr,"reset");c(Ss,"isInitialized");c(ys,"getStatus");c(Es,"forceReinitialize");c(Ts,"getCurrentInstance");c(Ms,"waitForInitialization");We={getInstance:xn,cleanup:On,reset:Tr,isInitialized:Ss,getStatus:ys,forceReinitialize:Es,getCurrentInstance:Ts,waitForInitialization:Ms};process.on("exit",()=>{We.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 IndependentXiaozhiConnectionManager \u5355\u4F8B..."),We.reset())});process.on("uncaughtException",async i=>{console.error("\u{1F4A5} \u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u6E05\u7406 IndependentXiaozhiConnectionManager \u5355\u4F8B:",i);try{await We.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 IndependentXiaozhiConnectionManager \u5355\u4F8B:",i);try{await We.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});var ge,it=m(()=>{"use strict";y();q();z();ge=class{static{c(this,"ConfigService")}logger;eventBus;constructor(){this.logger=p.withTag("ConfigService"),this.eventBus=M()}async getConfig(){try{let e=h.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!==h.getMcpEndpoint()&&h.updateMcpEndpoint(e.mcpEndpoint);let r=h.getMcpServers();for(let[n,o]of Object.entries(e.mcpServers))JSON.stringify(r[n])!==JSON.stringify(o)&&h.updateMcpServer(n,o);for(let n of Object.keys(r))n in e.mcpServers||(h.removeMcpServer(n),h.removeServerToolsConfig(n));if(e.connection&&h.updateConnectionConfig(e.connection),e.modelscope&&h.updateModelScopeConfig(e.modelscope),e.webUI&&h.updateWebUIConfig(e.webUI),e.mcpServerConfig)for(let[n,o]of Object.entries(e.mcpServerConfig))for(let[s,a]of Object.entries(o.tools))h.setToolEnabled(n,s,a.enable);if(e?.platforms)for(let[n,o]of Object.entries(e.platforms))h.updatePlatformConfig(n,o);this.logger.info("\u914D\u7F6E\u66F4\u65B0\u6210\u529F"),this.eventBus.emitEvent("config:updated",{type:"config",timestamp:new Date})}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 h.getMcpEndpoint()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",e),e}}getMcpEndpoints(){try{return h.getMcpEndpoints()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",e),e}}getMcpServers(){try{return h.getMcpServers()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",e),e}}getConnectionConfig(){try{return h.getConnectionConfig()}catch(e){throw this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",e),e}}getWebUIPort(){try{return h.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&&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 h.configExists()}async reloadConfig(){try{this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E"),h.reloadConfig();let e=await this.getConfig();return this.eventBus.emitEvent("config:updated",{type:"config",timestamp:new Date}),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 h.getConfigPath()}}});var xt,Nn=m(()=>{"use strict";y();it();xt=class{static{c(this,"ConfigApiHandler")}logger;configService;constructor(){this.logger=p.withTag("ConfigApiHandler"),this.configService=new ge}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 Ps(i,e=3,t=1e3){for(let r=1;r<=e;r++)try{return await i()}catch(n){if(r===e)throw n;let o=t*2**(r-1);p.warn(`\u6263\u5B50 API \u8C03\u7528\u5931\u8D25\uFF0C${o}ms \u540E\u91CD\u8BD5 (${r}/${e})`,n),await new Promise(s=>setTimeout(s,o))}throw new Error("Max retry attempts exceeded")}function ws(i,e){let t=i.status;return t===401?new pe("\u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6263\u5B50 API Token \u914D\u7F6E","AUTH_FAILED",401,e):t===429?new pe("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED",429,e):t>=500?new pe("\u6263\u5B50\u670D\u52A1\u5668\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","SERVER_ERROR",t,e):new pe(e?.msg||`API \u8C03\u7528\u5931\u8D25: ${i.statusText}`,"API_ERROR",t,e)}var Mr,pe,Ot,Dn=m(()=>{"use strict";y();Mr=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())}}},pe=class extends Error{static{c(this,"CozeApiErrorImpl")}code;statusCode;response;constructor(e,t,r,n){super(e),this.name="CozeApiError",this.code=t,this.statusCode=r,this.response=n}};c(Ps,"retryWithBackoff");c(ws,"handleCozeApiError");Ot=class{static{c(this,"CozeApiService")}cache=new Mr;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 p.debug("\u4ECE\u7F13\u5B58\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868"),t;p.info("\u83B7\u53D6\u6263\u5B50\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868");let r=await this.request("/v1/workspaces");if(r.code!==0)throw new pe(r.msg||"\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25","API_ERROR",void 0,r);let n=r.data.workspaces;return this.cache.set(e,n,"workspaces"),p.info(`\u6210\u529F\u83B7\u53D6 ${n.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),n}async getWorkflows(e){let{workspace_id:t,page_num:r=1,page_size:n=20}=e;if(!t||typeof t!="string")throw new Error("\u5DE5\u4F5C\u7A7A\u95F4ID\u4E0D\u80FD\u4E3A\u7A7A");let o=`workflows:${t}:${r}:${n}`,s=this.cache.get(o);if(s)return p.debug(`\u4ECE\u7F13\u5B58\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868: ${t}`),s;p.info(`\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684\u5DE5\u4F5C\u6D41\u5217\u8868 (\u9875\u7801: ${r}, \u6BCF\u9875: ${n})`);let a=new URLSearchParams({workspace_id:t,page_num:r.toString(),page_size:n.toString(),workflow_mode:"workflow"}),l=await this.request(`/v1/workflows?${a}`);if(l.code!==0)throw new pe(l.msg||"\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25","API_ERROR",void 0,l);let g={items:l.data.items,hasMore:l.data.has_more};return this.cache.set(o,g,"workflows"),p.info(`\u6210\u529F\u83B7\u53D6 ${g.items.length} \u4E2A\u5DE5\u4F5C\u6D41\uFF0ChasMore: ${g.hasMore}`),g}async request(e){return Ps(async()=>{let t=`${this.API_BASE_URL}${e}`;p.debug(`\u53D1\u8D77\u6263\u5B50 API \u8BF7\u6C42: ${t}`);let r=new AbortController,n=setTimeout(()=>r.abort(),this.TIMEOUT);try{let o=await fetch(t,{headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},signal:r.signal});clearTimeout(n);let s;try{s=await o.json()}catch(a){throw p.error("\u89E3\u6790\u54CD\u5E94 JSON \u5931\u8D25:",a),new pe("\u54CD\u5E94\u6570\u636E\u683C\u5F0F\u9519\u8BEF","PARSE_ERROR",o.status)}if(!o.ok)throw ws(o,s);return s}catch(o){throw clearTimeout(n),o instanceof Error&&o.name==="AbortError"?new pe(`\u8BF7\u6C42\u8D85\u65F6 (${this.TIMEOUT}ms)`,"TIMEOUT",void 0):o}},this.RETRY_ATTEMPTS)}clearCache(e){this.cache.clear(e),p.info(`\u6E05\u9664\u6263\u5B50 API \u7F13\u5B58${e?` (\u6A21\u5F0F: ${e})`:""}`)}getCacheStats(){return this.cache.getStats()}}});function At(i,e){return{success:!0,data:i,message:e}}function k(i,e,t){return{success:!1,message:i,error:e?{code:e,details:t}:void 0}}function Nt(){let i=h.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 Ot(i)}var Pe,kn=m(()=>{"use strict";y();q();Dn();c(At,"createSuccessResponse");c(k,"createErrorResponse");c(Nt,"getCozeApiService");Pe=class{static{c(this,"CozeApiHandler")}static async getWorkspaces(e){try{if(p.info("\u5904\u7406\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u8BF7\u6C42"),!h.isCozeConfigValid())return p.debug("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(k("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=await Nt().getWorkspaces();return p.info(`\u6210\u529F\u83B7\u53D6 ${r.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),e.json(At({workspaces:r}))}catch(t){return p.error("\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25:",t),t instanceof Error&&t.code==="AUTH_FAILED"?e.json(k("\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(k("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(k("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(k(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(p.info("\u5904\u7406\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u8BF7\u6C42"),!h.isCozeConfigValid())return p.debug("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(k("\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),n=Number.parseInt(e.req.query("page_size")||"20",10);if(!t)return p.warn("\u7F3A\u5C11 workspace_id \u53C2\u6570"),e.json(k("\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570: workspace_id","MISSING_PARAMETER"),400);if(r<1||r>1e3)return e.json(k("page_num \u5FC5\u987B\u5728 1-1000 \u4E4B\u95F4","INVALID_PARAMETER"),400);if(n<1||n>100)return e.json(k("page_size \u5FC5\u987B\u5728 1-100 \u4E4B\u95F4","INVALID_PARAMETER"),400);let o={workspace_id:t,page_num:r,page_size:n},a=await Nt().getWorkflows(o);p.info(`\u6210\u529F\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684 ${a.items.length} \u4E2A\u5DE5\u4F5C\u6D41`);let l=h.getCustomMCPTools(),g=a.items.map(u=>{let d=l.find(v=>v.handler.type==="proxy"&&v.handler.platform==="coze"&&v.handler.config.workflow_id===u.workflow_id);return{...u,isAddedAsTool:!!d,toolName:d?.name||null}});return p.info(`\u5DE5\u4F5C\u6D41\u5DE5\u5177\u72B6\u6001\u68C0\u67E5\u5B8C\u6210\uFF0C\u5171 ${g.filter(u=>u.isAddedAsTool).length} \u4E2A\u5DE5\u4F5C\u6D41\u5DF2\u6DFB\u52A0\u4E3A\u5DE5\u5177`),e.json(At({items:g,has_more:a.hasMore,page_num:r,page_size:n,total_count:a.items.length}))}catch(t){return p.error("\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25:",t),t instanceof Error&&t.code==="AUTH_FAILED"?e.json(k("\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(k("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(k("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(k(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(p.info("\u5904\u7406\u6E05\u9664\u6263\u5B50 API \u7F13\u5B58\u8BF7\u6C42"),!h.isCozeConfigValid())return p.debug("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(k("\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=Nt(),n=r.getCacheStats();r.clearCache(t);let o=r.getCacheStats();return p.info(`\u7F13\u5B58\u6E05\u9664\u5B8C\u6210\uFF0C\u6E05\u9664\u524D: ${n.size} \u9879\uFF0C\u6E05\u9664\u540E: ${o.size} \u9879`),e.json(At({cleared:n.size-o.size,remaining:o.size,pattern:t||"all"},"\u7F13\u5B58\u6E05\u9664\u6210\u529F"))}catch(t){return p.error("\u6E05\u9664\u7F13\u5B58\u5931\u8D25:",t),e.json(k(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(p.info("\u5904\u7406\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u8BF7\u6C42"),!h.isCozeConfigValid())return p.debug("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(k("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=Nt().getCacheStats();return e.json(At(r))}catch(t){return p.error("\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:",t),e.json(k(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 Dt,_n=m(()=>{"use strict";y();it();Dt=class{static{c(this,"HeartbeatHandler")}logger;statusService;notificationService;configService;constructor(e,t){this.logger=p.withTag("HeartbeatHandler"),this.statusService=e,this.notificationService=t,this.configService=new ge}async handleClientStatus(e,t,r){try{this.logger.debug(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0: ${r}`,t.data);let n={...t.data,lastHeartbeat:Date.now()};this.statusService.updateClientInfo(n,`websocket-${r}`),await this.sendLatestConfig(e,r),this.logger.debug(`\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u6210\u529F: ${r}`)}catch(n){this.logger.error(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25: ${r}`,n),this.sendError(e,"CLIENT_STATUS_ERROR",n instanceof Error?n.message:"\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25")}}async sendLatestConfig(e,t){try{let n={type:"configUpdate",data:await this.configService.getConfig(),timestamp:Date.now()};e.send(JSON.stringify(n)),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 n={type:"error",error:{code:t,message:r,timestamp:Date.now()}};e.send(JSON.stringify(n))}catch(n){this.logger.error("\u53D1\u9001\u9519\u8BEF\u6D88\u606F\u5931\u8D25:",n)}}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"}}});var de,Ln=m(()=>{"use strict";y();z();de=class{static{c(this,"MCPEndpointApiHandler")}logger;xiaozhiConnectionManager;configManager;eventBus;constructor(e,t){this.logger=p.withTag("MCPEndpointApiHandler"),this.xiaozhiConnectionManager=e,this.configManager=t,this.eventBus=M()}createErrorResponse(e,t,r,n){return{error:{code:e,message:t,details:r?{endpoint:r,...n}:n}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async getEndpointStatus(e){try{let t=decodeURIComponent(e.req.param("endpoint"));if(this.logger.debug(`\u5904\u7406\u83B7\u53D6\u63A5\u5165\u70B9\u72B6\u6001\u8BF7\u6C42: ${t}`),!t||typeof t!="string"){let o=this.createErrorResponse("INVALID_ENDPOINT","\u7AEF\u70B9\u53C2\u6570\u65E0\u6548",t);return e.json(o,400)}let n=this.xiaozhiConnectionManager.getConnectionStatus().find(o=>o.endpoint===t);if(!n){let o=this.createErrorResponse("ENDPOINT_NOT_FOUND","\u7AEF\u70B9\u4E0D\u5B58\u5728",t);return e.json(o,404)}return this.logger.debug(`\u83B7\u53D6\u63A5\u5165\u70B9\u72B6\u6001\u6210\u529F: ${t}`),e.json(this.createSuccessResponse(n))}catch(t){this.logger.error("\u83B7\u53D6\u63A5\u5165\u70B9\u72B6\u6001\u5931\u8D25:",t);let r=e.req.param("endpoint"),n=this.createErrorResponse("ENDPOINT_STATUS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u63A5\u5165\u70B9\u72B6\u6001\u5931\u8D25",r);return e.json(n,500)}}async connectEndpoint(e){try{let t=decodeURIComponent(e.req.param("endpoint"));if(this.logger.info(`\u5904\u7406\u63A5\u5165\u70B9\u8FDE\u63A5\u8BF7\u6C42: ${t}`),!t||typeof t!="string"){let l=this.createErrorResponse("INVALID_ENDPOINT","\u7AEF\u70B9\u53C2\u6570\u65E0\u6548",t);return e.json(l,400)}let n=this.xiaozhiConnectionManager.getConnectionStatus().find(l=>l.endpoint===t);if(!n){let l=this.createErrorResponse("ENDPOINT_NOT_FOUND","\u7AEF\u70B9\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u6DFB\u52A0\u63A5\u5165\u70B9",t);return e.json(l,404)}if(n.connected){let l=this.createErrorResponse("ENDPOINT_ALREADY_CONNECTED","\u7AEF\u70B9\u5DF2\u8FDE\u63A5",t);return e.json(l,409)}await this.xiaozhiConnectionManager.connectExistingEndpoint(t);let s=this.xiaozhiConnectionManager.getConnectionStatus().find(l=>l.endpoint===t);if(!s){let l=this.createErrorResponse("ENDPOINT_STATUS_NOT_FOUND","\u65E0\u6CD5\u83B7\u53D6\u7AEF\u70B9\u8FDE\u63A5\u72B6\u6001",t);return e.json(l,500)}this.eventBus.emitEvent("endpoint:status:changed",{endpoint:t,connected:!0,operation:"connect",success:!0,message:"\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F",timestamp:Date.now(),source:"http-api"}),this.logger.info(`\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F: ${t}`);let a=this.createSuccessResponse(s);return e.json(a)}catch(t){this.logger.error("\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",t);let r=e.req.param("endpoint"),n=this.createErrorResponse("ENDPOINT_CONNECT_ERROR",t instanceof Error?t.message:"\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25",r);return e.json(n,500)}}async disconnectEndpoint(e){try{let t=decodeURIComponent(e.req.param("endpoint"));if(this.logger.info(`\u5904\u7406\u63A5\u5165\u70B9\u65AD\u5F00\u8BF7\u6C42: ${t}`),!t||typeof t!="string"){let g=this.createErrorResponse("INVALID_ENDPOINT","\u7AEF\u70B9\u53C2\u6570\u65E0\u6548",t);return e.json(g,400)}let n=this.xiaozhiConnectionManager.getConnectionStatus().find(g=>g.endpoint===t);if(!n){let g=this.createErrorResponse("ENDPOINT_NOT_FOUND","\u7AEF\u70B9\u4E0D\u5B58\u5728",t);return e.json(g,404)}if(!n.connected){let g=this.createErrorResponse("ENDPOINT_NOT_CONNECTED","\u7AEF\u70B9\u672A\u8FDE\u63A5",t);return e.json(g,409)}await this.xiaozhiConnectionManager.disconnectEndpoint(t);let s=this.xiaozhiConnectionManager.getConnectionStatus().find(g=>g.endpoint===t);this.eventBus.emitEvent("endpoint:status:changed",{endpoint:t,connected:!1,operation:"disconnect",success:!0,message:"\u63A5\u5165\u70B9\u65AD\u5F00\u6210\u529F",timestamp:Date.now(),source:"http-api"}),this.logger.info(`\u63A5\u5165\u70B9\u65AD\u5F00\u6210\u529F: ${t}`);let a={endpoint:t,connected:!1,initialized:!0,isReconnecting:!1,reconnectAttempts:0,nextReconnectTime:void 0,reconnectDelay:0},l=this.createSuccessResponse(s||a);return e.json(l)}catch(t){this.logger.error("\u63A5\u5165\u70B9\u65AD\u5F00\u5931\u8D25:",t);let r=e.req.param("endpoint"),n=this.createErrorResponse("ENDPOINT_DISCONNECT_ERROR",t instanceof Error?t.message:"\u63A5\u5165\u70B9\u65AD\u5F00\u5931\u8D25",r);return e.json(n,500)}}async reconnectEndpoint(e){try{let t=decodeURIComponent(e.req.param("endpoint"));if(this.logger.info(`\u5904\u7406\u63A5\u5165\u70B9\u91CD\u8FDE\u8BF7\u6C42: ${t}`),!t||typeof t!="string"){let l=this.createErrorResponse("INVALID_ENDPOINT","\u7AEF\u70B9\u53C2\u6570\u65E0\u6548",t);return e.json(l,400)}let n=this.xiaozhiConnectionManager.getConnectionStatus().find(l=>l.endpoint===t);if(!n){let l=this.createErrorResponse("ENDPOINT_NOT_FOUND","\u7AEF\u70B9\u4E0D\u5B58\u5728",t);return e.json(l,404)}n.connected&&await this.xiaozhiConnectionManager.disconnectEndpoint(t),await this.xiaozhiConnectionManager.triggerReconnect(t);let s=this.xiaozhiConnectionManager.getConnectionStatus().find(l=>l.endpoint===t);if(!s){let l=this.createErrorResponse("ENDPOINT_STATUS_NOT_FOUND","\u65E0\u6CD5\u83B7\u53D6\u7AEF\u70B9\u8FDE\u63A5\u72B6\u6001",t);return e.json(l,500)}this.eventBus.emitEvent("endpoint:status:changed",{endpoint:t,connected:!0,operation:"reconnect",success:!0,message:"\u63A5\u5165\u70B9\u91CD\u8FDE\u6210\u529F",timestamp:Date.now(),source:"http-api"}),this.logger.info(`\u63A5\u5165\u70B9\u91CD\u8FDE\u6210\u529F: ${t}`);let a=this.createSuccessResponse(s);return e.json(a)}catch(t){this.logger.error("\u63A5\u5165\u70B9\u91CD\u8FDE\u5931\u8D25:",t);let r=e.req.param("endpoint"),n=this.createErrorResponse("ENDPOINT_RECONNECT_ERROR",t instanceof Error?t.message:"\u63A5\u5165\u70B9\u91CD\u8FDE\u5931\u8D25",r);return e.json(n,500)}}async addEndpoint(e){try{let r=(await e.req.json()).endpoint;if(!r||typeof r!="string"){let g=this.createErrorResponse("INVALID_ENDPOINT","\u7AEF\u70B9\u53C2\u6570\u65E0\u6548",r);return e.json(g,400)}if(this.xiaozhiConnectionManager.getConnectionStatus().find(g=>g.endpoint===r)){let g=this.createErrorResponse("ENDPOINT_ALREADY_EXISTS","\u63A5\u5165\u70B9\u5DF2\u5B58\u5728",r);return e.json(g,409)}await this.xiaozhiConnectionManager.addEndpoint(r);let a=this.xiaozhiConnectionManager.getConnectionStatus().find(g=>g.endpoint===r);if(!a){let g=this.createErrorResponse("ENDPOINT_STATUS_NOT_FOUND","\u65E0\u6CD5\u83B7\u53D6\u7AEF\u70B9\u72B6\u6001",r);return e.json(g,500)}this.eventBus.emitEvent("endpoint:status:changed",{endpoint:r,connected:!1,operation:"add",success:!0,message:"\u63A5\u5165\u70B9\u6DFB\u52A0\u6210\u529F",timestamp:Date.now(),source:"http-api"}),this.logger.info(`\u63A5\u5165\u70B9\u6DFB\u52A0\u6210\u529F: ${r}`);let l=this.createSuccessResponse(a);return e.json(l)}catch(t){this.logger.error("\u63A5\u5165\u70B9\u6DFB\u52A0\u5931\u8D25:",t);let r="ENDPOINT_ADD_ERROR",n=500;t instanceof Error&&(t.message.includes("\u5DF2\u5B58\u5728\u4E8E\u914D\u7F6E\u6587\u4EF6\u4E2D")?(r="ENDPOINT_ALREADY_IN_CONFIG",n=409):t.message.includes("\u5DF2\u5B58\u5728")?(r="ENDPOINT_ALREADY_EXISTS",n=409):t.message.includes("\u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")?(r="INVALID_ENDPOINT",n=400):t.message.includes("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A")&&(r="LAST_ENDPOINT_CANNOT_REMOVE",n=400));let o=this.createErrorResponse(r,t instanceof Error?t.message:"\u63A5\u5165\u70B9\u6DFB\u52A0\u5931\u8D25",void 0);return e.json(o,n)}}async removeEndpoint(e){try{let t=decodeURIComponent(e.req.param("endpoint"));if(this.logger.info(`\u5904\u7406\u63A5\u5165\u70B9\u79FB\u9664\u8BF7\u6C42: ${t}`),!t||typeof t!="string"){let s=this.createErrorResponse("INVALID_ENDPOINT","\u7AEF\u70B9\u53C2\u6570\u65E0\u6548",t);return e.json(s,400)}let n=this.xiaozhiConnectionManager.getConnectionStatus().find(s=>s.endpoint===t);if(!n){let s=this.createErrorResponse("ENDPOINT_NOT_FOUND","\u7AEF\u70B9\u4E0D\u5B58\u5728",t);return e.json(s,404)}n.connected&&await this.xiaozhiConnectionManager.disconnectEndpoint(t),await this.xiaozhiConnectionManager.removeEndpoint(t),this.eventBus.emitEvent("endpoint:status:changed",{endpoint:t,connected:!1,operation:"remove",success:!0,message:"\u63A5\u5165\u70B9\u79FB\u9664\u6210\u529F",timestamp:Date.now(),source:"http-api"}),this.logger.info(`\u63A5\u5165\u70B9\u79FB\u9664\u6210\u529F: ${t}`);let o=this.createSuccessResponse({endpoint:t,operation:"remove",success:!0,message:"\u63A5\u5165\u70B9\u79FB\u9664\u6210\u529F"});return e.json(o)}catch(t){this.logger.error("\u63A5\u5165\u70B9\u79FB\u9664\u5931\u8D25:",t);let r=e.req.param("endpoint"),n="ENDPOINT_REMOVE_ERROR",o=500;t instanceof Error&&(t.message.includes("\u4E0D\u5B58\u5728")?(n="ENDPOINT_NOT_FOUND",o=404):t.message.includes("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A")?(n="LAST_ENDPOINT_CANNOT_REMOVE",o=400):t.message.includes("\u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")&&(n="INVALID_ENDPOINT",o=400));let s=this.createErrorResponse(n,t instanceof Error?t.message:"\u63A5\u5165\u70B9\u79FB\u9664\u5931\u8D25",r);return e.json(s,o)}}}});import{randomUUID as bs}from"crypto";var kt,jn=m(()=>{"use strict";y();Cr();It();kt=class{static{c(this,"MCPRouteHandler")}logger;mcpMessageHandler=null;clients=new Map;config;metrics;cleanupInterval=null;startTime;constructor(e={}){this.logger=p.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,n]of this.clients.entries())(e.getTime()-n.lastActivity.getTime()>this.config.connectionTimeout||!n.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 X.getInstance();this.mcpMessageHandler=new je(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 n=e.req.query("sessionId");if(n)return await this.handleSSEMessage(e,n);let o=e.req.header("content-length");if(o&&Number.parseInt(o)>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 g;try{let v=await e.req.text();if(v.length>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);g=JSON.parse(v),r=g.id||null}catch{return this.metrics.errorCount++,this.createErrorResponse(-32700,"Parse error: Invalid JSON",null)}if(!this.validateMessage(g))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(g);this.metrics.totalMessages++;let d=Date.now()-t;return this.metrics.averageResponseTime=(this.metrics.averageResponseTime*(this.metrics.totalMessages-1)+d)/this.metrics.totalMessages,this.logger.debug("MCP POST \u8BF7\u6C42\u5904\u7406\u6210\u529F",{method:g.method,messageId:r,responseTime:d,isNotification:u===null}),u===null?new Response(null,{status:204,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":d.toString()}}):e.json(u,200,{"Content-Type":"application/json","MCP-Protocol-Version":"2024-11-05","X-Response-Time":d.toString()})}catch(n){this.metrics.errorCount++;let o=Date.now()-t;this.logger.error("\u5904\u7406 MCP POST \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:n instanceof Error?n.message:String(n),messageId:r,responseTime:o,stack:n instanceof Error?n.stack:void 0});let s=n instanceof Error?n.message:String(n);return this.createErrorResponse(-32603,`Internal error: ${s}`,r)}}async handleSSEMessage(e,t){let r=Date.now(),n=null;try{this.logger.debug(`\u5904\u7406 SSE \u6D88\u606F (\u4F1A\u8BDD: ${t})`);let o=this.clients.get(t);if(!o)return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Invalid or missing sessionId",null);o.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),n=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",n);await this.initializeMessageHandler();let l=await this.mcpMessageHandler.handleMessage(a);if(o.messageCount++,this.metrics.totalMessages++,l!==null&&o.writer&&o.isAlive)try{await this.sendSSEEvent(o.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),o.isAlive=!1}let g=Date.now()-r;return this.logger.debug(`SSE \u6D88\u606F\u5904\u7406\u5B8C\u6210 (\u4F1A\u8BDD: ${t})`,{method:a.method,messageId:n,responseTime:g,messageCount:o.messageCount,isNotification:l===null}),new Response(null,{status:202,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":g.toString()}})}catch(o){this.metrics.errorCount++;let s=Date.now()-r;this.logger.error(`\u5904\u7406 SSE \u6D88\u606F\u65F6\u51FA\u9519 (\u4F1A\u8BDD: ${t}):`,{error:o instanceof Error?o.message:String(o),messageId:n,responseTime:s,stack:o instanceof Error?o.stack:void 0});let a=o instanceof Error?o.message:String(o);return this.createErrorResponse(-32603,`Internal error: ${a}`,n)}}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=bs(),n=new Date,o=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:o,remoteAddress:s});let{readable:a,writable:l}=new TransformStream,g=l.getWriter(),u=new AbortController,d={id:t,sessionId:r,response:new Response(a),connectedAt:n,lastActivity:n,writer:g,abortController:u,isAlive:!0,messageCount:0,userAgent:o,remoteAddress:s};this.clients.set(r,d),this.metrics.totalConnections++,this.metrics.activeConnections=this.clients.size;try{await this.sendSSEEvent(g,"connected",JSON.stringify({sessionId:r,endpoint:`/mcp?sessionId=${r}`,timestamp:n.toISOString(),protocolVersion:"2024-11-05"}))}catch(I){this.logger.error(`\u521D\u59CB SSE \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25: ${r}`,I),d.isAlive=!1}this.startHeartbeat(d);let v=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),v}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 n=`event: ${t}
39
39
  data: ${r}
40
40
 
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 Nt,Lo=m(()=>{"use strict";y();st();K();Nt=class{static{c(this,"RealtimeNotificationHandler")}logger;notificationService;configService;statusService;eventBus;constructor(e,t){this.logger=g.withTag("RealtimeNotificationHandler"),this.notificationService=e,this.configService=new ge,this.statusService=t,this.eventBus=I()}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 _t}from"child_process";var Lt,Ho=m(()=>{"use strict";y();Mr();K();Lt=class{static{c(this,"ServiceApiHandler")}logger;statusService;eventBus;constructor(e){this.logger=g.withTag("ServiceApiHandler"),this.statusService=e,this.eventBus=I()}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 Pe()).get("serviceManager").getStatus();if(!r.running){this.logger.warn("MCP \u670D\u52A1\u672A\u8FD0\u884C\uFF0C\u5C1D\u8BD5\u542F\u52A8\u670D\u52A1"),_t("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"),_t("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"),_t("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"),_t("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 Pe()).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 Ht}from"fs";import{readFile as ws}from"fs/promises";import{dirname as bs,join as Se}from"path";import{fileURLToPath as Rs}from"url";var jt,jo=m(()=>{"use strict";y();jt=class{static{c(this,"StaticFileHandler")}logger;webPath=null;constructor(){this.logger=g.withTag("StaticFileHandler"),this.initializeWebPath()}initializeWebPath(){try{let e=bs(Rs(import.meta.url));this.logger.debug(`\u5F53\u524D\u6587\u4EF6\u76EE\u5F55: ${e}`);let t=[Se(e,"..","..","web","dist"),Se(e,"..","web","dist"),Se(e,"..","..","web"),Se(e,"..","web"),Se(e,"..","..","..","web","dist"),Se(e,"..","..","..","web")];this.webPath=t.find(r=>{let o=Ht(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=Se(this.webPath,r);if(!Ht(o)){let s=Se(this.webPath,"index.html");return Ht(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 ws(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=`
41
+ `;await e.write(new TextEncoder().encode(n))}catch(n){throw this.logger.error("\u53D1\u9001 SSE \u4E8B\u4EF6\u5931\u8D25:",n),n}}handleClientDisconnect(e,t){let r=this.clients.get(e);if(!r)return;let n=Date.now()-r.connectedAt.getTime();this.logger.info(`SSE \u5BA2\u6237\u7AEF\u65AD\u5F00\u8FDE\u63A5: ${r.id} (\u4F1A\u8BDD: ${e})`,{reason:t,duration:n,messageCount:r.messageCount,userAgent:r.userAgent,remoteAddress:r.remoteAddress}),this.stopHeartbeat(r),r.abortController&&r.abortController.abort();try{r.writer&&r.writer.close()}catch(o){this.logger.debug("\u5173\u95ED SSE writer \u65F6\u51FA\u9519:",o)}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 n={jsonrpc:"2.0",error:{code:e,message:t},id:r};return new Response(JSON.stringify(n),{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),n=[];for(let[o,s]of this.clients.entries()){if(!s.isAlive||!s.writer){n.push(o);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: ${o}`,a),s.isAlive=!1,n.push(o)}}for(let o of n)this.handleClientDisconnect(o,"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 _t,Hn=m(()=>{"use strict";y();it();z();_t=class{static{c(this,"RealtimeNotificationHandler")}logger;notificationService;configService;statusService;eventBus;constructor(e,t){this.logger=p.withTag("RealtimeNotificationHandler"),this.notificationService=e,this.configService=new ge,this.statusService=t,this.eventBus=M()}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(n){this.logger.error(`\u5904\u7406 WebSocket \u6D88\u606F\u5931\u8D25: ${t.type}`,n),this.sendError(e,"MESSAGE_PROCESSING_ERROR",n instanceof Error?n.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(n){this.logger.error("WebSocket: updateConfig \u8BF7\u6C42\u5904\u7406\u5931\u8D25",n),this.sendError(e,"CONFIG_UPDATE_ERROR",n instanceof Error?n.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 n={type:"error",error:{code:t,message:r,timestamp:Date.now()}};e.send(JSON.stringify(n))}catch(n){this.logger.error("\u53D1\u9001\u9519\u8BEF\u6D88\u606F\u5931\u8D25:",n)}}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 n=this.statusService.getFullStatus();e.send(JSON.stringify({type:"statusUpdate",data:n.client})),n.restart&&e.send(JSON.stringify({type:"restartStatus",data:n.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 Lt}from"child_process";var jt,zn=m(()=>{"use strict";y();Pr();z();jt=class{static{c(this,"ServiceApiHandler")}logger;statusService;eventBus;constructor(e){this.logger=p.withTag("ServiceApiHandler"),this.statusService=e,this.eventBus=M()}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 we()).get("serviceManager").getStatus();if(!r.running){this.logger.warn("MCP \u670D\u52A1\u672A\u8FD0\u884C\uFF0C\u5C1D\u8BD5\u542F\u52A8\u670D\u52A1"),Lt("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 n=r.mode==="daemon",o=["restart"];n&&o.push("--daemon"),Lt("xiaozhi",o,{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"),Lt("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"),Lt("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 n=await(await we()).get("serviceManager").getStatus();return this.logger.debug("\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(n))}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 Ht}from"fs";import{readFile as Rs}from"fs/promises";import{dirname as Is,join as ye}from"path";import{fileURLToPath as $s}from"url";var zt,Un=m(()=>{"use strict";y();zt=class{static{c(this,"StaticFileHandler")}logger;webPath=null;constructor(){this.logger=p.withTag("StaticFileHandler"),this.initializeWebPath()}initializeWebPath(){try{let e=Is($s(import.meta.url));this.logger.debug(`\u5F53\u524D\u6587\u4EF6\u76EE\u5F55: ${e}`);let t=[ye(e,"..","..","web","dist"),ye(e,"..","web","dist"),ye(e,"..","..","web"),ye(e,"..","web"),ye(e,"..","..","..","web","dist"),ye(e,"..","..","..","web")];this.webPath=t.find(r=>{let n=Ht(r);return this.logger.debug(`\u68C0\u67E5\u8DEF\u5F84 ${r}: ${n?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}`),n})||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 n=ye(this.webPath,r);if(!Ht(n)){let s=ye(this.webPath,"index.html");return Ht(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: ${n}`),e.text("Not Found",404))}let o=this.getContentType(n);return this.logger.debug(`\u670D\u52A1\u9759\u6001\u6587\u4EF6: ${n}, Content-Type: ${o}`),this.serveFile(e,n,o)}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 n=await Rs(t);return r.startsWith("text/")||r.includes("javascript")||r.includes("json")?e.text(n.toString(),200,{"Content-Type":r}):e.body(new Uint8Array(n),200,{"Content-Type":r})}catch(n){throw this.logger.error(`\u8BFB\u53D6\u6587\u4EF6\u5931\u8D25: ${t}`,n),n}}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=`
42
42
  <!DOCTYPE html>
43
43
  <html>
44
44
  <head>
@@ -93,7 +93,7 @@ data: ${r}
93
93
  </div>
94
94
  </body>
95
95
  </html>
96
- `;return e.html(r)}isWebPathAvailable(){return this.webPath!==null&&Ht(this.webPath)}getWebPath(){return this.webPath}reinitializeWebPath(){this.initializeWebPath()}}});var zt,zo=m(()=>{"use strict";y();zt=class{static{c(this,"StatusApiHandler")}logger;statusService;constructor(e){this.logger=g.withTag("StatusApiHandler"),this.statusService=e}createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async getStatus(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u72B6\u6001\u8BF7\u6C42");let t=this.statusService.getFullStatus();return this.logger.debug("\u83B7\u53D6\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("STATUS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}async getClientStatus(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u5BA2\u6237\u7AEF\u72B6\u6001\u8BF7\u6C42");let t=this.statusService.getClientStatus();return this.logger.debug("\u83B7\u53D6\u5BA2\u6237\u7AEF\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u5BA2\u6237\u7AEF\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("CLIENT_STATUS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u5BA2\u6237\u7AEF\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}async getRestartStatus(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u91CD\u542F\u72B6\u6001\u8BF7\u6C42");let t=this.statusService.getRestartStatus();return this.logger.debug("\u83B7\u53D6\u91CD\u542F\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u91CD\u542F\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("RESTART_STATUS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u91CD\u542F\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}async checkClientConnected(e){try{this.logger.debug("\u5904\u7406\u68C0\u67E5\u5BA2\u6237\u7AEF\u8FDE\u63A5\u8BF7\u6C42");let t=this.statusService.isClientConnected();return this.logger.debug(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u72B6\u6001: ${t}`),e.json(this.createSuccessResponse({connected:t}))}catch(t){this.logger.error("\u68C0\u67E5\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5931\u8D25:",t);let r=this.createErrorResponse("CLIENT_CONNECTION_CHECK_ERROR",t instanceof Error?t.message:"\u68C0\u67E5\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5931\u8D25");return e.json(r,500)}}async getLastHeartbeat(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u6700\u540E\u5FC3\u8DF3\u65F6\u95F4\u8BF7\u6C42");let t=this.statusService.getLastHeartbeat();return this.logger.debug("\u83B7\u53D6\u6700\u540E\u5FC3\u8DF3\u65F6\u95F4\u6210\u529F"),e.json(this.createSuccessResponse({lastHeartbeat:t}))}catch(t){this.logger.error("\u83B7\u53D6\u6700\u540E\u5FC3\u8DF3\u65F6\u95F4\u5931\u8D25:",t);let r=this.createErrorResponse("HEARTBEAT_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u6700\u540E\u5FC3\u8DF3\u65F6\u95F4\u5931\u8D25");return e.json(r,500)}}async getActiveMCPServers(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u8BF7\u6C42");let t=this.statusService.getActiveMCPServers();return this.logger.debug("\u83B7\u53D6\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u6210\u529F"),e.json(this.createSuccessResponse({servers:t}))}catch(t){this.logger.error("\u83B7\u53D6\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u5931\u8D25:",t);let r=this.createErrorResponse("ACTIVE_MCP_SERVERS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u5931\u8D25");return e.json(r,500)}}async updateClientStatus(e){try{this.logger.debug("\u5904\u7406\u66F4\u65B0\u5BA2\u6237\u7AEF\u72B6\u6001\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\u72B6\u6001\u5BF9\u8C61");return e.json(r,400)}return this.statusService.updateClientInfo(t,"http-api"),this.logger.info("\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u6210\u529F"),e.json(this.createSuccessResponse(null,"\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u6210\u529F"))}catch(t){this.logger.error("\u66F4\u65B0\u5BA2\u6237\u7AEF\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("CLIENT_STATUS_UPDATE_ERROR",t instanceof Error?t.message:"\u66F4\u65B0\u5BA2\u6237\u7AEF\u72B6\u6001\u5931\u8D25");return e.json(r,400)}}async setActiveMCPServers(e){try{this.logger.debug("\u5904\u7406\u8BBE\u7F6E\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u8BF7\u6C42");let{servers:t}=await e.req.json();if(!Array.isArray(t)){let r=this.createErrorResponse("INVALID_REQUEST_BODY","servers \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4");return e.json(r,400)}return this.statusService.setActiveMCPServers(t),this.logger.info("\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u8BBE\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(null,"\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u8BBE\u7F6E\u6210\u529F"))}catch(t){this.logger.error("\u8BBE\u7F6E\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u5931\u8D25:",t);let r=this.createErrorResponse("ACTIVE_MCP_SERVERS_UPDATE_ERROR",t instanceof Error?t.message:"\u8BBE\u7F6E\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u5931\u8D25");return e.json(r,400)}}async resetStatus(e){try{return this.logger.info("\u5904\u7406\u91CD\u7F6E\u72B6\u6001\u8BF7\u6C42"),this.statusService.reset(),this.logger.info("\u72B6\u6001\u91CD\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(null,"\u72B6\u6001\u91CD\u7F6E\u6210\u529F"))}catch(t){this.logger.error("\u91CD\u7F6E\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("STATUS_RESET_ERROR",t instanceof Error?t.message:"\u91CD\u7F6E\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}}});var We,Uo=m(()=>{"use strict";We=(o=>(o.MCP="mcp",o.COZE="coze",o.HTTP="http",o.FUNCTION="function",o))(We||{})});import Is from"ajv";import Ut from"dayjs";var Ft,Fo=m(()=>{"use strict";y();Z();Tt();Rt();Uo();Ft=class{static{c(this,"ToolApiHandler")}logger;ajv;constructor(){this.logger=g.withTag("ToolApiHandler"),this.ajv=new Is({allErrors:!0,verbose:!0})}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}createErrorResponse(e,t){return{success:!1,error:{code:e,message:t}}}async callTool(e){try{this.logger.info("\u5904\u7406\u5DE5\u5177\u8C03\u7528\u8BF7\u6C42");let t=await e.req.json(),{serviceName:r,toolName:o,args:n}=t;if(!r||!o){let l=this.createErrorResponse("INVALID_REQUEST","serviceName \u548C toolName \u662F\u5FC5\u9700\u7684\u53C2\u6570");return e.json(l,400)}if(this.logger.info(`\u51C6\u5907\u8C03\u7528\u5DE5\u5177: ${r}/${o}\uFF0C\u53C2\u6570:`,JSON.stringify(n)),!q.isInitialized()){let l=this.createErrorResponse("SERVICE_NOT_INITIALIZED","MCP \u670D\u52A1\u7BA1\u7406\u5668\u672A\u521D\u59CB\u5316\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002");return e.json(l,503)}let s=await q.getInstance();await this.validateServiceAndTool(s,r,o),r==="customMCP"&&await this.validateCustomMCPArguments(s,o,n||{});let a;if(r==="customMCP")a=await s.callTool(o,n||{});else{let l=`${r}__${o}`;a=await s.callTool(l,n||{})}return e.json(this.createSuccessResponse(a,"\u5DE5\u5177\u8C03\u7528\u6210\u529F"))}catch(t){this.logger.error("\u5DE5\u5177\u8C03\u7528\u5931\u8D25:",t);let r=t instanceof Error?t.message:String(t),o="TOOL_CALL_ERROR";r.includes("\u4E0D\u5B58\u5728")?o="SERVICE_OR_TOOL_NOT_FOUND":r.includes("\u672A\u542F\u52A8")||r.includes("\u672A\u8FDE\u63A5")?o="SERVICE_NOT_AVAILABLE":r.includes("\u5DF2\u88AB\u7981\u7528")?o="TOOL_DISABLED":r.includes("\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25")?o="INVALID_ARGUMENTS":r.includes("CustomMCP")||r.includes("customMCP")?o="CUSTOM_MCP_ERROR":r.includes("\u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25")||r.includes("API \u8BF7\u6C42\u5931\u8D25")?o="EXTERNAL_API_ERROR":r.includes("\u8D85\u65F6")&&(o="TIMEOUT_ERROR");let n=this.createErrorResponse(o,r);return e.json(n,500)}}async getCustomTools(e){try{if(this.logger.info("\u5904\u7406\u83B7\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u5217\u8868\u8BF7\u6C42"),!u.configExists()){let n=this.createErrorResponse("CONFIG_NOT_FOUND","\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C 'xiaozhi init' \u521D\u59CB\u5316\u914D\u7F6E");return e.json(n,404)}let t=[],r="";try{t=u.getCustomMCPTools(),r=u.getConfigPath()}catch(n){this.logger.error("\u8BFB\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u914D\u7F6E\u5931\u8D25:",n);let s=this.createErrorResponse("CONFIG_PARSE_ERROR",`\u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${n instanceof Error?n.message:"\u672A\u77E5\u9519\u8BEF"}`);return e.json(s,500)}if(!t||t.length===0)return this.logger.info("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177"),e.json(this.createSuccessResponse({tools:[],totalTools:0,configPath:r},"\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177"));if(!u.validateCustomMCPTools(t)){this.logger.warn("\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");let n=this.createErrorResponse("INVALID_TOOL_CONFIG","\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u5DE5\u5177\u5B9A\u4E49");return e.json(n,400)}return this.logger.info(`\u83B7\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u5217\u8868\u6210\u529F\uFF0C\u5171 ${t.length} \u4E2A\u5DE5\u5177`),e.json(this.createSuccessResponse({tools:t,totalTools:t.length,configPath:r},"\u83B7\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u5217\u8868\u6210\u529F"))}catch(t){this.logger.error("\u83B7\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u5217\u8868\u5931\u8D25:",t);let r=this.createErrorResponse("GET_CUSTOM_TOOLS_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u5217\u8868\u5931\u8D25");return e.json(r,500)}}async listTools(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u8BF7\u6C42");let t=e.req.query("status")||"all",r=[];switch(t){case"enabled":r=u.getCustomMCPTools(),this.logger.debug(`\u83B7\u53D6\u5DF2\u542F\u7528\u5DE5\u5177\uFF0C\u5171 ${r.length} \u4E2A`);break;case"disabled":r=await this.getDisabledTools(),this.logger.debug(`\u83B7\u53D6\u672A\u542F\u7528\u5DE5\u5177\uFF0C\u5171 ${r.length} \u4E2A`);break;default:r=u.getCustomMCPTools(),this.logger.debug(`\u83B7\u53D6\u6240\u6709\u5DE5\u5177\uFF0C\u5171 ${r.length} \u4E2A`);break}let o={list:r,total:r.length};return e.json(this.createSuccessResponse(o,`\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u6210\u529F\uFF08${t}\uFF09`))}catch(t){this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25:",t);let r=this.createErrorResponse("GET_TOOLS_FAILED","\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25");return e.json(r,500)}}async getDisabledTools(){try{let e=u.getCustomMCPTools(),t=new Set(e.map(l=>l.name)),o=await new pe().getAllCachedTools(),n=u.getConfig(),s=new Set(Object.keys(n.mcpServers||{})),a=[];for(let l of o){if(t.has(l.name))continue;let h=l.name.split("__")[0];if(!s.has(h)){this.logger.debug(`\u5DE5\u5177 ${l.name} \u5BF9\u5E94\u7684 MCP \u670D\u52A1 ${h} \u5DF2\u5220\u9664\uFF0C\u8DF3\u8FC7\u663E\u793A`);continue}let p={name:l.name,description:l.description||"",inputSchema:l.inputSchema||{},handler:{type:"mcp",config:{serviceName:h,toolName:l.name.split("__").slice(1).join("__")}}};a.push(p)}return this.logger.debug(`\u4ECE ${o.length} \u4E2A\u7F13\u5B58\u5DE5\u5177\u4E2D\u7B5B\u9009\u51FA ${a.length} \u4E2A\u672A\u542F\u7528\u5DE5\u5177`),a}catch(e){return this.logger.error("\u83B7\u53D6\u672A\u542F\u7528\u5DE5\u5177\u5931\u8D25:",e),[]}}async validateServiceAndTool(e,t,r){if(t==="customMCP"){if(!e.hasCustomMCPTool(r)){let o=e.getCustomMCPTools().map(n=>n.name);throw o.length===0?new Error(`customMCP \u5DE5\u5177 '${r}' \u4E0D\u5B58\u5728\u3002\u5F53\u524D\u6CA1\u6709\u914D\u7F6E\u4EFB\u4F55 customMCP \u5DE5\u5177\u3002\u8BF7\u68C0\u67E5 xiaozhi.config.json \u4E2D\u7684 customMCP \u914D\u7F6E\u3002`):new Error(`customMCP \u5DE5\u5177 '${r}' \u4E0D\u5B58\u5728\u3002\u53EF\u7528\u7684 customMCP \u5DE5\u5177: ${o.join(", ")}\u3002\u8BF7\u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u5DE5\u5177\u3002`)}try{let n=e.getCustomMCPTools().find(s=>s.name===r);n&&!n.description&&this.logger.warn(`customMCP \u5DE5\u5177 '${r}' \u7F3A\u5C11\u63CF\u8FF0\u4FE1\u606F`),n&&!n.inputSchema&&this.logger.warn(`customMCP \u5DE5\u5177 '${r}' \u7F3A\u5C11\u8F93\u5165\u53C2\u6570\u5B9A\u4E49`)}catch(o){throw this.logger.error(`\u9A8C\u8BC1 customMCP \u5DE5\u5177 '${r}' \u914D\u7F6E\u65F6\u51FA\u9519:`,o),new Error(`customMCP \u5DE5\u5177 '${r}' \u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25\u3002\u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u5DE5\u5177\u5B9A\u4E49\u3002`)}return}}async validateCustomMCPArguments(e,t,r){try{let n=e.getCustomMCPTools().find(l=>l.name===t);if(!n)throw new Error(`customMCP \u5DE5\u5177 '${t}' \u4E0D\u5B58\u5728`);if(!n.inputSchema){this.logger.warn(`customMCP \u5DE5\u5177 '${t}' \u6CA1\u6709\u5B9A\u4E49 inputSchema\uFF0C\u8DF3\u8FC7\u53C2\u6570\u9A8C\u8BC1`);return}let s=this.ajv.compile(n.inputSchema);if(!s(r)){let p=`\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25: ${(s.errors||[]).map(d=>{let C=d.instancePath||d.schemaPath||"",E=d.message||"\u672A\u77E5\u9519\u8BEF";if(d.keyword==="required")return`\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570: ${d.params?.missingProperty||"\u672A\u77E5\u5B57\u6BB5"}`;if(d.keyword==="type"){let R=d.params?.type||"\u672A\u77E5\u7C7B\u578B";return`\u53C2\u6570 ${C} \u7C7B\u578B\u9519\u8BEF\uFF0C\u671F\u671B: ${R}`}if(d.keyword==="enum"){let R=d.params?.allowedValues||[];return`\u53C2\u6570 ${C} \u503C\u65E0\u6548\uFF0C\u5141\u8BB8\u7684\u503C: ${R.join(", ")}`}return`\u53C2\u6570 ${C} ${E}`}).join("; ")}`;throw this.logger.error(`customMCP \u5DE5\u5177 '${t}' \u53C2\u6570\u9A8C\u8BC1\u5931\u8D25:`,p),new Error(p)}this.logger.debug(`customMCP \u5DE5\u5177 '${t}' \u53C2\u6570\u9A8C\u8BC1\u901A\u8FC7`)}catch(o){throw o instanceof Error&&o.message.includes("\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25")?o:(this.logger.error(`\u9A8C\u8BC1 customMCP \u5DE5\u5177 '${t}' \u53C2\u6570\u65F6\u51FA\u9519:`,o),new Error(`\u53C2\u6570\u9A8C\u8BC1\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF: ${o instanceof Error?o.message:"\u672A\u77E5\u9519\u8BEF"}`))}}async addCustomTool(e){try{this.logger.info("\u5904\u7406\u6DFB\u52A0\u81EA\u5B9A\u4E49\u5DE5\u5177\u8BF7\u6C42");let t=await e.req.json();return this.isNewFormatRequest(t)?await this.handleNewFormatAddTool(e,t):await this.handleLegacyFormatAddTool(e,t)}catch(t){this.logger.error("\u6DFB\u52A0\u81EA\u5B9A\u4E49\u5DE5\u5177\u5931\u8D25:",t);let{statusCode:r,errorResponse:o}=this.handleAddToolError(t);return e.json(o,r)}}isNewFormatRequest(e){return e&&typeof e=="object"&&"type"in e&&"data"in e}async handleNewFormatAddTool(e,t){let{type:r,data:o}=t;if(this.logger.info(`\u5904\u7406\u65B0\u683C\u5F0F\u5DE5\u5177\u6DFB\u52A0\u8BF7\u6C42\uFF0C\u7C7B\u578B: ${r}`),!Object.values(We).includes(r)){let n=this.createErrorResponse("INVALID_TOOL_TYPE",`\u4E0D\u652F\u6301\u7684\u5DE5\u5177\u7C7B\u578B: ${r}\u3002\u652F\u6301\u7684\u7C7B\u578B: ${Object.values(We).join(", ")}`);return e.json(n,400)}switch(r){case"mcp":return await this.handleAddMCPTool(e,o);case"coze":return await this.handleAddCozeTool(e,o);case"http":case"function":{let n=this.createErrorResponse("TOOL_TYPE_NOT_IMPLEMENTED",`\u5DE5\u5177\u7C7B\u578B ${r} \u6682\u672A\u5B9E\u73B0\uFF0C\u8BF7\u4F7F\u7528 MCP \u6216 Coze \u7C7B\u578B`);return e.json(n,501)}default:{let n=this.createErrorResponse("UNKNOWN_TOOL_TYPE",`\u672A\u77E5\u7684\u5DE5\u5177\u7C7B\u578B: ${r}`);return e.json(n,400)}}}async handleLegacyFormatAddTool(e,t){this.logger.info("\u5904\u7406\u65E7\u683C\u5F0F\u5DE5\u5177\u6DFB\u52A0\u8BF7\u6C42\uFF08\u5411\u540E\u517C\u5BB9\uFF09");let{workflow:r,customName:o,customDescription:n,parameterConfig:s}=t,a=this.performPreChecks(r,o,n);if(a)return e.json(a.errorResponse,a.statusCode);let l=this.convertWorkflowToTool(r,o,n,s);return u.addCustomMCPTool(l),this.logger.info(`\u6210\u529F\u6DFB\u52A0\u81EA\u5B9A\u4E49\u5DE5\u5177: ${l.name}`),e.json(this.createSuccessResponse({tool:l},`\u5DE5\u5177 "${l.name}" \u6DFB\u52A0\u6210\u529F`))}async handleAddMCPTool(e,t){let{serviceName:r,toolName:o,customName:n,customDescription:s}=t;if(this.logger.info(`\u5904\u7406\u6DFB\u52A0 MCP \u5DE5\u5177: ${r}/${o}`),!r||!o){let A=this.createErrorResponse("MISSING_REQUIRED_FIELD","serviceName \u548C toolName \u662F\u5FC5\u9700\u5B57\u6BB5");return e.json(A,400)}if(!q.isInitialized()){let A=this.createErrorResponse("SERVICE_NOT_INITIALIZED","MCP \u670D\u52A1\u7BA1\u7406\u5668\u672A\u521D\u59CB\u5316\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002");return e.json(A,503)}let a=await q.getInstance();try{await this.validateServiceAndTool(a,r,o)}catch(A){let at=A instanceof Error?A.message:String(A),re=this.createErrorResponse("SERVICE_OR_TOOL_NOT_FOUND",at);return e.json(re,404)}let h=await new pe().getAllCachedTools(),p=`${r}__${o}`,d=h.find(A=>A.name===p);if(!d){let A=this.createErrorResponse("TOOL_NOT_FOUND",`\u5728\u7F13\u5B58\u4E2D\u672A\u627E\u5230\u5DE5\u5177: ${r}/${o}`);return e.json(A,404)}let C=n||p,E=u.getCustomMCPTools();if(new Set(E.map(A=>A.name)).has(C)){let A=this.createErrorResponse("TOOL_NAME_CONFLICT",`\u5DE5\u5177\u540D\u79F0 "${C}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u4F7F\u7528\u4E0D\u540C\u7684\u81EA\u5B9A\u4E49\u540D\u79F0`);return e.json(A,409)}let J={name:C,description:s||d.description||`MCP \u5DE5\u5177: ${r}/${o}`,inputSchema:d.inputSchema||{},handler:{type:"mcp",config:{serviceName:r,toolName:o}},stats:{usageCount:0,lastUsedTime:Ut().format("YYYY-MM-DD HH:mm:ss")}};u.addCustomMCPTool(J),this.logger.info(`\u68C0\u6D4B\u5230 MCP \u5DE5\u5177\u6DFB\u52A0\uFF0C\u540C\u6B65\u542F\u7528 mcpServerConfig \u4E2D\u7684\u5DE5\u5177: ${r}/${o}`);let V=u.getServerToolsConfig(r);V?.toolName&&(V[o].enable=!0,u.updateServerToolsConfig(r,V),this.logger.info(`\u5DF2\u540C\u6B65\u542F\u7528 mcpServerConfig \u4E2D\u7684\u5DE5\u5177: ${r}/${o}`)),this.logger.info(`\u6210\u529F\u6DFB\u52A0 MCP \u5DE5\u5177: ${C}`);let it={tool:J,toolName:C,toolType:"mcp",addedAt:Ut().format("YYYY-MM-DD HH:mm:ss")};return e.json(this.createSuccessResponse(it,`MCP \u5DE5\u5177 "${C}" \u6DFB\u52A0\u6210\u529F`))}async handleAddCozeTool(e,t){let{workflow:r,customName:o,customDescription:n,parameterConfig:s}=t;this.logger.info(`\u5904\u7406\u6DFB\u52A0 Coze \u5DE5\u5177: ${r.workflow_name}`);let a=this.performPreChecks(r,o,n);if(a)return e.json(a.errorResponse,a.statusCode);let l=this.convertWorkflowToTool(r,o,n,s);u.addCustomMCPTool(l),this.logger.info(`\u6210\u529F\u6DFB\u52A0 Coze \u5DE5\u5177: ${l.name}`);let h={tool:l,toolName:l.name,toolType:"coze",addedAt:Ut().format("YYYY-MM-DD HH:mm:ss")};return e.json(this.createSuccessResponse(h,`Coze \u5DE5\u5177 "${l.name}" \u6DFB\u52A0\u6210\u529F`))}async updateCustomTool(e){try{let t=e.req.param("toolName");if(!t){let n=this.createErrorResponse("INVALID_REQUEST","\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");return e.json(n,400)}this.logger.info(`\u5904\u7406\u66F4\u65B0\u81EA\u5B9A\u4E49\u5DE5\u5177\u914D\u7F6E\u8BF7\u6C42: ${t}`);let r=await e.req.json();if(!r||typeof r!="object"){let n=this.createErrorResponse("INVALID_REQUEST","\u8BF7\u6C42\u4F53\u5FC5\u987B\u662F\u6709\u6548\u5BF9\u8C61");return e.json(n,400)}if(this.isNewFormatRequest(r))return await this.handleNewFormatUpdateTool(e,t,r);let o=this.createErrorResponse("INVALID_REQUEST","\u66F4\u65B0\u64CD\u4F5C\u53EA\u652F\u6301\u65B0\u683C\u5F0F\u7684\u8BF7\u6C42");return e.json(o,400)}catch(t){this.logger.error("\u66F4\u65B0\u81EA\u5B9A\u4E49\u5DE5\u5177\u914D\u7F6E\u5931\u8D25:",t);let{statusCode:r,errorResponse:o}=this.handleUpdateToolError(t);return e.json(o,r)}}async handleNewFormatUpdateTool(e,t,r){let{type:o,data:n}=r;if(this.logger.info(`\u5904\u7406\u65B0\u683C\u5F0F\u5DE5\u5177\u66F4\u65B0\u8BF7\u6C42\uFF0C\u7C7B\u578B: ${o}`),!Object.values(We).includes(o)){let s=this.createErrorResponse("INVALID_TOOL_TYPE",`\u4E0D\u652F\u6301\u7684\u5DE5\u5177\u7C7B\u578B: ${o}\u3002\u652F\u6301\u7684\u7C7B\u578B: ${Object.values(We).join(", ")}`);return e.json(s,400)}switch(o){case"coze":return await this.handleUpdateCozeTool(e,t,n);case"mcp":case"http":case"function":{let s=this.createErrorResponse("TOOL_TYPE_NOT_IMPLEMENTED",`\u5DE5\u5177\u7C7B\u578B ${o} \u6682\u4E0D\u652F\u6301\u66F4\u65B0\u64CD\u4F5C\uFF0C\u76EE\u524D\u4EC5\u652F\u6301 Coze \u7C7B\u578B`);return e.json(s,501)}default:{let s=this.createErrorResponse("UNKNOWN_TOOL_TYPE",`\u672A\u77E5\u7684\u5DE5\u5177\u7C7B\u578B: ${o}`);return e.json(s,400)}}}async handleUpdateCozeTool(e,t,r){let{workflow:o,customName:n,customDescription:s,parameterConfig:a}=r;this.logger.info(`\u5904\u7406\u66F4\u65B0 Coze \u5DE5\u5177: ${t}`);let h=u.getCustomMCPTools().find(E=>E.name===t);if(!h){let E=this.createErrorResponse("TOOL_NOT_FOUND",`\u5DE5\u5177 "${t}" \u4E0D\u5B58\u5728`);return e.json(E,404)}if(h.handler.type!=="proxy"||h.handler.platform!=="coze"){let E=this.createErrorResponse("INVALID_TOOL_TYPE",`\u5DE5\u5177 "${t}" \u4E0D\u662F Coze \u5DE5\u4F5C\u6D41\u5DE5\u5177\uFF0C\u4E0D\u652F\u6301\u53C2\u6570\u914D\u7F6E\u66F4\u65B0`);return e.json(E,400)}!o.workflow_id&&h.handler?.config?.workflow_id&&(o.workflow_id=h.handler.config.workflow_id),!o.workflow_id&&o.app_id&&this.logger.warn(`\u5DE5\u4F5C\u6D41 ${t} \u7F3A\u5C11 workflow_id\uFF0C\u8FD9\u53EF\u80FD\u4F1A\u5F71\u54CD\u67D0\u4E9B\u529F\u80FD`),this.validateWorkflowUpdateData(o);let p=this.generateInputSchema(o,a),d={...h,description:s||h.description,inputSchema:p};u.updateCustomMCPTool(t,d),this.logger.info(`\u6210\u529F\u66F4\u65B0 Coze \u5DE5\u5177: ${t}`);let C={tool:d,toolName:t,toolType:"coze",updatedAt:Ut().format("YYYY-MM-DD HH:mm:ss")};return e.json(this.createSuccessResponse(C,`Coze \u5DE5\u5177 "${t}" \u914D\u7F6E\u66F4\u65B0\u6210\u529F`))}handleUpdateToolError(e){let t=e instanceof Error?e.message:"\u66F4\u65B0\u81EA\u5B9A\u4E49\u5DE5\u5177\u914D\u7F6E\u5931\u8D25";return t.includes("\u4E0D\u5B58\u5728")||t.includes("\u672A\u627E\u5230")?{statusCode:404,errorResponse:this.createErrorResponse("TOOL_NOT_FOUND",`${t}\u3002\u8BF7\u68C0\u67E5\u5DE5\u5177\u540D\u79F0\u662F\u5426\u6B63\u786E`)}:t.includes("\u5DE5\u5177\u7C7B\u578B")||t.includes("INVALID_TOOL_TYPE")?{statusCode:400,errorResponse:this.createErrorResponse("INVALID_TOOL_TYPE",t)}:t.includes("\u4E0D\u80FD\u4E3A\u7A7A")||t.includes("\u65E0\u6548")?{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST",`${t}\u3002\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u5DE5\u5177\u914D\u7F6E\u6570\u636E`)}:t.includes("\u914D\u7F6E")||t.includes("\u6743\u9650")?{statusCode:422,errorResponse:this.createErrorResponse("CONFIGURATION_ERROR",`${t}\u3002\u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u6743\u9650\u548C\u683C\u5F0F\u662F\u5426\u6B63\u786E`)}:t.includes("\u672A\u5B9E\u73B0")||t.includes("NOT_IMPLEMENTED")?{statusCode:501,errorResponse:this.createErrorResponse("TOOL_TYPE_NOT_IMPLEMENTED",t)}:{statusCode:500,errorResponse:this.createErrorResponse("UPDATE_CUSTOM_TOOL_ERROR",`\u66F4\u65B0\u5DE5\u5177\u914D\u7F6E\u5931\u8D25\uFF1A${t}\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF0C\u5982\u95EE\u9898\u6301\u7EED\u5B58\u5728\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458`)}}async removeCustomTool(e){try{let t=e.req.param("toolName");if(!t){let n=this.createErrorResponse("INVALID_REQUEST","\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");return e.json(n,400)}this.logger.info(`\u5904\u7406\u5220\u9664\u81EA\u5B9A\u4E49\u5DE5\u5177\u8BF7\u6C42: ${t}`);let o=u.getCustomMCPTools().find(n=>n.name===t);if(o&&o.handler.type==="mcp"){let n=o.handler.config;if(n.serviceName&&n.toolName){this.logger.info(`\u68C0\u6D4B\u5230 MCP \u5DE5\u5177\u5220\u9664\uFF0C\u540C\u6B65\u7981\u7528 mcpServerConfig \u4E2D\u7684\u5DE5\u5177: ${n.serviceName}/${n.toolName}`);let s=u.getServerToolsConfig(n.serviceName);s?.[n.toolName]&&(s[n.toolName].enable=!1,u.updateServerToolsConfig(n.serviceName,s),this.logger.info(`\u5DF2\u540C\u6B65\u7981\u7528 mcpServerConfig \u4E2D\u7684\u5DE5\u5177: ${n.serviceName}/${n.toolName}`))}}return u.removeCustomMCPTool(t),this.logger.info(`\u6210\u529F\u5220\u9664\u81EA\u5B9A\u4E49\u5DE5\u5177: ${t}`),e.json(this.createSuccessResponse(null,`\u5DE5\u5177 "${t}" \u5220\u9664\u6210\u529F`))}catch(t){this.logger.error("\u5220\u9664\u81EA\u5B9A\u4E49\u5DE5\u5177\u5931\u8D25:",t);let{statusCode:r,errorResponse:o}=this.handleRemoveToolError(t);return e.json(o,r)}}convertWorkflowToTool(e,t,r,o){this.validateWorkflowData(e);let n=t||this.sanitizeToolName(e.workflow_name),s=this.resolveToolNameConflict(n),a=this.generateToolDescription(e,r),l=this.generateInputSchema(e,o),h=this.createHttpHandler(e),p={name:s,description:a,inputSchema:l,handler:h};return this.validateGeneratedTool(p),p}sanitizeToolName(e){if(!e||typeof e!="string")return"coze_workflow_unnamed";let t=e.trim();return t?(t=this.convertChineseToEnglish(t),t=t.replace(/[^a-zA-Z0-9_]/g,"_"),t=t.replace(/_+/g,"_"),t=t.replace(/^_+|_+$/g,""),/^[a-zA-Z]/.test(t)||(t=`coze_workflow_${t}`),t.length>45&&(t=t.substring(0,45)),t||(t="coze_workflow_tool"),t):"coze_workflow_empty"}convertChineseToEnglish(e){let t={\u5DE5\u4F5C\u6D41:"workflow",\u6D4B\u8BD5:"test",\u6570\u636E:"data",\u5904\u7406:"process",\u5206\u6790:"analysis",\u751F\u6210:"generate",\u67E5\u8BE2:"query",\u641C\u7D22:"search",\u8F6C\u6362:"convert",\u8BA1\u7B97:"calculate",\u7EDF\u8BA1:"statistics",\u62A5\u544A:"report",\u6587\u6863:"document",\u56FE\u7247:"image",\u89C6\u9891:"video",\u97F3\u9891:"audio",\u6587\u672C:"text",\u7FFB\u8BD1:"translate",\u8BC6\u522B:"recognize",\u68C0\u6D4B:"detect",\u76D1\u63A7:"monitor",\u7BA1\u7406:"manage",\u914D\u7F6E:"config",\u8BBE\u7F6E:"setting",\u7528\u6237:"user",\u7CFB\u7EDF:"system",\u670D\u52A1:"service",\u63A5\u53E3:"api",\u6570\u636E\u5E93:"database",\u7F51\u7EDC:"network",\u5B89\u5168:"security",\u5907\u4EFD:"backup",\u6062\u590D:"restore",\u540C\u6B65:"sync",\u5BFC\u5165:"import",\u5BFC\u51FA:"export",\u4E0A\u4F20:"upload",\u4E0B\u8F7D:"download"},r=e;for(let[o,n]of Object.entries(t))r=r.replace(new RegExp(o,"g"),n);return/[\u4e00-\u9fa5]/.test(r)&&(r=`chinese_${r}`),r}validateWorkflowData(e){if(!e)throw new Error("\u5DE5\u4F5C\u6D41\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A");this.validateRequiredFields(e),this.validateFieldFormats(e),this.validateFieldLengths(e),this.validateBusinessLogic(e)}validateWorkflowUpdateData(e){if(!e)throw new Error("\u5DE5\u4F5C\u6D41\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A");if(e.workflow_id){if(typeof e.workflow_id!="string"||e.workflow_id.trim()==="")throw new Error("\u5DE5\u4F5C\u6D41ID\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!/^\d+$/.test(e.workflow_id))throw new Error("\u5DE5\u4F5C\u6D41ID\u683C\u5F0F\u65E0\u6548\uFF0C\u5E94\u4E3A\u6570\u5B57\u5B57\u7B26\u4E32")}if(e.workflow_name){if(typeof e.workflow_name!="string"||e.workflow_name.trim()==="")throw new Error("\u5DE5\u4F5C\u6D41\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(e.workflow_name.length>100)throw new Error("\u5DE5\u4F5C\u6D41\u540D\u79F0\u8FC7\u957F\uFF0C\u4E0D\u80FD\u8D85\u8FC7100\u4E2A\u5B57\u7B26")}if(e.app_id){if(typeof e.app_id!="string"||e.app_id.trim()==="")throw new Error("\u5E94\u7528ID\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!/^[a-zA-Z0-9_-]+$/.test(e.app_id))throw new Error("\u5E94\u7528ID\u683C\u5F0F\u65E0\u6548\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26");if(e.app_id.length>50)throw new Error("\u5E94\u7528ID\u8FC7\u957F\uFF0C\u4E0D\u80FD\u8D85\u8FC750\u4E2A\u5B57\u7B26")}}validateRequiredFields(e){let t=[{field:"workflow_id",name:"\u5DE5\u4F5C\u6D41ID"},{field:"workflow_name",name:"\u5DE5\u4F5C\u6D41\u540D\u79F0"},{field:"app_id",name:"\u5E94\u7528ID"}];for(let{field:r,name:o}of t){let n=e[r];if(!n||typeof n!="string"||n.trim()==="")throw new Error(`${o}\u4E0D\u80FD\u4E3A\u7A7A\u4E14\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32`)}}validateFieldFormats(e){if(!/^\d+$/.test(e.workflow_id))throw new Error("\u5DE5\u4F5C\u6D41ID\u683C\u5F0F\u65E0\u6548\uFF0C\u5E94\u4E3A\u6570\u5B57\u5B57\u7B26\u4E32");if(!/^[a-zA-Z0-9_-]+$/.test(e.app_id))throw new Error("\u5E94\u7528ID\u683C\u5F0F\u65E0\u6548\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26");if(e.icon_url?.trim())try{new URL(e.icon_url)}catch{throw new Error("\u56FE\u6807URL\u683C\u5F0F\u65E0\u6548")}if(e.created_at&&(!Number.isInteger(e.created_at)||e.created_at<=0))throw new Error("\u521B\u5EFA\u65F6\u95F4\u683C\u5F0F\u65E0\u6548\uFF0C\u5E94\u4E3A\u6B63\u6574\u6570\u65F6\u95F4\u6233");if(e.updated_at&&(!Number.isInteger(e.updated_at)||e.updated_at<=0))throw new Error("\u66F4\u65B0\u65F6\u95F4\u683C\u5F0F\u65E0\u6548\uFF0C\u5E94\u4E3A\u6B63\u6574\u6570\u65F6\u95F4\u6233")}validateFieldLengths(e){let t=[{field:"workflow_name",name:"\u5DE5\u4F5C\u6D41\u540D\u79F0",max:100},{field:"description",name:"\u5DE5\u4F5C\u6D41\u63CF\u8FF0",max:500},{field:"app_id",name:"\u5E94\u7528ID",max:50}];for(let{field:r,name:o,max:n}of t){let s=e[r];if(s&&s.length>n)throw new Error(`${o}\u8FC7\u957F\uFF0C\u4E0D\u80FD\u8D85\u8FC7${n}\u4E2A\u5B57\u7B26`)}}validateBusinessLogic(e){if(e.creator){if(!e.creator.id||typeof e.creator.id!="string")throw new Error("\u521B\u5EFA\u8005ID\u4E0D\u80FD\u4E3A\u7A7A\u4E14\u5FC5\u987B\u662F\u5B57\u7B26\u4E32");if(!e.creator.name||typeof e.creator.name!="string")throw new Error("\u521B\u5EFA\u8005\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u4E14\u5FC5\u987B\u662F\u5B57\u7B26\u4E32")}if(e.created_at&&e.updated_at&&e.updated_at<e.created_at)throw new Error("\u66F4\u65B0\u65F6\u95F4\u4E0D\u80FD\u65E9\u4E8E\u521B\u5EFA\u65F6\u95F4");let t=["admin","root","system","config","password","token"],r=e.workflow_name.toLowerCase();for(let o of t)if(r.includes(o))throw new Error(`\u5DE5\u4F5C\u6D41\u540D\u79F0\u4E0D\u80FD\u5305\u542B\u654F\u611F\u8BCD: ${o}`)}resolveToolNameConflict(e){let t=u.getCustomMCPTools(),r=new Set(t.map(s=>s.name)),o=e,n=1;for(;r.has(o);)if(o=`${e}_${n}`,n++,n>999)throw new Error(`\u65E0\u6CD5\u4E3A\u5DE5\u5177\u751F\u6210\u552F\u4E00\u540D\u79F0\uFF0C\u57FA\u7840\u540D\u79F0: ${e}`);return o}generateToolDescription(e,t){return t||(e.description?.trim()?e.description.trim():`\u6263\u5B50\u5DE5\u4F5C\u6D41\u5DE5\u5177: ${e.workflow_name}`)}createHttpHandler(e){return this.validateCozeApiConfig(),{type:"proxy",platform:"coze",config:{workflow_id:e.workflow_id}}}validateCozeApiConfig(){let e=u.getCozePlatformConfig();if(!e||!e.token)throw new Error("\u672A\u914D\u7F6E\u6263\u5B50API Token\uFF0C\u8BF7\u5148\u5728\u914D\u7F6E\u4E2D\u8BBE\u7F6E platforms.coze.token")}validateGeneratedTool(e){if(this.validateToolStructure(e),!u.validateCustomMCPTools([e]))throw new Error("\u751F\u6210\u7684\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u5177\u5B9A\u4E49");this.validateJsonSchema(e.inputSchema),this.validateProxyHandler(e.handler)}validateToolStructure(e){if(!e||typeof e!="object")throw new Error("\u5DE5\u5177\u914D\u7F6E\u5FC5\u987B\u662F\u6709\u6548\u5BF9\u8C61");let t=["name","description","inputSchema","handler"];for(let r of t)if(!(r in e)||e[r]==null)throw new Error(`\u5DE5\u5177\u914D\u7F6E\u7F3A\u5C11\u5FC5\u9700\u5B57\u6BB5: ${r}`);if(typeof e.name!="string"||e.name.trim()==="")throw new Error("\u5DE5\u5177\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(typeof e.description!="string"||e.description.trim()==="")throw new Error("\u5DE5\u5177\u63CF\u8FF0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(typeof e.inputSchema!="object")throw new Error("\u8F93\u5165\u53C2\u6570\u7ED3\u6784\u5FC5\u987B\u662F\u5BF9\u8C61");if(typeof e.handler!="object")throw new Error("\u5904\u7406\u5668\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61")}validateProxyHandler(e){if(!e||typeof e!="object")throw new Error("HTTP\u5904\u7406\u5668\u914D\u7F6E\u4E0D\u80FD\u4E3A\u7A7A");if(e.type!=="proxy")throw new Error("\u5904\u7406\u5668\u7C7B\u578B\u5FC5\u987B\u662F'proxy'");if(e.platform==="coze"){if(!e.config.workflow_id)throw new Error("Coze\u5904\u7406\u5668\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684workflow_id")}else throw new Error("\u4E0D\u652F\u6301\u7684\u5DE5\u4F5C\u6D41\u5E73\u53F0")}validateAuthConfig(e){if(!e||typeof e!="object")throw new Error("\u8BA4\u8BC1\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");if(!e.type||typeof e.type!="string")throw new Error("\u8BA4\u8BC1\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A");let t=["bearer","basic","api_key"];if(!t.includes(e.type))throw new Error(`\u8BA4\u8BC1\u7C7B\u578B\u5FC5\u987B\u662F\u4EE5\u4E0B\u4E4B\u4E00: ${t.join(", ")}`);if(e.type==="bearer"){if(!e.token||typeof e.token!="string")throw new Error("Bearer\u8BA4\u8BC1\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684token");if(!e.token.startsWith("${")&&!e.token.match(/^[a-zA-Z0-9_-]+$/))throw new Error("Bearer token\u683C\u5F0F\u65E0\u6548")}}validateBodyTemplate(e){if(typeof e!="string")throw new Error("\u8BF7\u6C42\u4F53\u6A21\u677F\u5FC5\u987B\u662F\u5B57\u7B26\u4E32");try{JSON.parse(e)}catch{throw new Error("\u8BF7\u6C42\u4F53\u6A21\u677F\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F")}let t=e.match(/\{\{[^}]+\}\}/g);if(t)for(let r of t){let o=r.slice(2,-2).trim();if(!o||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o))throw new Error(`\u6A21\u677F\u53D8\u91CF\u683C\u5F0F\u65E0\u6548: ${r}`)}}validateJsonSchema(e){if(!e||typeof e!="object")throw new Error("\u8F93\u5165\u53C2\u6570\u7ED3\u6784\u5FC5\u987B\u662F\u6709\u6548\u7684\u5BF9\u8C61");if(!e.type||e.type!=="object")throw new Error("\u8F93\u5165\u53C2\u6570\u7ED3\u6784\u7684type\u5FC5\u987B\u662F'object'");if(!e.properties||typeof e.properties!="object")throw new Error("\u8F93\u5165\u53C2\u6570\u7ED3\u6784\u5FC5\u987B\u5305\u542Bproperties\u5B57\u6BB5");if(e.required&&!Array.isArray(e.required))throw new Error("\u8F93\u5165\u53C2\u6570\u7ED3\u6784\u7684required\u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4")}generateInputSchema(e,t){return t&&t.parameters.length>0?this.generateInputSchemaFromConfig(t):{type:"object",properties:{input:{type:"string",description:"\u8F93\u5165\u5185\u5BB9"}},required:["input"],additionalProperties:!1}}generateInputSchemaFromConfig(e){let t={},r=[];for(let o of e.parameters)t[o.fieldName]={type:o.type,description:o.description},o.required&&r.push(o.fieldName);return{type:"object",properties:t,required:r.length>0?r:void 0,additionalProperties:!1}}handleAddToolError(e){let t=e instanceof Error?e.message:"\u6DFB\u52A0\u81EA\u5B9A\u4E49\u5DE5\u5177\u5931\u8D25";return t.includes("\u5DE5\u5177\u7C7B\u578B")||t.includes("TOOL_TYPE")?{statusCode:400,errorResponse:this.createErrorResponse("INVALID_TOOL_TYPE",t)}:t.includes("\u5FC5\u9700\u5B57\u6BB5")||t.includes("MISSING_REQUIRED_FIELD")?{statusCode:400,errorResponse:this.createErrorResponse("MISSING_REQUIRED_FIELD",t)}:t.includes("\u4E0D\u5B58\u5728")||t.includes("NOT_FOUND")||t.includes("\u672A\u627E\u5230")?{statusCode:404,errorResponse:this.createErrorResponse("SERVICE_OR_TOOL_NOT_FOUND",t)}:t.includes("\u672A\u521D\u59CB\u5316")||t.includes("SERVICE_NOT_INITIALIZED")?{statusCode:503,errorResponse:this.createErrorResponse("SERVICE_NOT_INITIALIZED",t)}:t.includes("\u5DF2\u5B58\u5728")||t.includes("\u51B2\u7A81")||t.includes("TOOL_NAME_CONFLICT")?{statusCode:409,errorResponse:this.createErrorResponse("TOOL_NAME_CONFLICT",`${t}\u3002\u5EFA\u8BAE\uFF1A1) \u4F7F\u7528\u81EA\u5B9A\u4E49\u540D\u79F0\uFF1B2) \u5220\u9664\u73B0\u6709\u540C\u540D\u5DE5\u5177\u540E\u91CD\u8BD5`)}:this.isValidationError(t)?{statusCode:400,errorResponse:this.createErrorResponse("VALIDATION_ERROR",this.formatValidationError(t))}:t.includes("\u914D\u7F6E")||t.includes("token")||t.includes("API")||t.includes("CONFIGURATION_ERROR")?{statusCode:422,errorResponse:this.createErrorResponse("CONFIGURATION_ERROR",`${t}\u3002\u8BF7\u68C0\u67E5\uFF1A1) \u76F8\u5173\u914D\u7F6E\u662F\u5426\u6B63\u786E\uFF1B2) \u7F51\u7EDC\u8FDE\u63A5\u662F\u5426\u6B63\u5E38\uFF1B3) \u914D\u7F6E\u6587\u4EF6\u6743\u9650\u662F\u5426\u6B63\u786E`)}:t.includes("\u8D44\u6E90\u9650\u5236")||t.includes("RESOURCE_LIMIT_EXCEEDED")?{statusCode:429,errorResponse:this.createErrorResponse("RESOURCE_LIMIT_EXCEEDED",t)}:t.includes("\u672A\u5B9E\u73B0")||t.includes("NOT_IMPLEMENTED")?{statusCode:501,errorResponse:this.createErrorResponse("TOOL_TYPE_NOT_IMPLEMENTED",t)}:{statusCode:500,errorResponse:this.createErrorResponse("ADD_CUSTOM_TOOL_ERROR",`\u6DFB\u52A0\u5DE5\u5177\u5931\u8D25\uFF1A${t}\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF0C\u5982\u95EE\u9898\u6301\u7EED\u5B58\u5728\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458`)}}handleRemoveToolError(e){let t=e instanceof Error?e.message:"\u5220\u9664\u81EA\u5B9A\u4E49\u5DE5\u5177\u5931\u8D25";return t.includes("\u4E0D\u5B58\u5728")||t.includes("\u672A\u627E\u5230")?{statusCode:404,errorResponse:this.createErrorResponse("TOOL_NOT_FOUND",`${t}\u3002\u8BF7\u68C0\u67E5\u5DE5\u5177\u540D\u79F0\u662F\u5426\u6B63\u786E\uFF0C\u6216\u5237\u65B0\u9875\u9762\u67E5\u770B\u6700\u65B0\u7684\u5DE5\u5177\u5217\u8868`)}:t.includes("\u4E0D\u80FD\u4E3A\u7A7A")||t.includes("\u65E0\u6548")?{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST",`${t}\u3002\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u5DE5\u5177\u540D\u79F0`)}:t.includes("\u914D\u7F6E")||t.includes("\u6743\u9650")?{statusCode:422,errorResponse:this.createErrorResponse("CONFIGURATION_ERROR",`${t}\u3002\u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u6743\u9650\u548C\u683C\u5F0F\u662F\u5426\u6B63\u786E`)}:{statusCode:500,errorResponse:this.createErrorResponse("REMOVE_CUSTOM_TOOL_ERROR",`\u5220\u9664\u5DE5\u5177\u5931\u8D25\uFF1A${t}\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF0C\u5982\u95EE\u9898\u6301\u7EED\u5B58\u5728\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458`)}}isValidationError(e){return["\u4E0D\u80FD\u4E3A\u7A7A","\u5FC5\u987B\u662F","\u683C\u5F0F\u65E0\u6548","\u8FC7\u957F","\u8FC7\u77ED","\u9A8C\u8BC1\u5931\u8D25","\u65E0\u6548","\u4E0D\u7B26\u5408","\u8D85\u8FC7","\u5C11\u4E8E","\u654F\u611F\u8BCD","\u65F6\u95F4","URL"].some(r=>e.includes(r))}formatValidationError(e){let t={\u5DE5\u4F5C\u6D41ID\u4E0D\u80FD\u4E3A\u7A7A:"\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u5DE5\u4F5C\u6D41ID",\u5DE5\u4F5C\u6D41\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A:"\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u5DE5\u4F5C\u6D41\u540D\u79F0",\u5E94\u7528ID\u4E0D\u80FD\u4E3A\u7A7A:"\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u5E94\u7528ID",\u5DE5\u4F5C\u6D41ID\u683C\u5F0F\u65E0\u6548:"\u5DE5\u4F5C\u6D41ID\u5E94\u4E3A\u6570\u5B57\u683C\u5F0F\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u4F5C\u6D41\u914D\u7F6E",\u5E94\u7528ID\u683C\u5F0F\u65E0\u6548:"\u5E94\u7528ID\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26",\u5DE5\u4F5C\u6D41\u540D\u79F0\u8FC7\u957F:"\u5DE5\u4F5C\u6D41\u540D\u79F0\u4E0D\u80FD\u8D85\u8FC7100\u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED\u540D\u79F0",\u5DE5\u4F5C\u6D41\u63CF\u8FF0\u8FC7\u957F:"\u5DE5\u4F5C\u6D41\u63CF\u8FF0\u4E0D\u80FD\u8D85\u8FC7500\u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED\u63CF\u8FF0",\u56FE\u6807URL\u683C\u5F0F\u65E0\u6548:"\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u56FE\u6807URL\u5730\u5740",\u66F4\u65B0\u65F6\u95F4\u4E0D\u80FD\u65E9\u4E8E\u521B\u5EFA\u65F6\u95F4:"\u5DE5\u4F5C\u6D41\u7684\u65F6\u95F4\u4FE1\u606F\u6709\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u4F5C\u6D41\u6570\u636E",\u654F\u611F\u8BCD:"\u5DE5\u4F5C\u6D41\u540D\u79F0\u5305\u542B\u654F\u611F\u8BCD\u6C47\uFF0C\u8BF7\u4FEE\u6539\u540E\u91CD\u8BD5"};for(let[r,o]of Object.entries(t))if(e.includes(r))return o;return e}performPreChecks(e,t,r){let o=this.checkBasicParameters(e,t,r);if(o)return o;let n=this.checkSystemStatus();if(n)return n;let s=this.checkResourceLimits();return s||null}checkBasicParameters(e,t,r){if(!e)return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","\u8BF7\u6C42\u4F53\u4E2D\u7F3A\u5C11 workflow \u53C2\u6570")};if(typeof e!="object")return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","workflow \u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61\u7C7B\u578B")};if(!e.workflow_id||typeof e.workflow_id!="string"||!e.workflow_id.trim())return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","workflow_id \u4E0D\u80FD\u4E3A\u7A7A\u4E14\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")};if(!e.workflow_name||typeof e.workflow_name!="string"||!e.workflow_name.trim())return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","workflow_name \u4E0D\u80FD\u4E3A\u7A7A\u4E14\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")};if(t!==void 0){if(typeof t!="string")return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","customName \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u7C7B\u578B")};if(t.trim()==="")return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","customName \u4E0D\u80FD\u4E3A\u7A7A\u5B57\u7B26\u4E32")};if(t.length>50)return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","customName \u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC750\u4E2A\u5B57\u7B26")}}if(r!==void 0){if(typeof r!="string")return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","customDescription \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u7C7B\u578B")};if(r.length>200)return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","customDescription \u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7200\u4E2A\u5B57\u7B26")}}return null}checkSystemStatus(){try{let e=u.getCozePlatformConfig();if(!e||!e.token)return{statusCode:422,errorResponse:this.createErrorResponse("CONFIGURATION_ERROR","\u672A\u914D\u7F6E\u6263\u5B50API Token\u3002\u8BF7\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u4E2D\u914D\u7F6E platforms.coze.token")};if(typeof e.token!="string"||e.token.trim()==="")return{statusCode:422,errorResponse:this.createErrorResponse("CONFIGURATION_ERROR","\u6263\u5B50API Token\u683C\u5F0F\u65E0\u6548\u3002\u8BF7\u68C0\u67E5\u914D\u7F6E\u4E2D\u7684 platforms.coze.token")}}catch{return{statusCode:500,errorResponse:this.createErrorResponse("SYSTEM_ERROR","\u7CFB\u7EDF\u914D\u7F6E\u68C0\u67E5\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5")}}return null}checkResourceLimits(){try{let e=u.getCustomMCPTools(),t=100;if(e.length>=t)return{statusCode:429,errorResponse:this.createErrorResponse("RESOURCE_LIMIT_EXCEEDED",`\u5DF2\u8FBE\u5230\u6700\u5927\u5DE5\u5177\u6570\u91CF\u9650\u5236 (${t})\u3002\u8BF7\u5220\u9664\u4E00\u4E9B\u4E0D\u9700\u8981\u7684\u5DE5\u5177\u540E\u91CD\u8BD5`)};let r=JSON.stringify(e).length,o=1024*1024;if(r>o)return{statusCode:413,errorResponse:this.createErrorResponse("PAYLOAD_TOO_LARGE","\u914D\u7F6E\u6587\u4EF6\u8FC7\u5927\u3002\u8BF7\u5220\u9664\u4E00\u4E9B\u4E0D\u9700\u8981\u7684\u5DE5\u5177\u4EE5\u91CA\u653E\u7A7A\u95F4")}}catch(e){this.logger.warn("\u8D44\u6E90\u9650\u5236\u68C0\u67E5\u5931\u8D25:",e)}return null}}});var Wt,Wo=m(()=>{"use strict";y();lr();Wt=class{static{c(this,"VersionApiHandler")}logger;constructor(){this.logger=g.withTag("VersionApiHandler")}createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async getVersion(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u7248\u672C\u4FE1\u606F\u8BF7\u6C42");let t=me.getVersionInfo();return this.logger.debug("\u83B7\u53D6\u7248\u672C\u4FE1\u606F\u6210\u529F:",t),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u7248\u672C\u4FE1\u606F\u5931\u8D25:",t);let r=this.createErrorResponse("VERSION_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u7248\u672C\u4FE1\u606F\u5931\u8D25");return e.json(r,500)}}async getVersionSimple(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u7248\u672C\u53F7\u8BF7\u6C42");let t=me.getVersion();return this.logger.debug(`\u83B7\u53D6\u7248\u672C\u53F7\u6210\u529F: ${t}`),e.json(this.createSuccessResponse({version:t}))}catch(t){this.logger.error("\u83B7\u53D6\u7248\u672C\u53F7\u5931\u8D25:",t);let r=this.createErrorResponse("VERSION_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u7248\u672C\u53F7\u5931\u8D25");return e.json(r,500)}}async clearVersionCache(e){try{return this.logger.debug("\u5904\u7406\u6E05\u9664\u7248\u672C\u7F13\u5B58\u8BF7\u6C42"),me.clearCache(),this.logger.info("\u7248\u672C\u7F13\u5B58\u5DF2\u6E05\u9664"),e.json(this.createSuccessResponse(null,"\u7248\u672C\u7F13\u5B58\u5DF2\u6E05\u9664"))}catch(t){this.logger.error("\u6E05\u9664\u7248\u672C\u7F13\u5B58\u5931\u8D25:",t);let r=this.createErrorResponse("CACHE_CLEAR_ERROR",t instanceof Error?t.message:"\u6E05\u9664\u7248\u672C\u7F13\u5B58\u5931\u8D25");return e.json(r,500)}}}});var Vt,Vo=m(()=>{"use strict";y();Z();K();Vt=class{static{c(this,"NotificationService")}logger;eventBus;clients=new Map;messageQueue=new Map;maxQueueSize=100;constructor(){this.logger=g.withTag("NotificationService"),this.eventBus=I(),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("config:updated",e=>{let t=u.getConfig();this.broadcastConfigUpdate(t)}),this.eventBus.onEvent("status:updated",e=>{this.broadcastStatusUpdate(e.status)}),this.eventBus.onEvent("service:restart:started",e=>{this.broadcastRestartStatus("restarting",void 0,e.timestamp)}),this.eventBus.onEvent("service:restart:completed",e=>{this.broadcastRestartStatus("completed",void 0,e.timestamp)}),this.eventBus.onEvent("service:restart:failed",e=>{this.broadcastRestartStatus("failed",e.error.message,e.timestamp)}),this.eventBus.onEvent("notification:broadcast",e=>{e.target?this.sendToClient(e.target,e.type,e.data):this.broadcast(e.type,e.data)})}registerClient(e,t){try{let r={id:e,ws:t,readyState:t.readyState,send:c(o=>{t.readyState===1&&t.send(o)},"send")};this.clients.set(e,r),this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u6CE8\u518C: ${e}`),this.logger.debug(`\u5F53\u524D\u5BA2\u6237\u7AEF\u6570\u91CF: ${this.clients.size}`),this.sendQueuedMessages(e),this.eventBus.emitEvent("websocket:client:connected",{clientId:e,timestamp:Date.now()})}catch(r){this.logger.error(`\u6CE8\u518C\u5BA2\u6237\u7AEF\u5931\u8D25: ${e}`,r),this.eventBus.emitEvent("notification:error",{error:r instanceof Error?r:new Error(String(r)),type:"client:register"})}}unregisterClient(e){try{this.clients.has(e)&&(this.clients.delete(e),this.messageQueue.delete(e),this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u6CE8\u9500: ${e}`),this.logger.debug(`\u5269\u4F59\u5BA2\u6237\u7AEF\u6570\u91CF: ${this.clients.size}`),this.eventBus.emitEvent("websocket:client:disconnected",{clientId:e,timestamp:Date.now()}))}catch(t){this.logger.error(`\u6CE8\u9500\u5BA2\u6237\u7AEF\u5931\u8D25: ${e}`,t)}}broadcast(e,t){let r={type:e,data:t,timestamp:Date.now()};this.logger.debug(`\u5E7F\u64AD\u6D88\u606F: ${e}`,{clientCount:this.clients.size});for(let[o,n]of this.clients)this.sendMessageToClient(n,r,o)}sendToClient(e,t,r){let o={type:t,data:r,timestamp:Date.now()},n=this.clients.get(e);n?this.sendMessageToClient(n,o,e):this.queueMessage(e,o)}sendMessageToClient(e,t,r){try{if(e.ws.readyState===1){let o=JSON.stringify(t);e.send(o),this.logger.debug(`\u6D88\u606F\u5DF2\u53D1\u9001\u7ED9\u5BA2\u6237\u7AEF ${r}: ${t.type}`)}else this.queueMessage(r,t),this.logger.warn(`\u5BA2\u6237\u7AEF ${r} \u8FDE\u63A5\u4E0D\u53EF\u7528\uFF0C\u6D88\u606F\u5DF2\u52A0\u5165\u961F\u5217`)}catch(o){this.logger.error(`\u53D1\u9001\u6D88\u606F\u7ED9\u5BA2\u6237\u7AEF ${r} \u5931\u8D25:`,o),this.queueMessage(r,t),this.eventBus.emitEvent("notification:error",{error:o instanceof Error?o:new Error(String(o)),type:"message:send"})}}queueMessage(e,t){this.messageQueue.has(e)||this.messageQueue.set(e,[]);let r=this.messageQueue.get(e);r.push(t),r.length>this.maxQueueSize&&(r.shift(),this.logger.warn(`\u5BA2\u6237\u7AEF ${e} \u6D88\u606F\u961F\u5217\u5DF2\u6EE1\uFF0C\u79FB\u9664\u6700\u65E7\u6D88\u606F`))}sendQueuedMessages(e){let t=this.messageQueue.get(e);if(!t||t.length===0)return;let r=this.clients.get(e);if(r){this.logger.info(`\u53D1\u9001 ${t.length} \u6761\u6392\u961F\u6D88\u606F\u7ED9\u5BA2\u6237\u7AEF ${e}`);for(let o of t)this.sendMessageToClient(r,o,e);this.messageQueue.delete(e)}}broadcastConfigUpdate(e){this.broadcast("configUpdate",e)}broadcastStatusUpdate(e){this.broadcast("statusUpdate",e)}broadcastRestartStatus(e,t,r){let o={status:e,error:t,timestamp:r||Date.now()};this.broadcast("restartStatus",o)}getClientStats(){let e=Array.from(this.clients.values()).filter(r=>r.ws.readyState===1).length,t=Array.from(this.messageQueue.values()).reduce((r,o)=>r+o.length,0);return{totalClients:this.clients.size,connectedClients:e,queuedMessages:t}}cleanupDisconnectedClients(){let e=[];for(let[t,r]of this.clients)r.ws.readyState!==1&&e.push(t);for(let t of e)this.unregisterClient(t);e.length>0&&this.logger.info(`\u6E05\u7406\u4E86 ${e.length} \u4E2A\u65AD\u5F00\u7684\u5BA2\u6237\u7AEF`)}destroy(){this.logger.info("\u9500\u6BC1\u901A\u77E5\u670D\u52A1"),this.clients.clear(),this.messageQueue.clear()}}});var Bt,Bo=m(()=>{"use strict";y();K();Bt=class{static{c(this,"StatusService")}logger;eventBus;clientInfo={status:"disconnected",mcpEndpoint:"",activeMCPServers:[]};restartStatus;heartbeatTimeout;HEARTBEAT_TIMEOUT=35e3;constructor(){this.logger=g.withTag("StatusService"),this.eventBus=I()}getClientStatus(){return{...this.clientInfo}}updateClientInfo(e,t="unknown"){try{let r={...this.clientInfo};this.clientInfo={...this.clientInfo,...e},e.lastHeartbeat&&(this.clientInfo.lastHeartbeat=Date.now()),e.status==="connected"&&this.resetHeartbeatTimeout(),this.logger.debug(`\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\uFF0C\u6765\u6E90: ${t}`,{old:r,new:this.clientInfo}),this.eventBus.emitEvent("status:updated",{status:this.clientInfo,source:t})}catch(r){this.logger.error("\u66F4\u65B0\u5BA2\u6237\u7AEF\u72B6\u6001\u5931\u8D25:",r),this.eventBus.emitEvent("status:error",{error:r instanceof Error?r:new Error(String(r)),operation:"updateClientInfo"})}}getRestartStatus(){return this.restartStatus?{...this.restartStatus}:void 0}updateRestartStatus(e,t){try{switch(this.restartStatus={status:e,error:t,timestamp:Date.now()},this.logger.info(`\u91CD\u542F\u72B6\u6001\u66F4\u65B0: ${e}`,{error:t}),e){case"restarting":this.eventBus.emitEvent("service:restart:started",{timestamp:this.restartStatus.timestamp});break;case"completed":this.eventBus.emitEvent("service:restart:completed",{timestamp:this.restartStatus.timestamp});break;case"failed":this.eventBus.emitEvent("service:restart:failed",{error:new Error(t||"\u91CD\u542F\u5931\u8D25"),timestamp:this.restartStatus.timestamp});break}}catch(r){this.logger.error("\u66F4\u65B0\u91CD\u542F\u72B6\u6001\u5931\u8D25:",r),this.eventBus.emitEvent("status:error",{error:r instanceof Error?r:new Error(String(r)),operation:"updateRestartStatus"})}}getFullStatus(){return{client:this.getClientStatus(),restart:this.getRestartStatus(),timestamp:Date.now()}}resetHeartbeatTimeout(){this.heartbeatTimeout&&clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=setTimeout(()=>{this.logger.warn("\u5BA2\u6237\u7AEF\u5FC3\u8DF3\u8D85\u65F6\uFF0C\u6807\u8BB0\u4E3A\u65AD\u5F00\u8FDE\u63A5"),this.updateClientInfo({status:"disconnected"},"heartbeat-timeout")},this.HEARTBEAT_TIMEOUT)}clearHeartbeatTimeout(){this.heartbeatTimeout&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=void 0)}isClientConnected(){return this.clientInfo.status==="connected"}getLastHeartbeat(){return this.clientInfo.lastHeartbeat}getActiveMCPServers(){return[...this.clientInfo.activeMCPServers]}setActiveMCPServers(e){this.updateClientInfo({activeMCPServers:[...e]},"mcp-servers-update")}setMcpEndpoint(e){this.updateClientInfo({mcpEndpoint:e},"mcp-endpoint-update")}reset(){this.logger.info("\u91CD\u7F6E\u72B6\u6001\u670D\u52A1"),this.clearHeartbeatTimeout(),this.clientInfo={status:"disconnected",mcpEndpoint:"",activeMCPServers:[]},this.restartStatus=void 0}destroy(){this.logger.info("\u9500\u6BC1\u72B6\u6001\u670D\u52A1"),this.clearHeartbeatTimeout(),this.reset()}}});var wr={};B(wr,{WebServer:()=>Pr});import{createServer as $s}from"http";import{serve as xs}from"@hono/node-server";import{Hono as Os}from"hono";import{cors as As}from"hono/cors";import{WebSocketServer as ks}from"ws";var Pr,br=m(()=>{"use strict";y();ft();wo();Z();Rt();Oo();Ao();Do();No();_o();Lo();Ho();jo();zo();Fo();Wo();st();K();Vo();Bo();Pr=class{static{c(this,"WebServer")}app;httpServer=null;wss=null;logger;port;eventBus;configService;statusService;notificationService;configApiHandler;statusApiHandler;serviceApiHandler;toolApiHandler;versionApiHandler;staticFileHandler;mcpRouteHandler;realtimeNotificationHandler;heartbeatHandler;heartbeatMonitorInterval;proxyMCPServer;xiaozhiConnectionManager;mcpServiceManager;createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}logDeprecationWarning(e,t){this.logger.warn(`[DEPRECATED] ${e} \u529F\u80FD\u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u4F7F\u7528 ${t} \u66FF\u4EE3`)}constructor(e){try{this.port=e??u.getWebUIPort()??9999}catch{this.port=e??9999}this.logger=g.withTag("WebServer"),this.eventBus=I(),this.configService=new ge,this.statusService=new Bt,this.notificationService=new Vt,this.configApiHandler=new $t,this.statusApiHandler=new zt(this.statusService),this.serviceApiHandler=new Lt(this.statusService),this.toolApiHandler=new Ft,this.versionApiHandler=new Wt,this.staticFileHandler=new jt,this.mcpRouteHandler=new Dt,this.realtimeNotificationHandler=new Nt(this.notificationService,this.statusService),this.heartbeatHandler=new kt(this.statusService,this.notificationService),this.app=new Os,this.setupMiddleware(),this.setupRoutes(),this.logger.info("WebServer \u67B6\u6784\u91CD\u6784\u5B8C\u6210 - \u7B2C\u4E8C\u9636\u6BB5\uFF1A\u6A21\u5757\u5316\u62C6\u5206")}async initializeConnections(){try{this.logger.info("\u5F00\u59CB\u521D\u59CB\u5316\u8FDE\u63A5...");let e=await this.loadConfiguration();this.mcpServiceManager=await q.getInstance(),await this.loadMCPServicesFromConfig(e.mcpServers);let t=this.mcpServiceManager.getAllTools();this.logger.info(`\u5DF2\u52A0\u8F7D ${t.length} \u4E2A\u5DE5\u5177`),await this.initializeXiaozhiConnection(e.mcpEndpoint,t),this.logger.info("\u6240\u6709\u8FDE\u63A5\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw this.logger.error("\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25:",e),e}}async loadConfiguration(){if(!u.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C 'xiaozhi init' \u521D\u59CB\u5316\u914D\u7F6E");u.cleanupInvalidServerToolsConfig();let e=u.getConfig();return{mcpEndpoint:e.mcpEndpoint,mcpServers:e.mcpServers,webUIPort:e.webUI?.port??9999}}async loadMCPServicesFromConfig(e){if(!this.mcpServiceManager)throw new Error("MCPServiceManager \u672A\u521D\u59CB\u5316");for(let[t,r]of Object.entries(e)){this.logger.info(`\u6DFB\u52A0 MCP \u670D\u52A1\u914D\u7F6E: ${t}`);let o=Po(t,r);this.mcpServiceManager.addServiceConfig(t,o)}await this.mcpServiceManager.startAllServices(),this.logger.info("\u6240\u6709 MCP \u670D\u52A1\u5DF2\u542F\u52A8")}async initializeXiaozhiConnection(e,t){let o=(Array.isArray(e)?e:[e]).filter(n=>n&&!n.includes("<\u8BF7\u586B\u5199"));if(o.length===0){this.logger.warn("\u672A\u914D\u7F6E\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u8DF3\u8FC7\u8FDE\u63A5");return}this.logger.info(`\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u7BA1\u7406\u5668\uFF0C\u7AEF\u70B9\u6570\u91CF: ${o.length}`),this.logger.debug("\u6709\u6548\u7AEF\u70B9\u5217\u8868:",o);try{this.xiaozhiConnectionManager=await Fe.getInstance({reconnectInterval:5e3,maxReconnectAttempts:3,connectionTimeout:1e4}),this.mcpServiceManager&&this.xiaozhiConnectionManager&&this.xiaozhiConnectionManager.setServiceManager(this.mcpServiceManager),this.xiaozhiConnectionManager&&(await this.xiaozhiConnectionManager.initialize(o,t),await this.xiaozhiConnectionManager.connect(),this.xiaozhiConnectionManager.on("configChange",n=>{this.logger.info(`\u5C0F\u667A\u8FDE\u63A5\u914D\u7F6E\u53D8\u66F4: ${n.type}`,n.data)})),this.logger.info(`\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u7BA1\u7406\u5668\u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u7BA1\u7406 ${o.length} \u4E2A\u7AEF\u70B9`)}catch(n){this.logger.error("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u7BA1\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",n),this.logger.warn("\u56DE\u9000\u5230\u5355\u8FDE\u63A5\u6A21\u5F0F");let s=o[0];this.logger.info(`\u521D\u59CB\u5316\u5355\u4E2A\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5: ${s}`),this.proxyMCPServer=new fe(s),this.mcpServiceManager&&this.proxyMCPServer.setServiceManager(this.mcpServiceManager),await this.connectWithRetry(()=>this.proxyMCPServer.connect(),"\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5"),this.logger.info("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F\uFF08\u5355\u8FDE\u63A5\u6A21\u5F0F\uFF09")}}getXiaozhiConnectionStatus(){return this.xiaozhiConnectionManager?{type:"multi-endpoint",manager:{connectedConnections:this.xiaozhiConnectionManager.getConnectionStatus().filter(e=>e.connected).length,totalConnections:this.xiaozhiConnectionManager.getConnectionStatus().length,healthCheckStats:{},reconnectStats:this.xiaozhiConnectionManager.getReconnectStats()},connections:this.xiaozhiConnectionManager.getConnectionStatus()}:this.proxyMCPServer?{type:"single-endpoint",connected:!0,endpoint:"unknown"}:{type:"none",connected:!1}}async connectWithRetry(e,t,r=5,o=1e3,n=3e4,s=2){let a=null;for(let l=1;l<=r;l++)try{return this.logger.info(`${t} - \u5C1D\u8BD5\u8FDE\u63A5 (${l}/${r})`),await e()}catch(h){if(a=h,this.logger.warn(`${t} - \u8FDE\u63A5\u5931\u8D25:`,h),l<r){let p=Math.min(o*s**(l-1),n);this.logger.info(`${t} - ${p}ms \u540E\u91CD\u8BD5...`),await this.sleep(p)}}throw new Error(`${t} - \u8FDE\u63A5\u5931\u8D25\uFF0C\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570: ${a?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}setupMiddleware(){this.app?.use("*",As({origin:"*",allowMethods:["GET","POST","PUT","OPTIONS"],allowHeaders:["Content-Type"]})),this.app?.onError((e,t)=>{this.logger.error("HTTP request error:",e);let r=this.createErrorResponse("INTERNAL_SERVER_ERROR","\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF",process.env.NODE_ENV==="development"?e.stack:void 0);return t.json(r,500)})}setupRoutes(){this.app?.get("/api/config",e=>this.configApiHandler.getConfig(e)),this.app?.put("/api/config",e=>this.configApiHandler.updateConfig(e)),this.app?.get("/api/config/mcp-endpoint",e=>this.configApiHandler.getMcpEndpoint(e)),this.app?.get("/api/config/mcp-endpoints",e=>this.configApiHandler.getMcpEndpoints(e)),this.app?.get("/api/config/mcp-servers",e=>this.configApiHandler.getMcpServers(e)),this.app?.get("/api/config/connection",e=>this.configApiHandler.getConnectionConfig(e)),this.app?.post("/api/config/reload",e=>this.configApiHandler.reloadConfig(e)),this.app?.get("/api/config/path",e=>this.configApiHandler.getConfigPath(e)),this.app?.get("/api/config/exists",e=>this.configApiHandler.checkConfigExists(e)),this.app?.get("/api/version",e=>this.versionApiHandler.getVersion(e)),this.app?.get("/api/version/simple",e=>this.versionApiHandler.getVersionSimple(e)),this.app?.post("/api/version/cache/clear",e=>this.versionApiHandler.clearVersionCache(e)),this.app?.get("/api/status",e=>this.statusApiHandler.getStatus(e)),this.app?.get("/api/status/client",e=>this.statusApiHandler.getClientStatus(e)),this.app?.get("/api/status/restart",e=>this.statusApiHandler.getRestartStatus(e)),this.app?.get("/api/status/connected",e=>this.statusApiHandler.checkClientConnected(e)),this.app?.get("/api/status/heartbeat",e=>this.statusApiHandler.getLastHeartbeat(e)),this.app?.get("/api/status/mcp-servers",e=>this.statusApiHandler.getActiveMCPServers(e)),this.app?.put("/api/status/client",e=>this.statusApiHandler.updateClientStatus(e)),this.app?.put("/api/status/mcp-servers",e=>this.statusApiHandler.setActiveMCPServers(e)),this.app?.post("/api/status/reset",e=>this.statusApiHandler.resetStatus(e)),this.app?.post("/api/services/restart",e=>this.serviceApiHandler.restartService(e)),this.app?.post("/api/services/stop",e=>this.serviceApiHandler.stopService(e)),this.app?.post("/api/services/start",e=>this.serviceApiHandler.startService(e)),this.app?.get("/api/services/status",e=>this.serviceApiHandler.getServiceStatus(e)),this.app?.get("/api/services/health",e=>this.serviceApiHandler.getServiceHealth(e)),this.app?.post("/api/tools/call",e=>this.toolApiHandler.callTool(e)),this.app?.get("/api/tools/list",e=>this.toolApiHandler.listTools(e)),this.app?.get("/api/tools/custom",e=>this.toolApiHandler.getCustomTools(e)),this.app?.post("/api/tools/custom",e=>this.toolApiHandler.addCustomTool(e)),this.app?.put("/api/tools/custom/:toolName",e=>this.toolApiHandler.updateCustomTool(e)),this.app?.delete("/api/tools/custom/:toolName",e=>this.toolApiHandler.removeCustomTool(e)),this.app?.get("/api/coze/workspaces",e=>Me.getWorkspaces(e)),this.app?.get("/api/coze/workflows",e=>Me.getWorkflows(e)),this.app?.post("/api/coze/cache/clear",e=>Me.clearCache(e)),this.app?.get("/api/coze/cache/stats",e=>Me.getCacheStats(e)),this.app?.post("/mcp",e=>this.mcpRouteHandler.handlePost(e)),this.app?.get("/mcp",e=>this.mcpRouteHandler.handleGet(e)),this.app?.all("/api/*",async e=>{let t=this.createErrorResponse("API_NOT_FOUND",`API \u7AEF\u70B9\u4E0D\u5B58\u5728: ${e.req.path}`);return e.json(t,404)}),this.app.get("*",e=>this.staticFileHandler.handleStaticFile(e))}setupWebSocket(){this.wss&&this.wss.on("connection",e=>{let t=`client-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u8FDE\u63A5: ${t}`),this.logger.debug(`\u5F53\u524D WebSocket \u8FDE\u63A5\u6570: ${this.wss?.clients.size||0}`),this.realtimeNotificationHandler.handleClientConnect(e,t),this.heartbeatHandler.handleClientConnect(t),e.on("message",async r=>{try{let o=JSON.parse(r.toString());o.type==="clientStatus"?await this.heartbeatHandler.handleClientStatus(e,o,t):await this.realtimeNotificationHandler.handleMessage(e,o,t)}catch(o){this.logger.error("WebSocket message error:",o);let n={type:"error",error:{code:"MESSAGE_PARSE_ERROR",message:o instanceof Error?o.message:"\u6D88\u606F\u89E3\u6790\u5931\u8D25",timestamp:Date.now()}};e.send(JSON.stringify(n))}}),e.on("close",()=>{this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u65AD\u5F00\u8FDE\u63A5: ${t}`),this.logger.debug(`\u5269\u4F59 WebSocket \u8FDE\u63A5\u6570: ${this.wss?.clients.size||0}`),this.realtimeNotificationHandler.handleClientDisconnect(t),this.heartbeatHandler.handleClientDisconnect(t)}),e.on("error",r=>{this.logger.error(`WebSocket \u8FDE\u63A5\u9519\u8BEF (${t}):`,r)}),this.realtimeNotificationHandler.sendInitialData(e,t)})}async start(){if(this.httpServer){this.logger.warn("Web server is already running");return}let e=xs({fetch:this.app.fetch,port:this.port,hostname:"0.0.0.0",createServer:$s});this.httpServer=e,this.wss=new ks({server:this.httpServer}),this.setupWebSocket(),this.heartbeatMonitorInterval=this.heartbeatHandler.startHeartbeatMonitoring(),this.logger.info(`Web server listening on http://0.0.0.0:${this.port}`),this.logger.info(`Local access: http://localhost:${this.port}`),this.logger.info("=== \u901A\u4FE1\u67B6\u6784\u91CD\u6784\u4FE1\u606F - \u7B2C\u4E8C\u9636\u6BB5\u5B8C\u6210 ==="),this.logger.info("\u2705 \u6A21\u5757\u5316\u62C6\u5206: HTTP/WebSocket \u5904\u7406\u5668\u72EC\u7ACB"),this.logger.info("\u2705 \u670D\u52A1\u5C42\u62BD\u8C61: ConfigService, StatusService, NotificationService"),this.logger.info("\u2705 \u4E8B\u4EF6\u9A71\u52A8\u673A\u5236: EventBus \u5B9E\u73B0\u6A21\u5757\u95F4\u89E3\u8026\u901A\u4FE1"),this.logger.info("\u2705 HTTP API \u804C\u8D23: \u914D\u7F6E\u7BA1\u7406\u3001\u72B6\u6001\u67E5\u8BE2\u3001\u670D\u52A1\u63A7\u5236"),this.logger.info("\u2705 WebSocket \u804C\u8D23: \u5B9E\u65F6\u901A\u77E5\u3001\u5FC3\u8DF3\u68C0\u6D4B\u3001\u4E8B\u4EF6\u5E7F\u64AD"),this.logger.info("\u26A0\uFE0F \u5DF2\u5E9F\u5F03\u7684 WebSocket \u6D88\u606F: getConfig, updateConfig, getStatus, restartService"),this.logger.info("\u{1F4D6} \u63A8\u8350\u4F7F\u7528\u5BF9\u5E94\u7684 HTTP API \u66FF\u4EE3\u5E9F\u5F03\u7684 WebSocket \u6D88\u606F"),this.logger.info("================================================");try{await this.initializeConnections()}catch(t){this.logger.error("\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25\uFF0C\u4F46 Web \u670D\u52A1\u5668\u7EE7\u7EED\u8FD0\u884C:",t)}}stop(){return new Promise(e=>{let t=!1,r=c(()=>{t||(t=!0,e())},"doResolve");if(this.proxyMCPServer?.disconnect(),this.heartbeatMonitorInterval&&(this.heartbeatHandler.stopHeartbeatMonitoring(this.heartbeatMonitorInterval),this.heartbeatMonitorInterval=void 0),this.wss){for(let o of this.wss.clients)o.terminate();this.wss.close(()=>{this.httpServer?this.httpServer.close(()=>{this.logger.info("Web server stopped"),r()}):(this.logger.info("Web server stopped"),r()),setTimeout(()=>{this.logger.info("Web server force stopped"),r()},2e3)})}else this.logger.info("Web server stopped"),r()})}destroy(){this.logger.info("\u9500\u6BC1 WebServer \u5B9E\u4F8B"),this.heartbeatMonitorInterval&&(this.heartbeatHandler.stopHeartbeatMonitoring(this.heartbeatMonitorInterval),this.heartbeatMonitorInterval=void 0),this.statusService.destroy(),this.notificationService.destroy(),Ur(),this.proxyMCPServer?.disconnect(),this.logger.info("WebServer \u5B9E\u4F8B\u5DF2\u9500\u6BC1")}}});var Go={};B(Go,{ServiceManagerImpl:()=>Rr});var Rr,qo=m(()=>{"use strict";ne();ke();Ze();pt();Rr=class{constructor(e,t,r){this.processManager=e;this.configManager=t;this.logger=r}static{c(this,"ServiceManagerImpl")}async start(e){try{this.validateStartOptions(e),this.processManager.cleanupContainerState();let t=this.getStatus();if(t.running){console.log(`\u68C0\u6D4B\u5230\u670D\u52A1\u5DF2\u5728\u8FD0\u884C (PID: ${t.pid})\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u542F...`);try{await this.processManager.gracefulKillProcess(t.pid),this.processManager.cleanupPidFile(),await new Promise(r=>setTimeout(r,1e3)),console.log("\u73B0\u6709\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u6B63\u5728\u542F\u52A8\u65B0\u670D\u52A1...")}catch(r){console.warn(`\u505C\u6B62\u73B0\u6709\u670D\u52A1\u65F6\u51FA\u73B0\u8B66\u544A: ${r instanceof Error?r.message:String(r)}`)}}switch(this.checkEnvironment(),e.mode){case"mcp-server":await this.startMcpServerMode(e);break;case"stdio":await this.startStdioMode(e);break;case"normal":await this.startNormalMode(e);break;default:await this.startNormalMode(e);break}}catch(t){throw t instanceof x?t:x.startFailed(t instanceof Error?t.message:String(t))}}async stop(){try{let e=this.getStatus();if(!e.running)throw x.notRunning();await this.processManager.gracefulKillProcess(e.pid),this.processManager.cleanupPidFile()}catch(e){throw e instanceof x?e:new x(`\u505C\u6B62\u670D\u52A1\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async restart(e){try{this.getStatus().running&&(await this.stop(),await new Promise(r=>setTimeout(r,1e3))),await this.start(e)}catch(t){throw new x(`\u91CD\u542F\u670D\u52A1\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}getStatus(){return this.processManager.getServiceStatus()}validateStartOptions(e){if(e.port!==void 0&&Q.validatePort(e.port),e.mode&&!["normal","mcp-server","stdio"].includes(e.mode))throw new x(`\u65E0\u6548\u7684\u8FD0\u884C\u6A21\u5F0F: ${e.mode}`)}checkEnvironment(){if(!this.configManager.configExists())throw Te.configNotFound();try{if(!this.configManager.getConfig())throw new Te("\u914D\u7F6E\u6587\u4EF6\u65E0\u6548")}catch(e){throw e instanceof Te?e:new Te(`\u914D\u7F6E\u6587\u4EF6\u9519\u8BEF: ${e instanceof Error?e.message:String(e)}`)}}async startNormalMode(e){let{spawn:t}=await import("child_process");e.daemon?await this.startWebServerInDaemon(e.ui||!1):await this.startWebServerInForeground(e.ui||!1)}async startMcpServerMode(e){let t=e.port||3e3,{spawn:r}=await import("child_process");if(e.daemon){let o=$.getExecutablePath("cli"),n=r("node",[o,"start","--server",t.toString()],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:$.getConfigDir(),XIAOZHI_DAEMON:"true",MCP_SERVER_MODE:"true"}});this.processManager.savePidInfo(n.pid,"daemon"),n.unref(),console.log(`\u2705 MCP Server \u5DF2\u5728\u540E\u53F0\u542F\u52A8 (PID: ${n.pid}, Port: ${t})`),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi status' \u67E5\u770B\u72B6\u6001"),process.exit(0)}else{let{MCPServer:o}=await Promise.resolve().then(()=>(yo(),So)),n=new o(t),s=c(async()=>{await n.stop(),process.exit(0)},"cleanup");process.on("SIGINT",s),process.on("SIGTERM",s),await n.start()}}async startStdioMode(e){let{spawn:t}=await import("child_process"),r=$.getMcpServerProxyPath(),o=t("node",[r],{stdio:"inherit",env:{...process.env,XIAOZHI_CONFIG_DIR:$.getConfigDir()}});this.processManager.savePidInfo(o.pid,"foreground")}async startWebServerInDaemon(e){let{spawn:t}=await import("child_process"),r=$.getWebServerStandalonePath();if(!(await import("fs")).default.existsSync(r))throw new x(`WebServer \u6587\u4EF6\u4E0D\u5B58\u5728: ${r}`);let n=[r];e&&n.push("--open-browser");let s=t("node",n,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:$.getConfigDir(),XIAOZHI_DAEMON:"true"}});this.processManager.savePidInfo(s.pid,"daemon"),s.unref(),console.log(`\u2705 \u540E\u53F0\u670D\u52A1\u5DF2\u542F\u52A8 (PID: ${s.pid})`),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi status' \u67E5\u770B\u72B6\u6001"),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi attach' \u67E5\u770B\u65E5\u5FD7"),process.exit(0)}async startWebServerInForeground(e){let{WebServer:t}=await Promise.resolve().then(()=>(br(),wr)),r=new t,o=c(async()=>{await r.stop(),this.processManager.cleanupPidFile(),process.exit(0)},"cleanup");if(process.on("SIGINT",o),process.on("SIGTERM",o),this.processManager.savePidInfo(process.pid,"foreground"),await r.start(),e){let s=this.configManager.getConfig()?.webServer?.port||9999;await this.openBrowserUrl(`http://localhost:${s}`)}}async openBrowserUrl(e){try{let{spawn:t}=await import("child_process"),r=G.getCurrentPlatform(),o,n;r==="darwin"?(o="open",n=[e]):r==="win32"?(o="start",n=["",e]):(o="xdg-open",n=[e]),t(o,n,{detached:!0,stdio:"ignore"}),console.log(`\u{1F310} \u5DF2\u5C1D\u8BD5\u6253\u5F00\u6D4F\u89C8\u5668: ${e}`)}catch{console.log(`\u26A0\uFE0F \u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE: ${e}`)}}}});var Jo={};B(Jo,{TemplateManagerImpl:()=>Ir});import Ds from"fs";import we from"path";var Ir,Xo=m(()=>{"use strict";ne();Ke();ke();pt();Ir=class{static{c(this,"TemplateManagerImpl")}templateCache=new Map;async getAvailableTemplates(){try{let e=$.findTemplatesDir();if(!e)return[];let t=[],r=Ds.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of r)try{let n=await this.getTemplateInfo(o);n&&t.push(n)}catch{console.warn(`\u8DF3\u8FC7\u65E0\u6548\u6A21\u677F: ${o}`)}return t}catch{throw new S("\u65E0\u6CD5\u8BFB\u53D6\u6A21\u677F\u76EE\u5F55",$.findTemplatesDir()||"")}}async getTemplateInfo(e){try{if(Q.validateTemplateName(e),this.templateCache.has(e))return this.templateCache.get(e);let t=$.getTemplatePath(e);if(!t)return null;let r=we.join(t,"template.json"),o={};if(P.exists(r))try{let a=P.readFile(r);o=JSON.parse(a)}catch{console.warn(`\u6A21\u677F\u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${e}`)}let n=this.getTemplateFiles(t),s={name:e,path:t,description:o.description||`${e} \u6A21\u677F`,version:o.version||"1.0.0",author:o.author,files:n};return this.templateCache.set(e,s),s}catch(t){throw t instanceof M?t:new S(`\u65E0\u6CD5\u83B7\u53D6\u6A21\u677F\u4FE1\u606F: ${e}`,"")}}async copyTemplate(e,t){await this.createProject({templateName:e,targetPath:t,projectName:we.basename(t)})}async createProject(e){try{this.validateCreateOptions(e);let t=e.templateName||"default",r=await this.getTemplateInfo(t);if(!r)throw new S(`\u6A21\u677F\u4E0D\u5B58\u5728: ${t}`,"");let o=we.resolve(e.targetPath);if(P.exists(o))throw S.alreadyExists(o);P.ensureDir(o),await this.copyTemplateFiles(r,o,e),await this.processTemplateVariables(o,e),console.log(`\u2705 \u9879\u76EE\u521B\u5EFA\u6210\u529F: ${o}`)}catch(t){throw t instanceof S||t instanceof M?t:new S(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,e.targetPath)}}async validateTemplate(e){try{let t=await this.getTemplateInfo(e);if(!t)return!1;let r=["package.json"];for(let o of r){let n=we.join(t.path,o);if(!P.exists(n))return console.warn(`\u6A21\u677F\u7F3A\u5C11\u5FC5\u8981\u6587\u4EF6: ${o}`),!1}return!0}catch{return!1}}clearCache(){this.templateCache.clear()}getTemplateFiles(e){try{return P.listDirectory(e,{recursive:!0,includeHidden:!1}).filter(r=>{let o=we.relative(e,r);return!o.startsWith(".")&&o!=="template.json"&&!o.includes("node_modules")})}catch{return[]}}validateCreateOptions(e){Q.validateRequired(e.targetPath,"targetPath"),Q.validateRequired(e.projectName,"projectName"),Q.validateProjectName(e.projectName),e.templateName&&Q.validateTemplateName(e.templateName)}async copyTemplateFiles(e,t,r){try{P.copyDirectory(e.path,t,{exclude:["template.json",".git","node_modules"],overwrite:!1,recursive:!0})}catch(o){throw new S(`\u590D\u5236\u6A21\u677F\u6587\u4EF6\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`,e.path)}}async processTemplateVariables(e,t){try{let r={PROJECT_NAME:t.projectName,PROJECT_NAME_LOWER:t.projectName.toLowerCase(),PROJECT_NAME_UPPER:t.projectName.toUpperCase(),...t.variables},o=["package.json","README.md","src/**/*.ts","src/**/*.js","src/**/*.json"];for(let n of o){let s=this.findFilesByPattern(e,n);for(let a of s)await this.replaceVariablesInFile(a,r)}}catch(r){console.warn(`\u5904\u7406\u6A21\u677F\u53D8\u91CF\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}findFilesByPattern(e,t){try{if(!t.includes("*")){let n=we.join(e,t);return P.exists(n)?[n]:[]}let r=P.listDirectory(e,{recursive:!0}),o=new RegExp(t.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*"));return r.filter(n=>{let s=we.relative(e,n);return o.test(s)})}catch{return[]}}async replaceVariablesInFile(e,t){try{let r=P.readFile(e),o=!1;for(let[n,s]of Object.entries(t)){let a=new RegExp(`{{\\s*${n}\\s*}}`,"g");a.test(r)&&(r=r.replace(a,s),o=!0)}o&&P.writeFile(e,r,{overwrite:!0})}catch(r){console.warn(`\u66FF\u6362\u6587\u4EF6\u53D8\u91CF\u5931\u8D25 ${e}: ${r instanceof Error?r.message:String(r)}`)}}}});async function Pe(){return $r.create()}var $r,Mr=m(()=>{"use strict";y();Z();ar();Ke();cr();ke();Ze();pt();lr();$r=class i{static{c(this,"DIContainer")}instances=new Map;factories=new Map;asyncFactories=new Map;singletons=new Set;register(e,t,r=!1){this.factories.set(e,t),r&&this.singletons.add(e)}registerSingleton(e,t){this.register(e,t,!0)}registerInstance(e,t){this.instances.set(e,t),this.singletons.add(e)}get(e){if(this.singletons.has(e)&&this.instances.has(e))return this.instances.get(e);let t=this.factories.get(e);if(!t)throw new Error(`Service ${e} not registered`);let r=t();return this.singletons.has(e)&&this.instances.set(e,r),r}has(e){return this.factories.has(e)||this.instances.has(e)}clear(){this.instances.clear(),this.factories.clear(),this.singletons.clear()}getRegisteredKeys(){let e=Array.from(this.factories.keys()),t=Array.from(this.instances.keys());return[...new Set([...e,...t])]}static create(){let e=new i;return e.registerSingleton("versionUtils",()=>me),e.registerSingleton("platformUtils",()=>G),e.registerSingleton("formatUtils",()=>Ae),e.registerSingleton("fileUtils",()=>P),e.registerSingleton("pathUtils",()=>$),e.registerSingleton("validation",()=>Q),e.registerSingleton("configManager",()=>u),e.registerSingleton("logger",()=>g),e.registerSingleton("errorHandler",()=>se),e.registerSingleton("processManager",()=>{let t=(gr(),oe(Xr));return new t.ProcessManagerImpl}),e.registerSingleton("daemonManager",()=>{let t=(Yr(),oe(Zr)),r=e.get("processManager"),o=e.get("logger");return new t.DaemonManagerImpl(r,o)}),e.registerSingleton("serviceManager",()=>{let t=(qo(),oe(Go)),r=e.get("processManager"),o=e.get("configManager"),n=e.get("logger");return new t.ServiceManagerImpl(r,o,n)}),e.registerSingleton("templateManager",()=>{let t=(Xo(),oe(Jo));return new t.TemplateManagerImpl}),e}};c(Pe,"createContainer")});var W,be=m(()=>{"use strict";W=class{constructor(e){this.container=e}static{c(this,"BaseCommandHandler")}options;subcommands;getService(e){return this.container.get(e)}handleError(e){this.getService("errorHandler").handle(e)}validateArgs(e,t){if(e.length<t)throw new Error(`\u547D\u4EE4\u9700\u8981\u81F3\u5C11 ${t} \u4E2A\u53C2\u6570\uFF0C\u4F46\u53EA\u63D0\u4F9B\u4E86 ${e.length} \u4E2A`)}}});var Ko={};B(Ko,{ServiceCommandHandler:()=>xr});var xr,Zo=m(()=>{"use strict";y();be();xr=class extends W{static{c(this,"ServiceCommandHandler")}name="service";description="\u670D\u52A1\u7BA1\u7406\u547D\u4EE4";subcommands=[{name:"start",description:"\u542F\u52A8\u670D\u52A1",options:[{flags:"-d, --daemon",description:"\u5728\u540E\u53F0\u8FD0\u884C\u670D\u52A1"},{flags:"-u, --ui",description:"\u540C\u65F6\u542F\u52A8 Web UI \u670D\u52A1"},{flags:"--debug",description:"\u542F\u7528\u8C03\u8BD5\u6A21\u5F0F (\u8F93\u51FADEBUG\u7EA7\u522B\u65E5\u5FD7)"},{flags:"--stdio",description:"\u4EE5 stdio \u6A21\u5F0F\u8FD0\u884C MCP Server (\u7528\u4E8E Cursor \u7B49\u5BA2\u6237\u7AEF)"}],execute:c(async(e,t)=>{await this.handleStart(t)},"execute")},{name:"stop",description:"\u505C\u6B62\u670D\u52A1",execute:c(async(e,t)=>{await this.handleStop()},"execute")},{name:"status",description:"\u68C0\u67E5\u670D\u52A1\u72B6\u6001",execute:c(async(e,t)=>{await this.handleStatus()},"execute")},{name:"restart",description:"\u91CD\u542F\u670D\u52A1",options:[{flags:"-d, --daemon",description:"\u5728\u540E\u53F0\u8FD0\u884C\u670D\u52A1"},{flags:"-u, --ui",description:"\u540C\u65F6\u542F\u52A8 Web UI \u670D\u52A1"}],execute:c(async(e,t)=>{await this.handleRestart(t)},"execute")},{name:"attach",description:"\u8FDE\u63A5\u5230\u540E\u53F0\u670D\u52A1\u67E5\u770B\u65E5\u5FD7",execute:c(async(e,t)=>{await this.handleAttach()},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("\u670D\u52A1\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleStart(e){try{e.debug&&zr("debug");let t=this.getService("serviceManager");e.stdio?await this.startStdioMode():await t.start({daemon:e.daemon||!1,ui:e.ui||!1})}catch(t){this.handleError(t)}}async handleStop(){try{await this.getService("serviceManager").stop()}catch(e){this.handleError(e)}}async handleStatus(){try{let t=await this.getService("serviceManager").getStatus();t.running?(console.log(`\u2705 \u670D\u52A1\u6B63\u5728\u8FD0\u884C (PID: ${t.pid})`),t.uptime&&console.log(`\u23F1\uFE0F \u8FD0\u884C\u65F6\u95F4: ${t.uptime}`),t.mode&&console.log(`\u{1F527} \u8FD0\u884C\u6A21\u5F0F: ${t.mode}`)):console.log("\u274C \u670D\u52A1\u672A\u8FD0\u884C")}catch(e){this.handleError(e)}}async handleRestart(e){try{await this.getService("serviceManager").restart({daemon:e.daemon||!1,ui:e.ui||!1})}catch(t){this.handleError(t)}}async handleAttach(){try{await this.getService("daemonManager").attachToLogs()}catch(e){this.handleError(e)}}async startStdioMode(){let{spawn:e}=await import("child_process"),{fileURLToPath:t}=await import("url"),r=await import("path"),o=t(import.meta.url),n=r.dirname(o),s=r.join(n,"mcpServerProxy.js");e("node",[s],{stdio:"inherit",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}})}}});var Yo={};B(Yo,{ConfigCommandHandler:()=>Ar});import Ns from"path";import b from"chalk";import Or from"ora";var Ar,Qo=m(()=>{"use strict";be();Ar=class extends W{static{c(this,"ConfigCommandHandler")}name="config";description="\u914D\u7F6E\u7BA1\u7406\u547D\u4EE4";subcommands=[{name:"init",description:"\u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6",options:[{flags:"-f, --format <format>",description:"\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F (json, json5, jsonc)",defaultValue:"json"}],execute:c(async(e,t)=>{await this.handleInit(t)},"execute")},{name:"get",description:"\u67E5\u770B\u914D\u7F6E\u503C",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleGet(e[0])},"execute")},{name:"set",description:"\u8BBE\u7F6E\u914D\u7F6E\u503C",execute:c(async(e,t)=>{this.validateArgs(e,2),await this.handleSet(e[0],e[1])},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("\u914D\u7F6E\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleInit(e){let t=Or("\u521D\u59CB\u5316\u914D\u7F6E...").start();try{let r=e.format;if(r!=="json"&&r!=="json5"&&r!=="jsonc")throw new Error("\u683C\u5F0F\u5FC5\u987B\u662F json, json5 \u6216 jsonc");let o=this.getService("configManager");if(o.configExists()){t.warn("\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728"),console.log(b.yellow("\u5982\u9700\u91CD\u65B0\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u5220\u9664\u73B0\u6709\u7684\u914D\u7F6E\u6587\u4EF6"));return}o.initConfig(r),t.succeed("\u914D\u7F6E\u6587\u4EF6\u521D\u59CB\u5316\u6210\u529F");let n=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),s=`xiaozhi.config.${r}`,a=Ns.join(n,s);console.log(b.green(`\u2705 \u914D\u7F6E\u6587\u4EF6\u5DF2\u521B\u5EFA: ${s}`)),console.log(b.yellow("\u{1F4DD} \u8BF7\u7F16\u8F91\u914D\u7F6E\u6587\u4EF6\u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9:")),console.log(b.gray(` \u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84: ${a}`)),console.log(b.yellow("\u{1F4A1} \u6216\u8005\u4F7F\u7528\u547D\u4EE4\u8BBE\u7F6E:")),console.log(b.gray(" xiaozhi config set mcpEndpoint <your-endpoint-url>"))}catch(r){t.fail(`\u521D\u59CB\u5316\u914D\u7F6E\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleGet(e){let t=Or("\u8BFB\u53D6\u914D\u7F6E...").start();try{let r=this.getService("configManager");if(!r.configExists()){t.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log(b.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}let o=r.getConfig();switch(e){case"mcpEndpoint":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let n=r.getMcpEndpoints();n.length===0?console.log(b.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):n.length===1?console.log(b.green(`MCP \u7AEF\u70B9: ${n[0]}`)):(console.log(b.green(`MCP \u7AEF\u70B9 (${n.length} \u4E2A):`)),n.forEach((s,a)=>{console.log(b.gray(` ${a+1}. ${s}`))}));break}case"mcpServers":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(b.green("MCP \u670D\u52A1:"));for(let[n,s]of Object.entries(o.mcpServers)){let a=s;"type"in a&&a.type==="sse"?console.log(b.gray(` ${n}: [SSE] ${a.url}`)):console.log(b.gray(` ${n}: ${a.command} ${a.args.join(" ")}`))}break;case"connection":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let n=r.getConnectionConfig();console.log(b.green("\u8FDE\u63A5\u914D\u7F6E:")),console.log(b.gray(` \u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${n.heartbeatInterval}ms`)),console.log(b.gray(` \u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${n.heartbeatTimeout}ms`)),console.log(b.gray(` \u91CD\u8FDE\u95F4\u9694: ${n.reconnectInterval}ms`));break}case"heartbeatInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(b.green(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${r.getHeartbeatInterval()}ms`));break;case"heartbeatTimeout":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(b.green(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${r.getHeartbeatTimeout()}ms`));break;case"reconnectInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(b.green(`\u91CD\u8FDE\u95F4\u9694: ${r.getReconnectInterval()}ms`));break;default:t.fail(`\u672A\u77E5\u7684\u914D\u7F6E\u9879: ${e}`),console.log(b.yellow("\u652F\u6301\u7684\u914D\u7F6E\u9879: mcpEndpoint, mcpServers, connection, heartbeatInterval, heartbeatTimeout, reconnectInterval"))}}catch(r){t.fail(`\u8BFB\u53D6\u914D\u7F6E\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleSet(e,t){let r=Or("\u66F4\u65B0\u914D\u7F6E...").start();try{let o=this.getService("configManager");if(!o.configExists()){r.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log(b.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}switch(e){case"mcpEndpoint":o.updateMcpEndpoint(t),r.succeed(`MCP \u7AEF\u70B9\u5DF2\u8BBE\u7F6E\u4E3A: ${t}`);break;case"heartbeatInterval":{let n=Number.parseInt(t);if(Number.isNaN(n)||n<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u662F\u6B63\u6574\u6570");o.updateHeartbeatInterval(n),r.succeed(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5DF2\u8BBE\u7F6E\u4E3A: ${n}ms`);break}case"heartbeatTimeout":{let n=Number.parseInt(t);if(Number.isNaN(n)||n<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u662F\u6B63\u6574\u6570");o.updateHeartbeatTimeout(n),r.succeed(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5DF2\u8BBE\u7F6E\u4E3A: ${n}ms`);break}case"reconnectInterval":{let n=Number.parseInt(t);if(Number.isNaN(n)||n<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u662F\u6B63\u6574\u6570");o.updateReconnectInterval(n),r.succeed(`\u91CD\u8FDE\u95F4\u9694\u5DF2\u8BBE\u7F6E\u4E3A: ${n}ms`);break}default:r.fail(`\u4E0D\u652F\u6301\u8BBE\u7F6E\u7684\u914D\u7F6E\u9879: ${e}`),console.log(b.yellow("\u652F\u6301\u8BBE\u7F6E\u7684\u914D\u7F6E\u9879: mcpEndpoint, heartbeatInterval, heartbeatTimeout, reconnectInterval"))}}catch(o){r.fail(`\u8BBE\u7F6E\u914D\u7F6E\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`),this.handleError(o)}}}});var en={};B(en,{ProjectCommandHandler:()=>kr});import _s from"path";import k from"chalk";import Ls from"ora";var kr,tn=m(()=>{"use strict";be();kr=class extends W{static{c(this,"ProjectCommandHandler")}name="create";description="\u521B\u5EFA\u9879\u76EE";options=[{flags:"-t, --template <templateName>",description:"\u4F7F\u7528\u6307\u5B9A\u6A21\u677F\u521B\u5EFA\u9879\u76EE"}];constructor(e){super(e)}async execute(e,t){this.validateArgs(e,1);let r=e[0];await this.handleCreate(r,t)}async handleCreate(e,t){let r=Ls("\u521D\u59CB\u5316\u9879\u76EE...").start();try{let o=this.getService("templateManager"),n=this.getService("fileUtils"),s=_s.join(process.cwd(),e);if(await n.exists(s)){r.fail(`\u76EE\u5F55 "${e}" \u5DF2\u5B58\u5728`),console.log(k.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u9009\u62E9\u4E0D\u540C\u7684\u9879\u76EE\u540D\u79F0\u6216\u5220\u9664\u73B0\u6709\u76EE\u5F55"));return}t.template?await this.createFromTemplate(e,t.template,s,r,o):await this.createBasicProject(e,s,r,o)}catch(o){r.fail(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`),this.handleError(o)}}async createFromTemplate(e,t,r,o,n){o.text="\u68C0\u67E5\u6A21\u677F...";let s=await n.getAvailableTemplates();if(s.length===0){o.fail("\u627E\u4E0D\u5230\u53EF\u7528\u6A21\u677F"),console.log(k.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u786E\u4FDD xiaozhi-client \u6B63\u786E\u5B89\u88C5"));return}let a=t;if(!await n.validateTemplate(a)){o.fail(`\u6A21\u677F "${a}" \u4E0D\u5B58\u5728`);let h=this.findSimilarTemplate(a,s);if(h)if(console.log(k.yellow(`\u{1F4A1} \u4F60\u662F\u60F3\u4F7F\u7528\u6A21\u677F "${h}" \u5417\uFF1F`)),await this.askUserConfirmation(k.cyan("\u786E\u8BA4\u4F7F\u7528\u6B64\u6A21\u677F\uFF1F(y/n): ")))a=h;else{this.showAvailableTemplates(s);return}else{this.showAvailableTemplates(s);return}}o.text=`\u4ECE\u6A21\u677F "${a}" \u521B\u5EFA\u9879\u76EE "${e}"...`,await n.createProject({templateName:a,targetPath:r,projectName:e}),o.succeed(`\u9879\u76EE "${e}" \u521B\u5EFA\u6210\u529F`),console.log(k.green("\u2705 \u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(k.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(k.gray(` cd ${e}`)),console.log(k.gray(" pnpm install # \u5B89\u88C5\u4F9D\u8D56")),console.log(k.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9")),console.log(k.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1"))}async createBasicProject(e,t,r,o){r.text=`\u521B\u5EFA\u57FA\u672C\u9879\u76EE "${e}"...`,await o.createProject({templateName:null,targetPath:t,projectName:e}),r.succeed(`\u9879\u76EE "${e}" \u521B\u5EFA\u6210\u529F`),console.log(k.green("\u2705 \u57FA\u672C\u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(k.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(k.gray(` cd ${e}`)),console.log(k.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9\u548C\u670D\u52A1")),console.log(k.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1")),console.log(k.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 --template \u9009\u9879\u53EF\u4EE5\u4ECE\u6A21\u677F\u521B\u5EFA\u9879\u76EE"))}showAvailableTemplates(e){console.log(k.yellow("\u53EF\u7528\u7684\u6A21\u677F:"));for(let t of e)console.log(k.gray(` - ${t}`))}findSimilarTemplate(e,t){let r=this.getService("formatUtils"),o=null,n=0;for(let s of t){let a=r.calculateSimilarity(e.toLowerCase(),s.toLowerCase());a>n&&a>.6&&(n=a,o=s)}return o}async askUserConfirmation(e){let r=(await import("readline")).createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{r.question(e,n=>{r.close(),o(n.toLowerCase().trim()==="y"||n.toLowerCase().trim()==="yes")})})}}});var Gt,rn=m(()=>{"use strict";y();gr();Z();Gt=class{static{c(this,"ToolCallService")}logger;processManager;baseUrl;constructor(){this.logger=g.withTag("ToolCallService"),this.processManager=new Ye;try{let e=u.getWebUIPort()??9999;this.baseUrl=`http://localhost:${e}`}catch{this.baseUrl="http://localhost:9999"}}async callTool(e,t,r){await this.validateServiceStatus();try{let o=await fetch(`${this.baseUrl}/api/tools/call`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceName:e,toolName:t,args:r})});if(!o.ok){let s=await o.json();throw new Error(s.error?.message||`HTTP ${o.status}: ${o.statusText}`)}let n=await o.json();if(!n.success)throw new Error(n.error?.message||"\u5DE5\u5177\u8C03\u7528\u5931\u8D25");return n.data}catch(o){throw this.logger.error(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e}/${t}`,o instanceof Error?o.message:String(o)),o}}parseJsonArgs(e){try{return JSON.parse(e)}catch(t){throw new Error(`\u53C2\u6570\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u4F7F\u7528\u6709\u6548\u7684 JSON \u683C\u5F0F\u3002\u9519\u8BEF\u8BE6\u60C5: ${t instanceof Error?t.message:String(t)}`)}}async validateServiceStatus(){if(!this.processManager.getServiceStatus().running)throw new Error("xiaozhi \u670D\u52A1\u672A\u542F\u52A8\u3002\u8BF7\u5148\u8FD0\u884C 'xiaozhi start' \u6216 'xiaozhi start -d' \u542F\u52A8\u670D\u52A1\u3002");try{let t=await fetch(`${this.baseUrl}/api/status`,{method:"GET",signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Web \u670D\u52A1\u5668\u54CD\u5E94\u9519\u8BEF: ${t.status}`)}catch(t){throw t instanceof Error&&t.name==="AbortError"?new Error("\u8FDE\u63A5 xiaozhi \u670D\u52A1\u8D85\u65F6\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u662F\u5426\u6B63\u5E38\u8FD0\u884C\u3002"):new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230 xiaozhi \u670D\u52A1\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002\u9519\u8BEF\u8BE6\u60C5: ${t instanceof Error?t.message:String(t)}`)}}formatOutput(e){return JSON.stringify(e)}async getServiceStatus(){try{let e=this.processManager.getServiceStatus();if(!e.running)return"\u670D\u52A1\u672A\u542F\u52A8";try{let t=await fetch(`${this.baseUrl}/api/tools/list`,{method:"GET",signal:AbortSignal.timeout(3e3)});if(t.ok){let r=await t.json();if(r.success)return`\u670D\u52A1\u5DF2\u542F\u52A8 (PID: ${e.pid}, ${r.data.totalTools} \u4E2A\u5DE5\u5177\u53EF\u7528)`}return`\u670D\u52A1\u8FDB\u7A0B\u8FD0\u884C\u4E2D (PID: ${e.pid})\uFF0C\u4F46 MCP \u670D\u52A1\u53EF\u80FD\u672A\u5B8C\u5168\u521D\u59CB\u5316`}catch{return`\u670D\u52A1\u8FDB\u7A0B\u8FD0\u884C\u4E2D (PID: ${e.pid})\uFF0C\u4F46\u65E0\u6CD5\u8FDE\u63A5\u5230 Web API`}}catch(e){return`\u670D\u52A1\u72B6\u6001\u68C0\u67E5\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`}}}});var Jt={};B(Jt,{getDisplayWidth:()=>Nr,listMcpServers:()=>Hs,listServerTools:()=>js,setToolEnabled:()=>zs,truncateToWidth:()=>qt});import f from"chalk";import on from"cli-table3";import Dr from"ora";function Nr(i){let e=0;for(let t of i)/[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef]/.test(t)?e+=2:e+=1;return e}function qt(i,e){if(Nr(i)<=e)return i;if(e<=3)return"";let t="",r=0,o=!1;for(let n of i){let s=/[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef]/.test(n)?2:1;if(r+s>e-3){if(!o)return"";t+="...";break}t+=n,r+=s,o=!0}return t}async function Hs(i={}){let e=Dr("\u83B7\u53D6 MCP \u670D\u52A1\u5217\u8868...").start();try{let t=u.getMcpServers(),r=Object.keys(t),o=u.getCustomMCPTools(),n=o.length>0,s=r.length+(n?1:0);if(s===0){e.warn("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u670D\u52A1\u6216 customMCP \u5DE5\u5177"),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi config' \u547D\u4EE4\u914D\u7F6E MCP \u670D\u52A1\u6216\u5728 xiaozhi.config.json \u4E2D\u914D\u7F6E customMCP \u5DE5\u5177"));return}if(e.succeed(`\u627E\u5230 ${s} \u4E2A MCP \u670D\u52A1${n?" (\u5305\u62EC customMCP)":""}`),i.tools){console.log(),console.log(f.bold("MCP \u670D\u52A1\u5DE5\u5177\u5217\u8868:")),console.log();let a=8,l=[];for(let p of r){let d=u.getServerToolsConfig(p),C=Object.keys(d);l.push(...C)}if(n){let p=o.map(d=>d.name);l.push(...p)}for(let p of l){let d=Nr(p);d>a&&(a=d)}a=Math.max(10,Math.min(a+2,30));let h=new on({head:[f.bold("MCP"),f.bold("\u5DE5\u5177\u540D\u79F0"),f.bold("\u72B6\u6001"),f.bold("\u63CF\u8FF0")],colWidths:[15,a,8,40],wordWrap:!0,style:{head:[],border:[]}});if(n)for(let p of o){let d=qt(p.description||"",32);h.push(["customMCP",p.name,f.green("\u542F\u7528"),d])}for(let p of r){let d=u.getServerToolsConfig(p),C=Object.keys(d);if(C.length===0)h.push([f.gray(p),f.gray("-"),f.gray("-"),f.gray("\u6682\u672A\u8BC6\u522B\u5230\u76F8\u5173\u5DE5\u5177")]);else{h.length>0&&h.push([{colSpan:4,content:""}]);for(let E of C){let R=d[E],J=R.enable?f.green("\u542F\u7528"):f.red("\u7981\u7528"),V=qt(R.description||"",32);h.push([p,E,J,V])}}}console.log(h.toString())}else{console.log(),console.log(f.bold("MCP \u670D\u52A1\u5217\u8868:")),console.log(),n&&(console.log(`${f.cyan("\u2022")} ${f.bold("customMCP")}`),console.log(` \u7C7B\u578B: ${f.gray("\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177")}`),console.log(` \u914D\u7F6E: ${f.gray("xiaozhi.config.json")}`),console.log(` \u5DE5\u5177: ${f.green(o.length)} \u542F\u7528 / ${f.yellow(o.length)} \u603B\u8BA1`),console.log());for(let a of r){let l=t[a],h=u.getServerToolsConfig(a),p=Object.keys(h).length,d=Object.values(h).filter(C=>C.enable!==!1).length;console.log(`${f.cyan("\u2022")} ${f.bold(a)}`),"url"in l?("type"in l&&l.type==="sse"?console.log(` \u7C7B\u578B: ${f.gray("SSE")}`):console.log(` \u7C7B\u578B: ${f.gray("Streamable HTTP")}`),console.log(` URL: ${f.gray(l.url)}`)):console.log(` \u547D\u4EE4: ${f.gray(l.command)} ${f.gray(l.args.join(" "))}`),p>0?console.log(` \u5DE5\u5177: ${f.green(d)} \u542F\u7528 / ${f.yellow(p)} \u603B\u8BA1`):console.log(` \u5DE5\u5177: ${f.gray("\u672A\u626B\u63CF (\u8BF7\u5148\u542F\u52A8\u670D\u52A1)")}`),console.log()}}console.log(f.gray("\u{1F4A1} \u63D0\u793A:")),console.log(f.gray(" - \u4F7F\u7528 'xiaozhi mcp list --tools' \u67E5\u770B\u6240\u6709\u5DE5\u5177")),console.log(f.gray(" - \u4F7F\u7528 'xiaozhi mcp <\u670D\u52A1\u540D> list' \u67E5\u770B\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177")),console.log(f.gray(" - \u4F7F\u7528 'xiaozhi mcp <\u670D\u52A1\u540D> <\u5DE5\u5177\u540D> enable/disable' \u542F\u7528/\u7981\u7528\u5DE5\u5177"))}catch(t){e.fail("\u83B7\u53D6 MCP \u670D\u52A1\u5217\u8868\u5931\u8D25"),console.error(f.red(`\u9519\u8BEF: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function js(i){let e=Dr(`\u83B7\u53D6 ${i} \u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868...`).start();try{if(!u.getMcpServers()[i]){e.fail(`\u670D\u52A1 '${i}' \u4E0D\u5B58\u5728`),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u670D\u52A1"));return}let r=u.getServerToolsConfig(i),o=Object.keys(r);if(o.length===0){e.warn(`\u670D\u52A1 '${i}' \u6682\u65E0\u5DE5\u5177\u4FE1\u606F`),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u542F\u52A8\u670D\u52A1\u4EE5\u626B\u63CF\u5DE5\u5177\u5217\u8868"));return}e.succeed(`\u670D\u52A1 '${i}' \u5171\u6709 ${o.length} \u4E2A\u5DE5\u5177`),console.log(),console.log(f.bold(`${i} \u670D\u52A1\u5DE5\u5177\u5217\u8868:`)),console.log();let n=new on({head:[f.bold("\u5DE5\u5177\u540D\u79F0"),f.bold("\u72B6\u6001"),f.bold("\u63CF\u8FF0")],colWidths:[30,8,50],wordWrap:!0,style:{head:[],border:[]}});for(let s of o){let a=r[s],l=a.enable?f.green("\u542F\u7528"):f.red("\u7981\u7528"),h=qt(a.description||"",40);n.push([s,l,h])}console.log(n.toString()),console.log(),console.log(f.gray("\u{1F4A1} \u63D0\u793A:")),console.log(f.gray(` - \u4F7F\u7528 'xiaozhi mcp ${i} <\u5DE5\u5177\u540D> enable' \u542F\u7528\u5DE5\u5177`)),console.log(f.gray(` - \u4F7F\u7528 'xiaozhi mcp ${i} <\u5DE5\u5177\u540D> disable' \u7981\u7528\u5DE5\u5177`))}catch(t){e.fail("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25"),console.error(f.red(`\u9519\u8BEF: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function zs(i,e,t){let r=t?"\u542F\u7528":"\u7981\u7528",o=Dr(`${r}\u5DE5\u5177 ${i}/${e}...`).start();try{if(!u.getMcpServers()[i]){o.fail(`\u670D\u52A1 '${i}' \u4E0D\u5B58\u5728`),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u670D\u52A1"));return}let s=u.getServerToolsConfig(i);if(!s[e]){o.fail(`\u5DE5\u5177 '${e}' \u5728\u670D\u52A1 '${i}' \u4E2D\u4E0D\u5B58\u5728`),console.log(f.yellow(`\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp ${i} list' \u67E5\u770B\u8BE5\u670D\u52A1\u7684\u6240\u6709\u5DE5\u5177`));return}u.setToolEnabled(i,e,t,s[e].description),o.succeed(`\u6210\u529F${r}\u5DE5\u5177 ${f.cyan(i)}/${f.cyan(e)}`),console.log(),console.log(f.gray("\u{1F4A1} \u63D0\u793A: \u5DE5\u5177\u72B6\u6001\u66F4\u6539\u5C06\u5728\u4E0B\u6B21\u542F\u52A8\u670D\u52A1\u65F6\u751F\u6548"))}catch(n){o.fail(`${r}\u5DE5\u5177\u5931\u8D25`),console.error(f.red(`\u9519\u8BEF: ${n instanceof Error?n.message:String(n)}`)),process.exit(1)}}var Xt=m(()=>{"use strict";Z();c(Nr,"getDisplayWidth");c(qt,"truncateToWidth");c(Hs,"listMcpServers");c(js,"listServerTools");c(zs,"setToolEnabled")});var nn={};B(nn,{McpCommandHandler:()=>_r});import Re from"chalk";var _r,sn=m(()=>{"use strict";rn();be();_r=class extends W{static{c(this,"McpCommandHandler")}name="mcp";description="MCP \u670D\u52A1\u548C\u5DE5\u5177\u7BA1\u7406";subcommands=[{name:"list",description:"\u5217\u51FA MCP \u670D\u52A1",options:[{flags:"--tools",description:"\u663E\u793A\u6240\u6709\u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868"}],execute:c(async(e,t)=>{await this.handleList(t)},"execute")},{name:"server",description:"\u7BA1\u7406\u6307\u5B9A\u7684 MCP \u670D\u52A1",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleServer(e[0])},"execute")},{name:"tool",description:"\u542F\u7528\u6216\u7981\u7528\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177",execute:c(async(e,t)=>{this.validateArgs(e,3);let[r,o,n]=e;n!=="enable"&&n!=="disable"&&(console.error(Re.red("\u9519\u8BEF: \u64CD\u4F5C\u5FC5\u987B\u662F 'enable' \u6216 'disable'")),process.exit(1));let s=n==="enable";await this.handleTool(r,o,s)},"execute")},{name:"call",description:"\u8C03\u7528\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177",options:[{flags:"--args <json>",description:"\u5DE5\u5177\u53C2\u6570 (JSON \u683C\u5F0F)",defaultValue:"{}"}],execute:c(async(e,t)=>{this.validateArgs(e,2);let[r,o]=e;await this.handleCall(r,o,t.args)},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("MCP \u670D\u52A1\u548C\u5DE5\u5177\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleList(e){try{let{listMcpServers:t}=await Promise.resolve().then(()=>(Xt(),Jt));await t(e)}catch(t){this.handleError(t)}}async handleServer(e){try{let{listServerTools:t}=await Promise.resolve().then(()=>(Xt(),Jt));await t(e)}catch(t){this.handleError(t)}}async handleTool(e,t,r){try{let{setToolEnabled:o}=await Promise.resolve().then(()=>(Xt(),Jt));await o(e,t,r)}catch(o){this.handleError(o)}}async handleCall(e,t,r){try{let o=new Gt,n=o.parseJsonArgs(r),s=await o.callTool(e,t,n);console.log(o.formatOutput(s))}catch(o){console.log(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e}/${t}`),console.error(Re.red("\u9519\u8BEF:"),o.message),o.message.includes("\u670D\u52A1\u672A\u542F\u52A8")?(console.log(),console.log(Re.yellow("\u{1F4A1} \u8BF7\u5148\u542F\u52A8\u670D\u52A1:")),console.log(Re.gray(" xiaozhi start # \u524D\u53F0\u542F\u52A8")),console.log(Re.gray(" xiaozhi start -d # \u540E\u53F0\u542F\u52A8"))):o.message.includes("\u53C2\u6570\u683C\u5F0F\u9519\u8BEF")&&(console.log(),console.log(Re.yellow("\u{1F4A1} \u6B63\u786E\u683C\u5F0F\u793A\u4F8B:")),console.log(Re.gray(` xiaozhi mcp call ${e} ${t} --args '{"param": "value"}'`))),process.exit(1)}}}});var an={};B(an,{EndpointCommandHandler:()=>Lr});import Ve from"chalk";import Kt from"ora";var Lr,cn=m(()=>{"use strict";be();Lr=class extends W{static{c(this,"EndpointCommandHandler")}name="endpoint";description="\u7BA1\u7406 MCP \u7AEF\u70B9";subcommands=[{name:"list",description:"\u5217\u51FA\u6240\u6709 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{await this.handleList()},"execute")},{name:"add",description:"\u6DFB\u52A0\u65B0\u7684 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleAdd(e[0])},"execute")},{name:"remove",description:"\u79FB\u9664\u6307\u5B9A\u7684 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleRemove(e[0])},"execute")},{name:"set",description:"\u8BBE\u7F6E MCP \u7AEF\u70B9\uFF08\u53EF\u4EE5\u662F\u5355\u4E2A\u6216\u591A\u4E2A\uFF09",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleSet(e)},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("MCP \u7AEF\u70B9\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleList(){let e=Kt("\u8BFB\u53D6\u7AEF\u70B9\u914D\u7F6E...").start();try{let r=this.getService("configManager").getMcpEndpoints();e.succeed("\u7AEF\u70B9\u5217\u8868"),r.length===0?console.log(Ve.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):(console.log(Ve.green(`\u5171 ${r.length} \u4E2A\u7AEF\u70B9:`)),r.forEach((o,n)=>{console.log(Ve.gray(` ${n+1}. ${o}`))}))}catch(t){e.fail(`\u8BFB\u53D6\u7AEF\u70B9\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),this.handleError(t)}}async handleAdd(e){let t=Kt("\u6DFB\u52A0\u7AEF\u70B9...").start();try{let r=this.getService("configManager");r.addMcpEndpoint(e),t.succeed(`\u6210\u529F\u6DFB\u52A0\u7AEF\u70B9: ${e}`);let o=r.getMcpEndpoints();console.log(Ve.gray(`\u5F53\u524D\u5171 ${o.length} \u4E2A\u7AEF\u70B9`))}catch(r){t.fail(`\u6DFB\u52A0\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleRemove(e){let t=Kt("\u79FB\u9664\u7AEF\u70B9...").start();try{let r=this.getService("configManager");r.removeMcpEndpoint(e),t.succeed(`\u6210\u529F\u79FB\u9664\u7AEF\u70B9: ${e}`);let o=r.getMcpEndpoints();console.log(Ve.gray(`\u5F53\u524D\u5269\u4F59 ${o.length} \u4E2A\u7AEF\u70B9`))}catch(r){t.fail(`\u79FB\u9664\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleSet(e){let t=Kt("\u8BBE\u7F6E\u7AEF\u70B9...").start();try{let r=this.getService("configManager");if(e.length===1)r.updateMcpEndpoint(e[0]),t.succeed(`\u6210\u529F\u8BBE\u7F6E\u7AEF\u70B9: ${e[0]}`);else{r.updateMcpEndpoint(e),t.succeed(`\u6210\u529F\u8BBE\u7F6E ${e.length} \u4E2A\u7AEF\u70B9`);for(let[o,n]of e.entries())console.log(Ve.gray(` ${o+1}. ${n}`))}}catch(r){t.fail(`\u8BBE\u7F6E\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}}});var ln={};B(ln,{UICommandHandler:()=>Hr});import Ie from"chalk";import Us from"ora";var Hr,gn=m(()=>{"use strict";be();Hr=class extends W{static{c(this,"UICommandHandler")}name="ui";description="\u542F\u52A8\u914D\u7F6E\u7BA1\u7406\u7F51\u9875";constructor(e){super(e)}async execute(e,t){await this.handleUI()}async handleUI(){let e=Us("\u542F\u52A8 UI \u670D\u52A1...").start();try{let t=this.getService("configManager");if(!t.configExists()){e.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log(Ie.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}let{WebServer:r}=await Promise.resolve().then(()=>(br(),wr));await new r().start(),e.succeed("UI \u670D\u52A1\u5DF2\u542F\u52A8");let n=t.getWebUIPort();console.log(Ie.green("\u2705 \u914D\u7F6E\u7BA1\u7406\u7F51\u9875\u5DF2\u542F\u52A8\uFF0C\u53EF\u901A\u8FC7\u4EE5\u4E0B\u5730\u5740\u8BBF\u95EE:")),console.log(Ie.green(` \u672C\u5730\u8BBF\u95EE: http://localhost:${n}`)),console.log(Ie.green(` \u7F51\u7EDC\u8BBF\u95EE: http://<\u4F60\u7684IP\u5730\u5740>:${n}`)),console.log(Ie.yellow("\u{1F4A1} \u63D0\u793A: \u6309 Ctrl+C \u505C\u6B62\u670D\u52A1")),await this.openBrowser(`http://localhost:${n}`)}catch(t){e.fail(`\u542F\u52A8 UI \u670D\u52A1\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),this.handleError(t)}}async openBrowser(e){try{let{spawn:t}=await import("child_process"),r;process.platform==="darwin"?r=t("open",[e],{detached:!0,stdio:"ignore"}):process.platform==="win32"?r=t("cmd",["/c","start",e],{detached:!0,stdio:"ignore"}):r=t("xdg-open",[e],{detached:!0,stdio:"ignore"}),r.on("error",()=>{console.log(Ie.gray(`\u{1F4A1} \u63D0\u793A: \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE: ${e}`))}),r.unref()}catch{console.log(Ie.gray(`\u{1F4A1} \u63D0\u793A: \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE: ${e}`))}}}});Mr();import de from"chalk";import{Command as Fs}from"commander";ar();var Zt=class{constructor(e){this.container=e}static{c(this,"CommandHandlerFactory")}createHandlers(){return[this.createHandler("service"),this.createHandler("config"),this.createHandler("project"),this.createHandler("mcp"),this.createHandler("endpoint"),this.createHandler("ui")]}createHandler(e){switch(e){case"service":return this.createServiceCommandHandler();case"config":return this.createConfigCommandHandler();case"project":return this.createProjectCommandHandler();case"mcp":return this.createMcpCommandHandler();case"endpoint":return this.createEndpointCommandHandler();case"ui":return this.createUICommandHandler();default:throw new Error(`\u672A\u77E5\u7684\u547D\u4EE4\u5904\u7406\u5668\u7C7B\u578B: ${e}`)}}createServiceCommandHandler(){let{ServiceCommandHandler:e}=(Zo(),oe(Ko));return new e(this.container)}createConfigCommandHandler(){let{ConfigCommandHandler:e}=(Qo(),oe(Yo));return new e(this.container)}createProjectCommandHandler(){let{ProjectCommandHandler:e}=(tn(),oe(en));return new e(this.container)}createMcpCommandHandler(){let{McpCommandHandler:e}=(sn(),oe(nn));return new e(this.container)}createEndpointCommandHandler(){let{EndpointCommandHandler:e}=(cn(),oe(an));return new e(this.container)}createUICommandHandler(){let{UICommandHandler:e}=(gn(),oe(ln));return new e(this.container)}};var Yt=class{constructor(e){this.container=e;this.handlerFactory=new Zt(e)}static{c(this,"CommandRegistry")}handlers=[];handlerFactory;async registerCommands(e){try{this.registerVersionCommand(e),this.registerHelpCommand(e);let t=this.handlerFactory.createHandlers();for(let r of t)this.registerHandler(r),this.registerCommand(e,r);this.registerLegacyServiceCommands(e,t)}catch(t){se.handle(t)}}registerHandler(e){this.handlers.push(e)}registerCommand(e,t){if(t.subcommands&&t.subcommands.length>0){let r=e.command(t.name).description(t.description);for(let o of t.subcommands){let n=o.name;o.name==="get"?n="get <key>":o.name==="set"?n="set <key> <value>":o.name==="call"&&(n="call <serviceName> <toolName>");let s=r.command(n).description(o.description);if(o.options)for(let a of o.options)s.option(a.flags,a.description,a.defaultValue);s.action(async(...a)=>{try{let h=a[a.length-1].opts();await o.execute(a.slice(0,-1),h)}catch(l){se.handle(l)}})}r.action(async(...o)=>{try{let s=o[o.length-1].opts();await t.execute(o.slice(0,-1),s)}catch(n){se.handle(n)}})}else{let r=t.name;t.name==="create"&&(r="create <projectName>");let o=e.command(r).description(t.description);if(t.options)for(let n of t.options)o.option(n.flags,n.description,n.defaultValue);o.action(async(...n)=>{try{let a=n[n.length-1].opts();await t.execute(n.slice(0,-1),a)}catch(s){se.handle(s)}})}}registerVersionCommand(e){let t=this.container.get("versionUtils");e.version(t.getVersion(),"-v, --version","\u663E\u793A\u7248\u672C\u4FE1\u606F"),e.option("--info","\u663E\u793A\u8BE6\u7EC6\u4FE1\u606F"),e.option("--version-info","\u663E\u793A\u8BE6\u7EC6\u7248\u672C\u4FE1\u606F")}registerHelpCommand(e){e.helpOption("-h, --help","\u663E\u793A\u5E2E\u52A9\u4FE1\u606F").addHelpText("after",`
96
+ `;return e.html(r)}isWebPathAvailable(){return this.webPath!==null&&Ht(this.webPath)}getWebPath(){return this.webPath}reinitializeWebPath(){this.initializeWebPath()}}});var Ut,Fn=m(()=>{"use strict";y();Ut=class{static{c(this,"StatusApiHandler")}logger;statusService;constructor(e){this.logger=p.withTag("StatusApiHandler"),this.statusService=e}createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async getStatus(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u72B6\u6001\u8BF7\u6C42");let t=this.statusService.getFullStatus();return this.logger.debug("\u83B7\u53D6\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("STATUS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}async getClientStatus(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u5BA2\u6237\u7AEF\u72B6\u6001\u8BF7\u6C42");let t=this.statusService.getClientStatus();return this.logger.debug("\u83B7\u53D6\u5BA2\u6237\u7AEF\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u5BA2\u6237\u7AEF\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("CLIENT_STATUS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u5BA2\u6237\u7AEF\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}async getRestartStatus(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u91CD\u542F\u72B6\u6001\u8BF7\u6C42");let t=this.statusService.getRestartStatus();return this.logger.debug("\u83B7\u53D6\u91CD\u542F\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u91CD\u542F\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("RESTART_STATUS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u91CD\u542F\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}async checkClientConnected(e){try{this.logger.debug("\u5904\u7406\u68C0\u67E5\u5BA2\u6237\u7AEF\u8FDE\u63A5\u8BF7\u6C42");let t=this.statusService.isClientConnected();return this.logger.debug(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u72B6\u6001: ${t}`),e.json(this.createSuccessResponse({connected:t}))}catch(t){this.logger.error("\u68C0\u67E5\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5931\u8D25:",t);let r=this.createErrorResponse("CLIENT_CONNECTION_CHECK_ERROR",t instanceof Error?t.message:"\u68C0\u67E5\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5931\u8D25");return e.json(r,500)}}async getLastHeartbeat(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u6700\u540E\u5FC3\u8DF3\u65F6\u95F4\u8BF7\u6C42");let t=this.statusService.getLastHeartbeat();return this.logger.debug("\u83B7\u53D6\u6700\u540E\u5FC3\u8DF3\u65F6\u95F4\u6210\u529F"),e.json(this.createSuccessResponse({lastHeartbeat:t}))}catch(t){this.logger.error("\u83B7\u53D6\u6700\u540E\u5FC3\u8DF3\u65F6\u95F4\u5931\u8D25:",t);let r=this.createErrorResponse("HEARTBEAT_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u6700\u540E\u5FC3\u8DF3\u65F6\u95F4\u5931\u8D25");return e.json(r,500)}}async getActiveMCPServers(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u8BF7\u6C42");let t=this.statusService.getActiveMCPServers();return this.logger.debug("\u83B7\u53D6\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u6210\u529F"),e.json(this.createSuccessResponse({servers:t}))}catch(t){this.logger.error("\u83B7\u53D6\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u5931\u8D25:",t);let r=this.createErrorResponse("ACTIVE_MCP_SERVERS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u5931\u8D25");return e.json(r,500)}}async updateClientStatus(e){try{this.logger.debug("\u5904\u7406\u66F4\u65B0\u5BA2\u6237\u7AEF\u72B6\u6001\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\u72B6\u6001\u5BF9\u8C61");return e.json(r,400)}return this.statusService.updateClientInfo(t,"http-api"),this.logger.info("\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u6210\u529F"),e.json(this.createSuccessResponse(null,"\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u6210\u529F"))}catch(t){this.logger.error("\u66F4\u65B0\u5BA2\u6237\u7AEF\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("CLIENT_STATUS_UPDATE_ERROR",t instanceof Error?t.message:"\u66F4\u65B0\u5BA2\u6237\u7AEF\u72B6\u6001\u5931\u8D25");return e.json(r,400)}}async setActiveMCPServers(e){try{this.logger.debug("\u5904\u7406\u8BBE\u7F6E\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u8BF7\u6C42");let{servers:t}=await e.req.json();if(!Array.isArray(t)){let r=this.createErrorResponse("INVALID_REQUEST_BODY","servers \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4");return e.json(r,400)}return this.statusService.setActiveMCPServers(t),this.logger.info("\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u8BBE\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(null,"\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u8BBE\u7F6E\u6210\u529F"))}catch(t){this.logger.error("\u8BBE\u7F6E\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u5931\u8D25:",t);let r=this.createErrorResponse("ACTIVE_MCP_SERVERS_UPDATE_ERROR",t instanceof Error?t.message:"\u8BBE\u7F6E\u6D3B\u8DC3 MCP \u670D\u52A1\u5668\u5931\u8D25");return e.json(r,400)}}async resetStatus(e){try{return this.logger.info("\u5904\u7406\u91CD\u7F6E\u72B6\u6001\u8BF7\u6C42"),this.statusService.reset(),this.logger.info("\u72B6\u6001\u91CD\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(null,"\u72B6\u6001\u91CD\u7F6E\u6210\u529F"))}catch(t){this.logger.error("\u91CD\u7F6E\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("STATUS_RESET_ERROR",t instanceof Error?t.message:"\u91CD\u7F6E\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}}});var Ve,Wn=m(()=>{"use strict";Ve=(n=>(n.MCP="mcp",n.COZE="coze",n.HTTP="http",n.FUNCTION="function",n))(Ve||{})});import xs from"ajv";import Ft from"dayjs";var Wt,Vn=m(()=>{"use strict";y();q();Tt();It();Wn();Wt=class{static{c(this,"ToolApiHandler")}logger;ajv;constructor(){this.logger=p.withTag("ToolApiHandler"),this.ajv=new xs({allErrors:!0,verbose:!0})}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}createErrorResponse(e,t){return{success:!1,error:{code:e,message:t}}}async callTool(e){try{this.logger.info("\u5904\u7406\u5DE5\u5177\u8C03\u7528\u8BF7\u6C42");let t=await e.req.json(),{serviceName:r,toolName:n,args:o}=t;if(!r||!n){let l=this.createErrorResponse("INVALID_REQUEST","serviceName \u548C toolName \u662F\u5FC5\u9700\u7684\u53C2\u6570");return e.json(l,400)}if(this.logger.info(`\u51C6\u5907\u8C03\u7528\u5DE5\u5177: ${r}/${n}\uFF0C\u53C2\u6570:`,JSON.stringify(o)),!X.isInitialized()){let l=this.createErrorResponse("SERVICE_NOT_INITIALIZED","MCP \u670D\u52A1\u7BA1\u7406\u5668\u672A\u521D\u59CB\u5316\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002");return e.json(l,503)}let s=await X.getInstance();await this.validateServiceAndTool(s,r,n),r==="customMCP"&&await this.validateCustomMCPArguments(s,n,o||{});let a;if(r==="customMCP")a=await s.callTool(n,o||{});else{let l=`${r}__${n}`;a=await s.callTool(l,o||{})}return e.json(this.createSuccessResponse(a,"\u5DE5\u5177\u8C03\u7528\u6210\u529F"))}catch(t){this.logger.error("\u5DE5\u5177\u8C03\u7528\u5931\u8D25:",t);let r=t instanceof Error?t.message:String(t),n="TOOL_CALL_ERROR";r.includes("\u4E0D\u5B58\u5728")?n="SERVICE_OR_TOOL_NOT_FOUND":r.includes("\u672A\u542F\u52A8")||r.includes("\u672A\u8FDE\u63A5")?n="SERVICE_NOT_AVAILABLE":r.includes("\u5DF2\u88AB\u7981\u7528")?n="TOOL_DISABLED":r.includes("\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25")?n="INVALID_ARGUMENTS":r.includes("CustomMCP")||r.includes("customMCP")?n="CUSTOM_MCP_ERROR":r.includes("\u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25")||r.includes("API \u8BF7\u6C42\u5931\u8D25")?n="EXTERNAL_API_ERROR":r.includes("\u8D85\u65F6")&&(n="TIMEOUT_ERROR");let o=this.createErrorResponse(n,r);return e.json(o,500)}}async getCustomTools(e){try{if(this.logger.info("\u5904\u7406\u83B7\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u5217\u8868\u8BF7\u6C42"),!h.configExists()){let o=this.createErrorResponse("CONFIG_NOT_FOUND","\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C 'xiaozhi init' \u521D\u59CB\u5316\u914D\u7F6E");return e.json(o,404)}let t=[],r="";try{t=h.getCustomMCPTools(),r=h.getConfigPath()}catch(o){this.logger.error("\u8BFB\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u914D\u7F6E\u5931\u8D25:",o);let s=this.createErrorResponse("CONFIG_PARSE_ERROR",`\u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${o instanceof Error?o.message:"\u672A\u77E5\u9519\u8BEF"}`);return e.json(s,500)}if(!t||t.length===0)return this.logger.info("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177"),e.json(this.createSuccessResponse({tools:[],totalTools:0,configPath:r},"\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177"));if(!h.validateCustomMCPTools(t)){this.logger.warn("\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");let o=this.createErrorResponse("INVALID_TOOL_CONFIG","\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u5DE5\u5177\u5B9A\u4E49");return e.json(o,400)}return this.logger.info(`\u83B7\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u5217\u8868\u6210\u529F\uFF0C\u5171 ${t.length} \u4E2A\u5DE5\u5177`),e.json(this.createSuccessResponse({tools:t,totalTools:t.length,configPath:r},"\u83B7\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u5217\u8868\u6210\u529F"))}catch(t){this.logger.error("\u83B7\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u5217\u8868\u5931\u8D25:",t);let r=this.createErrorResponse("GET_CUSTOM_TOOLS_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u5217\u8868\u5931\u8D25");return e.json(r,500)}}async listTools(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u8BF7\u6C42");let t=e.req.query("status")||"all",r=[];switch(t){case"enabled":r=h.getCustomMCPTools(),this.logger.debug(`\u83B7\u53D6\u5DF2\u542F\u7528\u5DE5\u5177\uFF0C\u5171 ${r.length} \u4E2A`);break;case"disabled":r=await this.getDisabledTools(),this.logger.debug(`\u83B7\u53D6\u672A\u542F\u7528\u5DE5\u5177\uFF0C\u5171 ${r.length} \u4E2A`);break;default:r=h.getCustomMCPTools(),this.logger.debug(`\u83B7\u53D6\u6240\u6709\u5DE5\u5177\uFF0C\u5171 ${r.length} \u4E2A`);break}let n={list:r,total:r.length};return e.json(this.createSuccessResponse(n,`\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u6210\u529F\uFF08${t}\uFF09`))}catch(t){this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25:",t);let r=this.createErrorResponse("GET_TOOLS_FAILED","\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25");return e.json(r,500)}}async getDisabledTools(){try{let e=h.getCustomMCPTools(),t=new Set(e.map(l=>l.name)),n=await new ue().getAllCachedTools(),o=h.getConfig(),s=new Set(Object.keys(o.mcpServers||{})),a=[];for(let l of n){if(t.has(l.name))continue;let g=l.name.split("__")[0];if(!s.has(g)){this.logger.debug(`\u5DE5\u5177 ${l.name} \u5BF9\u5E94\u7684 MCP \u670D\u52A1 ${g} \u5DF2\u5220\u9664\uFF0C\u8DF3\u8FC7\u663E\u793A`);continue}let u={name:l.name,description:l.description||"",inputSchema:l.inputSchema||{},handler:{type:"mcp",config:{serviceName:g,toolName:l.name.split("__").slice(1).join("__")}}};a.push(u)}return this.logger.debug(`\u4ECE ${n.length} \u4E2A\u7F13\u5B58\u5DE5\u5177\u4E2D\u7B5B\u9009\u51FA ${a.length} \u4E2A\u672A\u542F\u7528\u5DE5\u5177`),a}catch(e){return this.logger.error("\u83B7\u53D6\u672A\u542F\u7528\u5DE5\u5177\u5931\u8D25:",e),[]}}async validateServiceAndTool(e,t,r){if(t==="customMCP"){if(!e.hasCustomMCPTool(r)){let n=e.getCustomMCPTools().map(o=>o.name);throw n.length===0?new Error(`customMCP \u5DE5\u5177 '${r}' \u4E0D\u5B58\u5728\u3002\u5F53\u524D\u6CA1\u6709\u914D\u7F6E\u4EFB\u4F55 customMCP \u5DE5\u5177\u3002\u8BF7\u68C0\u67E5 xiaozhi.config.json \u4E2D\u7684 customMCP \u914D\u7F6E\u3002`):new Error(`customMCP \u5DE5\u5177 '${r}' \u4E0D\u5B58\u5728\u3002\u53EF\u7528\u7684 customMCP \u5DE5\u5177: ${n.join(", ")}\u3002\u8BF7\u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u5DE5\u5177\u3002`)}try{let o=e.getCustomMCPTools().find(s=>s.name===r);o&&!o.description&&this.logger.warn(`customMCP \u5DE5\u5177 '${r}' \u7F3A\u5C11\u63CF\u8FF0\u4FE1\u606F`),o&&!o.inputSchema&&this.logger.warn(`customMCP \u5DE5\u5177 '${r}' \u7F3A\u5C11\u8F93\u5165\u53C2\u6570\u5B9A\u4E49`)}catch(n){throw this.logger.error(`\u9A8C\u8BC1 customMCP \u5DE5\u5177 '${r}' \u914D\u7F6E\u65F6\u51FA\u9519:`,n),new Error(`customMCP \u5DE5\u5177 '${r}' \u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25\u3002\u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u5DE5\u5177\u5B9A\u4E49\u3002`)}return}}async validateCustomMCPArguments(e,t,r){try{let o=e.getCustomMCPTools().find(l=>l.name===t);if(!o)throw new Error(`customMCP \u5DE5\u5177 '${t}' \u4E0D\u5B58\u5728`);if(!o.inputSchema){this.logger.warn(`customMCP \u5DE5\u5177 '${t}' \u6CA1\u6709\u5B9A\u4E49 inputSchema\uFF0C\u8DF3\u8FC7\u53C2\u6570\u9A8C\u8BC1`);return}let s=this.ajv.compile(o.inputSchema);if(!s(r)){let u=`\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25: ${(s.errors||[]).map(d=>{let v=d.instancePath||d.schemaPath||"",T=d.message||"\u672A\u77E5\u9519\u8BEF";if(d.keyword==="required")return`\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570: ${d.params?.missingProperty||"\u672A\u77E5\u5B57\u6BB5"}`;if(d.keyword==="type"){let I=d.params?.type||"\u672A\u77E5\u7C7B\u578B";return`\u53C2\u6570 ${v} \u7C7B\u578B\u9519\u8BEF\uFF0C\u671F\u671B: ${I}`}if(d.keyword==="enum"){let I=d.params?.allowedValues||[];return`\u53C2\u6570 ${v} \u503C\u65E0\u6548\uFF0C\u5141\u8BB8\u7684\u503C: ${I.join(", ")}`}return`\u53C2\u6570 ${v} ${T}`}).join("; ")}`;throw this.logger.error(`customMCP \u5DE5\u5177 '${t}' \u53C2\u6570\u9A8C\u8BC1\u5931\u8D25:`,u),new Error(u)}this.logger.debug(`customMCP \u5DE5\u5177 '${t}' \u53C2\u6570\u9A8C\u8BC1\u901A\u8FC7`)}catch(n){throw n instanceof Error&&n.message.includes("\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25")?n:(this.logger.error(`\u9A8C\u8BC1 customMCP \u5DE5\u5177 '${t}' \u53C2\u6570\u65F6\u51FA\u9519:`,n),new Error(`\u53C2\u6570\u9A8C\u8BC1\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF: ${n instanceof Error?n.message:"\u672A\u77E5\u9519\u8BEF"}`))}}async addCustomTool(e){try{this.logger.info("\u5904\u7406\u6DFB\u52A0\u81EA\u5B9A\u4E49\u5DE5\u5177\u8BF7\u6C42");let t=await e.req.json();return this.isNewFormatRequest(t)?await this.handleNewFormatAddTool(e,t):await this.handleLegacyFormatAddTool(e,t)}catch(t){this.logger.error("\u6DFB\u52A0\u81EA\u5B9A\u4E49\u5DE5\u5177\u5931\u8D25:",t);let{statusCode:r,errorResponse:n}=this.handleAddToolError(t);return e.json(n,r)}}isNewFormatRequest(e){return e&&typeof e=="object"&&"type"in e&&"data"in e}async handleNewFormatAddTool(e,t){let{type:r,data:n}=t;if(this.logger.info(`\u5904\u7406\u65B0\u683C\u5F0F\u5DE5\u5177\u6DFB\u52A0\u8BF7\u6C42\uFF0C\u7C7B\u578B: ${r}`),!Object.values(Ve).includes(r)){let o=this.createErrorResponse("INVALID_TOOL_TYPE",`\u4E0D\u652F\u6301\u7684\u5DE5\u5177\u7C7B\u578B: ${r}\u3002\u652F\u6301\u7684\u7C7B\u578B: ${Object.values(Ve).join(", ")}`);return e.json(o,400)}switch(r){case"mcp":return await this.handleAddMCPTool(e,n);case"coze":return await this.handleAddCozeTool(e,n);case"http":case"function":{let o=this.createErrorResponse("TOOL_TYPE_NOT_IMPLEMENTED",`\u5DE5\u5177\u7C7B\u578B ${r} \u6682\u672A\u5B9E\u73B0\uFF0C\u8BF7\u4F7F\u7528 MCP \u6216 Coze \u7C7B\u578B`);return e.json(o,501)}default:{let o=this.createErrorResponse("UNKNOWN_TOOL_TYPE",`\u672A\u77E5\u7684\u5DE5\u5177\u7C7B\u578B: ${r}`);return e.json(o,400)}}}async handleLegacyFormatAddTool(e,t){this.logger.info("\u5904\u7406\u65E7\u683C\u5F0F\u5DE5\u5177\u6DFB\u52A0\u8BF7\u6C42\uFF08\u5411\u540E\u517C\u5BB9\uFF09");let{workflow:r,customName:n,customDescription:o,parameterConfig:s}=t,a=this.performPreChecks(r,n,o);if(a)return e.json(a.errorResponse,a.statusCode);let l=this.convertWorkflowToTool(r,n,o,s);return h.addCustomMCPTool(l),this.logger.info(`\u6210\u529F\u6DFB\u52A0\u81EA\u5B9A\u4E49\u5DE5\u5177: ${l.name}`),e.json(this.createSuccessResponse({tool:l},`\u5DE5\u5177 "${l.name}" \u6DFB\u52A0\u6210\u529F`))}async handleAddMCPTool(e,t){let{serviceName:r,toolName:n,customName:o,customDescription:s}=t;if(this.logger.info(`\u5904\u7406\u6DFB\u52A0 MCP \u5DE5\u5177: ${r}/${n}`),!r||!n){let A=this.createErrorResponse("MISSING_REQUIRED_FIELD","serviceName \u548C toolName \u662F\u5FC5\u9700\u5B57\u6BB5");return e.json(A,400)}if(!X.isInitialized()){let A=this.createErrorResponse("SERVICE_NOT_INITIALIZED","MCP \u670D\u52A1\u7BA1\u7406\u5668\u672A\u521D\u59CB\u5316\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002");return e.json(A,503)}let a=await X.getInstance();try{await this.validateServiceAndTool(a,r,n)}catch(A){let ct=A instanceof Error?A.message:String(A),re=this.createErrorResponse("SERVICE_OR_TOOL_NOT_FOUND",ct);return e.json(re,404)}let g=await new ue().getAllCachedTools(),u=`${r}__${n}`,d=g.find(A=>A.name===u);if(!d){let A=this.createErrorResponse("TOOL_NOT_FOUND",`\u5728\u7F13\u5B58\u4E2D\u672A\u627E\u5230\u5DE5\u5177: ${r}/${n}`);return e.json(A,404)}let v=o||u,T=h.getCustomMCPTools();if(new Set(T.map(A=>A.name)).has(v)){let A=this.createErrorResponse("TOOL_NAME_CONFLICT",`\u5DE5\u5177\u540D\u79F0 "${v}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u4F7F\u7528\u4E0D\u540C\u7684\u81EA\u5B9A\u4E49\u540D\u79F0`);return e.json(A,409)}let K={name:v,description:s||d.description||`MCP \u5DE5\u5177: ${r}/${n}`,inputSchema:d.inputSchema||{},handler:{type:"mcp",config:{serviceName:r,toolName:n}},stats:{usageCount:0,lastUsedTime:Ft().format("YYYY-MM-DD HH:mm:ss")}};h.addCustomMCPTool(K),this.logger.info(`\u68C0\u6D4B\u5230 MCP \u5DE5\u5177\u6DFB\u52A0\uFF0C\u540C\u6B65\u542F\u7528 mcpServerConfig \u4E2D\u7684\u5DE5\u5177: ${r}/${n}`);let B=h.getServerToolsConfig(r);B?.toolName&&(B[n].enable=!0,h.updateServerToolsConfig(r,B),this.logger.info(`\u5DF2\u540C\u6B65\u542F\u7528 mcpServerConfig \u4E2D\u7684\u5DE5\u5177: ${r}/${n}`)),this.logger.info(`\u6210\u529F\u6DFB\u52A0 MCP \u5DE5\u5177: ${v}`);let at={tool:K,toolName:v,toolType:"mcp",addedAt:Ft().format("YYYY-MM-DD HH:mm:ss")};return e.json(this.createSuccessResponse(at,`MCP \u5DE5\u5177 "${v}" \u6DFB\u52A0\u6210\u529F`))}async handleAddCozeTool(e,t){let{workflow:r,customName:n,customDescription:o,parameterConfig:s}=t;this.logger.info(`\u5904\u7406\u6DFB\u52A0 Coze \u5DE5\u5177: ${r.workflow_name}`);let a=this.performPreChecks(r,n,o);if(a)return e.json(a.errorResponse,a.statusCode);let l=this.convertWorkflowToTool(r,n,o,s);h.addCustomMCPTool(l),this.logger.info(`\u6210\u529F\u6DFB\u52A0 Coze \u5DE5\u5177: ${l.name}`);let g={tool:l,toolName:l.name,toolType:"coze",addedAt:Ft().format("YYYY-MM-DD HH:mm:ss")};return e.json(this.createSuccessResponse(g,`Coze \u5DE5\u5177 "${l.name}" \u6DFB\u52A0\u6210\u529F`))}async updateCustomTool(e){try{let t=e.req.param("toolName");if(!t){let o=this.createErrorResponse("INVALID_REQUEST","\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");return e.json(o,400)}this.logger.info(`\u5904\u7406\u66F4\u65B0\u81EA\u5B9A\u4E49\u5DE5\u5177\u914D\u7F6E\u8BF7\u6C42: ${t}`);let r=await e.req.json();if(!r||typeof r!="object"){let o=this.createErrorResponse("INVALID_REQUEST","\u8BF7\u6C42\u4F53\u5FC5\u987B\u662F\u6709\u6548\u5BF9\u8C61");return e.json(o,400)}if(this.isNewFormatRequest(r))return await this.handleNewFormatUpdateTool(e,t,r);let n=this.createErrorResponse("INVALID_REQUEST","\u66F4\u65B0\u64CD\u4F5C\u53EA\u652F\u6301\u65B0\u683C\u5F0F\u7684\u8BF7\u6C42");return e.json(n,400)}catch(t){this.logger.error("\u66F4\u65B0\u81EA\u5B9A\u4E49\u5DE5\u5177\u914D\u7F6E\u5931\u8D25:",t);let{statusCode:r,errorResponse:n}=this.handleUpdateToolError(t);return e.json(n,r)}}async handleNewFormatUpdateTool(e,t,r){let{type:n,data:o}=r;if(this.logger.info(`\u5904\u7406\u65B0\u683C\u5F0F\u5DE5\u5177\u66F4\u65B0\u8BF7\u6C42\uFF0C\u7C7B\u578B: ${n}`),!Object.values(Ve).includes(n)){let s=this.createErrorResponse("INVALID_TOOL_TYPE",`\u4E0D\u652F\u6301\u7684\u5DE5\u5177\u7C7B\u578B: ${n}\u3002\u652F\u6301\u7684\u7C7B\u578B: ${Object.values(Ve).join(", ")}`);return e.json(s,400)}switch(n){case"coze":return await this.handleUpdateCozeTool(e,t,o);case"mcp":case"http":case"function":{let s=this.createErrorResponse("TOOL_TYPE_NOT_IMPLEMENTED",`\u5DE5\u5177\u7C7B\u578B ${n} \u6682\u4E0D\u652F\u6301\u66F4\u65B0\u64CD\u4F5C\uFF0C\u76EE\u524D\u4EC5\u652F\u6301 Coze \u7C7B\u578B`);return e.json(s,501)}default:{let s=this.createErrorResponse("UNKNOWN_TOOL_TYPE",`\u672A\u77E5\u7684\u5DE5\u5177\u7C7B\u578B: ${n}`);return e.json(s,400)}}}async handleUpdateCozeTool(e,t,r){let{workflow:n,customName:o,customDescription:s,parameterConfig:a}=r;this.logger.info(`\u5904\u7406\u66F4\u65B0 Coze \u5DE5\u5177: ${t}`);let g=h.getCustomMCPTools().find(T=>T.name===t);if(!g){let T=this.createErrorResponse("TOOL_NOT_FOUND",`\u5DE5\u5177 "${t}" \u4E0D\u5B58\u5728`);return e.json(T,404)}if(g.handler.type!=="proxy"||g.handler.platform!=="coze"){let T=this.createErrorResponse("INVALID_TOOL_TYPE",`\u5DE5\u5177 "${t}" \u4E0D\u662F Coze \u5DE5\u4F5C\u6D41\u5DE5\u5177\uFF0C\u4E0D\u652F\u6301\u53C2\u6570\u914D\u7F6E\u66F4\u65B0`);return e.json(T,400)}!n.workflow_id&&g.handler?.config?.workflow_id&&(n.workflow_id=g.handler.config.workflow_id),!n.workflow_id&&n.app_id&&this.logger.warn(`\u5DE5\u4F5C\u6D41 ${t} \u7F3A\u5C11 workflow_id\uFF0C\u8FD9\u53EF\u80FD\u4F1A\u5F71\u54CD\u67D0\u4E9B\u529F\u80FD`),this.validateWorkflowUpdateData(n);let u=this.generateInputSchema(n,a),d={...g,description:s||g.description,inputSchema:u};h.updateCustomMCPTool(t,d),this.logger.info(`\u6210\u529F\u66F4\u65B0 Coze \u5DE5\u5177: ${t}`);let v={tool:d,toolName:t,toolType:"coze",updatedAt:Ft().format("YYYY-MM-DD HH:mm:ss")};return e.json(this.createSuccessResponse(v,`Coze \u5DE5\u5177 "${t}" \u914D\u7F6E\u66F4\u65B0\u6210\u529F`))}handleUpdateToolError(e){let t=e instanceof Error?e.message:"\u66F4\u65B0\u81EA\u5B9A\u4E49\u5DE5\u5177\u914D\u7F6E\u5931\u8D25";return t.includes("\u4E0D\u5B58\u5728")||t.includes("\u672A\u627E\u5230")?{statusCode:404,errorResponse:this.createErrorResponse("TOOL_NOT_FOUND",`${t}\u3002\u8BF7\u68C0\u67E5\u5DE5\u5177\u540D\u79F0\u662F\u5426\u6B63\u786E`)}:t.includes("\u5DE5\u5177\u7C7B\u578B")||t.includes("INVALID_TOOL_TYPE")?{statusCode:400,errorResponse:this.createErrorResponse("INVALID_TOOL_TYPE",t)}:t.includes("\u4E0D\u80FD\u4E3A\u7A7A")||t.includes("\u65E0\u6548")?{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST",`${t}\u3002\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u5DE5\u5177\u914D\u7F6E\u6570\u636E`)}:t.includes("\u914D\u7F6E")||t.includes("\u6743\u9650")?{statusCode:422,errorResponse:this.createErrorResponse("CONFIGURATION_ERROR",`${t}\u3002\u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u6743\u9650\u548C\u683C\u5F0F\u662F\u5426\u6B63\u786E`)}:t.includes("\u672A\u5B9E\u73B0")||t.includes("NOT_IMPLEMENTED")?{statusCode:501,errorResponse:this.createErrorResponse("TOOL_TYPE_NOT_IMPLEMENTED",t)}:{statusCode:500,errorResponse:this.createErrorResponse("UPDATE_CUSTOM_TOOL_ERROR",`\u66F4\u65B0\u5DE5\u5177\u914D\u7F6E\u5931\u8D25\uFF1A${t}\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF0C\u5982\u95EE\u9898\u6301\u7EED\u5B58\u5728\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458`)}}async removeCustomTool(e){try{let t=e.req.param("toolName");if(!t){let o=this.createErrorResponse("INVALID_REQUEST","\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");return e.json(o,400)}this.logger.info(`\u5904\u7406\u5220\u9664\u81EA\u5B9A\u4E49\u5DE5\u5177\u8BF7\u6C42: ${t}`);let n=h.getCustomMCPTools().find(o=>o.name===t);if(n&&n.handler.type==="mcp"){let o=n.handler.config;if(o.serviceName&&o.toolName){this.logger.info(`\u68C0\u6D4B\u5230 MCP \u5DE5\u5177\u5220\u9664\uFF0C\u540C\u6B65\u7981\u7528 mcpServerConfig \u4E2D\u7684\u5DE5\u5177: ${o.serviceName}/${o.toolName}`);let s=h.getServerToolsConfig(o.serviceName);s?.[o.toolName]&&(s[o.toolName].enable=!1,h.updateServerToolsConfig(o.serviceName,s),this.logger.info(`\u5DF2\u540C\u6B65\u7981\u7528 mcpServerConfig \u4E2D\u7684\u5DE5\u5177: ${o.serviceName}/${o.toolName}`))}}return h.removeCustomMCPTool(t),this.logger.info(`\u6210\u529F\u5220\u9664\u81EA\u5B9A\u4E49\u5DE5\u5177: ${t}`),e.json(this.createSuccessResponse(null,`\u5DE5\u5177 "${t}" \u5220\u9664\u6210\u529F`))}catch(t){this.logger.error("\u5220\u9664\u81EA\u5B9A\u4E49\u5DE5\u5177\u5931\u8D25:",t);let{statusCode:r,errorResponse:n}=this.handleRemoveToolError(t);return e.json(n,r)}}convertWorkflowToTool(e,t,r,n){this.validateWorkflowData(e);let o=t||this.sanitizeToolName(e.workflow_name),s=this.resolveToolNameConflict(o),a=this.generateToolDescription(e,r),l=this.generateInputSchema(e,n),g=this.createHttpHandler(e),u={name:s,description:a,inputSchema:l,handler:g};return this.validateGeneratedTool(u),u}sanitizeToolName(e){if(!e||typeof e!="string")return"coze_workflow_unnamed";let t=e.trim();return t?(t=this.convertChineseToEnglish(t),t=t.replace(/[^a-zA-Z0-9_]/g,"_"),t=t.replace(/_+/g,"_"),t=t.replace(/^_+|_+$/g,""),/^[a-zA-Z]/.test(t)||(t=`coze_workflow_${t}`),t.length>45&&(t=t.substring(0,45)),t||(t="coze_workflow_tool"),t):"coze_workflow_empty"}convertChineseToEnglish(e){let t={\u5DE5\u4F5C\u6D41:"workflow",\u6D4B\u8BD5:"test",\u6570\u636E:"data",\u5904\u7406:"process",\u5206\u6790:"analysis",\u751F\u6210:"generate",\u67E5\u8BE2:"query",\u641C\u7D22:"search",\u8F6C\u6362:"convert",\u8BA1\u7B97:"calculate",\u7EDF\u8BA1:"statistics",\u62A5\u544A:"report",\u6587\u6863:"document",\u56FE\u7247:"image",\u89C6\u9891:"video",\u97F3\u9891:"audio",\u6587\u672C:"text",\u7FFB\u8BD1:"translate",\u8BC6\u522B:"recognize",\u68C0\u6D4B:"detect",\u76D1\u63A7:"monitor",\u7BA1\u7406:"manage",\u914D\u7F6E:"config",\u8BBE\u7F6E:"setting",\u7528\u6237:"user",\u7CFB\u7EDF:"system",\u670D\u52A1:"service",\u63A5\u53E3:"api",\u6570\u636E\u5E93:"database",\u7F51\u7EDC:"network",\u5B89\u5168:"security",\u5907\u4EFD:"backup",\u6062\u590D:"restore",\u540C\u6B65:"sync",\u5BFC\u5165:"import",\u5BFC\u51FA:"export",\u4E0A\u4F20:"upload",\u4E0B\u8F7D:"download"},r=e;for(let[n,o]of Object.entries(t))r=r.replace(new RegExp(n,"g"),o);return/[\u4e00-\u9fa5]/.test(r)&&(r=`chinese_${r}`),r}validateWorkflowData(e){if(!e)throw new Error("\u5DE5\u4F5C\u6D41\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A");this.validateRequiredFields(e),this.validateFieldFormats(e),this.validateFieldLengths(e),this.validateBusinessLogic(e)}validateWorkflowUpdateData(e){if(!e)throw new Error("\u5DE5\u4F5C\u6D41\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A");if(e.workflow_id){if(typeof e.workflow_id!="string"||e.workflow_id.trim()==="")throw new Error("\u5DE5\u4F5C\u6D41ID\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!/^\d+$/.test(e.workflow_id))throw new Error("\u5DE5\u4F5C\u6D41ID\u683C\u5F0F\u65E0\u6548\uFF0C\u5E94\u4E3A\u6570\u5B57\u5B57\u7B26\u4E32")}if(e.workflow_name){if(typeof e.workflow_name!="string"||e.workflow_name.trim()==="")throw new Error("\u5DE5\u4F5C\u6D41\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(e.workflow_name.length>100)throw new Error("\u5DE5\u4F5C\u6D41\u540D\u79F0\u8FC7\u957F\uFF0C\u4E0D\u80FD\u8D85\u8FC7100\u4E2A\u5B57\u7B26")}if(e.app_id){if(typeof e.app_id!="string"||e.app_id.trim()==="")throw new Error("\u5E94\u7528ID\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!/^[a-zA-Z0-9_-]+$/.test(e.app_id))throw new Error("\u5E94\u7528ID\u683C\u5F0F\u65E0\u6548\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26");if(e.app_id.length>50)throw new Error("\u5E94\u7528ID\u8FC7\u957F\uFF0C\u4E0D\u80FD\u8D85\u8FC750\u4E2A\u5B57\u7B26")}}validateRequiredFields(e){let t=[{field:"workflow_id",name:"\u5DE5\u4F5C\u6D41ID"},{field:"workflow_name",name:"\u5DE5\u4F5C\u6D41\u540D\u79F0"},{field:"app_id",name:"\u5E94\u7528ID"}];for(let{field:r,name:n}of t){let o=e[r];if(!o||typeof o!="string"||o.trim()==="")throw new Error(`${n}\u4E0D\u80FD\u4E3A\u7A7A\u4E14\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32`)}}validateFieldFormats(e){if(!/^\d+$/.test(e.workflow_id))throw new Error("\u5DE5\u4F5C\u6D41ID\u683C\u5F0F\u65E0\u6548\uFF0C\u5E94\u4E3A\u6570\u5B57\u5B57\u7B26\u4E32");if(!/^[a-zA-Z0-9_-]+$/.test(e.app_id))throw new Error("\u5E94\u7528ID\u683C\u5F0F\u65E0\u6548\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26");if(e.icon_url?.trim())try{new URL(e.icon_url)}catch{throw new Error("\u56FE\u6807URL\u683C\u5F0F\u65E0\u6548")}if(e.created_at&&(!Number.isInteger(e.created_at)||e.created_at<=0))throw new Error("\u521B\u5EFA\u65F6\u95F4\u683C\u5F0F\u65E0\u6548\uFF0C\u5E94\u4E3A\u6B63\u6574\u6570\u65F6\u95F4\u6233");if(e.updated_at&&(!Number.isInteger(e.updated_at)||e.updated_at<=0))throw new Error("\u66F4\u65B0\u65F6\u95F4\u683C\u5F0F\u65E0\u6548\uFF0C\u5E94\u4E3A\u6B63\u6574\u6570\u65F6\u95F4\u6233")}validateFieldLengths(e){let t=[{field:"workflow_name",name:"\u5DE5\u4F5C\u6D41\u540D\u79F0",max:100},{field:"description",name:"\u5DE5\u4F5C\u6D41\u63CF\u8FF0",max:500},{field:"app_id",name:"\u5E94\u7528ID",max:50}];for(let{field:r,name:n,max:o}of t){let s=e[r];if(s&&s.length>o)throw new Error(`${n}\u8FC7\u957F\uFF0C\u4E0D\u80FD\u8D85\u8FC7${o}\u4E2A\u5B57\u7B26`)}}validateBusinessLogic(e){if(e.creator){if(!e.creator.id||typeof e.creator.id!="string")throw new Error("\u521B\u5EFA\u8005ID\u4E0D\u80FD\u4E3A\u7A7A\u4E14\u5FC5\u987B\u662F\u5B57\u7B26\u4E32");if(!e.creator.name||typeof e.creator.name!="string")throw new Error("\u521B\u5EFA\u8005\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u4E14\u5FC5\u987B\u662F\u5B57\u7B26\u4E32")}if(e.created_at&&e.updated_at&&e.updated_at<e.created_at)throw new Error("\u66F4\u65B0\u65F6\u95F4\u4E0D\u80FD\u65E9\u4E8E\u521B\u5EFA\u65F6\u95F4");let t=["admin","root","system","config","password","token"],r=e.workflow_name.toLowerCase();for(let n of t)if(r.includes(n))throw new Error(`\u5DE5\u4F5C\u6D41\u540D\u79F0\u4E0D\u80FD\u5305\u542B\u654F\u611F\u8BCD: ${n}`)}resolveToolNameConflict(e){let t=h.getCustomMCPTools(),r=new Set(t.map(s=>s.name)),n=e,o=1;for(;r.has(n);)if(n=`${e}_${o}`,o++,o>999)throw new Error(`\u65E0\u6CD5\u4E3A\u5DE5\u5177\u751F\u6210\u552F\u4E00\u540D\u79F0\uFF0C\u57FA\u7840\u540D\u79F0: ${e}`);return n}generateToolDescription(e,t){return t||(e.description?.trim()?e.description.trim():`\u6263\u5B50\u5DE5\u4F5C\u6D41\u5DE5\u5177: ${e.workflow_name}`)}createHttpHandler(e){return this.validateCozeApiConfig(),{type:"proxy",platform:"coze",config:{workflow_id:e.workflow_id}}}validateCozeApiConfig(){let e=h.getCozePlatformConfig();if(!e||!e.token)throw new Error("\u672A\u914D\u7F6E\u6263\u5B50API Token\uFF0C\u8BF7\u5148\u5728\u914D\u7F6E\u4E2D\u8BBE\u7F6E platforms.coze.token")}validateGeneratedTool(e){if(this.validateToolStructure(e),!h.validateCustomMCPTools([e]))throw new Error("\u751F\u6210\u7684\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u5177\u5B9A\u4E49");this.validateJsonSchema(e.inputSchema),this.validateProxyHandler(e.handler)}validateToolStructure(e){if(!e||typeof e!="object")throw new Error("\u5DE5\u5177\u914D\u7F6E\u5FC5\u987B\u662F\u6709\u6548\u5BF9\u8C61");let t=["name","description","inputSchema","handler"];for(let r of t)if(!(r in e)||e[r]==null)throw new Error(`\u5DE5\u5177\u914D\u7F6E\u7F3A\u5C11\u5FC5\u9700\u5B57\u6BB5: ${r}`);if(typeof e.name!="string"||e.name.trim()==="")throw new Error("\u5DE5\u5177\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(typeof e.description!="string"||e.description.trim()==="")throw new Error("\u5DE5\u5177\u63CF\u8FF0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(typeof e.inputSchema!="object")throw new Error("\u8F93\u5165\u53C2\u6570\u7ED3\u6784\u5FC5\u987B\u662F\u5BF9\u8C61");if(typeof e.handler!="object")throw new Error("\u5904\u7406\u5668\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61")}validateProxyHandler(e){if(!e||typeof e!="object")throw new Error("HTTP\u5904\u7406\u5668\u914D\u7F6E\u4E0D\u80FD\u4E3A\u7A7A");if(e.type!=="proxy")throw new Error("\u5904\u7406\u5668\u7C7B\u578B\u5FC5\u987B\u662F'proxy'");if(e.platform==="coze"){if(!e.config.workflow_id)throw new Error("Coze\u5904\u7406\u5668\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684workflow_id")}else throw new Error("\u4E0D\u652F\u6301\u7684\u5DE5\u4F5C\u6D41\u5E73\u53F0")}validateAuthConfig(e){if(!e||typeof e!="object")throw new Error("\u8BA4\u8BC1\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");if(!e.type||typeof e.type!="string")throw new Error("\u8BA4\u8BC1\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A");let t=["bearer","basic","api_key"];if(!t.includes(e.type))throw new Error(`\u8BA4\u8BC1\u7C7B\u578B\u5FC5\u987B\u662F\u4EE5\u4E0B\u4E4B\u4E00: ${t.join(", ")}`);if(e.type==="bearer"){if(!e.token||typeof e.token!="string")throw new Error("Bearer\u8BA4\u8BC1\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684token");if(!e.token.startsWith("${")&&!e.token.match(/^[a-zA-Z0-9_-]+$/))throw new Error("Bearer token\u683C\u5F0F\u65E0\u6548")}}validateBodyTemplate(e){if(typeof e!="string")throw new Error("\u8BF7\u6C42\u4F53\u6A21\u677F\u5FC5\u987B\u662F\u5B57\u7B26\u4E32");try{JSON.parse(e)}catch{throw new Error("\u8BF7\u6C42\u4F53\u6A21\u677F\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F")}let t=e.match(/\{\{[^}]+\}\}/g);if(t)for(let r of t){let n=r.slice(2,-2).trim();if(!n||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n))throw new Error(`\u6A21\u677F\u53D8\u91CF\u683C\u5F0F\u65E0\u6548: ${r}`)}}validateJsonSchema(e){if(!e||typeof e!="object")throw new Error("\u8F93\u5165\u53C2\u6570\u7ED3\u6784\u5FC5\u987B\u662F\u6709\u6548\u7684\u5BF9\u8C61");if(!e.type||e.type!=="object")throw new Error("\u8F93\u5165\u53C2\u6570\u7ED3\u6784\u7684type\u5FC5\u987B\u662F'object'");if(!e.properties||typeof e.properties!="object")throw new Error("\u8F93\u5165\u53C2\u6570\u7ED3\u6784\u5FC5\u987B\u5305\u542Bproperties\u5B57\u6BB5");if(e.required&&!Array.isArray(e.required))throw new Error("\u8F93\u5165\u53C2\u6570\u7ED3\u6784\u7684required\u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4")}generateInputSchema(e,t){return t&&t.parameters.length>0?this.generateInputSchemaFromConfig(t):{type:"object",properties:{input:{type:"string",description:"\u8F93\u5165\u5185\u5BB9"}},required:["input"],additionalProperties:!1}}generateInputSchemaFromConfig(e){let t={},r=[];for(let n of e.parameters)t[n.fieldName]={type:n.type,description:n.description},n.required&&r.push(n.fieldName);return{type:"object",properties:t,required:r.length>0?r:void 0,additionalProperties:!1}}handleAddToolError(e){let t=e instanceof Error?e.message:"\u6DFB\u52A0\u81EA\u5B9A\u4E49\u5DE5\u5177\u5931\u8D25";return t.includes("\u5DE5\u5177\u7C7B\u578B")||t.includes("TOOL_TYPE")?{statusCode:400,errorResponse:this.createErrorResponse("INVALID_TOOL_TYPE",t)}:t.includes("\u5FC5\u9700\u5B57\u6BB5")||t.includes("MISSING_REQUIRED_FIELD")?{statusCode:400,errorResponse:this.createErrorResponse("MISSING_REQUIRED_FIELD",t)}:t.includes("\u4E0D\u5B58\u5728")||t.includes("NOT_FOUND")||t.includes("\u672A\u627E\u5230")?{statusCode:404,errorResponse:this.createErrorResponse("SERVICE_OR_TOOL_NOT_FOUND",t)}:t.includes("\u672A\u521D\u59CB\u5316")||t.includes("SERVICE_NOT_INITIALIZED")?{statusCode:503,errorResponse:this.createErrorResponse("SERVICE_NOT_INITIALIZED",t)}:t.includes("\u5DF2\u5B58\u5728")||t.includes("\u51B2\u7A81")||t.includes("TOOL_NAME_CONFLICT")?{statusCode:409,errorResponse:this.createErrorResponse("TOOL_NAME_CONFLICT",`${t}\u3002\u5EFA\u8BAE\uFF1A1) \u4F7F\u7528\u81EA\u5B9A\u4E49\u540D\u79F0\uFF1B2) \u5220\u9664\u73B0\u6709\u540C\u540D\u5DE5\u5177\u540E\u91CD\u8BD5`)}:this.isValidationError(t)?{statusCode:400,errorResponse:this.createErrorResponse("VALIDATION_ERROR",this.formatValidationError(t))}:t.includes("\u914D\u7F6E")||t.includes("token")||t.includes("API")||t.includes("CONFIGURATION_ERROR")?{statusCode:422,errorResponse:this.createErrorResponse("CONFIGURATION_ERROR",`${t}\u3002\u8BF7\u68C0\u67E5\uFF1A1) \u76F8\u5173\u914D\u7F6E\u662F\u5426\u6B63\u786E\uFF1B2) \u7F51\u7EDC\u8FDE\u63A5\u662F\u5426\u6B63\u5E38\uFF1B3) \u914D\u7F6E\u6587\u4EF6\u6743\u9650\u662F\u5426\u6B63\u786E`)}:t.includes("\u8D44\u6E90\u9650\u5236")||t.includes("RESOURCE_LIMIT_EXCEEDED")?{statusCode:429,errorResponse:this.createErrorResponse("RESOURCE_LIMIT_EXCEEDED",t)}:t.includes("\u672A\u5B9E\u73B0")||t.includes("NOT_IMPLEMENTED")?{statusCode:501,errorResponse:this.createErrorResponse("TOOL_TYPE_NOT_IMPLEMENTED",t)}:{statusCode:500,errorResponse:this.createErrorResponse("ADD_CUSTOM_TOOL_ERROR",`\u6DFB\u52A0\u5DE5\u5177\u5931\u8D25\uFF1A${t}\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF0C\u5982\u95EE\u9898\u6301\u7EED\u5B58\u5728\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458`)}}handleRemoveToolError(e){let t=e instanceof Error?e.message:"\u5220\u9664\u81EA\u5B9A\u4E49\u5DE5\u5177\u5931\u8D25";return t.includes("\u4E0D\u5B58\u5728")||t.includes("\u672A\u627E\u5230")?{statusCode:404,errorResponse:this.createErrorResponse("TOOL_NOT_FOUND",`${t}\u3002\u8BF7\u68C0\u67E5\u5DE5\u5177\u540D\u79F0\u662F\u5426\u6B63\u786E\uFF0C\u6216\u5237\u65B0\u9875\u9762\u67E5\u770B\u6700\u65B0\u7684\u5DE5\u5177\u5217\u8868`)}:t.includes("\u4E0D\u80FD\u4E3A\u7A7A")||t.includes("\u65E0\u6548")?{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST",`${t}\u3002\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u5DE5\u5177\u540D\u79F0`)}:t.includes("\u914D\u7F6E")||t.includes("\u6743\u9650")?{statusCode:422,errorResponse:this.createErrorResponse("CONFIGURATION_ERROR",`${t}\u3002\u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u6743\u9650\u548C\u683C\u5F0F\u662F\u5426\u6B63\u786E`)}:{statusCode:500,errorResponse:this.createErrorResponse("REMOVE_CUSTOM_TOOL_ERROR",`\u5220\u9664\u5DE5\u5177\u5931\u8D25\uFF1A${t}\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF0C\u5982\u95EE\u9898\u6301\u7EED\u5B58\u5728\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458`)}}isValidationError(e){return["\u4E0D\u80FD\u4E3A\u7A7A","\u5FC5\u987B\u662F","\u683C\u5F0F\u65E0\u6548","\u8FC7\u957F","\u8FC7\u77ED","\u9A8C\u8BC1\u5931\u8D25","\u65E0\u6548","\u4E0D\u7B26\u5408","\u8D85\u8FC7","\u5C11\u4E8E","\u654F\u611F\u8BCD","\u65F6\u95F4","URL"].some(r=>e.includes(r))}formatValidationError(e){let t={\u5DE5\u4F5C\u6D41ID\u4E0D\u80FD\u4E3A\u7A7A:"\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u5DE5\u4F5C\u6D41ID",\u5DE5\u4F5C\u6D41\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A:"\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u5DE5\u4F5C\u6D41\u540D\u79F0",\u5E94\u7528ID\u4E0D\u80FD\u4E3A\u7A7A:"\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u5E94\u7528ID",\u5DE5\u4F5C\u6D41ID\u683C\u5F0F\u65E0\u6548:"\u5DE5\u4F5C\u6D41ID\u5E94\u4E3A\u6570\u5B57\u683C\u5F0F\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u4F5C\u6D41\u914D\u7F6E",\u5E94\u7528ID\u683C\u5F0F\u65E0\u6548:"\u5E94\u7528ID\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26",\u5DE5\u4F5C\u6D41\u540D\u79F0\u8FC7\u957F:"\u5DE5\u4F5C\u6D41\u540D\u79F0\u4E0D\u80FD\u8D85\u8FC7100\u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED\u540D\u79F0",\u5DE5\u4F5C\u6D41\u63CF\u8FF0\u8FC7\u957F:"\u5DE5\u4F5C\u6D41\u63CF\u8FF0\u4E0D\u80FD\u8D85\u8FC7500\u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED\u63CF\u8FF0",\u56FE\u6807URL\u683C\u5F0F\u65E0\u6548:"\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u56FE\u6807URL\u5730\u5740",\u66F4\u65B0\u65F6\u95F4\u4E0D\u80FD\u65E9\u4E8E\u521B\u5EFA\u65F6\u95F4:"\u5DE5\u4F5C\u6D41\u7684\u65F6\u95F4\u4FE1\u606F\u6709\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u4F5C\u6D41\u6570\u636E",\u654F\u611F\u8BCD:"\u5DE5\u4F5C\u6D41\u540D\u79F0\u5305\u542B\u654F\u611F\u8BCD\u6C47\uFF0C\u8BF7\u4FEE\u6539\u540E\u91CD\u8BD5"};for(let[r,n]of Object.entries(t))if(e.includes(r))return n;return e}performPreChecks(e,t,r){let n=this.checkBasicParameters(e,t,r);if(n)return n;let o=this.checkSystemStatus();if(o)return o;let s=this.checkResourceLimits();return s||null}checkBasicParameters(e,t,r){if(!e)return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","\u8BF7\u6C42\u4F53\u4E2D\u7F3A\u5C11 workflow \u53C2\u6570")};if(typeof e!="object")return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","workflow \u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61\u7C7B\u578B")};if(!e.workflow_id||typeof e.workflow_id!="string"||!e.workflow_id.trim())return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","workflow_id \u4E0D\u80FD\u4E3A\u7A7A\u4E14\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")};if(!e.workflow_name||typeof e.workflow_name!="string"||!e.workflow_name.trim())return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","workflow_name \u4E0D\u80FD\u4E3A\u7A7A\u4E14\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")};if(t!==void 0){if(typeof t!="string")return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","customName \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u7C7B\u578B")};if(t.trim()==="")return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","customName \u4E0D\u80FD\u4E3A\u7A7A\u5B57\u7B26\u4E32")};if(t.length>50)return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","customName \u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC750\u4E2A\u5B57\u7B26")}}if(r!==void 0){if(typeof r!="string")return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","customDescription \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u7C7B\u578B")};if(r.length>200)return{statusCode:400,errorResponse:this.createErrorResponse("INVALID_REQUEST","customDescription \u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7200\u4E2A\u5B57\u7B26")}}return null}checkSystemStatus(){try{let e=h.getCozePlatformConfig();if(!e||!e.token)return{statusCode:422,errorResponse:this.createErrorResponse("CONFIGURATION_ERROR","\u672A\u914D\u7F6E\u6263\u5B50API Token\u3002\u8BF7\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u4E2D\u914D\u7F6E platforms.coze.token")};if(typeof e.token!="string"||e.token.trim()==="")return{statusCode:422,errorResponse:this.createErrorResponse("CONFIGURATION_ERROR","\u6263\u5B50API Token\u683C\u5F0F\u65E0\u6548\u3002\u8BF7\u68C0\u67E5\u914D\u7F6E\u4E2D\u7684 platforms.coze.token")}}catch{return{statusCode:500,errorResponse:this.createErrorResponse("SYSTEM_ERROR","\u7CFB\u7EDF\u914D\u7F6E\u68C0\u67E5\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5")}}return null}checkResourceLimits(){try{let e=h.getCustomMCPTools(),t=100;if(e.length>=t)return{statusCode:429,errorResponse:this.createErrorResponse("RESOURCE_LIMIT_EXCEEDED",`\u5DF2\u8FBE\u5230\u6700\u5927\u5DE5\u5177\u6570\u91CF\u9650\u5236 (${t})\u3002\u8BF7\u5220\u9664\u4E00\u4E9B\u4E0D\u9700\u8981\u7684\u5DE5\u5177\u540E\u91CD\u8BD5`)};let r=JSON.stringify(e).length,n=1024*1024;if(r>n)return{statusCode:413,errorResponse:this.createErrorResponse("PAYLOAD_TOO_LARGE","\u914D\u7F6E\u6587\u4EF6\u8FC7\u5927\u3002\u8BF7\u5220\u9664\u4E00\u4E9B\u4E0D\u9700\u8981\u7684\u5DE5\u5177\u4EE5\u91CA\u653E\u7A7A\u95F4")}}catch(e){this.logger.warn("\u8D44\u6E90\u9650\u5236\u68C0\u67E5\u5931\u8D25:",e)}return null}}});var Vt,Bn=m(()=>{"use strict";y();gr();Vt=class{static{c(this,"VersionApiHandler")}logger;constructor(){this.logger=p.withTag("VersionApiHandler")}createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async getVersion(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u7248\u672C\u4FE1\u606F\u8BF7\u6C42");let t=fe.getVersionInfo();return this.logger.debug("\u83B7\u53D6\u7248\u672C\u4FE1\u606F\u6210\u529F:",t),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u7248\u672C\u4FE1\u606F\u5931\u8D25:",t);let r=this.createErrorResponse("VERSION_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u7248\u672C\u4FE1\u606F\u5931\u8D25");return e.json(r,500)}}async getVersionSimple(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u7248\u672C\u53F7\u8BF7\u6C42");let t=fe.getVersion();return this.logger.debug(`\u83B7\u53D6\u7248\u672C\u53F7\u6210\u529F: ${t}`),e.json(this.createSuccessResponse({version:t}))}catch(t){this.logger.error("\u83B7\u53D6\u7248\u672C\u53F7\u5931\u8D25:",t);let r=this.createErrorResponse("VERSION_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u7248\u672C\u53F7\u5931\u8D25");return e.json(r,500)}}async clearVersionCache(e){try{return this.logger.debug("\u5904\u7406\u6E05\u9664\u7248\u672C\u7F13\u5B58\u8BF7\u6C42"),fe.clearCache(),this.logger.info("\u7248\u672C\u7F13\u5B58\u5DF2\u6E05\u9664"),e.json(this.createSuccessResponse(null,"\u7248\u672C\u7F13\u5B58\u5DF2\u6E05\u9664"))}catch(t){this.logger.error("\u6E05\u9664\u7248\u672C\u7F13\u5B58\u5931\u8D25:",t);let r=this.createErrorResponse("CACHE_CLEAR_ERROR",t instanceof Error?t.message:"\u6E05\u9664\u7248\u672C\u7F13\u5B58\u5931\u8D25");return e.json(r,500)}}}});var Bt,Gn=m(()=>{"use strict";y();q();z();Bt=class{static{c(this,"NotificationService")}logger;eventBus;clients=new Map;messageQueue=new Map;maxQueueSize=100;constructor(){this.logger=p.withTag("NotificationService"),this.eventBus=M(),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("config:updated",e=>{let t=h.getConfig();this.broadcastConfigUpdate(t)}),this.eventBus.onEvent("status:updated",e=>{this.broadcastStatusUpdate(e.status)}),this.eventBus.onEvent("service:restart:started",e=>{this.broadcastRestartStatus("restarting",void 0,e.timestamp)}),this.eventBus.onEvent("service:restart:completed",e=>{this.broadcastRestartStatus("completed",void 0,e.timestamp)}),this.eventBus.onEvent("service:restart:failed",e=>{this.broadcastRestartStatus("failed",e.error.message,e.timestamp)}),this.eventBus.onEvent("notification:broadcast",e=>{e.target?this.sendToClient(e.target,e.type,e.data):this.broadcast(e.type,e.data)})}registerClient(e,t){try{let r={id:e,ws:t,readyState:t.readyState,send:c(n=>{t.readyState===1&&t.send(n)},"send")};this.clients.set(e,r),this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u6CE8\u518C: ${e}`),this.logger.debug(`\u5F53\u524D\u5BA2\u6237\u7AEF\u6570\u91CF: ${this.clients.size}`),this.sendQueuedMessages(e),this.eventBus.emitEvent("websocket:client:connected",{clientId:e,timestamp:Date.now()})}catch(r){this.logger.error(`\u6CE8\u518C\u5BA2\u6237\u7AEF\u5931\u8D25: ${e}`,r),this.eventBus.emitEvent("notification:error",{error:r instanceof Error?r:new Error(String(r)),type:"client:register"})}}unregisterClient(e){try{this.clients.has(e)&&(this.clients.delete(e),this.messageQueue.delete(e),this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u6CE8\u9500: ${e}`),this.logger.debug(`\u5269\u4F59\u5BA2\u6237\u7AEF\u6570\u91CF: ${this.clients.size}`),this.eventBus.emitEvent("websocket:client:disconnected",{clientId:e,timestamp:Date.now()}))}catch(t){this.logger.error(`\u6CE8\u9500\u5BA2\u6237\u7AEF\u5931\u8D25: ${e}`,t)}}broadcast(e,t){let r={type:e,data:t,timestamp:Date.now()};this.logger.debug(`\u5E7F\u64AD\u6D88\u606F: ${e}`,{clientCount:this.clients.size});for(let[n,o]of this.clients)this.sendMessageToClient(o,r,n)}sendToClient(e,t,r){let n={type:t,data:r,timestamp:Date.now()},o=this.clients.get(e);o?this.sendMessageToClient(o,n,e):this.queueMessage(e,n)}sendMessageToClient(e,t,r){try{if(e.ws.readyState===1){let n=JSON.stringify(t);e.send(n),this.logger.debug(`\u6D88\u606F\u5DF2\u53D1\u9001\u7ED9\u5BA2\u6237\u7AEF ${r}: ${t.type}`)}else this.queueMessage(r,t),this.logger.warn(`\u5BA2\u6237\u7AEF ${r} \u8FDE\u63A5\u4E0D\u53EF\u7528\uFF0C\u6D88\u606F\u5DF2\u52A0\u5165\u961F\u5217`)}catch(n){this.logger.error(`\u53D1\u9001\u6D88\u606F\u7ED9\u5BA2\u6237\u7AEF ${r} \u5931\u8D25:`,n),this.queueMessage(r,t),this.eventBus.emitEvent("notification:error",{error:n instanceof Error?n:new Error(String(n)),type:"message:send"})}}queueMessage(e,t){this.messageQueue.has(e)||this.messageQueue.set(e,[]);let r=this.messageQueue.get(e);r.push(t),r.length>this.maxQueueSize&&(r.shift(),this.logger.warn(`\u5BA2\u6237\u7AEF ${e} \u6D88\u606F\u961F\u5217\u5DF2\u6EE1\uFF0C\u79FB\u9664\u6700\u65E7\u6D88\u606F`))}sendQueuedMessages(e){let t=this.messageQueue.get(e);if(!t||t.length===0)return;let r=this.clients.get(e);if(r){this.logger.info(`\u53D1\u9001 ${t.length} \u6761\u6392\u961F\u6D88\u606F\u7ED9\u5BA2\u6237\u7AEF ${e}`);for(let n of t)this.sendMessageToClient(r,n,e);this.messageQueue.delete(e)}}broadcastConfigUpdate(e){this.broadcast("configUpdate",e)}broadcastStatusUpdate(e){this.broadcast("statusUpdate",e)}broadcastRestartStatus(e,t,r){let n={status:e,error:t,timestamp:r||Date.now()};this.broadcast("restartStatus",n)}getClientStats(){let e=Array.from(this.clients.values()).filter(r=>r.ws.readyState===1).length,t=Array.from(this.messageQueue.values()).reduce((r,n)=>r+n.length,0);return{totalClients:this.clients.size,connectedClients:e,queuedMessages:t}}cleanupDisconnectedClients(){let e=[];for(let[t,r]of this.clients)r.ws.readyState!==1&&e.push(t);for(let t of e)this.unregisterClient(t);e.length>0&&this.logger.info(`\u6E05\u7406\u4E86 ${e.length} \u4E2A\u65AD\u5F00\u7684\u5BA2\u6237\u7AEF`)}destroy(){this.logger.info("\u9500\u6BC1\u901A\u77E5\u670D\u52A1"),this.clients.clear(),this.messageQueue.clear()}}});var Gt,qn=m(()=>{"use strict";y();z();Gt=class{static{c(this,"StatusService")}logger;eventBus;clientInfo={status:"disconnected",mcpEndpoint:"",activeMCPServers:[]};restartStatus;heartbeatTimeout;HEARTBEAT_TIMEOUT=35e3;constructor(){this.logger=p.withTag("StatusService"),this.eventBus=M()}getClientStatus(){return{...this.clientInfo}}updateClientInfo(e,t="unknown"){try{let r={...this.clientInfo};this.clientInfo={...this.clientInfo,...e},e.lastHeartbeat&&(this.clientInfo.lastHeartbeat=Date.now()),e.status==="connected"&&this.resetHeartbeatTimeout(),this.logger.debug(`\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\uFF0C\u6765\u6E90: ${t}`,{old:r,new:this.clientInfo}),this.eventBus.emitEvent("status:updated",{status:this.clientInfo,source:t})}catch(r){this.logger.error("\u66F4\u65B0\u5BA2\u6237\u7AEF\u72B6\u6001\u5931\u8D25:",r),this.eventBus.emitEvent("status:error",{error:r instanceof Error?r:new Error(String(r)),operation:"updateClientInfo"})}}getRestartStatus(){return this.restartStatus?{...this.restartStatus}:void 0}updateRestartStatus(e,t){try{switch(this.restartStatus={status:e,error:t,timestamp:Date.now()},this.logger.info(`\u91CD\u542F\u72B6\u6001\u66F4\u65B0: ${e}`,{error:t}),e){case"restarting":this.eventBus.emitEvent("service:restart:started",{timestamp:this.restartStatus.timestamp});break;case"completed":this.eventBus.emitEvent("service:restart:completed",{timestamp:this.restartStatus.timestamp});break;case"failed":this.eventBus.emitEvent("service:restart:failed",{error:new Error(t||"\u91CD\u542F\u5931\u8D25"),timestamp:this.restartStatus.timestamp});break}}catch(r){this.logger.error("\u66F4\u65B0\u91CD\u542F\u72B6\u6001\u5931\u8D25:",r),this.eventBus.emitEvent("status:error",{error:r instanceof Error?r:new Error(String(r)),operation:"updateRestartStatus"})}}getFullStatus(){return{client:this.getClientStatus(),restart:this.getRestartStatus(),timestamp:Date.now()}}resetHeartbeatTimeout(){this.heartbeatTimeout&&clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=setTimeout(()=>{this.logger.warn("\u5BA2\u6237\u7AEF\u5FC3\u8DF3\u8D85\u65F6\uFF0C\u6807\u8BB0\u4E3A\u65AD\u5F00\u8FDE\u63A5"),this.updateClientInfo({status:"disconnected"},"heartbeat-timeout")},this.HEARTBEAT_TIMEOUT)}clearHeartbeatTimeout(){this.heartbeatTimeout&&(clearTimeout(this.heartbeatTimeout),this.heartbeatTimeout=void 0)}isClientConnected(){return this.clientInfo.status==="connected"}getLastHeartbeat(){return this.clientInfo.lastHeartbeat}getActiveMCPServers(){return[...this.clientInfo.activeMCPServers]}setActiveMCPServers(e){this.updateClientInfo({activeMCPServers:[...e]},"mcp-servers-update")}setMcpEndpoint(e){this.updateClientInfo({mcpEndpoint:e},"mcp-endpoint-update")}reset(){this.logger.info("\u91CD\u7F6E\u72B6\u6001\u670D\u52A1"),this.clearHeartbeatTimeout(),this.clientInfo={status:"disconnected",mcpEndpoint:"",activeMCPServers:[]},this.restartStatus=void 0}destroy(){this.logger.info("\u9500\u6BC1\u72B6\u6001\u670D\u52A1"),this.clearHeartbeatTimeout(),this.reset()}}});var br={};G(br,{WebServer:()=>wr});import{createServer as Os}from"http";import{serve as As}from"@hono/node-server";import{Hono as Ns}from"hono";import{cors as Ds}from"hono/cors";import{WebSocketServer as ks}from"ws";var wr,Rr=m(()=>{"use strict";y();Ct();bn();q();It();An();Nn();kn();_n();Ln();jn();Hn();zn();Un();Fn();Vn();Bn();it();z();Gn();qn();wr=class{static{c(this,"WebServer")}app;httpServer=null;wss=null;logger;port;eventBus;configService;statusService;notificationService;configApiHandler;statusApiHandler;serviceApiHandler;toolApiHandler;versionApiHandler;staticFileHandler;mcpRouteHandler;realtimeNotificationHandler;heartbeatHandler;heartbeatMonitorInterval;proxyMCPServer;xiaozhiConnectionManager;mcpServiceManager;createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}logDeprecationWarning(e,t){this.logger.warn(`[DEPRECATED] ${e} \u529F\u80FD\u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u4F7F\u7528 ${t} \u66FF\u4EE3`)}constructor(e){try{this.port=e??h.getWebUIPort()??9999}catch{this.port=e??9999}this.logger=p.withTag("WebServer"),this.eventBus=M(),this.configService=new ge,this.statusService=new Gt,this.notificationService=new Bt,this.configApiHandler=new xt,this.statusApiHandler=new Ut(this.statusService),this.serviceApiHandler=new jt(this.statusService),this.toolApiHandler=new Wt,this.versionApiHandler=new Vt,this.staticFileHandler=new zt,this.mcpRouteHandler=new kt,this.realtimeNotificationHandler=new _t(this.notificationService,this.statusService),this.heartbeatHandler=new Dt(this.statusService,this.notificationService),this.app=new Ns,this.setupMiddleware(),this.setupRoutes(),this.logger.info("WebServer \u67B6\u6784\u91CD\u6784\u5B8C\u6210 - \u7B2C\u4E8C\u9636\u6BB5\uFF1A\u6A21\u5757\u5316\u62C6\u5206"),this.setupEndpointStatusListener()}async initializeConnections(){try{this.logger.info("\u5F00\u59CB\u521D\u59CB\u5316\u8FDE\u63A5...");let e=await this.loadConfiguration();this.mcpServiceManager=await X.getInstance(),await this.loadMCPServicesFromConfig(e.mcpServers);let t=this.mcpServiceManager.getAllTools();this.logger.info(`\u5DF2\u52A0\u8F7D ${t.length} \u4E2A\u5DE5\u5177`),await this.initializeXiaozhiConnection(e.mcpEndpoint,t),this.logger.info("\u6240\u6709\u8FDE\u63A5\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw this.logger.error("\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25:",e),e}}async loadConfiguration(){if(!h.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C 'xiaozhi init' \u521D\u59CB\u5316\u914D\u7F6E");h.cleanupInvalidServerToolsConfig();let e=h.getConfig();return{mcpEndpoint:e.mcpEndpoint,mcpServers:e.mcpServers,webUIPort:e.webUI?.port??9999}}async loadMCPServicesFromConfig(e){if(!this.mcpServiceManager)throw new Error("MCPServiceManager \u672A\u521D\u59CB\u5316");for(let[t,r]of Object.entries(e)){this.logger.info(`\u6DFB\u52A0 MCP \u670D\u52A1\u914D\u7F6E: ${t}`);let n=wn(t,r);this.mcpServiceManager.addServiceConfig(t,n)}await this.mcpServiceManager.startAllServices(),this.logger.info("\u6240\u6709 MCP \u670D\u52A1\u5DF2\u542F\u52A8")}async initializeXiaozhiConnection(e,t){let n=(Array.isArray(e)?e:[e]).filter(o=>o&&!o.includes("<\u8BF7\u586B\u5199"));if(n.length===0){this.logger.warn("\u672A\u914D\u7F6E\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u8DF3\u8FC7\u8FDE\u63A5");return}this.logger.info(`\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u7BA1\u7406\u5668\uFF0C\u7AEF\u70B9\u6570\u91CF: ${n.length}`),this.logger.debug("\u6709\u6548\u7AEF\u70B9\u5217\u8868:",n);try{this.xiaozhiConnectionManager=await We.getInstance({reconnectInterval:5e3,maxReconnectAttempts:3,connectionTimeout:1e4}),this.mcpServiceManager&&this.xiaozhiConnectionManager&&this.xiaozhiConnectionManager.setServiceManager(this.mcpServiceManager),this.xiaozhiConnectionManager&&(await this.xiaozhiConnectionManager.initialize(n,t),await this.xiaozhiConnectionManager.connect(),this.xiaozhiConnectionManager.on("configChange",o=>{this.logger.info(`\u5C0F\u667A\u8FDE\u63A5\u914D\u7F6E\u53D8\u66F4: ${o.type}`,o.data)})),this.logger.info(`\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u7BA1\u7406\u5668\u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u7BA1\u7406 ${n.length} \u4E2A\u7AEF\u70B9`)}catch(o){this.logger.error("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u7BA1\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",o),this.logger.warn("\u56DE\u9000\u5230\u5355\u8FDE\u63A5\u6A21\u5F0F");let s=n[0];this.logger.info(`\u521D\u59CB\u5316\u5355\u4E2A\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5: ${s}`),this.proxyMCPServer=new Ce(s),this.mcpServiceManager&&this.proxyMCPServer.setServiceManager(this.mcpServiceManager),await this.connectWithRetry(()=>this.proxyMCPServer.connect(),"\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5"),this.logger.info("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F\uFF08\u5355\u8FDE\u63A5\u6A21\u5F0F\uFF09")}}getXiaozhiConnectionStatus(){return this.xiaozhiConnectionManager?{type:"multi-endpoint",manager:{connectedConnections:this.xiaozhiConnectionManager.getConnectionStatus().filter(e=>e.connected).length,totalConnections:this.xiaozhiConnectionManager.getConnectionStatus().length,healthCheckStats:{},reconnectStats:this.xiaozhiConnectionManager.getReconnectStats()},connections:this.xiaozhiConnectionManager.getConnectionStatus()}:this.proxyMCPServer?{type:"single-endpoint",connected:!0,endpoint:"unknown"}:{type:"none",connected:!1}}async handleEndpointStatus(e){if(!this.xiaozhiConnectionManager){let r=this.createErrorResponse("CONNECTION_MANAGER_NOT_AVAILABLE","\u8FDE\u63A5\u7BA1\u7406\u5668\u672A\u521D\u59CB\u5316");return e.json(r,503)}return new de(this.xiaozhiConnectionManager,h).getEndpointStatus(e)}async handleEndpointConnect(e){if(!this.xiaozhiConnectionManager){let r=this.createErrorResponse("CONNECTION_MANAGER_NOT_AVAILABLE","\u8FDE\u63A5\u7BA1\u7406\u5668\u672A\u521D\u59CB\u5316");return e.json(r,503)}return new de(this.xiaozhiConnectionManager,h).connectEndpoint(e)}async handleEndpointDisconnect(e){if(!this.xiaozhiConnectionManager){let r=this.createErrorResponse("CONNECTION_MANAGER_NOT_AVAILABLE","\u8FDE\u63A5\u7BA1\u7406\u5668\u672A\u521D\u59CB\u5316");return e.json(r,503)}return new de(this.xiaozhiConnectionManager,h).disconnectEndpoint(e)}async handleEndpointReconnect(e){if(!this.xiaozhiConnectionManager){let r=this.createErrorResponse("CONNECTION_MANAGER_NOT_AVAILABLE","\u8FDE\u63A5\u7BA1\u7406\u5668\u672A\u521D\u59CB\u5316");return e.json(r,503)}return new de(this.xiaozhiConnectionManager,h).reconnectEndpoint(e)}async handleEndpointAdd(e){if(!this.xiaozhiConnectionManager){let r=this.createErrorResponse("CONNECTION_MANAGER_NOT_AVAILABLE","\u8FDE\u63A5\u7BA1\u7406\u5668\u672A\u521D\u59CB\u5316");return e.json(r,503)}return await new de(this.xiaozhiConnectionManager,h).addEndpoint(e)}async handleEndpointRemove(e){if(!this.xiaozhiConnectionManager){let r=this.createErrorResponse("CONNECTION_MANAGER_NOT_AVAILABLE","\u8FDE\u63A5\u7BA1\u7406\u5668\u672A\u521D\u59CB\u5316");return e.json(r,503)}return new de(this.xiaozhiConnectionManager,h).removeEndpoint(e)}async connectWithRetry(e,t,r=5,n=1e3,o=3e4,s=2){let a=null;for(let l=1;l<=r;l++)try{return this.logger.info(`${t} - \u5C1D\u8BD5\u8FDE\u63A5 (${l}/${r})`),await e()}catch(g){if(a=g,this.logger.warn(`${t} - \u8FDE\u63A5\u5931\u8D25:`,g),l<r){let u=Math.min(n*s**(l-1),o);this.logger.info(`${t} - ${u}ms \u540E\u91CD\u8BD5...`),await this.sleep(u)}}throw new Error(`${t} - \u8FDE\u63A5\u5931\u8D25\uFF0C\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570: ${a?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}setupMiddleware(){this.app?.use("*",Ds({origin:"*",allowMethods:["GET","POST","PUT","OPTIONS"],allowHeaders:["Content-Type"]})),this.app?.onError((e,t)=>{this.logger.error("HTTP request error:",e);let r=this.createErrorResponse("INTERNAL_SERVER_ERROR","\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF",process.env.NODE_ENV==="development"?e.stack:void 0);return t.json(r,500)})}setupRoutes(){this.app?.get("/api/config",e=>this.configApiHandler.getConfig(e)),this.app?.put("/api/config",e=>this.configApiHandler.updateConfig(e)),this.app?.get("/api/config/mcp-endpoint",e=>this.configApiHandler.getMcpEndpoint(e)),this.app?.get("/api/config/mcp-endpoints",e=>this.configApiHandler.getMcpEndpoints(e)),this.app?.get("/api/config/mcp-servers",e=>this.configApiHandler.getMcpServers(e)),this.app?.get("/api/config/connection",e=>this.configApiHandler.getConnectionConfig(e)),this.app?.post("/api/config/reload",e=>this.configApiHandler.reloadConfig(e)),this.app?.get("/api/config/path",e=>this.configApiHandler.getConfigPath(e)),this.app?.get("/api/config/exists",e=>this.configApiHandler.checkConfigExists(e)),this.app?.get("/api/version",e=>this.versionApiHandler.getVersion(e)),this.app?.get("/api/version/simple",e=>this.versionApiHandler.getVersionSimple(e)),this.app?.post("/api/version/cache/clear",e=>this.versionApiHandler.clearVersionCache(e)),this.app?.get("/api/status",e=>this.statusApiHandler.getStatus(e)),this.app?.get("/api/status/client",e=>this.statusApiHandler.getClientStatus(e)),this.app?.get("/api/status/restart",e=>this.statusApiHandler.getRestartStatus(e)),this.app?.get("/api/status/connected",e=>this.statusApiHandler.checkClientConnected(e)),this.app?.get("/api/status/heartbeat",e=>this.statusApiHandler.getLastHeartbeat(e)),this.app?.get("/api/status/mcp-servers",e=>this.statusApiHandler.getActiveMCPServers(e)),this.app?.put("/api/status/client",e=>this.statusApiHandler.updateClientStatus(e)),this.app?.put("/api/status/mcp-servers",e=>this.statusApiHandler.setActiveMCPServers(e)),this.app?.post("/api/status/reset",e=>this.statusApiHandler.resetStatus(e)),this.app?.post("/api/services/restart",e=>this.serviceApiHandler.restartService(e)),this.app?.post("/api/services/stop",e=>this.serviceApiHandler.stopService(e)),this.app?.post("/api/services/start",e=>this.serviceApiHandler.startService(e)),this.app?.get("/api/services/status",e=>this.serviceApiHandler.getServiceStatus(e)),this.app?.get("/api/services/health",e=>this.serviceApiHandler.getServiceHealth(e)),this.app?.post("/api/tools/call",e=>this.toolApiHandler.callTool(e)),this.app?.get("/api/tools/list",e=>this.toolApiHandler.listTools(e)),this.app?.get("/api/tools/custom",e=>this.toolApiHandler.getCustomTools(e)),this.app?.post("/api/tools/custom",e=>this.toolApiHandler.addCustomTool(e)),this.app?.put("/api/tools/custom/:toolName",e=>this.toolApiHandler.updateCustomTool(e)),this.app?.delete("/api/tools/custom/:toolName",e=>this.toolApiHandler.removeCustomTool(e)),this.app?.get("/api/coze/workspaces",e=>Pe.getWorkspaces(e)),this.app?.get("/api/coze/workflows",e=>Pe.getWorkflows(e)),this.app?.post("/api/coze/cache/clear",e=>Pe.clearCache(e)),this.app?.get("/api/coze/cache/stats",e=>Pe.getCacheStats(e)),this.app?.get("/api/endpoints/:endpoint/status",e=>this.handleEndpointStatus(e)),this.app?.post("/api/endpoints/:endpoint/connect",e=>this.handleEndpointConnect(e)),this.app?.post("/api/endpoints/:endpoint/disconnect",e=>this.handleEndpointDisconnect(e)),this.app?.post("/api/endpoints/:endpoint/reconnect",e=>this.handleEndpointReconnect(e)),this.app?.post("/api/endpoints/add",e=>this.handleEndpointAdd(e)),this.app?.delete("/api/endpoints/:endpoint",e=>this.handleEndpointRemove(e)),this.app?.post("/mcp",e=>this.mcpRouteHandler.handlePost(e)),this.app?.get("/mcp",e=>this.mcpRouteHandler.handleGet(e)),this.app?.all("/api/*",async e=>{let t=this.createErrorResponse("API_NOT_FOUND",`API \u7AEF\u70B9\u4E0D\u5B58\u5728: ${e.req.path}`);return e.json(t,404)}),this.app.get("*",e=>this.staticFileHandler.handleStaticFile(e))}setupWebSocket(){this.wss&&this.wss.on("connection",e=>{let t=`client-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u8FDE\u63A5: ${t}`),this.logger.debug(`\u5F53\u524D WebSocket \u8FDE\u63A5\u6570: ${this.wss?.clients.size||0}`),this.realtimeNotificationHandler.handleClientConnect(e,t),this.heartbeatHandler.handleClientConnect(t),e.on("message",async r=>{try{let n=JSON.parse(r.toString());n.type==="clientStatus"?await this.heartbeatHandler.handleClientStatus(e,n,t):await this.realtimeNotificationHandler.handleMessage(e,n,t)}catch(n){this.logger.error("WebSocket message error:",n);let o={type:"error",error:{code:"MESSAGE_PARSE_ERROR",message:n instanceof Error?n.message:"\u6D88\u606F\u89E3\u6790\u5931\u8D25",timestamp:Date.now()}};e.send(JSON.stringify(o))}}),e.on("close",()=>{this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u65AD\u5F00\u8FDE\u63A5: ${t}`),this.logger.debug(`\u5269\u4F59 WebSocket \u8FDE\u63A5\u6570: ${this.wss?.clients.size||0}`),this.realtimeNotificationHandler.handleClientDisconnect(t),this.heartbeatHandler.handleClientDisconnect(t)}),e.on("error",r=>{this.logger.error(`WebSocket \u8FDE\u63A5\u9519\u8BEF (${t}):`,r)}),this.realtimeNotificationHandler.sendInitialData(e,t)})}setupEndpointStatusListener(){this.eventBus.onEvent("endpoint:status:changed",e=>{let t={type:"endpoint_status_changed",data:{endpoint:e.endpoint,connected:e.connected,operation:e.operation,success:e.success,message:e.message,timestamp:e.timestamp}};this.notificationService.broadcast("endpoint_status_changed",t),this.logger.debug(`\u5E7F\u64AD\u63A5\u5165\u70B9\u72B6\u6001\u53D8\u66F4\u4E8B\u4EF6: ${e.endpoint} - ${e.operation}`)})}async start(){if(this.httpServer){this.logger.warn("Web server is already running");return}let e=As({fetch:this.app.fetch,port:this.port,hostname:"0.0.0.0",createServer:Os});this.httpServer=e,this.wss=new ks({server:this.httpServer}),this.setupWebSocket(),this.heartbeatMonitorInterval=this.heartbeatHandler.startHeartbeatMonitoring(),this.logger.info(`Web server listening on http://0.0.0.0:${this.port}`),this.logger.info(`Local access: http://localhost:${this.port}`),this.logger.info("=== \u901A\u4FE1\u67B6\u6784\u91CD\u6784\u4FE1\u606F - \u7B2C\u4E8C\u9636\u6BB5\u5B8C\u6210 ==="),this.logger.info("\u2705 \u6A21\u5757\u5316\u62C6\u5206: HTTP/WebSocket \u5904\u7406\u5668\u72EC\u7ACB"),this.logger.info("\u2705 \u670D\u52A1\u5C42\u62BD\u8C61: ConfigService, StatusService, NotificationService"),this.logger.info("\u2705 \u4E8B\u4EF6\u9A71\u52A8\u673A\u5236: EventBus \u5B9E\u73B0\u6A21\u5757\u95F4\u89E3\u8026\u901A\u4FE1"),this.logger.info("\u2705 HTTP API \u804C\u8D23: \u914D\u7F6E\u7BA1\u7406\u3001\u72B6\u6001\u67E5\u8BE2\u3001\u670D\u52A1\u63A7\u5236"),this.logger.info("\u2705 WebSocket \u804C\u8D23: \u5B9E\u65F6\u901A\u77E5\u3001\u5FC3\u8DF3\u68C0\u6D4B\u3001\u4E8B\u4EF6\u5E7F\u64AD"),this.logger.info("\u26A0\uFE0F \u5DF2\u5E9F\u5F03\u7684 WebSocket \u6D88\u606F: getConfig, updateConfig, getStatus, restartService"),this.logger.info("\u{1F4D6} \u63A8\u8350\u4F7F\u7528\u5BF9\u5E94\u7684 HTTP API \u66FF\u4EE3\u5E9F\u5F03\u7684 WebSocket \u6D88\u606F"),this.logger.info("================================================");try{await this.initializeConnections()}catch(t){this.logger.error("\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25\uFF0C\u4F46 Web \u670D\u52A1\u5668\u7EE7\u7EED\u8FD0\u884C:",t)}}stop(){return new Promise(e=>{let t=!1,r=c(()=>{t||(t=!0,e())},"doResolve");if(this.proxyMCPServer?.disconnect(),this.heartbeatMonitorInterval&&(this.heartbeatHandler.stopHeartbeatMonitoring(this.heartbeatMonitorInterval),this.heartbeatMonitorInterval=void 0),this.wss){for(let n of this.wss.clients)n.terminate();this.wss.close(()=>{this.httpServer?this.httpServer.close(()=>{this.logger.info("Web server stopped"),r()}):(this.logger.info("Web server stopped"),r()),setTimeout(()=>{this.logger.info("Web server force stopped"),r()},2e3)})}else this.logger.info("Web server stopped"),r()})}destroy(){this.logger.info("\u9500\u6BC1 WebServer \u5B9E\u4F8B"),this.heartbeatMonitorInterval&&(this.heartbeatHandler.stopHeartbeatMonitoring(this.heartbeatMonitorInterval),this.heartbeatMonitorInterval=void 0),this.statusService.destroy(),this.notificationService.destroy(),Fr(),this.proxyMCPServer?.disconnect(),this.logger.info("WebServer \u5B9E\u4F8B\u5DF2\u9500\u6BC1")}}});var Jn={};G(Jn,{ServiceManagerImpl:()=>Ir});var Ir,Xn=m(()=>{"use strict";oe();De();Ye();dt();Ir=class{constructor(e,t,r){this.processManager=e;this.configManager=t;this.logger=r}static{c(this,"ServiceManagerImpl")}async start(e){try{this.validateStartOptions(e),this.processManager.cleanupContainerState();let t=this.getStatus();if(t.running){console.log(`\u68C0\u6D4B\u5230\u670D\u52A1\u5DF2\u5728\u8FD0\u884C (PID: ${t.pid})\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u542F...`);try{await this.processManager.gracefulKillProcess(t.pid),this.processManager.cleanupPidFile(),await new Promise(r=>setTimeout(r,1e3)),console.log("\u73B0\u6709\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u6B63\u5728\u542F\u52A8\u65B0\u670D\u52A1...")}catch(r){console.warn(`\u505C\u6B62\u73B0\u6709\u670D\u52A1\u65F6\u51FA\u73B0\u8B66\u544A: ${r instanceof Error?r.message:String(r)}`)}}switch(this.checkEnvironment(),e.mode){case"mcp-server":await this.startMcpServerMode(e);break;case"stdio":await this.startStdioMode(e);break;case"normal":await this.startNormalMode(e);break;default:await this.startNormalMode(e);break}}catch(t){throw t instanceof x?t:x.startFailed(t instanceof Error?t.message:String(t))}}async stop(){try{let e=this.getStatus();if(!e.running)throw x.notRunning();await this.processManager.gracefulKillProcess(e.pid),this.processManager.cleanupPidFile()}catch(e){throw e instanceof x?e:new x(`\u505C\u6B62\u670D\u52A1\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async restart(e){try{this.getStatus().running&&(await this.stop(),await new Promise(r=>setTimeout(r,1e3))),await this.start(e)}catch(t){throw new x(`\u91CD\u542F\u670D\u52A1\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}getStatus(){return this.processManager.getServiceStatus()}validateStartOptions(e){if(e.port!==void 0&&Q.validatePort(e.port),e.mode&&!["normal","mcp-server","stdio"].includes(e.mode))throw new x(`\u65E0\u6548\u7684\u8FD0\u884C\u6A21\u5F0F: ${e.mode}`)}checkEnvironment(){if(!this.configManager.configExists())throw Te.configNotFound();try{if(!this.configManager.getConfig())throw new Te("\u914D\u7F6E\u6587\u4EF6\u65E0\u6548")}catch(e){throw e instanceof Te?e:new Te(`\u914D\u7F6E\u6587\u4EF6\u9519\u8BEF: ${e instanceof Error?e.message:String(e)}`)}}async startNormalMode(e){let{spawn:t}=await import("child_process");e.daemon?await this.startWebServerInDaemon(e.ui||!1):await this.startWebServerInForeground(e.ui||!1)}async startMcpServerMode(e){let t=e.port||3e3,{spawn:r}=await import("child_process");if(e.daemon){let n=$.getExecutablePath("cli"),o=r("node",[n,"start","--server",t.toString()],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:$.getConfigDir(),XIAOZHI_DAEMON:"true",MCP_SERVER_MODE:"true"}});this.processManager.savePidInfo(o.pid,"daemon"),o.unref(),console.log(`\u2705 MCP Server \u5DF2\u5728\u540E\u53F0\u542F\u52A8 (PID: ${o.pid}, Port: ${t})`),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi status' \u67E5\u770B\u72B6\u6001"),process.exit(0)}else{let{MCPServer:n}=await Promise.resolve().then(()=>(En(),yn)),o=new n(t),s=c(async()=>{await o.stop(),process.exit(0)},"cleanup");process.on("SIGINT",s),process.on("SIGTERM",s),await o.start()}}async startStdioMode(e){let{spawn:t}=await import("child_process"),r=$.getMcpServerProxyPath(),n=t("node",[r],{stdio:"inherit",env:{...process.env,XIAOZHI_CONFIG_DIR:$.getConfigDir()}});this.processManager.savePidInfo(n.pid,"foreground")}async startWebServerInDaemon(e){let{spawn:t}=await import("child_process"),r=$.getWebServerStandalonePath();if(!(await import("fs")).default.existsSync(r))throw new x(`WebServer \u6587\u4EF6\u4E0D\u5B58\u5728: ${r}`);let o=[r];e&&o.push("--open-browser");let s=t("node",o,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:$.getConfigDir(),XIAOZHI_DAEMON:"true"}});this.processManager.savePidInfo(s.pid,"daemon"),s.unref(),console.log(`\u2705 \u540E\u53F0\u670D\u52A1\u5DF2\u542F\u52A8 (PID: ${s.pid})`),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi status' \u67E5\u770B\u72B6\u6001"),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi attach' \u67E5\u770B\u65E5\u5FD7"),process.exit(0)}async startWebServerInForeground(e){let{WebServer:t}=await Promise.resolve().then(()=>(Rr(),br)),r=new t,n=c(async()=>{await r.stop(),this.processManager.cleanupPidFile(),process.exit(0)},"cleanup");if(process.on("SIGINT",n),process.on("SIGTERM",n),this.processManager.savePidInfo(process.pid,"foreground"),await r.start(),e){let s=this.configManager.getConfig()?.webServer?.port||9999;await this.openBrowserUrl(`http://localhost:${s}`)}}async openBrowserUrl(e){try{let{spawn:t}=await import("child_process"),r=J.getCurrentPlatform(),n,o;r==="darwin"?(n="open",o=[e]):r==="win32"?(n="start",o=["",e]):(n="xdg-open",o=[e]),t(n,o,{detached:!0,stdio:"ignore"}),console.log(`\u{1F310} \u5DF2\u5C1D\u8BD5\u6253\u5F00\u6D4F\u89C8\u5668: ${e}`)}catch{console.log(`\u26A0\uFE0F \u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE: ${e}`)}}}});var Kn={};G(Kn,{TemplateManagerImpl:()=>$r});import _s from"fs";import be from"path";var $r,Zn=m(()=>{"use strict";oe();Ze();De();dt();$r=class{static{c(this,"TemplateManagerImpl")}templateCache=new Map;async getAvailableTemplates(){try{let e=$.findTemplatesDir();if(!e)return[];let t=[],r=_s.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name);for(let n of r)try{let o=await this.getTemplateInfo(n);o&&t.push(o)}catch{console.warn(`\u8DF3\u8FC7\u65E0\u6548\u6A21\u677F: ${n}`)}return t}catch{throw new S("\u65E0\u6CD5\u8BFB\u53D6\u6A21\u677F\u76EE\u5F55",$.findTemplatesDir()||"")}}async getTemplateInfo(e){try{if(Q.validateTemplateName(e),this.templateCache.has(e))return this.templateCache.get(e);let t=$.getTemplatePath(e);if(!t)return null;let r=be.join(t,"template.json"),n={};if(w.exists(r))try{let a=w.readFile(r);n=JSON.parse(a)}catch{console.warn(`\u6A21\u677F\u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${e}`)}let o=this.getTemplateFiles(t),s={name:e,path:t,description:n.description||`${e} \u6A21\u677F`,version:n.version||"1.0.0",author:n.author,files:o};return this.templateCache.set(e,s),s}catch(t){throw t instanceof P?t:new S(`\u65E0\u6CD5\u83B7\u53D6\u6A21\u677F\u4FE1\u606F: ${e}`,"")}}async copyTemplate(e,t){await this.createProject({templateName:e,targetPath:t,projectName:be.basename(t)})}async createProject(e){try{this.validateCreateOptions(e);let t=e.templateName||"default",r=await this.getTemplateInfo(t);if(!r)throw new S(`\u6A21\u677F\u4E0D\u5B58\u5728: ${t}`,"");let n=be.resolve(e.targetPath);if(w.exists(n))throw S.alreadyExists(n);w.ensureDir(n),await this.copyTemplateFiles(r,n,e),await this.processTemplateVariables(n,e),console.log(`\u2705 \u9879\u76EE\u521B\u5EFA\u6210\u529F: ${n}`)}catch(t){throw t instanceof S||t instanceof P?t:new S(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,e.targetPath)}}async validateTemplate(e){try{let t=await this.getTemplateInfo(e);if(!t)return!1;let r=["package.json"];for(let n of r){let o=be.join(t.path,n);if(!w.exists(o))return console.warn(`\u6A21\u677F\u7F3A\u5C11\u5FC5\u8981\u6587\u4EF6: ${n}`),!1}return!0}catch{return!1}}clearCache(){this.templateCache.clear()}getTemplateFiles(e){try{return w.listDirectory(e,{recursive:!0,includeHidden:!1}).filter(r=>{let n=be.relative(e,r);return!n.startsWith(".")&&n!=="template.json"&&!n.includes("node_modules")})}catch{return[]}}validateCreateOptions(e){Q.validateRequired(e.targetPath,"targetPath"),Q.validateRequired(e.projectName,"projectName"),Q.validateProjectName(e.projectName),e.templateName&&Q.validateTemplateName(e.templateName)}async copyTemplateFiles(e,t,r){try{w.copyDirectory(e.path,t,{exclude:["template.json",".git","node_modules"],overwrite:!1,recursive:!0})}catch(n){throw new S(`\u590D\u5236\u6A21\u677F\u6587\u4EF6\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`,e.path)}}async processTemplateVariables(e,t){try{let r={PROJECT_NAME:t.projectName,PROJECT_NAME_LOWER:t.projectName.toLowerCase(),PROJECT_NAME_UPPER:t.projectName.toUpperCase(),...t.variables},n=["package.json","README.md","src/**/*.ts","src/**/*.js","src/**/*.json"];for(let o of n){let s=this.findFilesByPattern(e,o);for(let a of s)await this.replaceVariablesInFile(a,r)}}catch(r){console.warn(`\u5904\u7406\u6A21\u677F\u53D8\u91CF\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}findFilesByPattern(e,t){try{if(!t.includes("*")){let o=be.join(e,t);return w.exists(o)?[o]:[]}let r=w.listDirectory(e,{recursive:!0}),n=new RegExp(t.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*"));return r.filter(o=>{let s=be.relative(e,o);return n.test(s)})}catch{return[]}}async replaceVariablesInFile(e,t){try{let r=w.readFile(e),n=!1;for(let[o,s]of Object.entries(t)){let a=new RegExp(`{{\\s*${o}\\s*}}`,"g");a.test(r)&&(r=r.replace(a,s),n=!0)}n&&w.writeFile(e,r,{overwrite:!0})}catch(r){console.warn(`\u66FF\u6362\u6587\u4EF6\u53D8\u91CF\u5931\u8D25 ${e}: ${r instanceof Error?r.message:String(r)}`)}}}});async function we(){return xr.create()}var xr,Pr=m(()=>{"use strict";y();q();cr();Ze();lr();De();Ye();dt();gr();xr=class i{static{c(this,"DIContainer")}instances=new Map;factories=new Map;asyncFactories=new Map;singletons=new Set;register(e,t,r=!1){this.factories.set(e,t),r&&this.singletons.add(e)}registerSingleton(e,t){this.register(e,t,!0)}registerInstance(e,t){this.instances.set(e,t),this.singletons.add(e)}get(e){if(this.singletons.has(e)&&this.instances.has(e))return this.instances.get(e);let t=this.factories.get(e);if(!t)throw new Error(`Service ${e} not registered`);let r=t();return this.singletons.has(e)&&this.instances.set(e,r),r}has(e){return this.factories.has(e)||this.instances.has(e)}clear(){this.instances.clear(),this.factories.clear(),this.singletons.clear()}getRegisteredKeys(){let e=Array.from(this.factories.keys()),t=Array.from(this.instances.keys());return[...new Set([...e,...t])]}static create(){let e=new i;return e.registerSingleton("versionUtils",()=>fe),e.registerSingleton("platformUtils",()=>J),e.registerSingleton("formatUtils",()=>Ne),e.registerSingleton("fileUtils",()=>w),e.registerSingleton("pathUtils",()=>$),e.registerSingleton("validation",()=>Q),e.registerSingleton("configManager",()=>h),e.registerSingleton("logger",()=>p),e.registerSingleton("errorHandler",()=>se),e.registerSingleton("processManager",()=>{let t=(pr(),ne(Kr));return new t.ProcessManagerImpl}),e.registerSingleton("daemonManager",()=>{let t=(Qr(),ne(Yr)),r=e.get("processManager"),n=e.get("logger");return new t.DaemonManagerImpl(r,n)}),e.registerSingleton("serviceManager",()=>{let t=(Xn(),ne(Jn)),r=e.get("processManager"),n=e.get("configManager"),o=e.get("logger");return new t.ServiceManagerImpl(r,n,o)}),e.registerSingleton("templateManager",()=>{let t=(Zn(),ne(Kn));return new t.TemplateManagerImpl}),e}};c(we,"createContainer")});var V,Re=m(()=>{"use strict";V=class{constructor(e){this.container=e}static{c(this,"BaseCommandHandler")}options;subcommands;getService(e){return this.container.get(e)}handleError(e){this.getService("errorHandler").handle(e)}validateArgs(e,t){if(e.length<t)throw new Error(`\u547D\u4EE4\u9700\u8981\u81F3\u5C11 ${t} \u4E2A\u53C2\u6570\uFF0C\u4F46\u53EA\u63D0\u4F9B\u4E86 ${e.length} \u4E2A`)}}});var Yn={};G(Yn,{ServiceCommandHandler:()=>Or});var Or,Qn=m(()=>{"use strict";y();Re();Or=class extends V{static{c(this,"ServiceCommandHandler")}name="service";description="\u670D\u52A1\u7BA1\u7406\u547D\u4EE4";subcommands=[{name:"start",description:"\u542F\u52A8\u670D\u52A1",options:[{flags:"-d, --daemon",description:"\u5728\u540E\u53F0\u8FD0\u884C\u670D\u52A1"},{flags:"-u, --ui",description:"\u540C\u65F6\u542F\u52A8 Web UI \u670D\u52A1"},{flags:"--debug",description:"\u542F\u7528\u8C03\u8BD5\u6A21\u5F0F (\u8F93\u51FADEBUG\u7EA7\u522B\u65E5\u5FD7)"},{flags:"--stdio",description:"\u4EE5 stdio \u6A21\u5F0F\u8FD0\u884C MCP Server (\u7528\u4E8E Cursor \u7B49\u5BA2\u6237\u7AEF)"}],execute:c(async(e,t)=>{await this.handleStart(t)},"execute")},{name:"stop",description:"\u505C\u6B62\u670D\u52A1",execute:c(async(e,t)=>{await this.handleStop()},"execute")},{name:"status",description:"\u68C0\u67E5\u670D\u52A1\u72B6\u6001",execute:c(async(e,t)=>{await this.handleStatus()},"execute")},{name:"restart",description:"\u91CD\u542F\u670D\u52A1",options:[{flags:"-d, --daemon",description:"\u5728\u540E\u53F0\u8FD0\u884C\u670D\u52A1"},{flags:"-u, --ui",description:"\u540C\u65F6\u542F\u52A8 Web UI \u670D\u52A1"}],execute:c(async(e,t)=>{await this.handleRestart(t)},"execute")},{name:"attach",description:"\u8FDE\u63A5\u5230\u540E\u53F0\u670D\u52A1\u67E5\u770B\u65E5\u5FD7",execute:c(async(e,t)=>{await this.handleAttach()},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("\u670D\u52A1\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleStart(e){try{e.debug&&Ur("debug");let t=this.getService("serviceManager");e.stdio?await this.startStdioMode():await t.start({daemon:e.daemon||!1,ui:e.ui||!1})}catch(t){this.handleError(t)}}async handleStop(){try{await this.getService("serviceManager").stop()}catch(e){this.handleError(e)}}async handleStatus(){try{let t=await this.getService("serviceManager").getStatus();t.running?(console.log(`\u2705 \u670D\u52A1\u6B63\u5728\u8FD0\u884C (PID: ${t.pid})`),t.uptime&&console.log(`\u23F1\uFE0F \u8FD0\u884C\u65F6\u95F4: ${t.uptime}`),t.mode&&console.log(`\u{1F527} \u8FD0\u884C\u6A21\u5F0F: ${t.mode}`)):console.log("\u274C \u670D\u52A1\u672A\u8FD0\u884C")}catch(e){this.handleError(e)}}async handleRestart(e){try{await this.getService("serviceManager").restart({daemon:e.daemon||!1,ui:e.ui||!1})}catch(t){this.handleError(t)}}async handleAttach(){try{await this.getService("daemonManager").attachToLogs()}catch(e){this.handleError(e)}}async startStdioMode(){let{spawn:e}=await import("child_process"),{fileURLToPath:t}=await import("url"),r=await import("path"),n=t(import.meta.url),o=r.dirname(n),s=r.join(o,"mcpServerProxy.js");e("node",[s],{stdio:"inherit",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}})}}});var eo={};G(eo,{ConfigCommandHandler:()=>Nr});import Ls from"path";import R from"chalk";import Ar from"ora";var Nr,to=m(()=>{"use strict";Re();Nr=class extends V{static{c(this,"ConfigCommandHandler")}name="config";description="\u914D\u7F6E\u7BA1\u7406\u547D\u4EE4";subcommands=[{name:"init",description:"\u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6",options:[{flags:"-f, --format <format>",description:"\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F (json, json5, jsonc)",defaultValue:"json"}],execute:c(async(e,t)=>{await this.handleInit(t)},"execute")},{name:"get",description:"\u67E5\u770B\u914D\u7F6E\u503C",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleGet(e[0])},"execute")},{name:"set",description:"\u8BBE\u7F6E\u914D\u7F6E\u503C",execute:c(async(e,t)=>{this.validateArgs(e,2),await this.handleSet(e[0],e[1])},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("\u914D\u7F6E\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleInit(e){let t=Ar("\u521D\u59CB\u5316\u914D\u7F6E...").start();try{let r=e.format;if(r!=="json"&&r!=="json5"&&r!=="jsonc")throw new Error("\u683C\u5F0F\u5FC5\u987B\u662F json, json5 \u6216 jsonc");let n=this.getService("configManager");if(n.configExists()){t.warn("\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728"),console.log(R.yellow("\u5982\u9700\u91CD\u65B0\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u5220\u9664\u73B0\u6709\u7684\u914D\u7F6E\u6587\u4EF6"));return}n.initConfig(r),t.succeed("\u914D\u7F6E\u6587\u4EF6\u521D\u59CB\u5316\u6210\u529F");let o=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),s=`xiaozhi.config.${r}`,a=Ls.join(o,s);console.log(R.green(`\u2705 \u914D\u7F6E\u6587\u4EF6\u5DF2\u521B\u5EFA: ${s}`)),console.log(R.yellow("\u{1F4DD} \u8BF7\u7F16\u8F91\u914D\u7F6E\u6587\u4EF6\u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9:")),console.log(R.gray(` \u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84: ${a}`)),console.log(R.yellow("\u{1F4A1} \u6216\u8005\u4F7F\u7528\u547D\u4EE4\u8BBE\u7F6E:")),console.log(R.gray(" xiaozhi config set mcpEndpoint <your-endpoint-url>"))}catch(r){t.fail(`\u521D\u59CB\u5316\u914D\u7F6E\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleGet(e){let t=Ar("\u8BFB\u53D6\u914D\u7F6E...").start();try{let r=this.getService("configManager");if(!r.configExists()){t.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log(R.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}let n=r.getConfig();switch(e){case"mcpEndpoint":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let o=r.getMcpEndpoints();o.length===0?console.log(R.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):o.length===1?console.log(R.green(`MCP \u7AEF\u70B9: ${o[0]}`)):(console.log(R.green(`MCP \u7AEF\u70B9 (${o.length} \u4E2A):`)),o.forEach((s,a)=>{console.log(R.gray(` ${a+1}. ${s}`))}));break}case"mcpServers":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(R.green("MCP \u670D\u52A1:"));for(let[o,s]of Object.entries(n.mcpServers)){let a=s;"type"in a&&a.type==="sse"?console.log(R.gray(` ${o}: [SSE] ${a.url}`)):console.log(R.gray(` ${o}: ${a.command} ${a.args.join(" ")}`))}break;case"connection":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let o=r.getConnectionConfig();console.log(R.green("\u8FDE\u63A5\u914D\u7F6E:")),console.log(R.gray(` \u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${o.heartbeatInterval}ms`)),console.log(R.gray(` \u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${o.heartbeatTimeout}ms`)),console.log(R.gray(` \u91CD\u8FDE\u95F4\u9694: ${o.reconnectInterval}ms`));break}case"heartbeatInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(R.green(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${r.getHeartbeatInterval()}ms`));break;case"heartbeatTimeout":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(R.green(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${r.getHeartbeatTimeout()}ms`));break;case"reconnectInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(R.green(`\u91CD\u8FDE\u95F4\u9694: ${r.getReconnectInterval()}ms`));break;default:t.fail(`\u672A\u77E5\u7684\u914D\u7F6E\u9879: ${e}`),console.log(R.yellow("\u652F\u6301\u7684\u914D\u7F6E\u9879: mcpEndpoint, mcpServers, connection, heartbeatInterval, heartbeatTimeout, reconnectInterval"))}}catch(r){t.fail(`\u8BFB\u53D6\u914D\u7F6E\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleSet(e,t){let r=Ar("\u66F4\u65B0\u914D\u7F6E...").start();try{let n=this.getService("configManager");if(!n.configExists()){r.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log(R.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}switch(e){case"mcpEndpoint":n.updateMcpEndpoint(t),r.succeed(`MCP \u7AEF\u70B9\u5DF2\u8BBE\u7F6E\u4E3A: ${t}`);break;case"heartbeatInterval":{let o=Number.parseInt(t);if(Number.isNaN(o)||o<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u662F\u6B63\u6574\u6570");n.updateHeartbeatInterval(o),r.succeed(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5DF2\u8BBE\u7F6E\u4E3A: ${o}ms`);break}case"heartbeatTimeout":{let o=Number.parseInt(t);if(Number.isNaN(o)||o<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u662F\u6B63\u6574\u6570");n.updateHeartbeatTimeout(o),r.succeed(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5DF2\u8BBE\u7F6E\u4E3A: ${o}ms`);break}case"reconnectInterval":{let o=Number.parseInt(t);if(Number.isNaN(o)||o<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u662F\u6B63\u6574\u6570");n.updateReconnectInterval(o),r.succeed(`\u91CD\u8FDE\u95F4\u9694\u5DF2\u8BBE\u7F6E\u4E3A: ${o}ms`);break}default:r.fail(`\u4E0D\u652F\u6301\u8BBE\u7F6E\u7684\u914D\u7F6E\u9879: ${e}`),console.log(R.yellow("\u652F\u6301\u8BBE\u7F6E\u7684\u914D\u7F6E\u9879: mcpEndpoint, heartbeatInterval, heartbeatTimeout, reconnectInterval"))}}catch(n){r.fail(`\u8BBE\u7F6E\u914D\u7F6E\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`),this.handleError(n)}}}});var ro={};G(ro,{ProjectCommandHandler:()=>Dr});import js from"path";import N from"chalk";import Hs from"ora";var Dr,no=m(()=>{"use strict";Re();Dr=class extends V{static{c(this,"ProjectCommandHandler")}name="create";description="\u521B\u5EFA\u9879\u76EE";options=[{flags:"-t, --template <templateName>",description:"\u4F7F\u7528\u6307\u5B9A\u6A21\u677F\u521B\u5EFA\u9879\u76EE"}];constructor(e){super(e)}async execute(e,t){this.validateArgs(e,1);let r=e[0];await this.handleCreate(r,t)}async handleCreate(e,t){let r=Hs("\u521D\u59CB\u5316\u9879\u76EE...").start();try{let n=this.getService("templateManager"),o=this.getService("fileUtils"),s=js.join(process.cwd(),e);if(await o.exists(s)){r.fail(`\u76EE\u5F55 "${e}" \u5DF2\u5B58\u5728`),console.log(N.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u9009\u62E9\u4E0D\u540C\u7684\u9879\u76EE\u540D\u79F0\u6216\u5220\u9664\u73B0\u6709\u76EE\u5F55"));return}t.template?await this.createFromTemplate(e,t.template,s,r,n):await this.createBasicProject(e,s,r,n)}catch(n){r.fail(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`),this.handleError(n)}}async createFromTemplate(e,t,r,n,o){n.text="\u68C0\u67E5\u6A21\u677F...";let s=await o.getAvailableTemplates();if(s.length===0){n.fail("\u627E\u4E0D\u5230\u53EF\u7528\u6A21\u677F"),console.log(N.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u786E\u4FDD xiaozhi-client \u6B63\u786E\u5B89\u88C5"));return}let a=t;if(!await o.validateTemplate(a)){n.fail(`\u6A21\u677F "${a}" \u4E0D\u5B58\u5728`);let g=this.findSimilarTemplate(a,s);if(g)if(console.log(N.yellow(`\u{1F4A1} \u4F60\u662F\u60F3\u4F7F\u7528\u6A21\u677F "${g}" \u5417\uFF1F`)),await this.askUserConfirmation(N.cyan("\u786E\u8BA4\u4F7F\u7528\u6B64\u6A21\u677F\uFF1F(y/n): ")))a=g;else{this.showAvailableTemplates(s);return}else{this.showAvailableTemplates(s);return}}n.text=`\u4ECE\u6A21\u677F "${a}" \u521B\u5EFA\u9879\u76EE "${e}"...`,await o.createProject({templateName:a,targetPath:r,projectName:e}),n.succeed(`\u9879\u76EE "${e}" \u521B\u5EFA\u6210\u529F`),console.log(N.green("\u2705 \u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(N.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(N.gray(` cd ${e}`)),console.log(N.gray(" pnpm install # \u5B89\u88C5\u4F9D\u8D56")),console.log(N.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9")),console.log(N.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1"))}async createBasicProject(e,t,r,n){r.text=`\u521B\u5EFA\u57FA\u672C\u9879\u76EE "${e}"...`,await n.createProject({templateName:null,targetPath:t,projectName:e}),r.succeed(`\u9879\u76EE "${e}" \u521B\u5EFA\u6210\u529F`),console.log(N.green("\u2705 \u57FA\u672C\u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(N.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(N.gray(` cd ${e}`)),console.log(N.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9\u548C\u670D\u52A1")),console.log(N.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1")),console.log(N.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 --template \u9009\u9879\u53EF\u4EE5\u4ECE\u6A21\u677F\u521B\u5EFA\u9879\u76EE"))}showAvailableTemplates(e){console.log(N.yellow("\u53EF\u7528\u7684\u6A21\u677F:"));for(let t of e)console.log(N.gray(` - ${t}`))}findSimilarTemplate(e,t){let r=this.getService("formatUtils"),n=null,o=0;for(let s of t){let a=r.calculateSimilarity(e.toLowerCase(),s.toLowerCase());a>o&&a>.6&&(o=a,n=s)}return n}async askUserConfirmation(e){let r=(await import("readline")).createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{r.question(e,o=>{r.close(),n(o.toLowerCase().trim()==="y"||o.toLowerCase().trim()==="yes")})})}}});var qt,oo=m(()=>{"use strict";y();pr();q();qt=class{static{c(this,"ToolCallService")}logger;processManager;baseUrl;constructor(){this.logger=p.withTag("ToolCallService"),this.processManager=new Qe;try{let e=h.getWebUIPort()??9999;this.baseUrl=`http://localhost:${e}`}catch{this.baseUrl="http://localhost:9999"}}async callTool(e,t,r){await this.validateServiceStatus();try{let n=await fetch(`${this.baseUrl}/api/tools/call`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceName:e,toolName:t,args:r})});if(!n.ok){let s=await n.json();throw new Error(s.error?.message||`HTTP ${n.status}: ${n.statusText}`)}let o=await n.json();if(!o.success)throw new Error(o.error?.message||"\u5DE5\u5177\u8C03\u7528\u5931\u8D25");return o.data}catch(n){throw this.logger.error(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e}/${t}`,n instanceof Error?n.message:String(n)),n}}parseJsonArgs(e){try{return JSON.parse(e)}catch(t){throw new Error(`\u53C2\u6570\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u4F7F\u7528\u6709\u6548\u7684 JSON \u683C\u5F0F\u3002\u9519\u8BEF\u8BE6\u60C5: ${t instanceof Error?t.message:String(t)}`)}}async validateServiceStatus(){if(!this.processManager.getServiceStatus().running)throw new Error("xiaozhi \u670D\u52A1\u672A\u542F\u52A8\u3002\u8BF7\u5148\u8FD0\u884C 'xiaozhi start' \u6216 'xiaozhi start -d' \u542F\u52A8\u670D\u52A1\u3002");try{let t=await fetch(`${this.baseUrl}/api/status`,{method:"GET",signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Web \u670D\u52A1\u5668\u54CD\u5E94\u9519\u8BEF: ${t.status}`)}catch(t){throw t instanceof Error&&t.name==="AbortError"?new Error("\u8FDE\u63A5 xiaozhi \u670D\u52A1\u8D85\u65F6\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u662F\u5426\u6B63\u5E38\u8FD0\u884C\u3002"):new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230 xiaozhi \u670D\u52A1\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002\u9519\u8BEF\u8BE6\u60C5: ${t instanceof Error?t.message:String(t)}`)}}formatOutput(e){return JSON.stringify(e)}async getServiceStatus(){try{let e=this.processManager.getServiceStatus();if(!e.running)return"\u670D\u52A1\u672A\u542F\u52A8";try{let t=await fetch(`${this.baseUrl}/api/tools/list`,{method:"GET",signal:AbortSignal.timeout(3e3)});if(t.ok){let r=await t.json();if(r.success)return`\u670D\u52A1\u5DF2\u542F\u52A8 (PID: ${e.pid}, ${r.data.totalTools} \u4E2A\u5DE5\u5177\u53EF\u7528)`}return`\u670D\u52A1\u8FDB\u7A0B\u8FD0\u884C\u4E2D (PID: ${e.pid})\uFF0C\u4F46 MCP \u670D\u52A1\u53EF\u80FD\u672A\u5B8C\u5168\u521D\u59CB\u5316`}catch{return`\u670D\u52A1\u8FDB\u7A0B\u8FD0\u884C\u4E2D (PID: ${e.pid})\uFF0C\u4F46\u65E0\u6CD5\u8FDE\u63A5\u5230 Web API`}}catch(e){return`\u670D\u52A1\u72B6\u6001\u68C0\u67E5\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`}}}});var Xt={};G(Xt,{getDisplayWidth:()=>_r,listMcpServers:()=>zs,listServerTools:()=>Us,setToolEnabled:()=>Fs,truncateToWidth:()=>Jt});import f from"chalk";import so from"cli-table3";import kr from"ora";function _r(i){let e=0;for(let t of i)/[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef]/.test(t)?e+=2:e+=1;return e}function Jt(i,e){if(_r(i)<=e)return i;if(e<=3)return"";let t="",r=0,n=!1;for(let o of i){let s=/[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef]/.test(o)?2:1;if(r+s>e-3){if(!n)return"";t+="...";break}t+=o,r+=s,n=!0}return t}async function zs(i={}){let e=kr("\u83B7\u53D6 MCP \u670D\u52A1\u5217\u8868...").start();try{let t=h.getMcpServers(),r=Object.keys(t),n=h.getCustomMCPTools(),o=n.length>0,s=r.length+(o?1:0);if(s===0){e.warn("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u670D\u52A1\u6216 customMCP \u5DE5\u5177"),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi config' \u547D\u4EE4\u914D\u7F6E MCP \u670D\u52A1\u6216\u5728 xiaozhi.config.json \u4E2D\u914D\u7F6E customMCP \u5DE5\u5177"));return}if(e.succeed(`\u627E\u5230 ${s} \u4E2A MCP \u670D\u52A1${o?" (\u5305\u62EC customMCP)":""}`),i.tools){console.log(),console.log(f.bold("MCP \u670D\u52A1\u5DE5\u5177\u5217\u8868:")),console.log();let a=8,l=[];for(let u of r){let d=h.getServerToolsConfig(u),v=Object.keys(d);l.push(...v)}if(o){let u=n.map(d=>d.name);l.push(...u)}for(let u of l){let d=_r(u);d>a&&(a=d)}a=Math.max(10,Math.min(a+2,30));let g=new so({head:[f.bold("MCP"),f.bold("\u5DE5\u5177\u540D\u79F0"),f.bold("\u72B6\u6001"),f.bold("\u63CF\u8FF0")],colWidths:[15,a,8,40],wordWrap:!0,style:{head:[],border:[]}});if(o)for(let u of n){let d=Jt(u.description||"",32);g.push(["customMCP",u.name,f.green("\u542F\u7528"),d])}for(let u of r){let d=h.getServerToolsConfig(u),v=Object.keys(d);if(v.length===0)g.push([f.gray(u),f.gray("-"),f.gray("-"),f.gray("\u6682\u672A\u8BC6\u522B\u5230\u76F8\u5173\u5DE5\u5177")]);else{g.length>0&&g.push([{colSpan:4,content:""}]);for(let T of v){let I=d[T],K=I.enable?f.green("\u542F\u7528"):f.red("\u7981\u7528"),B=Jt(I.description||"",32);g.push([u,T,K,B])}}}console.log(g.toString())}else{console.log(),console.log(f.bold("MCP \u670D\u52A1\u5217\u8868:")),console.log(),o&&(console.log(`${f.cyan("\u2022")} ${f.bold("customMCP")}`),console.log(` \u7C7B\u578B: ${f.gray("\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177")}`),console.log(` \u914D\u7F6E: ${f.gray("xiaozhi.config.json")}`),console.log(` \u5DE5\u5177: ${f.green(n.length)} \u542F\u7528 / ${f.yellow(n.length)} \u603B\u8BA1`),console.log());for(let a of r){let l=t[a],g=h.getServerToolsConfig(a),u=Object.keys(g).length,d=Object.values(g).filter(v=>v.enable!==!1).length;console.log(`${f.cyan("\u2022")} ${f.bold(a)}`),"url"in l?("type"in l&&l.type==="sse"?console.log(` \u7C7B\u578B: ${f.gray("SSE")}`):console.log(` \u7C7B\u578B: ${f.gray("Streamable HTTP")}`),console.log(` URL: ${f.gray(l.url)}`)):console.log(` \u547D\u4EE4: ${f.gray(l.command)} ${f.gray(l.args.join(" "))}`),u>0?console.log(` \u5DE5\u5177: ${f.green(d)} \u542F\u7528 / ${f.yellow(u)} \u603B\u8BA1`):console.log(` \u5DE5\u5177: ${f.gray("\u672A\u626B\u63CF (\u8BF7\u5148\u542F\u52A8\u670D\u52A1)")}`),console.log()}}console.log(f.gray("\u{1F4A1} \u63D0\u793A:")),console.log(f.gray(" - \u4F7F\u7528 'xiaozhi mcp list --tools' \u67E5\u770B\u6240\u6709\u5DE5\u5177")),console.log(f.gray(" - \u4F7F\u7528 'xiaozhi mcp <\u670D\u52A1\u540D> list' \u67E5\u770B\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177")),console.log(f.gray(" - \u4F7F\u7528 'xiaozhi mcp <\u670D\u52A1\u540D> <\u5DE5\u5177\u540D> enable/disable' \u542F\u7528/\u7981\u7528\u5DE5\u5177"))}catch(t){e.fail("\u83B7\u53D6 MCP \u670D\u52A1\u5217\u8868\u5931\u8D25"),console.error(f.red(`\u9519\u8BEF: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function Us(i){let e=kr(`\u83B7\u53D6 ${i} \u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868...`).start();try{if(!h.getMcpServers()[i]){e.fail(`\u670D\u52A1 '${i}' \u4E0D\u5B58\u5728`),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u670D\u52A1"));return}let r=h.getServerToolsConfig(i),n=Object.keys(r);if(n.length===0){e.warn(`\u670D\u52A1 '${i}' \u6682\u65E0\u5DE5\u5177\u4FE1\u606F`),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u542F\u52A8\u670D\u52A1\u4EE5\u626B\u63CF\u5DE5\u5177\u5217\u8868"));return}e.succeed(`\u670D\u52A1 '${i}' \u5171\u6709 ${n.length} \u4E2A\u5DE5\u5177`),console.log(),console.log(f.bold(`${i} \u670D\u52A1\u5DE5\u5177\u5217\u8868:`)),console.log();let o=new so({head:[f.bold("\u5DE5\u5177\u540D\u79F0"),f.bold("\u72B6\u6001"),f.bold("\u63CF\u8FF0")],colWidths:[30,8,50],wordWrap:!0,style:{head:[],border:[]}});for(let s of n){let a=r[s],l=a.enable?f.green("\u542F\u7528"):f.red("\u7981\u7528"),g=Jt(a.description||"",40);o.push([s,l,g])}console.log(o.toString()),console.log(),console.log(f.gray("\u{1F4A1} \u63D0\u793A:")),console.log(f.gray(` - \u4F7F\u7528 'xiaozhi mcp ${i} <\u5DE5\u5177\u540D> enable' \u542F\u7528\u5DE5\u5177`)),console.log(f.gray(` - \u4F7F\u7528 'xiaozhi mcp ${i} <\u5DE5\u5177\u540D> disable' \u7981\u7528\u5DE5\u5177`))}catch(t){e.fail("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25"),console.error(f.red(`\u9519\u8BEF: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function Fs(i,e,t){let r=t?"\u542F\u7528":"\u7981\u7528",n=kr(`${r}\u5DE5\u5177 ${i}/${e}...`).start();try{if(!h.getMcpServers()[i]){n.fail(`\u670D\u52A1 '${i}' \u4E0D\u5B58\u5728`),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u670D\u52A1"));return}let s=h.getServerToolsConfig(i);if(!s[e]){n.fail(`\u5DE5\u5177 '${e}' \u5728\u670D\u52A1 '${i}' \u4E2D\u4E0D\u5B58\u5728`),console.log(f.yellow(`\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp ${i} list' \u67E5\u770B\u8BE5\u670D\u52A1\u7684\u6240\u6709\u5DE5\u5177`));return}h.setToolEnabled(i,e,t,s[e].description),n.succeed(`\u6210\u529F${r}\u5DE5\u5177 ${f.cyan(i)}/${f.cyan(e)}`),console.log(),console.log(f.gray("\u{1F4A1} \u63D0\u793A: \u5DE5\u5177\u72B6\u6001\u66F4\u6539\u5C06\u5728\u4E0B\u6B21\u542F\u52A8\u670D\u52A1\u65F6\u751F\u6548"))}catch(o){n.fail(`${r}\u5DE5\u5177\u5931\u8D25`),console.error(f.red(`\u9519\u8BEF: ${o instanceof Error?o.message:String(o)}`)),process.exit(1)}}var Kt=m(()=>{"use strict";q();c(_r,"getDisplayWidth");c(Jt,"truncateToWidth");c(zs,"listMcpServers");c(Us,"listServerTools");c(Fs,"setToolEnabled")});var io={};G(io,{McpCommandHandler:()=>Lr});import Ie from"chalk";var Lr,ao=m(()=>{"use strict";oo();Re();Lr=class extends V{static{c(this,"McpCommandHandler")}name="mcp";description="MCP \u670D\u52A1\u548C\u5DE5\u5177\u7BA1\u7406";subcommands=[{name:"list",description:"\u5217\u51FA MCP \u670D\u52A1",options:[{flags:"--tools",description:"\u663E\u793A\u6240\u6709\u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868"}],execute:c(async(e,t)=>{await this.handleList(t)},"execute")},{name:"server",description:"\u7BA1\u7406\u6307\u5B9A\u7684 MCP \u670D\u52A1",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleServer(e[0])},"execute")},{name:"tool",description:"\u542F\u7528\u6216\u7981\u7528\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177",execute:c(async(e,t)=>{this.validateArgs(e,3);let[r,n,o]=e;o!=="enable"&&o!=="disable"&&(console.error(Ie.red("\u9519\u8BEF: \u64CD\u4F5C\u5FC5\u987B\u662F 'enable' \u6216 'disable'")),process.exit(1));let s=o==="enable";await this.handleTool(r,n,s)},"execute")},{name:"call",description:"\u8C03\u7528\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177",options:[{flags:"--args <json>",description:"\u5DE5\u5177\u53C2\u6570 (JSON \u683C\u5F0F)",defaultValue:"{}"}],execute:c(async(e,t)=>{this.validateArgs(e,2);let[r,n]=e;await this.handleCall(r,n,t.args)},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("MCP \u670D\u52A1\u548C\u5DE5\u5177\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleList(e){try{let{listMcpServers:t}=await Promise.resolve().then(()=>(Kt(),Xt));await t(e)}catch(t){this.handleError(t)}}async handleServer(e){try{let{listServerTools:t}=await Promise.resolve().then(()=>(Kt(),Xt));await t(e)}catch(t){this.handleError(t)}}async handleTool(e,t,r){try{let{setToolEnabled:n}=await Promise.resolve().then(()=>(Kt(),Xt));await n(e,t,r)}catch(n){this.handleError(n)}}async handleCall(e,t,r){try{let n=new qt,o=n.parseJsonArgs(r),s=await n.callTool(e,t,o);console.log(n.formatOutput(s))}catch(n){console.log(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e}/${t}`),console.error(Ie.red("\u9519\u8BEF:"),n.message),n.message.includes("\u670D\u52A1\u672A\u542F\u52A8")?(console.log(),console.log(Ie.yellow("\u{1F4A1} \u8BF7\u5148\u542F\u52A8\u670D\u52A1:")),console.log(Ie.gray(" xiaozhi start # \u524D\u53F0\u542F\u52A8")),console.log(Ie.gray(" xiaozhi start -d # \u540E\u53F0\u542F\u52A8"))):n.message.includes("\u53C2\u6570\u683C\u5F0F\u9519\u8BEF")&&(console.log(),console.log(Ie.yellow("\u{1F4A1} \u6B63\u786E\u683C\u5F0F\u793A\u4F8B:")),console.log(Ie.gray(` xiaozhi mcp call ${e} ${t} --args '{"param": "value"}'`))),process.exit(1)}}}});var co={};G(co,{EndpointCommandHandler:()=>jr});import Be from"chalk";import Zt from"ora";var jr,lo=m(()=>{"use strict";Re();jr=class extends V{static{c(this,"EndpointCommandHandler")}name="endpoint";description="\u7BA1\u7406 MCP \u7AEF\u70B9";subcommands=[{name:"list",description:"\u5217\u51FA\u6240\u6709 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{await this.handleList()},"execute")},{name:"add",description:"\u6DFB\u52A0\u65B0\u7684 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleAdd(e[0])},"execute")},{name:"remove",description:"\u79FB\u9664\u6307\u5B9A\u7684 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleRemove(e[0])},"execute")},{name:"set",description:"\u8BBE\u7F6E MCP \u7AEF\u70B9\uFF08\u53EF\u4EE5\u662F\u5355\u4E2A\u6216\u591A\u4E2A\uFF09",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleSet(e)},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("MCP \u7AEF\u70B9\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleList(){let e=Zt("\u8BFB\u53D6\u7AEF\u70B9\u914D\u7F6E...").start();try{let r=this.getService("configManager").getMcpEndpoints();e.succeed("\u7AEF\u70B9\u5217\u8868"),r.length===0?console.log(Be.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):(console.log(Be.green(`\u5171 ${r.length} \u4E2A\u7AEF\u70B9:`)),r.forEach((n,o)=>{console.log(Be.gray(` ${o+1}. ${n}`))}))}catch(t){e.fail(`\u8BFB\u53D6\u7AEF\u70B9\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),this.handleError(t)}}async handleAdd(e){let t=Zt("\u6DFB\u52A0\u7AEF\u70B9...").start();try{let r=this.getService("configManager");r.addMcpEndpoint(e),t.succeed(`\u6210\u529F\u6DFB\u52A0\u7AEF\u70B9: ${e}`);let n=r.getMcpEndpoints();console.log(Be.gray(`\u5F53\u524D\u5171 ${n.length} \u4E2A\u7AEF\u70B9`))}catch(r){t.fail(`\u6DFB\u52A0\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleRemove(e){let t=Zt("\u79FB\u9664\u7AEF\u70B9...").start();try{let r=this.getService("configManager");r.removeMcpEndpoint(e),t.succeed(`\u6210\u529F\u79FB\u9664\u7AEF\u70B9: ${e}`);let n=r.getMcpEndpoints();console.log(Be.gray(`\u5F53\u524D\u5269\u4F59 ${n.length} \u4E2A\u7AEF\u70B9`))}catch(r){t.fail(`\u79FB\u9664\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleSet(e){let t=Zt("\u8BBE\u7F6E\u7AEF\u70B9...").start();try{let r=this.getService("configManager");if(e.length===1)r.updateMcpEndpoint(e[0]),t.succeed(`\u6210\u529F\u8BBE\u7F6E\u7AEF\u70B9: ${e[0]}`);else{r.updateMcpEndpoint(e),t.succeed(`\u6210\u529F\u8BBE\u7F6E ${e.length} \u4E2A\u7AEF\u70B9`);for(let[n,o]of e.entries())console.log(Be.gray(` ${n+1}. ${o}`))}}catch(r){t.fail(`\u8BBE\u7F6E\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}}});var go={};G(go,{UICommandHandler:()=>Hr});import $e from"chalk";import Ws from"ora";var Hr,po=m(()=>{"use strict";Re();Hr=class extends V{static{c(this,"UICommandHandler")}name="ui";description="\u542F\u52A8\u914D\u7F6E\u7BA1\u7406\u7F51\u9875";constructor(e){super(e)}async execute(e,t){await this.handleUI()}async handleUI(){let e=Ws("\u542F\u52A8 UI \u670D\u52A1...").start();try{let t=this.getService("configManager");if(!t.configExists()){e.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log($e.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}let{WebServer:r}=await Promise.resolve().then(()=>(Rr(),br));await new r().start(),e.succeed("UI \u670D\u52A1\u5DF2\u542F\u52A8");let o=t.getWebUIPort();console.log($e.green("\u2705 \u914D\u7F6E\u7BA1\u7406\u7F51\u9875\u5DF2\u542F\u52A8\uFF0C\u53EF\u901A\u8FC7\u4EE5\u4E0B\u5730\u5740\u8BBF\u95EE:")),console.log($e.green(` \u672C\u5730\u8BBF\u95EE: http://localhost:${o}`)),console.log($e.green(` \u7F51\u7EDC\u8BBF\u95EE: http://<\u4F60\u7684IP\u5730\u5740>:${o}`)),console.log($e.yellow("\u{1F4A1} \u63D0\u793A: \u6309 Ctrl+C \u505C\u6B62\u670D\u52A1")),await this.openBrowser(`http://localhost:${o}`)}catch(t){e.fail(`\u542F\u52A8 UI \u670D\u52A1\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),this.handleError(t)}}async openBrowser(e){try{let{spawn:t}=await import("child_process"),r;process.platform==="darwin"?r=t("open",[e],{detached:!0,stdio:"ignore"}):process.platform==="win32"?r=t("cmd",["/c","start",e],{detached:!0,stdio:"ignore"}):r=t("xdg-open",[e],{detached:!0,stdio:"ignore"}),r.on("error",()=>{console.log($e.gray(`\u{1F4A1} \u63D0\u793A: \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE: ${e}`))}),r.unref()}catch{console.log($e.gray(`\u{1F4A1} \u63D0\u793A: \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE: ${e}`))}}}});Pr();import me from"chalk";import{Command as Vs}from"commander";cr();var Yt=class{constructor(e){this.container=e}static{c(this,"CommandHandlerFactory")}createHandlers(){return[this.createHandler("service"),this.createHandler("config"),this.createHandler("project"),this.createHandler("mcp"),this.createHandler("endpoint"),this.createHandler("ui")]}createHandler(e){switch(e){case"service":return this.createServiceCommandHandler();case"config":return this.createConfigCommandHandler();case"project":return this.createProjectCommandHandler();case"mcp":return this.createMcpCommandHandler();case"endpoint":return this.createEndpointCommandHandler();case"ui":return this.createUICommandHandler();default:throw new Error(`\u672A\u77E5\u7684\u547D\u4EE4\u5904\u7406\u5668\u7C7B\u578B: ${e}`)}}createServiceCommandHandler(){let{ServiceCommandHandler:e}=(Qn(),ne(Yn));return new e(this.container)}createConfigCommandHandler(){let{ConfigCommandHandler:e}=(to(),ne(eo));return new e(this.container)}createProjectCommandHandler(){let{ProjectCommandHandler:e}=(no(),ne(ro));return new e(this.container)}createMcpCommandHandler(){let{McpCommandHandler:e}=(ao(),ne(io));return new e(this.container)}createEndpointCommandHandler(){let{EndpointCommandHandler:e}=(lo(),ne(co));return new e(this.container)}createUICommandHandler(){let{UICommandHandler:e}=(po(),ne(go));return new e(this.container)}};var Qt=class{constructor(e){this.container=e;this.handlerFactory=new Yt(e)}static{c(this,"CommandRegistry")}handlers=[];handlerFactory;async registerCommands(e){try{this.registerVersionCommand(e),this.registerHelpCommand(e);let t=this.handlerFactory.createHandlers();for(let r of t)this.registerHandler(r),this.registerCommand(e,r);this.registerLegacyServiceCommands(e,t)}catch(t){se.handle(t)}}registerHandler(e){this.handlers.push(e)}registerCommand(e,t){if(t.subcommands&&t.subcommands.length>0){let r=e.command(t.name).description(t.description);for(let n of t.subcommands){let o=n.name;n.name==="get"?o="get <key>":n.name==="set"?o="set <key> <value>":n.name==="call"&&(o="call <serviceName> <toolName>");let s=r.command(o).description(n.description);if(n.options)for(let a of n.options)s.option(a.flags,a.description,a.defaultValue);s.action(async(...a)=>{try{let g=a[a.length-1].opts();await n.execute(a.slice(0,-1),g)}catch(l){se.handle(l)}})}r.action(async(...n)=>{try{let s=n[n.length-1].opts();await t.execute(n.slice(0,-1),s)}catch(o){se.handle(o)}})}else{let r=t.name;t.name==="create"&&(r="create <projectName>");let n=e.command(r).description(t.description);if(t.options)for(let o of t.options)n.option(o.flags,o.description,o.defaultValue);n.action(async(...o)=>{try{let a=o[o.length-1].opts();await t.execute(o.slice(0,-1),a)}catch(s){se.handle(s)}})}}registerVersionCommand(e){let t=this.container.get("versionUtils");e.version(t.getVersion(),"-v, --version","\u663E\u793A\u7248\u672C\u4FE1\u606F"),e.option("--info","\u663E\u793A\u8BE6\u7EC6\u4FE1\u606F"),e.option("--version-info","\u663E\u793A\u8BE6\u7EC6\u7248\u672C\u4FE1\u606F")}registerHelpCommand(e){e.helpOption("-h, --help","\u663E\u793A\u5E2E\u52A9\u4FE1\u606F").addHelpText("after",`
97
97
  \u793A\u4F8B:
98
98
  xiaozhi init # \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6
99
99
  xiaozhi start # \u542F\u52A8\u670D\u52A1
@@ -108,7 +108,7 @@ data: ${r}
108
108
  xiaozhi mcp list # \u5217\u51FA MCP \u670D\u52A1
109
109
 
110
110
  \u66F4\u591A\u4FE1\u606F\u8BF7\u8BBF\u95EE: https://github.com/your-org/xiaozhi-client
111
- `)}registerLegacyServiceCommands(e,t){let r=t.find(o=>o.name==="service");if(!(!r||!r.subcommands))for(let o of r.subcommands){let n=e.command(o.name).description(o.description);if(o.options)for(let s of o.options)n.option(s.flags,s.description,s.defaultValue);n.action(async(...s)=>{try{let l=s[s.length-1].opts();await o.execute(s.slice(0,-1),l)}catch(a){se.handle(a)}})}}};var Qt=new Fs;function Ws(){console.log(de.blue("\u{1F916} \u5C0F\u667A MCP \u5BA2\u6237\u7AEF")),console.log(),console.log("\u4E00\u4E2A\u5F3A\u5927\u7684 MCP (Model Context Protocol) \u5BA2\u6237\u7AEF\uFF0C\u652F\u6301\u591A\u79CD\u8FDE\u63A5\u65B9\u5F0F\u548C\u670D\u52A1\u7BA1\u7406\u3002"),console.log(),console.log(de.yellow("\u4E3B\u8981\u529F\u80FD:")),console.log(" \u2022 \u652F\u6301 WebSocket \u548C HTTP \u8FDE\u63A5"),console.log(" \u2022 \u591A MCP \u670D\u52A1\u7BA1\u7406"),console.log(" \u2022 \u5DE5\u5177\u8C03\u7528\u548C\u8D44\u6E90\u8BBF\u95EE"),console.log(" \u2022 \u914D\u7F6E\u7BA1\u7406\u548C\u6A21\u677F\u521B\u5EFA"),console.log(" \u2022 \u540E\u53F0\u670D\u52A1\u548C Web UI"),console.log(),console.log(de.yellow("\u5FEB\u901F\u5F00\u59CB:")),console.log(" xiaozhi config init # \u521D\u59CB\u5316\u914D\u7F6E"),console.log(" xiaozhi start # \u542F\u52A8\u670D\u52A1"),console.log(" xiaozhi ui # \u542F\u52A8 Web UI"),console.log(),console.log("\u4F7F\u7528 'xiaozhi --help' \u67E5\u770B\u6240\u6709\u53EF\u7528\u547D\u4EE4")}c(Ws,"showHelp");function Vs(i){let e=i.get("versionUtils"),t=i.get("platformUtils"),r=e.getVersionInfo(),o=t.getSystemInfo();console.log(de.blue("\u{1F916} \u5C0F\u667A MCP \u5BA2\u6237\u7AEF - \u8BE6\u7EC6\u4FE1\u606F")),console.log(),console.log(de.green("\u7248\u672C\u4FE1\u606F:")),console.log(` \u540D\u79F0: ${r.name||"xiaozhi"}`),console.log(` \u7248\u672C: ${r.version}`),r.description&&console.log(` \u63CF\u8FF0: ${r.description}`),console.log(),console.log(de.green("\u7CFB\u7EDF\u4FE1\u606F:")),console.log(` Node.js: ${o.nodeVersion}`),console.log(` \u5E73\u53F0: ${o.platform} ${o.arch}`),o.isContainer&&console.log(" \u73AF\u5883: Container"),console.log(),console.log(de.green("\u914D\u7F6E\u4FE1\u606F:"));let n=i.get("configManager");if(n.configExists()){let s=n.getConfigPath();console.log(` \u914D\u7F6E\u6587\u4EF6: ${s}`);try{let a=n.getMcpEndpoints();console.log(` MCP \u7AEF\u70B9: ${a.length} \u4E2A`)}catch{console.log(" MCP \u7AEF\u70B9: \u8BFB\u53D6\u5931\u8D25")}}else console.log(" \u914D\u7F6E\u6587\u4EF6: \u672A\u521D\u59CB\u5316")}c(Vs,"showDetailedInfo");async function Bs(){try{if(process.argv.includes("--info")){let t=await Pe();Vs(t),process.exit(0)}if(process.argv.includes("--version-info")){let t=await Pe(),r=t.get("versionUtils"),o=t.get("platformUtils"),n=r.getVersionInfo(),s=o.getSystemInfo();console.log(`${n.name||"xiaozhi"} v${n.version}`),n.description&&console.log(n.description),console.log(`Node.js: ${s.nodeVersion}`),console.log(`Platform: ${s.platform} ${s.arch}`),s.isContainer&&console.log("Environment: Container"),process.exit(0)}let i=await Pe(),e=new Yt(i);Qt.name("xiaozhi").description("\u5C0F\u667A MCP \u5BA2\u6237\u7AEF - \u5F3A\u5927\u7684 Model Context Protocol \u5BA2\u6237\u7AEF"),await e.registerCommands(Qt),Qt.helpOption("-h, --help","\u663E\u793A\u5E2E\u52A9\u4FE1\u606F").addHelpText("after",`
111
+ `)}registerLegacyServiceCommands(e,t){let r=t.find(n=>n.name==="service");if(!(!r||!r.subcommands))for(let n of r.subcommands){let o=e.command(n.name).description(n.description);if(n.options)for(let s of n.options)o.option(s.flags,s.description,s.defaultValue);o.action(async(...s)=>{try{let l=s[s.length-1].opts();await n.execute(s.slice(0,-1),l)}catch(a){se.handle(a)}})}}};var er=new Vs;function Bs(){console.log(me.blue("\u{1F916} \u5C0F\u667A MCP \u5BA2\u6237\u7AEF")),console.log(),console.log("\u4E00\u4E2A\u5F3A\u5927\u7684 MCP (Model Context Protocol) \u5BA2\u6237\u7AEF\uFF0C\u652F\u6301\u591A\u79CD\u8FDE\u63A5\u65B9\u5F0F\u548C\u670D\u52A1\u7BA1\u7406\u3002"),console.log(),console.log(me.yellow("\u4E3B\u8981\u529F\u80FD:")),console.log(" \u2022 \u652F\u6301 WebSocket \u548C HTTP \u8FDE\u63A5"),console.log(" \u2022 \u591A MCP \u670D\u52A1\u7BA1\u7406"),console.log(" \u2022 \u5DE5\u5177\u8C03\u7528\u548C\u8D44\u6E90\u8BBF\u95EE"),console.log(" \u2022 \u914D\u7F6E\u7BA1\u7406\u548C\u6A21\u677F\u521B\u5EFA"),console.log(" \u2022 \u540E\u53F0\u670D\u52A1\u548C Web UI"),console.log(),console.log(me.yellow("\u5FEB\u901F\u5F00\u59CB:")),console.log(" xiaozhi config init # \u521D\u59CB\u5316\u914D\u7F6E"),console.log(" xiaozhi start # \u542F\u52A8\u670D\u52A1"),console.log(" xiaozhi ui # \u542F\u52A8 Web UI"),console.log(),console.log("\u4F7F\u7528 'xiaozhi --help' \u67E5\u770B\u6240\u6709\u53EF\u7528\u547D\u4EE4")}c(Bs,"showHelp");function Gs(i){let e=i.get("versionUtils"),t=i.get("platformUtils"),r=e.getVersionInfo(),n=t.getSystemInfo();console.log(me.blue("\u{1F916} \u5C0F\u667A MCP \u5BA2\u6237\u7AEF - \u8BE6\u7EC6\u4FE1\u606F")),console.log(),console.log(me.green("\u7248\u672C\u4FE1\u606F:")),console.log(` \u540D\u79F0: ${r.name||"xiaozhi"}`),console.log(` \u7248\u672C: ${r.version}`),r.description&&console.log(` \u63CF\u8FF0: ${r.description}`),console.log(),console.log(me.green("\u7CFB\u7EDF\u4FE1\u606F:")),console.log(` Node.js: ${n.nodeVersion}`),console.log(` \u5E73\u53F0: ${n.platform} ${n.arch}`),n.isContainer&&console.log(" \u73AF\u5883: Container"),console.log(),console.log(me.green("\u914D\u7F6E\u4FE1\u606F:"));let o=i.get("configManager");if(o.configExists()){let s=o.getConfigPath();console.log(` \u914D\u7F6E\u6587\u4EF6: ${s}`);try{let a=o.getMcpEndpoints();console.log(` MCP \u7AEF\u70B9: ${a.length} \u4E2A`)}catch{console.log(" MCP \u7AEF\u70B9: \u8BFB\u53D6\u5931\u8D25")}}else console.log(" \u914D\u7F6E\u6587\u4EF6: \u672A\u521D\u59CB\u5316")}c(Gs,"showDetailedInfo");async function qs(){try{if(process.argv.includes("--info")){let t=await we();Gs(t),process.exit(0)}if(process.argv.includes("--version-info")){let t=await we(),r=t.get("versionUtils"),n=t.get("platformUtils"),o=r.getVersionInfo(),s=n.getSystemInfo();console.log(`${o.name||"xiaozhi"} v${o.version}`),o.description&&console.log(o.description),console.log(`Node.js: ${s.nodeVersion}`),console.log(`Platform: ${s.platform} ${s.arch}`),s.isContainer&&console.log("Environment: Container"),process.exit(0)}let i=await we(),e=new Qt(i);er.name("xiaozhi").description("\u5C0F\u667A MCP \u5BA2\u6237\u7AEF - \u5F3A\u5927\u7684 Model Context Protocol \u5BA2\u6237\u7AEF"),await e.registerCommands(er),er.helpOption("-h, --help","\u663E\u793A\u5E2E\u52A9\u4FE1\u606F").addHelpText("after",`
112
112
  \u793A\u4F8B:
113
113
  xiaozhi config init # \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6
114
114
  xiaozhi start # \u542F\u52A8\u670D\u52A1
@@ -125,5 +125,5 @@ data: ${r}
125
125
  xiaozhi ui # \u542F\u52A8 Web UI
126
126
 
127
127
  \u66F4\u591A\u4FE1\u606F\u8BF7\u8BBF\u95EE: https://github.com/your-org/xiaozhi-client
128
- `),process.argv.length<=2&&(Ws(),process.exit(0)),await Qt.parseAsync(process.argv)}catch(i){console.error(de.red("\u7A0B\u5E8F\u542F\u52A8\u5931\u8D25:"),i instanceof Error?i.message:String(i)),process.exit(1)}}c(Bs,"main");Bs().catch(i=>{console.error(de.red("\u7A0B\u5E8F\u6267\u884C\u5931\u8D25:"),i instanceof Error?i.message:String(i)),process.exit(1)});
128
+ `),process.argv.length<=2&&(Bs(),process.exit(0)),await er.parseAsync(process.argv)}catch(i){console.error(me.red("\u7A0B\u5E8F\u542F\u52A8\u5931\u8D25:"),i instanceof Error?i.message:String(i)),process.exit(1)}}c(qs,"main");qs().catch(i=>{console.error(me.red("\u7A0B\u5E8F\u6267\u884C\u5931\u8D25:"),i instanceof Error?i.message:String(i)),process.exit(1)});
129
129
  //# sourceMappingURL=cli.js.map