xiaozhi-client 1.7.3 → 1.7.5

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.
Files changed (55) hide show
  1. package/README.md +6 -285
  2. package/dist/WebServerStandalone.js +14 -14
  3. package/dist/WebServerStandalone.js.map +1 -1
  4. package/dist/cli.js +14 -14
  5. package/dist/cli.js.map +1 -1
  6. package/dist/mcpServerProxy.js +11 -11
  7. package/dist/mcpServerProxy.js.map +1 -1
  8. package/dist/package.json +3 -2
  9. package/docs/docs.json +4 -0
  10. package/docs/getting-started/install.mdx +2 -2
  11. package/docs/getting-started/quickstart.mdx +3 -3
  12. package/docs/images/add-to-cherry-studio/step-1.png +0 -0
  13. package/docs/images/add-to-cherry-studio/step-2.png +0 -0
  14. package/docs/images/add-to-cherry-studio/step-3.png +0 -0
  15. package/docs/images/add-to-cherry-studio/step-4.png +0 -0
  16. package/docs/images/add-to-cherry-studio/step-5.png +0 -0
  17. package/docs/images/add-to-cursor/step-1.png +0 -0
  18. package/docs/images/add-to-cursor/step-2.png +0 -0
  19. package/docs/images/add-to-cursor/step-3.png +0 -0
  20. package/docs/images/coze-workflow/config-workflow-step-1.png +0 -0
  21. package/docs/images/coze-workflow/config-workflow-step-2.png +0 -0
  22. package/docs/images/coze-workflow/config-workflow-step-3.png +0 -0
  23. package/docs/images/coze-workflow/get-parameter.png +0 -0
  24. package/docs/images/modelscope/step-1.png +0 -0
  25. package/docs/images/modelscope/step-2.png +0 -0
  26. package/docs/images/modelscope/step-3.png +0 -0
  27. package/docs/images/modelscope/step-4.png +0 -0
  28. package/docs/images/use-multi-xiaozhi-mcp-endpoints/step-1.png +0 -0
  29. package/docs/images/use-multi-xiaozhi-mcp-endpoints/step-2.png +0 -0
  30. package/docs/images/use-multi-xiaozhi-mcp-endpoints/step-3.png +0 -0
  31. package/docs/images/use-multi-xiaozhi-mcp-endpoints/step-4.png +0 -0
  32. package/docs/images/use-multi-xiaozhi-mcp-endpoints/step-5.png +0 -0
  33. package/docs/usage/as-a-mcp-server.mdx +73 -3
  34. package/docs/usage/coze-workflow.mdx +73 -0
  35. package/docs/usage/docker.mdx +6 -6
  36. package/docs/usage/modelscope.mdx +69 -1
  37. package/docs/usage/use-multi-xiaozhi-mcp-endpoints.mdx +77 -0
  38. package/package.json +3 -2
  39. package/web/dist/assets/form-utils-D6Zwv25A.js +24 -0
  40. package/web/dist/assets/form-utils-D6Zwv25A.js.map +1 -0
  41. package/web/dist/assets/index-C9KBrMbo.css +1 -0
  42. package/web/dist/assets/index-D0fujP5T.js +31 -0
  43. package/web/dist/assets/index-D0fujP5T.js.map +1 -0
  44. package/web/dist/assets/react-vendor-SSuibrMc.js +239 -0
  45. package/web/dist/assets/react-vendor-SSuibrMc.js.map +1 -0
  46. package/web/dist/assets/{utils-N_0RTAPv.js → utils-CF9sajHy.js} +2 -2
  47. package/web/dist/assets/{utils-N_0RTAPv.js.map → utils-CF9sajHy.js.map} +1 -1
  48. package/web/dist/index.html +5 -5
  49. package/web/dist/assets/form-utils-RpkiEEz8.js +0 -22
  50. package/web/dist/assets/form-utils-RpkiEEz8.js.map +0 -1
  51. package/web/dist/assets/index-BjG6tl-5.css +0 -1
  52. package/web/dist/assets/index-BvDVeF-B.js +0 -31
  53. package/web/dist/assets/index-BvDVeF-B.js.map +0 -1
  54. package/web/dist/assets/react-vendor-CoesXubw.js +0 -234
  55. package/web/dist/assets/react-vendor-CoesXubw.js.map +0 -1
package/dist/cli.js CHANGED
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- var ot=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var an=Object.getOwnPropertyNames;var cn=Object.prototype.hasOwnProperty;var c=(i,e)=>ot(i,"name",{value:e,configurable:!0});var m=(i,e)=>()=>(i&&(e=i(i=0)),e);var F=(i,e)=>{for(var t in e)ot(i,t,{get:e[t],enumerable:!0})},ln=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of an(e))!cn.call(i,o)&&o!==t&&ot(i,o,{get:()=>e[o],enumerable:!(r=sn(e,o))||r.enumerable});return i};var ee=i=>ln(ot({},"__esModule",{value:!0}),i);import*as N from"fs";import*as q from"path";import Ue from"chalk";import Re from"pino";import{z as gn}from"zod";function un(i){let e=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),r=String(i.getDate()).padStart(2,"0"),o=String(i.getHours()).padStart(2,"0"),n=String(i.getMinutes()).padStart(2,"0"),s=String(i.getSeconds()).padStart(2,"0");return`${e}-${t}-${r} ${o}:${n}:${s}`}function Dr(i="info"){return new Ie(i)}function pn(){return nt||(nt=new Ie("info")),nt}function Nr(i){nt=i}var hn,Ie,nt,g,S=m(()=>{"use strict";hn=gn.enum(["fatal","error","warn","info","debug","trace"]);c(un,"formatDateTime");Ie=class{static{c(this,"Logger")}logFilePath=null;pinoInstance;isDaemonMode;logLevel;maxLogFileSize=10*1024*1024;maxLogFiles=5;constructor(e="info"){this.isDaemonMode=process.env.XIAOZHI_DAEMON==="true",this.logLevel=this.validateLogLevel(e),this.pinoInstance=this.createPinoInstance()}validateLogLevel(e){let t=e.toLowerCase(),r=hn.safeParse(t);return r.success?r.data:"info"}createPinoInstance(){let e=[];if(!this.isDaemonMode){let t=this.createOptimizedConsoleStream();e.push({level:this.logLevel,stream:t})}return this.logFilePath&&e.push({level:this.logLevel,stream:Re.destination({dest:this.logFilePath,sync:!1,append:!0,mkdir:!0})}),e.length===0&&e.push({level:this.logLevel,stream:Re.destination({dest:"/dev/null"})}),Re({level:this.logLevel,timestamp:Re.stdTimeFunctions?.isoTime||(()=>`,"time":${Date.now()}`),formatters:{level:c((t,r)=>({level:r}),"level")},base:null,serializers:{err:Re.stdSerializers?.err||(t=>t)}},Re.multistream(e,{dedupe:!0}))}createOptimizedConsoleStream(){let e=new Map([[20,{name:"DEBUG",color:Ue.gray}],[30,{name:"INFO",color:Ue.blue}],[40,{name:"WARN",color:Ue.yellow}],[50,{name:"ERROR",color:Ue.red}],[60,{name:"FATAL",color:Ue.red}]]);return{write:c(t=>{try{let r=JSON.parse(t),o=this.formatConsoleMessageOptimized(r,e);this.safeWrite(`${o}
3
- `)}catch{this.safeWrite(t)}},"write")}}safeWrite(e){try{process.stderr&&typeof process.stderr.write=="function"?process.stderr.write(e):console&&typeof console.error=="function"&&console.error(e.trim())}catch{}}formatConsoleMessageOptimized(e,t){let r=un(new Date),o=t.get(e.level)||{name:"UNKNOWN",color:c(a=>a,"color")},n=o.color(`[${o.name}]`),s=e.msg;if(e.args&&Array.isArray(e.args)){let a=e.args.map(l=>typeof l=="object"?JSON.stringify(l):String(l)).join(" ");s=`${s} ${a}`}return`[${r}] ${n} ${s}`}initLogFile(e){this.logFilePath=q.join(e,"xiaozhi.log"),this.rotateLogFileIfNeeded(),N.existsSync(this.logFilePath)||N.writeFileSync(this.logFilePath,""),this.pinoInstance=this.createPinoInstance()}enableFileLogging(e){e&&this.logFilePath&&(this.pinoInstance=this.createPinoInstance())}info(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}success(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}warn(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.warn(e):this.pinoInstance.warn({args:t},e):this.pinoInstance.warn(e,t[0]||"")}error(e,...t){if(typeof e=="string")if(t.length===0)this.pinoInstance.error(e);else{let r=t.map(o=>o instanceof Error?{message:o.message,stack:o.stack,name:o.name,cause:o.cause}:o);this.pinoInstance.error({args:r},e)}else{let r=this.enhanceErrorObject(e);this.pinoInstance.error(r,t[0]||"")}}debug(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.debug(e):this.pinoInstance.debug({args:t},e):this.pinoInstance.debug(e,t[0]||"")}log(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}enhanceErrorObject(e){let t={...e};for(let[r,o]of Object.entries(t))o instanceof Error&&(t[r]={message:o.message,stack:o.stack,name:o.name,cause:o.cause});return t}rotateLogFileIfNeeded(){if(!(!this.logFilePath||!N.existsSync(this.logFilePath)))try{N.statSync(this.logFilePath).size>this.maxLogFileSize&&this.rotateLogFile()}catch{}}rotateLogFile(){if(this.logFilePath)try{let e=q.dirname(this.logFilePath),t=q.basename(this.logFilePath,".log");for(let o=this.maxLogFiles-1;o>=1;o--){let n=q.join(e,`${t}.${o}.log`),s=q.join(e,`${t}.${o+1}.log`);N.existsSync(n)&&(o===this.maxLogFiles-1?N.unlinkSync(n):N.renameSync(n,s))}let r=q.join(e,`${t}.1.log`);N.renameSync(this.logFilePath,r)}catch{}}cleanupOldLogs(){if(this.logFilePath)try{let e=q.dirname(this.logFilePath),t=q.basename(this.logFilePath,".log");for(let r=this.maxLogFiles+1;r<=this.maxLogFiles+10;r++){let o=q.join(e,`${t}.${r}.log`);N.existsSync(o)&&N.unlinkSync(o)}}catch{}}setLogFileOptions(e,t){this.maxLogFileSize=e,this.maxLogFiles=t}withTag(e){return this}close(){}},nt=null;c(Dr,"createLogger");c(pn,"getLogger");c(Nr,"setGlobalLogger");g=pn()});function dn(i){if(!i||typeof i!="object")throw new Error("\u670D\u52A1\u914D\u7F6E\u5FC5\u987B\u662F\u4E00\u4E2A\u6709\u6548\u7684\u5BF9\u8C61");if("command"in i&&typeof i.command=="string")return"stdio";if("type"in i&&i.type==="sse")return"sse";if("type"in i&&i.type==="streamable-http"||"url"in i&&typeof i.url=="string")return"streamable-http";throw new Error("\u65E0\u6CD5\u8BC6\u522B\u7684 MCP \u670D\u52A1\u914D\u7F6E\u7C7B\u578B\u3002\u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5\uFF08stdio\uFF09\u3001type: 'sse' \u5B57\u6BB5\uFF08sse\uFF09\u6216 url \u5B57\u6BB5\uFF08streamable-http\uFF09")}function Kt(i,e){if(!e||typeof e!="object")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u5FC5\u987B\u662F\u4E00\u4E2A\u5BF9\u8C61`};try{switch(dn(e)){case"stdio":if(!e.command||typeof e.command!="string")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7F3A\u5C11\u5FC5\u9700\u7684 command \u5B57\u6BB5\u6216\u5B57\u6BB5\u7C7B\u578B\u4E0D\u6B63\u786E`};if(!Array.isArray(e.args))return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4`};if(e.env&&typeof e.env!="object")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61`};break;case"sse":if(e.type!=="sse")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 type \u5B57\u6BB5\u5FC5\u987B\u662F "sse"`};if(!e.url||typeof e.url!="string")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7F3A\u5C11\u5FC5\u9700\u7684 url \u5B57\u6BB5\u6216\u5B57\u6BB5\u7C7B\u578B\u4E0D\u6B63\u786E`};break;case"streamable-http":if(!e.url||typeof e.url!="string")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7F3A\u5C11\u5FC5\u9700\u7684 url \u5B57\u6BB5\u6216\u5B57\u6BB5\u7C7B\u578B\u4E0D\u6B63\u786E`};if(e.type&&e.type!=="streamable-http")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 type \u5B57\u6BB5\u5982\u679C\u5B58\u5728\uFF0C\u5FC5\u987B\u662F "streamable-http"`};break;default:return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u7C7B\u578B\u65E0\u6CD5\u8BC6\u522B`}}return{valid:!0}}catch(t){return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u65E0\u6548: ${t instanceof Error?t.message:"\u672A\u77E5\u9519\u8BEF"}`}}}var _r=m(()=>{"use strict";c(dn,"getMcpServerCommunicationType");c(Kt,"validateMcpServerConfig")});import{copyFileSync as mn,existsSync as st,readFileSync as fn,writeFileSync as Cn}from"fs";import{dirname as vn,resolve as Ce}from"path";import{fileURLToPath as Sn}from"url";import*as it from"comment-json";import Lr from"dayjs";import Zt from"json5";import*as zr from"json5-writer";var Hr,Yt,Qt,d,Y=m(()=>{"use strict";S();_r();Hr=vn(Sn(import.meta.url)),Yt={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},Qt=class i{static{c(this,"ConfigManager")}static instance;defaultConfigPath;config=null;currentConfigPath=null;json5Writer=null;statsUpdateLocks=new Map;statsUpdateLockTimeouts=new Map;STATS_UPDATE_TIMEOUT=5e3;constructor(){let e=[Ce(Hr,"templates","default","xiaozhi.config.json"),Ce(Hr,"..","templates","default","xiaozhi.config.json"),Ce(process.cwd(),"templates","default","xiaozhi.config.json")];this.defaultConfigPath=e.find(t=>st(t))||e[0]}getConfigFilePath(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),t=["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"];for(let r of t){let o=Ce(e,r);if(st(o))return o}return Ce(e,"xiaozhi.config.json")}getConfigFileFormat(e){return e.endsWith(".json5")?"json5":e.endsWith(".jsonc")?"jsonc":"json"}static getInstance(){return i.instance||(i.instance=new i),i.instance}configExists(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),t=["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"];for(let r of t){let o=Ce(e,r);if(st(o))return!0}return!1}initConfig(e="json"){if(!st(this.defaultConfigPath))throw new Error(`\u9ED8\u8BA4\u914D\u7F6E\u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${this.defaultConfigPath}`);if(this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u521D\u59CB\u5316");let t=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),r=`xiaozhi.config.${e}`,o=Ce(t,r);mn(this.defaultConfigPath,o),this.config=null,this.json5Writer=null}loadConfig(){if(!this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C xiaozhi init \u521D\u59CB\u5316\u914D\u7F6E");try{let e=this.getConfigFilePath();this.currentConfigPath=e;let t=this.getConfigFileFormat(e),o=fn(e,"utf8").replace(/^\uFEFF/,""),n;switch(t){case"json5":n=Zt.parse(o),this.json5Writer=zr.load(o);break;case"jsonc":n=it.parse(o);break;default:n=JSON.parse(o);break}return this.validateConfig(n),n}catch(e){throw e instanceof SyntaxError?new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF: ${e.message}`):e}}validateConfig(e){if(!e||typeof e!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A\u6839\u5BF9\u8C61\u65E0\u6548");let t=e;if(t.mcpEndpoint===void 0||t.mcpEndpoint===null)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5B57\u6BB5\u65E0\u6548");if(typeof t.mcpEndpoint!="string")if(Array.isArray(t.mcpEndpoint)){if(t.mcpEndpoint.length===0)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let r of t.mcpEndpoint)if(typeof r!="string"||r.trim()==="")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u5B57\u7B26\u4E32\u6570\u7EC4");if(!t.mcpServers||typeof t.mcpServers!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers \u5B57\u6BB5\u65E0\u6548");for(let[r,o]of Object.entries(t.mcpServers)){if(!o||typeof o!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${r} \u65E0\u6548`);let n=Kt(r,o);if(!n.valid)throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A${n.error}`)}}getConfig(){return this.config=this.loadConfig(),JSON.parse(JSON.stringify(this.config))}getMutableConfig(){return this.config||(this.config=this.loadConfig()),this.config}getMcpEndpoint(){let e=this.getConfig();return Array.isArray(e.mcpEndpoint)?e.mcpEndpoint[0]||"":e.mcpEndpoint}getMcpEndpoints(){let e=this.getConfig();return Array.isArray(e.mcpEndpoint)?[...e.mcpEndpoint]:e.mcpEndpoint?[e.mcpEndpoint]:[]}getMcpServers(){return this.getConfig().mcpServers}getMcpServerConfig(){return this.getConfig().mcpServerConfig||{}}getServerToolsConfig(e){return this.getMcpServerConfig()[e]?.tools||{}}isToolEnabled(e,t){return this.getServerToolsConfig(e)[t]?.enable!==!1}updateMcpEndpoint(e){if(Array.isArray(e)){if(e.length===0)throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let r of e)if(!r||typeof r!="string")throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getMutableConfig();t.mcpEndpoint=e,this.saveConfig(t)}addMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getMutableConfig(),r=this.getMcpEndpoints();if(r.includes(e))throw new Error(`MCP \u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728`);let o=[...r,e];t.mcpEndpoint=o,this.saveConfig(t)}removeMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getMutableConfig(),r=this.getMcpEndpoints();if(r.indexOf(e)===-1)throw new Error(`MCP \u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(r.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");let n=r.filter(s=>s!==e);t.mcpEndpoint=n,this.saveConfig(t)}updateMcpServer(e,t){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let r=Kt(e,t);if(!r.valid)throw new Error(r.error||"\u670D\u52A1\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");let o=this.getMutableConfig();o.mcpServers[e]=t,this.saveConfig(o)}removeMcpServer(e){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getConfig();if(!t.mcpServers[e])throw new Error(`\u670D\u52A1 ${e} \u4E0D\u5B58\u5728`);let r={...t.mcpServers};delete r[e];let o={...t,mcpServers:r};this.saveConfig(o)}updateServerToolsConfig(e,t){let r=this.getMutableConfig();r.mcpServerConfig||(r.mcpServerConfig={}),Object.keys(t).length===0?delete r.mcpServerConfig[e]:r.mcpServerConfig[e]={tools:t},this.saveConfig(r)}removeServerToolsConfig(e){let r={...this.getConfig()};r.mcpServerConfig&&(delete r.mcpServerConfig[e],this.saveConfig(r))}cleanupInvalidServerToolsConfig(){let e=this.getMutableConfig();if(!e.mcpServerConfig)return;let t=Object.keys(e.mcpServers),o=Object.keys(e.mcpServerConfig).filter(n=>!t.includes(n));if(o.length>0){for(let n of o)delete e.mcpServerConfig[n];this.saveConfig(e),g.info(`\u5DF2\u6E05\u7406 ${o.length} \u4E2A\u65E0\u6548\u7684\u670D\u52A1\u5DE5\u5177\u914D\u7F6E: ${o.join(", ")}`)}}setToolEnabled(e,t,r,o){let n=this.getMutableConfig();n.mcpServerConfig||(n.mcpServerConfig={}),n.mcpServerConfig[e]||(n.mcpServerConfig[e]={tools:{}}),n.mcpServerConfig[e].tools[t]={...n.mcpServerConfig[e].tools[t],enable:r,...o&&{description:o}},this.saveConfig(n)}saveConfig(e){try{this.validateConfig(e);let t;this.currentConfigPath?t=this.currentConfigPath:(t=this.getConfigFilePath(),this.currentConfigPath=t);let r=this.getConfigFileFormat(t),o;switch(r){case"json5":try{this.json5Writer?(this.json5Writer.write(e),o=this.json5Writer.toSource()):(console.warn("\u6CA1\u6709 json5Writer \u5B9E\u4F8B\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F"),o=Zt.stringify(e,null,2))}catch(n){console.warn("\u4F7F\u7528 json5-writer \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F:",n),o=Zt.stringify(e,null,2)}break;case"jsonc":try{o=it.stringify(e,null,2)}catch(n){console.warn("\u4F7F\u7528 comment-json \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON \u683C\u5F0F:",n),o=JSON.stringify(e,null,2)}break;default:o=JSON.stringify(e,null,2);break}Cn(t,o,"utf8"),this.config=e,this.notifyConfigUpdate(e)}catch(t){throw new Error(`\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}reloadConfig(){this.config=null,this.currentConfigPath=null,this.json5Writer=null}getConfigPath(){return this.getConfigFilePath()}getDefaultConfigPath(){return this.defaultConfigPath}getConnectionConfig(){let t=this.getConfig().connection||{};return{heartbeatInterval:t.heartbeatInterval??Yt.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??Yt.heartbeatTimeout,reconnectInterval:t.reconnectInterval??Yt.reconnectInterval}}getHeartbeatInterval(){return this.getConnectionConfig().heartbeatInterval}getHeartbeatTimeout(){return this.getConnectionConfig().heartbeatTimeout}getReconnectInterval(){return this.getConnectionConfig().reconnectInterval}updateConnectionConfig(e){let t=this.getMutableConfig();t.connection||(t.connection={}),Object.assign(t.connection,e),this.saveConfig(t)}async updateToolUsageStats(e,t,r){try{if(typeof t=="string"&&r){let o=e,n=t,s=r;await Promise.all([this._updateMCPServerToolStats(o,n,s),this.updateCustomMCPToolStats(o,n,s)]),g.debug(`\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${o}/${n}`)}else{let o=e,n=t,s=new Date().toISOString();await this.updateCustomMCPToolStats(o,s,n),g.debug(`CustomMCP \u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${o}`)}}catch(o){if(typeof t=="string"&&r){let n=e,s=t;g.error(`\u66F4\u65B0\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${n}/${s}): ${o instanceof Error?o.message:String(o)}`)}else{let n=e;g.error(`\u66F4\u65B0 CustomMCP \u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${n}): ${o instanceof Error?o.message:String(o)}`)}}}async updateMCPServerToolStats(e,t,r,o=!0){await this._updateMCPServerToolStats(e,t,r,o)}setHeartbeatInterval(e){if(e<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatInterval:e})}setHeartbeatTimeout(e){if(e<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatTimeout:e})}setReconnectInterval(e){if(e<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({reconnectInterval:e})}getModelScopeConfig(){return this.getConfig().modelscope||{}}getModelScopeApiKey(){return this.getModelScopeConfig().apiKey||process.env.MODELSCOPE_API_TOKEN}updateModelScopeConfig(e){let t=this.getMutableConfig();t.modelscope||(t.modelscope={}),Object.assign(t.modelscope,e),this.saveConfig(t)}setModelScopeApiKey(e){if(!e||typeof e!="string")throw new Error("API Key \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");this.updateModelScopeConfig({apiKey:e})}getCustomMCPConfig(){return this.getConfig().customMCP||null}getCustomMCPTools(){let e=this.getCustomMCPConfig();return!e||!e.tools?[]:e.tools}validateCustomMCPTools(e){if(!Array.isArray(e))return!1;for(let t of e){if(!t.name||typeof t.name!="string")return g.warn(`CustomMCP \u5DE5\u5177\u7F3A\u5C11\u6709\u6548\u7684 name \u5B57\u6BB5: ${JSON.stringify(t)}`),!1;if(!t.description||typeof t.description!="string")return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 description \u5B57\u6BB5`),!1;if(!t.inputSchema||typeof t.inputSchema!="object")return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 inputSchema \u5B57\u6BB5`),!1;if(!t.handler||typeof t.handler!="object")return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 handler \u5B57\u6BB5`),!1;if(!["proxy","function","http","script","chain","mcp"].includes(t.handler.type))return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7684 handler.type \u5FC5\u987B\u662F 'proxy', 'function', 'http', 'script', 'chain' \u6216 'mcp'`),!1;if(!this.validateHandlerConfig(t.name,t.handler))return!1}return!0}validateHandlerConfig(e,t){switch(t.type){case"proxy":return this.validateProxyHandler(e,t);case"http":return this.validateHttpHandler(e,t);case"function":return this.validateFunctionHandler(e,t);case"script":return this.validateScriptHandler(e,t);case"chain":return this.validateChainHandler(e,t);case"mcp":return this.validateMCPHandler(e,t);default:return g.warn(`CustomMCP \u5DE5\u5177 ${e} \u4F7F\u7528\u4E86\u672A\u77E5\u7684\u5904\u7406\u5668\u7C7B\u578B`),!1}}validateProxyHandler(e,t){return t.platform?["coze","openai","anthropic","custom"].includes(t.platform)?!t.config||typeof t.config!="object"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u7F3A\u5C11 config \u5B57\u6BB5`),!1):t.platform==="coze"&&!t.config.workflow_id&&!t.config.bot_id?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 Coze \u5904\u7406\u5668\u5FC5\u987B\u63D0\u4F9B workflow_id \u6216 bot_id`),!1):!0:(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u5E73\u53F0: ${t.platform}`),!1):(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u7F3A\u5C11 platform \u5B57\u6BB5`),!1)}validateHttpHandler(e,t){if(!t.url||typeof t.url!="string")return g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 http \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 url \u5B57\u6BB5`),!1;try{new URL(t.url)}catch{return g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 http \u5904\u7406\u5668 url \u683C\u5F0F\u65E0\u6548: ${t.url}`),!1}return t.method&&!["GET","POST","PUT","DELETE","PATCH"].includes(t.method)?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 http \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684 HTTP \u65B9\u6CD5: ${t.method}`),!1):!0}validateFunctionHandler(e,t){return!t.module||typeof t.module!="string"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 function \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 module \u5B57\u6BB5`),!1):!t.function||typeof t.function!="string"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 function \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 function \u5B57\u6BB5`),!1):!0}validateScriptHandler(e,t){return!t.script||typeof t.script!="string"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 script \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 script \u5B57\u6BB5`),!1):t.interpreter&&!["node","python","bash"].includes(t.interpreter)?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 script \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u89E3\u91CA\u5668: ${t.interpreter}`),!1):!0}validateChainHandler(e,t){return!t.tools||!Array.isArray(t.tools)||t.tools.length===0?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 chain \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 tools \u6570\u7EC4`),!1):["sequential","parallel"].includes(t.mode)?["stop","continue","retry"].includes(t.error_handling)?!0:(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 chain \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u9519\u8BEF\u5904\u7406\u7B56\u7565: ${t.error_handling}`),!1):(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 chain \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u6267\u884C\u6A21\u5F0F: ${t.mode}`),!1)}validateMCPHandler(e,t){return!t.config||typeof t.config!="object"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11 config \u5B57\u6BB5`),!1):!t.config.serviceName||typeof t.config.serviceName!="string"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 serviceName`),!1):!t.config.toolName||typeof t.config.toolName!="string"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 toolName`),!1):!0}hasValidCustomMCPTools(){try{let e=this.getCustomMCPTools();return e.length===0?!1:this.validateCustomMCPTools(e)}catch(e){return g.error("\u68C0\u67E5 customMCP \u5DE5\u5177\u914D\u7F6E\u65F6\u51FA\u9519:",e),!1}}addCustomMCPTool(e){if(!e||typeof e!="object")throw new Error("\u5DE5\u5177\u914D\u7F6E\u4E0D\u80FD\u4E3A\u7A7A");let t=this.getMutableConfig();if(t.customMCP||(t.customMCP={tools:[]}),t.customMCP.tools.find(o=>o.name===e.name))throw new Error(`\u5DE5\u5177 "${e.name}" \u5DF2\u5B58\u5728`);if(!this.validateCustomMCPTools([e]))throw new Error("\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");t.customMCP.tools.unshift(e),this.saveConfig(t),g.info(`\u6210\u529F\u6DFB\u52A0\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${e.name}`)}async addCustomMCPTools(e){if(!Array.isArray(e))throw new Error("\u5DE5\u5177\u914D\u7F6E\u5FC5\u987B\u662F\u6570\u7EC4");if(e.length===0)return;let t=this.getMutableConfig();t.customMCP||(t.customMCP={tools:[]});let r=new Set(t.customMCP.tools.map(n=>n.name)),o=e.filter(n=>!r.has(n.name));if(o.length>0){if(!this.validateCustomMCPTools(o))throw new Error("\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");t.customMCP.tools.push(...o),this.saveConfig(t),g.info(`\u6210\u529F\u6279\u91CF\u6DFB\u52A0 ${o.length} \u4E2A\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${o.map(n=>n.name).join(", ")}`)}}removeCustomMCPTool(e){if(!e||typeof e!="string")throw new Error("\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");let t=this.getMutableConfig();if(!t.customMCP||!t.customMCP.tools)throw new Error("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177");let r=t.customMCP.tools.findIndex(o=>o.name===e);if(r===-1)throw new Error(`\u5DE5\u5177 "${e}" \u4E0D\u5B58\u5728`);t.customMCP.tools.splice(r,1),this.saveConfig(t),g.info(`\u6210\u529F\u5220\u9664\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${e}`)}updateCustomMCPTool(e,t){if(!e||typeof e!="string")throw new Error("\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");if(!t||typeof t!="object")throw new Error("\u66F4\u65B0\u540E\u7684\u5DE5\u5177\u914D\u7F6E\u4E0D\u80FD\u4E3A\u7A7A");let r=this.getMutableConfig();if(!r.customMCP||!r.customMCP.tools)throw new Error("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177");let o=r.customMCP.tools.findIndex(n=>n.name===e);if(o===-1)throw new Error(`\u5DE5\u5177 "${e}" \u4E0D\u5B58\u5728`);if(!this.validateCustomMCPTools([t]))throw new Error("\u66F4\u65B0\u540E\u7684\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");r.customMCP.tools[o]=t,this.saveConfig(r),g.info(`\u6210\u529F\u66F4\u65B0\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${e}`)}updateCustomMCPTools(e){if(!Array.isArray(e))throw new Error("\u5DE5\u5177\u914D\u7F6E\u5FC5\u987B\u662F\u6570\u7EC4");if(!this.validateCustomMCPTools(e))throw new Error("\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");let t=this.getMutableConfig();t.customMCP||(t.customMCP={tools:[]}),t.customMCP.tools=e,this.saveConfig(t),g.info(`\u6210\u529F\u66F4\u65B0\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u914D\u7F6E\uFF0C\u5171 ${e.length} \u4E2A\u5DE5\u5177`)}getWebUIConfig(){return this.getConfig().webUI||{}}getWebUIPort(){return this.getWebUIConfig().port??9999}notifyConfigUpdate(e){try{let t=global.__webServer;t&&typeof t.broadcastConfigUpdate=="function"&&(t.broadcastConfigUpdate(e),console.log("\u5DF2\u901A\u8FC7 WebSocket \u5E7F\u64AD\u914D\u7F6E\u66F4\u65B0"))}catch(t){console.warn("\u901A\u77E5 Web \u754C\u9762\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",t instanceof Error?t.message:String(t))}}updateWebUIConfig(e){let t=this.getMutableConfig();t.webUI||(t.webUI={}),Object.assign(t.webUI,e),this.saveConfig(t)}setWebUIPort(e){if(!Number.isInteger(e)||e<=0||e>65535)throw new Error("\u7AEF\u53E3\u53F7\u5FC5\u987B\u662F 1-65535 \u4E4B\u95F4\u7684\u6574\u6570");this.updateWebUIConfig({port:e})}updatePlatformConfig(e,t){let r=this.getMutableConfig();r.platforms||(r.platforms={}),r.platforms[e]=t,this.saveConfig(r)}getCozePlatformConfig(){let t=this.getConfig().platforms?.coze;return!t||!t.token?null:{token:t.token}}getCozeToken(){return this.getCozePlatformConfig()?.token||null}setCozePlatformConfig(e){if(!e.token||typeof e.token!="string"||e.token.trim()==="")throw new Error("\u6263\u5B50 API Token \u4E0D\u80FD\u4E3A\u7A7A");this.updatePlatformConfig("coze",{token:e.token.trim()})}isCozeConfigValid(){let e=this.getCozePlatformConfig();return e!==null&&typeof e.token=="string"&&e.token.trim()!==""}async _updateMCPServerToolStats(e,t,r,o=!0){let n=this.getMutableConfig();n.mcpServerConfig||(n.mcpServerConfig={}),n.mcpServerConfig[e]||(n.mcpServerConfig[e]={tools:{}}),n.mcpServerConfig[e].tools[t]||(n.mcpServerConfig[e].tools[t]={enable:!0});let s=n.mcpServerConfig[e].tools[t],a=s.usageCount||0,l=s.lastUsedTime;o&&(s.usageCount=a+1),(!l||new Date(r)>new Date(l))&&(s.lastUsedTime=Lr(r).format("YYYY-MM-DD HH:mm:ss")),this.saveConfig(n)}async updateCustomMCPToolStats(e,t,r){try{let o,n,s=!0,a;if(typeof r=="string"){let b=e;o=`${b}__${t}`,n=r,a=`${b}/${t}`}else o=e,n=t,s=r||!0,a=o;let l=this.getCustomMCPTools(),h=l.findIndex(b=>b.name===o);if(h===-1)return;let u=[...l],p=u[h];p.stats||(p.stats={});let C=p.stats.usageCount||0,T=p.stats.lastUsedTime;s&&(p.stats.usageCount=C+1),(!T||new Date(n)>new Date(T))&&(p.stats.lastUsedTime=Lr(n).format("YYYY-MM-DD HH:mm:ss")),await this.updateCustomMCPTools(u)}catch(o){if(typeof r=="string"){let n=e,s=t;g.error(`\u66F4\u65B0 customMCP \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25 (${n}/${s}): ${o instanceof Error?o.message:String(o)}`)}else{let n=e;g.error(`\u66F4\u65B0 customMCP \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25 (${n}): ${o instanceof Error?o.message:String(o)}`)}}}async acquireStatsUpdateLock(e){if(this.statsUpdateLocks.has(e))return g.debug(`\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u66F4\u65B0\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8DF3\u8FC7\u672C\u6B21\u66F4\u65B0`),!1;let t=new Promise(o=>{});this.statsUpdateLocks.set(e,t);let r=setTimeout(()=>{this.releaseStatsUpdateLock(e)},this.STATS_UPDATE_TIMEOUT);return this.statsUpdateLockTimeouts.set(e,r),!0}releaseStatsUpdateLock(e){this.statsUpdateLocks.delete(e);let t=this.statsUpdateLockTimeouts.get(e);t&&(clearTimeout(t),this.statsUpdateLockTimeouts.delete(e)),g.debug(`\u5DF2\u91CA\u653E\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u66F4\u65B0\u9501`)}async updateToolUsageStatsWithLock(e,t=!0){let r=`custommcp_${e}`;if(await this.acquireStatsUpdateLock(r))try{await this.updateToolUsageStats(e,t),g.debug(`\u5DE5\u5177 ${e} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(o){throw g.error(`\u5DE5\u5177 ${e} \u7EDF\u8BA1\u66F4\u65B0\u5931\u8D25:`,o),o}finally{this.releaseStatsUpdateLock(r)}}async updateMCPServerToolStatsWithLock(e,t,r,o=!0){let n=`mcpserver_${e}_${t}`;if(await this.acquireStatsUpdateLock(n))try{await this.updateMCPServerToolStats(e,t,r,o),g.debug(`MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(s){throw g.error(`MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u66F4\u65B0\u5931\u8D25:`,s),s}finally{this.releaseStatsUpdateLock(n)}}clearAllStatsUpdateLocks(){let e=this.statsUpdateLocks.size;this.statsUpdateLocks.clear();for(let t of this.statsUpdateLockTimeouts.values())clearTimeout(t);this.statsUpdateLockTimeouts.clear(),e>0&&g.info(`\u5DF2\u6E05\u7406 ${e} \u4E2A\u7EDF\u8BA1\u66F4\u65B0\u9501`)}getStatsUpdateLocks(){return Array.from(this.statsUpdateLocks.keys())}},d=Qt.getInstance()});var er,$e,Fe,y,tr,We=m(()=>{"use strict";er={NAME:"xiaozhi-mcp-service",DEFAULT_PORT:3e3,DEFAULT_WEB_UI_PORT:9999,PID_FILE:"xiaozhi.pid",LOG_FILE:"xiaozhi.log"},$e={FILE_NAMES:["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"],DEFAULT_FILE:"xiaozhi.config.default.json",DIR_ENV_VAR:"XIAOZHI_CONFIG_DIR"},Fe={WORK_DIR:".xiaozhi",TEMPLATES_DIR:"templates",LOGS_DIR:"logs"},y={GENERAL_ERROR:"GENERAL_ERROR",CONFIG_ERROR:"CONFIG_ERROR",SERVICE_ERROR:"SERVICE_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",FILE_ERROR:"FILE_ERROR",PROCESS_ERROR:"PROCESS_ERROR",NETWORK_ERROR:"NETWORK_ERROR",PERMISSION_ERROR:"PERMISSION_ERROR"},tr={PROCESS_STOP:3e3,SERVICE_START:1e4,NETWORK_REQUEST:5e3,FILE_OPERATION:2e3}});var yn,Tn,at,jr=m(()=>{"use strict";We();yn={[y.CONFIG_ERROR]:'\u8FD0\u884C "xiaozhi --help" \u67E5\u770B\u914D\u7F6E\u76F8\u5173\u547D\u4EE4',[y.SERVICE_ERROR]:'\u8FD0\u884C "xiaozhi status" \u68C0\u67E5\u670D\u52A1\u72B6\u6001',[y.VALIDATION_ERROR]:"\u68C0\u67E5\u8F93\u5165\u53C2\u6570\u662F\u5426\u6B63\u786E",[y.FILE_ERROR]:"\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u548C\u6743\u9650",[y.PROCESS_ERROR]:"\u68C0\u67E5\u8FDB\u7A0B\u72B6\u6001\u548C\u6743\u9650",[y.NETWORK_ERROR]:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C\u9632\u706B\u5899\u8BBE\u7F6E",[y.PERMISSION_ERROR]:"\u5C1D\u8BD5\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"},Tn={config_not_found:['\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6',"\u68C0\u67E5\u5F53\u524D\u76EE\u5F55\u662F\u5426\u4E3A\u9879\u76EE\u6839\u76EE\u5F55","\u8BBE\u7F6E XIAOZHI_CONFIG_DIR \u73AF\u5883\u53D8\u91CF\u6307\u5B9A\u914D\u7F6E\u76EE\u5F55"],service_port_occupied:["\u68C0\u67E5\u7AEF\u53E3\u662F\u5426\u88AB\u5176\u4ED6\u7A0B\u5E8F\u5360\u7528",'\u4F7F\u7528 "lsof -i :\u7AEF\u53E3\u53F7" \u67E5\u770B\u7AEF\u53E3\u4F7F\u7528\u60C5\u51B5',"\u66F4\u6539\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u7AEF\u53E3\u8BBE\u7F6E"],permission_denied:["\u68C0\u67E5\u6587\u4EF6\u548C\u76EE\u5F55\u6743\u9650","\u4F7F\u7528 sudo \u6216\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C","\u786E\u4FDD\u5F53\u524D\u7528\u6237\u6709\u8DB3\u591F\u7684\u6743\u9650"],service_start_failed:["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u662F\u5426\u6B63\u786E","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F","\u786E\u4FDD\u6240\u6709\u4F9D\u8D56\u670D\u52A1\u6B63\u5E38\u8FD0\u884C"]},at=class{static{c(this,"ERROR_MESSAGES")}static getHelpMessage(e){return yn[e]}static getSolutions(e){return Tn[e]||[]}static formatError(e,t){return`${t?`[${t}] `:""}${e.message}`}static getFriendlyMessage(e){return{[y.CONFIG_ERROR]:"\u914D\u7F6E\u6587\u4EF6\u76F8\u5173\u9519\u8BEF",[y.SERVICE_ERROR]:"\u670D\u52A1\u8FD0\u884C\u76F8\u5173\u9519\u8BEF",[y.VALIDATION_ERROR]:"\u8F93\u5165\u9A8C\u8BC1\u9519\u8BEF",[y.FILE_ERROR]:"\u6587\u4EF6\u64CD\u4F5C\u9519\u8BEF",[y.PROCESS_ERROR]:"\u8FDB\u7A0B\u7BA1\u7406\u9519\u8BEF",[y.NETWORK_ERROR]:"\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF",[y.PERMISSION_ERROR]:"\u6743\u9650\u4E0D\u8DB3\u9519\u8BEF"}[e]||"\u672A\u77E5\u9519\u8BEF"}static isRecoverable(e){return[y.NETWORK_ERROR,y.FILE_ERROR,y.SERVICE_ERROR].includes(e)}static getSeverity(e){return{[y.VALIDATION_ERROR]:"low",[y.FILE_ERROR]:"medium",[y.CONFIG_ERROR]:"medium",[y.NETWORK_ERROR]:"medium",[y.SERVICE_ERROR]:"high",[y.PROCESS_ERROR]:"high",[y.PERMISSION_ERROR]:"critical"}[e]||"medium"}}});var _,ve,I,E,v,le,te=m(()=>{"use strict";We();_=class i extends Error{constructor(t,r,o=1,n){super(t);this.code=r;this.exitCode=o;this.suggestions=n;this.name="CLIError",Error.captureStackTrace&&Error.captureStackTrace(this,i)}static{c(this,"CLIError")}static withSuggestions(t,r,o){return new i(t,r,1,o)}},ve=class i extends _{static{c(this,"ConfigError")}constructor(e,t){super(e,y.CONFIG_ERROR,1,t),this.name="ConfigError"}static configNotFound(){return new i("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728",['\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6'])}static invalidFormat(e){return new i(`\u65E0\u6548\u7684\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F: ${e}`,["\u652F\u6301\u7684\u683C\u5F0F: json, json5, jsonc"])}},I=class i extends _{static{c(this,"ServiceError")}constructor(e,t){super(e,y.SERVICE_ERROR,1,t),this.name="ServiceError"}static alreadyRunning(e){return new i(`\u670D\u52A1\u5DF2\u7ECF\u5728\u8FD0\u884C (PID: ${e})`,['\u8BF7\u5148\u8FD0\u884C "xiaozhi stop" \u505C\u6B62\u73B0\u6709\u670D\u52A1','\u6216\u8005\u4F7F\u7528 "xiaozhi restart" \u91CD\u542F\u670D\u52A1'])}static autoRestarting(e){return new i(`\u68C0\u6D4B\u5230\u670D\u52A1\u5DF2\u5728\u8FD0\u884C (PID: ${e})\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u542F...`,["\u5982\u679C\u4E0D\u5E0C\u671B\u81EA\u52A8\u91CD\u542F\uFF0C\u8BF7\u4F7F\u7528 xiaozhi stop \u624B\u52A8\u505C\u6B62\u670D\u52A1"])}static notRunning(){return new i("\u670D\u52A1\u672A\u8FD0\u884C",['\u8BF7\u8FD0\u884C "xiaozhi start" \u542F\u52A8\u670D\u52A1'])}static startFailed(e){return new i(`\u670D\u52A1\u542F\u52A8\u5931\u8D25: ${e}`,["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u662F\u5426\u6B63\u786E","\u786E\u4FDD\u7AEF\u53E3\u672A\u88AB\u5360\u7528","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u4FE1\u606F"])}},E=class i extends _{static{c(this,"ValidationError")}constructor(e,t){super(`\u9A8C\u8BC1\u5931\u8D25: ${t} - ${e}`,y.VALIDATION_ERROR,1),this.name="ValidationError"}static invalidPort(e){return new i(`\u7AEF\u53E3\u53F7\u5FC5\u987B\u5728 1-65535 \u8303\u56F4\u5185\uFF0C\u5F53\u524D\u503C: ${e}`,"port")}static requiredField(e){return new i("\u5FC5\u586B\u5B57\u6BB5\u4E0D\u80FD\u4E3A\u7A7A",e)}},v=class i extends _{static{c(this,"FileError")}constructor(e,t,r){let o=t?`${e}: ${t}`:e;super(o,y.FILE_ERROR,1,r),this.name="FileError"}static notFound(e){return new i("\u6587\u4EF6\u4E0D\u5B58\u5728",e,["\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E"])}static permissionDenied(e){return new i("\u6743\u9650\u4E0D\u8DB3",e,["\u68C0\u67E5\u6587\u4EF6\u6743\u9650\u6216\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"])}static alreadyExists(e){return new i("\u6587\u4EF6\u5DF2\u5B58\u5728",e,["\u4F7F\u7528\u4E0D\u540C\u7684\u6587\u4EF6\u540D\u6216\u5220\u9664\u73B0\u6709\u6587\u4EF6"])}},le=class i extends _{static{c(this,"ProcessError")}constructor(e,t,r){let o=t?`${e} (PID: ${t})`:e;super(o,y.PROCESS_ERROR,1,r),this.name="ProcessError"}static killFailed(e){return new i("\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B",e,["\u8FDB\u7A0B\u53EF\u80FD\u5DF2\u7ECF\u505C\u6B62\u6216\u6743\u9650\u4E0D\u8DB3"])}static notFound(e){return new i("\u8FDB\u7A0B\u4E0D\u5B58\u5728",e)}}});import H from"chalk";var re,rr=m(()=>{"use strict";jr();te();re=class i{static{c(this,"ErrorHandler")}static handle(e){e instanceof _?i.handleCLIError(e):i.handleUnknownError(e),process.exit(1)}static handleCLIError(e){if(console.error(H.red(`\u274C \u9519\u8BEF: ${e.message}`)),process.env.DEBUG&&console.error(H.gray(`\u9519\u8BEF\u7801: ${e.code}`)),e.suggestions&&e.suggestions.length>0){console.log(H.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of e.suggestions)console.log(H.gray(` ${r}`))}let t=at.getHelpMessage(e.code);t&&console.log(H.blue(`\u2139\uFE0F ${t}`))}static handleUnknownError(e){console.error(H.red(`\u274C \u672A\u77E5\u9519\u8BEF: ${e.message}`)),process.env.DEBUG||process.env.NODE_ENV==="development"?(console.error(H.gray("\u5806\u6808\u4FE1\u606F:")),console.error(H.gray(e.stack))):console.log(H.yellow("\u{1F4A1} \u63D0\u793A: \u8BBE\u7F6E DEBUG=1 \u73AF\u5883\u53D8\u91CF\u67E5\u770B\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F"))}static async handleAsync(e,t){try{return await e()}catch(r){throw r instanceof _?r:r instanceof Error?new _(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new _(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static handleSync(e,t){try{return e()}catch(r){throw r instanceof _?r:r instanceof Error?new _(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new _(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static warn(e,t){if(console.warn(H.yellow(`\u26A0\uFE0F \u8B66\u544A: ${e}`)),t&&t.length>0){console.log(H.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of t)console.log(H.gray(` ${r}`))}}static info(e){console.log(H.blue(`\u2139\uFE0F ${e}`))}static success(e){console.log(H.green(`\u2705 ${e}`))}}});import k from"fs";import G from"path";var M,Ve=m(()=>{"use strict";te();M=class i{static{c(this,"FileUtils")}static exists(e){try{return k.existsSync(e)}catch{return!1}}static ensureDir(e){try{k.existsSync(e)||k.mkdirSync(e,{recursive:!0})}catch{throw new v("\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55",e)}}static readFile(e,t="utf8"){try{if(!i.exists(e))throw v.notFound(e);return k.readFileSync(e,t)}catch(r){throw r instanceof v?r:new v("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6",e)}}static writeFile(e,t,r){try{if(!r?.overwrite&&i.exists(e))throw v.alreadyExists(e);let o=G.dirname(e);i.ensureDir(o),k.writeFileSync(e,t,"utf8")}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u5199\u5165\u6587\u4EF6",e)}}static copyFile(e,t,r){try{if(!i.exists(e))throw v.notFound(e);if(!r?.overwrite&&i.exists(t))throw v.alreadyExists(t);let o=G.dirname(t);i.ensureDir(o),k.copyFileSync(e,t)}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u590D\u5236\u6587\u4EF6",e)}}static deleteFile(e){try{i.exists(e)&&k.unlinkSync(e)}catch{throw new v("\u65E0\u6CD5\u5220\u9664\u6587\u4EF6",e)}}static copyDirectory(e,t,r={}){try{if(!i.exists(e))throw v.notFound(e);i.ensureDir(t);let o=k.readdirSync(e);for(let n of o){if(r.exclude?.includes(n))continue;let s=G.join(e,n),a=G.join(t,n);k.statSync(s).isDirectory()?r.recursive!==!1&&i.copyDirectory(s,a,r):i.copyFile(s,a,{overwrite:r.overwrite})}}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u590D\u5236\u76EE\u5F55",e)}}static deleteDirectory(e,t={}){try{i.exists(e)&&k.rmSync(e,{recursive:t.recursive??!0,force:!0})}catch{throw new v("\u65E0\u6CD5\u5220\u9664\u76EE\u5F55",e)}}static getFileInfo(e){try{if(!i.exists(e))throw v.notFound(e);let t=k.statSync(e);return{size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory(),mtime:t.mtime,ctime:t.ctime}}catch(t){throw t instanceof v?t:new v("\u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F",e)}}static listDirectory(e,t={}){try{if(!i.exists(e))throw v.notFound(e);let r=k.readdirSync(e),o=[];for(let n of r){if(!t.includeHidden&&n.startsWith("."))continue;let s=G.join(e,n);if(o.push(s),t.recursive&&k.statSync(s).isDirectory()){let a=i.listDirectory(s,t);o=o.concat(a)}}return o}catch(r){throw r instanceof v?r:new v("\u65E0\u6CD5\u5217\u51FA\u76EE\u5F55\u5185\u5BB9",e)}}static createTempFile(e="xiaozhi-",t=".tmp"){let r=process.env.TMPDIR||process.env.TEMP||"/tmp",o=Date.now(),n=Math.random().toString(36).substring(2),s=`${e}${o}-${n}${t}`;return G.join(r,s)}static checkPermissions(e,t=k.constants.R_OK|k.constants.W_OK){try{return k.accessSync(e,t),!0}catch{return!1}}static getExtension(e){return G.extname(e).toLowerCase()}static getBaseName(e){return G.basename(e,G.extname(e))}static normalizePath(e){return G.normalize(e)}static resolvePath(e,t){return t?G.resolve(t,e):G.resolve(e)}}});var xe,or=m(()=>{"use strict";xe=class{static{c(this,"FormatUtils")}static formatUptime(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),o=Math.floor(r/60),n=Math.floor(o/24);return n>0?`${n}\u5929 ${o%24}\u5C0F\u65F6 ${r%60}\u5206\u949F`:o>0?`${o}\u5C0F\u65F6 ${r%60}\u5206\u949F`:r>0?`${r}\u5206\u949F ${t%60}\u79D2`:`${t}\u79D2`}static formatFileSize(e){let t=["B","KB","MB","GB","TB"],r=e,o=0;for(;r>=1024&&o<t.length-1;)r/=1024,o++;return`${r.toFixed(o===0?0:1)} ${t[o]}`}static formatTimestamp(e,t="full"){let r=new Date(e);switch(t){case"date":return r.toLocaleDateString("zh-CN");case"time":return r.toLocaleTimeString("zh-CN");default:return r.toLocaleString("zh-CN")}}static formatPid(e){return`PID: ${e}`}static formatPort(e){return`\u7AEF\u53E3: ${e}`}static formatUrl(e,t,r,o){let n=`${e}://${t}:${r}`;return o?`${n}${o}`:n}static formatConfigPair(e,t){return typeof t=="object"?`${e}: ${JSON.stringify(t,null,2)}`:`${e}: ${t}`}static formatError(e,t=!1){let r=`\u9519\u8BEF: ${e.message}`;return t&&e.stack&&(r+=`
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+=`
4
4
  \u5806\u6808\u4FE1\u606F:
5
5
  ${e.stack}`),r}static formatList(e,t="\u2022"){return e.map(r=>`${t} ${r}`).join(`
6
6
  `)}static formatTable(e){if(e.length===0)return"";let t=Object.keys(e[0]),r=t.map(a=>Math.max(a.length,...e.map(l=>String(l[a]).length))),o=t.map((a,l)=>a.padEnd(r[l])).join(" | "),n=r.map(a=>"-".repeat(a)).join("-|-"),s=e.map(a=>t.map((l,h)=>String(a[l]).padEnd(r[h])).join(" | "));return[o,n,...s].join(`
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 En}from"fs";import{tmpdir as Mn}from"os";import P from"path";import{fileURLToPath as Ur}from"url";var R,Oe=m(()=>{"use strict";We();Ve();R=class i{static{c(this,"PathUtils")}static getPidFile(){let e=process.env[$e.DIR_ENV_VAR]||process.cwd();return P.join(e,`.${er.NAME}.pid`)}static getLogFile(e){let t=e||process.cwd();return P.join(t,er.LOG_FILE)}static getConfigDir(){return process.env[$e.DIR_ENV_VAR]||process.cwd()}static getWorkDir(){let e=i.getConfigDir();return P.join(e,Fe.WORK_DIR)}static getTemplatesDir(){let e=Ur(import.meta.url),t=P.dirname(e);return[P.join(t,Fe.TEMPLATES_DIR),P.join(t,"..","..","..",Fe.TEMPLATES_DIR),P.join(t,"..","..","..","..",Fe.TEMPLATES_DIR)]}static findTemplatesDir(){let e=i.getTemplatesDir();for(let t of e)if(M.exists(t))return t;return null}static getTemplatePath(e){let t=i.findTemplatesDir();if(!t)return null;let r=P.join(t,e);return M.exists(r)?r:null}static getScriptDir(){let e=Ur(import.meta.url);return P.dirname(e)}static getProjectRoot(){let e=i.getScriptDir();return P.join(e,"..","..","..")}static getDistDir(){let e=i.getProjectRoot();return P.join(e,"dist")}static getRelativePath(e){let t=i.getProjectRoot();return P.relative(t,e)}static resolveConfigPath(e){let t=i.getConfigDir();if(e)return P.join(t,`xiaozhi.config.${e}`);for(let r of $e.FILE_NAMES){let o=P.join(t,r);if(M.exists(o))return o}return P.join(t,$e.FILE_NAMES[2])}static getDefaultConfigPath(){let e=i.getProjectRoot();return P.join(e,$e.DEFAULT_FILE)}static validatePath(e){return!P.normalize(e).includes("..")}static ensurePathWithin(e,t){let r=P.resolve(t,e),o=P.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 P.join(process.cwd(),`${e}.js`);let r;try{r=En(t)}catch{r=t}let o=P.dirname(r);return P.join(o,`${e}.js`)}static getMcpServerProxyPath(){return i.getExecutablePath("mcpServerProxy")}static getWebServerStandalonePath(){return i.getExecutablePath("WebServerStandalone")}static createSafePath(...e){let t=P.join(...e),r=P.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||Mn()}static getHomeDir(){return process.env.HOME||process.env.USERPROFILE||""}}});import{execSync as Fr}from"child_process";var W,Be=m(()=>{"use strict";We();te();W=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=Fr(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{encoding:"utf8",timeout:tr.PROCESS_STOP}).toLowerCase():t=Fr(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:tr.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 le(`\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 J,ct=m(()=>{"use strict";te();J=class i{static{c(this,"Validation")}static validatePort(e){if(!Number.isInteger(e)||e<1||e>65535)throw E.invalidPort(e)}static validateConfigFormat(e){let t=["json","json5","jsonc"];if(!t.includes(e))throw new E(`\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 E.requiredField(t)}static validateStringLength(e,t,r={}){if(r.min!==void 0&&e.length<r.min)throw new E(`\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 E(`\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 E(`\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 E(`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 E(`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 E('\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u5305\u542B\u4EE5\u4E0B\u5B57\u7B26: < > : " / \\ | ? * \u4EE5\u53CA\u63A7\u5236\u5B57\u7B26',"projectName");if(e.startsWith("."))throw new E("\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 E("\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 E("\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 E(`\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 E(`\u503C\u4E0D\u80FD\u5C0F\u4E8E ${r.min}\uFF0C\u5F53\u524D\u503C: ${e}`,t);if(r.max!==void 0&&e>r.max)throw new E(`\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 E(`\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 E(`\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 E(`\u7F3A\u5C11\u5FC5\u9700\u7684\u5C5E\u6027: ${o}`,r)}static validateEnum(e,t,r){if(!t.includes(e))throw new E(`\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 E(`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${r instanceof Error?r.message:String(r)}`,t)}}}});import lt from"fs";import oe from"path";import{fileURLToPath as Wr}from"url";var gt,Vr=m(()=>{"use strict";te();gt=class i{static{c(this,"VersionUtils")}static cachedVersion=null;static getVersion(){if(i.cachedVersion)return i.cachedVersion;try{let e=Wr(import.meta.url),t=oe.dirname(e),r=[oe.join(t,"package.json"),oe.join(t,"..","package.json"),oe.join(t,"..","..","..","package.json"),oe.join(t,"..","..","..","..","package.json")];for(let o of r)if(lt.existsSync(o)){let n=JSON.parse(lt.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=Wr(import.meta.url),t=oe.dirname(e),r=[oe.join(t,"package.json"),oe.join(t,"..","package.json"),oe.join(t,"..","..","..","package.json"),oe.join(t,"..","..","..","..","package.json")];for(let o of r)if(lt.existsSync(o)){let n=JSON.parse(lt.readFileSync(o,"utf8"));return{version:n.version||"unknown",name:n.name,description:n.description,author:n.author}}return{version:"unknown"}}catch{throw new v("\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 Br={};F(Br,{ProcessManagerImpl:()=>qe});var qe,nr=m(()=>{"use strict";te();Ve();or();Oe();Be();qe=class{static{c(this,"ProcessManagerImpl")}getPidFilePath(){return R.getPidFile()}readPidFile(){try{let e=this.getPidFilePath();if(!M.exists(e))return null;let t=M.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();M.writeFile(o,r,{overwrite:!0})}catch{throw new v("\u65E0\u6CD5\u5199\u5165 PID \u6587\u4EF6",this.getPidFilePath())}}isXiaozhiProcess(e){return W.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=xe.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 W.killProcess(e)}catch(t){throw new le(`\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 le(`\u65E0\u6CD5\u505C\u6B62\u8FDB\u7A0B: ${t instanceof Error?t.message:String(t)}`,e)}}cleanupPidFile(){try{let e=this.getPidFilePath();M.exists(e)&&M.deleteFile(e)}catch(e){console.warn("\u6E05\u7406 PID \u6587\u4EF6\u5931\u8D25:",e)}}processExists(e){return W.processExists(e)}cleanupContainerState(){if(W.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 Gr={};F(Gr,{DaemonManagerImpl:()=>sr});import{spawn as qr}from"child_process";import ht from"fs";var sr,Jr=m(()=>{"use strict";te();Oe();Be();sr=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 I.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 I(`\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 I.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 I(`\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 I(`\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=R.getLogFile();if(!ht.existsSync(t))throw new I("\u65E5\u5FD7\u6587\u4EF6\u4E0D\u5B58\u5728");let{command:r,args:o}=W.getTailCommand(t),n=qr(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 I(`\u8FDE\u63A5\u65E5\u5FD7\u5931\u8D25: ${s.message}`)})}catch(t){throw new I(`\u8FDE\u63A5\u65E5\u5FD7\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}async spawnDaemonProcess(e,t){let o=[R.getWebServerStandalonePath()];t.openBrowser&&o.push("--open-browser");let n={...process.env,XIAOZHI_CONFIG_DIR:R.getConfigDir(),XIAOZHI_DAEMON:"true",...t.env},s=qr("node",o,{detached:!0,stdio:["ignore","pipe","pipe"],env:n,cwd:t.cwd||process.cwd()});if(!s.pid)throw new le("\u65E0\u6CD5\u542F\u52A8\u5B88\u62A4\u8FDB\u7A0B",0);return s}async setupLogging(e,t){try{let r=R.getLogFile(),n=(await import("path")).dirname(r);ht.existsSync(n)||ht.mkdirSync(n,{recursive:!0});let s=ht.createWriteStream(r,{flags:"a"});e.stdout?.pipe(s),e.stderr?.pipe(s);let a=new Date().toISOString();s.write(`
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(`
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 ne from"ws";var O,pe,ut=m(()=>{"use strict";S();O=class extends Error{constructor(t,r,o){super(r);this.code=t;this.data=o;this.name="ToolCallError"}static{c(this,"ToolCallError")}},pe=class{static{c(this,"ProxyMCPServer")}endpointUrl;ws=null;logger;isConnected=!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 MCP \u63A5\u5165\u70B9: ${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 ne(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.isConnected=!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.isConnected=!1,this.serverInitialized=!1,this.logger.info(`MCP \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 ${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===ne.OPEN?this.ws.close(1e3,"Cleaning up connection"):this.ws.readyState===ne.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.isConnected=!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.isConnected}, wsReadyState=${this.ws?.readyState}`),this.isConnected&&this.ws?.readyState===ne.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.isConnected,wsReadyState:this.ws?.readyState,wsReadyStateText:this.ws?.readyState===ne.OPEN?"OPEN":this.ws?.readyState===ne.CONNECTING?"CONNECTING":this.ws?.readyState===ne.CLOSING?"CLOSING":this.ws?.readyState===ne.CLOSED?"CLOSED":"UNKNOWN"}),(!this.isConnected||this.ws?.readyState!==ne.OPEN)&&(this.logger.warn(`\u5C1D\u8BD5\u91CD\u65B0\u8FDE\u63A5\u4EE5\u53D1\u9001\u54CD\u5E94: id=${e}`),this.scheduleReconnect())}getStatus(){return{connected:this.isConnected,initialized:this.serverInitialized,url:this.endpointUrl,availableTools:this.tools.size,connectionState:this.connectionState,reconnectAttempts:this.reconnectState.attempts,lastError:this.reconnectState.lastError?.message||null}}disconnect(){this.logger.info("\u4E3B\u52A8\u65AD\u5F00 MCP \u8FDE\u63A5"),this.reconnectState.isManualDisconnect=!0,this.stopReconnect(),this.cleanupConnection(),this.connectionState="disconnected"}async reconnect(){this.logger.info("\u624B\u52A8\u91CD\u8FDE MCP \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 O(-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 O(-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 O?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 O(-32602,"\u8BF7\u6C42\u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61");if(!e.name||typeof e.name!="string")throw new O(-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 O(-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 O?o=s:o=new O(-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 O(-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 O(-32601,`\u5DE5\u5177\u4E0D\u5B58\u5728: ${t}`)):l.message?.includes("\u670D\u52A1")&&l.message?.includes("\u4E0D\u53EF\u7528")?s(new O(-32001,l.message)):l.message?.includes("\u6682\u65F6\u4E0D\u53EF\u7528")?s(new O(-32001,l.message)):l.message?.includes("\u6301\u7EED\u4E0D\u53EF\u7528")?s(new O(-32001,l.message)):s(new O(-32e3,`\u5DE5\u5177\u6267\u884C\u5931\u8D25: ${l.message}`))})})}handleToolCallError(e,t,r){let o;e instanceof O?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.isConnected&&this.ws?.readyState===ne.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.isConnected,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 Ae,Ge=m(()=>{"use strict";S();Ae=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 Pn}from"crypto";import ir from"express";var pt,Xr=m(()=>{"use strict";Ge();pt=class extends Ae{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=ir(),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(ir.json({limit:"10mb"})),this.app.use(ir.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=Pn();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
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
11
  data: /messages?sessionId=${o}
12
12
 
13
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}
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 Kr=m(()=>{"use strict";Ge()});import Ma,{WebSocketServer as Pa}from"ws";var Zr=m(()=>{"use strict";Ge()});import{createHash as wn}from"crypto";function de(i,e){let t=wn("md5").update(JSON.stringify(e||{})).digest("hex");return`${i}_${t}`}function ke(i,e){let t=new Date(i).getTime();return Date.now()-t>e}function Se(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 me,dt=m(()=>{"use strict";c(de,"generateCacheKey");c(ke,"isCacheExpired");c(Se,"shouldCleanupCache");me={TIMEOUT:8e3,CACHE_TTL:3e5,CLEANUP_INTERVAL:6e4,MAX_CACHE_SIZE:1e3,ENABLE_ONE_TIME_CACHE:!0}});var mt,Yr=m(()=>{"use strict";dt();mt=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}`)})},me.CLEANUP_INTERVAL),this.logger.info(`[CacheLifecycle] \u542F\u52A8\u81EA\u52A8\u6E05\u7406\u5B9A\u65F6\u5668\uFF0C\u95F4\u9694: ${me.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:me.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 ke(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&&Se(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)ke(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}`),ke(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 ft,Qr=m(()=>{"use strict";ft=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,u)=>{let p=this.getTaskExecutionTime(u.taskId)||0;return h+p},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 eo(i,e){return{content:[{type:"text",text:e?bn(e,i):to(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 bn(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 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...
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:to(e)};return t[i]||t.default}function to(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: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...
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 Je,ro=m(()=>{"use strict";Je=class i extends Error{static{c(this,"TimeoutError")}name="TimeoutError";constructor(e){super(e),this.name="TimeoutError",Error.captureStackTrace(this,i)}toJSON(){return{name:this.name,message:this.message,stack:this.stack}}};c(eo,"createTimeoutResponse");c(bn,"getToolSpecificTimeoutMessage");c(to,"getDefaultTimeoutMessage")});import{createHash as Rn}from"crypto";import{existsSync as Xe,mkdirSync as In,readFileSync as oo,renameSync as $n,writeFileSync as no}from"fs";import{dirname as xn,resolve as so}from"path";import On from"dayjs";var ge,Ct=m(()=>{"use strict";S();dt();ge=class{static{c(this,"MCPCacheManager")}cachePath;logger;CACHE_VERSION="1.0.0";CACHE_ENTRY_VERSION="1.0.0";cleanupInterval;CLEANUP_INTERVAL=6e4;constructor(e){this.logger=g,this.cachePath=e||this.getCacheFilePath(),this.startCleanupTimer()}formatTimestamp(){return On().format("YYYY-MM-DD HH:mm:ss")}getCacheFilePath(){try{let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return so(e,"xiaozhi.cache.json")}catch{let t=process.env.XIAOZHI_CONFIG_DIR||"/tmp";return so(t,"xiaozhi.cache.json")}}async ensureCacheFile(){try{if(!Xe(this.cachePath)){let e=xn(this.cachePath);Xe(e)||(In(e,{recursive:!0}),this.logger.debug(`[CacheManager] \u5DF2\u521B\u5EFA\u7F13\u5B58\u76EE\u5F55: ${e}`)),this.logger.debug("[CacheManager] \u7F13\u5B58\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u521B\u5EFA\u521D\u59CB\u7F13\u5B58\u6587\u4EF6");let t=await this.createInitialCache();await this.saveCache(t),this.logger.info(`[CacheManager] \u5DF2\u521B\u5EFA\u7F13\u5B58\u6587\u4EF6: ${this.cachePath}`)}}catch(e){this.logger.warn(`[CacheManager] \u521B\u5EFA\u7F13\u5B58\u6587\u4EF6\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async createInitialCache(){let e=this.formatTimestamp();return{version:this.CACHE_VERSION,mcpServers:{},metadata:{lastGlobalUpdate:e,totalWrites:0,createdAt:e}}}async writeCacheEntry(e,t,r){try{this.logger.debug(`[CacheManager] \u5F00\u59CB\u5199\u5165\u7F13\u5B58: ${e}`),await this.ensureCacheFile();let o=await this.loadExistingCache(),n=this.generateConfigHash(r),s={tools:t.map(a=>({name:a.name,description:a.description||"",inputSchema:a.inputSchema})),lastUpdated:this.formatTimestamp(),serverConfig:{...r},configHash:n,version:this.CACHE_ENTRY_VERSION};o.mcpServers[e]=s,o.metadata.lastGlobalUpdate=this.formatTimestamp(),o.metadata.totalWrites+=1,await this.saveCache(o),this.logger.info(`[CacheManager] \u7F13\u5B58\u5199\u5165\u6210\u529F: ${e}, \u5DE5\u5177\u6570\u91CF: ${t.length}`)}catch(o){this.logger.warn(`[CacheManager] \u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e}, \u9519\u8BEF: ${o instanceof Error?o.message:String(o)}`)}}async loadExistingCache(){try{if(!Xe(this.cachePath))return await this.createInitialCache();let e=oo(this.cachePath,"utf8"),t=JSON.parse(e);return this.validateCacheStructure(t)?t:(this.logger.warn("[CacheManager] \u7F13\u5B58\u6587\u4EF6\u7ED3\u6784\u65E0\u6548\uFF0C\u91CD\u65B0\u521B\u5EFA"),await this.createInitialCache())}catch(e){return this.logger.warn(`[CacheManager] \u52A0\u8F7D\u7F13\u5B58\u5931\u8D25\uFF0C\u521B\u5EFA\u65B0\u7F13\u5B58: ${e instanceof Error?e.message:String(e)}`),await this.createInitialCache()}}async saveCache(e){let t=JSON.stringify(e,null,2);await this.atomicWrite(this.cachePath,t)}async atomicWrite(e,t){let r=`${e}.tmp`;try{no(r,t,"utf8"),$n(r,e)}catch(o){try{Xe(r)&&no(r,"","utf8")}catch{}throw o}}generateConfigHash(e){try{return Rn("sha256").update(JSON.stringify(e)).digest("hex")}catch(t){return this.logger.warn(`[CacheManager] \u751F\u6210\u914D\u7F6E\u54C8\u5E0C\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),""}}validateCacheStructure(e){try{return e&&typeof e=="object"&&typeof e.version=="string"&&typeof e.mcpServers=="object"&&e.metadata&&typeof e.metadata=="object"&&typeof e.metadata.lastGlobalUpdate=="string"&&typeof e.metadata.totalWrites=="number"&&typeof e.metadata.createdAt=="string"}catch{return!1}}async getStats(){try{let e=await this.loadExistingCache();return{totalWrites:e.metadata.totalWrites,lastUpdate:e.metadata.lastGlobalUpdate,serverCount:Object.keys(e.mcpServers).length,cacheFileSize:Xe(this.cachePath)?oo(this.cachePath,"utf8").length:0}}catch(e){return this.logger.warn(`[CacheManager] \u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),null}}getFilePath(){return this.cachePath}async getAllCachedTools(){try{let e=await this.loadExistingCache(),t=[];for(let[r,o]of Object.entries(e.mcpServers))for(let n of o.tools)t.push({...n,name:`${r}__${n.name}`});return this.logger.debug(`[CacheManager] \u83B7\u53D6\u5230\u6240\u6709\u7F13\u5B58\u5DE5\u5177\uFF0C\u5171 ${t.length} \u4E2A`),t}catch(e){return this.logger.warn(`[CacheManager] \u83B7\u53D6\u6240\u6709\u7F13\u5B58\u5DE5\u5177\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),[]}}async writeCustomMCPResult(e,t,r,o="completed",n,s=3e5){try{let a=await this.loadExtendedCache(),l=de(e,t),h={result:r,timestamp:new Date().toISOString(),ttl:s,status:o,consumed:!1,taskId:n,retryCount:0};a.customMCPResults||(a.customMCPResults={}),a.customMCPResults[l]=h,await this.saveExtendedCache(a),this.logger.debug(`[CacheManager] \u5199\u5165CustomMCP\u7ED3\u679C\u7F13\u5B58: ${e}, \u72B6\u6001: ${o}`)}catch(a){this.logger.warn(`[CacheManager] \u5199\u5165CustomMCP\u7ED3\u679C\u7F13\u5B58\u5931\u8D25: ${a instanceof Error?a.message:String(a)}`)}}async readCustomMCPResult(e,t){try{let r=await this.loadExtendedCache(),o=de(e,t);if(!r.customMCPResults||!r.customMCPResults[o])return null;let n=r.customMCPResults[o],s=Date.now(),a=new Date(n.timestamp).getTime();return s-a>n.ttl?(this.logger.debug(`[CacheManager] \u7F13\u5B58\u5DF2\u8FC7\u671F: ${e}`),null):n}catch(r){return this.logger.warn(`[CacheManager] \u8BFB\u53D6CustomMCP\u7ED3\u679C\u7F13\u5B58\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),null}}async updateCustomMCPStatus(e,t,r,o,n){try{let s=await this.loadExtendedCache(),a=de(e,t);if(!s.customMCPResults||!s.customMCPResults[a])return!1;let l=s.customMCPResults[a],h=l.status;return l.status=r,l.timestamp=new Date().toISOString(),o&&(l.result=o),n&&r==="failed"&&(l.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${n}`}]},l.consumed=!0),r==="completed"&&(l.consumed=!1),await this.saveExtendedCache(s),this.logger.debug(`[CacheManager] \u66F4\u65B0\u7F13\u5B58\u72B6\u6001: ${e} ${h} -> ${r}`),!0}catch(s){return this.logger.warn(`[CacheManager] \u66F4\u65B0CustomMCP\u7F13\u5B58\u72B6\u6001\u5931\u8D25: ${s instanceof Error?s.message:String(s)}`),!1}}async markCustomMCPAsConsumed(e,t){try{let r=await this.loadExtendedCache(),o=de(e,t);if(!r.customMCPResults||!r.customMCPResults[o])return!1;let n=r.customMCPResults[o];return n.consumed||(n.consumed=!0,n.timestamp=new Date().toISOString(),await this.saveExtendedCache(r),this.logger.debug(`[CacheManager] \u6807\u8BB0\u7F13\u5B58\u4E3A\u5DF2\u6D88\u8D39: ${e}`)),!0}catch(r){return this.logger.warn(`[CacheManager] \u6807\u8BB0CustomMCP\u7F13\u5B58\u4E3A\u5DF2\u6D88\u8D39\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),!1}}async deleteCustomMCPResult(e,t){try{let r=await this.loadExtendedCache(),o=de(e,t);return!r.customMCPResults||!r.customMCPResults[o]?!1:(delete r.customMCPResults[o],await this.saveExtendedCache(r),this.logger.debug(`[CacheManager] \u5220\u9664\u7F13\u5B58\u6761\u76EE: ${e}`),!0)}catch(r){return this.logger.warn(`[CacheManager] \u5220\u9664CustomMCP\u7F13\u5B58\u6761\u76EE\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),!1}}async cleanupCustomMCPResults(){try{let e=await this.loadExtendedCache();if(!e.customMCPResults)return{cleaned:0,total:0};let t=Object.entries(e.customMCPResults),r=0;for(let[o,n]of t)Se(n)&&(delete e.customMCPResults[o],r++);return r>0&&(await this.saveExtendedCache(e),this.logger.info(`[CacheManager] \u6E05\u7406CustomMCP\u7F13\u5B58: ${r}/${t.length}`)),{cleaned:r,total:t.length}}catch(e){return this.logger.warn(`[CacheManager] \u6E05\u7406CustomMCP\u7F13\u5B58\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),{cleaned:0,total:0}}}async getCustomMCPStatistics(){try{let e=await this.loadExtendedCache();if(!e.customMCPResults)return{totalEntries:0,pendingTasks:0,completedTasks:0,failedTasks:0,consumedEntries:0,cacheHitRate:0,lastCleanupTime:new Date().toISOString(),memoryUsage:0};let t=Object.values(e.customMCPResults),r=t.length,o=t.filter(u=>u.status==="pending").length,n=t.filter(u=>u.status==="completed").length,s=t.filter(u=>u.status==="failed").length,a=t.filter(u=>u.consumed).length,l=n>0?a/n*100:0,h=JSON.stringify(e.customMCPResults).length;return{totalEntries:r,pendingTasks:o,completedTasks:n,failedTasks:s,consumedEntries:a,cacheHitRate:l,lastCleanupTime:new Date().toISOString(),memoryUsage:h}}catch(e){return this.logger.warn(`[CacheManager] \u83B7\u53D6CustomMCP\u7F13\u5B58\u7EDF\u8BA1\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),{totalEntries:0,pendingTasks:0,completedTasks:0,failedTasks:0,consumedEntries:0,cacheHitRate:0,lastCleanupTime:new Date().toISOString(),memoryUsage:0}}}async loadExtendedCache(){try{return await this.loadExistingCache()}catch(e){return this.logger.warn(`[CacheManager] \u52A0\u8F7D\u6269\u5C55\u7F13\u5B58\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),{version:this.CACHE_VERSION,mcpServers:{},metadata:{lastGlobalUpdate:this.formatTimestamp(),totalWrites:0,createdAt:this.formatTimestamp()},customMCPResults:{}}}}async saveExtendedCache(e){await this.saveCache(e)}startCleanupTimer(){this.cleanupInterval=setInterval(()=>{this.cleanupCustomMCPResults().catch(e=>{this.logger.warn(`[CacheManager] \u81EA\u52A8\u6E05\u7406\u5931\u8D25: ${e}`)})},this.CLEANUP_INTERVAL),this.logger.debug(`[CacheManager] \u542F\u52A8\u6E05\u7406\u5B9A\u65F6\u5668\uFF0C\u95F4\u9694: ${this.CLEANUP_INTERVAL}ms`)}stopCleanupTimer(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0,this.logger.debug("[CacheManager] \u505C\u6B62\u6E05\u7406\u5B9A\u65F6\u5668"))}cleanup(){this.stopCleanupTimer(),this.logger.debug("[CacheManager] \u6E05\u7406\u8D44\u6E90\u5B8C\u6210")}}});var vt,io=m(()=>{"use strict";S();Y();Yr();Qr();dt();ro();Ct();vt=class{static{c(this,"CustomMCPHandler")}logger;tools=new Map;cacheManager;cacheLifecycleManager;taskStateManager;TIMEOUT=me.TIMEOUT;CACHE_TTL=me.CACHE_TTL;CLEANUP_INTERVAL=me.CLEANUP_INTERVAL;cleanupTimer;activeTasks=new Map;constructor(e){this.logger=g,this.cacheManager=e||new ge,this.cacheLifecycleManager=new mt(this.logger),this.taskStateManager=new ft(this.logger),this.startCleanupTimer(),this.cacheLifecycleManager.startAutoCleanup()}initialize(e){this.logger.info("[CustomMCP] \u521D\u59CB\u5316 CustomMCP \u5904\u7406\u5668...");try{let t=e||d.getCustomMCPTools();this.tools.clear();for(let r of t)this.tools.set(r.name,r),this.logger.info(`[CustomMCP] \u5DF2\u52A0\u8F7D\u5DE5\u5177: ${r.name} (${r.handler.type})`);this.logger.info(`[CustomMCP] \u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.tools.size} \u4E2A\u5DE5\u5177`)}catch(t){throw this.logger.error("[CustomMCP] \u521D\u59CB\u5316\u5931\u8D25:",t),t}}getTools(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}))}hasTool(e){return this.tools.has(e)}getToolCount(){return this.tools.size}getToolNames(){return Array.from(this.tools.keys())}async callTool(e,t,r){let o=this.tools.get(e);if(!o)throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);this.logger.info(`[CustomMCP] \u8C03\u7528\u5DE5\u5177: ${e}`,{handler:o.handler.type,arguments:t});let n=await this.getCompletedResult(e,t);if(n)return this.logger.debug(`[CustomMCP] \u8FD4\u56DE\u5DF2\u5B8C\u6210\u7684\u4EFB\u52A1\u7ED3\u679C: ${e}`),await this.clearConsumedCache(e,t),n;try{let s=await Promise.race([this.executeToolWithBackgroundProcessing(e,t),this.createTimeoutPromise(e,t)]);return await this.cacheResult(e,t,s),s}catch(s){if(s instanceof Je){let a=await this.generateTaskId(e,t);return this.logger.info(`[CustomMCP] \u5DE5\u5177\u8D85\u65F6\uFF0C\u8FD4\u56DE\u53CB\u597D\u63D0\u793A: ${e}, taskId: ${a}`),eo(a,e)}throw s}}async executeToolWithBackgroundProcessing(e,t){let r=this.tools.get(e);if(!r)throw new Error(`\u5DE5\u5177\u4E0D\u5B58\u5728: ${e}`);let o=await this.generateTaskId(e,t);await this.markTaskAsPending(o,e,t);try{let n=await this.callToolByType(r,t);return await this.markTaskAsCompleted(o,n),n}catch(n){throw await this.markTaskAsFailed(o,n),n}}async createTimeoutPromise(e,t){return new Promise((r,o)=>{setTimeout(()=>{o(new Je(`\u5DE5\u5177\u8C03\u7528\u8D85\u65F6: ${e}`))},this.TIMEOUT)})}async getCompletedResult(e,t){try{let r=this.generateCacheKey(e,t),o=await this.loadExtendedCache();if(!o.customMCPResults||!o.customMCPResults[r])return null;let n=o.customMCPResults[r];return n.status==="completed"&&!n.consumed&&!ke(n.timestamp,n.ttl)?n.result:null}catch(r){return this.logger.warn(`[CustomMCP] \u83B7\u53D6\u7F13\u5B58\u5931\u8D25: ${r}`),null}}async callToolByType(e,t){switch(e.handler.type){case"proxy":return await this.callProxyTool(e,t);case"function":return await this.callFunctionTool(e,t);case"http":return await this.callHttpTool(e,t);case"script":return await this.callScriptTool(e,t);case"chain":return await this.callChainTool(e,t);case"mcp":return this.logger.error(`MCP \u7C7B\u578B\u5DE5\u5177 ${e.name} \u4E0D\u5E94\u8BE5\u7531 CustomMCPHandler \u5904\u7406`),{content:[{type:"text",text:"\u5185\u90E8\u9519\u8BEF\uFF1AMCP \u7C7B\u578B\u5DE5\u5177\u8DEF\u7531\u9519\u8BEF"}],isError:!0};default:throw new Error(`\u4E0D\u652F\u6301\u7684\u5904\u7406\u5668\u7C7B\u578B: ${e.handler.type}`)}}async callProxyTool(e,t){let r=e.handler;if(this.logger.info(`[CustomMCP] \u8C03\u7528\u4EE3\u7406\u5DE5\u5177: ${e.name}`,{platform:r.platform,config:r.config}),r.platform==="coze")return await this.callCozeWorkflow(e,t);throw new Error(`\u4E0D\u652F\u6301\u7684\u4EE3\u7406\u5E73\u53F0: ${r.platform}`)}async callCozeWorkflow(e,t){let o=e.handler.config;this.logger.info(`[CustomMCP] \u8C03\u7528 Coze \u5DE5\u4F5C\u6D41: ${e.name}`,{workflow_id:o.workflow_id,bot_id:o.bot_id});try{let n=this.buildCozeRequest(o,t),s=await this.sendCozeRequest(o,n);return this.logger.info(`[CustomMCP] Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u6210\u529F: ${e.name}`,{response:s}),this.processCozeResponse(e.name,s)}catch(n){return this.logger.error(`[CustomMCP] Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}buildCozeRequest(e,t){return{workflow_id:e.workflow_id,parameters:{...t}}}async sendCozeRequest(e,t){let r=e.base_url||"https://api.coze.cn",o="",n=d.getConfig().platforms?.coze?.token;if(!n)throw new Error("Coze Token \u914D\u7F6E\u4E0D\u5B58\u5728");if(e.workflow_id)o="/v1/workflow/run",t.workflow_id=e.workflow_id;else if(e.bot_id)o="/v3/chat",t.bot_id=e.bot_id;else throw new Error("Coze \u914D\u7F6E\u5FC5\u987B\u63D0\u4F9B workflow_id \u6216 bot_id");let s=`${r}${o}`,a=e.timeout||3e5,l={"Content-Type":"application/json",Authorization:`Bearer ${n}`,...e.headers};this.logger.debug(`[CustomMCP] \u53D1\u9001 Coze \u8BF7\u6C42\u5230: ${s}`,{headers:{...l},body:t});let h=new AbortController,u=setTimeout(()=>h.abort(),a);try{let p=await fetch(s,{method:"POST",headers:l,body:JSON.stringify(t)});if(clearTimeout(u),!p.ok){let T=await p.text();throw new Error(`Coze API \u8BF7\u6C42\u5931\u8D25 (${p.status}): ${T}`)}let C=await p.json();return this.logger.debug("[CustomMCP] Coze API \u54CD\u5E94:",C),C}catch(p){throw clearTimeout(u),p instanceof Error&&p.name==="AbortError"?new Error(`Coze API \u8BF7\u6C42\u8D85\u65F6 (${a}ms)`):p}}processCozeResponse(e,t){try{return t.data?{content:[{type:"text",text:t.data}],isError:!1}:{content:[{type:"text",text:JSON.stringify(t,null,2)}],isError:!1}}catch(r){return this.logger.error(`[CustomMCP] \u5904\u7406 Coze \u54CD\u5E94\u5931\u8D25: ${e}`,r),{content:[{type:"text",text:`\u5904\u7406\u54CD\u5E94\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async callFunctionTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528\u51FD\u6570\u5DE5\u5177: ${e.name}`,{module:r.module,function:r.function});try{let o=await this.loadModule(r.module),n=this.getFunction(o,r.function),s=await this.executeFunction(n,t,r);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s,null,2)}],isError:!1}}catch(o){return this.logger.error(`[CustomMCP] \u51FD\u6570\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`\u51FD\u6570\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async loadModule(e){try{let t=e;return!e.startsWith("/")&&!e.startsWith("file://")&&(t=new URL(e,`file://${process.cwd()}/`).href),this.logger.debug(`[CustomMCP] \u52A0\u8F7D\u6A21\u5757: ${t}`),await import(t)}catch(t){throw new Error(`\u65E0\u6CD5\u52A0\u8F7D\u6A21\u5757 ${e}: ${t instanceof Error?t.message:String(t)}`)}}getFunction(e,t){let r;if(e.default&&typeof e.default=="function"&&(t==="default"?r=e.default:e.default[t]&&typeof e.default[t]=="function"&&(r=e.default[t])),!r&&e[t]&&typeof e[t]=="function"&&(r=e[t]),!r)throw new Error(`\u5728\u6A21\u5757\u4E2D\u627E\u4E0D\u5230\u51FD\u6570: ${t}`);return r}async executeFunction(e,t,r){let o=r.timeout||3e4,n={...r.context,logger:this.logger,arguments:t},s=Promise.resolve().then(()=>e.length>1?e(t,n):e(t)),a=new Promise((l,h)=>{setTimeout(()=>h(new Error(`\u51FD\u6570\u6267\u884C\u8D85\u65F6 (${o}ms)`)),o)});return Promise.race([s,a])}async callHttpTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528 HTTP \u5DE5\u5177: ${e.name}`,{url:r.url,method:r.method||"POST"});try{let{url:o,requestOptions:n}=this.buildHttpRequest(r,t),s=await this.sendHttpRequest(o,n,r);return this.processHttpResponse(e.name,s,r)}catch(o){return this.logger.error(`[CustomMCP] HTTP \u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`HTTP \u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}buildHttpRequest(e,t){let r=e.method||"POST",o={"Content-Type":"application/json","User-Agent":"xiaozhi-client/1.0",...e.headers};if(e.auth)switch(e.auth.type){case"bearer":e.auth.token&&(o.Authorization=`Bearer ${e.auth.token}`);break;case"basic":if(e.auth.username&&e.auth.password){let l=btoa(`${e.auth.username}:${e.auth.password}`);o.Authorization=`Basic ${l}`}break;case"api_key":e.auth.api_key&&e.auth.api_key_header&&(o[e.auth.api_key_header]=e.auth.api_key);break}let n,s=e.url;if(r!=="GET")e.body_template?n=this.replaceTemplateVariables(e.body_template,t):n=JSON.stringify(t);else{let l=new URLSearchParams;for(let[u,p]of Object.entries(t))p!=null&&l.append(u,String(p));let h=l.toString();h&&(s+=(s.includes("?")?"&":"?")+h)}return{url:s,requestOptions:{method:r,headers:o,body:n}}}async sendHttpRequest(e,t,r){let o=r.timeout||3e4,n=r.retry_count||0,s=r.retry_delay||1e3,a=null;for(let l=0;l<=n;l++){try{this.logger.debug(`[CustomMCP] \u53D1\u9001 HTTP \u8BF7\u6C42 (\u5C1D\u8BD5 ${l+1}/${n+1}): ${e}`,{method:t.method,headers:t.headers});let h=new AbortController,u=setTimeout(()=>h.abort(),o),p=await fetch(e,{...t,signal:h.signal});if(clearTimeout(u),p.ok||l===n)return p;this.logger.warn(`[CustomMCP] HTTP \u8BF7\u6C42\u5931\u8D25 (${p.status}), \u5C06\u5728 ${s}ms \u540E\u91CD\u8BD5`),a=new Error(`HTTP \u8BF7\u6C42\u5931\u8D25: ${p.status} ${p.statusText}`)}catch(h){if(a=h instanceof Error?h:new Error(String(h)),h instanceof Error&&h.name==="AbortError"&&(a=new Error(`HTTP \u8BF7\u6C42\u8D85\u65F6 (${o}ms)`)),this.logger.warn(`[CustomMCP] HTTP \u8BF7\u6C42\u5F02\u5E38 (\u5C1D\u8BD5 ${l+1}/${n+1}):`,a.message),l===n)throw a}l<n&&await new Promise(h=>setTimeout(h,s))}throw a||new Error("HTTP \u8BF7\u6C42\u5931\u8D25")}async processHttpResponse(e,t,r){try{let o=t.headers.get("content-type")||"",n;if(o.includes("application/json")?n=await t.json():n=await t.text(),!t.ok)return{content:[{type:"text",text:`HTTP \u8BF7\u6C42\u5931\u8D25 (${t.status}): ${typeof n=="string"?n:JSON.stringify(n)}`}],isError:!0};let s=n;return r.response_mapping&&(s=this.extractResponseData(n,r.response_mapping)),{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s,null,2)}],isError:!1}}catch(o){return this.logger.error(`[CustomMCP] \u5904\u7406 HTTP \u54CD\u5E94\u5931\u8D25: ${e}`,o),{content:[{type:"text",text:`\u5904\u7406\u54CD\u5E94\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}replaceTemplateVariables(e,t){let r=e;for(let[o,n]of Object.entries(t)){let s=`{{${o}}}`,a=typeof n=="string"?n:JSON.stringify(n);r=r.replace(new RegExp(s.replace(/[{}]/g,"\\$&"),"g"),a)}return r}extractResponseData(e,t){if(!t)return e;let r=c((o,n)=>{if(!n)return o;let s=n.split("."),a=o;for(let l of s)if(a&&typeof a=="object"&&l in a)a=a[l];else return;return a},"extractByPath");if(t.success_path){let o=r(e,t.success_path);if(o!==void 0)return t.data_path?r(o,t.data_path):o}if(t.data_path){let o=r(e,t.data_path);if(o!==void 0)return o}return e}async callScriptTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528\u811A\u672C\u5DE5\u5177: ${e.name}`,{script:r.script.substring(0,100)+(r.script.length>100?"...":""),interpreter:r.interpreter||"node"});try{let o=await this.executeScript(r,t);return{content:[{type:"text",text:typeof o=="string"?o:JSON.stringify(o,null,2)}],isError:!1}}catch(o){return this.logger.error(`[CustomMCP] \u811A\u672C\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`\u811A\u672C\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async executeScript(e,t){let{spawn:r}=await import("child_process"),{promisify:o}=await import("util"),n=await import("fs/promises"),s=await import("path"),a=await import("os"),l=e.timeout||3e4,h=e.interpreter||"node",u,p=!1;try{if(e.script.includes(`
37
- `)||e.script.length>200){let b=await n.mkdtemp(s.join(a.tmpdir(),"xiaozhi-script-")),B=this.getScriptExtension(h);u=s.join(b,`script${B}`),await n.writeFile(u,e.script,"utf8"),p=!0}else{u=e.script;try{await n.access(u)}catch{throw new Error(`\u811A\u672C\u6587\u4EF6\u4E0D\u5B58\u5728: ${u}`)}}let C={...process.env,...e.env,XIAOZHI_ARGUMENTS:JSON.stringify(t)},T=this.buildScriptCommand(h,u);return this.logger.debug(`[CustomMCP] \u6267\u884C\u811A\u672C\u547D\u4EE4: ${T.join(" ")}`),new Promise((b,B)=>{let Z=r(T[0],T.slice(1),{env:C,stdio:["pipe","pipe","pipe"]}),$="",tt="";Z.stdout?.on("data",ue=>{$+=ue.toString()}),Z.stderr?.on("data",ue=>{tt+=ue.toString()});let rt=setTimeout(()=>{Z.kill("SIGTERM"),B(new Error(`\u811A\u672C\u6267\u884C\u8D85\u65F6 (${l}ms)`))},l);Z.on("close",ue=>{clearTimeout(rt),ue===0?b($.trim()):B(new Error(`\u811A\u672C\u6267\u884C\u5931\u8D25 (\u9000\u51FA\u7801: ${ue}): ${tt.trim()}`))}),Z.on("error",ue=>{clearTimeout(rt),B(new Error(`\u811A\u672C\u6267\u884C\u9519\u8BEF: ${ue.message}`))}),t&&Object.keys(t).length>0&&(Z.stdin?.write(JSON.stringify(t)),Z.stdin?.end())})}finally{if(p&&u)try{await n.unlink(u),await n.rmdir(s.dirname(u))}catch{}}}getScriptExtension(e){switch(e){case"node":return".js";case"python":return".py";case"bash":return".sh";default:return".txt"}}buildScriptCommand(e,t){switch(e){case"node":return["node",t];case"python":return["python3",t];case"bash":return["bash",t];default:throw new Error(`\u4E0D\u652F\u6301\u7684\u811A\u672C\u89E3\u91CA\u5668: ${e}`)}}async callChainTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528\u94FE\u5F0F\u5DE5\u5177: ${e.name}`,{tools:r.tools,mode:r.mode,error_handling:r.error_handling});try{let o;r.mode==="sequential"?o=await this.executeSequentialChain(r,t):o=await this.executeParallelChain(r,t);let n=o.flatMap(a=>a.content),s=o.some(a=>a.isError);return{content:n,isError:s}}catch(o){return this.logger.error(`[CustomMCP] \u94FE\u5F0F\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`\u94FE\u5F0F\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}delay(e){return new Promise(t=>setTimeout(t,e))}getToolInfo(e){return this.tools.get(e)}async executeSequentialChain(e,t){let r=[],o=t;for(let n of e.tools)try{this.logger.debug(`[CustomMCP] \u6267\u884C\u94FE\u5F0F\u5DE5\u5177\u4E2D\u7684: ${n}`);let s=await this.callToolRecursive(n,o);if(r.push(s),s.isError){if(e.error_handling==="stop")break;if(e.error_handling==="retry"){this.logger.warn(`[CustomMCP] \u5DE5\u5177 ${n} \u6267\u884C\u5931\u8D25\uFF0C\u5C1D\u8BD5\u91CD\u8BD5`);let a=await this.callToolRecursive(n,o);if(r[r.length-1]=a,a.isError)break}}if(!s.isError&&s.content.length>0){let a=s.content.filter(l=>l.type==="text").map(l=>l.text).join(`
38
- `);if(a)try{o=JSON.parse(a)}catch{o={input:a,...t}}}}catch(s){let a={content:[{type:"text",text:`\u5DE5\u5177 ${n} \u6267\u884C\u5F02\u5E38: ${s instanceof Error?s.message:String(s)}`}],isError:!0};if(r.push(a),e.error_handling==="stop")break}return r}async executeParallelChain(e,t){let r=e.tools.map(async o=>{try{return this.logger.debug(`[CustomMCP] \u5E76\u884C\u6267\u884C\u94FE\u5F0F\u5DE5\u5177\u4E2D\u7684: ${o}`),await this.callToolRecursive(o,t)}catch(n){return{content:[{type:"text",text:`\u5DE5\u5177 ${o} \u6267\u884C\u5F02\u5E38: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}});return Promise.all(r)}async callToolRecursive(e,t){if(this.tools.get(e))return this.callTool(e,t);throw new Error(`\u94FE\u5F0F\u5DE5\u5177\u4E2D\u5F15\u7528\u7684\u5DE5\u5177 ${e} \u4E0D\u5B58\u5728\u4E8E\u5F53\u524D CustomMCP \u5DE5\u5177\u96C6\u4E2D`)}async clearConsumedCache(e,t){try{let r=this.generateCacheKey(e,t),o=await this.loadExtendedCache();if(o.customMCPResults?.[r]){o.customMCPResults[r].consumed=!0;let n=o.customMCPResults[r];Se(n)&&delete o.customMCPResults[r],await this.saveCache(o),this.logger.debug(`[CustomMCP] \u6E05\u7406\u5DF2\u6D88\u8D39\u7F13\u5B58: ${r}`)}}catch(r){this.logger.warn(`[CustomMCP] \u6E05\u7406\u7F13\u5B58\u5931\u8D25: ${r}`)}}async generateTaskId(e,t){return this.taskStateManager.generateTaskId(e,t)}async markTaskAsPending(e,t,r){try{let o=this.generateCacheKey(t,r),n={result:{content:[{type:"text",text:"\u5904\u7406\u4E2D..."}]},timestamp:new Date().toISOString(),ttl:this.CACHE_TTL,status:"pending",consumed:!1,taskId:e,retryCount:0};await this.updateCacheWithResult(o,n),this.taskStateManager.markTaskAsPending(e,t,r),this.activeTasks.set(e,{taskId:e,status:"pending",startTime:Date.now()}),this.logger.debug(`[CustomMCP] \u6807\u8BB0\u4EFB\u52A1\u4E3A\u5904\u7406\u4E2D: ${e}`)}catch(o){this.logger.warn(`[CustomMCP] \u6807\u8BB0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${o}`)}}async markTaskAsCompleted(e,t){try{let r=this.activeTasks.get(e);r&&(r.status="completed",r.endTime=new Date().toISOString(),r.result=t);let o=await this.loadExtendedCache();for(let[n,s]of Object.entries(o.customMCPResults||{}))if(s.taskId===e){s.status="completed",s.result=t,s.timestamp=new Date().toISOString(),s.consumed=!1;break}await this.saveCache(o),this.taskStateManager.markTaskAsCompleted(e,t),this.logger.debug(`[CustomMCP] \u6807\u8BB0\u4EFB\u52A1\u4E3A\u5DF2\u5B8C\u6210: ${e}`)}catch(r){this.logger.warn(`[CustomMCP] \u66F4\u65B0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${r}`)}}async markTaskAsFailed(e,t){try{let r=await this.loadExtendedCache();for(let[n,s]of Object.entries(r.customMCPResults||{}))if(s.taskId===e){s.status="failed",s.result={content:[{type:"text",text:`\u4EFB\u52A1\u5931\u8D25: ${t.message}`}]},s.timestamp=new Date().toISOString(),s.consumed=!0;break}await this.saveCache(r),this.taskStateManager.markTaskAsFailed(e,t.message);let o=this.activeTasks.get(e);o&&(o.status="failed",o.endTime=new Date().toISOString(),o.error=t.message),this.logger.debug(`[CustomMCP] \u6807\u8BB0\u4EFB\u52A1\u4E3A\u5931\u8D25: ${e}`)}catch(r){this.logger.warn(`[CustomMCP] \u66F4\u65B0\u4EFB\u52A1\u72B6\u6001\u5931\u8D25: ${r}`)}}startCleanupTimer(){this.cleanupTimer=setInterval(()=>{this.cleanupExpiredCache().catch(e=>{this.logger.warn(`[CustomMCP] \u7F13\u5B58\u6E05\u7406\u5931\u8D25: ${e}`)})},this.CLEANUP_INTERVAL),this.logger.info(`[CustomMCP] \u542F\u52A8\u7F13\u5B58\u6E05\u7406\u5B9A\u65F6\u5668\uFF0C\u95F4\u9694: ${this.CLEANUP_INTERVAL}ms`)}async cleanupExpiredCache(){try{let e=await this.loadExtendedCache(),t=!1,r=0;for(let[o,n]of Object.entries(e.customMCPResults||{}))Se(n)&&(e.customMCPResults?.[o]&&delete e.customMCPResults[o],t=!0,r++,n.taskId&&this.activeTasks.delete(n.taskId));t&&(await this.saveCache(e),this.logger.debug(`[CustomMCP] \u6E05\u7406\u8FC7\u671F\u7F13\u5B58\u5B8C\u6210\uFF0C\u6E05\u7406\u4E86 ${r} \u4E2A\u6761\u76EE`))}catch(e){this.logger.warn(`[CustomMCP] \u6E05\u7406\u8FC7\u671F\u7F13\u5B58\u5931\u8D25: ${e}`)}}generateCacheKey(e,t){return de(e,t)}async loadExtendedCache(){try{return await this.cacheManager.loadExistingCache()}catch{return{version:"1.0.0",mcpServers:{},metadata:{lastGlobalUpdate:new Date().toISOString(),totalWrites:0,createdAt:new Date().toISOString()},customMCPResults:{}}}}async updateCacheWithResult(e,t){try{let r=await this.loadExtendedCache();r.customMCPResults||(r.customMCPResults={}),r.customMCPResults[e]=t,await this.saveCache(r)}catch(r){this.logger.warn(`[CustomMCP] \u66F4\u65B0\u7F13\u5B58\u5931\u8D25: ${r}`)}}async cacheResult(e,t,r){try{let o=this.generateCacheKey(e,t),n={result:r,timestamp:new Date().toISOString(),ttl:this.CACHE_TTL,status:"completed",consumed:!1,retryCount:0};await this.updateCacheWithResult(o,n),this.logger.debug(`[CustomMCP] \u7F13\u5B58\u5DE5\u5177\u7ED3\u679C: ${e}`)}catch(o){this.logger.warn(`[CustomMCP] \u7F13\u5B58\u7ED3\u679C\u5931\u8D25: ${o}`)}}async saveCache(e){try{await this.cacheManager.saveCache(e)}catch(t){this.logger.warn(`[CustomMCP] \u4FDD\u5B58\u7F13\u5B58\u5931\u8D25: ${t}`)}}stopCleanupTimer(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0,this.logger.info("[CustomMCP] \u505C\u6B62\u7F13\u5B58\u6E05\u7406\u5B9A\u65F6\u5668"))}cleanup(){this.logger.info("[CustomMCP] \u6E05\u7406 CustomMCP \u5904\u7406\u5668\u8D44\u6E90"),this.stopCleanupTimer(),this.cacheLifecycleManager.stopAutoCleanup(),this.cacheLifecycleManager.cleanup(),this.taskStateManager.cleanup(),this.cacheManager.cleanup(),this.tools.clear(),this.activeTasks.clear()}getCacheLifecycleManager(){return this.cacheLifecycleManager}getTaskStateManager(){return this.taskStateManager}async getCacheStatistics(){return this.cacheManager.getCustomMCPStatistics()}getTaskStatistics(){return this.taskStateManager.getTaskStatistics()}getTaskStatus(e){return this.taskStateManager.getTaskStatus(e)}validateTaskId(e){return this.taskStateManager.validateTaskId(e)}restartStalledTasks(e=3e4){return this.taskStateManager.restartStalledTasks(e)}async manualCleanupCache(){return this.cacheManager.cleanupCustomMCPResults()}async validateSystemIntegrity(){let e=await this.cacheManager.loadExtendedCache(),t=this.cacheLifecycleManager.validateCacheIntegrity(e),r=this.taskStateManager.validateTaskIntegrity();return{cacheValid:t.isValid,taskValid:r.isValid,issues:[...t.issues,...r.issues]}}}});import{SSEClientTransport as ao}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as An}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as kn}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{EventSource as Dn}from"eventsource";function Nn(){return g}function _n(i){switch(Nn().info(`[TransportFactory] \u521B\u5EFA ${i.type} transport for ${i.name}`),i.type){case"stdio":return Ln(i);case"sse":return Hn(i);case"modelscope-sse":return zn(i);case"streamable-http":return jn(i);default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function Ln(i){if(!i.command)throw new Error("stdio transport \u9700\u8981 command \u914D\u7F6E");return new An({command:i.command,args:i.args||[],env:i.env})}function Hn(i){if(!i.url)throw new Error("SSE transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=Un(i);return new ao(e,t)}function zn(i){if(!i.url)throw new Error("ModelScope SSE transport \u9700\u8981 URL \u914D\u7F6E");if(!i.apiKey)throw new Error("ModelScope SSE transport \u9700\u8981 apiKey \u914D\u7F6E");let e=new URL(i.url),t=Fn(i);return new ao(e,t)}function jn(i){if(!i.url)throw new Error("StreamableHTTP transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=Wn(i);return new kn(e,t)}function Un(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function Fn(i){let e=i.apiKey;return i.customSSEOptions?i.customSSEOptions:{eventSourceInit:{fetch:c(async(t,r)=>{let o={...r?.headers,Authorization:`Bearer ${e}`};return fetch(t,{...r,headers:o})},"fetch")},requestInit:{headers:{Authorization:`Bearer ${e}`,...i.headers}}}}function Wn(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function Vn(i){if(!i.name||typeof i.name!="string")throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(!i.type)throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B type \u5B57\u6BB5");switch(i.type){case"stdio":if(!i.command)throw new Error("stdio \u7C7B\u578B\u9700\u8981 command \u5B57\u6BB5");break;case"sse":case"streamable-http":if(!i.url)throw new Error(`${i.type} \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5`);break;case"modelscope-sse":if(!i.url)throw new Error("modelscope-sse \u7C7B\u578B\u9700\u8981 url \u5B57\u6BB5");if(!i.apiKey)throw new Error("modelscope-sse \u7C7B\u578B\u9700\u8981 apiKey \u5B57\u6BB5\u3002\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E modelscope.apiKey \u6216\u786E\u4FDD\u670D\u52A1\u914D\u7F6E\u5305\u542B apiKey");break;default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function Bn(){return["stdio","sse","modelscope-sse","streamable-http"]}var cr,co=m(()=>{"use strict";S();St();typeof global<"u"&&!global.EventSource&&(global.EventSource=Dn);c(Nn,"getLogger");c(_n,"createTransport");c(Ln,"createStdioTransport");c(Hn,"createSSETransport");c(zn,"createModelScopeSSETransport");c(jn,"createStreamableHTTPTransport");c(Un,"createSSEOptions");c(Fn,"createModelScopeSSEOptions");c(Wn,"createStreamableHTTPOptions");c(Vn,"validateConfig");c(Bn,"getSupportedTypes");cr={create:_n,validateConfig:Vn,getSupportedTypes:Bn}});import{Client as qn}from"@modelcontextprotocol/sdk/client/index.js";var Ke,yt,St=m(()=>{"use strict";S();co();Ke=(o=>(o.STDIO="stdio",o.SSE="sse",o.STREAMABLE_HTTP="streamable-http",o.MODELSCOPE_SSE="modelscope-sse",o))(Ke||{}),yt=class{static{c(this,"MCPService")}config;client=null;transport=null;tools=new Map;connectionState="disconnected";reconnectOptions;reconnectState;logger;connectionTimeout=null;initialized=!1;pingOptions;pingTimer=null;pingFailureCount=0;lastPingTime=null;isPinging=!1;constructor(e,t){this.config=e,this.logger=g,this.validateConfig(),this.reconnectOptions={enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:1e4,jitter:!0,...t?.reconnect,...e.reconnect},this.pingOptions={enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3,...e.ping},this.reconnectState={attempts:0,nextInterval:this.reconnectOptions.initialInterval,timer:null,lastError:null,isManualDisconnect:!1}}logWithTag(e,t,...r){let o=`[MCP-${this.config.name}] ${t}`;this.logger[e](o,...r)}validateConfig(){cr.validateConfig(this.config)}async connect(){if(this.connectionState==="connecting")throw new Error("\u8FDE\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u8FDE\u63A5\u5B8C\u6210");return this.cleanupConnection(),this.reconnectState.isManualDisconnect=!1,this.attemptConnection()}async attemptConnection(){return this.connectionState="connecting",this.logWithTag("info",`\u6B63\u5728\u8FDE\u63A5 MCP \u670D\u52A1: ${this.config.name} (\u5C1D\u8BD5 ${this.reconnectState.attempts+1}/${this.reconnectOptions.maxAttempts})`),new Promise((e,t)=>{this.connectionTimeout=setTimeout(()=>{let r=new Error(`\u8FDE\u63A5\u8D85\u65F6 (${this.reconnectOptions.timeout}ms)`);this.handleConnectionError(r),t(r)},this.reconnectOptions.timeout);try{this.client=new qn({name:`xiaozhi-${this.config.name}-client`,version:"1.0.0"},{capabilities:{tools:{}}}),this.transport=cr.create(this.config),this.client.connect(this.transport).then(async()=>{this.handleConnectionSuccess(),await this.refreshTools(),e()}).catch(r=>{this.handleConnectionError(r),t(r)})}catch(r){this.handleConnectionError(r),t(r)}})}handleConnectionSuccess(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.connectionState="connected",this.initialized=!0,this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.lastError=null,this.resetPingState(),this.logWithTag("info",`MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5\u5DF2\u5EFA\u7ACB`),this.startPingMonitoring()}handleConnectionError(e){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.reconnectState.lastError=e,this.logger.error(`MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5\u9519\u8BEF:`,e.message),this.cleanupConnection(),this.shouldReconnect()?this.scheduleReconnect():(this.connectionState="failed",this.logger.warn(`${this.config.name} \u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8FDE\u6B21\u6570 (${this.reconnectOptions.maxAttempts})\uFF0C\u505C\u6B62\u91CD\u8FDE`))}shouldReconnect(){return this.reconnectOptions.enabled&&this.reconnectState.attempts<this.reconnectOptions.maxAttempts&&!this.reconnectState.isManualDisconnect}scheduleReconnect(){this.connectionState="reconnecting",this.reconnectState.attempts++,this.calculateNextInterval(),this.logger.info(`${this.config.name} \u5C06\u5728 ${this.reconnectState.nextInterval}ms \u540E\u8FDB\u884C\u7B2C ${this.reconnectState.attempts} \u6B21\u91CD\u8FDE`),this.reconnectState.timer&&clearTimeout(this.reconnectState.timer),this.reconnectState.timer=setTimeout(async()=>{try{await this.attemptConnection()}catch{}},this.reconnectState.nextInterval)}calculateNextInterval(){let e;switch(this.reconnectOptions.backoffStrategy){case"fixed":e=this.reconnectOptions.initialInterval;break;case"linear":e=this.reconnectOptions.initialInterval+this.reconnectState.attempts*this.reconnectOptions.backoffMultiplier*1e3;break;case"exponential":e=this.reconnectOptions.initialInterval*this.reconnectOptions.backoffMultiplier**(this.reconnectState.attempts-1);break;default:e=this.reconnectOptions.initialInterval}if(e=Math.min(e,this.reconnectOptions.maxInterval),this.reconnectOptions.jitter){let t=e*.1,r=(Math.random()-.5)*2*t;e+=r}this.reconnectState.nextInterval=Math.max(e,1e3)}cleanupConnection(){if(this.stopPingMonitoring(),this.client){try{this.client.close().catch(()=>{})}catch{}this.client=null}this.transport=null,this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.initialized=!1}stopReconnect(){this.reconnectState.timer&&(clearTimeout(this.reconnectState.timer),this.reconnectState.timer=null)}async refreshTools(){if(!this.client)throw new Error("\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316");try{let t=(await this.client.listTools()).tools||[];this.tools.clear();for(let r of t)this.tools.set(r.name,r);this.logger.info(`${this.config.name} \u670D\u52A1\u52A0\u8F7D\u4E86 ${t.length} \u4E2A\u5DE5\u5177: ${t.map(r=>r.name).join(", ")}`)}catch(e){throw this.logger.error(`${this.config.name} \u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25:`,e instanceof Error?e.message:String(e)),e}}async disconnect(){this.logger.info(`\u4E3B\u52A8\u65AD\u5F00 MCP \u670D\u52A1 ${this.config.name} \u8FDE\u63A5`),this.reconnectState.isManualDisconnect=!0,this.stopPingMonitoring(),this.stopReconnect(),this.cleanupConnection(),this.connectionState="disconnected"}async reconnect(){this.logger.info(`\u624B\u52A8\u91CD\u8FDE MCP \u670D\u52A1 ${this.config.name}`),this.stopReconnect(),this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.isManualDisconnect=!1,this.cleanupConnection(),await this.connect()}getTools(){return Array.from(this.tools.values())}async callTool(e,t){if(!this.client)throw new Error(`\u670D\u52A1 ${this.config.name} \u672A\u8FDE\u63A5`);if(!this.tools.has(e))throw new Error(`\u5DE5\u5177 ${e} \u5728\u670D\u52A1 ${this.config.name} \u4E2D\u4E0D\u5B58\u5728`);this.logger.info(`\u8C03\u7528 ${this.config.name} \u670D\u52A1\u7684\u5DE5\u5177 ${e}\uFF0C\u53C2\u6570:`,JSON.stringify(t));try{let r=await this.client.callTool({name:e,arguments:t||{}});return this.logger.info(`\u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F\uFF0C\u7ED3\u679C:`,`${JSON.stringify(r).substring(0,500)}...`),r}catch(r){throw this.logger.error(`\u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,r instanceof Error?r.message:String(r)),r}}getConfig(){return this.config}getStatus(){return{name:this.config.name,connected:this.connectionState==="connected",initialized:this.initialized,transportType:this.config.type,toolCount:this.tools.size,lastError:this.reconnectState.lastError?.message,reconnectAttempts:this.reconnectState.attempts,connectionState:this.connectionState,pingEnabled:this.pingOptions.enabled,lastPingTime:this.lastPingTime||void 0,pingFailureCount:this.pingFailureCount,isPinging:this.isPinging}}isConnected(){return this.connectionState==="connected"&&this.initialized}enableReconnect(){this.reconnectOptions.enabled=!0,this.logger.info(`${this.config.name} \u81EA\u52A8\u91CD\u8FDE\u5DF2\u542F\u7528`)}disableReconnect(){this.reconnectOptions.enabled=!1,this.stopReconnect(),this.logger.info(`${this.config.name} \u81EA\u52A8\u91CD\u8FDE\u5DF2\u7981\u7528`)}updateReconnectOptions(e){this.reconnectOptions={...this.reconnectOptions,...e},this.logger.info(`${this.config.name} \u91CD\u8FDE\u914D\u7F6E\u5DF2\u66F4\u65B0`,e)}getReconnectOptions(){return{...this.reconnectOptions}}resetReconnectState(){this.stopReconnect(),this.reconnectState.attempts=0,this.reconnectState.nextInterval=this.reconnectOptions.initialInterval,this.reconnectState.lastError=null,this.logger.info(`${this.config.name} \u91CD\u8FDE\u72B6\u6001\u5DF2\u91CD\u7F6E`)}startPingMonitoring(){!this.pingOptions.enabled||this.pingTimer||!this.isConnected()||(this.logger.info(`${this.config.name} \u542F\u52A8ping\u76D1\u63A7\uFF0C\u95F4\u9694: ${this.pingOptions.interval}ms`),setTimeout(()=>{this.isConnected()&&!this.pingTimer&&(this.pingTimer=setInterval(()=>{this.performPing()},this.pingOptions.interval))},this.pingOptions.startDelay))}stopPingMonitoring(){this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null,this.logger.debug(`${this.config.name} \u505C\u6B62ping\u76D1\u63A7`))}async performPing(){if(!this.client||this.isPinging||!this.isConnected())return;this.isPinging=!0;let e=performance.now();try{this.logger.debug(`${this.config.name} \u53D1\u9001ping\u8BF7\u6C42\uFF08\u901A\u8FC7listTools\u68C0\u6D4B\u8FDE\u63A5\uFF09`);let t=this.client.listTools(),r=new Promise((n,s)=>{setTimeout(()=>{s(new Error(`Ping\u8D85\u65F6 (${this.pingOptions.timeout}ms)`))},this.pingOptions.timeout)});await Promise.race([t,r]);let o=performance.now()-e;this.handlePingSuccess(o)}catch(t){let r=performance.now()-e;this.handlePingFailure(t,r)}finally{this.isPinging=!1}}handlePingSuccess(e){this.pingFailureCount=0,this.lastPingTime=new Date,this.logger.debug(`${this.config.name} ping\u6210\u529F\uFF0C\u5EF6\u8FDF: ${e.toFixed(2)}ms`)}handlePingFailure(e,t){if(this.pingFailureCount++,this.logger.warn(`${this.config.name} ping\u5931\u8D25 (${this.pingFailureCount}/${this.pingOptions.maxFailures})\uFF0C\u5EF6\u8FDF: ${t.toFixed(2)}ms\uFF0C\u9519\u8BEF: ${e.message}`),this.pingFailureCount>=this.pingOptions.maxFailures){this.logger.error(`${this.config.name} \u8FDE\u7EEDping\u5931\u8D25\u8FBE\u5230\u9608\u503C\uFF0C\u89E6\u53D1\u91CD\u8FDE\u673A\u5236`),this.stopPingMonitoring();let r=new Error(`Ping\u68C0\u6D4B\u5931\u8D25\uFF0C\u8FDE\u7EED\u5931\u8D25${this.pingFailureCount}\u6B21\uFF0C\u8FDE\u63A5\u53EF\u80FD\u5DF2\u65AD\u5F00`);this.handleConnectionError(r)}}resetPingState(){this.pingFailureCount=0,this.lastPingTime=null,this.isPinging=!1}enablePing(){this.pingOptions.enabled=!0,this.logger.info(`${this.config.name} ping\u76D1\u63A7\u5DF2\u542F\u7528`),this.isConnected()&&this.startPingMonitoring()}disablePing(){this.pingOptions.enabled=!1,this.stopPingMonitoring(),this.logger.info(`${this.config.name} ping\u76D1\u63A7\u5DF2\u7981\u7528`)}updatePingOptions(e){let t=this.pingOptions.enabled;this.pingOptions={...this.pingOptions,...e},this.logger.info(`${this.config.name} ping\u914D\u7F6E\u5DF2\u66F4\u65B0`,e),t!==this.pingOptions.enabled&&(this.pingOptions.enabled&&this.isConnected()?this.startPingMonitoring():this.pingOptions.enabled||this.stopPingMonitoring())}getPingOptions(){return{...this.pingOptions}}}});var Tt,lo=m(()=>{"use strict";S();Tt=class{static{c(this,"ToolSyncManager")}configManager;logger;syncLocks=new Map;constructor(e,t=g){this.configManager=e,this.logger=t.withTag("ToolSync")}async syncToolsAfterConnection(e,t){if(this.syncLocks.has(e)){this.logger.debug(`\u670D\u52A1 ${e} \u6B63\u5728\u540C\u6B65\u4E2D\uFF0C\u8DF3\u8FC7`);return}let r=this.doSyncTools(e,t).finally(()=>{this.syncLocks.delete(e)});this.syncLocks.set(e,r),await r}async doSyncTools(e,t){try{this.logger.info(`\u5F00\u59CB\u540C\u6B65\u670D\u52A1 ${e} \u7684\u5DE5\u5177`);let r=this.configManager.getServerToolsConfig(e);if(!r){this.logger.debug(`\u670D\u52A1 ${e} \u65E0 mcpServerConfig \u914D\u7F6E\uFF0C\u8DF3\u8FC7\u540C\u6B65`);return}let o=this.getEnabledTools(r,t);if(o.length===0){this.logger.debug(`\u670D\u52A1 ${e} \u65E0\u542F\u7528\u5DE5\u5177\uFF0C\u8DF3\u8FC7\u540C\u6B65`);return}let n=this.configManager.getCustomMCPTools(),s=new Set(n.map(l=>l.name)),a=o.filter(l=>!s.has(`${e}__${l.name}`));if(a.length===0){this.logger.info(`\u670D\u52A1 ${e} \u7684\u542F\u7528\u5DE5\u5177\u5DF2\u5B58\u5728\u4E8E customMCP \u4E2D\uFF0C\u8DF3\u8FC7\u540C\u6B65`);return}await this.addToolsToCustomMCP(e,a),this.logger.info(`\u6210\u529F\u540C\u6B65\u670D\u52A1 ${e} \u7684 ${a.length} \u4E2A\u5DE5\u5177\u5230 customMCP`)}catch(r){this.logger.error(`\u540C\u6B65\u670D\u52A1 ${e} \u5DE5\u5177\u5931\u8D25:`,r),this.recordSyncError(e,r)}}getEnabledTools(e,t){let r=[];for(let o of t){let n=e[o.name];n&&n.enable!==!1&&r.push(o)}return r}async addToolsToCustomMCP(e,t){let r=t.map(o=>({name:`${e}__${o.name}`,description:o.description||"",inputSchema:o.inputSchema||{},handler:{type:"mcp",config:{serviceName:e,toolName:o.name}}}));await this.configManager.addCustomMCPTools(r),await this.syncToolStats(e,t)}recordSyncError(e,t){let r={serviceName:e,error:t instanceof Error?t.message:String(t),timestamp:new Date().toISOString(),type:t instanceof Error?t.constructor.name:"UnknownError"};this.logger.error("\u540C\u6B65\u9519\u8BEF\u8BB0\u5F55:",r)}getSyncLocks(){return Array.from(this.syncLocks.keys())}clearSyncLocks(){this.syncLocks.clear(),this.logger.debug("\u5DF2\u6E05\u7406\u6240\u6709\u540C\u6B65\u9501")}async syncToolStats(e,t){try{let r=this.configManager.getServerToolsConfig(e);if(!r){this.logger.debug(`\u670D\u52A1 ${e} \u65E0 mcpServerConfig \u914D\u7F6E\uFF0C\u8DF3\u8FC7\u7EDF\u8BA1\u4FE1\u606F\u540C\u6B65`);return}let o=this.configManager.getCustomMCPTools(),n=new Map(o.map(s=>[s.name,s]));for(let s of t){let a=`${e}__${s.name}`,l=n.get(a),h=r[s.name];if(l&&h&&(!l.stats||!l.stats.usageCount&&!l.stats.lastUsedTime)){let u={};h.usageCount!==void 0&&(u.usageCount=h.usageCount),h.lastUsedTime&&(u.lastUsedTime=h.lastUsedTime),Object.keys(u).length>0&&(await this.updateCustomMCPToolStats(a,u),this.logger.debug(`\u5DF2\u540C\u6B65\u5DE5\u5177 ${a} \u7684\u7EDF\u8BA1\u4FE1\u606F: ${JSON.stringify(u)}`))}}}catch(r){this.logger.error(`\u540C\u6B65\u670D\u52A1 ${e} \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,r instanceof Error?r.message:String(r))}}async updateCustomMCPToolStats(e,t){try{let r=this.configManager.getCustomMCPTools(),o=r.findIndex(a=>a.name===e);if(o===-1){this.logger.warn(`\u5DE5\u5177 ${e} \u4E0D\u5B58\u5728\u4E8E customMCP \u4E2D`);return}let n=[...r],s=n[o];s.stats||(s.stats={}),t.usageCount!==void 0&&(s.stats.usageCount=t.usageCount),t.lastUsedTime!==void 0&&(s.stats.lastUsedTime=t.lastUsedTime),await this.configManager.updateCustomMCPTools(n)}catch(r){throw this.logger.error(`\u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,r instanceof Error?r.message:String(r)),r}}}});var Ze,go,lr=m(()=>{"use strict";S();Y();io();Ct();St();lo();Ze=class{static{c(this,"MCPServiceManager")}services=new Map;configs={};logger;tools=new Map;customMCPHandler;cacheManager;toolSyncManager;constructor(e){this.logger=g,this.configs=e||{};let r=process.env.NODE_ENV==="test"||process.env.VITEST==="true"?`/tmp/xiaozhi-test-${Date.now()}-${Math.random().toString(36).substring(2,11)}/xiaozhi.cache.json`:void 0;this.cacheManager=new ge(r),this.customMCPHandler=new vt,this.toolSyncManager=new Tt(d,this.logger)}async startAllServices(){this.logger.info("[MCPManager] \u6B63\u5728\u542F\u52A8\u6240\u6709 MCP \u670D\u52A1...");try{this.customMCPHandler.initialize(),this.logger.info("[MCPManager] CustomMCP \u5904\u7406\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(t){this.logger.error("[MCPManager] CustomMCP \u5904\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",t)}let e=Object.entries(this.configs);if(e.length===0){this.logger.warn("[MCPManager] \u6CA1\u6709\u914D\u7F6E\u4EFB\u4F55 MCP \u670D\u52A1\uFF0C\u8BF7\u4F7F\u7528 addServiceConfig() \u6DFB\u52A0\u670D\u52A1\u914D\u7F6E");return}for(let[t]of e)await this.startService(t);this.logger.info("[MCPManager] \u6240\u6709 MCP \u670D\u52A1\u542F\u52A8\u5B8C\u6210")}async startService(e){this.logger.info(`[MCPManager] \u542F\u52A8 MCP \u670D\u52A1: ${e}`);let t=this.configs[e];if(!t)throw new Error(`\u672A\u627E\u5230\u670D\u52A1\u914D\u7F6E: ${e}`);try{this.services.has(e)&&await this.stopService(e);let r=new yt(t);await r.connect(),this.services.set(e,r),await this.refreshToolsCache();let o=r.getTools();await this.toolSyncManager.syncToolsAfterConnection(e,o),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u542F\u52A8\u6210\u529F\uFF0C\u52A0\u8F7D\u4E86 ${o.length} \u4E2A\u5DE5\u5177:`,o.map(n=>n.name).join(", "))}catch(r){throw this.logger.error(`[MCPManager] \u542F\u52A8 ${e} \u670D\u52A1\u5931\u8D25:`,r.message),r}}async stopService(e){this.logger.info(`[MCPManager] \u505C\u6B62 MCP \u670D\u52A1: ${e}`);let t=this.services.get(e);if(!t){this.logger.warn(`[MCPManager] \u670D\u52A1 ${e} \u4E0D\u5B58\u5728\u6216\u672A\u542F\u52A8`);return}try{await t.disconnect(),this.services.delete(e),await this.refreshToolsCache(),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u5DF2\u505C\u6B62`)}catch(r){throw this.logger.error(`[MCPManager] \u505C\u6B62 ${e} \u670D\u52A1\u5931\u8D25:`,r.message),r}}async refreshToolsCache(){this.tools.clear();for(let[e,t]of this.services)if(t.isConnected()){let r=t.getTools(),o=this.configs[e];o&&this.cacheManager.writeCacheEntry(e,r,o).then(()=>{this.logger.debug(`[MCPManager] \u5DF2\u5C06 ${e} \u5DE5\u5177\u5217\u8868\u5199\u5165\u7F13\u5B58`)}).catch(n=>{this.logger.warn(`[MCPManager] \u5199\u5165\u7F13\u5B58\u5931\u8D25: ${e}, \u9519\u8BEF: ${n instanceof Error?n.message:String(n)}`)});for(let n of r){let s=`${e}__${n.name}`;this.tools.set(s,{serviceName:e,originalName:n.name,tool:n})}}await this.syncToolsConfigToFile()}getAllTools(){let e=[];if(d.getCustomMCPConfig()!==null){this.logger.info("[MCPManager] \u68C0\u6D4B\u5230\u65B0\u7248\u672C\u914D\u7F6E\uFF0C\u4F7F\u7528 customMCP \u5DE5\u5177\u5217\u8868");try{let r=this.customMCPHandler.getTools();for(let o of r)e.push({name:o.name,description:o.description||"",inputSchema:o.inputSchema,serviceName:this.getServiceNameForTool(o),originalName:o.name});this.logger.info(`[MCPManager] \u65B0\u7248\u672C\u914D\u7F6E\u8FD4\u56DE ${e.length} \u4E2A\u5DE5\u5177 (\u4EC5\u6765\u81EA customMCP.tools)`)}catch(r){this.logger.error("[MCPManager] \u83B7\u53D6 customMCP \u5DE5\u5177\u5931\u8D25:",r)}}else{this.logger.info("[MCPManager] \u68C0\u6D4B\u5230\u8001\u7248\u672C\u914D\u7F6E\uFF0C\u4F7F\u7528\u517C\u5BB9\u6A21\u5F0F\u5904\u7406");let r=new Set;try{let o=this.customMCPHandler.getTools();for(let n of o){let s=n.name;r.has(s)||(r.add(s),e.push({name:s,description:n.description||"",inputSchema:n.inputSchema,serviceName:"customMCP",originalName:n.name}))}o.length>0&&this.logger.info(`[MCPManager] \u6DFB\u52A0\u4E86 ${o.length} \u4E2A customMCP \u5DE5\u5177`)}catch(o){this.logger.error("[MCPManager] \u83B7\u53D6 CustomMCP \u5DE5\u5177\u5931\u8D25:",o)}for(let[o,n]of this.tools){if(r.has(o))continue;d.isToolEnabled(n.serviceName,n.originalName)&&(r.add(o),e.push({name:o,description:n.tool.description||"",inputSchema:n.tool.inputSchema,serviceName:n.serviceName,originalName:n.originalName}))}this.logger.info(`[MCPManager] \u8001\u7248\u672C\u914D\u7F6E\u8FD4\u56DE\u603B\u8BA1 ${e.length} \u4E2A\u5DE5\u5177 (customMCP \u4F18\u5148\uFF0C\u53BB\u91CD\u540E\u603B\u6570)`)}return e}getServiceNameForTool(e){return e.handler?.type==="mcp"?e.handler.config.serviceName:"customMCP"}async callTool(e,t){if(this.logger.info(`[MCPManager] \u8C03\u7528\u5DE5\u5177: ${e}\uFF0C\u53C2\u6570:`,t),this.customMCPHandler.hasTool(e)){let n=this.customMCPHandler.getToolInfo(e);if(n?.handler?.type==="mcp")try{let s=await this.callMCPTool(e,n.handler.config,t);return this.updateToolStats(e,n.handler.config.serviceName,n.handler.config.toolName,!0).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),s}catch(s){throw this.updateToolStatsForFailedCall(e,n.handler.config.serviceName,n.handler.config.toolName,s).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),s}try{let s=await this.customMCPHandler.callTool(e,t);return this.updateToolStats(e,"customMCP",e,!0).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),this.logger.info(`[MCPManager] CustomMCP \u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F`),s}catch(s){throw this.updateToolStatsForFailedCall(e,"customMCP",e,s).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),this.logger.error(`[MCPManager] CustomMCP \u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,s.message),s}}let r=this.tools.get(e);if(!r)throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);let o=this.services.get(r.serviceName);if(!o)throw new Error(`\u670D\u52A1 ${r.serviceName} \u4E0D\u53EF\u7528`);if(!o.isConnected())throw new Error(`\u670D\u52A1 ${r.serviceName} \u672A\u8FDE\u63A5`);try{let n=await o.callTool(r.originalName,t||{});return this.updateToolStats(e,r.serviceName,r.originalName,!0).catch(s=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,s)}),this.logger.info(`[MCPManager] \u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F\uFF0C\u7ED3\u679C:`,n),n}catch(n){throw this.updateToolStatsForFailedCall(e,r.serviceName,r.originalName,n).catch(s=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,s)}),this.logger.error(`[MCPManager] \u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,n.message),n}}async updateToolStats(e,t,r,o){try{if(!o)return;let n=new Date().toISOString();await this.updateCustomMCPToolStats(e,n),t!=="customMCP"&&await this.updateMCPServerToolStats(t,r,n),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u4FE1\u606F`)}catch(n){throw this.logger.error(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,n),n}}async updateToolStatsForFailedCall(e,t,r,o){try{let n=new Date().toISOString();await this.updateCustomMCPToolLastUsedTime(e,n),t!=="customMCP"&&await this.updateMCPServerToolLastUsedTime(t,r,n),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0\u5DE5\u5177 ${e} \u7684\u5931\u8D25\u8C03\u7528\u7EDF\u8BA1\u4FE1\u606F`)}catch(n){throw this.logger.error(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u8C03\u7528\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,n),n}}async updateCustomMCPToolStats(e,t){try{await d.updateToolUsageStatsWithLock(e,!0),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u4F7F\u7528\u7EDF\u8BA1`)}catch(r){throw this.logger.error(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u7EDF\u8BA1\u5931\u8D25:`,r),r}}async updateCustomMCPToolLastUsedTime(e,t){try{await d.updateToolUsageStatsWithLock(e,!1),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u6700\u540E\u4F7F\u7528\u65F6\u95F4`)}catch(r){throw this.logger.error(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u6700\u540E\u4F7F\u7528\u65F6\u95F4\u5931\u8D25:`,r),r}}async updateMCPServerToolStats(e,t,r){try{await d.updateMCPServerToolStatsWithLock(e,t,r,!0),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1`)}catch(o){throw this.logger.error(`[MCPManager] \u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u5931\u8D25:`,o),o}}async updateMCPServerToolLastUsedTime(e,t,r){try{await d.updateMCPServerToolStatsWithLock(e,t,r,!1),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u6700\u540E\u4F7F\u7528\u65F6\u95F4`)}catch(o){throw this.logger.error(`[MCPManager] \u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u6700\u540E\u4F7F\u7528\u65F6\u95F4\u5931\u8D25:`,o),o}}async callMCPTool(e,t,r){let{serviceName:o,toolName:n}=t;this.logger.info(`[MCPManager] \u8C03\u7528 MCP \u540C\u6B65\u5DE5\u5177 ${e} -> ${o}.${n}`);let s=this.services.get(o);if(!s)throw new Error(`\u670D\u52A1 ${o} \u4E0D\u53EF\u7528`);if(!s.isConnected())throw new Error(`\u670D\u52A1 ${o} \u672A\u8FDE\u63A5`);try{let a=await s.callTool(n,r||{});return this.logger.info(`[MCPManager] MCP \u540C\u6B65\u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F`),a}catch(a){throw this.logger.error(`[MCPManager] MCP \u540C\u6B65\u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,a.message),a}}hasTool(e){return this.customMCPHandler.hasTool(e)?!0:this.tools.has(e)}async stopAllServices(){this.logger.info("[MCPManager] \u6B63\u5728\u505C\u6B62\u6240\u6709 MCP \u670D\u52A1...");for(let[e,t]of this.services)try{await t.disconnect(),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u5DF2\u505C\u6B62`)}catch(r){this.logger.error(`[MCPManager] \u505C\u6B62 ${e} \u670D\u52A1\u5931\u8D25:`,r.message)}try{this.customMCPHandler.cleanup(),this.logger.info("[MCPManager] CustomMCP \u5904\u7406\u5668\u5DF2\u6E05\u7406")}catch(e){this.logger.error("[MCPManager] CustomMCP \u5904\u7406\u5668\u6E05\u7406\u5931\u8D25:",e)}try{d.clearAllStatsUpdateLocks(),this.logger.info("[MCPManager] \u7EDF\u8BA1\u66F4\u65B0\u9501\u5DF2\u6E05\u7406")}catch(e){this.logger.error("[MCPManager] \u6E05\u7406\u7EDF\u8BA1\u66F4\u65B0\u9501\u5931\u8D25:",e)}this.services.clear(),this.tools.clear(),this.logger.info("[MCPManager] \u6240\u6709 MCP \u670D\u52A1\u5DF2\u505C\u6B62")}getStatus(){let e=this.customMCPHandler.getToolCount(),t=this.tools.size+e,r=Array.from(this.tools.keys()),o=this.customMCPHandler.getToolNames(),n=[...r,...o],s={services:{},totalTools:t,availableTools:n};for(let[a,l]of this.services){let h=l.getStatus();s.services[a]={connected:h.connected,clientName:`xiaozhi-${a}-client`}}return e>0&&(s.services.customMCP={connected:!0,clientName:"xiaozhi-customMCP-handler"}),s}getStatsUpdateInfo(){try{let e=d.getStatsUpdateLocks();return{activeLocks:e,totalLocks:e.length}}catch(e){return this.logger.warn("[MCPManager] \u83B7\u53D6\u7EDF\u8BA1\u66F4\u65B0\u76D1\u63A7\u4FE1\u606F\u5931\u8D25:",e),{activeLocks:[],totalLocks:0}}}getService(e){return this.services.get(e)}getAllServices(){return new Map(this.services)}getCustomMCPHandler(){return this.customMCPHandler}hasCustomMCPTool(e){return this.customMCPHandler.hasTool(e)}getCustomMCPTools(){return this.customMCPHandler.getTools()}enhanceServiceConfig(e){let t={...e};try{if(e.type==="modelscope-sse"){let r=d.getModelScopeApiKey();if(r)t.apiKey=r,this.logger.info(`[MCPManager] \u4E3A ${e.name} \u670D\u52A1\u6DFB\u52A0 ModelScope API Key`);else throw this.logger.warn(`[MCPManager] ${e.name} \u670D\u52A1\u9700\u8981 ModelScope API Key\uFF0C\u4F46\u672A\u5728\u914D\u7F6E\u4E2D\u627E\u5230`),new Error(`ModelScope SSE \u670D\u52A1 ${e.name} \u9700\u8981 API Key\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E modelscope.apiKey`)}return t}catch(r){throw this.logger.error(`[MCPManager] \u914D\u7F6E\u589E\u5F3A\u5931\u8D25: ${e.name}`,r),r}}addServiceConfig(e,t){let r,o;if(typeof e=="string"&&t)o=e,r=t;else if(typeof e=="object")o=e.name,r=e;else throw new Error("Invalid arguments for addServiceConfig");let n=this.enhanceServiceConfig(r);this.configs[o]=n,this.logger.info(`[MCPManager] \u5DF2\u6DFB\u52A0\u670D\u52A1\u914D\u7F6E: ${o}`)}updateServiceConfig(e,t){let r=this.enhanceServiceConfig(t);this.configs[e]=r,this.logger.info(`[MCPManager] \u5DF2\u66F4\u65B0\u5E76\u589E\u5F3A\u670D\u52A1\u914D\u7F6E: ${e}`)}removeServiceConfig(e){delete this.configs[e],this.logger.info(`[MCPManager] \u5DF2\u79FB\u9664\u670D\u52A1\u914D\u7F6E: ${e}`)}async syncToolsConfigToFile(){try{this.logger.debug("[MCPManager] \u5F00\u59CB\u540C\u6B65\u5DE5\u5177\u914D\u7F6E\u5230\u914D\u7F6E\u6587\u4EF6");let e=d.getMcpServerConfig();for(let[t,r]of this.services){if(!r.isConnected())continue;let o=r.getTools();if(o.length===0)continue;let n=e[t]?.tools||{},s={};for(let p of o){let C=n[p.name];C?s[p.name]={...C,description:p.description||C.description||""}:s[p.name]={description:p.description||"",enable:!0}}let a=o.map(p=>p.name),h=Object.keys(n).filter(p=>!a.includes(p));if(h.length>0&&this.logger.info(`[MCPManager] \u68C0\u6D4B\u5230\u670D\u52A1 ${t} \u79FB\u9664\u4E86 ${h.length} \u4E2A\u5DE5\u5177: ${h.join(", ")}`),this.hasToolsConfigChanged(n,s)){d.updateServerToolsConfig(t,s);let p=Object.keys(s).filter(T=>!n[T]),C=Object.keys(s).filter(T=>{let b=n[T],B=s[T];return b&&b.description!==B.description});this.logger.info(`[MCPManager] \u5DF2\u540C\u6B65\u670D\u52A1 ${t} \u7684\u5DE5\u5177\u914D\u7F6E:`),p.length>0&&this.logger.info(` - \u65B0\u589E\u5DE5\u5177: ${p.join(", ")}`),C.length>0&&this.logger.info(` - \u66F4\u65B0\u5DE5\u5177: ${C.join(", ")}`),h.length>0&&this.logger.info(` - \u79FB\u9664\u5DE5\u5177: ${h.join(", ")}`)}}this.logger.debug("[MCPManager] \u5DE5\u5177\u914D\u7F6E\u540C\u6B65\u5B8C\u6210")}catch(e){this.logger.error("[MCPManager] \u540C\u6B65\u5DE5\u5177\u914D\u7F6E\u5230\u914D\u7F6E\u6587\u4EF6\u5931\u8D25:",e)}}hasToolsConfigChanged(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!0;let n=o.filter(a=>!r.includes(a)),s=r.filter(a=>!o.includes(a));if(n.length>0||s.length>0)return!0;for(let a of r){let l=e[a],h=t[a];if(l.description!==h.description)return!0}return!1}},go=Ze});var De,gr=m(()=>{"use strict";S();De=class{static{c(this,"MCPMessageHandler")}logger;serviceManager;constructor(e){this.serviceManager=e,this.logger=g}async handleMessage(e){this.logger.debug(`\u5904\u7406 MCP \u6D88\u606F: ${e.method}`,e);try{let t=e.id===void 0;switch(e.method){case"initialize":return await this.handleInitialize(e.params,e.id);case"notifications/initialized":return await this.handleInitializedNotification(e.params);case"tools/list":return await this.handleToolsList(e.id);case"tools/call":return await this.handleToolCall(e.params,e.id);case"resources/list":return await this.handleResourcesList(e.id);case"prompts/list":return await this.handlePromptsList(e.id);case"ping":return await this.handlePing(e.id);default:if(t)return this.logger.warn(`\u6536\u5230\u672A\u77E5\u7684\u901A\u77E5\u6D88\u606F: ${e.method}`,e),null;throw new Error(`\u672A\u77E5\u7684\u65B9\u6CD5: ${e.method}`)}}catch(t){return this.logger.error(`\u5904\u7406\u6D88\u606F\u65F6\u51FA\u9519: ${e.method}`,t),e.id===void 0?null:this.createErrorResponse(t,e.id)}}async handleInitialize(e,t){this.logger.info("\u5904\u7406 initialize \u8BF7\u6C42",e);let r=["2024-11-05","2025-06-18"],o=e.protocolVersion,n=r.includes(o)?o:"2024-11-05";return this.logger.info(`\u534F\u8BAE\u7248\u672C\u534F\u5546: \u5BA2\u6237\u7AEF=${o}, \u670D\u52A1\u5668\u54CD\u5E94=${n}`),{jsonrpc:"2.0",result:{serverInfo:{name:"xiaozhi-mcp-server",version:"1.0.0"},capabilities:{tools:{},logging:{}},protocolVersion:n},id:t!==void 0?t:1}}async handleInitializedNotification(e){return this.logger.info("\u6536\u5230 initialized \u901A\u77E5\uFF0C\u5BA2\u6237\u7AEF\u521D\u59CB\u5316\u5B8C\u6210",e),null}async handleToolsList(e){this.logger.info("\u5904\u7406 tools/list \u8BF7\u6C42");try{let r=this.serviceManager.getAllTools().map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema}));return this.logger.info(`\u8FD4\u56DE ${r.length} \u4E2A\u5DE5\u5177`),{jsonrpc:"2.0",result:{tools:r},id:e!==void 0?e:1}}catch(t){throw this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25",t),t}}async handleToolCall(e,t){this.logger.info(`\u5904\u7406 tools/call \u8BF7\u6C42: ${e.name}`,e);try{if(!e.name)throw new Error("\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");let r=await this.serviceManager.callTool(e.name,e.arguments||{});return this.logger.info(`\u5DE5\u5177 ${e.name} \u8C03\u7528\u6210\u529F`),{jsonrpc:"2.0",result:{content:r.content,isError:r.isError||!1},id:t!==void 0?t:1}}catch(r){throw this.logger.error(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,r),r}}async handlePing(e){return this.logger.debug("\u5904\u7406 ping \u8BF7\u6C42"),{jsonrpc:"2.0",result:{status:"ok",timestamp:new Date().toISOString()},id:e!==void 0?e:1}}async handleResourcesList(e){this.logger.info("\u5904\u7406 resources/list \u8BF7\u6C42");let t=[];return this.logger.info(`\u8FD4\u56DE ${t.length} \u4E2A\u8D44\u6E90`),{jsonrpc:"2.0",result:{resources:t},id:e!==void 0?e:1}}async handlePromptsList(e){this.logger.info("\u5904\u7406 prompts/list \u8BF7\u6C42");let t=[];return this.logger.info(`\u8FD4\u56DE ${t.length} \u4E2A\u63D0\u793A\u6A21\u677F`),{jsonrpc:"2.0",result:{prompts:t},id:e!==void 0?e:1}}createErrorResponse(e,t){let r=-32603;return e.message.includes("\u672A\u627E\u5230\u5DE5\u5177")||e.message.includes("\u672A\u77E5\u7684\u65B9\u6CD5")?r=-32601:(e.message.includes("\u53C2\u6570")||e.message.includes("\u4E0D\u80FD\u4E3A\u7A7A"))&&(r=-32602),{jsonrpc:"2.0",error:{code:r,message:e.message,data:{stack:e.stack}},id:t!==void 0?t:1}}getServiceManager(){return this.serviceManager}}});import{EventEmitter as ho}from"events";var hr,ur,Et,uo=m(()=>{"use strict";S();lr();Ge();gr();hr=class{static{c(this,"ToolRegistry")}serviceManager;logger;constructor(e){this.serviceManager=e,this.logger=g}async initialize(){this.logger.info("\u521D\u59CB\u5316\u5DE5\u5177\u6CE8\u518C\u8868")}getAllTools(){return this.serviceManager.getAllTools().map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema,serviceName:e.serviceName,originalName:e.originalName}))}findTool(e){return this.getAllTools().find(r=>r.name===e)||null}hasTool(e){return this.findTool(e)!==null}},ur=class extends ho{static{c(this,"ConnectionManager")}connections=new Map;logger;constructor(){super(),this.logger=g}async initialize(){this.logger.info("\u521D\u59CB\u5316\u8FDE\u63A5\u7BA1\u7406\u5668")}registerConnection(e,t,r){let o={id:e,transportName:t,state:r,connectedAt:new Date,lastActivity:new Date};this.connections.set(e,o),this.emit("connectionRegistered",o),this.logger.debug(`\u8FDE\u63A5\u5DF2\u6CE8\u518C: ${e} (${t})`)}updateConnectionState(e,t){let r=this.connections.get(e);r&&(r.state=t,r.lastActivity=new Date,this.emit("connectionStateChanged",r),this.logger.debug(`\u8FDE\u63A5\u72B6\u6001\u66F4\u65B0: ${e} -> ${t}`))}removeConnection(e){let t=this.connections.get(e);t&&(this.connections.delete(e),this.emit("connectionRemoved",t),this.logger.debug(`\u8FDE\u63A5\u5DF2\u79FB\u9664: ${e}`))}getAllConnections(){return Array.from(this.connections.values())}getActiveConnectionCount(){return Array.from(this.connections.values()).filter(e=>e.state==="connected").length}async closeAllConnections(){this.logger.info("\u5173\u95ED\u6240\u6709\u8FDE\u63A5"),this.connections.clear(),this.emit("allConnectionsClosed")}},Et=class extends ho{static{c(this,"UnifiedMCPServer")}serviceManager;messageHandler;transportAdapters=new Map;toolRegistry;connectionManager;isRunning=!1;logger;config;constructor(e={}){super(),this.config={name:"UnifiedMCPServer",enableLogging:!0,logLevel:"info",maxConnections:100,connectionTimeout:3e4,...e},this.logger=g,this.serviceManager=new Ze,this.messageHandler=new De(this.serviceManager),this.toolRegistry=new hr(this.serviceManager),this.connectionManager=new ur,this.setupEventListeners()}setupEventListeners(){this.connectionManager.on("connectionRegistered",e=>{this.emit("connectionRegistered",e)}),this.connectionManager.on("connectionStateChanged",e=>{this.emit("connectionStateChanged",e)}),this.connectionManager.on("connectionRemoved",e=>{this.emit("connectionRemoved",e)})}async initialize(){this.logger.info("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{await this.serviceManager.startAllServices(),await this.toolRegistry.initialize(),await this.connectionManager.initialize(),this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210"),this.emit("initialized")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5931\u8D25",e),e}}async registerTransport(e,t){if(this.transportAdapters.has(e))throw new Error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u5DF2\u5B58\u5728`);this.logger.info(`\u6CE8\u518C\u4F20\u8F93\u9002\u914D\u5668: ${e}`);try{await t.initialize(),this.transportAdapters.set(e,t),this.connectionManager.registerConnection(t.getConnectionId(),e,t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u6CE8\u518C\u6210\u529F`),this.emit("transportRegistered",{name:e,adapter:t})}catch(r){throw this.logger.error(`\u6CE8\u518C\u4F20\u8F93\u9002\u914D\u5668 ${e} \u5931\u8D25`,r),r}}async start(){if(this.isRunning)throw new Error("\u670D\u52A1\u5668\u5DF2\u5728\u8FD0\u884C");this.logger.info("\u542F\u52A8\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{for(let[e,t]of this.transportAdapters)try{await t.start(),this.connectionManager.updateConnectionState(t.getConnectionId(),t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u542F\u52A8\u6210\u529F`)}catch(r){throw this.logger.error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u542F\u52A8\u5931\u8D25`,r),r}this.isRunning=!0,this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F"),this.emit("started")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u542F\u52A8\u5931\u8D25",e),e}}async stop(){if(this.isRunning){this.logger.info("\u505C\u6B62\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{for(let[e,t]of this.transportAdapters)try{await t.stop(),this.connectionManager.updateConnectionState(t.getConnectionId(),t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u505C\u6B62\u6210\u529F`)}catch(r){this.logger.error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u505C\u6B62\u5931\u8D25`,r)}await this.connectionManager.closeAllConnections(),await this.serviceManager.stopAllServices(),this.isRunning=!1,this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u505C\u6B62\u6210\u529F"),this.emit("stopped")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u505C\u6B62\u5931\u8D25",e),e}}}getServiceManager(){return this.serviceManager}getToolRegistry(){return this.toolRegistry}getConnectionManager(){return this.connectionManager}getMessageHandler(){return this.messageHandler}getStatus(){return{isRunning:this.isRunning,transportCount:this.transportAdapters.size,activeConnections:this.connectionManager.getActiveConnectionCount(),toolCount:this.toolRegistry.getAllTools().length,config:this.config}}getTransportAdapters(){return new Map(this.transportAdapters)}isServerRunning(){return this.isRunning}}});async function po(i={name:"http"}){g.info("\u521B\u5EFA HTTP \u6A21\u5F0F\u670D\u52A1\u5668");let e=new Et;await e.initialize();let t=e.getMessageHandler(),r=new pt(t,i);return await e.registerTransport("http",r),g.info("HTTP \u6A21\u5F0F\u670D\u52A1\u5668\u521B\u5EFA\u6210\u529F"),e}var mo=m(()=>{"use strict";S();Xr();Kr();Zr();uo();c(po,"createHTTPServer")});var fo={};F(fo,{MCPServer:()=>pr});import{EventEmitter as Gn}from"events";var D,pr,Co=m(()=>{"use strict";S();ut();Y();mo();D=new Ie,pr=class extends Gn{static{c(this,"MCPServer")}unifiedServer=null;proxyMCPServer=null;port;isStarted=!1;constructor(e=3e3){super(),this.port=e}async initializeUnifiedServer(){if(!this.unifiedServer){D.info("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{let e={name:"http",port:this.port,host:"0.0.0.0",enableSSE:!0,enableRPC:!0};this.unifiedServer=await po(e),this.unifiedServer.on("started",()=>this.emit("started")),this.unifiedServer.on("stopped",()=>this.emit("stopped")),this.unifiedServer.on("connectionRegistered",t=>{this.emit("connectionRegistered",t)}),D.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw D.error("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u5931\u8D25",e),e}}}async initializeMCPClient(){try{let e=null;try{d.configExists()&&(e=d.getMcpEndpoints().find(r=>r&&!r.includes("<\u8BF7\u586B\u5199"))||null)}catch(t){D.warn("\u4ECE\u914D\u7F6E\u4E2D\u8BFB\u53D6\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25:",t)}e?(this.proxyMCPServer=new pe(e),this.unifiedServer&&this.proxyMCPServer.setServiceManager(this.unifiedServer.getServiceManager()),await this.proxyMCPServer.connect(),D.info("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F")):D.info("\u672A\u914D\u7F6E\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u8DF3\u8FC7\u8FDE\u63A5")}catch(e){D.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}}async start(){if(this.isStarted){D.warn("\u670D\u52A1\u5668\u5DF2\u542F\u52A8");return}try{D.info("\u542F\u52A8 MCP \u670D\u52A1\u5668"),await this.initializeUnifiedServer(),this.unifiedServer&&await this.unifiedServer.start(),this.initializeMCPClient().catch(e=>{D.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}),this.isStarted=!0,this.emit("started"),D.info("MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F")}catch(e){throw D.error("\u542F\u52A8 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}async stop(){if(!this.isStarted){D.warn("\u670D\u52A1\u5668\u672A\u542F\u52A8");return}try{D.info("\u505C\u6B62 MCP \u670D\u52A1\u5668"),this.unifiedServer&&await this.unifiedServer.stop(),this.proxyMCPServer&&(this.proxyMCPServer.disconnect(),this.proxyMCPServer=null),this.isStarted=!1,this.emit("stopped"),D.info("MCP \u670D\u52A1\u5668\u5DF2\u505C\u6B62")}catch(e){throw D.error("\u505C\u6B62 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}getServiceManager(){return this.unifiedServer?.getServiceManager()||null}getMessageHandler(){return this.unifiedServer?.getMessageHandler()||null}getStatus(){return this.unifiedServer?{...this.unifiedServer.getStatus(),port:this.port,mode:"mcp-server",proxyConnected:this.proxyMCPServer!==null}:{isRunning:!1,port:this.port,mode:"mcp-server"}}isRunning(){return this.isStarted&&(this.unifiedServer?.isServerRunning()||!1)}}});import{isAbsolute as Jn,resolve as Xn}from"path";function vo(i,e){Mt.debug(`\u8F6C\u6362\u914D\u7F6E: ${i}`,e);try{if(!i||typeof i!="string")throw new L("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!e||typeof e!="object")throw new L("\u914D\u7F6E\u5BF9\u8C61\u4E0D\u80FD\u4E3A\u7A7A",i);let t=Kn(i,e);return ss(t),Mt.info(`\u914D\u7F6E\u8F6C\u6362\u6210\u529F: ${i} -> ${t.type}`),t}catch(t){throw Mt.error(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${i}`,t),t instanceof L?t:new L(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,i)}}function Kn(i,e){if(ts(e))return Zn(i,e);if(rs(e))return Yn(i,e);if(os(e))return Qn(i,e);throw new L("\u65E0\u6CD5\u8BC6\u522B\u7684\u914D\u7F6E\u7C7B\u578B",i)}function Zn(i,e){if(!e.command)throw new L("\u672C\u5730\u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5",i);let t=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),r=(e.args||[]).map(o=>{if(es(o)){let n=Xn(t,o);return Mt.debug(`\u89E3\u6790\u76F8\u5BF9\u8DEF\u5F84: ${o} -> ${n}`),n}return o});return{name:i,type:"stdio",command:e.command,args:r,env:e.env,reconnect:{enabled:!0,maxAttempts:5,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:1e4,jitter:!0},ping:{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3},timeout:3e4}}function Yn(i,e){if(!e.url)throw new L("SSE \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);let t=ns(e.url),r={name:i,type:t?"modelscope-sse":"sse",url:e.url,reconnect:{enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:15e3,jitter:!0},ping:{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3},timeout:3e4};return t&&(r.modelScopeAuth=!0),r}function Qn(i,e){if(!e.url)throw new L("Streamable HTTP \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);return{name:i,type:"streamable-http",url:e.url,reconnect:{enabled:!0,maxAttempts:5,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:15e3,jitter:!0},ping:{enabled:!1,interval:6e4,timeout:1e4,maxFailures:3,startDelay:1e4},timeout:3e4}}function es(i){return Jn(i)?!1:!!(i.startsWith("./")||i.startsWith("../")||/\.(js|py|ts|mjs|cjs)$/i.test(i))}function ts(i){return"command"in i&&typeof i.command=="string"}function rs(i){return"type"in i&&i.type==="sse"&&"url"in i}function os(i){return"url"in i&&(!("type"in i)||i.type==="streamable-http")}function ns(i){return i.includes("modelscope.net")||i.includes("modelscope.cn")}function ss(i){if(!i.name||typeof i.name!="string")throw new L("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(!Object.values(Ke).includes(i.type))throw new L(`\u65E0\u6548\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`);switch(i.type){case"stdio":if(!i.command)throw new L("STDIO \u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5");break;case"sse":case"modelscope-sse":case"streamable-http":if(!i.url)throw new L(`${i.type} \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5`);break;default:throw new L(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}var Mt,L,So=m(()=>{"use strict";S();St();Mt=g.withTag("ConfigAdapter"),L=class extends Error{constructor(t,r){super(t);this.configName=r;this.name="ConfigValidationError"}static{c(this,"ConfigValidationError")}};c(vo,"convertLegacyToNew");c(Kn,"convertByConfigType");c(Zn,"convertLocalConfig");c(Yn,"convertSSEConfig");c(Qn,"convertStreamableHTTPConfig");c(es,"isRelativePath");c(ts,"isLocalConfig");c(rs,"isSSEConfig");c(os,"isStreamableHTTPConfig");c(ns,"isModelScopeURL");c(ss,"validateNewConfig")});async function is(){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),new go}async function yo(){if(se&&z==="initialized")return se;if(Q&&z==="initializing")return Q;z==="failed"&&dr(),z="initializing",Q=is();try{return se=await Q,z="initialized",Ne=`mcp-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,Ye=null,console.log(`\u2705 MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${Ne}`),se}catch(i){throw z="failed",Ye=i,Q=null,console.error("\u274C MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",i.message),i}}async function To(){if(z==="cleanup"){console.log("\u26A0\uFE0F MCPServiceManager \u5355\u4F8B\u5DF2\u5728\u6E05\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u91CD\u590D\u6E05\u7406");return}console.log("\u{1F9F9} \u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B\u8D44\u6E90..."),z="cleanup";try{if(Q){try{await(await Q).stopAllServices()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}Q=null}se&&(await se.stopAllServices(),se=null),z="not_initialized",Ye=null,Ne=null,console.log("\u2705 MCPServiceManager \u5355\u4F8B\u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(i){throw console.error("\u274C MCPServiceManager \u5355\u4F8B\u6E05\u7406\u5931\u8D25:",i.message),dr(),i}}function dr(){console.log("\u{1F504} \u91CD\u7F6E MCPServiceManager \u5355\u4F8B\u72B6\u6001"),se=null,Q=null,z="not_initialized",Ye=null,Ne=null}function as(){return z==="initialized"&&se!==null}function cs(){return{state:z,initializationTime:Ne?new Date:void 0,lastError:Ye||void 0,instanceId:Ne||void 0}}async function ls(){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),await To(),yo()}function gs(){return se}async function hs(){if(z==="initialized")return!0;if(z==="initializing"&&Q)try{return await Q,!0}catch{return!1}return!1}var se,Q,z,Ye,Ne,V,Pt=m(()=>{"use strict";lr();se=null,Q=null,z="not_initialized",Ye=null,Ne=null;c(is,"createInstance");c(yo,"getInstance");c(To,"cleanup");c(dr,"reset");c(as,"isInitialized");c(cs,"getStatus");c(ls,"forceReinitialize");c(gs,"getCurrentInstance");c(hs,"waitForInitialization");V={getInstance:yo,cleanup:To,reset:dr,isInitialized:as,getStatus:cs,forceReinitialize:ls,getCurrentInstance:gs,waitForInitialization:hs};process.on("exit",()=>{V.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B..."),V.reset())});process.on("uncaughtException",async i=>{console.error("\u{1F4A5} \u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u6E05\u7406 MCPServiceManager \u5355\u4F8B:",i);try{await V.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}});process.on("unhandledRejection",async i=>{console.error("\u{1F4A5} \u672A\u5904\u7406\u7684Promise\u62D2\u7EDD\uFF0C\u6E05\u7406 MCPServiceManager \u5355\u4F8B:",i);try{await V.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as us}from"events";var Eo,ps,wt,Mo=m(()=>{"use strict";S();ut();Eo=(o=>(o.EXPONENTIAL_BACKOFF="exponential_backoff",o.LINEAR_BACKOFF="linear_backoff",o.FIXED_INTERVAL="fixed_interval",o.ADAPTIVE="adaptive",o))(Eo||{}),ps={healthCheckInterval:3e4,reconnectInterval:5e3,maxReconnectAttempts:10,loadBalanceStrategy:"round-robin",connectionTimeout:1e4,reconnectStrategy:"exponential_backoff",maxReconnectDelay:3e4,reconnectBackoffMultiplier:2,jitterEnabled:!0},wt=class extends us{static{c(this,"XiaozhiConnectionManager")}connections=new Map;connectionStates=new Map;mcpServiceManager=null;logger;isInitialized=!1;isConnecting=!1;options;healthCheckInterval=null;reconnectTimers=new Map;roundRobinIndex=0;lastSelectedEndpoint=null;performanceMetrics={connectionStartTime:0,totalConnectionTime:0,averageConnectionTime:0,connectionCount:0,memoryUsage:{initial:0,current:0,peak:0},prewarmedConnections:new Set};constructor(e){super(),this.logger=g,this.options={...ps,...e},this.logger.info("[XiaozhiConnectionManager] \u5B9E\u4F8B\u5DF2\u521B\u5EFA"),this.logger.debug("[XiaozhiConnectionManager] \u914D\u7F6E\u9009\u9879:",this.options)}async initialize(e,t){if(this.isInitialized){this.logger.warn("XiaozhiConnectionManager \u5DF2\u7ECF\u521D\u59CB\u5316\uFF0C\u8DF3\u8FC7\u91CD\u590D\u521D\u59CB\u5316");return}this.logger.info(`\u5F00\u59CB\u521D\u59CB\u5316 XiaozhiConnectionManager\uFF0C\u7AEF\u70B9\u6570\u91CF: ${e.length}`);try{this.validateInitializeParams(e,t),await this.cleanup();for(let r of e)await this.createConnection(r,t);this.isInitialized=!0,this.performanceMetrics.memoryUsage.initial=process.memoryUsage().heapUsed,this.performanceMetrics.memoryUsage.current=this.performanceMetrics.memoryUsage.initial,this.performanceMetrics.memoryUsage.peak=this.performanceMetrics.memoryUsage.initial,this.logger.info(`XiaozhiConnectionManager \u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u7BA1\u7406 ${this.connections.size} \u4E2A\u8FDE\u63A5`)}catch(r){throw this.logger.error("XiaozhiConnectionManager \u521D\u59CB\u5316\u5931\u8D25:",r),await this.cleanup(),r}}async connect(){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 initialize()");if(this.isConnecting){this.logger.warn("\u8FDE\u63A5\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");return}this.isConnecting=!0,this.performanceMetrics.connectionStartTime=Date.now(),this.logger.info(`\u5F00\u59CB\u8FDE\u63A5\u6240\u6709\u7AEF\u70B9\uFF0C\u603B\u6570: ${this.connections.size}`);try{let e=[];for(let[s,a]of this.connections)e.push(this.connectSingleEndpoint(s,a));let t=await Promise.allSettled(e),r=t.filter(s=>s.status==="fulfilled").length,o=t.length-r,n=Date.now()-this.performanceMetrics.connectionStartTime;if(this.performanceMetrics.totalConnectionTime+=n,this.performanceMetrics.connectionCount++,this.performanceMetrics.averageConnectionTime=this.performanceMetrics.totalConnectionTime/this.performanceMetrics.connectionCount,this.logger.info(`\u8FDE\u63A5\u5B8C\u6210 - \u6210\u529F: ${r}, \u5931\u8D25: ${o}, \u8017\u65F6: ${n}ms`),r===0)throw new Error("\u6240\u6709\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25");this.startHealthCheck()}finally{this.isConnecting=!1}}async disconnect(){this.logger.info("\u5F00\u59CB\u65AD\u5F00\u6240\u6709\u8FDE\u63A5"),this.stopHealthCheck(),this.clearAllReconnectTimers();let e=[];for(let[t,r]of this.connections)e.push(this.disconnectSingleEndpoint(t,r));await Promise.allSettled(e),this.logger.info("\u6240\u6709\u8FDE\u63A5\u5DF2\u65AD\u5F00")}async addEndpoint(e){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316");if(this.connections.has(e)){this.logger.warn(`\u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728\uFF0C\u8DF3\u8FC7\u6DFB\u52A0`);return}this.logger.info(`\u52A8\u6001\u6DFB\u52A0\u7AEF\u70B9: ${e}`);try{let t=this.getCurrentTools();if(await this.createConnection(e,t),this.isAnyConnected()){let r=this.connections.get(e);await this.connectSingleEndpoint(e,r)}this.logger.info(`\u7AEF\u70B9 ${e} \u6DFB\u52A0\u6210\u529F`)}catch(t){throw this.logger.error(`\u6DFB\u52A0\u7AEF\u70B9 ${e} \u5931\u8D25:`,t),this.connections.delete(e),this.connectionStates.delete(e),t}}async removeEndpoint(e){if(!this.connections.has(e)){this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u79FB\u9664`);return}this.logger.info(`\u52A8\u6001\u79FB\u9664\u7AEF\u70B9: ${e}`);try{let t=this.connections.get(e);await this.disconnectSingleEndpoint(e,t),this.connections.delete(e),this.connectionStates.delete(e);let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e)),this.logger.info(`\u7AEF\u70B9 ${e} \u79FB\u9664\u6210\u529F`)}catch(t){throw this.logger.error(`\u79FB\u9664\u7AEF\u70B9 ${e} \u5931\u8D25:`,t),t}}getHealthyConnections(){let e=[];for(let[t,r]of this.connections){let o=this.connectionStates.get(t);o?.connected&&o.healthScore>50&&e.push(r)}return e}getConnectionStatus(){return Array.from(this.connectionStates.values())}isAnyConnected(){for(let e of this.connectionStates.values())if(e.connected)return!0;return!1}setServiceManager(e){this.mcpServiceManager=e,this.logger.info("\u5DF2\u8BBE\u7F6E MCPServiceManager"),this.connections.size>0&&this.syncToolsToAllConnections()}setHealthCheckEnabled(e,t){let r=this.connectionStates.get(e);r?(r.healthCheckEnabled=t,this.logger.info(`\u7AEF\u70B9 ${e} \u5065\u5EB7\u68C0\u67E5\u5DF2${t?"\u542F\u7528":"\u7981\u7528"}`)):this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u8BBE\u7F6E\u5065\u5EB7\u68C0\u67E5\u72B6\u6001`)}getHealthCheckStats(){let e={};for(let[t,r]of this.connectionStates){let o=r.totalRequests>0?r.successfulRequests/r.totalRequests*100:0;e[t]={endpoint:t,healthScore:r.healthScore,successRate:Math.round(o*100)/100,averageResponseTime:r.responseTime||0,consecutiveFailures:r.consecutiveFailures,lastHealthCheck:r.lastHealthCheck,lastSuccessTime:r.lastSuccessTime}}return e}async triggerHealthCheck(){this.logger.info("\u624B\u52A8\u89E6\u53D1\u5065\u5EB7\u68C0\u67E5"),await this.performHealthCheck()}async triggerReconnect(e){let t=this.connectionStates.get(e);if(!t)throw new Error(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(t.connected){this.logger.warn(`\u7AEF\u70B9 ${e} \u5DF2\u8FDE\u63A5\uFF0C\u65E0\u9700\u91CD\u8FDE`);return}this.logger.info(`\u624B\u52A8\u89E6\u53D1\u91CD\u8FDE: ${e}`);let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e)),await this.performReconnect(e)}stopReconnect(e){let t=this.connectionStates.get(e);if(!t){this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);return}let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e),t.isReconnecting=!1,t.nextReconnectTime=void 0,this.logger.info(`\u5DF2\u505C\u6B62\u7AEF\u70B9 ${e} \u7684\u91CD\u8FDE`))}stopAllReconnects(){this.logger.info("\u505C\u6B62\u6240\u6709\u7AEF\u70B9\u7684\u91CD\u8FDE");for(let[e]of this.reconnectTimers)this.stopReconnect(e)}getReconnectStats(){let e={};for(let[t,r]of this.connectionStates)e[t]={endpoint:t,reconnectAttempts:r.reconnectAttempts,isReconnecting:r.isReconnecting,nextReconnectTime:r.nextReconnectTime,lastReconnectAttempt:r.lastReconnectAttempt,reconnectDelay:r.reconnectDelay,errorType:r.errorType,recentReconnectHistory:r.reconnectHistory.slice(-5)};return e}validateEndpoints(e){let t=[],r=[];for(let o of e){if(!o||typeof o!="string"){r.push(o);continue}if(!o.startsWith("ws://")&&!o.startsWith("wss://")){r.push(o);continue}try{new URL(o),t.push(o)}catch{r.push(o)}}return{valid:t,invalid:r}}validateOptions(e){let t=[];if(e.healthCheckInterval!==void 0&&(typeof e.healthCheckInterval!="number"||e.healthCheckInterval<1e3)&&t.push("healthCheckInterval \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.reconnectInterval!==void 0&&(typeof e.reconnectInterval!="number"||e.reconnectInterval<100)&&t.push("reconnectInterval \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 100 \u7684\u6570\u5B57"),e.maxReconnectAttempts!==void 0&&(typeof e.maxReconnectAttempts!="number"||e.maxReconnectAttempts<0)&&t.push("maxReconnectAttempts \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 0 \u7684\u6570\u5B57"),e.connectionTimeout!==void 0&&(typeof e.connectionTimeout!="number"||e.connectionTimeout<1e3)&&t.push("connectionTimeout \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.maxReconnectDelay!==void 0&&(typeof e.maxReconnectDelay!="number"||e.maxReconnectDelay<1e3)&&t.push("maxReconnectDelay \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.reconnectBackoffMultiplier!==void 0&&(typeof e.reconnectBackoffMultiplier!="number"||e.reconnectBackoffMultiplier<1)&&t.push("reconnectBackoffMultiplier \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6570\u5B57"),e.loadBalanceStrategy!==void 0){let r=["round-robin","random","health-based"];r.includes(e.loadBalanceStrategy)||t.push(`loadBalanceStrategy \u5FC5\u987B\u662F\u4EE5\u4E0B\u503C\u4E4B\u4E00: ${r.join(", ")}`)}if(e.reconnectStrategy!==void 0){let r=Object.values(Eo);r.includes(e.reconnectStrategy)||t.push(`reconnectStrategy \u5FC5\u987B\u662F\u4EE5\u4E0B\u503C\u4E4B\u4E00: ${r.join(", ")}`)}return{valid:t.length===0,errors:t}}async updateEndpoints(e,t=[]){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316");this.logger.info(`\u66F4\u65B0\u7AEF\u70B9\u914D\u7F6E\uFF0C\u65B0\u7AEF\u70B9\u6570\u91CF: ${e.length}`);let{valid:r,invalid:o}=this.validateEndpoints(e);if(o.length>0&&this.logger.warn(`\u53D1\u73B0\u65E0\u6548\u7AEF\u70B9: ${o.join(", ")}`),r.length===0)throw new Error("\u6CA1\u6709\u6709\u6548\u7684\u7AEF\u70B9");let n=Array.from(this.connections.keys()),s=r.filter(h=>!n.includes(h)),a=n.filter(h=>!r.includes(h)),l=n.filter(h=>r.includes(h));this.logger.info(`\u7AEF\u70B9\u53D8\u66F4 - \u6DFB\u52A0: ${s.length}, \u79FB\u9664: ${a.length}, \u4FDD\u6301: ${l.length}`);try{for(let u of a)await this.removeEndpoint(u);for(let u of s)await this.addEndpoint(u);let h={type:s.length>0&&a.length>0?"endpoints_updated":s.length>0?"endpoints_added":"endpoints_removed",data:{added:s.length>0?s:void 0,removed:a.length>0?a:void 0,updated:s.length>0&&a.length>0?r:void 0},timestamp:new Date};this.emit("configChange",h),this.logger.info("\u7AEF\u70B9\u914D\u7F6E\u66F4\u65B0\u5B8C\u6210")}catch(h){throw this.logger.error("\u7AEF\u70B9\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",h),h}}updateOptions(e){this.logger.info("\u66F4\u65B0\u8FDE\u63A5\u9009\u9879");let{valid:t,errors:r}=this.validateOptions(e);if(!t)throw new Error(`\u65E0\u6548\u7684\u8FDE\u63A5\u9009\u9879: ${r.join(", ")}`);let o={...this.options};this.options={...this.options,...e};let n={type:"options_updated",data:{oldOptions:o,newOptions:e},timestamp:new Date};this.emit("configChange",n),this.logger.info("\u8FDE\u63A5\u9009\u9879\u66F4\u65B0\u5B8C\u6210"),this.logger.debug("\u65B0\u7684\u914D\u7F6E\u9009\u9879:",this.options)}getCurrentConfig(){return{endpoints:Array.from(this.connections.keys()),options:{...this.options}}}async reloadConfig(e){this.logger.info("\u5F00\u59CB\u70ED\u91CD\u8F7D\u914D\u7F6E");try{e.options&&this.updateOptions(e.options),e.endpoints&&await this.updateEndpoints(e.endpoints,e.tools||[]),this.logger.info("\u914D\u7F6E\u70ED\u91CD\u8F7D\u5B8C\u6210")}catch(t){throw this.logger.error("\u914D\u7F6E\u70ED\u91CD\u8F7D\u5931\u8D25:",t),t}}selectBestConnection(e=[]){let t=this.getHealthyConnections();if(t.length===0)return this.logger.warn("\u6CA1\u6709\u5065\u5EB7\u7684\u8FDE\u63A5\u53EF\u7528"),null;let r=t.filter(n=>{let s=this.getEndpointByConnection(n);return s&&!e.includes(s)});if(r.length===0)return this.logger.warn("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5\uFF08\u6392\u9664\u6307\u5B9A\u7AEF\u70B9\u540E\uFF09"),null;let o;switch(this.options.loadBalanceStrategy){case"round-robin":o=this.selectRoundRobin(r);break;case"random":o=this.selectRandom(r);break;case"health-based":o=this.selectHealthBased(r);break;default:o=this.selectRoundRobin(r)}return this.lastSelectedEndpoint=this.getEndpointByConnection(o),o}selectRoundRobin(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=e[this.roundRobinIndex%e.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%e.length,t}selectRandom(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=Math.floor(Math.random()*e.length);return e[t]}selectHealthBased(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=e.map(n=>{let s=this.getEndpointByConnection(n),a=s?this.connectionStates.get(s):null;return{connection:n,endpoint:s,healthScore:a?.healthScore||0,responseTime:a?.responseTime||Number.POSITIVE_INFINITY,successRate:a&&a.totalRequests>0?a.successfulRequests/a.totalRequests*100:0}});t.sort((n,s)=>n.healthScore!==s.healthScore?s.healthScore-n.healthScore:n.successRate!==s.successRate?s.successRate-n.successRate:n.responseTime-s.responseTime);let r=t.reduce((n,s)=>n+(s.healthScore+1),0),o=Math.random()*r;for(let n of t)if(o-=n.healthScore+1,o<=0)return n.connection;return t[0].connection}getEndpointByConnection(e){for(let[t,r]of this.connections)if(r===e)return t;return null}getLoadBalanceStats(){let e=this.getHealthyConnections(),t={};for(let[r,o]of this.connectionStates){let n=o.totalRequests>0?o.successfulRequests/o.totalRequests*100:0,s=o.healthScore+1;t[r]={healthScore:o.healthScore,responseTime:o.responseTime||0,successRate:Math.round(n*100)/100,weight:s}}return{strategy:this.options.loadBalanceStrategy,totalConnections:this.connections.size,healthyConnections:e.length,lastSelectedEndpoint:this.lastSelectedEndpoint,roundRobinIndex:this.roundRobinIndex,connectionWeights:t}}setLoadBalanceStrategy(e){let t=this.options.loadBalanceStrategy;this.options.loadBalanceStrategy=e,e==="round-robin"&&(this.roundRobinIndex=0),this.logger.info(`\u8D1F\u8F7D\u5747\u8861\u7B56\u7565\u5DF2\u4ECE ${t} \u5207\u6362\u5230 ${e}`);let r={type:"options_updated",data:{oldOptions:{loadBalanceStrategy:t},newOptions:{loadBalanceStrategy:e}},timestamp:new Date};this.emit("configChange",r)}async performFailover(e){this.logger.warn(`\u6267\u884C\u6545\u969C\u8F6C\u79FB\uFF0C\u5931\u8D25\u7AEF\u70B9: ${e}`);let t=this.selectBestConnection([e]);if(!t)return this.logger.error("\u6545\u969C\u8F6C\u79FB\u5931\u8D25\uFF1A\u6CA1\u6709\u53EF\u7528\u7684\u5907\u7528\u8FDE\u63A5"),null;let r=this.getEndpointByConnection(t);return this.logger.info(`\u6545\u969C\u8F6C\u79FB\u6210\u529F\uFF0C\u5207\u6362\u5230\u7AEF\u70B9: ${r}`),t}async prewarmConnections(e=[]){let t=e.length>0?e:Array.from(this.connections.keys());this.logger.info(`\u5F00\u59CB\u9884\u70ED\u8FDE\u63A5\uFF0C\u7AEF\u70B9\u6570\u91CF: ${t.length}`);let r=t.map(async o=>{if(this.performanceMetrics.prewarmedConnections.has(o)){this.logger.debug(`\u7AEF\u70B9 ${o} \u5DF2\u9884\u70ED\uFF0C\u8DF3\u8FC7`);return}try{this.connections.get(o)&&(await this.performHealthCheck(),this.performanceMetrics.prewarmedConnections.add(o),this.logger.debug(`\u7AEF\u70B9 ${o} \u9884\u70ED\u5B8C\u6210`))}catch(n){this.logger.warn(`\u7AEF\u70B9 ${o} \u9884\u70ED\u5931\u8D25:`,n)}});await Promise.all(r),this.logger.info(`\u8FDE\u63A5\u9884\u70ED\u5B8C\u6210\uFF0C\u6210\u529F\u9884\u70ED ${this.performanceMetrics.prewarmedConnections.size} \u4E2A\u7AEF\u70B9`)}updatePerformanceMetrics(){let e=process.memoryUsage().heapUsed;this.performanceMetrics.memoryUsage.current=e,e>this.performanceMetrics.memoryUsage.peak&&(this.performanceMetrics.memoryUsage.peak=e)}getPerformanceMetrics(){this.updatePerformanceMetrics();let e=this.performanceMetrics.memoryUsage.current-this.performanceMetrics.memoryUsage.initial,t=this.performanceMetrics.memoryUsage.initial>0?e/this.performanceMetrics.memoryUsage.initial*100:0;return{connectionTime:{total:this.performanceMetrics.totalConnectionTime,average:this.performanceMetrics.averageConnectionTime,count:this.performanceMetrics.connectionCount},memoryUsage:{initial:this.performanceMetrics.memoryUsage.initial,current:this.performanceMetrics.memoryUsage.current,peak:this.performanceMetrics.memoryUsage.peak,growth:e,growthPercentage:Math.round(t*100)/100},prewarmedConnections:this.performanceMetrics.prewarmedConnections.size,totalConnections:this.connections.size,healthyConnections:this.getHealthyConnections().length}}optimizeMemoryUsage(){this.logger.info("\u5F00\u59CB\u5185\u5B58\u4F18\u5316");for(let[,e]of this.connectionStates)if(e.reconnectHistory&&e.reconnectHistory.length>10&&(e.reconnectHistory=e.reconnectHistory.slice(-10)),e.totalRequests>1e4){let t=e.successfulRequests/e.totalRequests;e.totalRequests=1e3,e.successfulRequests=Math.round(t*1e3)}global.gc&&global.gc(),this.updatePerformanceMetrics(),this.logger.info("\u5185\u5B58\u4F18\u5316\u5B8C\u6210")}async cleanup(){this.logger.info("\u5F00\u59CB\u6E05\u7406 XiaozhiConnectionManager \u8D44\u6E90");try{await this.disconnect(),this.connections.clear(),this.connectionStates.clear(),this.isInitialized=!1,this.isConnecting=!1,this.roundRobinIndex=0,this.lastSelectedEndpoint=null,this.logger.info("XiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(e){throw this.logger.error("XiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5931\u8D25:",e),e}}validateInitializeParams(e,t){if(!Array.isArray(e)||e.length===0)throw new Error("\u7AEF\u70B9\u5217\u8868\u4E0D\u80FD\u4E3A\u7A7A");if(!Array.isArray(t))throw new Error("\u5DE5\u5177\u5217\u8868\u5FC5\u987B\u662F\u6570\u7EC4");for(let r of e){if(!r||typeof r!="string")throw new Error(`\u65E0\u6548\u7684\u7AEF\u70B9\u5730\u5740: ${r}`);if(!r.startsWith("ws://")&&!r.startsWith("wss://"))throw new Error(`\u7AEF\u70B9\u5730\u5740\u5FC5\u987B\u662F WebSocket URL: ${r}`)}}async createConnection(e,t){this.logger.debug(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B: ${e}`);try{let r=new pe(e);this.mcpServiceManager&&r.setServiceManager(this.mcpServiceManager),this.connections.set(e,r),this.connectionStates.set(e,{endpoint:e,connected:!1,initialized:!1,reconnectAttempts:0,healthScore:100,consecutiveFailures:0,totalRequests:0,successfulRequests:0,healthCheckEnabled:!0,isReconnecting:!1,reconnectDelay:this.options.reconnectInterval,reconnectHistory:[]}),this.logger.debug(`\u8FDE\u63A5\u5B9E\u4F8B\u521B\u5EFA\u6210\u529F: ${e}`)}catch(r){throw this.logger.error(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B\u5931\u8D25 ${e}:`,r),r}}async connectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(!r)throw new Error(`\u7AEF\u70B9\u72B6\u6001\u4E0D\u5B58\u5728: ${e}`);this.logger.debug(`\u8FDE\u63A5\u7AEF\u70B9: ${e}`);try{r.connected=!1,r.initialized=!1,await t.connect(),r.connected=!0,r.initialized=!0,r.lastConnected=new Date,r.lastError=void 0,r.reconnectAttempts=0,r.healthScore=100,this.logger.info(`\u7AEF\u70B9\u8FDE\u63A5\u6210\u529F: ${e}`)}catch(o){throw r.connected=!1,r.initialized=!1,r.lastError=o instanceof Error?o.message:String(o),r.reconnectAttempts++,r.healthScore=Math.max(0,r.healthScore-20),this.logger.error(`\u7AEF\u70B9\u8FDE\u63A5\u5931\u8D25 ${e}:`,o),this.scheduleReconnect(e),o}}async disconnectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(r){this.logger.debug(`\u65AD\u5F00\u7AEF\u70B9: ${e}`);try{t.disconnect(),r.connected=!1,r.initialized=!1,this.logger.debug(`\u7AEF\u70B9\u65AD\u5F00\u6210\u529F: ${e}`)}catch(o){this.logger.error(`\u7AEF\u70B9\u65AD\u5F00\u5931\u8D25 ${e}:`,o),r.connected=!1,r.initialized=!1}}}getCurrentTools(){if(!this.mcpServiceManager)return[];try{return this.mcpServiceManager.getAllTools()}catch(e){return this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25:",e),[]}}syncToolsToAllConnections(){if(this.mcpServiceManager){this.logger.debug("\u540C\u6B65\u5DE5\u5177\u5230\u6240\u6709\u8FDE\u63A5");for(let[e,t]of this.connections)try{t.setServiceManager(this.mcpServiceManager),this.logger.debug(`\u5DE5\u5177\u540C\u6B65\u6210\u529F: ${e}`)}catch(r){this.logger.error(`\u5DE5\u5177\u540C\u6B65\u5931\u8D25 ${e}:`,r)}}}startHealthCheck(){this.healthCheckInterval||(this.logger.debug(`\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\uFF0C\u95F4\u9694: ${this.options.healthCheckInterval}ms`),this.healthCheckInterval=setInterval(()=>{this.performHealthCheck()},this.options.healthCheckInterval))}stopHealthCheck(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null,this.logger.debug("\u5065\u5EB7\u68C0\u67E5\u5DF2\u505C\u6B62"))}async performHealthCheck(){this.logger.debug("\u6267\u884C\u5065\u5EB7\u68C0\u67E5");let e=[];for(let[t,r]of this.connectionStates)r.healthCheckEnabled&&e.push(this.performSingleHealthCheck(t,r));await Promise.allSettled(e)}async performSingleHealthCheck(e,t){let r=Date.now();t.lastHealthCheck=new Date,t.totalRequests++;try{let o=this.connections.get(e);if(!o)throw new Error(`\u8FDE\u63A5\u5B9E\u4F8B\u4E0D\u5B58\u5728: ${e}`);await this.checkConnectionHealth(o,e);let n=Date.now()-r;this.handleHealthCheckSuccess(t,n)}catch(o){let n=Date.now()-r;this.handleHealthCheckFailure(t,o,n)}}async checkConnectionHealth(e,t){if(!e)throw new Error("\u8FDE\u63A5\u5B9E\u4F8B\u4E0D\u5B58\u5728");if(await new Promise(o=>setTimeout(o,10)),!this.connectionStates.get(t)?.connected)throw new Error("\u8FDE\u63A5\u5DF2\u65AD\u5F00")}handleHealthCheckSuccess(e,t){e.successfulRequests++,e.consecutiveFailures=0,e.responseTime=t,e.lastSuccessTime=new Date,this.updateHealthScore(e,!0,t),this.logger.debug(`\u5065\u5EB7\u68C0\u67E5\u6210\u529F: ${e.endpoint}, \u54CD\u5E94\u65F6\u95F4: ${t}ms, \u5065\u5EB7\u5EA6: ${e.healthScore}`)}handleHealthCheckFailure(e,t,r){e.consecutiveFailures++,e.responseTime=r,e.lastError=t.message,this.updateHealthScore(e,!1,r),this.logger.warn(`\u5065\u5EB7\u68C0\u67E5\u5931\u8D25: ${e.endpoint}, \u9519\u8BEF: ${t.message}, \u8FDE\u7EED\u5931\u8D25: ${e.consecutiveFailures}, \u5065\u5EB7\u5EA6: ${e.healthScore}`),e.consecutiveFailures>=3&&e.connected&&this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8FDE\u7EED\u5931\u8D25 ${e.consecutiveFailures} \u6B21\uFF0C\u53EF\u80FD\u9700\u8981\u91CD\u8FDE`)}updateHealthScore(e,t,r){let o=e.healthScore;if(t){let n=5;r<100?n=10:r<500?n=7:r<1e3?n=5:n=2,e.healthScore=Math.min(100,o+n)}else{let n=15;e.consecutiveFailures>=5?n=30:e.consecutiveFailures>=3&&(n=20),e.healthScore=Math.max(0,o-n)}if(e.totalRequests>0){let n=e.successfulRequests/e.totalRequests;n<.5?e.healthScore=Math.max(0,e.healthScore-10):n>.9&&(e.healthScore=Math.min(100,e.healthScore+5))}}classifyConnectionError(e){let t=e.message.toLowerCase();return t.includes("timeout")||t.includes("timed out")?"timeout_error":t.includes("network")||t.includes("connection refused")||t.includes("econnrefused")||t.includes("enotfound")?"network_error":t.includes("auth")||t.includes("unauthorized")||t.includes("forbidden")||t.includes("401")||t.includes("403")?"authentication_error":t.includes("server")||t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")?"server_error":"unknown_error"}calculateReconnectDelay(e){let t=this.options.reconnectInterval,r=this.options.maxReconnectDelay,o=this.options.reconnectBackoffMultiplier,n=e.reconnectAttempts,s;switch(this.options.reconnectStrategy){case"fixed_interval":s=t;break;case"linear_backoff":s=t*(n+1);break;case"exponential_backoff":s=t*o**n;break;case"adaptive":s=this.calculateAdaptiveDelay(e,t,o,n);break;default:s=t*o**n}if(s=Math.min(s,r),this.options.jitterEnabled){let a=s*.1*Math.random();s+=a}return Math.round(s)}calculateAdaptiveDelay(e,t,r,o){let n=t;switch(e.errorType){case"network_error":n=t*r**o;break;case"authentication_error":n=t*r**o*2;break;case"server_error":n=t*(1+o);break;case"timeout_error":n=t*(1+o*.5);break;default:n=t*r**o}if(e.reconnectHistory.length>0){let s=e.reconnectHistory.slice(-5),a=s.filter(l=>l.success).length/s.length;a<.2?n*=1.5:a>.8&&(n*=.8)}return n}shouldReconnect(e){return e.reconnectAttempts>=this.options.maxReconnectAttempts?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8FDE\u6B21\u6570 ${this.options.maxReconnectAttempts}`),!1):e.errorType==="authentication_error"&&e.reconnectAttempts>=3?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8BA4\u8BC1\u9519\u8BEF\uFF0C\u505C\u6B62\u91CD\u8FDE`),!1):e.consecutiveFailures>=10?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8FDE\u7EED\u5931\u8D25\u6B21\u6570\u8FC7\u591A\uFF0C\u505C\u6B62\u91CD\u8FDE`),!1):!0}scheduleReconnect(e){let t=this.connectionStates.get(e);if(!t)return;if(t.lastError&&(t.errorType=this.classifyConnectionError(new Error(t.lastError))),!this.shouldReconnect(t)){t.isReconnecting=!1;return}let r=this.reconnectTimers.get(e);r&&clearTimeout(r);let o=this.calculateReconnectDelay(t);t.reconnectDelay=o,t.isReconnecting=!0,t.nextReconnectTime=new Date(Date.now()+o),this.logger.info(`\u5B89\u6392\u91CD\u8FDE ${e}\uFF0C\u5EF6\u8FDF: ${o}ms\uFF0C\u5C1D\u8BD5\u6B21\u6570: ${t.reconnectAttempts+1}\uFF0C\u9519\u8BEF\u7C7B\u578B: ${t.errorType}`);let n=setTimeout(async()=>{this.reconnectTimers.delete(e),await this.performReconnect(e)},o);this.reconnectTimers.set(e,n)}async performReconnect(e){let t=this.connectionStates.get(e),r=this.connections.get(e);if(!(!t||!r)){t.lastReconnectAttempt=new Date,t.isReconnecting=!0,this.logger.info(`\u5F00\u59CB\u91CD\u8FDE ${e}\uFF0C\u7B2C ${t.reconnectAttempts+1} \u6B21\u5C1D\u8BD5`);try{await this.connectSingleEndpoint(e,r),t.isReconnecting=!1,t.reconnectHistory.push({timestamp:new Date,success:!0,delay:t.reconnectDelay}),this.logger.info(`\u91CD\u8FDE\u6210\u529F ${e}`)}catch(o){t.isReconnecting=!1,t.reconnectHistory.push({timestamp:new Date,success:!1,error:o instanceof Error?o.message:String(o),delay:t.reconnectDelay}),this.logger.error(`\u91CD\u8FDE\u5931\u8D25 ${e}:`,o),this.scheduleReconnect(e)}t.reconnectHistory.length>20&&(t.reconnectHistory=t.reconnectHistory.slice(-20))}}clearAllReconnectTimers(){for(let[,e]of this.reconnectTimers)clearTimeout(e);this.reconnectTimers.clear()}}});async function ds(i){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 XiaozhiConnectionManager \u5355\u4F8B..."),new wt(i)}async function Po(i){if(ie&&j==="initialized")return ie;if(X&&j==="initializing")return X;j==="failed"&&mr(),j="initializing",X=ds(i);try{return ie=await X,j="initialized",_e=`xiaozhi-connection-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,Qe=null,console.log(`\u2705 XiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${_e}`),ie}catch(e){throw j="failed",Qe=e,X=null,console.error("\u274C XiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",e.message),e}}async function wo(){if(j==="cleanup"){console.log("\u26A0\uFE0F XiaozhiConnectionManager \u5355\u4F8B\u5DF2\u5728\u6E05\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u91CD\u590D\u6E05\u7406");return}console.log("\u{1F9F9} \u6B63\u5728\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90..."),j="cleanup";try{if(X){try{await(await X).cleanup()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}X=null}ie&&(await ie.cleanup(),ie=null),j="not_initialized",Qe=null,_e=null,console.log("\u2705 XiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(i){throw console.error("\u274C XiaozhiConnectionManager \u5355\u4F8B\u6E05\u7406\u5931\u8D25:",i.message),mr(),i}}function mr(){console.log("\u{1F504} \u91CD\u7F6E XiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001..."),X&&(X=null),ie=null,j="not_initialized",Qe=null,_e=null,console.log("\u2705 XiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001\u5DF2\u91CD\u7F6E")}function ms(){return j==="initialized"&&ie!==null}function fs(){return{state:j,initializationTime:_e?new Date:void 0,lastError:Qe||void 0,instanceId:_e||void 0}}async function Cs(i){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 XiaozhiConnectionManager \u5355\u4F8B..."),await wo(),Po(i)}function vs(){return ie}async function Ss(){if(j==="initialized")return!0;if(j==="initializing"&&X)try{return await X,!0}catch{return!1}return!1}var ie,X,j,Qe,_e,Le,bo=m(()=>{"use strict";Mo();ie=null,X=null,j="not_initialized",Qe=null,_e=null;c(ds,"createInstance");c(Po,"getInstance");c(wo,"cleanup");c(mr,"reset");c(ms,"isInitialized");c(fs,"getStatus");c(Cs,"forceReinitialize");c(vs,"getCurrentInstance");c(Ss,"waitForInitialization");Le={getInstance:Po,cleanup:wo,reset:mr,isInitialized:ms,getStatus:fs,forceReinitialize:Cs,getCurrentInstance:vs,waitForInitialization:Ss};process.on("exit",()=>{Le.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B..."),Le.reset())});process.on("uncaughtException",async i=>{console.error("\u{1F4A5} \u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B:",i);try{await Le.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}});process.on("unhandledRejection",async i=>{console.error("\u{1F4A5} \u672A\u5904\u7406\u7684Promise\u62D2\u7EDD\uFF0C\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B:",i);try{await Le.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as ys}from"events";function K(){return He||(He=new fr),He}function Ro(){He&&(He.destroy(),He=null)}var fr,He,ye=m(()=>{"use strict";S();fr=class extends ys{static{c(this,"EventBus")}logger;eventStats=new Map;maxListeners=50;constructor(){super(),this.logger=g.withTag("EventBus"),this.setMaxListeners(this.maxListeners),this.setupErrorHandling()}setupErrorHandling(){this.on("error",e=>{this.logger.error("EventBus \u5185\u90E8\u9519\u8BEF:",e)}),this.on("newListener",e=>{let t=this.listenerCount(e);t>this.maxListeners*.8&&this.logger.warn(`\u4E8B\u4EF6 ${e} \u7684\u76D1\u542C\u5668\u6570\u91CF\u8FC7\u591A: ${t}`)})}emitEvent(e,t){try{return this.updateEventStats(e),this.logger.debug(`\u53D1\u5C04\u4E8B\u4EF6: ${e}`,t),this.emit(e,t)}catch(r){return this.logger.error(`\u53D1\u5C04\u4E8B\u4EF6\u5931\u8D25: ${e}`,r),!1}}onEvent(e,t){return this.logger.debug(`\u6DFB\u52A0\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.on(e,t)}onceEvent(e,t){return this.logger.debug(`\u6DFB\u52A0\u4E00\u6B21\u6027\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.once(e,t)}offEvent(e,t){return this.logger.debug(`\u79FB\u9664\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.off(e,t)}updateEventStats(e){let t=this.eventStats.get(e)||{count:0,lastEmitted:new Date};t.count++,t.lastEmitted=new Date,this.eventStats.set(e,t)}getEventStats(){let e={};for(let[t,r]of this.eventStats)e[t]={...r};return e}getListenerStats(){let e={};for(let t of this.eventNames())e[t]=this.listenerCount(t);return e}clearEventStats(){this.eventStats.clear(),this.logger.info("\u4E8B\u4EF6\u7EDF\u8BA1\u5DF2\u6E05\u7406")}getStatus(){return{totalEvents:this.eventStats.size,totalListeners:Object.values(this.getListenerStats()).reduce((e,t)=>e+t,0),eventStats:this.getEventStats(),listenerStats:this.getListenerStats()}}destroy(){this.removeAllListeners(),this.eventStats.clear(),this.logger.info("EventBus \u5DF2\u9500\u6BC1")}},He=null;c(K,"getEventBus");c(Ro,"destroyEventBus")});var ae,et=m(()=>{"use strict";S();Y();ye();ae=class{static{c(this,"ConfigService")}logger;eventBus;constructor(){this.logger=g.withTag("ConfigService"),this.eventBus=K()}async getConfig(){try{let e=d.getConfig();return this.logger.debug("\u83B7\u53D6\u914D\u7F6E\u6210\u529F"),e}catch(e){throw this.logger.error("\u83B7\u53D6\u914D\u7F6E\u5931\u8D25:",e),this.eventBus.emitEvent("config:error",{error:e instanceof Error?e:new Error(String(e)),operation:"getConfig"}),e}}async updateConfig(e,t="unknown"){try{this.logger.info(`\u5F00\u59CB\u66F4\u65B0\u914D\u7F6E\uFF0C\u6765\u6E90: ${t}`),this.validateConfig(e),e.mcpEndpoint!==d.getMcpEndpoint()&&d.updateMcpEndpoint(e.mcpEndpoint);let r=d.getMcpServers();for(let[o,n]of Object.entries(e.mcpServers))JSON.stringify(r[o])!==JSON.stringify(n)&&d.updateMcpServer(o,n);for(let o of Object.keys(r))o in e.mcpServers||(d.removeMcpServer(o),d.removeServerToolsConfig(o));if(e.connection&&d.updateConnectionConfig(e.connection),e.modelscope&&d.updateModelScopeConfig(e.modelscope),e.webUI&&d.updateWebUIConfig(e.webUI),e.mcpServerConfig)for(let[o,n]of Object.entries(e.mcpServerConfig))for(let[s,a]of Object.entries(n.tools))d.setToolEnabled(o,s,a.enable);if(e?.platforms)for(let[o,n]of Object.entries(e.platforms))d.updatePlatformConfig(o,n);this.logger.info("\u914D\u7F6E\u66F4\u65B0\u6210\u529F"),this.eventBus.emitEvent("config:updated",{config:e,source:t})}catch(r){throw this.logger.error("\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",r),this.eventBus.emitEvent("config:error",{error:r instanceof Error?r:new Error(String(r)),operation:"updateConfig"}),r}}getMcpEndpoint(){try{return d.getMcpEndpoint()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",e),e}}getMcpEndpoints(){try{return d.getMcpEndpoints()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",e),e}}getMcpServers(){try{return d.getMcpServers()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",e),e}}getConnectionConfig(){try{return d.getConnectionConfig()}catch(e){throw this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",e),e}}getWebUIPort(){try{return d.getWebUIPort()||9999}catch(e){return this.logger.error("\u83B7\u53D6 Web UI \u7AEF\u53E3\u5931\u8D25:",e),9999}}validateConfig(e){if(!e||typeof e!="object")throw new Error("\u914D\u7F6E\u5FC5\u987B\u662F\u6709\u6548\u7684\u5BF9\u8C61");if(!e.mcpEndpoint)throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B mcpEndpoint");if(!e.mcpServers||typeof e.mcpServers!="object")throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 mcpServers")}configExists(){return d.configExists()}async reloadConfig(){try{this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E"),d.reloadConfig();let e=await this.getConfig();return this.eventBus.emitEvent("config:updated",{config:e,source:"reload"}),e}catch(e){throw this.logger.error("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25:",e),this.eventBus.emitEvent("config:error",{error:e instanceof Error?e:new Error(String(e)),operation:"reloadConfig"}),e}}getConfigPath(){return d.getConfigPath()}}});var bt,Io=m(()=>{"use strict";S();et();bt=class{static{c(this,"ConfigApiHandler")}logger;configService;constructor(){this.logger=g.withTag("ConfigApiHandler"),this.configService=new ae}createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async getConfig(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u914D\u7F6E\u8BF7\u6C42");let t=await this.configService.getConfig();return this.logger.info("\u83B7\u53D6\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async updateConfig(e){try{this.logger.debug("\u5904\u7406\u66F4\u65B0\u914D\u7F6E\u8BF7\u6C42");let t=await e.req.json();if(!t||typeof t!="object"){let r=this.createErrorResponse("INVALID_REQUEST_BODY","\u8BF7\u6C42\u4F53\u5FC5\u987B\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61");return e.json(r,400)}return await this.configService.updateConfig(t,"http-api"),this.logger.info("\u914D\u7F6E\u66F4\u65B0\u6210\u529F"),e.json(this.createSuccessResponse(null,"\u914D\u7F6E\u66F4\u65B0\u6210\u529F"))}catch(t){this.logger.error("\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_UPDATE_ERROR",t instanceof Error?t.message:"\u914D\u7F6E\u66F4\u65B0\u5931\u8D25");return e.json(r,400)}}async getMcpEndpoint(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u7AEF\u70B9\u8BF7\u6C42");let t=this.configService.getMcpEndpoint();return this.logger.debug("\u83B7\u53D6 MCP \u7AEF\u70B9\u6210\u529F"),e.json(this.createSuccessResponse({endpoint:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_ENDPOINT_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25");return e.json(r,500)}}async getMcpEndpoints(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u8BF7\u6C42");let t=this.configService.getMcpEndpoints();return this.logger.debug("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u6210\u529F"),e.json(this.createSuccessResponse({endpoints:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_ENDPOINTS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25");return e.json(r,500)}}async getMcpServers(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u8BF7\u6C42");let t=this.configService.getMcpServers();return this.logger.debug("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse({servers:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_SERVERS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async getConnectionConfig(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u8BF7\u6C42");let t=this.configService.getConnectionConfig();return this.logger.debug("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse({connection:t}))}catch(t){this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONNECTION_CONFIG_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async reloadConfig(e){try{this.logger.info("\u5904\u7406\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u8BF7\u6C42");let t=await this.configService.reloadConfig();return this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(t,"\u914D\u7F6E\u91CD\u65B0\u52A0\u8F7D\u6210\u529F"))}catch(t){this.logger.error("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_RELOAD_ERROR",t instanceof Error?t.message:"\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async getConfigPath(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u8BF7\u6C42");let t=this.configService.getConfigPath();return this.logger.debug("\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u6210\u529F"),e.json(this.createSuccessResponse({path:t}))}catch(t){this.logger.error("\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_PATH_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25");return e.json(r,500)}}async checkConfigExists(e){try{this.logger.debug("\u5904\u7406\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u8BF7\u6C42");let t=this.configService.configExists();return this.logger.debug(`\u914D\u7F6E\u5B58\u5728\u68C0\u67E5\u7ED3\u679C: ${t}`),e.json(this.createSuccessResponse({exists:t}))}catch(t){this.logger.error("\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_EXISTS_CHECK_ERROR",t instanceof Error?t.message:"\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u5931\u8D25");return e.json(r,500)}}}});async function Ts(i,e=3,t=1e3){for(let r=1;r<=e;r++)try{return await i()}catch(o){if(r===e)throw o;let n=t*2**(r-1);g.warn(`\u6263\u5B50 API \u8C03\u7528\u5931\u8D25\uFF0C${n}ms \u540E\u91CD\u8BD5 (${r}/${e})`,o),await new Promise(s=>setTimeout(s,n))}throw new Error("Max retry attempts exceeded")}function Es(i,e){let t=i.status;return t===401?new ce("\u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6263\u5B50 API Token \u914D\u7F6E","AUTH_FAILED",401,e):t===429?new ce("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED",429,e):t>=500?new ce("\u6263\u5B50\u670D\u52A1\u5668\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","SERVER_ERROR",t,e):new ce(e?.msg||`API \u8C03\u7528\u5931\u8D25: ${i.statusText}`,"API_ERROR",t,e)}var Cr,ce,Rt,$o=m(()=>{"use strict";S();Cr=class{static{c(this,"CozeApiCache")}cache=new Map;TTL={workspaces:1800*1e3,workflows:300*1e3};set(e,t,r){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:this.TTL[r]})}get(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(e){if(!e){this.cache.clear();return}for(let t of this.cache.keys())t.includes(e)&&this.cache.delete(t)}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}},ce=class extends Error{static{c(this,"CozeApiErrorImpl")}code;statusCode;response;constructor(e,t,r,o){super(e),this.name="CozeApiError",this.code=t,this.statusCode=r,this.response=o}};c(Ts,"retryWithBackoff");c(Es,"handleCozeApiError");Rt=class{static{c(this,"CozeApiService")}cache=new Cr;token;API_BASE_URL="https://api.coze.cn";TIMEOUT=1e4;RETRY_ATTEMPTS=3;constructor(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("\u6263\u5B50 API Token \u4E0D\u80FD\u4E3A\u7A7A");this.token=e.trim()}async getWorkspaces(){let e="workspaces",t=this.cache.get(e);if(t)return g.debug("\u4ECE\u7F13\u5B58\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868"),t;g.info("\u83B7\u53D6\u6263\u5B50\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868");let r=await this.request("/v1/workspaces");if(r.code!==0)throw new ce(r.msg||"\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25","API_ERROR",void 0,r);let o=r.data.workspaces;return this.cache.set(e,o,"workspaces"),g.info(`\u6210\u529F\u83B7\u53D6 ${o.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),o}async getWorkflows(e){let{workspace_id:t,page_num:r=1,page_size:o=20}=e;if(!t||typeof t!="string")throw new Error("\u5DE5\u4F5C\u7A7A\u95F4ID\u4E0D\u80FD\u4E3A\u7A7A");let n=`workflows:${t}:${r}:${o}`,s=this.cache.get(n);if(s)return g.debug(`\u4ECE\u7F13\u5B58\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868: ${t}`),s;g.info(`\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684\u5DE5\u4F5C\u6D41\u5217\u8868 (\u9875\u7801: ${r}, \u6BCF\u9875: ${o})`);let a=new URLSearchParams({workspace_id:t,page_num:r.toString(),page_size:o.toString(),workflow_mode:"workflow"}),l=await this.request(`/v1/workflows?${a}`);if(l.code!==0)throw new ce(l.msg||"\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25","API_ERROR",void 0,l);let h={items:l.data.items,hasMore:l.data.has_more};return this.cache.set(n,h,"workflows"),g.info(`\u6210\u529F\u83B7\u53D6 ${h.items.length} \u4E2A\u5DE5\u4F5C\u6D41\uFF0ChasMore: ${h.hasMore}`),h}async request(e){return Ts(async()=>{let t=`${this.API_BASE_URL}${e}`;g.debug(`\u53D1\u8D77\u6263\u5B50 API \u8BF7\u6C42: ${t}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.TIMEOUT);try{let n=await fetch(t,{headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},signal:r.signal});clearTimeout(o);let s;try{s=await n.json()}catch(a){throw g.error("\u89E3\u6790\u54CD\u5E94 JSON \u5931\u8D25:",a),new ce("\u54CD\u5E94\u6570\u636E\u683C\u5F0F\u9519\u8BEF","PARSE_ERROR",n.status)}if(!n.ok)throw Es(n,s);return s}catch(n){throw clearTimeout(o),n instanceof Error&&n.name==="AbortError"?new ce(`\u8BF7\u6C42\u8D85\u65F6 (${this.TIMEOUT}ms)`,"TIMEOUT",void 0):n}},this.RETRY_ATTEMPTS)}clearCache(e){this.cache.clear(e),g.info(`\u6E05\u9664\u6263\u5B50 API \u7F13\u5B58${e?` (\u6A21\u5F0F: ${e})`:""}`)}getCacheStats(){return this.cache.getStats()}}});function It(i,e){return{success:!0,data:i,message:e}}function A(i,e,t){return{success:!1,message:i,error:e?{code:e,details:t}:void 0}}function $t(){let i=d.getCozeToken();if(!i)throw new Error("\u6263\u5B50 API Token \u672A\u914D\u7F6E\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E platforms.coze.token");return new Rt(i)}var Te,xo=m(()=>{"use strict";S();Y();$o();c(It,"createSuccessResponse");c(A,"createErrorResponse");c($t,"getCozeApiService");Te=class{static{c(this,"CozeApiHandler")}static async getWorkspaces(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=await $t().getWorkspaces();return g.info(`\u6210\u529F\u83B7\u53D6 ${r.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),e.json(It({workspaces:r}))}catch(t){return g.error("\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25:",t),t instanceof Error&&t.code==="AUTH_FAILED"?e.json(A("\u6263\u5B50 API \u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 Token \u914D\u7F6E","AUTH_FAILED"),401):t instanceof Error&&t.code==="RATE_LIMITED"?e.json(A("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(A("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async getWorkflows(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let t=e.req.query("workspace_id"),r=Number.parseInt(e.req.query("page_num")||"1",10),o=Number.parseInt(e.req.query("page_size")||"20",10);if(!t)return g.warn("\u7F3A\u5C11 workspace_id \u53C2\u6570"),e.json(A("\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570: workspace_id","MISSING_PARAMETER"),400);if(r<1||r>1e3)return e.json(A("page_num \u5FC5\u987B\u5728 1-1000 \u4E4B\u95F4","INVALID_PARAMETER"),400);if(o<1||o>100)return e.json(A("page_size \u5FC5\u987B\u5728 1-100 \u4E4B\u95F4","INVALID_PARAMETER"),400);let n={workspace_id:t,page_num:r,page_size:o},a=await $t().getWorkflows(n);g.info(`\u6210\u529F\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684 ${a.items.length} \u4E2A\u5DE5\u4F5C\u6D41`);let l=d.getCustomMCPTools(),h=a.items.map(u=>{let p=l.find(C=>C.handler.type==="proxy"&&C.handler.platform==="coze"&&C.handler.config.workflow_id===u.workflow_id);return{...u,isAddedAsTool:!!p,toolName:p?.name||null}});return g.info(`\u5DE5\u4F5C\u6D41\u5DE5\u5177\u72B6\u6001\u68C0\u67E5\u5B8C\u6210\uFF0C\u5171 ${h.filter(u=>u.isAddedAsTool).length} \u4E2A\u5DE5\u4F5C\u6D41\u5DF2\u6DFB\u52A0\u4E3A\u5DE5\u5177`),e.json(It({items:h,has_more:a.hasMore,page_num:r,page_size:o,total_count:a.items.length}))}catch(t){return g.error("\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25:",t),t instanceof Error&&t.code==="AUTH_FAILED"?e.json(A("\u6263\u5B50 API \u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 Token \u914D\u7F6E","AUTH_FAILED"),401):t instanceof Error&&t.code==="RATE_LIMITED"?e.json(A("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(A("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async clearCache(e){try{if(g.info("\u5904\u7406\u6E05\u9664\u6263\u5B50 API \u7F13\u5B58\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let t=e.req.query("pattern"),r=$t(),o=r.getCacheStats();r.clearCache(t);let n=r.getCacheStats();return g.info(`\u7F13\u5B58\u6E05\u9664\u5B8C\u6210\uFF0C\u6E05\u9664\u524D: ${o.size} \u9879\uFF0C\u6E05\u9664\u540E: ${n.size} \u9879`),e.json(It({cleared:o.size-n.size,remaining:n.size,pattern:t||"all"},"\u7F13\u5B58\u6E05\u9664\u6210\u529F"))}catch(t){return g.error("\u6E05\u9664\u7F13\u5B58\u5931\u8D25:",t),e.json(A(t instanceof Error?t.message:"\u6E05\u9664\u7F13\u5B58\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async getCacheStats(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=$t().getCacheStats();return e.json(It(r))}catch(t){return g.error("\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:",t),e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}}});var xt,Oo=m(()=>{"use strict";S();et();xt=class{static{c(this,"HeartbeatHandler")}logger;statusService;notificationService;configService;constructor(e,t){this.logger=g.withTag("HeartbeatHandler"),this.statusService=e,this.notificationService=t,this.configService=new ae}async handleClientStatus(e,t,r){try{this.logger.debug(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0: ${r}`,t.data);let o={...t.data,lastHeartbeat:Date.now()};this.statusService.updateClientInfo(o,`websocket-${r}`),await this.sendLatestConfig(e,r),this.logger.debug(`\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u6210\u529F: ${r}`)}catch(o){this.logger.error(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25: ${r}`,o),this.sendError(e,"CLIENT_STATUS_ERROR",o instanceof Error?o.message:"\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25")}}async sendLatestConfig(e,t){try{let o={type:"configUpdate",data:await this.configService.getConfig(),timestamp:Date.now()};e.send(JSON.stringify(o)),this.logger.debug(`\u6700\u65B0\u914D\u7F6E\u5DF2\u53D1\u9001\u7ED9\u5BA2\u6237\u7AEF: ${t}`)}catch(r){this.logger.error(`\u53D1\u9001\u6700\u65B0\u914D\u7F6E\u5931\u8D25: ${t}`,r)}}sendError(e,t,r){try{let o={type:"error",error:{code:t,message:r,timestamp:Date.now()}};e.send(JSON.stringify(o))}catch(o){this.logger.error("\u53D1\u9001\u9519\u8BEF\u6D88\u606F\u5931\u8D25:",o)}}checkHeartbeatTimeout(){let e=this.statusService.getLastHeartbeat(),t=Date.now();e&&t-e>35e3&&(this.logger.warn("\u5BA2\u6237\u7AEF\u5FC3\u8DF3\u8D85\u65F6\uFF0C\u6807\u8BB0\u4E3A\u65AD\u5F00\u8FDE\u63A5"),this.statusService.updateClientInfo({status:"disconnected"},"heartbeat-timeout"))}startHeartbeatMonitoring(){return this.logger.info("\u542F\u52A8\u5FC3\u8DF3\u76D1\u63A7"),setInterval(()=>{this.checkHeartbeatTimeout(),this.cleanupDisconnectedClients()},1e4)}cleanupDisconnectedClients(){try{this.notificationService.cleanupDisconnectedClients()}catch(e){this.logger.error("\u6E05\u7406\u65AD\u5F00\u8FDE\u63A5\u7684\u5BA2\u6237\u7AEF\u5931\u8D25:",e)}}stopHeartbeatMonitoring(e){this.logger.info("\u505C\u6B62\u5FC3\u8DF3\u76D1\u63A7"),clearInterval(e)}getHeartbeatStats(){return{lastHeartbeat:this.statusService.getLastHeartbeat(),isConnected:this.statusService.isClientConnected(),clientStats:this.notificationService.getClientStats()}}handleClientConnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5EFA\u7ACB: ${e}`),this.statusService.updateClientInfo({status:"connected",lastHeartbeat:Date.now()},`websocket-connect-${e}`)}handleClientDisconnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u65AD\u5F00: ${e}`),this.statusService.updateClientInfo({status:"disconnected"},`websocket-disconnect-${e}`)}sendHeartbeatResponse(e,t){try{let r={type:"heartbeatResponse",data:{timestamp:Date.now(),status:"ok"}};e.send(JSON.stringify(r)),this.logger.debug(`\u5FC3\u8DF3\u54CD\u5E94\u5DF2\u53D1\u9001: ${t}`)}catch(r){this.logger.error(`\u53D1\u9001\u5FC3\u8DF3\u54CD\u5E94\u5931\u8D25: ${t}`,r)}}validateHeartbeatMessage(e){return e&&typeof e=="object"&&e.type==="clientStatus"&&e.data&&typeof e.data=="object"}}});import{randomUUID as Ms}from"crypto";var Ot,Ao=m(()=>{"use strict";S();gr();Pt();Ot=class{static{c(this,"MCPRouteHandler")}logger;mcpMessageHandler=null;clients=new Map;config;metrics;cleanupInterval=null;startTime;constructor(e={}){this.logger=g.withTag("MCPRouteHandler"),this.config={maxClients:e.maxClients??100,connectionTimeout:e.connectionTimeout??3e5,heartbeatInterval:e.heartbeatInterval??3e4,maxMessageSize:e.maxMessageSize??1024*1024,enableMetrics:e.enableMetrics??!0},this.metrics={totalConnections:0,activeConnections:0,totalMessages:0,errorCount:0,averageResponseTime:0,uptime:0},this.startTime=new Date,this.startCleanupTask(),this.logger.info("MCPRouteHandler \u521D\u59CB\u5316\u5B8C\u6210",{maxClients:this.config.maxClients,connectionTimeout:this.config.connectionTimeout,heartbeatInterval:this.config.heartbeatInterval})}startCleanupTask(){this.cleanupInterval=setInterval(()=>{this.cleanupStaleConnections(),this.updateMetrics()},6e4)}stopCleanupTask(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}cleanupStaleConnections(){let e=new Date,t=[];for(let[r,o]of this.clients.entries())(e.getTime()-o.lastActivity.getTime()>this.config.connectionTimeout||!o.isAlive)&&t.push(r);for(let r of t)this.logger.info(`\u6E05\u7406\u8FC7\u671F\u8FDE\u63A5: ${r}`),this.handleClientDisconnect(r,"cleanup");t.length>0&&this.logger.info(`\u6E05\u7406\u4E86 ${t.length} \u4E2A\u8FC7\u671F\u8FDE\u63A5`)}updateMetrics(){this.config.enableMetrics&&(this.metrics.activeConnections=this.clients.size,this.metrics.uptime=Date.now()-this.startTime.getTime(),this.logger.debug("\u8FDE\u63A5\u7EDF\u8BA1",{activeConnections:this.metrics.activeConnections,totalConnections:this.metrics.totalConnections,totalMessages:this.metrics.totalMessages,errorCount:this.metrics.errorCount}))}async initializeMessageHandler(){if(!this.mcpMessageHandler)try{let e=await V.getInstance();this.mcpMessageHandler=new De(e),this.logger.info("MCP \u6D88\u606F\u5904\u7406\u5668\u521D\u59CB\u5316\u6210\u529F")}catch(e){throw this.logger.error("MCP \u6D88\u606F\u5904\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",e),this.metrics.errorCount++,e}}async handlePost(e){let t=Date.now(),r=null;try{this.logger.debug("\u5904\u7406 MCP POST \u8BF7\u6C42");let o=e.req.query("sessionId");if(o)return await this.handleSSEMessage(e,o);let n=e.req.header("content-length");if(n&&Number.parseInt(n)>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Request too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);if(!e.req.header("content-type")?.includes("application/json"))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Content-Type must be application/json",null);let a=e.req.header("mcp-protocol-version")||e.req.header("MCP-Protocol-Version")||e.req.header("Mcp-Protocol-Version"),l=["2024-11-05","2025-06-18"];a&&!l.includes(a)&&this.logger.warn(`\u4E0D\u652F\u6301\u7684 MCP \u534F\u8BAE\u7248\u672C: ${a}\uFF0C\u652F\u6301\u7684\u7248\u672C: ${l.join(", ")}`);let h;try{let C=await e.req.text();if(C.length>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);h=JSON.parse(C),r=h.id||null}catch{return this.metrics.errorCount++,this.createErrorResponse(-32700,"Parse error: Invalid JSON",null)}if(!this.validateMessage(h))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Message does not conform to JSON-RPC 2.0",r);await this.initializeMessageHandler();let u=await this.mcpMessageHandler.handleMessage(h);this.metrics.totalMessages++;let p=Date.now()-t;return this.metrics.averageResponseTime=(this.metrics.averageResponseTime*(this.metrics.totalMessages-1)+p)/this.metrics.totalMessages,this.logger.debug("MCP POST \u8BF7\u6C42\u5904\u7406\u6210\u529F",{method:h.method,messageId:r,responseTime:p,isNotification:u===null}),u===null?new Response(null,{status:204,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":p.toString()}}):e.json(u,200,{"Content-Type":"application/json","MCP-Protocol-Version":"2024-11-05","X-Response-Time":p.toString()})}catch(o){this.metrics.errorCount++;let n=Date.now()-t;this.logger.error("\u5904\u7406 MCP POST \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:o instanceof Error?o.message:String(o),messageId:r,responseTime:n,stack:o instanceof Error?o.stack:void 0});let s=o instanceof Error?o.message:String(o);return this.createErrorResponse(-32603,`Internal error: ${s}`,r)}}async handleSSEMessage(e,t){let r=Date.now(),o=null;try{this.logger.debug(`\u5904\u7406 SSE \u6D88\u606F (\u4F1A\u8BDD: ${t})`);let n=this.clients.get(t);if(!n)return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Invalid or missing sessionId",null);n.lastActivity=new Date;let s=e.req.header("content-length");if(s&&Number.parseInt(s)>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);let a;try{let u=await e.req.text();if(u.length>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);a=JSON.parse(u),o=a.id||null}catch{return this.metrics.errorCount++,this.createErrorResponse(-32700,"Parse error: Invalid JSON",null)}if(!this.validateMessage(a))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Message does not conform to JSON-RPC 2.0",o);await this.initializeMessageHandler();let l=await this.mcpMessageHandler.handleMessage(a);if(n.messageCount++,this.metrics.totalMessages++,l!==null&&n.writer&&n.isAlive)try{await this.sendSSEEvent(n.writer,"message",JSON.stringify(l))}catch(u){this.logger.warn(`SSE \u5199\u5165\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${t}`,u),n.isAlive=!1}let h=Date.now()-r;return this.logger.debug(`SSE \u6D88\u606F\u5904\u7406\u5B8C\u6210 (\u4F1A\u8BDD: ${t})`,{method:a.method,messageId:o,responseTime:h,messageCount:n.messageCount,isNotification:l===null}),new Response(null,{status:202,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":h.toString()}})}catch(n){this.metrics.errorCount++;let s=Date.now()-r;this.logger.error(`\u5904\u7406 SSE \u6D88\u606F\u65F6\u51FA\u9519 (\u4F1A\u8BDD: ${t}):`,{error:n instanceof Error?n.message:String(n),messageId:o,responseTime:s,stack:n instanceof Error?n.stack:void 0});let a=n instanceof Error?n.message:String(n);return this.createErrorResponse(-32603,`Internal error: ${a}`,o)}}async handleGet(e){try{if(this.logger.debug("\u5904\u7406 MCP GET \u8BF7\u6C42\uFF08SSE \u8FDE\u63A5\uFF09"),this.clients.size>=this.config.maxClients)return this.metrics.errorCount++,e.json({jsonrpc:"2.0",error:{code:-32e3,message:"Server busy: Maximum client connections reached",data:{maxClients:this.config.maxClients}},id:null},503);let t=Date.now().toString(),r=Ms(),o=new Date,n=e.req.header("user-agent"),s=e.req.header("x-forwarded-for")||e.req.header("x-real-ip")||"unknown";this.logger.info(`SSE \u5BA2\u6237\u7AEF\u8FDE\u63A5: ${t} (\u4F1A\u8BDD: ${r})`,{userAgent:n,remoteAddress:s});let{readable:a,writable:l}=new TransformStream,h=l.getWriter(),u=new AbortController,p={id:t,sessionId:r,response:new Response(a),connectedAt:o,lastActivity:o,writer:h,abortController:u,isAlive:!0,messageCount:0,userAgent:n,remoteAddress:s};this.clients.set(r,p),this.metrics.totalConnections++,this.metrics.activeConnections=this.clients.size;try{await this.sendSSEEvent(h,"connected",JSON.stringify({sessionId:r,endpoint:`/mcp?sessionId=${r}`,timestamp:o.toISOString(),protocolVersion:"2024-11-05"}))}catch(b){this.logger.error(`\u521D\u59CB SSE \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25: ${r}`,b),p.isAlive=!1}this.startHeartbeat(p);let C=new Response(a,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no","MCP-Protocol-Version":"2024-11-05","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type, MCP-Protocol-Version"}}),T=c(()=>{this.handleClientDisconnect(r,t)},"handleDisconnect");return e.req.raw.signal?.addEventListener("abort",T),u.signal.addEventListener("abort",T),C}catch(t){return this.metrics.errorCount++,this.logger.error("\u5904\u7406 MCP GET \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),e.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"},id:null},500)}}startHeartbeat(e){e.heartbeatInterval&&clearInterval(e.heartbeatInterval),e.heartbeatInterval=setInterval(async()=>{if(!e.isAlive||!e.writer){this.stopHeartbeat(e);return}try{await this.sendSSEEvent(e.writer,"heartbeat",JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId})),this.logger.debug(`\u5FC3\u8DF3\u53D1\u9001\u6210\u529F: ${e.sessionId}`)}catch(t){this.logger.warn(`\u5FC3\u8DF3\u53D1\u9001\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${e.sessionId}`,t),e.isAlive=!1,this.stopHeartbeat(e)}},this.config.heartbeatInterval)}stopHeartbeat(e){e.heartbeatInterval&&(clearInterval(e.heartbeatInterval),e.heartbeatInterval=void 0)}async sendSSEEvent(e,t,r){try{let o=`event: ${t}
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}
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 At,ko=m(()=>{"use strict";S();et();ye();At=class{static{c(this,"RealtimeNotificationHandler")}logger;notificationService;configService;statusService;eventBus;constructor(e,t){this.logger=g.withTag("RealtimeNotificationHandler"),this.notificationService=e,this.configService=new ae,this.statusService=t,this.eventBus=K()}async handleMessage(e,t,r){try{switch(this.logger.debug(`\u5904\u7406 WebSocket \u6D88\u606F: ${t.type}`,{clientId:r}),this.eventBus.emitEvent("websocket:message:received",{type:t.type,data:t.data,clientId:r}),t.type){case"getConfig":await this.handleGetConfig(e,r);break;case"updateConfig":await this.handleUpdateConfig(e,t.data,r);break;case"getStatus":await this.handleGetStatus(e,r);break;case"restartService":await this.handleRestartService(e,r);break;default:this.logger.warn(`\u672A\u77E5\u7684 WebSocket \u6D88\u606F\u7C7B\u578B: ${t.type}`,{clientId:r}),this.sendError(e,"UNKNOWN_MESSAGE_TYPE",`\u672A\u77E5\u7684\u6D88\u606F\u7C7B\u578B: ${t.type}`)}}catch(o){this.logger.error(`\u5904\u7406 WebSocket \u6D88\u606F\u5931\u8D25: ${t.type}`,o),this.sendError(e,"MESSAGE_PROCESSING_ERROR",o instanceof Error?o.message:"\u6D88\u606F\u5904\u7406\u5931\u8D25")}}async handleGetConfig(e,t){this.logDeprecationWarning("WebSocket getConfig","GET /api/config");try{let r=await this.configService.getConfig();this.logger.debug("WebSocket: getConfig \u8BF7\u6C42\u5904\u7406\u6210\u529F",{clientId:t}),e.send(JSON.stringify({type:"config",data:r}))}catch(r){this.logger.error("WebSocket: getConfig \u8BF7\u6C42\u5904\u7406\u5931\u8D25",r),this.sendError(e,"CONFIG_READ_ERROR",r instanceof Error?r.message:"\u83B7\u53D6\u914D\u7F6E\u5931\u8D25")}}async handleUpdateConfig(e,t,r){this.logDeprecationWarning("WebSocket updateConfig","PUT /api/config");try{await this.configService.updateConfig(t,`websocket-${r}`),this.logger.debug("WebSocket: updateConfig \u8BF7\u6C42\u5904\u7406\u6210\u529F",{clientId:r})}catch(o){this.logger.error("WebSocket: updateConfig \u8BF7\u6C42\u5904\u7406\u5931\u8D25",o),this.sendError(e,"CONFIG_UPDATE_ERROR",o instanceof Error?o.message:"\u914D\u7F6E\u66F4\u65B0\u5931\u8D25")}}async handleGetStatus(e,t){this.logDeprecationWarning("WebSocket getStatus","GET /api/status");try{let r=this.statusService.getFullStatus();e.send(JSON.stringify({type:"status",data:r.client})),this.logger.debug("WebSocket: getStatus \u8BF7\u6C42\u5904\u7406\u6210\u529F",{clientId:t})}catch(r){this.logger.error("WebSocket: getStatus \u8BF7\u6C42\u5904\u7406\u5931\u8D25",r),this.sendError(e,"STATUS_READ_ERROR",r instanceof Error?r.message:"\u83B7\u53D6\u72B6\u6001\u5931\u8D25")}}async handleRestartService(e,t){this.logDeprecationWarning("WebSocket restartService","POST /api/services/restart");try{this.logger.info("WebSocket: \u6536\u5230\u670D\u52A1\u91CD\u542F\u8BF7\u6C42",{clientId:t}),this.eventBus.emitEvent("service:restart:requested",{source:`websocket-${t}`}),this.statusService.updateRestartStatus("restarting")}catch(r){this.logger.error("WebSocket: \u5904\u7406\u91CD\u542F\u8BF7\u6C42\u5931\u8D25",r),this.sendError(e,"RESTART_REQUEST_ERROR",r instanceof Error?r.message:"\u5904\u7406\u91CD\u542F\u8BF7\u6C42\u5931\u8D25")}}sendError(e,t,r){try{let o={type:"error",error:{code:t,message:r,timestamp:Date.now()}};e.send(JSON.stringify(o))}catch(o){this.logger.error("\u53D1\u9001\u9519\u8BEF\u6D88\u606F\u5931\u8D25:",o)}}logDeprecationWarning(e,t){this.logger.warn(`[DEPRECATED] ${e} \u529F\u80FD\u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u4F7F\u7528 ${t} \u66FF\u4EE3`)}async sendInitialData(e,t){try{this.logger.debug("\u53D1\u9001\u521D\u59CB\u6570\u636E\u7ED9\u5BA2\u6237\u7AEF",{clientId:t});let r=await this.configService.getConfig();e.send(JSON.stringify({type:"configUpdate",data:r}));let o=this.statusService.getFullStatus();e.send(JSON.stringify({type:"statusUpdate",data:o.client})),o.restart&&e.send(JSON.stringify({type:"restartStatus",data:o.restart})),this.logger.debug("\u521D\u59CB\u6570\u636E\u53D1\u9001\u5B8C\u6210",{clientId:t})}catch(r){this.logger.error("\u53D1\u9001\u521D\u59CB\u6570\u636E\u5931\u8D25:",r),this.sendError(e,"INITIAL_DATA_ERROR",r instanceof Error?r.message:"\u53D1\u9001\u521D\u59CB\u6570\u636E\u5931\u8D25")}}handleClientDisconnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u65AD\u5F00\u8FDE\u63A5: ${e}`),this.notificationService.unregisterClient(e)}handleClientConnect(e,t){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5: ${t}`),this.notificationService.registerClient(t,e)}}});import{spawn as kt}from"child_process";var Dt,Do=m(()=>{"use strict";S();vr();ye();Dt=class{static{c(this,"ServiceApiHandler")}logger;statusService;eventBus;constructor(e){this.logger=g.withTag("ServiceApiHandler"),this.statusService=e,this.eventBus=K()}createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async restartService(e){try{return this.logger.info("\u5904\u7406\u670D\u52A1\u91CD\u542F\u8BF7\u6C42"),this.eventBus.emitEvent("service:restart:requested",{source:"http-api"}),this.statusService.updateRestartStatus("restarting"),setTimeout(async()=>{try{await this.executeRestart(),setTimeout(()=>{this.statusService.updateRestartStatus("completed")},5e3)}catch(t){this.logger.error("\u670D\u52A1\u91CD\u542F\u5931\u8D25:",t),this.statusService.updateRestartStatus("failed",t instanceof Error?t.message:"\u672A\u77E5\u9519\u8BEF")}},500),e.json(this.createSuccessResponse(null,"\u91CD\u542F\u8BF7\u6C42\u5DF2\u63A5\u6536"))}catch(t){this.logger.error("\u5904\u7406\u91CD\u542F\u8BF7\u6C42\u5931\u8D25:",t);let r=this.createErrorResponse("RESTART_REQUEST_ERROR",t instanceof Error?t.message:"\u5904\u7406\u91CD\u542F\u8BF7\u6C42\u5931\u8D25");return e.json(r,500)}}async executeRestart(){this.logger.info("\u6B63\u5728\u91CD\u542F MCP \u670D\u52A1...");try{let r=await(await Ee()).get("serviceManager").getStatus();if(!r.running){this.logger.warn("MCP \u670D\u52A1\u672A\u8FD0\u884C\uFF0C\u5C1D\u8BD5\u542F\u52A8\u670D\u52A1"),kt("xiaozhi",["start","--daemon"],{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u542F\u52A8\u547D\u4EE4\u5DF2\u53D1\u9001");return}let o=r.mode==="daemon",n=["restart"];o&&n.push("--daemon"),kt("xiaozhi",n,{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u91CD\u542F\u547D\u4EE4\u5DF2\u53D1\u9001")}catch(e){throw this.logger.error("\u91CD\u542F\u670D\u52A1\u5931\u8D25:",e),e}}async stopService(e){try{return this.logger.info("\u5904\u7406\u670D\u52A1\u505C\u6B62\u8BF7\u6C42"),kt("xiaozhi",["stop"],{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u505C\u6B62\u547D\u4EE4\u5DF2\u53D1\u9001"),e.json(this.createSuccessResponse(null,"\u505C\u6B62\u8BF7\u6C42\u5DF2\u63A5\u6536"))}catch(t){this.logger.error("\u5904\u7406\u505C\u6B62\u8BF7\u6C42\u5931\u8D25:",t);let r=this.createErrorResponse("STOP_REQUEST_ERROR",t instanceof Error?t.message:"\u5904\u7406\u505C\u6B62\u8BF7\u6C42\u5931\u8D25");return e.json(r,500)}}async startService(e){try{return this.logger.info("\u5904\u7406\u670D\u52A1\u542F\u52A8\u8BF7\u6C42"),kt("xiaozhi",["start","--daemon"],{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u542F\u52A8\u547D\u4EE4\u5DF2\u53D1\u9001"),e.json(this.createSuccessResponse(null,"\u542F\u52A8\u8BF7\u6C42\u5DF2\u63A5\u6536"))}catch(t){this.logger.error("\u5904\u7406\u542F\u52A8\u8BF7\u6C42\u5931\u8D25:",t);let r=this.createErrorResponse("START_REQUEST_ERROR",t instanceof Error?t.message:"\u5904\u7406\u542F\u52A8\u8BF7\u6C42\u5931\u8D25");return e.json(r,500)}}async getServiceStatus(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u8BF7\u6C42");let o=await(await Ee()).get("serviceManager").getStatus();return this.logger.debug("\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(o))}catch(t){this.logger.error("\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("SERVICE_STATUS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}async getServiceHealth(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u8BF7\u6C42");let t={status:"healthy",timestamp:Date.now(),uptime:process.uptime(),memory:process.memoryUsage(),version:process.version};return this.logger.debug("\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("SERVICE_HEALTH_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}}});import{existsSync as Nt}from"fs";import{readFile as Ps}from"fs/promises";import{dirname as ws,join as fe}from"path";import{fileURLToPath as bs}from"url";var _t,No=m(()=>{"use strict";S();_t=class{static{c(this,"StaticFileHandler")}logger;webPath=null;constructor(){this.logger=g.withTag("StaticFileHandler"),this.initializeWebPath()}initializeWebPath(){try{let e=ws(bs(import.meta.url));this.logger.debug(`\u5F53\u524D\u6587\u4EF6\u76EE\u5F55: ${e}`);let t=[fe(e,"..","..","web","dist"),fe(e,"..","web","dist"),fe(e,"..","..","web"),fe(e,"..","web"),fe(e,"..","..","..","web","dist"),fe(e,"..","..","..","web")];this.webPath=t.find(r=>{let o=Nt(r);return this.logger.debug(`\u68C0\u67E5\u8DEF\u5F84 ${r}: ${o?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}`),o})||null,this.webPath?this.logger.info(`\u9759\u6001\u6587\u4EF6\u670D\u52A1\u8DEF\u5F84: ${this.webPath}`):(this.logger.warn("\u672A\u627E\u5230\u9759\u6001\u6587\u4EF6\u76EE\u5F55"),this.logger.debug("\u5C1D\u8BD5\u7684\u8DEF\u5F84:",t))}catch(e){this.logger.error("\u521D\u59CB\u5316\u9759\u6001\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25:",e)}}async handleStaticFile(e){let t=new URL(e.req.url).pathname;try{if(this.logger.debug(`\u5904\u7406\u9759\u6001\u6587\u4EF6\u8BF7\u6C42: ${t}`),!this.webPath)return this.createErrorPage(e,"\u627E\u4E0D\u5230\u524D\u7AEF\u8D44\u6E90\u6587\u4EF6");let r=t;if(r==="/"&&(r="/index.html"),r.includes(".."))return this.logger.warn(`\u8DEF\u5F84\u904D\u5386\u653B\u51FB\u5C1D\u8BD5: ${r}`),e.text("Forbidden",403);let o=fe(this.webPath,r);if(!Nt(o)){let s=fe(this.webPath,"index.html");return Nt(s)?(this.logger.debug(`SPA \u56DE\u9000\u5230 index.html: ${t}`),this.serveFile(e,s,"text/html")):(this.logger.debug(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`),e.text("Not Found",404))}let n=this.getContentType(o);return this.logger.debug(`\u670D\u52A1\u9759\u6001\u6587\u4EF6: ${o}, Content-Type: ${n}`),this.serveFile(e,o,n)}catch(r){return this.logger.error(`\u670D\u52A1\u9759\u6001\u6587\u4EF6\u9519\u8BEF (${t}):`,r),e.text("Internal Server Error",500)}}async serveFile(e,t,r){try{let o=await Ps(t);return r.startsWith("text/")||r.includes("javascript")||r.includes("json")?e.text(o.toString(),200,{"Content-Type":r}):e.body(new Uint8Array(o),200,{"Content-Type":r})}catch(o){throw this.logger.error(`\u8BFB\u53D6\u6587\u4EF6\u5931\u8D25: ${t}`,o),o}}getContentType(e){let t=e.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",js:"application/javascript",mjs:"application/javascript",css:"text/css",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",eot:"application/vnd.ms-fontobject",pdf:"application/pdf",txt:"text/plain",xml:"application/xml",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}createErrorPage(e,t){let r=`
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=`
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&&Nt(this.webPath)}getWebPath(){return this.webPath}reinitializeWebPath(){this.initializeWebPath()}}});var Lt,_o=m(()=>{"use strict";S();Lt=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 ze,Lo=m(()=>{"use strict";ze=(o=>(o.MCP="mcp",o.COZE="coze",o.HTTP="http",o.FUNCTION="function",o))(ze||{})});import Rs from"ajv";import Ht from"dayjs";var zt,Ho=m(()=>{"use strict";S();Y();Ct();Pt();Lo();zt=class{static{c(this,"ToolApiHandler")}logger;ajv;constructor(){this.logger=g.withTag("ToolApiHandler"),this.ajv=new Rs({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)),!V.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 V.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"),!d.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=d.getCustomMCPTools(),r=d.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(!d.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=d.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=d.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=d.getCustomMCPTools(),t=new Set(e.map(s=>s.name)),o=await new ge().getAllCachedTools(),n=[];for(let s of o)if(!t.has(s.name)){let a={name:s.name,description:s.description||"",inputSchema:s.inputSchema||{},handler:{type:"mcp",config:{serviceName:s.name.split("__")[0],toolName:s.name.split("__").slice(1).join("__")}}};n.push(a)}return this.logger.debug(`\u4ECE ${o.length} \u4E2A\u7F13\u5B58\u5DE5\u5177\u4E2D\u7B5B\u9009\u51FA ${n.length} \u4E2A\u672A\u542F\u7528\u5DE5\u5177`),n}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 u=e.getCustomMCPTools().map(p=>p.name);throw u.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: ${u.join(", ")}\u3002\u8BF7\u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u5DE5\u5177\u3002`)}try{let p=e.getCustomMCPTools().find(C=>C.name===r);p&&!p.description&&this.logger.warn(`customMCP \u5DE5\u5177 '${r}' \u7F3A\u5C11\u63CF\u8FF0\u4FE1\u606F`),p&&!p.inputSchema&&this.logger.warn(`customMCP \u5DE5\u5177 '${r}' \u7F3A\u5C11\u8F93\u5165\u53C2\u6570\u5B9A\u4E49`)}catch(u){throw this.logger.error(`\u9A8C\u8BC1 customMCP \u5DE5\u5177 '${r}' \u914D\u7F6E\u65F6\u51FA\u9519:`,u),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}let o=d.getMcpServers();if(!o[t]){let u=Object.keys(o);throw new Error(`\u670D\u52A1 '${t}' \u4E0D\u5B58\u5728\u3002\u53EF\u7528\u670D\u52A1: ${u.join(", ")}`)}let n=e.getService(t);if(!n)throw new Error(`\u670D\u52A1 '${t}' \u672A\u542F\u52A8\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u914D\u7F6E\u6216\u91CD\u65B0\u542F\u52A8 xiaozhi \u670D\u52A1\u3002`);if(!n.isConnected())throw new Error(`\u670D\u52A1 '${t}' \u672A\u8FDE\u63A5\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u6216\u91CD\u65B0\u542F\u52A8 xiaozhi \u670D\u52A1\u3002`);let s=n.getTools();if(!s.some(u=>u.name===r)){let u=s.map(p=>p.name);throw new Error(`\u5DE5\u5177 '${r}' \u5728\u670D\u52A1 '${t}' \u4E2D\u4E0D\u5B58\u5728\u3002\u53EF\u7528\u5DE5\u5177: ${u.join(", ")}`)}let h=d.getServerToolsConfig(t)[r];if(h&&!h.enable)throw new Error(`\u5DE5\u5177 '${r}' \u5DF2\u88AB\u7981\u7528\u3002\u8BF7\u4F7F\u7528 'xiaozhi mcp tool ${t} ${r} enable' \u542F\u7528\u8BE5\u5DE5\u5177\u3002`)}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 u=`\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25: ${(s.errors||[]).map(p=>{let C=p.instancePath||p.schemaPath||"",T=p.message||"\u672A\u77E5\u9519\u8BEF";if(p.keyword==="required")return`\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570: ${p.params?.missingProperty||"\u672A\u77E5\u5B57\u6BB5"}`;if(p.keyword==="type"){let b=p.params?.type||"\u672A\u77E5\u7C7B\u578B";return`\u53C2\u6570 ${C} \u7C7B\u578B\u9519\u8BEF\uFF0C\u671F\u671B: ${b}`}if(p.keyword==="enum"){let b=p.params?.allowedValues||[];return`\u53C2\u6570 ${C} \u503C\u65E0\u6548\uFF0C\u5141\u8BB8\u7684\u503C: ${b.join(", ")}`}return`\u53C2\u6570 ${C} ${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(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(ze).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(ze).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 d.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 $=this.createErrorResponse("MISSING_REQUIRED_FIELD","serviceName \u548C toolName \u662F\u5FC5\u9700\u5B57\u6BB5");return e.json($,400)}if(!V.isInitialized()){let $=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($,503)}let a=await V.getInstance();try{await this.validateServiceAndTool(a,r,o)}catch($){let tt=$ instanceof Error?$.message:String($),rt=this.createErrorResponse("SERVICE_OR_TOOL_NOT_FOUND",tt);return e.json(rt,404)}let h=await new ge().getAllCachedTools(),u=`${r}__${o}`,p=h.find($=>$.name===u);if(!p){let $=this.createErrorResponse("TOOL_NOT_FOUND",`\u5728\u7F13\u5B58\u4E2D\u672A\u627E\u5230\u5DE5\u5177: ${r}/${o}`);return e.json($,404)}let C=n||u,T=d.getCustomMCPTools();if(new Set(T.map($=>$.name)).has(C)){let $=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($,409)}let B={name:C,description:s||p.description||`MCP \u5DE5\u5177: ${r}/${o}`,inputSchema:p.inputSchema||{},handler:{type:"mcp",config:{serviceName:r,toolName:o}},stats:{usageCount:0,lastUsedTime:Ht().format("YYYY-MM-DD HH:mm:ss")}};d.addCustomMCPTool(B),this.logger.info(`\u6210\u529F\u6DFB\u52A0 MCP \u5DE5\u5177: ${C}`);let Z={tool:B,toolName:C,toolType:"mcp",addedAt:Ht().format("YYYY-MM-DD HH:mm:ss")};return e.json(this.createSuccessResponse(Z,`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);d.addCustomMCPTool(l),this.logger.info(`\u6210\u529F\u6DFB\u52A0 Coze \u5DE5\u5177: ${l.name}`);let h={tool:l,toolName:l.name,toolType:"coze",addedAt:Ht().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(ze).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(ze).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=d.getCustomMCPTools().find(T=>T.name===t);if(!h){let T=this.createErrorResponse("TOOL_NOT_FOUND",`\u5DE5\u5177 "${t}" \u4E0D\u5B58\u5728`);return e.json(T,404)}if(h.handler.type!=="proxy"||h.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)}!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 u=this.generateInputSchema(o,a),p={...h,description:s||h.description,inputSchema:u};d.updateCustomMCPTool(t,p),this.logger.info(`\u6210\u529F\u66F4\u65B0 Coze \u5DE5\u5177: ${t}`);let C={tool:p,toolName:t,toolType:"coze",updatedAt:Ht().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 r=this.createErrorResponse("INVALID_REQUEST","\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");return e.json(r,400)}return this.logger.info(`\u5904\u7406\u5220\u9664\u81EA\u5B9A\u4E49\u5DE5\u5177\u8BF7\u6C42: ${t}`),d.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),u={name:s,description:a,inputSchema:l,handler:h};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[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=d.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=d.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),!d.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=d.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=d.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 jt,zo=m(()=>{"use strict";S();ye();jt=class{static{c(this,"NotificationService")}logger;eventBus;clients=new Map;messageQueue=new Map;maxQueueSize=100;constructor(){this.logger=g.withTag("NotificationService"),this.eventBus=K(),this.setupEventListeners()}setupEventListeners(){this.eventBus.onEvent("config:updated",e=>{this.broadcastConfigUpdate(e.config)}),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 Ut,jo=m(()=>{"use strict";S();ye();Ut=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=K()}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 yr={};F(yr,{WebServer:()=>Sr});import{createServer as Is}from"http";import{serve as $s}from"@hono/node-server";import{Hono as xs}from"hono";import{cors as Os}from"hono/cors";import{WebSocketServer as As}from"ws";var Sr,Tr=m(()=>{"use strict";S();ut();So();Y();Pt();bo();Io();xo();Oo();Ao();ko();Do();No();_o();Ho();et();ye();zo();jo();Sr=class{static{c(this,"WebServer")}app;httpServer=null;wss=null;logger;port;eventBus;configService;statusService;notificationService;configApiHandler;statusApiHandler;serviceApiHandler;toolApiHandler;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??d.getWebUIPort()??9999}catch{this.port=e??9999}this.logger=g.withTag("WebServer"),this.eventBus=K(),this.configService=new ae,this.statusService=new Ut,this.notificationService=new jt,this.configApiHandler=new bt,this.statusApiHandler=new Lt(this.statusService),this.serviceApiHandler=new Dt(this.statusService),this.toolApiHandler=new zt,this.staticFileHandler=new _t,this.mcpRouteHandler=new Ot,this.realtimeNotificationHandler=new At(this.notificationService,this.statusService),this.heartbeatHandler=new xt(this.statusService,this.notificationService),this.app=new xs,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 V.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(!d.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C 'xiaozhi init' \u521D\u59CB\u5316\u914D\u7F6E");d.cleanupInvalidServerToolsConfig();let e=d.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=vo(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 Le.getInstance({healthCheckInterval:3e4,reconnectInterval:5e3,maxReconnectAttempts:10,loadBalanceStrategy:"round-robin",connectionTimeout:1e4}),this.mcpServiceManager&&this.xiaozhiConnectionManager.setServiceManager(this.mcpServiceManager),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 pe(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")}}getBestXiaozhiConnection(){return this.xiaozhiConnectionManager?this.xiaozhiConnectionManager.selectBestConnection():this.proxyMCPServer||null}getXiaozhiConnectionStatus(){return this.xiaozhiConnectionManager?{type:"multi-endpoint",manager:{healthyConnections:this.xiaozhiConnectionManager.getHealthyConnections().length,totalConnections:this.xiaozhiConnectionManager.getConnectionStatus().length,loadBalanceStats:this.xiaozhiConnectionManager.getLoadBalanceStats(),healthCheckStats:this.xiaozhiConnectionManager.getHealthCheckStats(),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 u=Math.min(o*s**(l-1),n);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("*",Os({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/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=>Te.getWorkspaces(e)),this.app?.get("/api/coze/workflows",e=>Te.getWorkflows(e)),this.app?.post("/api/coze/cache/clear",e=>Te.clearCache(e)),this.app?.get("/api/coze/cache/stats",e=>Te.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=$s({fetch:this.app.fetch,port:this.port,hostname:"0.0.0.0",createServer:Is});this.httpServer=e,this.wss=new As({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(),this.logger.info("\u6240\u6709\u8FDE\u63A5\u521D\u59CB\u5316\u5B8C\u6210")}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(),Ro(),this.proxyMCPServer?.disconnect(),this.logger.info("WebServer \u5B9E\u4F8B\u5DF2\u9500\u6BC1")}}});var Uo={};F(Uo,{ServiceManagerImpl:()=>Er});var Er,Fo=m(()=>{"use strict";te();Oe();Be();ct();Er=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 I?t:I.startFailed(t instanceof Error?t.message:String(t))}}async stop(){try{let e=this.getStatus();if(!e.running)throw I.notRunning();await this.processManager.gracefulKillProcess(e.pid),this.processManager.cleanupPidFile()}catch(e){throw e instanceof I?e:new I(`\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 I(`\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&&J.validatePort(e.port),e.mode&&!["normal","mcp-server","stdio"].includes(e.mode))throw new I(`\u65E0\u6548\u7684\u8FD0\u884C\u6A21\u5F0F: ${e.mode}`)}checkEnvironment(){if(!this.configManager.configExists())throw ve.configNotFound();try{if(!this.configManager.getConfig())throw new ve("\u914D\u7F6E\u6587\u4EF6\u65E0\u6548")}catch(e){throw e instanceof ve?e:new ve(`\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=R.getExecutablePath("cli"),n=r("node",[o,"start","--server",t.toString()],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:R.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(()=>(Co(),fo)),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=R.getMcpServerProxyPath(),o=t("node",[r],{stdio:"inherit",env:{...process.env,XIAOZHI_CONFIG_DIR:R.getConfigDir()}});this.processManager.savePidInfo(o.pid,"foreground")}async startWebServerInDaemon(e){let{spawn:t}=await import("child_process"),r=R.getWebServerStandalonePath();if(!(await import("fs")).default.existsSync(r))throw new I(`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:R.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(()=>(Tr(),yr)),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=W.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 Wo={};F(Wo,{TemplateManagerImpl:()=>Mr});import ks from"fs";import Me from"path";var Mr,Vo=m(()=>{"use strict";te();Ve();Oe();ct();Mr=class{static{c(this,"TemplateManagerImpl")}templateCache=new Map;async getAvailableTemplates(){try{let e=R.findTemplatesDir();if(!e)return[];let t=[],r=ks.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 v("\u65E0\u6CD5\u8BFB\u53D6\u6A21\u677F\u76EE\u5F55",R.findTemplatesDir()||"")}}async getTemplateInfo(e){try{if(J.validateTemplateName(e),this.templateCache.has(e))return this.templateCache.get(e);let t=R.getTemplatePath(e);if(!t)return null;let r=Me.join(t,"template.json"),o={};if(M.exists(r))try{let a=M.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 E?t:new v(`\u65E0\u6CD5\u83B7\u53D6\u6A21\u677F\u4FE1\u606F: ${e}`,"")}}async copyTemplate(e,t){await this.createProject({templateName:e,targetPath:t,projectName:Me.basename(t)})}async createProject(e){try{this.validateCreateOptions(e);let t=e.templateName||"default",r=await this.getTemplateInfo(t);if(!r)throw new v(`\u6A21\u677F\u4E0D\u5B58\u5728: ${t}`,"");let o=Me.resolve(e.targetPath);if(M.exists(o))throw v.alreadyExists(o);M.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 v||t instanceof E?t:new v(`\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=Me.join(t.path,o);if(!M.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 M.listDirectory(e,{recursive:!0,includeHidden:!1}).filter(r=>{let o=Me.relative(e,r);return!o.startsWith(".")&&o!=="template.json"&&!o.includes("node_modules")})}catch{return[]}}validateCreateOptions(e){J.validateRequired(e.targetPath,"targetPath"),J.validateRequired(e.projectName,"projectName"),J.validateProjectName(e.projectName),e.templateName&&J.validateTemplateName(e.templateName)}async copyTemplateFiles(e,t,r){try{M.copyDirectory(e.path,t,{exclude:["template.json",".git","node_modules"],overwrite:!1,recursive:!0})}catch(o){throw new v(`\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=Me.join(e,t);return M.exists(n)?[n]:[]}let r=M.listDirectory(e,{recursive:!0}),o=new RegExp(t.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*"));return r.filter(n=>{let s=Me.relative(e,n);return o.test(s)})}catch{return[]}}async replaceVariablesInFile(e,t){try{let r=M.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&&M.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 Ee(){return Pr.create()}var Pr,vr=m(()=>{"use strict";S();Y();rr();Ve();or();Oe();Be();ct();Vr();Pr=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",()=>gt),e.registerSingleton("platformUtils",()=>W),e.registerSingleton("formatUtils",()=>xe),e.registerSingleton("fileUtils",()=>M),e.registerSingleton("pathUtils",()=>R),e.registerSingleton("validation",()=>J),e.registerSingleton("configManager",()=>d),e.registerSingleton("logger",()=>g),e.registerSingleton("errorHandler",()=>re),e.registerSingleton("processManager",()=>{let t=(nr(),ee(Br));return new t.ProcessManagerImpl}),e.registerSingleton("daemonManager",()=>{let t=(Jr(),ee(Gr)),r=e.get("processManager"),o=e.get("logger");return new t.DaemonManagerImpl(r,o)}),e.registerSingleton("serviceManager",()=>{let t=(Fo(),ee(Uo)),r=e.get("processManager"),o=e.get("configManager"),n=e.get("logger");return new t.ServiceManagerImpl(r,o,n)}),e.registerSingleton("templateManager",()=>{let t=(Vo(),ee(Wo));return new t.TemplateManagerImpl}),e}};c(Ee,"createContainer")});var U,Pe=m(()=>{"use strict";U=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 Bo={};F(Bo,{ServiceCommandHandler:()=>wr});var wr,qo=m(()=>{"use strict";S();Pe();wr=class extends U{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{if(e.debug){let r=Dr("debug");Nr(r)}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 Go={};F(Go,{ConfigCommandHandler:()=>Rr});import Ds from"path";import w from"chalk";import br from"ora";var Rr,Jo=m(()=>{"use strict";Pe();Rr=class extends U{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=br("\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(w.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=Ds.join(n,s);console.log(w.green(`\u2705 \u914D\u7F6E\u6587\u4EF6\u5DF2\u521B\u5EFA: ${s}`)),console.log(w.yellow("\u{1F4DD} \u8BF7\u7F16\u8F91\u914D\u7F6E\u6587\u4EF6\u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9:")),console.log(w.gray(` \u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84: ${a}`)),console.log(w.yellow("\u{1F4A1} \u6216\u8005\u4F7F\u7528\u547D\u4EE4\u8BBE\u7F6E:")),console.log(w.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=br("\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(w.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(w.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):n.length===1?console.log(w.green(`MCP \u7AEF\u70B9: ${n[0]}`)):(console.log(w.green(`MCP \u7AEF\u70B9 (${n.length} \u4E2A):`)),n.forEach((s,a)=>{console.log(w.gray(` ${a+1}. ${s}`))}));break}case"mcpServers":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(w.green("MCP \u670D\u52A1:"));for(let[n,s]of Object.entries(o.mcpServers)){let a=s;"type"in a&&a.type==="sse"?console.log(w.gray(` ${n}: [SSE] ${a.url}`)):console.log(w.gray(` ${n}: ${a.command} ${a.args.join(" ")}`))}break;case"connection":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let n=r.getConnectionConfig();console.log(w.green("\u8FDE\u63A5\u914D\u7F6E:")),console.log(w.gray(` \u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${n.heartbeatInterval}ms`)),console.log(w.gray(` \u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${n.heartbeatTimeout}ms`)),console.log(w.gray(` \u91CD\u8FDE\u95F4\u9694: ${n.reconnectInterval}ms`));break}case"heartbeatInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(w.green(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${r.getHeartbeatInterval()}ms`));break;case"heartbeatTimeout":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(w.green(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${r.getHeartbeatTimeout()}ms`));break;case"reconnectInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(w.green(`\u91CD\u8FDE\u95F4\u9694: ${r.getReconnectInterval()}ms`));break;default:t.fail(`\u672A\u77E5\u7684\u914D\u7F6E\u9879: ${e}`),console.log(w.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=br("\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(w.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(w.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 Xo={};F(Xo,{ProjectCommandHandler:()=>Ir});import Ns from"path";import x from"chalk";import _s from"ora";var Ir,Ko=m(()=>{"use strict";Pe();Ir=class extends U{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=_s("\u521D\u59CB\u5316\u9879\u76EE...").start();try{let o=this.getService("templateManager"),n=this.getService("fileUtils"),s=Ns.join(process.cwd(),e);if(await n.exists(s)){r.fail(`\u76EE\u5F55 "${e}" \u5DF2\u5B58\u5728`),console.log(x.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(x.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(x.yellow(`\u{1F4A1} \u4F60\u662F\u60F3\u4F7F\u7528\u6A21\u677F "${h}" \u5417\uFF1F`)),await this.askUserConfirmation(x.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(x.green("\u2705 \u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(x.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(x.gray(` cd ${e}`)),console.log(x.gray(" pnpm install # \u5B89\u88C5\u4F9D\u8D56")),console.log(x.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9")),console.log(x.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(x.green("\u2705 \u57FA\u672C\u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(x.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(x.gray(` cd ${e}`)),console.log(x.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9\u548C\u670D\u52A1")),console.log(x.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1")),console.log(x.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 --template \u9009\u9879\u53EF\u4EE5\u4ECE\u6A21\u677F\u521B\u5EFA\u9879\u76EE"))}showAvailableTemplates(e){console.log(x.yellow("\u53EF\u7528\u7684\u6A21\u677F:"));for(let t of e)console.log(x.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 Ft,Zo=m(()=>{"use strict";S();nr();Y();Ft=class{static{c(this,"ToolCallService")}logger;processManager;baseUrl;constructor(){this.logger=g.withTag("ToolCallService"),this.processManager=new qe;try{let e=d.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 Vt={};F(Vt,{getDisplayWidth:()=>xr,listMcpServers:()=>Ls,listServerTools:()=>Hs,setToolEnabled:()=>zs,truncateToWidth:()=>Wt});import f from"chalk";import Yo from"cli-table3";import $r from"ora";function xr(i){let e=0;for(let t of i)/[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef]/.test(t)?e+=2:e+=1;return e}function Wt(i,e){if(xr(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 Ls(i={}){let e=$r("\u83B7\u53D6 MCP \u670D\u52A1\u5217\u8868...").start();try{let t=d.getMcpServers(),r=Object.keys(t),o=d.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 u of r){let p=d.getServerToolsConfig(u),C=Object.keys(p);l.push(...C)}if(n){let u=o.map(p=>p.name);l.push(...u)}for(let u of l){let p=xr(u);p>a&&(a=p)}a=Math.max(10,Math.min(a+2,30));let h=new Yo({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 u of o){let p=Wt(u.description||"",32);h.push(["customMCP",u.name,f.green("\u542F\u7528"),p])}for(let u of r){let p=d.getServerToolsConfig(u),C=Object.keys(p);if(C.length===0)h.push([f.gray(u),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 T of C){let b=p[T],B=b.enable?f.green("\u542F\u7528"):f.red("\u7981\u7528"),Z=Wt(b.description||"",32);h.push([u,T,B,Z])}}}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=d.getServerToolsConfig(a),u=Object.keys(h).length,p=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(" "))}`),u>0?console.log(` \u5DE5\u5177: ${f.green(p)} \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 Hs(i){let e=$r(`\u83B7\u53D6 ${i} \u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868...`).start();try{if(!d.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=d.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 Yo({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=Wt(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=$r(`${r}\u5DE5\u5177 ${i}/${e}...`).start();try{if(!d.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=d.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}d.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 Bt=m(()=>{"use strict";Y();c(xr,"getDisplayWidth");c(Wt,"truncateToWidth");c(Ls,"listMcpServers");c(Hs,"listServerTools");c(zs,"setToolEnabled")});var Qo={};F(Qo,{McpCommandHandler:()=>Or});import we from"chalk";var Or,en=m(()=>{"use strict";Zo();Pe();Or=class extends U{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(we.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(()=>(Bt(),Vt));await t(e)}catch(t){this.handleError(t)}}async handleServer(e){try{let{listServerTools:t}=await Promise.resolve().then(()=>(Bt(),Vt));await t(e)}catch(t){this.handleError(t)}}async handleTool(e,t,r){try{let{setToolEnabled:o}=await Promise.resolve().then(()=>(Bt(),Vt));await o(e,t,r)}catch(o){this.handleError(o)}}async handleCall(e,t,r){try{let o=new Ft,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(we.red("\u9519\u8BEF:"),o.message),o.message.includes("\u670D\u52A1\u672A\u542F\u52A8")?(console.log(),console.log(we.yellow("\u{1F4A1} \u8BF7\u5148\u542F\u52A8\u670D\u52A1:")),console.log(we.gray(" xiaozhi start # \u524D\u53F0\u542F\u52A8")),console.log(we.gray(" xiaozhi start -d # \u540E\u53F0\u542F\u52A8"))):o.message.includes("\u53C2\u6570\u683C\u5F0F\u9519\u8BEF")&&(console.log(),console.log(we.yellow("\u{1F4A1} \u6B63\u786E\u683C\u5F0F\u793A\u4F8B:")),console.log(we.gray(` xiaozhi mcp call ${e} ${t} --args '{"param": "value"}'`))),process.exit(1)}}}});var tn={};F(tn,{EndpointCommandHandler:()=>Ar});import je from"chalk";import qt from"ora";var Ar,rn=m(()=>{"use strict";Pe();Ar=class extends U{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=qt("\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(je.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):(console.log(je.green(`\u5171 ${r.length} \u4E2A\u7AEF\u70B9:`)),r.forEach((o,n)=>{console.log(je.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=qt("\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(je.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=qt("\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(je.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=qt("\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(je.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 on={};F(on,{UICommandHandler:()=>kr});import be from"chalk";import js from"ora";var kr,nn=m(()=>{"use strict";Pe();kr=class extends U{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=js("\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(be.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(()=>(Tr(),yr));await new r().start(),e.succeed("UI \u670D\u52A1\u5DF2\u542F\u52A8");let n=t.getWebUIPort();console.log(be.green("\u2705 \u914D\u7F6E\u7BA1\u7406\u7F51\u9875\u5DF2\u542F\u52A8\uFF0C\u53EF\u901A\u8FC7\u4EE5\u4E0B\u5730\u5740\u8BBF\u95EE:")),console.log(be.green(` \u672C\u5730\u8BBF\u95EE: http://localhost:${n}`)),console.log(be.green(` \u7F51\u7EDC\u8BBF\u95EE: http://<\u4F60\u7684IP\u5730\u5740>:${n}`)),console.log(be.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(be.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(be.gray(`\u{1F4A1} \u63D0\u793A: \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE: ${e}`))}}}});vr();import he from"chalk";import{Command as Us}from"commander";rr();var Gt=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}=(qo(),ee(Bo));return new e(this.container)}createConfigCommandHandler(){let{ConfigCommandHandler:e}=(Jo(),ee(Go));return new e(this.container)}createProjectCommandHandler(){let{ProjectCommandHandler:e}=(Ko(),ee(Xo));return new e(this.container)}createMcpCommandHandler(){let{McpCommandHandler:e}=(en(),ee(Qo));return new e(this.container)}createEndpointCommandHandler(){let{EndpointCommandHandler:e}=(rn(),ee(tn));return new e(this.container)}createUICommandHandler(){let{UICommandHandler:e}=(nn(),ee(on));return new e(this.container)}};var Jt=class{constructor(e){this.container=e;this.handlerFactory=new Gt(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){re.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){re.handle(l)}})}r.action(async(...o)=>{try{let s=o[o.length-1].opts();await t.execute(o.slice(0,-1),s)}catch(n){re.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){re.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 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",`
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){re.handle(a)}})}}};var Xt=new Us;function Fs(){console.log(he.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(he.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(he.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(Fs,"showHelp");function Ws(i){let e=i.get("versionUtils"),t=i.get("platformUtils"),r=e.getVersionInfo(),o=t.getSystemInfo();console.log(he.blue("\u{1F916} \u5C0F\u667A MCP \u5BA2\u6237\u7AEF - \u8BE6\u7EC6\u4FE1\u606F")),console.log(),console.log(he.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(he.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(he.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(Ws,"showDetailedInfo");async function Vs(){try{if(process.argv.includes("--info")){let t=await Ee();Ws(t),process.exit(0)}if(process.argv.includes("--version-info")){let t=await Ee(),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 Ee(),e=new Jt(i);Xt.name("xiaozhi").description("\u5C0F\u667A MCP \u5BA2\u6237\u7AEF - \u5F3A\u5927\u7684 Model Context Protocol \u5BA2\u6237\u7AEF"),await e.registerCommands(Xt),Xt.helpOption("-h, --help","\u663E\u793A\u5E2E\u52A9\u4FE1\u606F").addHelpText("after",`
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",`
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&&(Fs(),process.exit(0)),await Xt.parseAsync(process.argv)}catch(i){console.error(he.red("\u7A0B\u5E8F\u542F\u52A8\u5931\u8D25:"),i instanceof Error?i.message:String(i)),process.exit(1)}}c(Vs,"main");Vs().catch(i=>{console.error(he.red("\u7A0B\u5E8F\u6267\u884C\u5931\u8D25:"),i instanceof Error?i.message:String(i)),process.exit(1)});
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)});
129
129
  //# sourceMappingURL=cli.js.map