xiaozhi-client 1.7.0 → 1.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -397
- package/dist/WebServerStandalone.js +34 -13
- package/dist/WebServerStandalone.js.map +1 -1
- package/dist/cli.js +36 -15
- package/dist/cli.js.map +1 -1
- package/dist/mcpServerProxy.js +28 -7
- package/dist/mcpServerProxy.js.map +1 -1
- package/dist/package.json +10 -5
- package/docs/{Architecture.md → development/architecture.mdx} +4 -1
- package/docs/docs.json +51 -0
- package/docs/getting-started/install.mdx +191 -0
- package/docs/getting-started/intro.mdx +11 -0
- package/docs/getting-started/quickstart.mdx +108 -0
- package/docs/images/preview.png +0 -0
- package/docs/reference/command.mdx +15 -0
- package/docs/usage/add-mcp-server.mdx +6 -0
- package/docs/usage/as-a-mcp-server.mdx +6 -0
- package/docs/usage/docker.mdx +99 -0
- package/docs/usage/modelscope.mdx +6 -0
- package/docs/usage/web-control.mdx +6 -0
- package/package.json +10 -5
- package/web/dist/assets/{form-utils-DmILtYcF.js → form-utils-RpkiEEz8.js} +2 -2
- package/web/dist/assets/{form-utils-DmILtYcF.js.map → form-utils-RpkiEEz8.js.map} +1 -1
- package/web/dist/assets/index-BjG6tl-5.css +1 -0
- package/web/dist/assets/index-BvDVeF-B.js +31 -0
- package/web/dist/assets/index-BvDVeF-B.js.map +1 -0
- package/web/dist/assets/radix-ui-BA32w1ww.js +2 -0
- package/web/dist/assets/radix-ui-BA32w1ww.js.map +1 -0
- package/web/dist/assets/react-vendor-CoesXubw.js +234 -0
- package/web/dist/assets/react-vendor-CoesXubw.js.map +1 -0
- package/web/dist/assets/{utils-DYeV2b9J.js → utils-N_0RTAPv.js} +2 -2
- package/web/dist/assets/{utils-DYeV2b9J.js.map → utils-N_0RTAPv.js.map} +1 -1
- package/web/dist/index.html +6 -6
- package/docs/CLI.md +0 -928
- package/docs/examples-usage.md +0 -647
- package/web/dist/assets/index-Cz9EK1KU.css +0 -1
- package/web/dist/assets/index-Uy1wxZ-_.js +0 -31
- package/web/dist/assets/index-Uy1wxZ-_.js.map +0 -1
- package/web/dist/assets/radix-ui-DW48STyt.js +0 -2
- package/web/dist/assets/radix-ui-DW48STyt.js.map +0 -1
- package/web/dist/assets/react-vendor-CP-QpYlg.js +0 -189
- package/web/dist/assets/react-vendor-CP-QpYlg.js.map +0 -1
- /package/docs/{RELEASE_GUIDE.md → development/todo__release-guide.md} +0 -0
- /package/docs/{SettingManager.md → development/todo__setting-manager.md} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,23 +1,44 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
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=An(new Date),n=t.get(e.level)||{name:"UNKNOWN",color:c(a=>a,"color")},o=n.color(`[${n.name}]`),s=e.msg;if(e.args&&Array.isArray(e.args)){let a=e.args.map(l=>typeof l=="object"?JSON.stringify(l):String(l)).join(" ");s=`${s} ${a}`}return`[${r}] ${o} ${s}`}initLogFile(e){this.logFilePath=W.join(e,"xiaozhi.log"),this.rotateLogFileIfNeeded(),D.existsSync(this.logFilePath)||D.writeFileSync(this.logFilePath,""),this.pinoInstance=this.createPinoInstance()}enableFileLogging(e){e&&this.logFilePath&&(this.pinoInstance=this.createPinoInstance())}info(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}success(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}warn(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.warn(e):this.pinoInstance.warn({args:t},e):this.pinoInstance.warn(e,t[0]||"")}error(e,...t){if(typeof e=="string")if(t.length===0)this.pinoInstance.error(e);else{let r=t.map(n=>n instanceof Error?{message:n.message,stack:n.stack,name:n.name,cause:n.cause}:n);this.pinoInstance.error({args:r},e)}else{let r=this.enhanceErrorObject(e);this.pinoInstance.error(r,t[0]||"")}}debug(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.debug(e):this.pinoInstance.debug({args:t},e):this.pinoInstance.debug(e,t[0]||"")}log(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}enhanceErrorObject(e){let t={...e};for(let[r,n]of Object.entries(t))n instanceof Error&&(t[r]={message:n.message,stack:n.stack,name:n.name,cause:n.cause});return t}rotateLogFileIfNeeded(){if(!(!this.logFilePath||!D.existsSync(this.logFilePath)))try{D.statSync(this.logFilePath).size>this.maxLogFileSize&&this.rotateLogFile()}catch{}}rotateLogFile(){if(this.logFilePath)try{let e=W.dirname(this.logFilePath),t=W.basename(this.logFilePath,".log");for(let n=this.maxLogFiles-1;n>=1;n--){let o=W.join(e,`${t}.${n}.log`),s=W.join(e,`${t}.${n+1}.log`);D.existsSync(o)&&(n===this.maxLogFiles-1?D.unlinkSync(o):D.renameSync(o,s))}let r=W.join(e,`${t}.1.log`);D.renameSync(this.logFilePath,r)}catch{}}cleanupOldLogs(){if(this.logFilePath)try{let e=W.dirname(this.logFilePath),t=W.basename(this.logFilePath,".log");for(let r=this.maxLogFiles+1;r<=this.maxLogFiles+10;r++){let n=W.join(e,`${t}.${r}.log`);D.existsSync(n)&&D.unlinkSync(n)}}catch{}}setLogFileOptions(e,t){this.maxLogFileSize=e,this.maxLogFiles=t}withTag(e){return this}close(){}},g=new Oe});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 It(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 dr=d(()=>{"use strict";c(Dn,"getMcpServerCommunicationType");c(It,"validateMcpServerConfig")});import{copyFileSync as Nn,existsSync as Ge,readFileSync as Hn,writeFileSync as kn}from"fs";import{dirname as jn,resolve as he}from"path";import{fileURLToPath as zn}from"url";import*as qe from"comment-json";import _n from"dayjs";import xt from"json5";import*as fr from"json5-writer";var mr,$t,Ot,m,K=d(()=>{"use strict";y();dr();mr=jn(zn(import.meta.url)),$t={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},Ot=class i{static{c(this,"ConfigManager")}static instance;defaultConfigPath;config=null;currentConfigPath=null;json5Writer=null;constructor(){let e=[he(mr,"templates","default","xiaozhi.config.json"),he(mr,"..","templates","default","xiaozhi.config.json"),he(process.cwd(),"templates","default","xiaozhi.config.json")];this.defaultConfigPath=e.find(t=>Ge(t))||e[0]}getConfigFilePath(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),t=["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"];for(let r of t){let n=he(e,r);if(Ge(n))return n}return he(e,"xiaozhi.config.json")}getConfigFileFormat(e){return e.endsWith(".json5")?"json5":e.endsWith(".jsonc")?"jsonc":"json"}static getInstance(){return i.instance||(i.instance=new i),i.instance}configExists(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),t=["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"];for(let r of t){let n=he(e,r);if(Ge(n))return!0}return!1}initConfig(e="json"){if(!Ge(this.defaultConfigPath))throw new Error(`\u9ED8\u8BA4\u914D\u7F6E\u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${this.defaultConfigPath}`);if(this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u521D\u59CB\u5316");let t=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),r=`xiaozhi.config.${e}`,n=he(t,r);Nn(this.defaultConfigPath,n),this.config=null,this.json5Writer=null}loadConfig(){if(!this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C xiaozhi init \u521D\u59CB\u5316\u914D\u7F6E");try{let e=this.getConfigFilePath();this.currentConfigPath=e;let t=this.getConfigFileFormat(e),n=Hn(e,"utf8").replace(/^\uFEFF/,""),o;switch(t){case"json5":o=xt.parse(n),this.json5Writer=fr.load(n);break;case"jsonc":o=qe.parse(n);break;default:o=JSON.parse(n);break}return this.validateConfig(o),o}catch(e){throw e instanceof SyntaxError?new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF: ${e.message}`):e}}validateConfig(e){if(!e||typeof e!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A\u6839\u5BF9\u8C61\u65E0\u6548");let t=e;if(t.mcpEndpoint===void 0||t.mcpEndpoint===null)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5B57\u6BB5\u65E0\u6548");if(typeof t.mcpEndpoint!="string")if(Array.isArray(t.mcpEndpoint)){if(t.mcpEndpoint.length===0)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let r of t.mcpEndpoint)if(typeof r!="string"||r.trim()==="")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u5B57\u7B26\u4E32\u6570\u7EC4");if(!t.mcpServers||typeof t.mcpServers!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers \u5B57\u6BB5\u65E0\u6548");for(let[r,n]of Object.entries(t.mcpServers)){if(!n||typeof n!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${r} \u65E0\u6548`);let o=It(r,n);if(!o.valid)throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A${o.error}`)}}getConfig(){return this.config=this.loadConfig(),JSON.parse(JSON.stringify(this.config))}getMutableConfig(){return this.config||(this.config=this.loadConfig()),this.config}getMcpEndpoint(){let e=this.getConfig();return Array.isArray(e.mcpEndpoint)?e.mcpEndpoint[0]||"":e.mcpEndpoint}getMcpEndpoints(){let e=this.getConfig();return Array.isArray(e.mcpEndpoint)?[...e.mcpEndpoint]:e.mcpEndpoint?[e.mcpEndpoint]:[]}getMcpServers(){return this.getConfig().mcpServers}getMcpServerConfig(){return this.getConfig().mcpServerConfig||{}}getServerToolsConfig(e){return this.getMcpServerConfig()[e]?.tools||{}}isToolEnabled(e,t){return this.getServerToolsConfig(e)[t]?.enable!==!1}updateMcpEndpoint(e){if(Array.isArray(e)){if(e.length===0)throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let r of e)if(!r||typeof r!="string")throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}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 n=[...r,e];t.mcpEndpoint=n,this.saveConfig(t)}removeMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getMutableConfig(),r=this.getMcpEndpoints();if(r.indexOf(e)===-1)throw new Error(`MCP \u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(r.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");let o=r.filter(s=>s!==e);t.mcpEndpoint=o,this.saveConfig(t)}updateMcpServer(e,t){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let r=It(e,t);if(!r.valid)throw new Error(r.error||"\u670D\u52A1\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");let n=this.getMutableConfig();n.mcpServers[e]=t,this.saveConfig(n)}removeMcpServer(e){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getConfig();if(!t.mcpServers[e])throw new Error(`\u670D\u52A1 ${e} \u4E0D\u5B58\u5728`);let r={...t.mcpServers};delete r[e];let n={...t,mcpServers:r};this.saveConfig(n)}updateServerToolsConfig(e,t){let r=this.getMutableConfig();r.mcpServerConfig||(r.mcpServerConfig={}),Object.keys(t).length===0?delete r.mcpServerConfig[e]:r.mcpServerConfig[e]={tools:t},this.saveConfig(r)}removeServerToolsConfig(e){let r={...this.getConfig()};r.mcpServerConfig&&(delete r.mcpServerConfig[e],this.saveConfig(r))}cleanupInvalidServerToolsConfig(){let e=this.getMutableConfig();if(!e.mcpServerConfig)return;let t=Object.keys(e.mcpServers),n=Object.keys(e.mcpServerConfig).filter(o=>!t.includes(o));if(n.length>0){for(let o of n)delete e.mcpServerConfig[o];this.saveConfig(e),g.info(`\u5DF2\u6E05\u7406 ${n.length} \u4E2A\u65E0\u6548\u7684\u670D\u52A1\u5DE5\u5177\u914D\u7F6E: ${n.join(", ")}`)}}setToolEnabled(e,t,r,n){let o=this.getMutableConfig();o.mcpServerConfig||(o.mcpServerConfig={}),o.mcpServerConfig[e]||(o.mcpServerConfig[e]={tools:{}}),o.mcpServerConfig[e].tools[t]={...o.mcpServerConfig[e].tools[t],enable:r,...n&&{description:n}},this.saveConfig(o)}saveConfig(e){try{this.validateConfig(e);let t;this.currentConfigPath?t=this.currentConfigPath:(t=this.getConfigFilePath(),this.currentConfigPath=t);let r=this.getConfigFileFormat(t),n;switch(r){case"json5":try{this.json5Writer?(this.json5Writer.write(e),n=this.json5Writer.toSource()):(console.warn("\u6CA1\u6709 json5Writer \u5B9E\u4F8B\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F"),n=xt.stringify(e,null,2))}catch(o){console.warn("\u4F7F\u7528 json5-writer \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F:",o),n=xt.stringify(e,null,2)}break;case"jsonc":try{n=qe.stringify(e,null,2)}catch(o){console.warn("\u4F7F\u7528 comment-json \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON \u683C\u5F0F:",o),n=JSON.stringify(e,null,2)}break;default:n=JSON.stringify(e,null,2);break}kn(t,n,"utf8"),this.config=e,this.notifyConfigUpdate(e)}catch(t){throw new Error(`\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}reloadConfig(){this.config=null,this.currentConfigPath=null,this.json5Writer=null}getConfigPath(){return this.getConfigFilePath()}getDefaultConfigPath(){return this.defaultConfigPath}getConnectionConfig(){let t=this.getConfig().connection||{};return{heartbeatInterval:t.heartbeatInterval??$t.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??$t.heartbeatTimeout,reconnectInterval:t.reconnectInterval??$t.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{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 o=n.mcpServerConfig[e].tools[t],s=o.usageCount||0,a=o.lastUsedTime;o.usageCount=s+1,(!a||new Date(r)>new Date(a))&&(o.lastUsedTime=_n(r).format("YYYY-MM-DD HH:mm:ss")),this.saveConfig(n),g.debug(`\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${e}/${t}, \u4F7F\u7528\u6B21\u6570: ${o.usageCount}`)}catch(n){g.error(`\u66F4\u65B0\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${e}/${t}): ${n instanceof Error?n.message:String(n)}`)}}setHeartbeatInterval(e){if(e<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatInterval:e})}setHeartbeatTimeout(e){if(e<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatTimeout:e})}setReconnectInterval(e){if(e<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({reconnectInterval:e})}getModelScopeConfig(){return this.getConfig().modelscope||{}}getModelScopeApiKey(){return this.getModelScopeConfig().apiKey||process.env.MODELSCOPE_API_TOKEN}updateModelScopeConfig(e){let t=this.getMutableConfig();t.modelscope||(t.modelscope={}),Object.assign(t.modelscope,e),this.saveConfig(t)}setModelScopeApiKey(e){if(!e||typeof e!="string")throw new Error("API Key \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");this.updateModelScopeConfig({apiKey:e})}getCustomMCPConfig(){return this.getConfig().customMCP||null}getCustomMCPTools(){let e=this.getCustomMCPConfig();return!e||!e.tools?[]:e.tools}validateCustomMCPTools(e){if(!Array.isArray(e))return!1;for(let t of e){if(!t.name||typeof t.name!="string")return 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"].includes(t.handler.type))return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7684 handler.type \u5FC5\u987B\u662F 'proxy', 'function', 'http', 'script' \u6216 'chain'`),!1;if(!this.validateHandlerConfig(t.name,t.handler))return!1;if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(t.name))return g.warn(`CustomMCP \u5DE5\u5177\u540D\u79F0 ${t.name} \u683C\u5F0F\u65E0\u6548\uFF0C\u5FC5\u987B\u4EE5\u5B57\u6BCD\u5F00\u5934\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF`),!1}return!0}validateHandlerConfig(e,t){switch(t.type){case"proxy":return this.validateProxyHandler(e,t);case"http":return this.validateHttpHandler(e,t);case"function":return this.validateFunctionHandler(e,t);case"script":return this.validateScriptHandler(e,t);case"chain":return this.validateChainHandler(e,t);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)}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}}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})}},m=Ot.getInstance()});var At,ye,Ae,v,Dt,De=d(()=>{"use strict";At={NAME:"xiaozhi-mcp-service",DEFAULT_PORT:3e3,DEFAULT_WEB_UI_PORT:9999,PID_FILE:"xiaozhi.pid",LOG_FILE:"xiaozhi.log"},ye={FILE_NAMES:["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"],DEFAULT_FILE:"xiaozhi.config.default.json",DIR_ENV_VAR:"XIAOZHI_CONFIG_DIR"},Ae={WORK_DIR:".xiaozhi",TEMPLATES_DIR:"templates",LOGS_DIR:"logs"},v={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"},Dt={PROCESS_STOP:3e3,SERVICE_START:1e4,NETWORK_REQUEST:5e3,FILE_OPERATION:2e3}});var Fn,Ln,Xe,Cr=d(()=>{"use strict";De();Fn={[v.CONFIG_ERROR]:'\u8FD0\u884C "xiaozhi --help" \u67E5\u770B\u914D\u7F6E\u76F8\u5173\u547D\u4EE4',[v.SERVICE_ERROR]:'\u8FD0\u884C "xiaozhi status" \u68C0\u67E5\u670D\u52A1\u72B6\u6001',[v.VALIDATION_ERROR]:"\u68C0\u67E5\u8F93\u5165\u53C2\u6570\u662F\u5426\u6B63\u786E",[v.FILE_ERROR]:"\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u548C\u6743\u9650",[v.PROCESS_ERROR]:"\u68C0\u67E5\u8FDB\u7A0B\u72B6\u6001\u548C\u6743\u9650",[v.NETWORK_ERROR]:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C\u9632\u706B\u5899\u8BBE\u7F6E",[v.PERMISSION_ERROR]:"\u5C1D\u8BD5\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"},Ln={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"]},Xe=class{static{c(this,"ERROR_MESSAGES")}static getHelpMessage(e){return Fn[e]}static getSolutions(e){return Ln[e]||[]}static formatError(e,t){return`${t?`[${t}] `:""}${e.message}`}static getFriendlyMessage(e){return{[v.CONFIG_ERROR]:"\u914D\u7F6E\u6587\u4EF6\u76F8\u5173\u9519\u8BEF",[v.SERVICE_ERROR]:"\u670D\u52A1\u8FD0\u884C\u76F8\u5173\u9519\u8BEF",[v.VALIDATION_ERROR]:"\u8F93\u5165\u9A8C\u8BC1\u9519\u8BEF",[v.FILE_ERROR]:"\u6587\u4EF6\u64CD\u4F5C\u9519\u8BEF",[v.PROCESS_ERROR]:"\u8FDB\u7A0B\u7BA1\u7406\u9519\u8BEF",[v.NETWORK_ERROR]:"\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF",[v.PERMISSION_ERROR]:"\u6743\u9650\u4E0D\u8DB3\u9519\u8BEF"}[e]||"\u672A\u77E5\u9519\u8BEF"}static isRecoverable(e){return[v.NETWORK_ERROR,v.FILE_ERROR,v.SERVICE_ERROR].includes(e)}static getSeverity(e){return{[v.VALIDATION_ERROR]:"low",[v.FILE_ERROR]:"medium",[v.CONFIG_ERROR]:"medium",[v.NETWORK_ERROR]:"medium",[v.SERVICE_ERROR]:"high",[v.PROCESS_ERROR]:"high",[v.PERMISSION_ERROR]:"critical"}[e]||"medium"}}});var N,pe,T,E,C,se,Z=d(()=>{"use strict";De();N=class i extends Error{constructor(t,r,n=1,o){super(t);this.code=r;this.exitCode=n;this.suggestions=o;this.name="CLIError",Error.captureStackTrace&&Error.captureStackTrace(this,i)}static{c(this,"CLIError")}static withSuggestions(t,r,n){return new i(t,r,1,n)}},pe=class i extends N{static{c(this,"ConfigError")}constructor(e,t){super(e,v.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"])}},T=class i extends N{static{c(this,"ServiceError")}constructor(e,t){super(e,v.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 N{static{c(this,"ValidationError")}constructor(e,t){super(`\u9A8C\u8BC1\u5931\u8D25: ${t} - ${e}`,v.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)}},C=class i extends N{static{c(this,"FileError")}constructor(e,t,r){let n=t?`${e}: ${t}`:e;super(n,v.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"])}},se=class i extends N{static{c(this,"ProcessError")}constructor(e,t,r){let n=t?`${e} (PID: ${t})`:e;super(n,v.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 k from"chalk";var Q,Nt=d(()=>{"use strict";Cr();Z();Q=class i{static{c(this,"ErrorHandler")}static handle(e){e instanceof N?i.handleCLIError(e):i.handleUnknownError(e),process.exit(1)}static handleCLIError(e){if(console.error(k.red(`\u274C \u9519\u8BEF: ${e.message}`)),process.env.DEBUG&&console.error(k.gray(`\u9519\u8BEF\u7801: ${e.code}`)),e.suggestions&&e.suggestions.length>0){console.log(k.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of e.suggestions)console.log(k.gray(` ${r}`))}let t=Xe.getHelpMessage(e.code);t&&console.log(k.blue(`\u2139\uFE0F ${t}`))}static handleUnknownError(e){console.error(k.red(`\u274C \u672A\u77E5\u9519\u8BEF: ${e.message}`)),process.env.DEBUG||process.env.NODE_ENV==="development"?(console.error(k.gray("\u5806\u6808\u4FE1\u606F:")),console.error(k.gray(e.stack))):console.log(k.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 N?r:r instanceof Error?new N(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new N(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static handleSync(e,t){try{return e()}catch(r){throw r instanceof N?r:r instanceof Error?new N(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new N(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static warn(e,t){if(console.warn(k.yellow(`\u26A0\uFE0F \u8B66\u544A: ${e}`)),t&&t.length>0){console.log(k.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of t)console.log(k.gray(` ${r}`))}}static info(e){console.log(k.blue(`\u2139\uFE0F ${e}`))}static success(e){console.log(k.green(`\u2705 ${e}`))}}});import O from"fs";import B from"path";var M,Ne=d(()=>{"use strict";Z();M=class i{static{c(this,"FileUtils")}static exists(e){try{return O.existsSync(e)}catch{return!1}}static ensureDir(e){try{O.existsSync(e)||O.mkdirSync(e,{recursive:!0})}catch{throw new C("\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55",e)}}static readFile(e,t="utf8"){try{if(!i.exists(e))throw C.notFound(e);return O.readFileSync(e,t)}catch(r){throw r instanceof C?r:new C("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6",e)}}static writeFile(e,t,r){try{if(!r?.overwrite&&i.exists(e))throw C.alreadyExists(e);let n=B.dirname(e);i.ensureDir(n),O.writeFileSync(e,t,"utf8")}catch(n){throw n instanceof C?n:new C("\u65E0\u6CD5\u5199\u5165\u6587\u4EF6",e)}}static copyFile(e,t,r){try{if(!i.exists(e))throw C.notFound(e);if(!r?.overwrite&&i.exists(t))throw C.alreadyExists(t);let n=B.dirname(t);i.ensureDir(n),O.copyFileSync(e,t)}catch(n){throw n instanceof C?n:new C("\u65E0\u6CD5\u590D\u5236\u6587\u4EF6",e)}}static deleteFile(e){try{i.exists(e)&&O.unlinkSync(e)}catch{throw new C("\u65E0\u6CD5\u5220\u9664\u6587\u4EF6",e)}}static copyDirectory(e,t,r={}){try{if(!i.exists(e))throw C.notFound(e);i.ensureDir(t);let n=O.readdirSync(e);for(let o of n){if(r.exclude?.includes(o))continue;let s=B.join(e,o),a=B.join(t,o);O.statSync(s).isDirectory()?r.recursive!==!1&&i.copyDirectory(s,a,r):i.copyFile(s,a,{overwrite:r.overwrite})}}catch(n){throw n instanceof C?n:new C("\u65E0\u6CD5\u590D\u5236\u76EE\u5F55",e)}}static deleteDirectory(e,t={}){try{i.exists(e)&&O.rmSync(e,{recursive:t.recursive??!0,force:!0})}catch{throw new C("\u65E0\u6CD5\u5220\u9664\u76EE\u5F55",e)}}static getFileInfo(e){try{if(!i.exists(e))throw C.notFound(e);let t=O.statSync(e);return{size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory(),mtime:t.mtime,ctime:t.ctime}}catch(t){throw t instanceof C?t:new C("\u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F",e)}}static listDirectory(e,t={}){try{if(!i.exists(e))throw C.notFound(e);let r=O.readdirSync(e),n=[];for(let o of r){if(!t.includeHidden&&o.startsWith("."))continue;let s=B.join(e,o);if(n.push(s),t.recursive&&O.statSync(s).isDirectory()){let a=i.listDirectory(s,t);n=n.concat(a)}}return n}catch(r){throw r instanceof C?r:new C("\u65E0\u6CD5\u5217\u51FA\u76EE\u5F55\u5185\u5BB9",e)}}static createTempFile(e="xiaozhi-",t=".tmp"){let r=process.env.TMPDIR||process.env.TEMP||"/tmp",n=Date.now(),o=Math.random().toString(36).substring(2),s=`${e}${n}-${o}${t}`;return B.join(r,s)}static checkPermissions(e,t=O.constants.R_OK|O.constants.W_OK){try{return O.accessSync(e,t),!0}catch{return!1}}static getExtension(e){return B.extname(e).toLowerCase()}static getBaseName(e){return B.basename(e,B.extname(e))}static normalizePath(e){return B.normalize(e)}static resolvePath(e,t){return t?B.resolve(t,e):B.resolve(e)}}});var Ee,Ht=d(()=>{"use strict";Ee=class{static{c(this,"FormatUtils")}static formatUptime(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),n=Math.floor(r/60),o=Math.floor(n/24);return o>0?`${o}\u5929 ${n%24}\u5C0F\u65F6 ${r%60}\u5206\u949F`:n>0?`${n}\u5C0F\u65F6 ${r%60}\u5206\u949F`:r>0?`${r}\u5206\u949F ${t%60}\u79D2`:`${t}\u79D2`}static formatFileSize(e){let t=["B","KB","MB","GB","TB"],r=e,n=0;for(;r>=1024&&n<t.length-1;)r/=1024,n++;return`${r.toFixed(n===0?0:1)} ${t[n]}`}static formatTimestamp(e,t="full"){let r=new Date(e);switch(t){case"date":return r.toLocaleDateString("zh-CN");case"time":return r.toLocaleTimeString("zh-CN");default:return r.toLocaleString("zh-CN")}}static formatPid(e){return`PID: ${e}`}static formatPort(e){return`\u7AEF\u53E3: ${e}`}static formatUrl(e,t,r,n){let o=`${e}://${t}:${r}`;return n?`${o}${n}`:o}static formatConfigPair(e,t){return typeof t=="object"?`${e}: ${JSON.stringify(t,null,2)}`:`${e}: ${t}`}static formatError(e,t=!1){let r=`\u9519\u8BEF: ${e.message}`;return t&&e.stack&&(r+=`
|
|
2
|
+
var ot=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var an=Object.getOwnPropertyNames;var cn=Object.prototype.hasOwnProperty;var c=(i,e)=>ot(i,"name",{value:e,configurable:!0});var m=(i,e)=>()=>(i&&(e=i(i=0)),e);var F=(i,e)=>{for(var t in e)ot(i,t,{get:e[t],enumerable:!0})},ln=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of an(e))!cn.call(i,o)&&o!==t&&ot(i,o,{get:()=>e[o],enumerable:!(r=sn(e,o))||r.enumerable});return i};var ee=i=>ln(ot({},"__esModule",{value:!0}),i);import*as N from"fs";import*as q from"path";import Ue from"chalk";import Re from"pino";import{z as gn}from"zod";function un(i){let e=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),r=String(i.getDate()).padStart(2,"0"),o=String(i.getHours()).padStart(2,"0"),n=String(i.getMinutes()).padStart(2,"0"),s=String(i.getSeconds()).padStart(2,"0");return`${e}-${t}-${r} ${o}:${n}:${s}`}function Dr(i="info"){return new Ie(i)}function pn(){return nt||(nt=new Ie("info")),nt}function Nr(i){nt=i}var hn,Ie,nt,g,S=m(()=>{"use strict";hn=gn.enum(["fatal","error","warn","info","debug","trace"]);c(un,"formatDateTime");Ie=class{static{c(this,"Logger")}logFilePath=null;pinoInstance;isDaemonMode;logLevel;maxLogFileSize=10*1024*1024;maxLogFiles=5;constructor(e="info"){this.isDaemonMode=process.env.XIAOZHI_DAEMON==="true",this.logLevel=this.validateLogLevel(e),this.pinoInstance=this.createPinoInstance()}validateLogLevel(e){let t=e.toLowerCase(),r=hn.safeParse(t);return r.success?r.data:"info"}createPinoInstance(){let e=[];if(!this.isDaemonMode){let t=this.createOptimizedConsoleStream();e.push({level:this.logLevel,stream:t})}return this.logFilePath&&e.push({level:this.logLevel,stream:Re.destination({dest:this.logFilePath,sync:!1,append:!0,mkdir:!0})}),e.length===0&&e.push({level:this.logLevel,stream:Re.destination({dest:"/dev/null"})}),Re({level:this.logLevel,timestamp:Re.stdTimeFunctions?.isoTime||(()=>`,"time":${Date.now()}`),formatters:{level:c((t,r)=>({level:r}),"level")},base:null,serializers:{err:Re.stdSerializers?.err||(t=>t)}},Re.multistream(e,{dedupe:!0}))}createOptimizedConsoleStream(){let e=new Map([[20,{name:"DEBUG",color:Ue.gray}],[30,{name:"INFO",color:Ue.blue}],[40,{name:"WARN",color:Ue.yellow}],[50,{name:"ERROR",color:Ue.red}],[60,{name:"FATAL",color:Ue.red}]]);return{write:c(t=>{try{let r=JSON.parse(t),o=this.formatConsoleMessageOptimized(r,e);this.safeWrite(`${o}
|
|
3
|
+
`)}catch{this.safeWrite(t)}},"write")}}safeWrite(e){try{process.stderr&&typeof process.stderr.write=="function"?process.stderr.write(e):console&&typeof console.error=="function"&&console.error(e.trim())}catch{}}formatConsoleMessageOptimized(e,t){let r=un(new Date),o=t.get(e.level)||{name:"UNKNOWN",color:c(a=>a,"color")},n=o.color(`[${o.name}]`),s=e.msg;if(e.args&&Array.isArray(e.args)){let a=e.args.map(l=>typeof l=="object"?JSON.stringify(l):String(l)).join(" ");s=`${s} ${a}`}return`[${r}] ${n} ${s}`}initLogFile(e){this.logFilePath=q.join(e,"xiaozhi.log"),this.rotateLogFileIfNeeded(),N.existsSync(this.logFilePath)||N.writeFileSync(this.logFilePath,""),this.pinoInstance=this.createPinoInstance()}enableFileLogging(e){e&&this.logFilePath&&(this.pinoInstance=this.createPinoInstance())}info(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}success(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}warn(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.warn(e):this.pinoInstance.warn({args:t},e):this.pinoInstance.warn(e,t[0]||"")}error(e,...t){if(typeof e=="string")if(t.length===0)this.pinoInstance.error(e);else{let r=t.map(o=>o instanceof Error?{message:o.message,stack:o.stack,name:o.name,cause:o.cause}:o);this.pinoInstance.error({args:r},e)}else{let r=this.enhanceErrorObject(e);this.pinoInstance.error(r,t[0]||"")}}debug(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.debug(e):this.pinoInstance.debug({args:t},e):this.pinoInstance.debug(e,t[0]||"")}log(e,...t){typeof e=="string"?t.length===0?this.pinoInstance.info(e):this.pinoInstance.info({args:t},e):this.pinoInstance.info(e,t[0]||"")}enhanceErrorObject(e){let t={...e};for(let[r,o]of Object.entries(t))o instanceof Error&&(t[r]={message:o.message,stack:o.stack,name:o.name,cause:o.cause});return t}rotateLogFileIfNeeded(){if(!(!this.logFilePath||!N.existsSync(this.logFilePath)))try{N.statSync(this.logFilePath).size>this.maxLogFileSize&&this.rotateLogFile()}catch{}}rotateLogFile(){if(this.logFilePath)try{let e=q.dirname(this.logFilePath),t=q.basename(this.logFilePath,".log");for(let o=this.maxLogFiles-1;o>=1;o--){let n=q.join(e,`${t}.${o}.log`),s=q.join(e,`${t}.${o+1}.log`);N.existsSync(n)&&(o===this.maxLogFiles-1?N.unlinkSync(n):N.renameSync(n,s))}let r=q.join(e,`${t}.1.log`);N.renameSync(this.logFilePath,r)}catch{}}cleanupOldLogs(){if(this.logFilePath)try{let e=q.dirname(this.logFilePath),t=q.basename(this.logFilePath,".log");for(let r=this.maxLogFiles+1;r<=this.maxLogFiles+10;r++){let o=q.join(e,`${t}.${r}.log`);N.existsSync(o)&&N.unlinkSync(o)}}catch{}}setLogFileOptions(e,t){this.maxLogFileSize=e,this.maxLogFiles=t}withTag(e){return this}close(){}},nt=null;c(Dr,"createLogger");c(pn,"getLogger");c(Nr,"setGlobalLogger");g=pn()});function dn(i){if(!i||typeof i!="object")throw new Error("\u670D\u52A1\u914D\u7F6E\u5FC5\u987B\u662F\u4E00\u4E2A\u6709\u6548\u7684\u5BF9\u8C61");if("command"in i&&typeof i.command=="string")return"stdio";if("type"in i&&i.type==="sse")return"sse";if("type"in i&&i.type==="streamable-http"||"url"in i&&typeof i.url=="string")return"streamable-http";throw new Error("\u65E0\u6CD5\u8BC6\u522B\u7684 MCP \u670D\u52A1\u914D\u7F6E\u7C7B\u578B\u3002\u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5\uFF08stdio\uFF09\u3001type: 'sse' \u5B57\u6BB5\uFF08sse\uFF09\u6216 url \u5B57\u6BB5\uFF08streamable-http\uFF09")}function Kt(i,e){if(!e||typeof e!="object")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u5FC5\u987B\u662F\u4E00\u4E2A\u5BF9\u8C61`};try{switch(dn(e)){case"stdio":if(!e.command||typeof e.command!="string")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7F3A\u5C11\u5FC5\u9700\u7684 command \u5B57\u6BB5\u6216\u5B57\u6BB5\u7C7B\u578B\u4E0D\u6B63\u786E`};if(!Array.isArray(e.args))return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4`};if(e.env&&typeof e.env!="object")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61`};break;case"sse":if(e.type!=="sse")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 type \u5B57\u6BB5\u5FC5\u987B\u662F "sse"`};if(!e.url||typeof e.url!="string")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7F3A\u5C11\u5FC5\u9700\u7684 url \u5B57\u6BB5\u6216\u5B57\u6BB5\u7C7B\u578B\u4E0D\u6B63\u786E`};break;case"streamable-http":if(!e.url||typeof e.url!="string")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7F3A\u5C11\u5FC5\u9700\u7684 url \u5B57\u6BB5\u6216\u5B57\u6BB5\u7C7B\u578B\u4E0D\u6B63\u786E`};if(e.type&&e.type!=="streamable-http")return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684 type \u5B57\u6BB5\u5982\u679C\u5B58\u5728\uFF0C\u5FC5\u987B\u662F "streamable-http"`};break;default:return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u7C7B\u578B\u65E0\u6CD5\u8BC6\u522B`}}return{valid:!0}}catch(t){return{valid:!1,error:`\u670D\u52A1 "${i}" \u7684\u914D\u7F6E\u65E0\u6548: ${t instanceof Error?t.message:"\u672A\u77E5\u9519\u8BEF"}`}}}var _r=m(()=>{"use strict";c(dn,"getMcpServerCommunicationType");c(Kt,"validateMcpServerConfig")});import{copyFileSync as mn,existsSync as st,readFileSync as fn,writeFileSync as Cn}from"fs";import{dirname as vn,resolve as Ce}from"path";import{fileURLToPath as Sn}from"url";import*as it from"comment-json";import Lr from"dayjs";import Zt from"json5";import*as zr from"json5-writer";var Hr,Yt,Qt,d,Y=m(()=>{"use strict";S();_r();Hr=vn(Sn(import.meta.url)),Yt={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},Qt=class i{static{c(this,"ConfigManager")}static instance;defaultConfigPath;config=null;currentConfigPath=null;json5Writer=null;statsUpdateLocks=new Map;statsUpdateLockTimeouts=new Map;STATS_UPDATE_TIMEOUT=5e3;constructor(){let e=[Ce(Hr,"templates","default","xiaozhi.config.json"),Ce(Hr,"..","templates","default","xiaozhi.config.json"),Ce(process.cwd(),"templates","default","xiaozhi.config.json")];this.defaultConfigPath=e.find(t=>st(t))||e[0]}getConfigFilePath(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),t=["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"];for(let r of t){let o=Ce(e,r);if(st(o))return o}return Ce(e,"xiaozhi.config.json")}getConfigFileFormat(e){return e.endsWith(".json5")?"json5":e.endsWith(".jsonc")?"jsonc":"json"}static getInstance(){return i.instance||(i.instance=new i),i.instance}configExists(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),t=["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"];for(let r of t){let o=Ce(e,r);if(st(o))return!0}return!1}initConfig(e="json"){if(!st(this.defaultConfigPath))throw new Error(`\u9ED8\u8BA4\u914D\u7F6E\u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${this.defaultConfigPath}`);if(this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u521D\u59CB\u5316");let t=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),r=`xiaozhi.config.${e}`,o=Ce(t,r);mn(this.defaultConfigPath,o),this.config=null,this.json5Writer=null}loadConfig(){if(!this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C xiaozhi init \u521D\u59CB\u5316\u914D\u7F6E");try{let e=this.getConfigFilePath();this.currentConfigPath=e;let t=this.getConfigFileFormat(e),o=fn(e,"utf8").replace(/^\uFEFF/,""),n;switch(t){case"json5":n=Zt.parse(o),this.json5Writer=zr.load(o);break;case"jsonc":n=it.parse(o);break;default:n=JSON.parse(o);break}return this.validateConfig(n),n}catch(e){throw e instanceof SyntaxError?new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF: ${e.message}`):e}}validateConfig(e){if(!e||typeof e!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A\u6839\u5BF9\u8C61\u65E0\u6548");let t=e;if(t.mcpEndpoint===void 0||t.mcpEndpoint===null)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5B57\u6BB5\u65E0\u6548");if(typeof t.mcpEndpoint!="string")if(Array.isArray(t.mcpEndpoint)){if(t.mcpEndpoint.length===0)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let r of t.mcpEndpoint)if(typeof r!="string"||r.trim()==="")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u5B57\u7B26\u4E32\u6570\u7EC4");if(!t.mcpServers||typeof t.mcpServers!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers \u5B57\u6BB5\u65E0\u6548");for(let[r,o]of Object.entries(t.mcpServers)){if(!o||typeof o!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${r} \u65E0\u6548`);let n=Kt(r,o);if(!n.valid)throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A${n.error}`)}}getConfig(){return this.config=this.loadConfig(),JSON.parse(JSON.stringify(this.config))}getMutableConfig(){return this.config||(this.config=this.loadConfig()),this.config}getMcpEndpoint(){let e=this.getConfig();return Array.isArray(e.mcpEndpoint)?e.mcpEndpoint[0]||"":e.mcpEndpoint}getMcpEndpoints(){let e=this.getConfig();return Array.isArray(e.mcpEndpoint)?[...e.mcpEndpoint]:e.mcpEndpoint?[e.mcpEndpoint]:[]}getMcpServers(){return this.getConfig().mcpServers}getMcpServerConfig(){return this.getConfig().mcpServerConfig||{}}getServerToolsConfig(e){return this.getMcpServerConfig()[e]?.tools||{}}isToolEnabled(e,t){return this.getServerToolsConfig(e)[t]?.enable!==!1}updateMcpEndpoint(e){if(Array.isArray(e)){if(e.length===0)throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let r of e)if(!r||typeof r!="string")throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E2D\u7684\u6BCF\u4E2A\u5143\u7D20\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getMutableConfig();t.mcpEndpoint=e,this.saveConfig(t)}addMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getMutableConfig(),r=this.getMcpEndpoints();if(r.includes(e))throw new Error(`MCP \u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728`);let o=[...r,e];t.mcpEndpoint=o,this.saveConfig(t)}removeMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getMutableConfig(),r=this.getMcpEndpoints();if(r.indexOf(e)===-1)throw new Error(`MCP \u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(r.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");let n=r.filter(s=>s!==e);t.mcpEndpoint=n,this.saveConfig(t)}updateMcpServer(e,t){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let r=Kt(e,t);if(!r.valid)throw new Error(r.error||"\u670D\u52A1\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");let o=this.getMutableConfig();o.mcpServers[e]=t,this.saveConfig(o)}removeMcpServer(e){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getConfig();if(!t.mcpServers[e])throw new Error(`\u670D\u52A1 ${e} \u4E0D\u5B58\u5728`);let r={...t.mcpServers};delete r[e];let o={...t,mcpServers:r};this.saveConfig(o)}updateServerToolsConfig(e,t){let r=this.getMutableConfig();r.mcpServerConfig||(r.mcpServerConfig={}),Object.keys(t).length===0?delete r.mcpServerConfig[e]:r.mcpServerConfig[e]={tools:t},this.saveConfig(r)}removeServerToolsConfig(e){let r={...this.getConfig()};r.mcpServerConfig&&(delete r.mcpServerConfig[e],this.saveConfig(r))}cleanupInvalidServerToolsConfig(){let e=this.getMutableConfig();if(!e.mcpServerConfig)return;let t=Object.keys(e.mcpServers),o=Object.keys(e.mcpServerConfig).filter(n=>!t.includes(n));if(o.length>0){for(let n of o)delete e.mcpServerConfig[n];this.saveConfig(e),g.info(`\u5DF2\u6E05\u7406 ${o.length} \u4E2A\u65E0\u6548\u7684\u670D\u52A1\u5DE5\u5177\u914D\u7F6E: ${o.join(", ")}`)}}setToolEnabled(e,t,r,o){let n=this.getMutableConfig();n.mcpServerConfig||(n.mcpServerConfig={}),n.mcpServerConfig[e]||(n.mcpServerConfig[e]={tools:{}}),n.mcpServerConfig[e].tools[t]={...n.mcpServerConfig[e].tools[t],enable:r,...o&&{description:o}},this.saveConfig(n)}saveConfig(e){try{this.validateConfig(e);let t;this.currentConfigPath?t=this.currentConfigPath:(t=this.getConfigFilePath(),this.currentConfigPath=t);let r=this.getConfigFileFormat(t),o;switch(r){case"json5":try{this.json5Writer?(this.json5Writer.write(e),o=this.json5Writer.toSource()):(console.warn("\u6CA1\u6709 json5Writer \u5B9E\u4F8B\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F"),o=Zt.stringify(e,null,2))}catch(n){console.warn("\u4F7F\u7528 json5-writer \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON5 \u683C\u5F0F:",n),o=Zt.stringify(e,null,2)}break;case"jsonc":try{o=it.stringify(e,null,2)}catch(n){console.warn("\u4F7F\u7528 comment-json \u4FDD\u5B58\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u6807\u51C6 JSON \u683C\u5F0F:",n),o=JSON.stringify(e,null,2)}break;default:o=JSON.stringify(e,null,2);break}Cn(t,o,"utf8"),this.config=e,this.notifyConfigUpdate(e)}catch(t){throw new Error(`\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}reloadConfig(){this.config=null,this.currentConfigPath=null,this.json5Writer=null}getConfigPath(){return this.getConfigFilePath()}getDefaultConfigPath(){return this.defaultConfigPath}getConnectionConfig(){let t=this.getConfig().connection||{};return{heartbeatInterval:t.heartbeatInterval??Yt.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??Yt.heartbeatTimeout,reconnectInterval:t.reconnectInterval??Yt.reconnectInterval}}getHeartbeatInterval(){return this.getConnectionConfig().heartbeatInterval}getHeartbeatTimeout(){return this.getConnectionConfig().heartbeatTimeout}getReconnectInterval(){return this.getConnectionConfig().reconnectInterval}updateConnectionConfig(e){let t=this.getMutableConfig();t.connection||(t.connection={}),Object.assign(t.connection,e),this.saveConfig(t)}async updateToolUsageStats(e,t,r){try{if(typeof t=="string"&&r){let o=e,n=t,s=r;await Promise.all([this._updateMCPServerToolStats(o,n,s),this.updateCustomMCPToolStats(o,n,s)]),g.debug(`\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${o}/${n}`)}else{let o=e,n=t,s=new Date().toISOString();await this.updateCustomMCPToolStats(o,s,n),g.debug(`CustomMCP \u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5DF2\u66F4\u65B0: ${o}`)}}catch(o){if(typeof t=="string"&&r){let n=e,s=t;g.error(`\u66F4\u65B0\u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${n}/${s}): ${o instanceof Error?o.message:String(o)}`)}else{let n=e;g.error(`\u66F4\u65B0 CustomMCP \u5DE5\u5177\u4F7F\u7528\u7EDF\u8BA1\u5931\u8D25 (${n}): ${o instanceof Error?o.message:String(o)}`)}}}async updateMCPServerToolStats(e,t,r,o=!0){await this._updateMCPServerToolStats(e,t,r,o)}setHeartbeatInterval(e){if(e<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatInterval:e})}setHeartbeatTimeout(e){if(e<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatTimeout:e})}setReconnectInterval(e){if(e<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({reconnectInterval:e})}getModelScopeConfig(){return this.getConfig().modelscope||{}}getModelScopeApiKey(){return this.getModelScopeConfig().apiKey||process.env.MODELSCOPE_API_TOKEN}updateModelScopeConfig(e){let t=this.getMutableConfig();t.modelscope||(t.modelscope={}),Object.assign(t.modelscope,e),this.saveConfig(t)}setModelScopeApiKey(e){if(!e||typeof e!="string")throw new Error("API Key \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");this.updateModelScopeConfig({apiKey:e})}getCustomMCPConfig(){return this.getConfig().customMCP||null}getCustomMCPTools(){let e=this.getCustomMCPConfig();return!e||!e.tools?[]:e.tools}validateCustomMCPTools(e){if(!Array.isArray(e))return!1;for(let t of e){if(!t.name||typeof t.name!="string")return g.warn(`CustomMCP \u5DE5\u5177\u7F3A\u5C11\u6709\u6548\u7684 name \u5B57\u6BB5: ${JSON.stringify(t)}`),!1;if(!t.description||typeof t.description!="string")return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 description \u5B57\u6BB5`),!1;if(!t.inputSchema||typeof t.inputSchema!="object")return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 inputSchema \u5B57\u6BB5`),!1;if(!t.handler||typeof t.handler!="object")return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7F3A\u5C11\u6709\u6548\u7684 handler \u5B57\u6BB5`),!1;if(!["proxy","function","http","script","chain","mcp"].includes(t.handler.type))return g.warn(`CustomMCP \u5DE5\u5177 ${t.name} \u7684 handler.type \u5FC5\u987B\u662F 'proxy', 'function', 'http', 'script', 'chain' \u6216 'mcp'`),!1;if(!this.validateHandlerConfig(t.name,t.handler))return!1;if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(t.name))return g.warn(`CustomMCP \u5DE5\u5177\u540D\u79F0 ${t.name} \u683C\u5F0F\u65E0\u6548\uFF0C\u5FC5\u987B\u4EE5\u5B57\u6BCD\u5F00\u5934\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF`),!1}return!0}validateHandlerConfig(e,t){switch(t.type){case"proxy":return this.validateProxyHandler(e,t);case"http":return this.validateHttpHandler(e,t);case"function":return this.validateFunctionHandler(e,t);case"script":return this.validateScriptHandler(e,t);case"chain":return this.validateChainHandler(e,t);case"mcp":return this.validateMCPHandler(e,t);default:return g.warn(`CustomMCP \u5DE5\u5177 ${e} \u4F7F\u7528\u4E86\u672A\u77E5\u7684\u5904\u7406\u5668\u7C7B\u578B`),!1}}validateProxyHandler(e,t){return t.platform?["coze","openai","anthropic","custom"].includes(t.platform)?!t.config||typeof t.config!="object"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u7F3A\u5C11 config \u5B57\u6BB5`),!1):t.platform==="coze"&&!t.config.workflow_id&&!t.config.bot_id?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 Coze \u5904\u7406\u5668\u5FC5\u987B\u63D0\u4F9B workflow_id \u6216 bot_id`),!1):!0:(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u5E73\u53F0: ${t.platform}`),!1):(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 proxy \u5904\u7406\u5668\u7F3A\u5C11 platform \u5B57\u6BB5`),!1)}validateHttpHandler(e,t){if(!t.url||typeof t.url!="string")return g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 http \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 url \u5B57\u6BB5`),!1;try{new URL(t.url)}catch{return g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 http \u5904\u7406\u5668 url \u683C\u5F0F\u65E0\u6548: ${t.url}`),!1}return t.method&&!["GET","POST","PUT","DELETE","PATCH"].includes(t.method)?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 http \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684 HTTP \u65B9\u6CD5: ${t.method}`),!1):!0}validateFunctionHandler(e,t){return!t.module||typeof t.module!="string"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 function \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 module \u5B57\u6BB5`),!1):!t.function||typeof t.function!="string"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 function \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 function \u5B57\u6BB5`),!1):!0}validateScriptHandler(e,t){return!t.script||typeof t.script!="string"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 script \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 script \u5B57\u6BB5`),!1):t.interpreter&&!["node","python","bash"].includes(t.interpreter)?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 script \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u89E3\u91CA\u5668: ${t.interpreter}`),!1):!0}validateChainHandler(e,t){return!t.tools||!Array.isArray(t.tools)||t.tools.length===0?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 chain \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 tools \u6570\u7EC4`),!1):["sequential","parallel"].includes(t.mode)?["stop","continue","retry"].includes(t.error_handling)?!0:(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 chain \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u9519\u8BEF\u5904\u7406\u7B56\u7565: ${t.error_handling}`),!1):(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 chain \u5904\u7406\u5668\u4F7F\u7528\u4E86\u4E0D\u652F\u6301\u7684\u6267\u884C\u6A21\u5F0F: ${t.mode}`),!1)}validateMCPHandler(e,t){return!t.config||typeof t.config!="object"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11 config \u5B57\u6BB5`),!1):!t.config.serviceName||typeof t.config.serviceName!="string"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 serviceName`),!1):!t.config.toolName||typeof t.config.toolName!="string"?(g.warn(`CustomMCP \u5DE5\u5177 ${e} \u7684 mcp \u5904\u7406\u5668\u7F3A\u5C11\u6709\u6548\u7684 toolName`),!1):!0}hasValidCustomMCPTools(){try{let e=this.getCustomMCPTools();return e.length===0?!1:this.validateCustomMCPTools(e)}catch(e){return g.error("\u68C0\u67E5 customMCP \u5DE5\u5177\u914D\u7F6E\u65F6\u51FA\u9519:",e),!1}}addCustomMCPTool(e){if(!e||typeof e!="object")throw new Error("\u5DE5\u5177\u914D\u7F6E\u4E0D\u80FD\u4E3A\u7A7A");let t=this.getMutableConfig();if(t.customMCP||(t.customMCP={tools:[]}),t.customMCP.tools.find(o=>o.name===e.name))throw new Error(`\u5DE5\u5177 "${e.name}" \u5DF2\u5B58\u5728`);if(!this.validateCustomMCPTools([e]))throw new Error("\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");t.customMCP.tools.unshift(e),this.saveConfig(t),g.info(`\u6210\u529F\u6DFB\u52A0\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${e.name}`)}async addCustomMCPTools(e){if(!Array.isArray(e))throw new Error("\u5DE5\u5177\u914D\u7F6E\u5FC5\u987B\u662F\u6570\u7EC4");if(e.length===0)return;let t=this.getMutableConfig();t.customMCP||(t.customMCP={tools:[]});let r=new Set(t.customMCP.tools.map(n=>n.name)),o=e.filter(n=>!r.has(n.name));if(o.length>0){if(!this.validateCustomMCPTools(o))throw new Error("\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");t.customMCP.tools.push(...o),this.saveConfig(t),g.info(`\u6210\u529F\u6279\u91CF\u6DFB\u52A0 ${o.length} \u4E2A\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${o.map(n=>n.name).join(", ")}`)}}removeCustomMCPTool(e){if(!e||typeof e!="string")throw new Error("\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");let t=this.getMutableConfig();if(!t.customMCP||!t.customMCP.tools)throw new Error("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177");let r=t.customMCP.tools.findIndex(o=>o.name===e);if(r===-1)throw new Error(`\u5DE5\u5177 "${e}" \u4E0D\u5B58\u5728`);t.customMCP.tools.splice(r,1),this.saveConfig(t),g.info(`\u6210\u529F\u5220\u9664\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${e}`)}updateCustomMCPTool(e,t){if(!e||typeof e!="string")throw new Error("\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");if(!t||typeof t!="object")throw new Error("\u66F4\u65B0\u540E\u7684\u5DE5\u5177\u914D\u7F6E\u4E0D\u80FD\u4E3A\u7A7A");let r=this.getMutableConfig();if(!r.customMCP||!r.customMCP.tools)throw new Error("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177");let o=r.customMCP.tools.findIndex(n=>n.name===e);if(o===-1)throw new Error(`\u5DE5\u5177 "${e}" \u4E0D\u5B58\u5728`);if(!this.validateCustomMCPTools([t]))throw new Error("\u66F4\u65B0\u540E\u7684\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");r.customMCP.tools[o]=t,this.saveConfig(r),g.info(`\u6210\u529F\u66F4\u65B0\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177: ${e}`)}updateCustomMCPTools(e){if(!Array.isArray(e))throw new Error("\u5DE5\u5177\u914D\u7F6E\u5FC5\u987B\u662F\u6570\u7EC4");if(!this.validateCustomMCPTools(e))throw new Error("\u5DE5\u5177\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25");let t=this.getMutableConfig();t.customMCP||(t.customMCP={tools:[]}),t.customMCP.tools=e,this.saveConfig(t),g.info(`\u6210\u529F\u66F4\u65B0\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177\u914D\u7F6E\uFF0C\u5171 ${e.length} \u4E2A\u5DE5\u5177`)}getWebUIConfig(){return this.getConfig().webUI||{}}getWebUIPort(){return this.getWebUIConfig().port??9999}notifyConfigUpdate(e){try{let t=global.__webServer;t&&typeof t.broadcastConfigUpdate=="function"&&(t.broadcastConfigUpdate(e),console.log("\u5DF2\u901A\u8FC7 WebSocket \u5E7F\u64AD\u914D\u7F6E\u66F4\u65B0"))}catch(t){console.warn("\u901A\u77E5 Web \u754C\u9762\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",t instanceof Error?t.message:String(t))}}updateWebUIConfig(e){let t=this.getMutableConfig();t.webUI||(t.webUI={}),Object.assign(t.webUI,e),this.saveConfig(t)}setWebUIPort(e){if(!Number.isInteger(e)||e<=0||e>65535)throw new Error("\u7AEF\u53E3\u53F7\u5FC5\u987B\u662F 1-65535 \u4E4B\u95F4\u7684\u6574\u6570");this.updateWebUIConfig({port:e})}updatePlatformConfig(e,t){let r=this.getMutableConfig();r.platforms||(r.platforms={}),r.platforms[e]=t,this.saveConfig(r)}getCozePlatformConfig(){let t=this.getConfig().platforms?.coze;return!t||!t.token?null:{token:t.token}}getCozeToken(){return this.getCozePlatformConfig()?.token||null}setCozePlatformConfig(e){if(!e.token||typeof e.token!="string"||e.token.trim()==="")throw new Error("\u6263\u5B50 API Token \u4E0D\u80FD\u4E3A\u7A7A");this.updatePlatformConfig("coze",{token:e.token.trim()})}isCozeConfigValid(){let e=this.getCozePlatformConfig();return e!==null&&typeof e.token=="string"&&e.token.trim()!==""}async _updateMCPServerToolStats(e,t,r,o=!0){let n=this.getMutableConfig();n.mcpServerConfig||(n.mcpServerConfig={}),n.mcpServerConfig[e]||(n.mcpServerConfig[e]={tools:{}}),n.mcpServerConfig[e].tools[t]||(n.mcpServerConfig[e].tools[t]={enable:!0});let s=n.mcpServerConfig[e].tools[t],a=s.usageCount||0,l=s.lastUsedTime;o&&(s.usageCount=a+1),(!l||new Date(r)>new Date(l))&&(s.lastUsedTime=Lr(r).format("YYYY-MM-DD HH:mm:ss")),this.saveConfig(n)}async updateCustomMCPToolStats(e,t,r){try{let o,n,s=!0,a;if(typeof r=="string"){let b=e;o=`${b}__${t}`,n=r,a=`${b}/${t}`}else o=e,n=t,s=r||!0,a=o;let l=this.getCustomMCPTools(),h=l.findIndex(b=>b.name===o);if(h===-1)return;let u=[...l],p=u[h];p.stats||(p.stats={});let C=p.stats.usageCount||0,T=p.stats.lastUsedTime;s&&(p.stats.usageCount=C+1),(!T||new Date(n)>new Date(T))&&(p.stats.lastUsedTime=Lr(n).format("YYYY-MM-DD HH:mm:ss")),await this.updateCustomMCPTools(u)}catch(o){if(typeof r=="string"){let n=e,s=t;g.error(`\u66F4\u65B0 customMCP \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25 (${n}/${s}): ${o instanceof Error?o.message:String(o)}`)}else{let n=e;g.error(`\u66F4\u65B0 customMCP \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25 (${n}): ${o instanceof Error?o.message:String(o)}`)}}}async acquireStatsUpdateLock(e){if(this.statsUpdateLocks.has(e))return g.debug(`\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u66F4\u65B0\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8DF3\u8FC7\u672C\u6B21\u66F4\u65B0`),!1;let t=new Promise(o=>{});this.statsUpdateLocks.set(e,t);let r=setTimeout(()=>{this.releaseStatsUpdateLock(e)},this.STATS_UPDATE_TIMEOUT);return this.statsUpdateLockTimeouts.set(e,r),!0}releaseStatsUpdateLock(e){this.statsUpdateLocks.delete(e);let t=this.statsUpdateLockTimeouts.get(e);t&&(clearTimeout(t),this.statsUpdateLockTimeouts.delete(e)),g.debug(`\u5DF2\u91CA\u653E\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u66F4\u65B0\u9501`)}async updateToolUsageStatsWithLock(e,t=!0){let r=`custommcp_${e}`;if(await this.acquireStatsUpdateLock(r))try{await this.updateToolUsageStats(e,t),g.debug(`\u5DE5\u5177 ${e} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(o){throw g.error(`\u5DE5\u5177 ${e} \u7EDF\u8BA1\u66F4\u65B0\u5931\u8D25:`,o),o}finally{this.releaseStatsUpdateLock(r)}}async updateMCPServerToolStatsWithLock(e,t,r,o=!0){let n=`mcpserver_${e}_${t}`;if(await this.acquireStatsUpdateLock(n))try{await this.updateMCPServerToolStats(e,t,r,o),g.debug(`MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u66F4\u65B0\u5B8C\u6210`)}catch(s){throw g.error(`MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u66F4\u65B0\u5931\u8D25:`,s),s}finally{this.releaseStatsUpdateLock(n)}}clearAllStatsUpdateLocks(){let e=this.statsUpdateLocks.size;this.statsUpdateLocks.clear();for(let t of this.statsUpdateLockTimeouts.values())clearTimeout(t);this.statsUpdateLockTimeouts.clear(),e>0&&g.info(`\u5DF2\u6E05\u7406 ${e} \u4E2A\u7EDF\u8BA1\u66F4\u65B0\u9501`)}getStatsUpdateLocks(){return Array.from(this.statsUpdateLocks.keys())}},d=Qt.getInstance()});var er,$e,Fe,y,tr,We=m(()=>{"use strict";er={NAME:"xiaozhi-mcp-service",DEFAULT_PORT:3e3,DEFAULT_WEB_UI_PORT:9999,PID_FILE:"xiaozhi.pid",LOG_FILE:"xiaozhi.log"},$e={FILE_NAMES:["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"],DEFAULT_FILE:"xiaozhi.config.default.json",DIR_ENV_VAR:"XIAOZHI_CONFIG_DIR"},Fe={WORK_DIR:".xiaozhi",TEMPLATES_DIR:"templates",LOGS_DIR:"logs"},y={GENERAL_ERROR:"GENERAL_ERROR",CONFIG_ERROR:"CONFIG_ERROR",SERVICE_ERROR:"SERVICE_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",FILE_ERROR:"FILE_ERROR",PROCESS_ERROR:"PROCESS_ERROR",NETWORK_ERROR:"NETWORK_ERROR",PERMISSION_ERROR:"PERMISSION_ERROR"},tr={PROCESS_STOP:3e3,SERVICE_START:1e4,NETWORK_REQUEST:5e3,FILE_OPERATION:2e3}});var yn,Tn,at,jr=m(()=>{"use strict";We();yn={[y.CONFIG_ERROR]:'\u8FD0\u884C "xiaozhi --help" \u67E5\u770B\u914D\u7F6E\u76F8\u5173\u547D\u4EE4',[y.SERVICE_ERROR]:'\u8FD0\u884C "xiaozhi status" \u68C0\u67E5\u670D\u52A1\u72B6\u6001',[y.VALIDATION_ERROR]:"\u68C0\u67E5\u8F93\u5165\u53C2\u6570\u662F\u5426\u6B63\u786E",[y.FILE_ERROR]:"\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u548C\u6743\u9650",[y.PROCESS_ERROR]:"\u68C0\u67E5\u8FDB\u7A0B\u72B6\u6001\u548C\u6743\u9650",[y.NETWORK_ERROR]:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C\u9632\u706B\u5899\u8BBE\u7F6E",[y.PERMISSION_ERROR]:"\u5C1D\u8BD5\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"},Tn={config_not_found:['\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6',"\u68C0\u67E5\u5F53\u524D\u76EE\u5F55\u662F\u5426\u4E3A\u9879\u76EE\u6839\u76EE\u5F55","\u8BBE\u7F6E XIAOZHI_CONFIG_DIR \u73AF\u5883\u53D8\u91CF\u6307\u5B9A\u914D\u7F6E\u76EE\u5F55"],service_port_occupied:["\u68C0\u67E5\u7AEF\u53E3\u662F\u5426\u88AB\u5176\u4ED6\u7A0B\u5E8F\u5360\u7528",'\u4F7F\u7528 "lsof -i :\u7AEF\u53E3\u53F7" \u67E5\u770B\u7AEF\u53E3\u4F7F\u7528\u60C5\u51B5',"\u66F4\u6539\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u7AEF\u53E3\u8BBE\u7F6E"],permission_denied:["\u68C0\u67E5\u6587\u4EF6\u548C\u76EE\u5F55\u6743\u9650","\u4F7F\u7528 sudo \u6216\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C","\u786E\u4FDD\u5F53\u524D\u7528\u6237\u6709\u8DB3\u591F\u7684\u6743\u9650"],service_start_failed:["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u662F\u5426\u6B63\u786E","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F","\u786E\u4FDD\u6240\u6709\u4F9D\u8D56\u670D\u52A1\u6B63\u5E38\u8FD0\u884C"]},at=class{static{c(this,"ERROR_MESSAGES")}static getHelpMessage(e){return yn[e]}static getSolutions(e){return Tn[e]||[]}static formatError(e,t){return`${t?`[${t}] `:""}${e.message}`}static getFriendlyMessage(e){return{[y.CONFIG_ERROR]:"\u914D\u7F6E\u6587\u4EF6\u76F8\u5173\u9519\u8BEF",[y.SERVICE_ERROR]:"\u670D\u52A1\u8FD0\u884C\u76F8\u5173\u9519\u8BEF",[y.VALIDATION_ERROR]:"\u8F93\u5165\u9A8C\u8BC1\u9519\u8BEF",[y.FILE_ERROR]:"\u6587\u4EF6\u64CD\u4F5C\u9519\u8BEF",[y.PROCESS_ERROR]:"\u8FDB\u7A0B\u7BA1\u7406\u9519\u8BEF",[y.NETWORK_ERROR]:"\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF",[y.PERMISSION_ERROR]:"\u6743\u9650\u4E0D\u8DB3\u9519\u8BEF"}[e]||"\u672A\u77E5\u9519\u8BEF"}static isRecoverable(e){return[y.NETWORK_ERROR,y.FILE_ERROR,y.SERVICE_ERROR].includes(e)}static getSeverity(e){return{[y.VALIDATION_ERROR]:"low",[y.FILE_ERROR]:"medium",[y.CONFIG_ERROR]:"medium",[y.NETWORK_ERROR]:"medium",[y.SERVICE_ERROR]:"high",[y.PROCESS_ERROR]:"high",[y.PERMISSION_ERROR]:"critical"}[e]||"medium"}}});var _,ve,I,E,v,le,te=m(()=>{"use strict";We();_=class i extends Error{constructor(t,r,o=1,n){super(t);this.code=r;this.exitCode=o;this.suggestions=n;this.name="CLIError",Error.captureStackTrace&&Error.captureStackTrace(this,i)}static{c(this,"CLIError")}static withSuggestions(t,r,o){return new i(t,r,1,o)}},ve=class i extends _{static{c(this,"ConfigError")}constructor(e,t){super(e,y.CONFIG_ERROR,1,t),this.name="ConfigError"}static configNotFound(){return new i("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728",['\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6'])}static invalidFormat(e){return new i(`\u65E0\u6548\u7684\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F: ${e}`,["\u652F\u6301\u7684\u683C\u5F0F: json, json5, jsonc"])}},I=class i extends _{static{c(this,"ServiceError")}constructor(e,t){super(e,y.SERVICE_ERROR,1,t),this.name="ServiceError"}static alreadyRunning(e){return new i(`\u670D\u52A1\u5DF2\u7ECF\u5728\u8FD0\u884C (PID: ${e})`,['\u8BF7\u5148\u8FD0\u884C "xiaozhi stop" \u505C\u6B62\u73B0\u6709\u670D\u52A1','\u6216\u8005\u4F7F\u7528 "xiaozhi restart" \u91CD\u542F\u670D\u52A1'])}static autoRestarting(e){return new i(`\u68C0\u6D4B\u5230\u670D\u52A1\u5DF2\u5728\u8FD0\u884C (PID: ${e})\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u542F...`,["\u5982\u679C\u4E0D\u5E0C\u671B\u81EA\u52A8\u91CD\u542F\uFF0C\u8BF7\u4F7F\u7528 xiaozhi stop \u624B\u52A8\u505C\u6B62\u670D\u52A1"])}static notRunning(){return new i("\u670D\u52A1\u672A\u8FD0\u884C",['\u8BF7\u8FD0\u884C "xiaozhi start" \u542F\u52A8\u670D\u52A1'])}static startFailed(e){return new i(`\u670D\u52A1\u542F\u52A8\u5931\u8D25: ${e}`,["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u662F\u5426\u6B63\u786E","\u786E\u4FDD\u7AEF\u53E3\u672A\u88AB\u5360\u7528","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u4FE1\u606F"])}},E=class i extends _{static{c(this,"ValidationError")}constructor(e,t){super(`\u9A8C\u8BC1\u5931\u8D25: ${t} - ${e}`,y.VALIDATION_ERROR,1),this.name="ValidationError"}static invalidPort(e){return new i(`\u7AEF\u53E3\u53F7\u5FC5\u987B\u5728 1-65535 \u8303\u56F4\u5185\uFF0C\u5F53\u524D\u503C: ${e}`,"port")}static requiredField(e){return new i("\u5FC5\u586B\u5B57\u6BB5\u4E0D\u80FD\u4E3A\u7A7A",e)}},v=class i extends _{static{c(this,"FileError")}constructor(e,t,r){let o=t?`${e}: ${t}`:e;super(o,y.FILE_ERROR,1,r),this.name="FileError"}static notFound(e){return new i("\u6587\u4EF6\u4E0D\u5B58\u5728",e,["\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E"])}static permissionDenied(e){return new i("\u6743\u9650\u4E0D\u8DB3",e,["\u68C0\u67E5\u6587\u4EF6\u6743\u9650\u6216\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"])}static alreadyExists(e){return new i("\u6587\u4EF6\u5DF2\u5B58\u5728",e,["\u4F7F\u7528\u4E0D\u540C\u7684\u6587\u4EF6\u540D\u6216\u5220\u9664\u73B0\u6709\u6587\u4EF6"])}},le=class i extends _{static{c(this,"ProcessError")}constructor(e,t,r){let o=t?`${e} (PID: ${t})`:e;super(o,y.PROCESS_ERROR,1,r),this.name="ProcessError"}static killFailed(e){return new i("\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B",e,["\u8FDB\u7A0B\u53EF\u80FD\u5DF2\u7ECF\u505C\u6B62\u6216\u6743\u9650\u4E0D\u8DB3"])}static notFound(e){return new i("\u8FDB\u7A0B\u4E0D\u5B58\u5728",e)}}});import H from"chalk";var re,rr=m(()=>{"use strict";jr();te();re=class i{static{c(this,"ErrorHandler")}static handle(e){e instanceof _?i.handleCLIError(e):i.handleUnknownError(e),process.exit(1)}static handleCLIError(e){if(console.error(H.red(`\u274C \u9519\u8BEF: ${e.message}`)),process.env.DEBUG&&console.error(H.gray(`\u9519\u8BEF\u7801: ${e.code}`)),e.suggestions&&e.suggestions.length>0){console.log(H.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of e.suggestions)console.log(H.gray(` ${r}`))}let t=at.getHelpMessage(e.code);t&&console.log(H.blue(`\u2139\uFE0F ${t}`))}static handleUnknownError(e){console.error(H.red(`\u274C \u672A\u77E5\u9519\u8BEF: ${e.message}`)),process.env.DEBUG||process.env.NODE_ENV==="development"?(console.error(H.gray("\u5806\u6808\u4FE1\u606F:")),console.error(H.gray(e.stack))):console.log(H.yellow("\u{1F4A1} \u63D0\u793A: \u8BBE\u7F6E DEBUG=1 \u73AF\u5883\u53D8\u91CF\u67E5\u770B\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F"))}static async handleAsync(e,t){try{return await e()}catch(r){throw r instanceof _?r:r instanceof Error?new _(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new _(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static handleSync(e,t){try{return e()}catch(r){throw r instanceof _?r:r instanceof Error?new _(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new _(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static warn(e,t){if(console.warn(H.yellow(`\u26A0\uFE0F \u8B66\u544A: ${e}`)),t&&t.length>0){console.log(H.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of t)console.log(H.gray(` ${r}`))}}static info(e){console.log(H.blue(`\u2139\uFE0F ${e}`))}static success(e){console.log(H.green(`\u2705 ${e}`))}}});import k from"fs";import G from"path";var M,Ve=m(()=>{"use strict";te();M=class i{static{c(this,"FileUtils")}static exists(e){try{return k.existsSync(e)}catch{return!1}}static ensureDir(e){try{k.existsSync(e)||k.mkdirSync(e,{recursive:!0})}catch{throw new v("\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55",e)}}static readFile(e,t="utf8"){try{if(!i.exists(e))throw v.notFound(e);return k.readFileSync(e,t)}catch(r){throw r instanceof v?r:new v("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6",e)}}static writeFile(e,t,r){try{if(!r?.overwrite&&i.exists(e))throw v.alreadyExists(e);let o=G.dirname(e);i.ensureDir(o),k.writeFileSync(e,t,"utf8")}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u5199\u5165\u6587\u4EF6",e)}}static copyFile(e,t,r){try{if(!i.exists(e))throw v.notFound(e);if(!r?.overwrite&&i.exists(t))throw v.alreadyExists(t);let o=G.dirname(t);i.ensureDir(o),k.copyFileSync(e,t)}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u590D\u5236\u6587\u4EF6",e)}}static deleteFile(e){try{i.exists(e)&&k.unlinkSync(e)}catch{throw new v("\u65E0\u6CD5\u5220\u9664\u6587\u4EF6",e)}}static copyDirectory(e,t,r={}){try{if(!i.exists(e))throw v.notFound(e);i.ensureDir(t);let o=k.readdirSync(e);for(let n of o){if(r.exclude?.includes(n))continue;let s=G.join(e,n),a=G.join(t,n);k.statSync(s).isDirectory()?r.recursive!==!1&&i.copyDirectory(s,a,r):i.copyFile(s,a,{overwrite:r.overwrite})}}catch(o){throw o instanceof v?o:new v("\u65E0\u6CD5\u590D\u5236\u76EE\u5F55",e)}}static deleteDirectory(e,t={}){try{i.exists(e)&&k.rmSync(e,{recursive:t.recursive??!0,force:!0})}catch{throw new v("\u65E0\u6CD5\u5220\u9664\u76EE\u5F55",e)}}static getFileInfo(e){try{if(!i.exists(e))throw v.notFound(e);let t=k.statSync(e);return{size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory(),mtime:t.mtime,ctime:t.ctime}}catch(t){throw t instanceof v?t:new v("\u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F",e)}}static listDirectory(e,t={}){try{if(!i.exists(e))throw v.notFound(e);let r=k.readdirSync(e),o=[];for(let n of r){if(!t.includeHidden&&n.startsWith("."))continue;let s=G.join(e,n);if(o.push(s),t.recursive&&k.statSync(s).isDirectory()){let a=i.listDirectory(s,t);o=o.concat(a)}}return o}catch(r){throw r instanceof v?r:new v("\u65E0\u6CD5\u5217\u51FA\u76EE\u5F55\u5185\u5BB9",e)}}static createTempFile(e="xiaozhi-",t=".tmp"){let r=process.env.TMPDIR||process.env.TEMP||"/tmp",o=Date.now(),n=Math.random().toString(36).substring(2),s=`${e}${o}-${n}${t}`;return G.join(r,s)}static checkPermissions(e,t=k.constants.R_OK|k.constants.W_OK){try{return k.accessSync(e,t),!0}catch{return!1}}static getExtension(e){return G.extname(e).toLowerCase()}static getBaseName(e){return G.basename(e,G.extname(e))}static normalizePath(e){return G.normalize(e)}static resolvePath(e,t){return t?G.resolve(t,e):G.resolve(e)}}});var xe,or=m(()=>{"use strict";xe=class{static{c(this,"FormatUtils")}static formatUptime(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),o=Math.floor(r/60),n=Math.floor(o/24);return n>0?`${n}\u5929 ${o%24}\u5C0F\u65F6 ${r%60}\u5206\u949F`:o>0?`${o}\u5C0F\u65F6 ${r%60}\u5206\u949F`:r>0?`${r}\u5206\u949F ${t%60}\u79D2`:`${t}\u79D2`}static formatFileSize(e){let t=["B","KB","MB","GB","TB"],r=e,o=0;for(;r>=1024&&o<t.length-1;)r/=1024,o++;return`${r.toFixed(o===0?0:1)} ${t[o]}`}static formatTimestamp(e,t="full"){let r=new Date(e);switch(t){case"date":return r.toLocaleDateString("zh-CN");case"time":return r.toLocaleTimeString("zh-CN");default:return r.toLocaleString("zh-CN")}}static formatPid(e){return`PID: ${e}`}static formatPort(e){return`\u7AEF\u53E3: ${e}`}static formatUrl(e,t,r,o){let n=`${e}://${t}:${r}`;return o?`${n}${o}`:n}static formatConfigPair(e,t){return typeof t=="object"?`${e}: ${JSON.stringify(t,null,2)}`:`${e}: ${t}`}static formatError(e,t=!1){let r=`\u9519\u8BEF: ${e.message}`;return t&&e.stack&&(r+=`
|
|
4
4
|
\u5806\u6808\u4FE1\u606F:
|
|
5
5
|
${e.stack}`),r}static formatList(e,t="\u2022"){return e.map(r=>`${t} ${r}`).join(`
|
|
6
|
-
`)}static formatTable(e){if(e.length===0)return"";let t=Object.keys(e[0]),r=t.map(a=>Math.max(a.length,...e.map(l=>String(l[a]).length))),
|
|
7
|
-
`)}static formatProgressBar(e,t,r=20){let n=Math.min(e/t,1),o=Math.floor(n*r),s=r-o,a="\u2588".repeat(o)+"\u2591".repeat(s),l=Math.floor(n*100);return`[${a}] ${l}% (${e}/${t})`}static formatCommandArgs(e,t){let r=t.map(n=>n.includes(" ")?`"${n}"`:n);return`${e} ${r.join(" ")}`}static truncateText(e,t,r="..."){return e.length<=t?e:e.substring(0,t-r.length)+r}static formatJson(e,t=2){try{return JSON.stringify(e,null,t)}catch{return String(e)}}static formatBoolean(e,t="\u662F",r="\u5426"){return e?t:r}}});import{realpathSync as Un}from"fs";import{tmpdir as Wn}from"os";import w from"path";import{fileURLToPath as vr}from"url";var b,Me=d(()=>{"use strict";De();Ne();b=class i{static{c(this,"PathUtils")}static getPidFile(){let e=process.env[ye.DIR_ENV_VAR]||process.cwd();return w.join(e,`.${At.NAME}.pid`)}static getLogFile(e){let t=e||process.cwd();return w.join(t,At.LOG_FILE)}static getConfigDir(){return process.env[ye.DIR_ENV_VAR]||process.cwd()}static getWorkDir(){let e=i.getConfigDir();return w.join(e,Ae.WORK_DIR)}static getTemplatesDir(){let e=vr(import.meta.url),t=w.dirname(e);return[w.join(t,Ae.TEMPLATES_DIR),w.join(t,"..","..","..",Ae.TEMPLATES_DIR),w.join(t,"..","..","..","..",Ae.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=w.join(t,e);return M.exists(r)?r:null}static getScriptDir(){let e=vr(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 ye.FILE_NAMES){let n=w.join(t,r);if(M.exists(n))return n}return w.join(t,ye.FILE_NAMES[2])}static getDefaultConfigPath(){let e=i.getProjectRoot();return w.join(e,ye.DEFAULT_FILE)}static validatePath(e){return!w.normalize(e).includes("..")}static ensurePathWithin(e,t){let r=w.resolve(t,e),n=w.resolve(t);if(!r.startsWith(n))throw new Error(`\u8DEF\u5F84 ${e} \u8D85\u51FA\u4E86\u5141\u8BB8\u7684\u8303\u56F4`);return r}static getExecutablePath(e){let t=process.argv[1];if(!t)return w.join(process.cwd(),`${e}.js`);let r;try{r=Un(t)}catch{r=t}let n=w.dirname(r);return w.join(n,`${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||Wn()}static getHomeDir(){return process.env.HOME||process.env.USERPROFILE||""}}});import{execSync as Sr}from"child_process";var L,He=d(()=>{"use strict";De();Z();L=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=Sr(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{encoding:"utf8",timeout:Dt.PROCESS_STOP}).toLowerCase():t=Sr(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:Dt.PROCESS_STOP}).toLowerCase(),t.includes("node")||t.includes("xiaozhi")}catch{return process.kill(e,0),!0}}catch{return!1}}static async killProcess(e,t="SIGTERM"){try{process.kill(e,t);let r=0,n=30;for(;r<n;){await new Promise(o=>setTimeout(o,100));try{process.kill(e,0),r++}catch{return}}try{process.kill(e,0),process.kill(e,"SIGKILL"),await new Promise(o=>setTimeout(o,500))}catch{}}catch(r){throw new se(`\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 V,Je=d(()=>{"use strict";Z();V=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(n=>n.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 n of t)if(!(n in e))throw new E(`\u7F3A\u5C11\u5FC5\u9700\u7684\u5C5E\u6027: ${n}`,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 Ke from"fs";import Y from"path";import{fileURLToPath as yr}from"url";var Ze,Er=d(()=>{"use strict";Z();Ze=class i{static{c(this,"VersionUtils")}static cachedVersion=null;static getVersion(){if(i.cachedVersion)return i.cachedVersion;try{let e=yr(import.meta.url),t=Y.dirname(e),r=[Y.join(t,"package.json"),Y.join(t,"..","package.json"),Y.join(t,"..","..","..","package.json"),Y.join(t,"..","..","..","..","package.json")];for(let n of r)if(Ke.existsSync(n)){let o=JSON.parse(Ke.readFileSync(n,"utf8"));if(o.version)return i.cachedVersion=o.version,o.version}return i.cachedVersion="unknown","unknown"}catch(e){return console.warn("\u65E0\u6CD5\u4ECE package.json \u8BFB\u53D6\u7248\u672C\u4FE1\u606F:",e),i.cachedVersion="unknown","unknown"}}static getVersionInfo(){try{let e=yr(import.meta.url),t=Y.dirname(e),r=[Y.join(t,"package.json"),Y.join(t,"..","package.json"),Y.join(t,"..","..","..","package.json"),Y.join(t,"..","..","..","..","package.json")];for(let n of r)if(Ke.existsSync(n)){let o=JSON.parse(Ke.readFileSync(n,"utf8"));return{version:o.version||"unknown",name:o.name,description:o.description,author:o.author}}return{version:"unknown"}}catch{throw new C("\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C\u4FE1\u606F","package.json")}}static compareVersions(e,t){let r=e.split(".").map(Number),n=t.split(".").map(Number),o=Math.max(r.length,n.length);for(let s=0;s<o;s++){let a=r[s]||0,l=n[s]||0;if(a>l)return 1;if(a<l)return-1}return 0}static isValidVersion(e){return/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?$/.test(e)}static clearCache(){i.cachedVersion=null}}});var Mr={};F(Mr,{ProcessManagerImpl:()=>ke});var ke,kt=d(()=>{"use strict";Z();Ne();Ht();Me();He();ke=class{static{c(this,"ProcessManagerImpl")}getPidFilePath(){return b.getPidFile()}readPidFile(){try{let e=this.getPidFilePath();if(!M.exists(e))return null;let t=M.readFile(e).trim(),[r,n,o]=t.split("|"),s=Number.parseInt(r),a=Number.parseInt(n);return Number.isNaN(s)||Number.isNaN(a)?(this.cleanupPidFile(),null):{pid:s,startTime:a,mode:o||"foreground"}}catch{return this.cleanupPidFile(),null}}writePidFile(e,t){try{let r=`${e}|${Date.now()}|${t}`,n=this.getPidFilePath();M.writeFile(n,r,{overwrite:!0})}catch{throw new C("\u65E0\u6CD5\u5199\u5165 PID \u6587\u4EF6",this.getPidFilePath())}}isXiaozhiProcess(e){return L.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=Ee.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 L.killProcess(e)}catch(t){throw new se(`\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B: ${t instanceof Error?t.message:String(t)}`,e)}}async gracefulKillProcess(e){try{process.kill(e,"SIGTERM");let t=0,r=30;for(;t<r;){await new Promise(n=>setTimeout(n,100));try{process.kill(e,0),t++}catch{return}}try{process.kill(e,0),process.kill(e,"SIGKILL"),await new Promise(n=>setTimeout(n,500))}catch{}}catch(t){throw new se(`\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 L.processExists(e)}cleanupContainerState(){if(L.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 Pr={};F(Pr,{DaemonManagerImpl:()=>jt});import{spawn as wr}from"child_process";import Qe from"fs";var jt,br=d(()=>{"use strict";Z();Me();He();jt=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 T.alreadyRunning(r.pid);let n=await this.spawnDaemonProcess(e,t);this.currentDaemon=n,this.processManager.savePidInfo(n.pid,"daemon"),await this.setupLogging(n,t.logFileName||"xiaozhi.log"),this.setupEventHandlers(n),n.unref(),this.logger.info(`\u5B88\u62A4\u8FDB\u7A0B\u5DF2\u542F\u52A8 (PID: ${n.pid})`)}catch(r){throw new T(`\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 T.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 T(`\u505C\u6B62\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async restartDaemon(e,t={}){try{this.processManager.getServiceStatus().running&&(await this.stopDaemon(),await new Promise(n=>setTimeout(n,1e3))),await this.startDaemon(e,t)}catch(r){throw new T(`\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=b.getLogFile();if(!Qe.existsSync(t))throw new T("\u65E5\u5FD7\u6587\u4EF6\u4E0D\u5B58\u5728");let{command:r,args:n}=L.getTailCommand(t),o=wr(r,n,{stdio:"inherit"});process.on("SIGINT",()=>{console.log(`
|
|
8
|
-
\u65AD\u5F00\u8FDE\u63A5\uFF0C\u670D\u52A1\u7EE7\u7EED\u5728\u540E\u53F0\u8FD0\u884C`),
|
|
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(`
|
|
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 ee from"ws";var x,le,Ye=d(()=>{"use strict";y();x=class extends Error{constructor(t,r,n){super(r);this.code=t;this.data=n;this.name="ToolCallError"}static{c(this,"ToolCallError")}},le=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 n of t)r.set(n.name,{name:n.name,description:n.description,inputSchema:n.inputSchema});this.tools=r,this.logger.info(`\u5DF2\u4ECE MCPServiceManager \u540C\u6B65 ${this.tools.size} \u4E2A\u5DE5\u5177`)}catch(t){this.logger.error(`\u540C\u6B65\u5DE5\u5177\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}addTool(e,t){return this.validateTool(e,t),this.tools.set(e,t),this.logger.debug(`\u5DE5\u5177 '${e}' \u5DF2\u6DFB\u52A0`),this}addTools(e){for(let[t,r]of Object.entries(e))this.addTool(t,r);return this}removeTool(e){return this.tools.delete(e)?this.logger.debug(`\u5DE5\u5177 '${e}' \u5DF2\u79FB\u9664`):this.logger.warn(`\u5C1D\u8BD5\u79FB\u9664\u4E0D\u5B58\u5728\u7684\u5DE5\u5177: '${e}'`),this}getTools(){try{this.syncToolsFromServiceManager()}catch{}return Array.from(this.tools.values())}hasTool(e){return this.tools.has(e)}validateTool(e,t){if(!e||typeof e!="string"||e.trim()==="")throw new Error("\u5DE5\u5177\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(this.tools.has(e))throw new Error(`\u5DE5\u5177 '${e}' \u5DF2\u5B58\u5728`);if(!t||typeof t!="object")throw new Error("\u5DE5\u5177\u5FC5\u987B\u662F\u6709\u6548\u7684\u5BF9\u8C61");if(!t.name||typeof t.name!="string")throw new Error("\u5DE5\u5177\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 'name' \u5B57\u6BB5");if(!t.description||typeof t.description!="string")throw new Error("\u5DE5\u5177\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 'description' \u5B57\u6BB5");if(!t.inputSchema||typeof t.inputSchema!="object")throw new Error("\u5DE5\u5177\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 'inputSchema' \u5B57\u6BB5");if(!t.inputSchema.type||!t.inputSchema.properties)throw new Error("\u5DE5\u5177\u7684 inputSchema \u5FC5\u987B\u5305\u542B 'type' \u548C 'properties' \u5B57\u6BB5")}async connect(){if(this.tools.size===0)throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u5DE5\u5177\u3002\u8BF7\u5728\u8FDE\u63A5\u524D\u81F3\u5C11\u6DFB\u52A0\u4E00\u4E2A\u5DE5\u5177\u3002");if(this.connectionState==="connecting")throw new Error("\u8FDE\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u8FDE\u63A5\u5B8C\u6210");return this.cleanupConnection(),this.reconnectState.isManualDisconnect=!1,this.attemptConnection()}async attemptConnection(){return this.connectionState="connecting",this.logger.info(`\u6B63\u5728\u8FDE\u63A5 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 ee(this.endpointUrl),this.ws.on("open",()=>{this.handleConnectionSuccess(),e()}),this.ws.on("message",r=>{try{let n=JSON.parse(r.toString());this.handleMessage(n)}catch(n){this.logger.error("MCP \u6D88\u606F\u89E3\u6790\u9519\u8BEF:",n)}}),this.ws.on("close",(r,n)=>{this.handleConnectionClose(r,n.toString())}),this.ws.on("error",r=>{this.handleConnectionError(r),t(r)})})}handleConnectionSuccess(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.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===ee.OPEN?this.ws.close(1e3,"Cleaning up connection"):this.ws.readyState===ee.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.info(`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===ee.OPEN){let r={jsonrpc:"2.0",id:e,result:t};try{this.ws.send(JSON.stringify(r)),this.logger.info(`\u54CD\u5E94\u5DF2\u53D1\u9001: id=${e}`,{responseSize:JSON.stringify(r).length})}catch(n){this.logger.error(`\u53D1\u9001\u54CD\u5E94\u5931\u8D25: id=${e}`,n)}}else this.logger.error(`\u65E0\u6CD5\u53D1\u9001\u54CD\u5E94: id=${e}, \u8FDE\u63A5\u72B6\u6001\u68C0\u67E5\u5931\u8D25`,{isConnected:this.isConnected,wsReadyState:this.ws?.readyState,wsReadyStateText:this.ws?.readyState===ee.OPEN?"OPEN":this.ws?.readyState===ee.CONNECTING?"CONNECTING":this.ws?.readyState===ee.CLOSING?"CLOSING":this.ws?.readyState===ee.CLOSED?"CLOSED":"UNKNOWN"}),(!this.isConnected||this.ws?.readyState!==ee.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 x(-32602,"\u8BF7\u6C42 ID \u4E0D\u80FD\u4E3A\u7A7A");let t=e.id,r=null;try{let n=this.validateToolCallParams(e.params);r=this.recordCallStart(n.name,t),this.logger.info(`\u5F00\u59CB\u5904\u7406\u5DE5\u5177\u8C03\u7528: ${n.name}`,{requestId:t,toolName:n.name,hasArguments:!!n.arguments});let o=this.serviceManager;if(!o)throw new x(-32001,"MCPServiceManager \u672A\u8BBE\u7F6E");let s=await this.executeToolWithRetry(o,n.name,n.arguments||{});this.sendResponse(t,{content:s.content||[{type:"text",text:JSON.stringify(s)}],isError:s.isError||!1}),r&&this.recordCallEnd(r,!0),this.logger.info(`\u5DE5\u5177\u8C03\u7528\u6210\u529F: ${n.name}`,{requestId:t,duration:r?.duration?`${r.duration}ms`:"unknown"})}catch(n){if(r){let o=n instanceof x?n.code:-32e3,s=n instanceof Error?n.message:"\u672A\u77E5\u9519\u8BEF";this.recordCallEnd(r,!1,o,s)}this.handleToolCallError(n,t,r?.duration||0)}}validateToolCallParams(e){if(!e||typeof e!="object")throw new x(-32602,"\u8BF7\u6C42\u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61");if(!e.name||typeof e.name!="string")throw new x(-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 x(-32602,"\u5DE5\u5177\u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61");return{name:e.name,arguments:e.arguments}}async executeToolWithRetry(e,t,r){let n=null;for(let o=1;o<=this.retryConfig.maxAttempts;o++)try{return await this.executeToolWithTimeout(e,t,r,this.toolCallConfig.timeout)}catch(s){if(s instanceof x?n=s:n=new x(-32e3,s instanceof Error?s.message:"\u672A\u77E5\u9519\u8BEF"),this.retryConfig.retryableErrors.includes(n.code)&&o<this.retryConfig.maxAttempts){let a=Math.min(this.retryConfig.initialDelay*this.retryConfig.backoffMultiplier**(o-1),this.retryConfig.maxDelay);this.logger.warn(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25\uFF0C\u5C06\u5728 ${a}ms \u540E\u91CD\u8BD5 (${o}/${this.retryConfig.maxAttempts})`,{toolName:t,error:n.message,attempt:o,delay:a}),await new Promise(l=>setTimeout(l,a));continue}break}throw n}async executeToolWithTimeout(e,t,r,n=3e4){return new Promise((o,s)=>{let a=setTimeout(()=>{s(new x(-32002,`\u5DE5\u5177\u8C03\u7528\u8D85\u65F6 (${n}ms): ${t}`))},n);e.callTool(t,r).then(l=>{clearTimeout(a),o(l)}).catch(l=>{clearTimeout(a),l.message?.includes("\u672A\u627E\u5230\u5DE5\u5177")?s(new x(-32601,`\u5DE5\u5177\u4E0D\u5B58\u5728: ${t}`)):l.message?.includes("\u670D\u52A1")&&l.message?.includes("\u4E0D\u53EF\u7528")?s(new x(-32001,l.message)):l.message?.includes("\u6682\u65F6\u4E0D\u53EF\u7528")?s(new x(-32001,l.message)):l.message?.includes("\u6301\u7EED\u4E0D\u53EF\u7528")?s(new x(-32001,l.message)):s(new x(-32e3,`\u5DE5\u5177\u6267\u884C\u5931\u8D25: ${l.message}`))})})}handleToolCallError(e,t,r){let n;e instanceof x?n={code:e.code,message:e.message,data:e.data}:n={code:-32e3,message:e?.message||"\u672A\u77E5\u9519\u8BEF",data:{originalError:e?.toString()||"null"}},this.sendErrorResponse(t,n),this.logger.error("\u5DE5\u5177\u8C03\u7528\u5931\u8D25",{requestId:t,duration:`${r}ms`,error:n})}sendErrorResponse(e,t){if(this.isConnected&&this.ws?.readyState===ee.OPEN){let r={jsonrpc:"2.0",id:e,error:t};this.ws.send(JSON.stringify(r)),this.logger.debug("\u5DF2\u53D1\u9001\u9519\u8BEF\u54CD\u5E94:",r)}}recordCallStart(e,t){let r={id:String(t),toolName:e,startTime:new Date,success:!1};return this.callRecords.push(r),this.callRecords.length>this.maxCallRecords&&this.callRecords.shift(),r}recordCallEnd(e,t,r,n){e.endTime=new Date,e.duration=e.endTime.getTime()-e.startTime.getTime(),e.success=t,e.errorCode=r,e.errorMessage=n,this.updatePerformanceMetrics(e)}updatePerformanceMetrics(e){if(this.performanceMetrics.totalCalls++,e.success?this.performanceMetrics.successfulCalls++:this.performanceMetrics.failedCalls++,e.duration!==void 0){e.duration<this.performanceMetrics.minResponseTime&&(this.performanceMetrics.minResponseTime=e.duration),e.duration>this.performanceMetrics.maxResponseTime&&(this.performanceMetrics.maxResponseTime=e.duration);let t=this.callRecords.filter(n=>n.duration!==void 0).reduce((n,o)=>n+(o.duration||0),0),r=this.callRecords.filter(n=>n.duration!==void 0).length;this.performanceMetrics.averageResponseTime=r>0?t/r:0}this.performanceMetrics.successRate=this.performanceMetrics.totalCalls>0?this.performanceMetrics.successfulCalls/this.performanceMetrics.totalCalls*100:0,this.performanceMetrics.lastUpdated=new Date}getPerformanceMetrics(){return{...this.performanceMetrics}}getCallRecords(e){let t=[...this.callRecords].reverse();return e?t.slice(0,e):t}resetPerformanceMetrics(){this.performanceMetrics={totalCalls:0,successfulCalls:0,failedCalls:0,averageResponseTime:0,minResponseTime:Number.MAX_VALUE,maxResponseTime:0,successRate:0,lastUpdated:new Date},this.callRecords=[]}updateToolCallConfig(e){this.toolCallConfig={...this.toolCallConfig,...e},this.logger.info("\u5DE5\u5177\u8C03\u7528\u914D\u7F6E\u5DF2\u66F4\u65B0",this.toolCallConfig)}updateRetryConfig(e){this.retryConfig={...this.retryConfig,...e},this.logger.info("\u91CD\u8BD5\u914D\u7F6E\u5DF2\u66F4\u65B0",this.retryConfig)}getConfiguration(){return{toolCall:{...this.toolCallConfig},retry:{...this.retryConfig}}}getEnhancedStatus(){return{connected:this.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 we,je=d(()=>{"use strict";y();we=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,n)=>{setTimeout(()=>{n(new Error(`\u64CD\u4F5C\u8D85\u65F6: ${t}ms`))},t)})])}}});import{randomUUID as Bn}from"crypto";import zt from"express";var et,Tr=d(()=>{"use strict";je();et=class extends we{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=zt(),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(zt.json({limit:"10mb"})),this.app.use(zt.urlencoded({extended:!0})),this.app.use((e,t,r)=>{t.header("Access-Control-Allow-Origin",this.corsOrigin),t.header("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.header("Access-Control-Allow-Headers","Content-Type, Accept"),t.header("Cache-Control","no-cache"),r()}),this.app.use((e,t,r)=>{this.logger.debug(`${e.method} ${e.path}`,{query:e.query,headers:e.headers}),r()})}setupRoutes(){this.enableSSE&&(this.app.get("/sse",this.handleSSE.bind(this)),this.app.post("/messages",this.handleMessages.bind(this))),this.enableRPC&&this.app.post("/rpc",this.handleRPC.bind(this)),this.app.get("/status",this.handleStatus.bind(this)),this.app.get("/health",this.handleHealth.bind(this))}handleSSE(e,t){if(this.clients.size>=this.maxClients){t.status(503).json({error:"\u670D\u52A1\u5668\u7E41\u5FD9\uFF0C\u5BA2\u6237\u7AEF\u8FDE\u63A5\u6570\u5DF2\u8FBE\u4E0A\u9650",maxClients:this.maxClients});return}let r=Date.now().toString(),n=Bn();t.setHeader("Content-Type","text/event-stream"),t.setHeader("Cache-Control","no-cache, no-transform"),t.setHeader("Connection","keep-alive"),t.setHeader("X-Accel-Buffering","no");let o={id:r,sessionId:n,response:t,connectedAt:new Date};this.clients.set(n,o),this.logger.info(`SSE \u5BA2\u6237\u7AEF\u5DF2\u8FDE\u63A5: ${r} (\u4F1A\u8BDD: ${n})`),t.write(`event: endpoint
|
|
11
|
-
data: /messages?sessionId=${
|
|
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
|
|
11
|
+
data: /messages?sessionId=${o}
|
|
12
12
|
|
|
13
|
-
`),e.on("close",()=>{this.clients.delete(
|
|
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 Rr=d(()=>{"use strict";je()});import _s,{WebSocketServer as Fs}from"ws";var Ir=d(()=>{"use strict";je()});var tt,xr=d(()=>{"use strict";y();K();tt=class{static{c(this,"CustomMCPHandler")}logger;tools=new Map;defaultTimeout=3e4;defaultRetries=2;defaultRetryDelay=1e3;constructor(){this.logger=g}initialize(e){this.logger.info("[CustomMCP] \u521D\u59CB\u5316 CustomMCP \u5904\u7406\u5668...");try{let t=e||m.getCustomMCPTools();this.tools.clear();for(let r of t)this.tools.set(r.name,r),this.logger.info(`[CustomMCP] \u5DF2\u52A0\u8F7D\u5DE5\u5177: ${r.name} (${r.handler.type})`);this.logger.info(`[CustomMCP] \u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.tools.size} \u4E2A\u5DE5\u5177`)}catch(t){throw this.logger.error("[CustomMCP] \u521D\u59CB\u5316\u5931\u8D25:",t),t}}getTools(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}))}hasTool(e){return this.tools.has(e)}getToolCount(){return this.tools.size}getToolNames(){return Array.from(this.tools.keys())}async callTool(e,t,r){let n=this.tools.get(e);if(!n)throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);this.logger.info(`[CustomMCP] \u8C03\u7528\u5DE5\u5177: ${e}`,{handler:n.handler.type,arguments:t});let o={timeout:r?.timeout??this.defaultTimeout,retries:r?.retries??this.defaultRetries,retryDelay:r?.retryDelay??this.defaultRetryDelay};return await this.executeWithRetry(n,t,o)}async executeWithRetry(e,t,r){let n=null;for(let o=0;o<=r.retries;o++)try{return o>0&&(this.logger.info(`[CustomMCP] \u91CD\u8BD5\u8C03\u7528\u5DE5\u5177 ${e.name}\uFF0C\u7B2C ${o} \u6B21\u91CD\u8BD5`),await this.delay(r.retryDelay)),await this.executeToolCall(e,t,r.timeout)}catch(s){if(n=s instanceof Error?s:new Error(String(s)),this.logger.warn(`[CustomMCP] \u5DE5\u5177 ${e.name} \u8C03\u7528\u5931\u8D25 (\u5C1D\u8BD5 ${o+1}/${r.retries+1}):`,n.message),o===r.retries)break}return this.logger.error(`[CustomMCP] \u5DE5\u5177 ${e.name} \u8C03\u7528\u6700\u7EC8\u5931\u8D25:`,n),{content:[{type:"text",text:`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${n?.message||"\u672A\u77E5\u9519\u8BEF"}`}],isError:!0}}async executeToolCall(e,t,r){let n=new Promise((s,a)=>{setTimeout(()=>{a(new Error(`\u5DE5\u5177\u8C03\u7528\u8D85\u65F6 (${r}ms)`))},r)}),o=this.callToolByType(e,t);try{return await Promise.race([o,n])}catch(s){throw s instanceof Error?s:new Error(String(s))}}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);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 n=e.handler.config;this.logger.info(`[CustomMCP] \u8C03\u7528 Coze \u5DE5\u4F5C\u6D41: ${e.name}`,{workflow_id:n.workflow_id,bot_id:n.bot_id});try{let o=this.buildCozeRequest(n,t),s=await this.sendCozeRequest(n,o);return this.processCozeResponse(e.name,s)}catch(o){return this.logger.error(`[CustomMCP] Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25: ${e.name}`,o),{content:[{type:"text",text:`Coze \u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}buildCozeRequest(e,t){return{workflow_id:e.workflow_id,parameters:{...t}}}async sendCozeRequest(e,t){let r=e.base_url||"https://api.coze.cn",n="",o=m.getConfig().platforms?.coze?.token;if(!o)throw new Error("Coze Token \u914D\u7F6E\u4E0D\u5B58\u5728");if(e.workflow_id)n="/v1/workflow/run",t.workflow_id=e.workflow_id;else if(e.bot_id)n="/v3/chat",t.bot_id=e.bot_id;else throw new Error("Coze \u914D\u7F6E\u5FC5\u987B\u63D0\u4F9B workflow_id \u6216 bot_id");let s=`${r}${n}`,a=e.timeout||3e4,l={"Content-Type":"application/json",Authorization:`Bearer ${o}`,...e.headers};this.logger.debug(`[CustomMCP] \u53D1\u9001 Coze \u8BF7\u6C42\u5230: ${s}`,{headers:{...l},body:t});let h=new AbortController,u=setTimeout(()=>h.abort(),a);try{let p=await fetch(s,{method:"POST",headers:l,body:JSON.stringify(t),signal:h.signal});if(clearTimeout(u),!p.ok){let R=await p.text();throw new Error(`Coze API \u8BF7\u6C42\u5931\u8D25 (${p.status}): ${R}`)}let S=await p.json();return this.logger.debug("[CustomMCP] Coze API \u54CD\u5E94:",S),S}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 n=await this.loadModule(r.module),o=this.getFunction(n,r.function),s=await this.executeFunction(o,t,r);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s,null,2)}],isError:!1}}catch(n){return this.logger.error(`[CustomMCP] \u51FD\u6570\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`\u51FD\u6570\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}async loadModule(e){try{let t=e;return!e.startsWith("/")&&!e.startsWith("file://")&&(t=new URL(e,`file://${process.cwd()}/`).href),this.logger.debug(`[CustomMCP] \u52A0\u8F7D\u6A21\u5757: ${t}`),await import(t)}catch(t){throw new Error(`\u65E0\u6CD5\u52A0\u8F7D\u6A21\u5757 ${e}: ${t instanceof Error?t.message:String(t)}`)}}getFunction(e,t){let r;if(e.default&&typeof e.default=="function"&&(t==="default"?r=e.default:e.default[t]&&typeof e.default[t]=="function"&&(r=e.default[t])),!r&&e[t]&&typeof e[t]=="function"&&(r=e[t]),!r)throw new Error(`\u5728\u6A21\u5757\u4E2D\u627E\u4E0D\u5230\u51FD\u6570: ${t}`);return r}async executeFunction(e,t,r){let n=r.timeout||3e4,o={...r.context,logger:this.logger,arguments:t},s=Promise.resolve().then(()=>e.length>1?e(t,o):e(t)),a=new Promise((l,h)=>{setTimeout(()=>h(new Error(`\u51FD\u6570\u6267\u884C\u8D85\u65F6 (${n}ms)`)),n)});return Promise.race([s,a])}async callHttpTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528 HTTP \u5DE5\u5177: ${e.name}`,{url:r.url,method:r.method||"POST"});try{let{url:n,requestOptions:o}=this.buildHttpRequest(r,t),s=await this.sendHttpRequest(n,o,r);return this.processHttpResponse(e.name,s,r)}catch(n){return this.logger.error(`[CustomMCP] HTTP \u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`HTTP \u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}buildHttpRequest(e,t){let r=e.method||"POST",n={"Content-Type":"application/json","User-Agent":"xiaozhi-client/1.0",...e.headers};if(e.auth)switch(e.auth.type){case"bearer":e.auth.token&&(n.Authorization=`Bearer ${e.auth.token}`);break;case"basic":if(e.auth.username&&e.auth.password){let l=btoa(`${e.auth.username}:${e.auth.password}`);n.Authorization=`Basic ${l}`}break;case"api_key":e.auth.api_key&&e.auth.api_key_header&&(n[e.auth.api_key_header]=e.auth.api_key);break}let o,s=e.url;if(r!=="GET")e.body_template?o=this.replaceTemplateVariables(e.body_template,t):o=JSON.stringify(t);else{let l=new URLSearchParams;for(let[u,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:n,body:o}}}async sendHttpRequest(e,t,r){let n=r.timeout||3e4,o=r.retry_count||0,s=r.retry_delay||1e3,a=null;for(let l=0;l<=o;l++){try{this.logger.debug(`[CustomMCP] \u53D1\u9001 HTTP \u8BF7\u6C42 (\u5C1D\u8BD5 ${l+1}/${o+1}): ${e}`,{method:t.method,headers:t.headers});let h=new AbortController,u=setTimeout(()=>h.abort(),n),p=await fetch(e,{...t,signal:h.signal});if(clearTimeout(u),p.ok||l===o)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 (${n}ms)`)),this.logger.warn(`[CustomMCP] HTTP \u8BF7\u6C42\u5F02\u5E38 (\u5C1D\u8BD5 ${l+1}/${o+1}):`,a.message),l===o)throw a}l<o&&await new Promise(h=>setTimeout(h,s))}throw a||new Error("HTTP \u8BF7\u6C42\u5931\u8D25")}async processHttpResponse(e,t,r){try{let n=t.headers.get("content-type")||"",o;if(n.includes("application/json")?o=await t.json():o=await t.text(),!t.ok)return{content:[{type:"text",text:`HTTP \u8BF7\u6C42\u5931\u8D25 (${t.status}): ${typeof o=="string"?o:JSON.stringify(o)}`}],isError:!0};let s=o;return r.response_mapping&&(s=this.extractResponseData(o,r.response_mapping)),{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s,null,2)}],isError:!1}}catch(n){return this.logger.error(`[CustomMCP] \u5904\u7406 HTTP \u54CD\u5E94\u5931\u8D25: ${e}`,n),{content:[{type:"text",text:`\u5904\u7406\u54CD\u5E94\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}replaceTemplateVariables(e,t){let r=e;for(let[n,o]of Object.entries(t)){let s=`{{${n}}}`,a=typeof o=="string"?o:JSON.stringify(o);r=r.replace(new RegExp(s.replace(/[{}]/g,"\\$&"),"g"),a)}return r}extractResponseData(e,t){if(!t)return e;let r=c((n,o)=>{if(!o)return n;let s=o.split("."),a=n;for(let l of s)if(a&&typeof a=="object"&&l in a)a=a[l];else return;return a},"extractByPath");if(t.success_path){let n=r(e,t.success_path);if(n!==void 0)return t.data_path?r(n,t.data_path):n}if(t.data_path){let n=r(e,t.data_path);if(n!==void 0)return n}return e}async callScriptTool(e,t){let r=e.handler;this.logger.info(`[CustomMCP] \u8C03\u7528\u811A\u672C\u5DE5\u5177: ${e.name}`,{script:r.script.substring(0,100)+(r.script.length>100?"...":""),interpreter:r.interpreter||"node"});try{let n=await this.executeScript(r,t);return{content:[{type:"text",text:typeof n=="string"?n:JSON.stringify(n,null,2)}],isError:!1}}catch(n){return this.logger.error(`[CustomMCP] \u811A\u672C\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,n),{content:[{type:"text",text:`\u811A\u672C\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}async executeScript(e,t){let{spawn:r}=await import("child_process"),{promisify:n}=await import("util"),o=await import("fs/promises"),s=await import("path"),a=await import("os"),l=e.timeout||3e4,h=e.interpreter||"node",u,p=!1;try{if(e.script.includes(`
|
|
16
|
-
|
|
17
|
-
`);if(a)try{n=JSON.parse(a)}catch{n={input:a,...t}}}}catch(s){let a={content:[{type:"text",text:`\u5DE5\u5177 ${o} \u6267\u884C\u5F02\u5E38: ${s instanceof Error?s.message:String(s)}`}],isError:!0};if(r.push(a),e.error_handling==="stop")break}return r}async executeParallelChain(e,t){let r=e.tools.map(async n=>{try{return this.logger.debug(`[CustomMCP] \u5E76\u884C\u6267\u884C\u94FE\u5F0F\u5DE5\u5177\u4E2D\u7684: ${n}`),await this.callToolRecursive(n,t)}catch(o){return{content:[{type:"text",text:`\u5DE5\u5177 ${n} \u6267\u884C\u5F02\u5E38: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}});return Promise.all(r)}async callToolRecursive(e,t){if(this.tools.get(e))return this.callTool(e,t);throw new Error(`\u94FE\u5F0F\u5DE5\u5177\u4E2D\u5F15\u7528\u7684\u5DE5\u5177 ${e} \u4E0D\u5B58\u5728\u4E8E\u5F53\u524D CustomMCP \u5DE5\u5177\u96C6\u4E2D`)}}});import{createHash as Vn}from"crypto";import{existsSync as ze,mkdirSync as Gn,readFileSync as $r,renameSync as qn,writeFileSync as Or}from"fs";import{dirname as Xn,resolve as Ar}from"path";import Jn from"dayjs";var _e,Dr=d(()=>{"use strict";y();_e=class{static{c(this,"MCPCacheManager")}cachePath;logger;CACHE_VERSION="1.0.0";CACHE_ENTRY_VERSION="1.0.0";constructor(e){this.logger=g,this.cachePath=e||this.getCacheFilePath()}formatTimestamp(){return Jn().format("YYYY-MM-DD HH:mm:ss")}getCacheFilePath(){try{let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return Ar(e,"xiaozhi.cache.json")}catch{let t=process.env.XIAOZHI_CONFIG_DIR||"/tmp";return Ar(t,"xiaozhi.cache.json")}}async ensureCacheFile(){try{if(!ze(this.cachePath)){let e=Xn(this.cachePath);ze(e)||(Gn(e,{recursive:!0}),this.logger.debug(`[CacheManager] \u5DF2\u521B\u5EFA\u7F13\u5B58\u76EE\u5F55: ${e}`)),this.logger.debug("[CacheManager] \u7F13\u5B58\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u521B\u5EFA\u521D\u59CB\u7F13\u5B58\u6587\u4EF6");let t=await this.createInitialCache();await this.saveCache(t),this.logger.info(`[CacheManager] \u5DF2\u521B\u5EFA\u7F13\u5B58\u6587\u4EF6: ${this.cachePath}`)}}catch(e){this.logger.warn(`[CacheManager] \u521B\u5EFA\u7F13\u5B58\u6587\u4EF6\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async createInitialCache(){let e=this.formatTimestamp();return{version:this.CACHE_VERSION,mcpServers:{},metadata:{lastGlobalUpdate:e,totalWrites:0,createdAt:e}}}async writeCacheEntry(e,t,r){try{this.logger.debug(`[CacheManager] \u5F00\u59CB\u5199\u5165\u7F13\u5B58: ${e}`),await this.ensureCacheFile();let n=await this.loadExistingCache(),o=this.generateConfigHash(r),s={tools:t.map(a=>({name:a.name,description:a.description||"",inputSchema:a.inputSchema})),lastUpdated:this.formatTimestamp(),serverConfig:{...r},configHash:o,version:this.CACHE_ENTRY_VERSION};n.mcpServers[e]=s,n.metadata.lastGlobalUpdate=this.formatTimestamp(),n.metadata.totalWrites+=1,await this.saveCache(n),this.logger.info(`[CacheManager] \u7F13\u5B58\u5199\u5165\u6210\u529F: ${e}, \u5DE5\u5177\u6570\u91CF: ${t.length}`)}catch(n){this.logger.warn(`[CacheManager] \u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e}, \u9519\u8BEF: ${n instanceof Error?n.message:String(n)}`)}}async loadExistingCache(){try{if(!ze(this.cachePath))return await this.createInitialCache();let e=$r(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{Or(r,t,"utf8"),qn(r,e)}catch(n){try{ze(r)&&Or(r,"","utf8")}catch{}throw n}}generateConfigHash(e){try{return Vn("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:ze(this.cachePath)?$r(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}}});import{SSEClientTransport as Nr}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as Kn}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Zn}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{EventSource as Qn}from"eventsource";function Yn(){return g}function eo(i){switch(Yn().info(`[TransportFactory] \u521B\u5EFA ${i.type} transport for ${i.name}`),i.type){case"stdio":return to(i);case"sse":return ro(i);case"modelscope-sse":return no(i);case"streamable-http":return oo(i);default:throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}function to(i){if(!i.command)throw new Error("stdio transport \u9700\u8981 command \u914D\u7F6E");return new Kn({command:i.command,args:i.args||[],env:i.env})}function ro(i){if(!i.url)throw new Error("SSE transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=io(i);return new Nr(e,t)}function no(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=so(i);return new Nr(e,t)}function oo(i){if(!i.url)throw new Error("StreamableHTTP transport \u9700\u8981 URL \u914D\u7F6E");let e=new URL(i.url),t=ao(i);return new Zn(e,t)}function io(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function so(i){let e=i.apiKey;return i.customSSEOptions?i.customSSEOptions:{eventSourceInit:{fetch:c(async(t,r)=>{let n={...r?.headers,Authorization:`Bearer ${e}`};return fetch(t,{...r,headers:n})},"fetch")},requestInit:{headers:{Authorization:`Bearer ${e}`,...i.headers}}}}function ao(i){let e={};return i.apiKey?e.headers={Authorization:`Bearer ${i.apiKey}`,...i.headers}:i.headers&&(e.headers=i.headers),e}function co(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 lo(){return["stdio","sse","modelscope-sse","streamable-http"]}var Ft,Hr=d(()=>{"use strict";y();rt();typeof global<"u"&&!global.EventSource&&(global.EventSource=Qn);c(Yn,"getLogger");c(eo,"createTransport");c(to,"createStdioTransport");c(ro,"createSSETransport");c(no,"createModelScopeSSETransport");c(oo,"createStreamableHTTPTransport");c(io,"createSSEOptions");c(so,"createModelScopeSSEOptions");c(ao,"createStreamableHTTPOptions");c(co,"validateConfig");c(lo,"getSupportedTypes");Ft={create:eo,validateConfig:co,getSupportedTypes:lo}});import{Client as go}from"@modelcontextprotocol/sdk/client/index.js";var Fe,nt,rt=d(()=>{"use strict";y();Hr();Fe=(n=>(n.STDIO="stdio",n.SSE="sse",n.STREAMABLE_HTTP="streamable-http",n.MODELSCOPE_SSE="modelscope-sse",n))(Fe||{}),nt=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 n=`[MCP-${this.config.name}] ${t}`;this.logger[e](n,...r)}validateConfig(){Ft.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 go({name:`xiaozhi-${this.config.name}-client`,version:"1.0.0"},{capabilities:{tools:{}}}),this.transport=Ft.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((o,s)=>{setTimeout(()=>{s(new Error(`Ping\u8D85\u65F6 (${this.pingOptions.timeout}ms)`))},this.pingOptions.timeout)});await Promise.race([t,r]);let n=performance.now()-e;this.handlePingSuccess(n)}catch(t){let r=performance.now()-e;this.handlePingFailure(t,r)}finally{this.isPinging=!1}}handlePingSuccess(e){this.pingFailureCount=0,this.lastPingTime=new Date,this.logger.debug(`${this.config.name} ping\u6210\u529F\uFF0C\u5EF6\u8FDF: ${e.toFixed(2)}ms`)}handlePingFailure(e,t){if(this.pingFailureCount++,this.logger.warn(`${this.config.name} ping\u5931\u8D25 (${this.pingFailureCount}/${this.pingOptions.maxFailures})\uFF0C\u5EF6\u8FDF: ${t.toFixed(2)}ms\uFF0C\u9519\u8BEF: ${e.message}`),this.pingFailureCount>=this.pingOptions.maxFailures){this.logger.error(`${this.config.name} \u8FDE\u7EEDping\u5931\u8D25\u8FBE\u5230\u9608\u503C\uFF0C\u89E6\u53D1\u91CD\u8FDE\u673A\u5236`),this.stopPingMonitoring();let r=new Error(`Ping\u68C0\u6D4B\u5931\u8D25\uFF0C\u8FDE\u7EED\u5931\u8D25${this.pingFailureCount}\u6B21\uFF0C\u8FDE\u63A5\u53EF\u80FD\u5DF2\u65AD\u5F00`);this.handleConnectionError(r)}}resetPingState(){this.pingFailureCount=0,this.lastPingTime=null,this.isPinging=!1}enablePing(){this.pingOptions.enabled=!0,this.logger.info(`${this.config.name} ping\u76D1\u63A7\u5DF2\u542F\u7528`),this.isConnected()&&this.startPingMonitoring()}disablePing(){this.pingOptions.enabled=!1,this.stopPingMonitoring(),this.logger.info(`${this.config.name} ping\u76D1\u63A7\u5DF2\u7981\u7528`)}updatePingOptions(e){let t=this.pingOptions.enabled;this.pingOptions={...this.pingOptions,...e},this.logger.info(`${this.config.name} ping\u914D\u7F6E\u5DF2\u66F4\u65B0`,e),t!==this.pingOptions.enabled&&(this.pingOptions.enabled&&this.isConnected()?this.startPingMonitoring():this.pingOptions.enabled||this.stopPingMonitoring())}getPingOptions(){return{...this.pingOptions}}}});var Le,kr,Lt=d(()=>{"use strict";y();K();xr();Dr();rt();Le=class{static{c(this,"MCPServiceManager")}services=new Map;configs={};logger;tools=new Map;customMCPHandler;cacheManager;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 _e(r),this.customMCPHandler=new tt,this.cacheManager=new _e}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 nt(t);await r.connect(),this.services.set(e,r),await this.refreshToolsCache();let n=r.getTools();this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u542F\u52A8\u6210\u529F\uFF0C\u52A0\u8F7D\u4E86 ${n.length} \u4E2A\u5DE5\u5177:`,n.map(o=>o.name).join(", "))}catch(r){throw this.logger.error(`[MCPManager] \u542F\u52A8 ${e} \u670D\u52A1\u5931\u8D25:`,r.message),r}}async stopService(e){this.logger.info(`[MCPManager] \u505C\u6B62 MCP \u670D\u52A1: ${e}`);let t=this.services.get(e);if(!t){this.logger.warn(`[MCPManager] \u670D\u52A1 ${e} \u4E0D\u5B58\u5728\u6216\u672A\u542F\u52A8`);return}try{await t.disconnect(),this.services.delete(e),await this.refreshToolsCache(),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u5DF2\u505C\u6B62`)}catch(r){throw this.logger.error(`[MCPManager] \u505C\u6B62 ${e} \u670D\u52A1\u5931\u8D25:`,r.message),r}}async refreshToolsCache(){this.tools.clear();for(let[e,t]of this.services)if(t.isConnected()){let r=t.getTools(),n=this.configs[e];n&&this.cacheManager.writeCacheEntry(e,r,n).then(()=>{this.logger.debug(`[MCPManager] \u5DF2\u5C06 ${e} \u5DE5\u5177\u5217\u8868\u5199\u5165\u7F13\u5B58`)}).catch(o=>{this.logger.warn(`[MCPManager] \u5199\u5165\u7F13\u5B58\u5931\u8D25: ${e}, \u9519\u8BEF: ${o instanceof Error?o.message:String(o)}`)});for(let o of r){let s=`${e}__${o.name}`;this.tools.set(s,{serviceName:e,originalName:o.name,tool:o})}}await this.syncToolsConfigToFile()}getAllTools(){let e=[];try{let t=this.customMCPHandler.getTools();for(let r of t)e.push({name:r.name,description:r.description||"",inputSchema:r.inputSchema,serviceName:"customMCP",originalName:r.name});t.length>0&&this.logger.info(`[MCPManager] \u6DFB\u52A0\u4E86 ${t.length} \u4E2A customMCP \u5DE5\u5177`)}catch(t){this.logger.error("[MCPManager] \u83B7\u53D6 CustomMCP \u5DE5\u5177\u5931\u8D25:",t)}for(let[t,r]of this.tools)m.isToolEnabled(r.serviceName,r.originalName)&&e.push({name:t,description:r.tool.description||"",inputSchema:r.tool.inputSchema,serviceName:r.serviceName,originalName:r.originalName});return this.logger.info(`[MCPManager] \u8FD4\u56DE\u603B\u8BA1 ${e.length} \u4E2A\u5DE5\u5177 (customMCP + \u6807\u51C6 MCP)`),e}async callTool(e,t){if(this.logger.info(`[MCPManager] \u8C03\u7528\u5DE5\u5177: ${e}\uFF0C\u53C2\u6570:`,t),this.customMCPHandler.hasTool(e))try{let o=await this.customMCPHandler.callTool(e,t);return this.logger.info(`[MCPManager] CustomMCP \u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F`),o}catch(o){throw this.logger.error(`[MCPManager] CustomMCP \u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,o.message),o}let r=this.tools.get(e);if(!r)throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);let n=this.services.get(r.serviceName);if(!n)throw new Error(`\u670D\u52A1 ${r.serviceName} \u4E0D\u53EF\u7528`);if(!n.isConnected())throw new Error(`\u670D\u52A1 ${r.serviceName} \u672A\u8FDE\u63A5`);try{let o=await n.callTool(r.originalName,t||{});return this.logger.info(`[MCPManager] \u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F\uFF0C\u7ED3\u679C:`,o),o}catch(o){throw this.logger.error(`[MCPManager] \u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,o.message),o}}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)}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()),n=this.customMCPHandler.getToolNames(),o=[...r,...n],s={services:{},totalTools:t,availableTools:o};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}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=m.getModelScopeApiKey();if(r)t.apiKey=r,this.logger.info(`[MCPManager] \u4E3A ${e.name} \u670D\u52A1\u6DFB\u52A0 ModelScope API Key`);else throw this.logger.warn(`[MCPManager] ${e.name} \u670D\u52A1\u9700\u8981 ModelScope API Key\uFF0C\u4F46\u672A\u5728\u914D\u7F6E\u4E2D\u627E\u5230`),new Error(`ModelScope SSE \u670D\u52A1 ${e.name} \u9700\u8981 API Key\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E modelscope.apiKey`)}return t}catch(r){throw this.logger.error(`[MCPManager] \u914D\u7F6E\u589E\u5F3A\u5931\u8D25: ${e.name}`,r),r}}addServiceConfig(e,t){let r,n;if(typeof e=="string"&&t)n=e,r=t;else if(typeof e=="object")n=e.name,r=e;else throw new Error("Invalid arguments for addServiceConfig");let o=this.enhanceServiceConfig(r);this.configs[n]=o,this.logger.info(`[MCPManager] \u5DF2\u6DFB\u52A0\u670D\u52A1\u914D\u7F6E: ${n}`)}updateServiceConfig(e,t){let r=this.enhanceServiceConfig(t);this.configs[e]=r,this.logger.info(`[MCPManager] \u5DF2\u66F4\u65B0\u5E76\u589E\u5F3A\u670D\u52A1\u914D\u7F6E: ${e}`)}removeServiceConfig(e){delete this.configs[e],this.logger.info(`[MCPManager] \u5DF2\u79FB\u9664\u670D\u52A1\u914D\u7F6E: ${e}`)}async syncToolsConfigToFile(){try{this.logger.debug("[MCPManager] \u5F00\u59CB\u540C\u6B65\u5DE5\u5177\u914D\u7F6E\u5230\u914D\u7F6E\u6587\u4EF6");let e=m.getMcpServerConfig();for(let[t,r]of this.services){if(!r.isConnected())continue;let n=r.getTools();if(n.length===0)continue;let o=e[t]?.tools||{},s={};for(let p of n){let S=o[p.name];S?s[p.name]={...S,description:p.description||S.description||""}:s[p.name]={description:p.description||"",enable:!0}}let a=n.map(p=>p.name),h=Object.keys(o).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(o,s)){m.updateServerToolsConfig(t,s);let p=Object.keys(s).filter(R=>!o[R]),S=Object.keys(s).filter(R=>{let $=o[R],oe=s[R];return $&&$.description!==oe.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(", ")}`),S.length>0&&this.logger.info(` - \u66F4\u65B0\u5DE5\u5177: ${S.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),n=Object.keys(t);if(r.length!==n.length)return!0;let o=n.filter(a=>!r.includes(a)),s=r.filter(a=>!n.includes(a));if(o.length>0||s.length>0)return!0;for(let a of r){let l=e[a],h=t[a];if(l.description!==h.description)return!0}return!1}},kr=Le});var Pe,Ut=d(()=>{"use strict";y();Pe=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"],n=e.protocolVersion,o=r.includes(n)?n:"2024-11-05";return this.logger.info(`\u534F\u8BAE\u7248\u672C\u534F\u5546: \u5BA2\u6237\u7AEF=${n}, \u670D\u52A1\u5668\u54CD\u5E94=${o}`),{jsonrpc:"2.0",result:{serverInfo:{name:"xiaozhi-mcp-server",version:"1.0.0"},capabilities:{tools:{},logging:{}},protocolVersion:o},id:t!==void 0?t:1}}async handleInitializedNotification(e){return this.logger.info("\u6536\u5230 initialized \u901A\u77E5\uFF0C\u5BA2\u6237\u7AEF\u521D\u59CB\u5316\u5B8C\u6210",e),null}async handleToolsList(e){this.logger.info("\u5904\u7406 tools/list \u8BF7\u6C42");try{let r=this.serviceManager.getAllTools().map(n=>({name:n.name,description:n.description,inputSchema:n.inputSchema}));return this.logger.info(`\u8FD4\u56DE ${r.length} \u4E2A\u5DE5\u5177`),{jsonrpc:"2.0",result:{tools:r},id:e!==void 0?e:1}}catch(t){throw this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25",t),t}}async handleToolCall(e,t){this.logger.info(`\u5904\u7406 tools/call \u8BF7\u6C42: ${e.name}`,e);try{if(!e.name)throw new Error("\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");let r=await this.serviceManager.callTool(e.name,e.arguments||{});return this.logger.info(`\u5DE5\u5177 ${e.name} \u8C03\u7528\u6210\u529F`),{jsonrpc:"2.0",result:{content:r.content,isError:r.isError||!1},id:t!==void 0?t:1}}catch(r){throw this.logger.error(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,r),r}}async handlePing(e){return this.logger.debug("\u5904\u7406 ping \u8BF7\u6C42"),{jsonrpc:"2.0",result:{status:"ok",timestamp:new Date().toISOString()},id:e!==void 0?e:1}}async handleResourcesList(e){this.logger.info("\u5904\u7406 resources/list \u8BF7\u6C42");let t=[];return this.logger.info(`\u8FD4\u56DE ${t.length} \u4E2A\u8D44\u6E90`),{jsonrpc:"2.0",result:{resources:t},id:e!==void 0?e:1}}async handlePromptsList(e){this.logger.info("\u5904\u7406 prompts/list \u8BF7\u6C42");let t=[];return this.logger.info(`\u8FD4\u56DE ${t.length} \u4E2A\u63D0\u793A\u6A21\u677F`),{jsonrpc:"2.0",result:{prompts:t},id:e!==void 0?e:1}}createErrorResponse(e,t){let r=-32603;return e.message.includes("\u672A\u627E\u5230\u5DE5\u5177")||e.message.includes("\u672A\u77E5\u7684\u65B9\u6CD5")?r=-32601:(e.message.includes("\u53C2\u6570")||e.message.includes("\u4E0D\u80FD\u4E3A\u7A7A"))&&(r=-32602),{jsonrpc:"2.0",error:{code:r,message:e.message,data:{stack:e.stack}},id:t!==void 0?t:1}}getServiceManager(){return this.serviceManager}}});import{EventEmitter as jr}from"events";var Wt,Bt,ot,zr=d(()=>{"use strict";y();Lt();je();Ut();Wt=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}},Bt=class extends jr{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 n={id:e,transportName:t,state:r,connectedAt:new Date,lastActivity:new Date};this.connections.set(e,n),this.emit("connectionRegistered",n),this.logger.debug(`\u8FDE\u63A5\u5DF2\u6CE8\u518C: ${e} (${t})`)}updateConnectionState(e,t){let r=this.connections.get(e);r&&(r.state=t,r.lastActivity=new Date,this.emit("connectionStateChanged",r),this.logger.debug(`\u8FDE\u63A5\u72B6\u6001\u66F4\u65B0: ${e} -> ${t}`))}removeConnection(e){let t=this.connections.get(e);t&&(this.connections.delete(e),this.emit("connectionRemoved",t),this.logger.debug(`\u8FDE\u63A5\u5DF2\u79FB\u9664: ${e}`))}getAllConnections(){return Array.from(this.connections.values())}getActiveConnectionCount(){return Array.from(this.connections.values()).filter(e=>e.state==="connected").length}async closeAllConnections(){this.logger.info("\u5173\u95ED\u6240\u6709\u8FDE\u63A5"),this.connections.clear(),this.emit("allConnectionsClosed")}},ot=class extends jr{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 Le,this.messageHandler=new Pe(this.serviceManager),this.toolRegistry=new Wt(this.serviceManager),this.connectionManager=new Bt,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 _r(i={name:"http"}){g.info("\u521B\u5EFA HTTP \u6A21\u5F0F\u670D\u52A1\u5668");let e=new ot;await e.initialize();let t=e.getMessageHandler(),r=new et(t,i);return await e.registerTransport("http",r),g.info("HTTP \u6A21\u5F0F\u670D\u52A1\u5668\u521B\u5EFA\u6210\u529F"),e}var Fr=d(()=>{"use strict";y();Tr();Rr();Ir();zr();c(_r,"createHTTPServer")});var Lr={};F(Lr,{MCPServer:()=>Vt});import{EventEmitter as ho}from"events";var A,Vt,Ur=d(()=>{"use strict";y();Ye();K();Fr();A=new Oe,Vt=class extends ho{static{c(this,"MCPServer")}unifiedServer=null;proxyMCPServer=null;port;isStarted=!1;constructor(e=3e3){super(),this.port=e}async initializeUnifiedServer(){if(!this.unifiedServer){A.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 _r(e),this.unifiedServer.on("started",()=>this.emit("started")),this.unifiedServer.on("stopped",()=>this.emit("stopped")),this.unifiedServer.on("connectionRegistered",t=>{this.emit("connectionRegistered",t)}),A.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw A.error("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u5931\u8D25",e),e}}}async initializeMCPClient(){try{let e=null;try{m.configExists()&&(e=m.getMcpEndpoints().find(r=>r&&!r.includes("<\u8BF7\u586B\u5199"))||null)}catch(t){A.warn("\u4ECE\u914D\u7F6E\u4E2D\u8BFB\u53D6\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25:",t)}e?(this.proxyMCPServer=new le(e),this.unifiedServer&&this.proxyMCPServer.setServiceManager(this.unifiedServer.getServiceManager()),await this.proxyMCPServer.connect(),A.info("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F")):A.info("\u672A\u914D\u7F6E\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u8DF3\u8FC7\u8FDE\u63A5")}catch(e){A.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}}async start(){if(this.isStarted){A.warn("\u670D\u52A1\u5668\u5DF2\u542F\u52A8");return}try{A.info("\u542F\u52A8 MCP \u670D\u52A1\u5668"),await this.initializeUnifiedServer(),this.unifiedServer&&await this.unifiedServer.start(),this.initializeMCPClient().catch(e=>{A.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}),this.isStarted=!0,this.emit("started"),A.info("MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F")}catch(e){throw A.error("\u542F\u52A8 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}async stop(){if(!this.isStarted){A.warn("\u670D\u52A1\u5668\u672A\u542F\u52A8");return}try{A.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"),A.info("MCP \u670D\u52A1\u5668\u5DF2\u505C\u6B62")}catch(e){throw A.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 po,resolve as uo}from"path";function Wr(i,e){it.debug(`\u8F6C\u6362\u914D\u7F6E: ${i}`,e);try{if(!i||typeof i!="string")throw new H("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!e||typeof e!="object")throw new H("\u914D\u7F6E\u5BF9\u8C61\u4E0D\u80FD\u4E3A\u7A7A",i);let t=mo(i,e);return Po(t),it.info(`\u914D\u7F6E\u8F6C\u6362\u6210\u529F: ${i} -> ${t.type}`),t}catch(t){throw it.error(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${i}`,t),t instanceof H?t:new H(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,i)}}function mo(i,e){if(yo(e))return fo(i,e);if(Eo(e))return Co(i,e);if(Mo(e))return vo(i,e);throw new H("\u65E0\u6CD5\u8BC6\u522B\u7684\u914D\u7F6E\u7C7B\u578B",i)}function fo(i,e){if(!e.command)throw new H("\u672C\u5730\u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5",i);let t=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),r=(e.args||[]).map(n=>{if(So(n)){let o=uo(t,n);return it.debug(`\u89E3\u6790\u76F8\u5BF9\u8DEF\u5F84: ${n} -> ${o}`),o}return n});return{name:i,type:"stdio",command:e.command,args:r,env:e.env,reconnect:{enabled:!0,maxAttempts:5,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:1e4,jitter:!0},ping:{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3},timeout:3e4}}function Co(i,e){if(!e.url)throw new H("SSE \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);let t=wo(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 vo(i,e){if(!e.url)throw new H("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 So(i){return po(i)?!1:!!(i.startsWith("./")||i.startsWith("../")||/\.(js|py|ts|mjs|cjs)$/i.test(i))}function yo(i){return"command"in i&&typeof i.command=="string"}function Eo(i){return"type"in i&&i.type==="sse"&&"url"in i}function Mo(i){return"url"in i&&(!("type"in i)||i.type==="streamable-http")}function wo(i){return i.includes("modelscope.net")||i.includes("modelscope.cn")}function Po(i){if(!i.name||typeof i.name!="string")throw new H("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(!Object.values(Fe).includes(i.type))throw new H(`\u65E0\u6548\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`);switch(i.type){case"stdio":if(!i.command)throw new H("STDIO \u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5");break;case"sse":case"modelscope-sse":case"streamable-http":if(!i.url)throw new H(`${i.type} \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5`);break;default:throw new H(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}var it,H,Br=d(()=>{"use strict";y();rt();it=g.withTag("ConfigAdapter"),H=class extends Error{constructor(t,r){super(t);this.configName=r;this.name="ConfigValidationError"}static{c(this,"ConfigValidationError")}};c(Wr,"convertLegacyToNew");c(mo,"convertByConfigType");c(fo,"convertLocalConfig");c(Co,"convertSSEConfig");c(vo,"convertStreamableHTTPConfig");c(So,"isRelativePath");c(yo,"isLocalConfig");c(Eo,"isSSEConfig");c(Mo,"isStreamableHTTPConfig");c(wo,"isModelScopeURL");c(Po,"validateNewConfig")});async function bo(){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),new kr}async function Vr(){if(te&&j==="initialized")return te;if(X&&j==="initializing")return X;j==="failed"&&Gt(),j="initializing",X=bo();try{return te=await X,j="initialized",be=`mcp-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,Ue=null,console.log(`\u2705 MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${be}`),te}catch(i){throw j="failed",Ue=i,X=null,console.error("\u274C MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",i.message),i}}async function Gr(){if(j==="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..."),j="cleanup";try{if(X){try{await(await X).stopAllServices()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}X=null}te&&(await te.stopAllServices(),te=null),j="not_initialized",Ue=null,be=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),Gt(),i}}function Gt(){console.log("\u{1F504} \u91CD\u7F6E MCPServiceManager \u5355\u4F8B\u72B6\u6001"),te=null,X=null,j="not_initialized",Ue=null,be=null}function To(){return j==="initialized"&&te!==null}function Ro(){return{state:j,initializationTime:be?new Date:void 0,lastError:Ue||void 0,instanceId:be||void 0}}async function Io(){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),await Gr(),Vr()}function xo(){return te}async function $o(){if(j==="initialized")return!0;if(j==="initializing"&&X)try{return await X,!0}catch{return!1}return!1}var te,X,j,Ue,be,U,st=d(()=>{"use strict";Lt();te=null,X=null,j="not_initialized",Ue=null,be=null;c(bo,"createInstance");c(Vr,"getInstance");c(Gr,"cleanup");c(Gt,"reset");c(To,"isInitialized");c(Ro,"getStatus");c(Io,"forceReinitialize");c(xo,"getCurrentInstance");c($o,"waitForInitialization");U={getInstance:Vr,cleanup:Gr,reset:Gt,isInitialized:To,getStatus:Ro,forceReinitialize:Io,getCurrentInstance:xo,waitForInitialization:$o};process.on("exit",()=>{U.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B..."),U.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 U.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 U.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as Oo}from"events";var qr,Ao,at,Xr=d(()=>{"use strict";y();Ye();qr=(n=>(n.EXPONENTIAL_BACKOFF="exponential_backoff",n.LINEAR_BACKOFF="linear_backoff",n.FIXED_INTERVAL="fixed_interval",n.ADAPTIVE="adaptive",n))(qr||{}),Ao={healthCheckInterval:3e4,reconnectInterval:5e3,maxReconnectAttempts:10,loadBalanceStrategy:"round-robin",connectionTimeout:1e4,reconnectStrategy:"exponential_backoff",maxReconnectDelay:3e4,reconnectBackoffMultiplier:2,jitterEnabled:!0},at=class extends Oo{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={...Ao,...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,n=t.length-r,o=Date.now()-this.performanceMetrics.connectionStartTime;if(this.performanceMetrics.totalConnectionTime+=o,this.performanceMetrics.connectionCount++,this.performanceMetrics.averageConnectionTime=this.performanceMetrics.totalConnectionTime/this.performanceMetrics.connectionCount,this.logger.info(`\u8FDE\u63A5\u5B8C\u6210 - \u6210\u529F: ${r}, \u5931\u8D25: ${n}, \u8017\u65F6: ${o}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 n=this.connectionStates.get(t);n?.connected&&n.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 n=r.totalRequests>0?r.successfulRequests/r.totalRequests*100:0;e[t]={endpoint:t,healthScore:r.healthScore,successRate:Math.round(n*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 n of e){if(!n||typeof n!="string"){r.push(n);continue}if(!n.startsWith("ws://")&&!n.startsWith("wss://")){r.push(n);continue}try{new URL(n),t.push(n)}catch{r.push(n)}}return{valid:t,invalid:r}}validateOptions(e){let t=[];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(qr);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:n}=this.validateEndpoints(e);if(n.length>0&&this.logger.warn(`\u53D1\u73B0\u65E0\u6548\u7AEF\u70B9: ${n.join(", ")}`),r.length===0)throw new Error("\u6CA1\u6709\u6709\u6548\u7684\u7AEF\u70B9");let o=Array.from(this.connections.keys()),s=r.filter(h=>!o.includes(h)),a=o.filter(h=>!r.includes(h)),l=o.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 n={...this.options};this.options={...this.options,...e};let o={type:"options_updated",data:{oldOptions:n,newOptions:e},timestamp:new Date};this.emit("configChange",o),this.logger.info("\u8FDE\u63A5\u9009\u9879\u66F4\u65B0\u5B8C\u6210"),this.logger.debug("\u65B0\u7684\u914D\u7F6E\u9009\u9879:",this.options)}getCurrentConfig(){return{endpoints:Array.from(this.connections.keys()),options:{...this.options}}}async reloadConfig(e){this.logger.info("\u5F00\u59CB\u70ED\u91CD\u8F7D\u914D\u7F6E");try{e.options&&this.updateOptions(e.options),e.endpoints&&await this.updateEndpoints(e.endpoints,e.tools||[]),this.logger.info("\u914D\u7F6E\u70ED\u91CD\u8F7D\u5B8C\u6210")}catch(t){throw this.logger.error("\u914D\u7F6E\u70ED\u91CD\u8F7D\u5931\u8D25:",t),t}}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(o=>{let s=this.getEndpointByConnection(o);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 n;switch(this.options.loadBalanceStrategy){case"round-robin":n=this.selectRoundRobin(r);break;case"random":n=this.selectRandom(r);break;case"health-based":n=this.selectHealthBased(r);break;default:n=this.selectRoundRobin(r)}return this.lastSelectedEndpoint=this.getEndpointByConnection(n),n}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(o=>{let s=this.getEndpointByConnection(o),a=s?this.connectionStates.get(s):null;return{connection:o,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((o,s)=>o.healthScore!==s.healthScore?s.healthScore-o.healthScore:o.successRate!==s.successRate?s.successRate-o.successRate:o.responseTime-s.responseTime);let r=t.reduce((o,s)=>o+(s.healthScore+1),0),n=Math.random()*r;for(let o of t)if(n-=o.healthScore+1,n<=0)return o.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,n]of this.connectionStates){let o=n.totalRequests>0?n.successfulRequests/n.totalRequests*100:0,s=n.healthScore+1;t[r]={healthScore:n.healthScore,responseTime:n.responseTime||0,successRate:Math.round(o*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 n=>{if(this.performanceMetrics.prewarmedConnections.has(n)){this.logger.debug(`\u7AEF\u70B9 ${n} \u5DF2\u9884\u70ED\uFF0C\u8DF3\u8FC7`);return}try{this.connections.get(n)&&(await this.performHealthCheck(),this.performanceMetrics.prewarmedConnections.add(n),this.logger.debug(`\u7AEF\u70B9 ${n} \u9884\u70ED\u5B8C\u6210`))}catch(o){this.logger.warn(`\u7AEF\u70B9 ${n} \u9884\u70ED\u5931\u8D25:`,o)}});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 le(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(n){throw r.connected=!1,r.initialized=!1,r.lastError=n instanceof Error?n.message:String(n),r.reconnectAttempts++,r.healthScore=Math.max(0,r.healthScore-20),this.logger.error(`\u7AEF\u70B9\u8FDE\u63A5\u5931\u8D25 ${e}:`,n),this.scheduleReconnect(e),n}}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(n){this.logger.error(`\u7AEF\u70B9\u65AD\u5F00\u5931\u8D25 ${e}:`,n),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 n=this.connections.get(e);if(!n)throw new Error(`\u8FDE\u63A5\u5B9E\u4F8B\u4E0D\u5B58\u5728: ${e}`);await this.checkConnectionHealth(n,e);let o=Date.now()-r;this.handleHealthCheckSuccess(t,o)}catch(n){let o=Date.now()-r;this.handleHealthCheckFailure(t,n,o)}}async checkConnectionHealth(e,t){if(!e)throw new Error("\u8FDE\u63A5\u5B9E\u4F8B\u4E0D\u5B58\u5728");if(await new Promise(n=>setTimeout(n,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 n=e.healthScore;if(t){let o=5;r<100?o=10:r<500?o=7:r<1e3?o=5:o=2,e.healthScore=Math.min(100,n+o)}else{let o=15;e.consecutiveFailures>=5?o=30:e.consecutiveFailures>=3&&(o=20),e.healthScore=Math.max(0,n-o)}if(e.totalRequests>0){let o=e.successfulRequests/e.totalRequests;o<.5?e.healthScore=Math.max(0,e.healthScore-10):o>.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,n=this.options.reconnectBackoffMultiplier,o=e.reconnectAttempts,s;switch(this.options.reconnectStrategy){case"fixed_interval":s=t;break;case"linear_backoff":s=t*(o+1);break;case"exponential_backoff":s=t*n**o;break;case"adaptive":s=this.calculateAdaptiveDelay(e,t,n,o);break;default:s=t*n**o}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,n){let o=t;switch(e.errorType){case"network_error":o=t*r**n;break;case"authentication_error":o=t*r**n*2;break;case"server_error":o=t*(1+n);break;case"timeout_error":o=t*(1+n*.5);break;default:o=t*r**n}if(e.reconnectHistory.length>0){let s=e.reconnectHistory.slice(-5),a=s.filter(l=>l.success).length/s.length;a<.2?o*=1.5:a>.8&&(o*=.8)}return o}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 n=this.calculateReconnectDelay(t);t.reconnectDelay=n,t.isReconnecting=!0,t.nextReconnectTime=new Date(Date.now()+n),this.logger.info(`\u5B89\u6392\u91CD\u8FDE ${e}\uFF0C\u5EF6\u8FDF: ${n}ms\uFF0C\u5C1D\u8BD5\u6B21\u6570: ${t.reconnectAttempts+1}\uFF0C\u9519\u8BEF\u7C7B\u578B: ${t.errorType}`);let o=setTimeout(async()=>{this.reconnectTimers.delete(e),await this.performReconnect(e)},n);this.reconnectTimers.set(e,o)}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(n){t.isReconnecting=!1,t.reconnectHistory.push({timestamp:new Date,success:!1,error:n instanceof Error?n.message:String(n),delay:t.reconnectDelay}),this.logger.error(`\u91CD\u8FDE\u5931\u8D25 ${e}:`,n),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 Do(i){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 XiaozhiConnectionManager \u5355\u4F8B..."),new at(i)}async function Jr(i){if(re&&z==="initialized")return re;if(G&&z==="initializing")return G;z==="failed"&&qt(),z="initializing",G=Do(i);try{return re=await G,z="initialized",Te=`xiaozhi-connection-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,We=null,console.log(`\u2705 XiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${Te}`),re}catch(e){throw z="failed",We=e,G=null,console.error("\u274C XiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",e.message),e}}async function Kr(){if(z==="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..."),z="cleanup";try{if(G){try{await(await G).cleanup()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}G=null}re&&(await re.cleanup(),re=null),z="not_initialized",We=null,Te=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),qt(),i}}function qt(){console.log("\u{1F504} \u91CD\u7F6E XiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001..."),G&&(G=null),re=null,z="not_initialized",We=null,Te=null,console.log("\u2705 XiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001\u5DF2\u91CD\u7F6E")}function No(){return z==="initialized"&&re!==null}function Ho(){return{state:z,initializationTime:Te?new Date:void 0,lastError:We||void 0,instanceId:Te||void 0}}async function ko(i){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 XiaozhiConnectionManager \u5355\u4F8B..."),await Kr(),Jr(i)}function jo(){return re}async function zo(){if(z==="initialized")return!0;if(z==="initializing"&&G)try{return await G,!0}catch{return!1}return!1}var re,G,z,We,Te,Re,Zr=d(()=>{"use strict";Xr();re=null,G=null,z="not_initialized",We=null,Te=null;c(Do,"createInstance");c(Jr,"getInstance");c(Kr,"cleanup");c(qt,"reset");c(No,"isInitialized");c(Ho,"getStatus");c(ko,"forceReinitialize");c(jo,"getCurrentInstance");c(zo,"waitForInitialization");Re={getInstance:Jr,cleanup:Kr,reset:qt,isInitialized:No,getStatus:Ho,forceReinitialize:ko,getCurrentInstance:jo,waitForInitialization:zo};process.on("exit",()=>{Re.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B..."),Re.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 Re.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 Re.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as _o}from"events";function q(){return Ie||(Ie=new Xt),Ie}function Qr(){Ie&&(Ie.destroy(),Ie=null)}var Xt,Ie,ue=d(()=>{"use strict";y();Xt=class extends _o{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")}},Ie=null;c(q,"getEventBus");c(Qr,"destroyEventBus")});var ne,Be=d(()=>{"use strict";y();K();ue();ne=class{static{c(this,"ConfigService")}logger;eventBus;constructor(){this.logger=g.withTag("ConfigService"),this.eventBus=q()}async getConfig(){try{let e=m.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!==m.getMcpEndpoint()&&m.updateMcpEndpoint(e.mcpEndpoint);let r=m.getMcpServers();for(let[n,o]of Object.entries(e.mcpServers))JSON.stringify(r[n])!==JSON.stringify(o)&&m.updateMcpServer(n,o);for(let n of Object.keys(r))n in e.mcpServers||(m.removeMcpServer(n),m.removeServerToolsConfig(n));if(e.connection&&m.updateConnectionConfig(e.connection),e.modelscope&&m.updateModelScopeConfig(e.modelscope),e.webUI&&m.updateWebUIConfig(e.webUI),e.mcpServerConfig)for(let[n,o]of Object.entries(e.mcpServerConfig))for(let[s,a]of Object.entries(o.tools))m.setToolEnabled(n,s,a.enable);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 m.getMcpEndpoint()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",e),e}}getMcpEndpoints(){try{return m.getMcpEndpoints()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",e),e}}getMcpServers(){try{return m.getMcpServers()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",e),e}}getConnectionConfig(){try{return m.getConnectionConfig()}catch(e){throw this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",e),e}}getWebUIPort(){try{return m.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 m.configExists()}async reloadConfig(){try{this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E"),m.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 m.getConfigPath()}}});var ct,Yr=d(()=>{"use strict";y();Be();ct=class{static{c(this,"ConfigApiHandler")}logger;configService;constructor(){this.logger=g.withTag("ConfigApiHandler"),this.configService=new ne}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)}}}});var lt,en=d(()=>{"use strict";y();Be();lt=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 ne}async handleClientStatus(e,t,r){try{this.logger.debug(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0: ${r}`,t.data);let n={...t.data,lastHeartbeat:Date.now()};this.statusService.updateClientInfo(n,`websocket-${r}`),await this.sendLatestConfig(e,r),this.logger.debug(`\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u6210\u529F: ${r}`)}catch(n){this.logger.error(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25: ${r}`,n),this.sendError(e,"CLIENT_STATUS_ERROR",n instanceof Error?n.message:"\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25")}}async sendLatestConfig(e,t){try{let n={type:"configUpdate",data:await this.configService.getConfig(),timestamp:Date.now()};e.send(JSON.stringify(n)),this.logger.debug(`\u6700\u65B0\u914D\u7F6E\u5DF2\u53D1\u9001\u7ED9\u5BA2\u6237\u7AEF: ${t}`)}catch(r){this.logger.error(`\u53D1\u9001\u6700\u65B0\u914D\u7F6E\u5931\u8D25: ${t}`,r)}}sendError(e,t,r){try{let n={type:"error",error:{code:t,message:r,timestamp:Date.now()}};e.send(JSON.stringify(n))}catch(n){this.logger.error("\u53D1\u9001\u9519\u8BEF\u6D88\u606F\u5931\u8D25:",n)}}checkHeartbeatTimeout(){let e=this.statusService.getLastHeartbeat(),t=Date.now();e&&t-e>35e3&&(this.logger.warn("\u5BA2\u6237\u7AEF\u5FC3\u8DF3\u8D85\u65F6\uFF0C\u6807\u8BB0\u4E3A\u65AD\u5F00\u8FDE\u63A5"),this.statusService.updateClientInfo({status:"disconnected"},"heartbeat-timeout"))}startHeartbeatMonitoring(){return this.logger.info("\u542F\u52A8\u5FC3\u8DF3\u76D1\u63A7"),setInterval(()=>{this.checkHeartbeatTimeout(),this.cleanupDisconnectedClients()},1e4)}cleanupDisconnectedClients(){try{this.notificationService.cleanupDisconnectedClients()}catch(e){this.logger.error("\u6E05\u7406\u65AD\u5F00\u8FDE\u63A5\u7684\u5BA2\u6237\u7AEF\u5931\u8D25:",e)}}stopHeartbeatMonitoring(e){this.logger.info("\u505C\u6B62\u5FC3\u8DF3\u76D1\u63A7"),clearInterval(e)}getHeartbeatStats(){return{lastHeartbeat:this.statusService.getLastHeartbeat(),isConnected:this.statusService.isClientConnected(),clientStats:this.notificationService.getClientStats()}}handleClientConnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5EFA\u7ACB: ${e}`),this.statusService.updateClientInfo({status:"connected",lastHeartbeat:Date.now()},`websocket-connect-${e}`)}handleClientDisconnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u65AD\u5F00: ${e}`),this.statusService.updateClientInfo({status:"disconnected"},`websocket-disconnect-${e}`)}sendHeartbeatResponse(e,t){try{let r={type:"heartbeatResponse",data:{timestamp:Date.now(),status:"ok"}};e.send(JSON.stringify(r)),this.logger.debug(`\u5FC3\u8DF3\u54CD\u5E94\u5DF2\u53D1\u9001: ${t}`)}catch(r){this.logger.error(`\u53D1\u9001\u5FC3\u8DF3\u54CD\u5E94\u5931\u8D25: ${t}`,r)}}validateHeartbeatMessage(e){return e&&typeof e=="object"&&e.type==="clientStatus"&&e.data&&typeof e.data=="object"}}});import{randomUUID as Fo}from"crypto";var gt,tn=d(()=>{"use strict";y();Ut();st();gt=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,n]of this.clients.entries())(e.getTime()-n.lastActivity.getTime()>this.config.connectionTimeout||!n.isAlive)&&t.push(r);for(let r of t)this.logger.info(`\u6E05\u7406\u8FC7\u671F\u8FDE\u63A5: ${r}`),this.handleClientDisconnect(r,"cleanup");t.length>0&&this.logger.info(`\u6E05\u7406\u4E86 ${t.length} \u4E2A\u8FC7\u671F\u8FDE\u63A5`)}updateMetrics(){this.config.enableMetrics&&(this.metrics.activeConnections=this.clients.size,this.metrics.uptime=Date.now()-this.startTime.getTime(),this.logger.debug("\u8FDE\u63A5\u7EDF\u8BA1",{activeConnections:this.metrics.activeConnections,totalConnections:this.metrics.totalConnections,totalMessages:this.metrics.totalMessages,errorCount:this.metrics.errorCount}))}async initializeMessageHandler(){if(!this.mcpMessageHandler)try{let e=await U.getInstance();this.mcpMessageHandler=new Pe(e),this.logger.info("MCP \u6D88\u606F\u5904\u7406\u5668\u521D\u59CB\u5316\u6210\u529F")}catch(e){throw this.logger.error("MCP \u6D88\u606F\u5904\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",e),this.metrics.errorCount++,e}}async handlePost(e){let t=Date.now(),r=null;try{this.logger.debug("\u5904\u7406 MCP POST \u8BF7\u6C42");let n=e.req.query("sessionId");if(n)return await this.handleSSEMessage(e,n);let o=e.req.header("content-length");if(o&&Number.parseInt(o)>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Request too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);if(!e.req.header("content-type")?.includes("application/json"))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Content-Type must be application/json",null);let a=e.req.header("mcp-protocol-version")||e.req.header("MCP-Protocol-Version")||e.req.header("Mcp-Protocol-Version"),l=["2024-11-05","2025-06-18"];a&&!l.includes(a)&&this.logger.warn(`\u4E0D\u652F\u6301\u7684 MCP \u534F\u8BAE\u7248\u672C: ${a}\uFF0C\u652F\u6301\u7684\u7248\u672C: ${l.join(", ")}`);let h;try{let S=await e.req.text();if(S.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(S),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(n){this.metrics.errorCount++;let o=Date.now()-t;this.logger.error("\u5904\u7406 MCP POST \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:n instanceof Error?n.message:String(n),messageId:r,responseTime:o,stack:n instanceof Error?n.stack:void 0});let s=n instanceof Error?n.message:String(n);return this.createErrorResponse(-32603,`Internal error: ${s}`,r)}}async handleSSEMessage(e,t){let r=Date.now(),n=null;try{this.logger.debug(`\u5904\u7406 SSE \u6D88\u606F (\u4F1A\u8BDD: ${t})`);let o=this.clients.get(t);if(!o)return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Invalid or missing sessionId",null);o.lastActivity=new Date;let s=e.req.header("content-length");if(s&&Number.parseInt(s)>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);let a;try{let u=await e.req.text();if(u.length>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);a=JSON.parse(u),n=a.id||null}catch{return this.metrics.errorCount++,this.createErrorResponse(-32700,"Parse error: Invalid JSON",null)}if(!this.validateMessage(a))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Message does not conform to JSON-RPC 2.0",n);await this.initializeMessageHandler();let l=await this.mcpMessageHandler.handleMessage(a);if(o.messageCount++,this.metrics.totalMessages++,l!==null&&o.writer&&o.isAlive)try{await this.sendSSEEvent(o.writer,"message",JSON.stringify(l))}catch(u){this.logger.warn(`SSE \u5199\u5165\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${t}`,u),o.isAlive=!1}let h=Date.now()-r;return this.logger.debug(`SSE \u6D88\u606F\u5904\u7406\u5B8C\u6210 (\u4F1A\u8BDD: ${t})`,{method:a.method,messageId:n,responseTime:h,messageCount:o.messageCount,isNotification:l===null}),new Response(null,{status:202,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":h.toString()}})}catch(o){this.metrics.errorCount++;let s=Date.now()-r;this.logger.error(`\u5904\u7406 SSE \u6D88\u606F\u65F6\u51FA\u9519 (\u4F1A\u8BDD: ${t}):`,{error:o instanceof Error?o.message:String(o),messageId:n,responseTime:s,stack:o instanceof Error?o.stack:void 0});let a=o instanceof Error?o.message:String(o);return this.createErrorResponse(-32603,`Internal error: ${a}`,n)}}async handleGet(e){try{if(this.logger.debug("\u5904\u7406 MCP GET \u8BF7\u6C42\uFF08SSE \u8FDE\u63A5\uFF09"),this.clients.size>=this.config.maxClients)return this.metrics.errorCount++,e.json({jsonrpc:"2.0",error:{code:-32e3,message:"Server busy: Maximum client connections reached",data:{maxClients:this.config.maxClients}},id:null},503);let t=Date.now().toString(),r=Fo(),n=new Date,o=e.req.header("user-agent"),s=e.req.header("x-forwarded-for")||e.req.header("x-real-ip")||"unknown";this.logger.info(`SSE \u5BA2\u6237\u7AEF\u8FDE\u63A5: ${t} (\u4F1A\u8BDD: ${r})`,{userAgent:o,remoteAddress:s});let{readable:a,writable:l}=new TransformStream,h=l.getWriter(),u=new AbortController,p={id:t,sessionId:r,response:new Response(a),connectedAt:n,lastActivity:n,writer:h,abortController:u,isAlive:!0,messageCount:0,userAgent:o,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:n.toISOString(),protocolVersion:"2024-11-05"}))}catch($){this.logger.error(`\u521D\u59CB SSE \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25: ${r}`,$),p.isAlive=!1}this.startHeartbeat(p);let S=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"}}),R=c(()=>{this.handleClientDisconnect(r,t)},"handleDisconnect");return e.req.raw.signal?.addEventListener("abort",R),u.signal.addEventListener("abort",R),S}catch(t){return this.metrics.errorCount++,this.logger.error("\u5904\u7406 MCP GET \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),e.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"},id:null},500)}}startHeartbeat(e){e.heartbeatInterval&&clearInterval(e.heartbeatInterval),e.heartbeatInterval=setInterval(async()=>{if(!e.isAlive||!e.writer){this.stopHeartbeat(e);return}try{await this.sendSSEEvent(e.writer,"heartbeat",JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId})),this.logger.debug(`\u5FC3\u8DF3\u53D1\u9001\u6210\u529F: ${e.sessionId}`)}catch(t){this.logger.warn(`\u5FC3\u8DF3\u53D1\u9001\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${e.sessionId}`,t),e.isAlive=!1,this.stopHeartbeat(e)}},this.config.heartbeatInterval)}stopHeartbeat(e){e.heartbeatInterval&&(clearInterval(e.heartbeatInterval),e.heartbeatInterval=void 0)}async sendSSEEvent(e,t,r){try{let n=`event: ${t}
|
|
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...
|
|
16
|
+
|
|
17
|
+
\u{1F4CB} \u4EFB\u52A1\u4FE1\u606F\uFF1A
|
|
18
|
+
- \u4EFB\u52A1ID: ${e}
|
|
19
|
+
- \u5DE5\u5177\u7C7B\u578B: \u6263\u5B50\u5DE5\u4F5C\u6D41
|
|
20
|
+
- \u72B6\u6001: \u5904\u7406\u4E2D
|
|
21
|
+
- \u5EFA\u8BAE: \u8BF7\u7B49\u5F8530-60\u79D2\u540E\u91CD\u8BD5\u67E5\u8BE2
|
|
22
|
+
|
|
23
|
+
\u{1F504} \u540E\u7EED\u64CD\u4F5C\uFF1A
|
|
24
|
+
1. \u4F7F\u7528\u76F8\u540C\u53C2\u6570\u91CD\u65B0\u8C03\u7528\u5DE5\u5177
|
|
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...
|
|
27
|
+
|
|
28
|
+
\u{1F4CB} \u4EFB\u52A1\u4FE1\u606F\uFF1A
|
|
29
|
+
- \u4EFB\u52A1ID: ${i}
|
|
30
|
+
- \u72B6\u6001: \u5904\u7406\u4E2D
|
|
31
|
+
- \u5EFA\u8BAE: \u8BF7\u7B49\u5F8530\u79D2\u540E\u91CD\u8BD5\u67E5\u8BE2
|
|
32
|
+
|
|
33
|
+
\u{1F504} \u540E\u7EED\u64CD\u4F5C\uFF1A
|
|
34
|
+
1. \u4F7F\u7528\u76F8\u540C\u7684\u53C2\u6570\u91CD\u65B0\u8C03\u7528\u5DE5\u5177
|
|
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}if(this.configManager.getCustomMCPConfig()){this.logger.debug("\u5DF2\u5B58\u5728 customMCP \u505C\u6B62\u540C\u6B65");return}let r=this.doSyncTools(e,t).finally(()=>{this.syncLocks.delete(e)});this.syncLocks.set(e,r),await r}async doSyncTools(e,t){try{this.logger.info(`\u5F00\u59CB\u540C\u6B65\u670D\u52A1 ${e} \u7684\u5DE5\u5177`);let r=this.configManager.getServerToolsConfig(e);if(!r){this.logger.debug(`\u670D\u52A1 ${e} \u65E0 mcpServerConfig \u914D\u7F6E\uFF0C\u8DF3\u8FC7\u540C\u6B65`);return}let o=this.getEnabledTools(r,t);if(o.length===0){this.logger.debug(`\u670D\u52A1 ${e} \u65E0\u542F\u7528\u5DE5\u5177\uFF0C\u8DF3\u8FC7\u540C\u6B65`);return}let n=this.configManager.getCustomMCPTools(),s=new Set(n.map(l=>l.name)),a=o.filter(l=>!s.has(`${e}__${l.name}`));if(a.length===0){this.logger.info(`\u670D\u52A1 ${e} \u7684\u542F\u7528\u5DE5\u5177\u5DF2\u5B58\u5728\u4E8E customMCP \u4E2D\uFF0C\u8DF3\u8FC7\u540C\u6B65`);return}await this.addToolsToCustomMCP(e,a),this.logger.info(`\u6210\u529F\u540C\u6B65\u670D\u52A1 ${e} \u7684 ${a.length} \u4E2A\u5DE5\u5177\u5230 customMCP`)}catch(r){this.logger.error(`\u540C\u6B65\u670D\u52A1 ${e} \u5DE5\u5177\u5931\u8D25:`,r),this.recordSyncError(e,r)}}getEnabledTools(e,t){let r=[];for(let o of t){let n=e[o.name];n&&n.enable!==!1&&r.push(o)}return r}async addToolsToCustomMCP(e,t){let r=t.map(o=>({name:`${e}__${o.name}`,description:o.description||"",inputSchema:o.inputSchema||{},handler:{type:"mcp",config:{serviceName:e,toolName:o.name}}}));await this.configManager.addCustomMCPTools(r),await this.syncToolStats(e,t)}recordSyncError(e,t){let r={serviceName:e,error:t instanceof Error?t.message:String(t),timestamp:new Date().toISOString(),type:t instanceof Error?t.constructor.name:"UnknownError"};this.logger.error("\u540C\u6B65\u9519\u8BEF\u8BB0\u5F55:",r)}getSyncLocks(){return Array.from(this.syncLocks.keys())}clearSyncLocks(){this.syncLocks.clear(),this.logger.debug("\u5DF2\u6E05\u7406\u6240\u6709\u540C\u6B65\u9501")}async syncToolStats(e,t){try{let r=this.configManager.getServerToolsConfig(e);if(!r){this.logger.debug(`\u670D\u52A1 ${e} \u65E0 mcpServerConfig \u914D\u7F6E\uFF0C\u8DF3\u8FC7\u7EDF\u8BA1\u4FE1\u606F\u540C\u6B65`);return}let o=this.configManager.getCustomMCPTools(),n=new Map(o.map(s=>[s.name,s]));for(let s of t){let a=`${e}__${s.name}`,l=n.get(a),h=r[s.name];if(l&&h&&(!l.stats||!l.stats.usageCount&&!l.stats.lastUsedTime)){let u={};h.usageCount!==void 0&&(u.usageCount=h.usageCount),h.lastUsedTime&&(u.lastUsedTime=h.lastUsedTime),Object.keys(u).length>0&&(await this.updateCustomMCPToolStats(a,u),this.logger.debug(`\u5DF2\u540C\u6B65\u5DE5\u5177 ${a} \u7684\u7EDF\u8BA1\u4FE1\u606F: ${JSON.stringify(u)}`))}}}catch(r){this.logger.error(`\u540C\u6B65\u670D\u52A1 ${e} \u5DE5\u5177\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,r instanceof Error?r.message:String(r))}}async updateCustomMCPToolStats(e,t){try{let r=this.configManager.getCustomMCPTools(),o=r.findIndex(a=>a.name===e);if(o===-1){this.logger.warn(`\u5DE5\u5177 ${e} \u4E0D\u5B58\u5728\u4E8E customMCP \u4E2D`);return}let n=[...r],s=n[o];s.stats||(s.stats={}),t.usageCount!==void 0&&(s.stats.usageCount=t.usageCount),t.lastUsedTime!==void 0&&(s.stats.lastUsedTime=t.lastUsedTime),await this.configManager.updateCustomMCPTools(n)}catch(r){throw this.logger.error(`\u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,r instanceof Error?r.message:String(r)),r}}}});var Ze,go,lr=m(()=>{"use strict";S();Y();io();Ct();St();lo();Ze=class{static{c(this,"MCPServiceManager")}services=new Map;configs={};logger;tools=new Map;customMCPHandler;cacheManager;toolSyncManager;constructor(e){this.logger=g,this.configs=e||{};let r=process.env.NODE_ENV==="test"||process.env.VITEST==="true"?`/tmp/xiaozhi-test-${Date.now()}-${Math.random().toString(36).substring(2,11)}/xiaozhi.cache.json`:void 0;this.cacheManager=new ge(r),this.customMCPHandler=new vt,this.toolSyncManager=new Tt(d,this.logger)}async startAllServices(){this.logger.info("[MCPManager] \u6B63\u5728\u542F\u52A8\u6240\u6709 MCP \u670D\u52A1...");try{this.customMCPHandler.initialize(),this.logger.info("[MCPManager] CustomMCP \u5904\u7406\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(t){this.logger.error("[MCPManager] CustomMCP \u5904\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",t)}let e=Object.entries(this.configs);if(e.length===0){this.logger.warn("[MCPManager] \u6CA1\u6709\u914D\u7F6E\u4EFB\u4F55 MCP \u670D\u52A1\uFF0C\u8BF7\u4F7F\u7528 addServiceConfig() \u6DFB\u52A0\u670D\u52A1\u914D\u7F6E");return}for(let[t]of e)await this.startService(t);this.logger.info("[MCPManager] \u6240\u6709 MCP \u670D\u52A1\u542F\u52A8\u5B8C\u6210")}async startService(e){this.logger.info(`[MCPManager] \u542F\u52A8 MCP \u670D\u52A1: ${e}`);let t=this.configs[e];if(!t)throw new Error(`\u672A\u627E\u5230\u670D\u52A1\u914D\u7F6E: ${e}`);try{this.services.has(e)&&await this.stopService(e);let r=new yt(t);await r.connect(),this.services.set(e,r),await this.refreshToolsCache();let o=r.getTools();await this.toolSyncManager.syncToolsAfterConnection(e,o),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u542F\u52A8\u6210\u529F\uFF0C\u52A0\u8F7D\u4E86 ${o.length} \u4E2A\u5DE5\u5177:`,o.map(n=>n.name).join(", "))}catch(r){throw this.logger.error(`[MCPManager] \u542F\u52A8 ${e} \u670D\u52A1\u5931\u8D25:`,r.message),r}}async stopService(e){this.logger.info(`[MCPManager] \u505C\u6B62 MCP \u670D\u52A1: ${e}`);let t=this.services.get(e);if(!t){this.logger.warn(`[MCPManager] \u670D\u52A1 ${e} \u4E0D\u5B58\u5728\u6216\u672A\u542F\u52A8`);return}try{await t.disconnect(),this.services.delete(e),await this.refreshToolsCache(),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u5DF2\u505C\u6B62`)}catch(r){throw this.logger.error(`[MCPManager] \u505C\u6B62 ${e} \u670D\u52A1\u5931\u8D25:`,r.message),r}}async refreshToolsCache(){this.tools.clear();for(let[e,t]of this.services)if(t.isConnected()){let r=t.getTools(),o=this.configs[e];o&&this.cacheManager.writeCacheEntry(e,r,o).then(()=>{this.logger.debug(`[MCPManager] \u5DF2\u5C06 ${e} \u5DE5\u5177\u5217\u8868\u5199\u5165\u7F13\u5B58`)}).catch(n=>{this.logger.warn(`[MCPManager] \u5199\u5165\u7F13\u5B58\u5931\u8D25: ${e}, \u9519\u8BEF: ${n instanceof Error?n.message:String(n)}`)});for(let n of r){let s=`${e}__${n.name}`;this.tools.set(s,{serviceName:e,originalName:n.name,tool:n})}}await this.syncToolsConfigToFile()}getAllTools(){let e=[];if(d.getCustomMCPConfig()!==null){this.logger.info("[MCPManager] \u68C0\u6D4B\u5230\u65B0\u7248\u672C\u914D\u7F6E\uFF0C\u4F7F\u7528 customMCP \u5DE5\u5177\u5217\u8868");try{let r=this.customMCPHandler.getTools();for(let o of r)e.push({name:o.name,description:o.description||"",inputSchema:o.inputSchema,serviceName:this.getServiceNameForTool(o),originalName:o.name});this.logger.info(`[MCPManager] \u65B0\u7248\u672C\u914D\u7F6E\u8FD4\u56DE ${e.length} \u4E2A\u5DE5\u5177 (\u4EC5\u6765\u81EA customMCP.tools)`)}catch(r){this.logger.error("[MCPManager] \u83B7\u53D6 customMCP \u5DE5\u5177\u5931\u8D25:",r)}}else{this.logger.info("[MCPManager] \u68C0\u6D4B\u5230\u8001\u7248\u672C\u914D\u7F6E\uFF0C\u4F7F\u7528\u517C\u5BB9\u6A21\u5F0F\u5904\u7406");let r=new Set;try{let o=this.customMCPHandler.getTools();for(let n of o){let s=n.name;r.has(s)||(r.add(s),e.push({name:s,description:n.description||"",inputSchema:n.inputSchema,serviceName:"customMCP",originalName:n.name}))}o.length>0&&this.logger.info(`[MCPManager] \u6DFB\u52A0\u4E86 ${o.length} \u4E2A customMCP \u5DE5\u5177`)}catch(o){this.logger.error("[MCPManager] \u83B7\u53D6 CustomMCP \u5DE5\u5177\u5931\u8D25:",o)}for(let[o,n]of this.tools){if(r.has(o))continue;d.isToolEnabled(n.serviceName,n.originalName)&&(r.add(o),e.push({name:o,description:n.tool.description||"",inputSchema:n.tool.inputSchema,serviceName:n.serviceName,originalName:n.originalName}))}this.logger.info(`[MCPManager] \u8001\u7248\u672C\u914D\u7F6E\u8FD4\u56DE\u603B\u8BA1 ${e.length} \u4E2A\u5DE5\u5177 (customMCP \u4F18\u5148\uFF0C\u53BB\u91CD\u540E\u603B\u6570)`)}return e}getServiceNameForTool(e){return e.handler?.type==="mcp"?e.handler.config.serviceName:"customMCP"}async callTool(e,t){if(this.logger.info(`[MCPManager] \u8C03\u7528\u5DE5\u5177: ${e}\uFF0C\u53C2\u6570:`,t),this.customMCPHandler.hasTool(e)){let n=this.customMCPHandler.getToolInfo(e);if(n?.handler?.type==="mcp")try{let s=await this.callMCPTool(e,n.handler.config,t);return this.updateToolStats(e,n.handler.config.serviceName,n.handler.config.toolName,!0).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),s}catch(s){throw this.updateToolStatsForFailedCall(e,n.handler.config.serviceName,n.handler.config.toolName,s).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),s}try{let s=await this.customMCPHandler.callTool(e,t);return this.updateToolStats(e,"customMCP",e,!0).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),this.logger.info(`[MCPManager] CustomMCP \u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F`),s}catch(s){throw this.updateToolStatsForFailedCall(e,"customMCP",e,s).catch(a=>{this.logger.warn(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,a)}),this.logger.error(`[MCPManager] CustomMCP \u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,s.message),s}}let r=this.tools.get(e);if(!r)throw new Error(`\u672A\u627E\u5230\u5DE5\u5177: ${e}`);let o=this.services.get(r.serviceName);if(!o)throw new Error(`\u670D\u52A1 ${r.serviceName} \u4E0D\u53EF\u7528`);if(!o.isConnected())throw new Error(`\u670D\u52A1 ${r.serviceName} \u672A\u8FDE\u63A5`);try{let n=await o.callTool(r.originalName,t||{});return this.updateToolStats(e,r.serviceName,r.originalName,!0).catch(s=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,s)}),this.logger.info(`[MCPManager] \u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F\uFF0C\u7ED3\u679C:`,n),n}catch(n){throw this.updateToolStatsForFailedCall(e,r.serviceName,r.originalName,n).catch(s=>{this.logger.warn(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,s)}),this.logger.error(`[MCPManager] \u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,n.message),n}}async updateToolStats(e,t,r,o){try{if(!o)return;let n=new Date().toISOString();await this.updateCustomMCPToolStats(e,n),t!=="customMCP"&&await this.updateMCPServerToolStats(t,r,n),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0\u5DE5\u5177 ${e} \u7684\u7EDF\u8BA1\u4FE1\u606F`)}catch(n){throw this.logger.error(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,n),n}}async updateToolStatsForFailedCall(e,t,r,o){try{let n=new Date().toISOString();await this.updateCustomMCPToolLastUsedTime(e,n),t!=="customMCP"&&await this.updateMCPServerToolLastUsedTime(t,r,n),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0\u5DE5\u5177 ${e} \u7684\u5931\u8D25\u8C03\u7528\u7EDF\u8BA1\u4FE1\u606F`)}catch(n){throw this.logger.error(`[MCPManager] \u66F4\u65B0\u5DE5\u5177 ${e} \u5931\u8D25\u8C03\u7528\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:`,n),n}}async updateCustomMCPToolStats(e,t){try{await d.updateToolUsageStatsWithLock(e,!0),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u4F7F\u7528\u7EDF\u8BA1`)}catch(r){throw this.logger.error(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u7EDF\u8BA1\u5931\u8D25:`,r),r}}async updateCustomMCPToolLastUsedTime(e,t){try{await d.updateToolUsageStatsWithLock(e,!1),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u6700\u540E\u4F7F\u7528\u65F6\u95F4`)}catch(r){throw this.logger.error(`[MCPManager] \u66F4\u65B0 customMCP \u5DE5\u5177 ${e} \u6700\u540E\u4F7F\u7528\u65F6\u95F4\u5931\u8D25:`,r),r}}async updateMCPServerToolStats(e,t,r){try{await d.updateMCPServerToolStatsWithLock(e,t,r,!0),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1`)}catch(o){throw this.logger.error(`[MCPManager] \u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u7EDF\u8BA1\u5931\u8D25:`,o),o}}async updateMCPServerToolLastUsedTime(e,t,r){try{await d.updateMCPServerToolStatsWithLock(e,t,r,!1),this.logger.debug(`[MCPManager] \u5DF2\u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u6700\u540E\u4F7F\u7528\u65F6\u95F4`)}catch(o){throw this.logger.error(`[MCPManager] \u66F4\u65B0 MCP \u670D\u52A1\u5DE5\u5177 ${e}/${t} \u6700\u540E\u4F7F\u7528\u65F6\u95F4\u5931\u8D25:`,o),o}}async callMCPTool(e,t,r){let{serviceName:o,toolName:n}=t;this.logger.info(`[MCPManager] \u8C03\u7528 MCP \u540C\u6B65\u5DE5\u5177 ${e} -> ${o}.${n}`);let s=this.services.get(o);if(!s)throw new Error(`\u670D\u52A1 ${o} \u4E0D\u53EF\u7528`);if(!s.isConnected())throw new Error(`\u670D\u52A1 ${o} \u672A\u8FDE\u63A5`);try{let a=await s.callTool(n,r||{});return this.logger.info(`[MCPManager] MCP \u540C\u6B65\u5DE5\u5177 ${e} \u8C03\u7528\u6210\u529F`),a}catch(a){throw this.logger.error(`[MCPManager] MCP \u540C\u6B65\u5DE5\u5177 ${e} \u8C03\u7528\u5931\u8D25:`,a.message),a}}hasTool(e){return this.customMCPHandler.hasTool(e)?!0:this.tools.has(e)}async stopAllServices(){this.logger.info("[MCPManager] \u6B63\u5728\u505C\u6B62\u6240\u6709 MCP \u670D\u52A1...");for(let[e,t]of this.services)try{await t.disconnect(),this.logger.info(`[MCPManager] ${e} \u670D\u52A1\u5DF2\u505C\u6B62`)}catch(r){this.logger.error(`[MCPManager] \u505C\u6B62 ${e} \u670D\u52A1\u5931\u8D25:`,r.message)}try{this.customMCPHandler.cleanup(),this.logger.info("[MCPManager] CustomMCP \u5904\u7406\u5668\u5DF2\u6E05\u7406")}catch(e){this.logger.error("[MCPManager] CustomMCP \u5904\u7406\u5668\u6E05\u7406\u5931\u8D25:",e)}try{d.clearAllStatsUpdateLocks(),this.logger.info("[MCPManager] \u7EDF\u8BA1\u66F4\u65B0\u9501\u5DF2\u6E05\u7406")}catch(e){this.logger.error("[MCPManager] \u6E05\u7406\u7EDF\u8BA1\u66F4\u65B0\u9501\u5931\u8D25:",e)}this.services.clear(),this.tools.clear(),this.logger.info("[MCPManager] \u6240\u6709 MCP \u670D\u52A1\u5DF2\u505C\u6B62")}getStatus(){let e=this.customMCPHandler.getToolCount(),t=this.tools.size+e,r=Array.from(this.tools.keys()),o=this.customMCPHandler.getToolNames(),n=[...r,...o],s={services:{},totalTools:t,availableTools:n};for(let[a,l]of this.services){let h=l.getStatus();s.services[a]={connected:h.connected,clientName:`xiaozhi-${a}-client`}}return e>0&&(s.services.customMCP={connected:!0,clientName:"xiaozhi-customMCP-handler"}),s}getStatsUpdateInfo(){try{let e=d.getStatsUpdateLocks();return{activeLocks:e,totalLocks:e.length}}catch(e){return this.logger.warn("[MCPManager] \u83B7\u53D6\u7EDF\u8BA1\u66F4\u65B0\u76D1\u63A7\u4FE1\u606F\u5931\u8D25:",e),{activeLocks:[],totalLocks:0}}}getService(e){return this.services.get(e)}getAllServices(){return new Map(this.services)}getCustomMCPHandler(){return this.customMCPHandler}hasCustomMCPTool(e){return this.customMCPHandler.hasTool(e)}getCustomMCPTools(){return this.customMCPHandler.getTools()}enhanceServiceConfig(e){let t={...e};try{if(e.type==="modelscope-sse"){let r=d.getModelScopeApiKey();if(r)t.apiKey=r,this.logger.info(`[MCPManager] \u4E3A ${e.name} \u670D\u52A1\u6DFB\u52A0 ModelScope API Key`);else throw this.logger.warn(`[MCPManager] ${e.name} \u670D\u52A1\u9700\u8981 ModelScope API Key\uFF0C\u4F46\u672A\u5728\u914D\u7F6E\u4E2D\u627E\u5230`),new Error(`ModelScope SSE \u670D\u52A1 ${e.name} \u9700\u8981 API Key\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E modelscope.apiKey`)}return t}catch(r){throw this.logger.error(`[MCPManager] \u914D\u7F6E\u589E\u5F3A\u5931\u8D25: ${e.name}`,r),r}}addServiceConfig(e,t){let r,o;if(typeof e=="string"&&t)o=e,r=t;else if(typeof e=="object")o=e.name,r=e;else throw new Error("Invalid arguments for addServiceConfig");let n=this.enhanceServiceConfig(r);this.configs[o]=n,this.logger.info(`[MCPManager] \u5DF2\u6DFB\u52A0\u670D\u52A1\u914D\u7F6E: ${o}`)}updateServiceConfig(e,t){let r=this.enhanceServiceConfig(t);this.configs[e]=r,this.logger.info(`[MCPManager] \u5DF2\u66F4\u65B0\u5E76\u589E\u5F3A\u670D\u52A1\u914D\u7F6E: ${e}`)}removeServiceConfig(e){delete this.configs[e],this.logger.info(`[MCPManager] \u5DF2\u79FB\u9664\u670D\u52A1\u914D\u7F6E: ${e}`)}async syncToolsConfigToFile(){try{this.logger.debug("[MCPManager] \u5F00\u59CB\u540C\u6B65\u5DE5\u5177\u914D\u7F6E\u5230\u914D\u7F6E\u6587\u4EF6");let e=d.getMcpServerConfig();for(let[t,r]of this.services){if(!r.isConnected())continue;let o=r.getTools();if(o.length===0)continue;let n=e[t]?.tools||{},s={};for(let p of o){let C=n[p.name];C?s[p.name]={...C,description:p.description||C.description||""}:s[p.name]={description:p.description||"",enable:!0}}let a=o.map(p=>p.name),h=Object.keys(n).filter(p=>!a.includes(p));if(h.length>0&&this.logger.info(`[MCPManager] \u68C0\u6D4B\u5230\u670D\u52A1 ${t} \u79FB\u9664\u4E86 ${h.length} \u4E2A\u5DE5\u5177: ${h.join(", ")}`),this.hasToolsConfigChanged(n,s)){d.updateServerToolsConfig(t,s);let p=Object.keys(s).filter(T=>!n[T]),C=Object.keys(s).filter(T=>{let b=n[T],B=s[T];return b&&b.description!==B.description});this.logger.info(`[MCPManager] \u5DF2\u540C\u6B65\u670D\u52A1 ${t} \u7684\u5DE5\u5177\u914D\u7F6E:`),p.length>0&&this.logger.info(` - \u65B0\u589E\u5DE5\u5177: ${p.join(", ")}`),C.length>0&&this.logger.info(` - \u66F4\u65B0\u5DE5\u5177: ${C.join(", ")}`),h.length>0&&this.logger.info(` - \u79FB\u9664\u5DE5\u5177: ${h.join(", ")}`)}}this.logger.debug("[MCPManager] \u5DE5\u5177\u914D\u7F6E\u540C\u6B65\u5B8C\u6210")}catch(e){this.logger.error("[MCPManager] \u540C\u6B65\u5DE5\u5177\u914D\u7F6E\u5230\u914D\u7F6E\u6587\u4EF6\u5931\u8D25:",e)}}hasToolsConfigChanged(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!0;let n=o.filter(a=>!r.includes(a)),s=r.filter(a=>!o.includes(a));if(n.length>0||s.length>0)return!0;for(let a of r){let l=e[a],h=t[a];if(l.description!==h.description)return!0}return!1}},go=Ze});var De,gr=m(()=>{"use strict";S();De=class{static{c(this,"MCPMessageHandler")}logger;serviceManager;constructor(e){this.serviceManager=e,this.logger=g}async handleMessage(e){this.logger.debug(`\u5904\u7406 MCP \u6D88\u606F: ${e.method}`,e);try{let t=e.id===void 0;switch(e.method){case"initialize":return await this.handleInitialize(e.params,e.id);case"notifications/initialized":return await this.handleInitializedNotification(e.params);case"tools/list":return await this.handleToolsList(e.id);case"tools/call":return await this.handleToolCall(e.params,e.id);case"resources/list":return await this.handleResourcesList(e.id);case"prompts/list":return await this.handlePromptsList(e.id);case"ping":return await this.handlePing(e.id);default:if(t)return this.logger.warn(`\u6536\u5230\u672A\u77E5\u7684\u901A\u77E5\u6D88\u606F: ${e.method}`,e),null;throw new Error(`\u672A\u77E5\u7684\u65B9\u6CD5: ${e.method}`)}}catch(t){return this.logger.error(`\u5904\u7406\u6D88\u606F\u65F6\u51FA\u9519: ${e.method}`,t),e.id===void 0?null:this.createErrorResponse(t,e.id)}}async handleInitialize(e,t){this.logger.info("\u5904\u7406 initialize \u8BF7\u6C42",e);let r=["2024-11-05","2025-06-18"],o=e.protocolVersion,n=r.includes(o)?o:"2024-11-05";return this.logger.info(`\u534F\u8BAE\u7248\u672C\u534F\u5546: \u5BA2\u6237\u7AEF=${o}, \u670D\u52A1\u5668\u54CD\u5E94=${n}`),{jsonrpc:"2.0",result:{serverInfo:{name:"xiaozhi-mcp-server",version:"1.0.0"},capabilities:{tools:{},logging:{}},protocolVersion:n},id:t!==void 0?t:1}}async handleInitializedNotification(e){return this.logger.info("\u6536\u5230 initialized \u901A\u77E5\uFF0C\u5BA2\u6237\u7AEF\u521D\u59CB\u5316\u5B8C\u6210",e),null}async handleToolsList(e){this.logger.info("\u5904\u7406 tools/list \u8BF7\u6C42");try{let r=this.serviceManager.getAllTools().map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema}));return this.logger.info(`\u8FD4\u56DE ${r.length} \u4E2A\u5DE5\u5177`),{jsonrpc:"2.0",result:{tools:r},id:e!==void 0?e:1}}catch(t){throw this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25",t),t}}async handleToolCall(e,t){this.logger.info(`\u5904\u7406 tools/call \u8BF7\u6C42: ${e.name}`,e);try{if(!e.name)throw new Error("\u5DE5\u5177\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");let r=await this.serviceManager.callTool(e.name,e.arguments||{});return this.logger.info(`\u5DE5\u5177 ${e.name} \u8C03\u7528\u6210\u529F`),{jsonrpc:"2.0",result:{content:r.content,isError:r.isError||!1},id:t!==void 0?t:1}}catch(r){throw this.logger.error(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e.name}`,r),r}}async handlePing(e){return this.logger.debug("\u5904\u7406 ping \u8BF7\u6C42"),{jsonrpc:"2.0",result:{status:"ok",timestamp:new Date().toISOString()},id:e!==void 0?e:1}}async handleResourcesList(e){this.logger.info("\u5904\u7406 resources/list \u8BF7\u6C42");let t=[];return this.logger.info(`\u8FD4\u56DE ${t.length} \u4E2A\u8D44\u6E90`),{jsonrpc:"2.0",result:{resources:t},id:e!==void 0?e:1}}async handlePromptsList(e){this.logger.info("\u5904\u7406 prompts/list \u8BF7\u6C42");let t=[];return this.logger.info(`\u8FD4\u56DE ${t.length} \u4E2A\u63D0\u793A\u6A21\u677F`),{jsonrpc:"2.0",result:{prompts:t},id:e!==void 0?e:1}}createErrorResponse(e,t){let r=-32603;return e.message.includes("\u672A\u627E\u5230\u5DE5\u5177")||e.message.includes("\u672A\u77E5\u7684\u65B9\u6CD5")?r=-32601:(e.message.includes("\u53C2\u6570")||e.message.includes("\u4E0D\u80FD\u4E3A\u7A7A"))&&(r=-32602),{jsonrpc:"2.0",error:{code:r,message:e.message,data:{stack:e.stack}},id:t!==void 0?t:1}}getServiceManager(){return this.serviceManager}}});import{EventEmitter as ho}from"events";var hr,ur,Et,uo=m(()=>{"use strict";S();lr();Ge();gr();hr=class{static{c(this,"ToolRegistry")}serviceManager;logger;constructor(e){this.serviceManager=e,this.logger=g}async initialize(){this.logger.info("\u521D\u59CB\u5316\u5DE5\u5177\u6CE8\u518C\u8868")}getAllTools(){return this.serviceManager.getAllTools().map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema,serviceName:e.serviceName,originalName:e.originalName}))}findTool(e){return this.getAllTools().find(r=>r.name===e)||null}hasTool(e){return this.findTool(e)!==null}},ur=class extends ho{static{c(this,"ConnectionManager")}connections=new Map;logger;constructor(){super(),this.logger=g}async initialize(){this.logger.info("\u521D\u59CB\u5316\u8FDE\u63A5\u7BA1\u7406\u5668")}registerConnection(e,t,r){let o={id:e,transportName:t,state:r,connectedAt:new Date,lastActivity:new Date};this.connections.set(e,o),this.emit("connectionRegistered",o),this.logger.debug(`\u8FDE\u63A5\u5DF2\u6CE8\u518C: ${e} (${t})`)}updateConnectionState(e,t){let r=this.connections.get(e);r&&(r.state=t,r.lastActivity=new Date,this.emit("connectionStateChanged",r),this.logger.debug(`\u8FDE\u63A5\u72B6\u6001\u66F4\u65B0: ${e} -> ${t}`))}removeConnection(e){let t=this.connections.get(e);t&&(this.connections.delete(e),this.emit("connectionRemoved",t),this.logger.debug(`\u8FDE\u63A5\u5DF2\u79FB\u9664: ${e}`))}getAllConnections(){return Array.from(this.connections.values())}getActiveConnectionCount(){return Array.from(this.connections.values()).filter(e=>e.state==="connected").length}async closeAllConnections(){this.logger.info("\u5173\u95ED\u6240\u6709\u8FDE\u63A5"),this.connections.clear(),this.emit("allConnectionsClosed")}},Et=class extends ho{static{c(this,"UnifiedMCPServer")}serviceManager;messageHandler;transportAdapters=new Map;toolRegistry;connectionManager;isRunning=!1;logger;config;constructor(e={}){super(),this.config={name:"UnifiedMCPServer",enableLogging:!0,logLevel:"info",maxConnections:100,connectionTimeout:3e4,...e},this.logger=g,this.serviceManager=new Ze,this.messageHandler=new De(this.serviceManager),this.toolRegistry=new hr(this.serviceManager),this.connectionManager=new ur,this.setupEventListeners()}setupEventListeners(){this.connectionManager.on("connectionRegistered",e=>{this.emit("connectionRegistered",e)}),this.connectionManager.on("connectionStateChanged",e=>{this.emit("connectionStateChanged",e)}),this.connectionManager.on("connectionRemoved",e=>{this.emit("connectionRemoved",e)})}async initialize(){this.logger.info("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{await this.serviceManager.startAllServices(),await this.toolRegistry.initialize(),await this.connectionManager.initialize(),this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210"),this.emit("initialized")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5931\u8D25",e),e}}async registerTransport(e,t){if(this.transportAdapters.has(e))throw new Error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u5DF2\u5B58\u5728`);this.logger.info(`\u6CE8\u518C\u4F20\u8F93\u9002\u914D\u5668: ${e}`);try{await t.initialize(),this.transportAdapters.set(e,t),this.connectionManager.registerConnection(t.getConnectionId(),e,t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u6CE8\u518C\u6210\u529F`),this.emit("transportRegistered",{name:e,adapter:t})}catch(r){throw this.logger.error(`\u6CE8\u518C\u4F20\u8F93\u9002\u914D\u5668 ${e} \u5931\u8D25`,r),r}}async start(){if(this.isRunning)throw new Error("\u670D\u52A1\u5668\u5DF2\u5728\u8FD0\u884C");this.logger.info("\u542F\u52A8\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{for(let[e,t]of this.transportAdapters)try{await t.start(),this.connectionManager.updateConnectionState(t.getConnectionId(),t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u542F\u52A8\u6210\u529F`)}catch(r){throw this.logger.error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u542F\u52A8\u5931\u8D25`,r),r}this.isRunning=!0,this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F"),this.emit("started")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u542F\u52A8\u5931\u8D25",e),e}}async stop(){if(this.isRunning){this.logger.info("\u505C\u6B62\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{for(let[e,t]of this.transportAdapters)try{await t.stop(),this.connectionManager.updateConnectionState(t.getConnectionId(),t.getState()),this.logger.info(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u505C\u6B62\u6210\u529F`)}catch(r){this.logger.error(`\u4F20\u8F93\u9002\u914D\u5668 ${e} \u505C\u6B62\u5931\u8D25`,r)}await this.connectionManager.closeAllConnections(),await this.serviceManager.stopAllServices(),this.isRunning=!1,this.logger.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u505C\u6B62\u6210\u529F"),this.emit("stopped")}catch(e){throw this.logger.error("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u505C\u6B62\u5931\u8D25",e),e}}}getServiceManager(){return this.serviceManager}getToolRegistry(){return this.toolRegistry}getConnectionManager(){return this.connectionManager}getMessageHandler(){return this.messageHandler}getStatus(){return{isRunning:this.isRunning,transportCount:this.transportAdapters.size,activeConnections:this.connectionManager.getActiveConnectionCount(),toolCount:this.toolRegistry.getAllTools().length,config:this.config}}getTransportAdapters(){return new Map(this.transportAdapters)}isServerRunning(){return this.isRunning}}});async function po(i={name:"http"}){g.info("\u521B\u5EFA HTTP \u6A21\u5F0F\u670D\u52A1\u5668");let e=new Et;await e.initialize();let t=e.getMessageHandler(),r=new pt(t,i);return await e.registerTransport("http",r),g.info("HTTP \u6A21\u5F0F\u670D\u52A1\u5668\u521B\u5EFA\u6210\u529F"),e}var mo=m(()=>{"use strict";S();Xr();Kr();Zr();uo();c(po,"createHTTPServer")});var fo={};F(fo,{MCPServer:()=>pr});import{EventEmitter as Gn}from"events";var D,pr,Co=m(()=>{"use strict";S();ut();Y();mo();D=new Ie,pr=class extends Gn{static{c(this,"MCPServer")}unifiedServer=null;proxyMCPServer=null;port;isStarted=!1;constructor(e=3e3){super(),this.port=e}async initializeUnifiedServer(){if(!this.unifiedServer){D.info("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668");try{let e={name:"http",port:this.port,host:"0.0.0.0",enableSSE:!0,enableRPC:!0};this.unifiedServer=await po(e),this.unifiedServer.on("started",()=>this.emit("started")),this.unifiedServer.on("stopped",()=>this.emit("stopped")),this.unifiedServer.on("connectionRegistered",t=>{this.emit("connectionRegistered",t)}),D.info("\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u521D\u59CB\u5316\u5B8C\u6210")}catch(e){throw D.error("\u521D\u59CB\u5316\u7EDF\u4E00 MCP \u670D\u52A1\u5668\u5931\u8D25",e),e}}}async initializeMCPClient(){try{let e=null;try{d.configExists()&&(e=d.getMcpEndpoints().find(r=>r&&!r.includes("<\u8BF7\u586B\u5199"))||null)}catch(t){D.warn("\u4ECE\u914D\u7F6E\u4E2D\u8BFB\u53D6\u5C0F\u667A\u63A5\u5165\u70B9\u5931\u8D25:",t)}e?(this.proxyMCPServer=new pe(e),this.unifiedServer&&this.proxyMCPServer.setServiceManager(this.unifiedServer.getServiceManager()),await this.proxyMCPServer.connect(),D.info("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u6210\u529F")):D.info("\u672A\u914D\u7F6E\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u8DF3\u8FC7\u8FDE\u63A5")}catch(e){D.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}}async start(){if(this.isStarted){D.warn("\u670D\u52A1\u5668\u5DF2\u542F\u52A8");return}try{D.info("\u542F\u52A8 MCP \u670D\u52A1\u5668"),await this.initializeUnifiedServer(),this.unifiedServer&&await this.unifiedServer.start(),this.initializeMCPClient().catch(e=>{D.error("\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25:",e)}),this.isStarted=!0,this.emit("started"),D.info("MCP \u670D\u52A1\u5668\u542F\u52A8\u6210\u529F")}catch(e){throw D.error("\u542F\u52A8 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}async stop(){if(!this.isStarted){D.warn("\u670D\u52A1\u5668\u672A\u542F\u52A8");return}try{D.info("\u505C\u6B62 MCP \u670D\u52A1\u5668"),this.unifiedServer&&await this.unifiedServer.stop(),this.proxyMCPServer&&(this.proxyMCPServer.disconnect(),this.proxyMCPServer=null),this.isStarted=!1,this.emit("stopped"),D.info("MCP \u670D\u52A1\u5668\u5DF2\u505C\u6B62")}catch(e){throw D.error("\u505C\u6B62 MCP \u670D\u52A1\u5668\u5931\u8D25:",e),e}}getServiceManager(){return this.unifiedServer?.getServiceManager()||null}getMessageHandler(){return this.unifiedServer?.getMessageHandler()||null}getStatus(){return this.unifiedServer?{...this.unifiedServer.getStatus(),port:this.port,mode:"mcp-server",proxyConnected:this.proxyMCPServer!==null}:{isRunning:!1,port:this.port,mode:"mcp-server"}}isRunning(){return this.isStarted&&(this.unifiedServer?.isServerRunning()||!1)}}});import{isAbsolute as Jn,resolve as Xn}from"path";function vo(i,e){Mt.debug(`\u8F6C\u6362\u914D\u7F6E: ${i}`,e);try{if(!i||typeof i!="string")throw new L("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!e||typeof e!="object")throw new L("\u914D\u7F6E\u5BF9\u8C61\u4E0D\u80FD\u4E3A\u7A7A",i);let t=Kn(i,e);return ss(t),Mt.info(`\u914D\u7F6E\u8F6C\u6362\u6210\u529F: ${i} -> ${t.type}`),t}catch(t){throw Mt.error(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${i}`,t),t instanceof L?t:new L(`\u914D\u7F6E\u8F6C\u6362\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,i)}}function Kn(i,e){if(ts(e))return Zn(i,e);if(rs(e))return Yn(i,e);if(os(e))return Qn(i,e);throw new L("\u65E0\u6CD5\u8BC6\u522B\u7684\u914D\u7F6E\u7C7B\u578B",i)}function Zn(i,e){if(!e.command)throw new L("\u672C\u5730\u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5",i);let t=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),r=(e.args||[]).map(o=>{if(es(o)){let n=Xn(t,o);return Mt.debug(`\u89E3\u6790\u76F8\u5BF9\u8DEF\u5F84: ${o} -> ${n}`),n}return o});return{name:i,type:"stdio",command:e.command,args:r,env:e.env,reconnect:{enabled:!0,maxAttempts:5,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:1e4,jitter:!0},ping:{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3},timeout:3e4}}function Yn(i,e){if(!e.url)throw new L("SSE \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);let t=ns(e.url),r={name:i,type:t?"modelscope-sse":"sse",url:e.url,reconnect:{enabled:!0,maxAttempts:10,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:15e3,jitter:!0},ping:{enabled:!0,interval:3e4,timeout:5e3,maxFailures:3,startDelay:5e3},timeout:3e4};return t&&(r.modelScopeAuth=!0),r}function Qn(i,e){if(!e.url)throw new L("Streamable HTTP \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5",i);return{name:i,type:"streamable-http",url:e.url,reconnect:{enabled:!0,maxAttempts:5,initialInterval:3e3,maxInterval:3e4,backoffStrategy:"exponential",backoffMultiplier:1.5,timeout:15e3,jitter:!0},ping:{enabled:!1,interval:6e4,timeout:1e4,maxFailures:3,startDelay:1e4},timeout:3e4}}function es(i){return Jn(i)?!1:!!(i.startsWith("./")||i.startsWith("../")||/\.(js|py|ts|mjs|cjs)$/i.test(i))}function ts(i){return"command"in i&&typeof i.command=="string"}function rs(i){return"type"in i&&i.type==="sse"&&"url"in i}function os(i){return"url"in i&&(!("type"in i)||i.type==="streamable-http")}function ns(i){return i.includes("modelscope.net")||i.includes("modelscope.cn")}function ss(i){if(!i.name||typeof i.name!="string")throw new L("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 name \u5B57\u6BB5");if(!Object.values(Ke).includes(i.type))throw new L(`\u65E0\u6548\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`);switch(i.type){case"stdio":if(!i.command)throw new L("STDIO \u914D\u7F6E\u5FC5\u987B\u5305\u542B command \u5B57\u6BB5");break;case"sse":case"modelscope-sse":case"streamable-http":if(!i.url)throw new L(`${i.type} \u914D\u7F6E\u5FC5\u987B\u5305\u542B url \u5B57\u6BB5`);break;default:throw new L(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${i.type}`)}}var Mt,L,So=m(()=>{"use strict";S();St();Mt=g.withTag("ConfigAdapter"),L=class extends Error{constructor(t,r){super(t);this.configName=r;this.name="ConfigValidationError"}static{c(this,"ConfigValidationError")}};c(vo,"convertLegacyToNew");c(Kn,"convertByConfigType");c(Zn,"convertLocalConfig");c(Yn,"convertSSEConfig");c(Qn,"convertStreamableHTTPConfig");c(es,"isRelativePath");c(ts,"isLocalConfig");c(rs,"isSSEConfig");c(os,"isStreamableHTTPConfig");c(ns,"isModelScopeURL");c(ss,"validateNewConfig")});async function is(){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),new go}async function yo(){if(se&&z==="initialized")return se;if(Q&&z==="initializing")return Q;z==="failed"&&dr(),z="initializing",Q=is();try{return se=await Q,z="initialized",Ne=`mcp-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,Ye=null,console.log(`\u2705 MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${Ne}`),se}catch(i){throw z="failed",Ye=i,Q=null,console.error("\u274C MCPServiceManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",i.message),i}}async function To(){if(z==="cleanup"){console.log("\u26A0\uFE0F MCPServiceManager \u5355\u4F8B\u5DF2\u5728\u6E05\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u91CD\u590D\u6E05\u7406");return}console.log("\u{1F9F9} \u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B\u8D44\u6E90..."),z="cleanup";try{if(Q){try{await(await Q).stopAllServices()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}Q=null}se&&(await se.stopAllServices(),se=null),z="not_initialized",Ye=null,Ne=null,console.log("\u2705 MCPServiceManager \u5355\u4F8B\u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(i){throw console.error("\u274C MCPServiceManager \u5355\u4F8B\u6E05\u7406\u5931\u8D25:",i.message),dr(),i}}function dr(){console.log("\u{1F504} \u91CD\u7F6E MCPServiceManager \u5355\u4F8B\u72B6\u6001"),se=null,Q=null,z="not_initialized",Ye=null,Ne=null}function as(){return z==="initialized"&&se!==null}function cs(){return{state:z,initializationTime:Ne?new Date:void 0,lastError:Ye||void 0,instanceId:Ne||void 0}}async function ls(){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 MCPServiceManager \u5355\u4F8B..."),await To(),yo()}function gs(){return se}async function hs(){if(z==="initialized")return!0;if(z==="initializing"&&Q)try{return await Q,!0}catch{return!1}return!1}var se,Q,z,Ye,Ne,V,Pt=m(()=>{"use strict";lr();se=null,Q=null,z="not_initialized",Ye=null,Ne=null;c(is,"createInstance");c(yo,"getInstance");c(To,"cleanup");c(dr,"reset");c(as,"isInitialized");c(cs,"getStatus");c(ls,"forceReinitialize");c(gs,"getCurrentInstance");c(hs,"waitForInitialization");V={getInstance:yo,cleanup:To,reset:dr,isInitialized:as,getStatus:cs,forceReinitialize:ls,getCurrentInstance:gs,waitForInitialization:hs};process.on("exit",()=>{V.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 MCPServiceManager \u5355\u4F8B..."),V.reset())});process.on("uncaughtException",async i=>{console.error("\u{1F4A5} \u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u6E05\u7406 MCPServiceManager \u5355\u4F8B:",i);try{await V.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}});process.on("unhandledRejection",async i=>{console.error("\u{1F4A5} \u672A\u5904\u7406\u7684Promise\u62D2\u7EDD\uFF0C\u6E05\u7406 MCPServiceManager \u5355\u4F8B:",i);try{await V.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as us}from"events";var Eo,ps,wt,Mo=m(()=>{"use strict";S();ut();Eo=(o=>(o.EXPONENTIAL_BACKOFF="exponential_backoff",o.LINEAR_BACKOFF="linear_backoff",o.FIXED_INTERVAL="fixed_interval",o.ADAPTIVE="adaptive",o))(Eo||{}),ps={healthCheckInterval:3e4,reconnectInterval:5e3,maxReconnectAttempts:10,loadBalanceStrategy:"round-robin",connectionTimeout:1e4,reconnectStrategy:"exponential_backoff",maxReconnectDelay:3e4,reconnectBackoffMultiplier:2,jitterEnabled:!0},wt=class extends us{static{c(this,"XiaozhiConnectionManager")}connections=new Map;connectionStates=new Map;mcpServiceManager=null;logger;isInitialized=!1;isConnecting=!1;options;healthCheckInterval=null;reconnectTimers=new Map;roundRobinIndex=0;lastSelectedEndpoint=null;performanceMetrics={connectionStartTime:0,totalConnectionTime:0,averageConnectionTime:0,connectionCount:0,memoryUsage:{initial:0,current:0,peak:0},prewarmedConnections:new Set};constructor(e){super(),this.logger=g,this.options={...ps,...e},this.logger.info("[XiaozhiConnectionManager] \u5B9E\u4F8B\u5DF2\u521B\u5EFA"),this.logger.debug("[XiaozhiConnectionManager] \u914D\u7F6E\u9009\u9879:",this.options)}async initialize(e,t){if(this.isInitialized){this.logger.warn("XiaozhiConnectionManager \u5DF2\u7ECF\u521D\u59CB\u5316\uFF0C\u8DF3\u8FC7\u91CD\u590D\u521D\u59CB\u5316");return}this.logger.info(`\u5F00\u59CB\u521D\u59CB\u5316 XiaozhiConnectionManager\uFF0C\u7AEF\u70B9\u6570\u91CF: ${e.length}`);try{this.validateInitializeParams(e,t),await this.cleanup();for(let r of e)await this.createConnection(r,t);this.isInitialized=!0,this.performanceMetrics.memoryUsage.initial=process.memoryUsage().heapUsed,this.performanceMetrics.memoryUsage.current=this.performanceMetrics.memoryUsage.initial,this.performanceMetrics.memoryUsage.peak=this.performanceMetrics.memoryUsage.initial,this.logger.info(`XiaozhiConnectionManager \u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u7BA1\u7406 ${this.connections.size} \u4E2A\u8FDE\u63A5`)}catch(r){throw this.logger.error("XiaozhiConnectionManager \u521D\u59CB\u5316\u5931\u8D25:",r),await this.cleanup(),r}}async connect(){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 initialize()");if(this.isConnecting){this.logger.warn("\u8FDE\u63A5\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");return}this.isConnecting=!0,this.performanceMetrics.connectionStartTime=Date.now(),this.logger.info(`\u5F00\u59CB\u8FDE\u63A5\u6240\u6709\u7AEF\u70B9\uFF0C\u603B\u6570: ${this.connections.size}`);try{let e=[];for(let[s,a]of this.connections)e.push(this.connectSingleEndpoint(s,a));let t=await Promise.allSettled(e),r=t.filter(s=>s.status==="fulfilled").length,o=t.length-r,n=Date.now()-this.performanceMetrics.connectionStartTime;if(this.performanceMetrics.totalConnectionTime+=n,this.performanceMetrics.connectionCount++,this.performanceMetrics.averageConnectionTime=this.performanceMetrics.totalConnectionTime/this.performanceMetrics.connectionCount,this.logger.info(`\u8FDE\u63A5\u5B8C\u6210 - \u6210\u529F: ${r}, \u5931\u8D25: ${o}, \u8017\u65F6: ${n}ms`),r===0)throw new Error("\u6240\u6709\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u5931\u8D25");this.startHealthCheck()}finally{this.isConnecting=!1}}async disconnect(){this.logger.info("\u5F00\u59CB\u65AD\u5F00\u6240\u6709\u8FDE\u63A5"),this.stopHealthCheck(),this.clearAllReconnectTimers();let e=[];for(let[t,r]of this.connections)e.push(this.disconnectSingleEndpoint(t,r));await Promise.allSettled(e),this.logger.info("\u6240\u6709\u8FDE\u63A5\u5DF2\u65AD\u5F00")}async addEndpoint(e){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316");if(this.connections.has(e)){this.logger.warn(`\u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728\uFF0C\u8DF3\u8FC7\u6DFB\u52A0`);return}this.logger.info(`\u52A8\u6001\u6DFB\u52A0\u7AEF\u70B9: ${e}`);try{let t=this.getCurrentTools();if(await this.createConnection(e,t),this.isAnyConnected()){let r=this.connections.get(e);await this.connectSingleEndpoint(e,r)}this.logger.info(`\u7AEF\u70B9 ${e} \u6DFB\u52A0\u6210\u529F`)}catch(t){throw this.logger.error(`\u6DFB\u52A0\u7AEF\u70B9 ${e} \u5931\u8D25:`,t),this.connections.delete(e),this.connectionStates.delete(e),t}}async removeEndpoint(e){if(!this.connections.has(e)){this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u79FB\u9664`);return}this.logger.info(`\u52A8\u6001\u79FB\u9664\u7AEF\u70B9: ${e}`);try{let t=this.connections.get(e);await this.disconnectSingleEndpoint(e,t),this.connections.delete(e),this.connectionStates.delete(e);let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e)),this.logger.info(`\u7AEF\u70B9 ${e} \u79FB\u9664\u6210\u529F`)}catch(t){throw this.logger.error(`\u79FB\u9664\u7AEF\u70B9 ${e} \u5931\u8D25:`,t),t}}getHealthyConnections(){let e=[];for(let[t,r]of this.connections){let o=this.connectionStates.get(t);o?.connected&&o.healthScore>50&&e.push(r)}return e}getConnectionStatus(){return Array.from(this.connectionStates.values())}isAnyConnected(){for(let e of this.connectionStates.values())if(e.connected)return!0;return!1}setServiceManager(e){this.mcpServiceManager=e,this.logger.info("\u5DF2\u8BBE\u7F6E MCPServiceManager"),this.connections.size>0&&this.syncToolsToAllConnections()}setHealthCheckEnabled(e,t){let r=this.connectionStates.get(e);r?(r.healthCheckEnabled=t,this.logger.info(`\u7AEF\u70B9 ${e} \u5065\u5EB7\u68C0\u67E5\u5DF2${t?"\u542F\u7528":"\u7981\u7528"}`)):this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u8BBE\u7F6E\u5065\u5EB7\u68C0\u67E5\u72B6\u6001`)}getHealthCheckStats(){let e={};for(let[t,r]of this.connectionStates){let o=r.totalRequests>0?r.successfulRequests/r.totalRequests*100:0;e[t]={endpoint:t,healthScore:r.healthScore,successRate:Math.round(o*100)/100,averageResponseTime:r.responseTime||0,consecutiveFailures:r.consecutiveFailures,lastHealthCheck:r.lastHealthCheck,lastSuccessTime:r.lastSuccessTime}}return e}async triggerHealthCheck(){this.logger.info("\u624B\u52A8\u89E6\u53D1\u5065\u5EB7\u68C0\u67E5"),await this.performHealthCheck()}async triggerReconnect(e){let t=this.connectionStates.get(e);if(!t)throw new Error(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(t.connected){this.logger.warn(`\u7AEF\u70B9 ${e} \u5DF2\u8FDE\u63A5\uFF0C\u65E0\u9700\u91CD\u8FDE`);return}this.logger.info(`\u624B\u52A8\u89E6\u53D1\u91CD\u8FDE: ${e}`);let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e)),await this.performReconnect(e)}stopReconnect(e){let t=this.connectionStates.get(e);if(!t){this.logger.warn(`\u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);return}let r=this.reconnectTimers.get(e);r&&(clearTimeout(r),this.reconnectTimers.delete(e),t.isReconnecting=!1,t.nextReconnectTime=void 0,this.logger.info(`\u5DF2\u505C\u6B62\u7AEF\u70B9 ${e} \u7684\u91CD\u8FDE`))}stopAllReconnects(){this.logger.info("\u505C\u6B62\u6240\u6709\u7AEF\u70B9\u7684\u91CD\u8FDE");for(let[e]of this.reconnectTimers)this.stopReconnect(e)}getReconnectStats(){let e={};for(let[t,r]of this.connectionStates)e[t]={endpoint:t,reconnectAttempts:r.reconnectAttempts,isReconnecting:r.isReconnecting,nextReconnectTime:r.nextReconnectTime,lastReconnectAttempt:r.lastReconnectAttempt,reconnectDelay:r.reconnectDelay,errorType:r.errorType,recentReconnectHistory:r.reconnectHistory.slice(-5)};return e}validateEndpoints(e){let t=[],r=[];for(let o of e){if(!o||typeof o!="string"){r.push(o);continue}if(!o.startsWith("ws://")&&!o.startsWith("wss://")){r.push(o);continue}try{new URL(o),t.push(o)}catch{r.push(o)}}return{valid:t,invalid:r}}validateOptions(e){let t=[];if(e.healthCheckInterval!==void 0&&(typeof e.healthCheckInterval!="number"||e.healthCheckInterval<1e3)&&t.push("healthCheckInterval \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.reconnectInterval!==void 0&&(typeof e.reconnectInterval!="number"||e.reconnectInterval<100)&&t.push("reconnectInterval \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 100 \u7684\u6570\u5B57"),e.maxReconnectAttempts!==void 0&&(typeof e.maxReconnectAttempts!="number"||e.maxReconnectAttempts<0)&&t.push("maxReconnectAttempts \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 0 \u7684\u6570\u5B57"),e.connectionTimeout!==void 0&&(typeof e.connectionTimeout!="number"||e.connectionTimeout<1e3)&&t.push("connectionTimeout \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.maxReconnectDelay!==void 0&&(typeof e.maxReconnectDelay!="number"||e.maxReconnectDelay<1e3)&&t.push("maxReconnectDelay \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1000 \u7684\u6570\u5B57"),e.reconnectBackoffMultiplier!==void 0&&(typeof e.reconnectBackoffMultiplier!="number"||e.reconnectBackoffMultiplier<1)&&t.push("reconnectBackoffMultiplier \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6570\u5B57"),e.loadBalanceStrategy!==void 0){let r=["round-robin","random","health-based"];r.includes(e.loadBalanceStrategy)||t.push(`loadBalanceStrategy \u5FC5\u987B\u662F\u4EE5\u4E0B\u503C\u4E4B\u4E00: ${r.join(", ")}`)}if(e.reconnectStrategy!==void 0){let r=Object.values(Eo);r.includes(e.reconnectStrategy)||t.push(`reconnectStrategy \u5FC5\u987B\u662F\u4EE5\u4E0B\u503C\u4E4B\u4E00: ${r.join(", ")}`)}return{valid:t.length===0,errors:t}}async updateEndpoints(e,t=[]){if(!this.isInitialized)throw new Error("XiaozhiConnectionManager \u672A\u521D\u59CB\u5316");this.logger.info(`\u66F4\u65B0\u7AEF\u70B9\u914D\u7F6E\uFF0C\u65B0\u7AEF\u70B9\u6570\u91CF: ${e.length}`);let{valid:r,invalid:o}=this.validateEndpoints(e);if(o.length>0&&this.logger.warn(`\u53D1\u73B0\u65E0\u6548\u7AEF\u70B9: ${o.join(", ")}`),r.length===0)throw new Error("\u6CA1\u6709\u6709\u6548\u7684\u7AEF\u70B9");let n=Array.from(this.connections.keys()),s=r.filter(h=>!n.includes(h)),a=n.filter(h=>!r.includes(h)),l=n.filter(h=>r.includes(h));this.logger.info(`\u7AEF\u70B9\u53D8\u66F4 - \u6DFB\u52A0: ${s.length}, \u79FB\u9664: ${a.length}, \u4FDD\u6301: ${l.length}`);try{for(let u of a)await this.removeEndpoint(u);for(let u of s)await this.addEndpoint(u);let h={type:s.length>0&&a.length>0?"endpoints_updated":s.length>0?"endpoints_added":"endpoints_removed",data:{added:s.length>0?s:void 0,removed:a.length>0?a:void 0,updated:s.length>0&&a.length>0?r:void 0},timestamp:new Date};this.emit("configChange",h),this.logger.info("\u7AEF\u70B9\u914D\u7F6E\u66F4\u65B0\u5B8C\u6210")}catch(h){throw this.logger.error("\u7AEF\u70B9\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",h),h}}updateOptions(e){this.logger.info("\u66F4\u65B0\u8FDE\u63A5\u9009\u9879");let{valid:t,errors:r}=this.validateOptions(e);if(!t)throw new Error(`\u65E0\u6548\u7684\u8FDE\u63A5\u9009\u9879: ${r.join(", ")}`);let o={...this.options};this.options={...this.options,...e};let n={type:"options_updated",data:{oldOptions:o,newOptions:e},timestamp:new Date};this.emit("configChange",n),this.logger.info("\u8FDE\u63A5\u9009\u9879\u66F4\u65B0\u5B8C\u6210"),this.logger.debug("\u65B0\u7684\u914D\u7F6E\u9009\u9879:",this.options)}getCurrentConfig(){return{endpoints:Array.from(this.connections.keys()),options:{...this.options}}}async reloadConfig(e){this.logger.info("\u5F00\u59CB\u70ED\u91CD\u8F7D\u914D\u7F6E");try{e.options&&this.updateOptions(e.options),e.endpoints&&await this.updateEndpoints(e.endpoints,e.tools||[]),this.logger.info("\u914D\u7F6E\u70ED\u91CD\u8F7D\u5B8C\u6210")}catch(t){throw this.logger.error("\u914D\u7F6E\u70ED\u91CD\u8F7D\u5931\u8D25:",t),t}}selectBestConnection(e=[]){let t=this.getHealthyConnections();if(t.length===0)return this.logger.warn("\u6CA1\u6709\u5065\u5EB7\u7684\u8FDE\u63A5\u53EF\u7528"),null;let r=t.filter(n=>{let s=this.getEndpointByConnection(n);return s&&!e.includes(s)});if(r.length===0)return this.logger.warn("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5\uFF08\u6392\u9664\u6307\u5B9A\u7AEF\u70B9\u540E\uFF09"),null;let o;switch(this.options.loadBalanceStrategy){case"round-robin":o=this.selectRoundRobin(r);break;case"random":o=this.selectRandom(r);break;case"health-based":o=this.selectHealthBased(r);break;default:o=this.selectRoundRobin(r)}return this.lastSelectedEndpoint=this.getEndpointByConnection(o),o}selectRoundRobin(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=e[this.roundRobinIndex%e.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%e.length,t}selectRandom(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=Math.floor(Math.random()*e.length);return e[t]}selectHealthBased(e){if(e.length===0)throw new Error("\u6CA1\u6709\u53EF\u7528\u7684\u8FDE\u63A5");let t=e.map(n=>{let s=this.getEndpointByConnection(n),a=s?this.connectionStates.get(s):null;return{connection:n,endpoint:s,healthScore:a?.healthScore||0,responseTime:a?.responseTime||Number.POSITIVE_INFINITY,successRate:a&&a.totalRequests>0?a.successfulRequests/a.totalRequests*100:0}});t.sort((n,s)=>n.healthScore!==s.healthScore?s.healthScore-n.healthScore:n.successRate!==s.successRate?s.successRate-n.successRate:n.responseTime-s.responseTime);let r=t.reduce((n,s)=>n+(s.healthScore+1),0),o=Math.random()*r;for(let n of t)if(o-=n.healthScore+1,o<=0)return n.connection;return t[0].connection}getEndpointByConnection(e){for(let[t,r]of this.connections)if(r===e)return t;return null}getLoadBalanceStats(){let e=this.getHealthyConnections(),t={};for(let[r,o]of this.connectionStates){let n=o.totalRequests>0?o.successfulRequests/o.totalRequests*100:0,s=o.healthScore+1;t[r]={healthScore:o.healthScore,responseTime:o.responseTime||0,successRate:Math.round(n*100)/100,weight:s}}return{strategy:this.options.loadBalanceStrategy,totalConnections:this.connections.size,healthyConnections:e.length,lastSelectedEndpoint:this.lastSelectedEndpoint,roundRobinIndex:this.roundRobinIndex,connectionWeights:t}}setLoadBalanceStrategy(e){let t=this.options.loadBalanceStrategy;this.options.loadBalanceStrategy=e,e==="round-robin"&&(this.roundRobinIndex=0),this.logger.info(`\u8D1F\u8F7D\u5747\u8861\u7B56\u7565\u5DF2\u4ECE ${t} \u5207\u6362\u5230 ${e}`);let r={type:"options_updated",data:{oldOptions:{loadBalanceStrategy:t},newOptions:{loadBalanceStrategy:e}},timestamp:new Date};this.emit("configChange",r)}async performFailover(e){this.logger.warn(`\u6267\u884C\u6545\u969C\u8F6C\u79FB\uFF0C\u5931\u8D25\u7AEF\u70B9: ${e}`);let t=this.selectBestConnection([e]);if(!t)return this.logger.error("\u6545\u969C\u8F6C\u79FB\u5931\u8D25\uFF1A\u6CA1\u6709\u53EF\u7528\u7684\u5907\u7528\u8FDE\u63A5"),null;let r=this.getEndpointByConnection(t);return this.logger.info(`\u6545\u969C\u8F6C\u79FB\u6210\u529F\uFF0C\u5207\u6362\u5230\u7AEF\u70B9: ${r}`),t}async prewarmConnections(e=[]){let t=e.length>0?e:Array.from(this.connections.keys());this.logger.info(`\u5F00\u59CB\u9884\u70ED\u8FDE\u63A5\uFF0C\u7AEF\u70B9\u6570\u91CF: ${t.length}`);let r=t.map(async o=>{if(this.performanceMetrics.prewarmedConnections.has(o)){this.logger.debug(`\u7AEF\u70B9 ${o} \u5DF2\u9884\u70ED\uFF0C\u8DF3\u8FC7`);return}try{this.connections.get(o)&&(await this.performHealthCheck(),this.performanceMetrics.prewarmedConnections.add(o),this.logger.debug(`\u7AEF\u70B9 ${o} \u9884\u70ED\u5B8C\u6210`))}catch(n){this.logger.warn(`\u7AEF\u70B9 ${o} \u9884\u70ED\u5931\u8D25:`,n)}});await Promise.all(r),this.logger.info(`\u8FDE\u63A5\u9884\u70ED\u5B8C\u6210\uFF0C\u6210\u529F\u9884\u70ED ${this.performanceMetrics.prewarmedConnections.size} \u4E2A\u7AEF\u70B9`)}updatePerformanceMetrics(){let e=process.memoryUsage().heapUsed;this.performanceMetrics.memoryUsage.current=e,e>this.performanceMetrics.memoryUsage.peak&&(this.performanceMetrics.memoryUsage.peak=e)}getPerformanceMetrics(){this.updatePerformanceMetrics();let e=this.performanceMetrics.memoryUsage.current-this.performanceMetrics.memoryUsage.initial,t=this.performanceMetrics.memoryUsage.initial>0?e/this.performanceMetrics.memoryUsage.initial*100:0;return{connectionTime:{total:this.performanceMetrics.totalConnectionTime,average:this.performanceMetrics.averageConnectionTime,count:this.performanceMetrics.connectionCount},memoryUsage:{initial:this.performanceMetrics.memoryUsage.initial,current:this.performanceMetrics.memoryUsage.current,peak:this.performanceMetrics.memoryUsage.peak,growth:e,growthPercentage:Math.round(t*100)/100},prewarmedConnections:this.performanceMetrics.prewarmedConnections.size,totalConnections:this.connections.size,healthyConnections:this.getHealthyConnections().length}}optimizeMemoryUsage(){this.logger.info("\u5F00\u59CB\u5185\u5B58\u4F18\u5316");for(let[,e]of this.connectionStates)if(e.reconnectHistory&&e.reconnectHistory.length>10&&(e.reconnectHistory=e.reconnectHistory.slice(-10)),e.totalRequests>1e4){let t=e.successfulRequests/e.totalRequests;e.totalRequests=1e3,e.successfulRequests=Math.round(t*1e3)}global.gc&&global.gc(),this.updatePerformanceMetrics(),this.logger.info("\u5185\u5B58\u4F18\u5316\u5B8C\u6210")}async cleanup(){this.logger.info("\u5F00\u59CB\u6E05\u7406 XiaozhiConnectionManager \u8D44\u6E90");try{await this.disconnect(),this.connections.clear(),this.connectionStates.clear(),this.isInitialized=!1,this.isConnecting=!1,this.roundRobinIndex=0,this.lastSelectedEndpoint=null,this.logger.info("XiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(e){throw this.logger.error("XiaozhiConnectionManager \u8D44\u6E90\u6E05\u7406\u5931\u8D25:",e),e}}validateInitializeParams(e,t){if(!Array.isArray(e)||e.length===0)throw new Error("\u7AEF\u70B9\u5217\u8868\u4E0D\u80FD\u4E3A\u7A7A");if(!Array.isArray(t))throw new Error("\u5DE5\u5177\u5217\u8868\u5FC5\u987B\u662F\u6570\u7EC4");for(let r of e){if(!r||typeof r!="string")throw new Error(`\u65E0\u6548\u7684\u7AEF\u70B9\u5730\u5740: ${r}`);if(!r.startsWith("ws://")&&!r.startsWith("wss://"))throw new Error(`\u7AEF\u70B9\u5730\u5740\u5FC5\u987B\u662F WebSocket URL: ${r}`)}}async createConnection(e,t){this.logger.debug(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B: ${e}`);try{let r=new pe(e);this.mcpServiceManager&&r.setServiceManager(this.mcpServiceManager),this.connections.set(e,r),this.connectionStates.set(e,{endpoint:e,connected:!1,initialized:!1,reconnectAttempts:0,healthScore:100,consecutiveFailures:0,totalRequests:0,successfulRequests:0,healthCheckEnabled:!0,isReconnecting:!1,reconnectDelay:this.options.reconnectInterval,reconnectHistory:[]}),this.logger.debug(`\u8FDE\u63A5\u5B9E\u4F8B\u521B\u5EFA\u6210\u529F: ${e}`)}catch(r){throw this.logger.error(`\u521B\u5EFA\u8FDE\u63A5\u5B9E\u4F8B\u5931\u8D25 ${e}:`,r),r}}async connectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(!r)throw new Error(`\u7AEF\u70B9\u72B6\u6001\u4E0D\u5B58\u5728: ${e}`);this.logger.debug(`\u8FDE\u63A5\u7AEF\u70B9: ${e}`);try{r.connected=!1,r.initialized=!1,await t.connect(),r.connected=!0,r.initialized=!0,r.lastConnected=new Date,r.lastError=void 0,r.reconnectAttempts=0,r.healthScore=100,this.logger.info(`\u7AEF\u70B9\u8FDE\u63A5\u6210\u529F: ${e}`)}catch(o){throw r.connected=!1,r.initialized=!1,r.lastError=o instanceof Error?o.message:String(o),r.reconnectAttempts++,r.healthScore=Math.max(0,r.healthScore-20),this.logger.error(`\u7AEF\u70B9\u8FDE\u63A5\u5931\u8D25 ${e}:`,o),this.scheduleReconnect(e),o}}async disconnectSingleEndpoint(e,t){let r=this.connectionStates.get(e);if(r){this.logger.debug(`\u65AD\u5F00\u7AEF\u70B9: ${e}`);try{t.disconnect(),r.connected=!1,r.initialized=!1,this.logger.debug(`\u7AEF\u70B9\u65AD\u5F00\u6210\u529F: ${e}`)}catch(o){this.logger.error(`\u7AEF\u70B9\u65AD\u5F00\u5931\u8D25 ${e}:`,o),r.connected=!1,r.initialized=!1}}}getCurrentTools(){if(!this.mcpServiceManager)return[];try{return this.mcpServiceManager.getAllTools()}catch(e){return this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25:",e),[]}}syncToolsToAllConnections(){if(this.mcpServiceManager){this.logger.debug("\u540C\u6B65\u5DE5\u5177\u5230\u6240\u6709\u8FDE\u63A5");for(let[e,t]of this.connections)try{t.setServiceManager(this.mcpServiceManager),this.logger.debug(`\u5DE5\u5177\u540C\u6B65\u6210\u529F: ${e}`)}catch(r){this.logger.error(`\u5DE5\u5177\u540C\u6B65\u5931\u8D25 ${e}:`,r)}}}startHealthCheck(){this.healthCheckInterval||(this.logger.debug(`\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\uFF0C\u95F4\u9694: ${this.options.healthCheckInterval}ms`),this.healthCheckInterval=setInterval(()=>{this.performHealthCheck()},this.options.healthCheckInterval))}stopHealthCheck(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null,this.logger.debug("\u5065\u5EB7\u68C0\u67E5\u5DF2\u505C\u6B62"))}async performHealthCheck(){this.logger.debug("\u6267\u884C\u5065\u5EB7\u68C0\u67E5");let e=[];for(let[t,r]of this.connectionStates)r.healthCheckEnabled&&e.push(this.performSingleHealthCheck(t,r));await Promise.allSettled(e)}async performSingleHealthCheck(e,t){let r=Date.now();t.lastHealthCheck=new Date,t.totalRequests++;try{let o=this.connections.get(e);if(!o)throw new Error(`\u8FDE\u63A5\u5B9E\u4F8B\u4E0D\u5B58\u5728: ${e}`);await this.checkConnectionHealth(o,e);let n=Date.now()-r;this.handleHealthCheckSuccess(t,n)}catch(o){let n=Date.now()-r;this.handleHealthCheckFailure(t,o,n)}}async checkConnectionHealth(e,t){if(!e)throw new Error("\u8FDE\u63A5\u5B9E\u4F8B\u4E0D\u5B58\u5728");if(await new Promise(o=>setTimeout(o,10)),!this.connectionStates.get(t)?.connected)throw new Error("\u8FDE\u63A5\u5DF2\u65AD\u5F00")}handleHealthCheckSuccess(e,t){e.successfulRequests++,e.consecutiveFailures=0,e.responseTime=t,e.lastSuccessTime=new Date,this.updateHealthScore(e,!0,t),this.logger.debug(`\u5065\u5EB7\u68C0\u67E5\u6210\u529F: ${e.endpoint}, \u54CD\u5E94\u65F6\u95F4: ${t}ms, \u5065\u5EB7\u5EA6: ${e.healthScore}`)}handleHealthCheckFailure(e,t,r){e.consecutiveFailures++,e.responseTime=r,e.lastError=t.message,this.updateHealthScore(e,!1,r),this.logger.warn(`\u5065\u5EB7\u68C0\u67E5\u5931\u8D25: ${e.endpoint}, \u9519\u8BEF: ${t.message}, \u8FDE\u7EED\u5931\u8D25: ${e.consecutiveFailures}, \u5065\u5EB7\u5EA6: ${e.healthScore}`),e.consecutiveFailures>=3&&e.connected&&this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8FDE\u7EED\u5931\u8D25 ${e.consecutiveFailures} \u6B21\uFF0C\u53EF\u80FD\u9700\u8981\u91CD\u8FDE`)}updateHealthScore(e,t,r){let o=e.healthScore;if(t){let n=5;r<100?n=10:r<500?n=7:r<1e3?n=5:n=2,e.healthScore=Math.min(100,o+n)}else{let n=15;e.consecutiveFailures>=5?n=30:e.consecutiveFailures>=3&&(n=20),e.healthScore=Math.max(0,o-n)}if(e.totalRequests>0){let n=e.successfulRequests/e.totalRequests;n<.5?e.healthScore=Math.max(0,e.healthScore-10):n>.9&&(e.healthScore=Math.min(100,e.healthScore+5))}}classifyConnectionError(e){let t=e.message.toLowerCase();return t.includes("timeout")||t.includes("timed out")?"timeout_error":t.includes("network")||t.includes("connection refused")||t.includes("econnrefused")||t.includes("enotfound")?"network_error":t.includes("auth")||t.includes("unauthorized")||t.includes("forbidden")||t.includes("401")||t.includes("403")?"authentication_error":t.includes("server")||t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")?"server_error":"unknown_error"}calculateReconnectDelay(e){let t=this.options.reconnectInterval,r=this.options.maxReconnectDelay,o=this.options.reconnectBackoffMultiplier,n=e.reconnectAttempts,s;switch(this.options.reconnectStrategy){case"fixed_interval":s=t;break;case"linear_backoff":s=t*(n+1);break;case"exponential_backoff":s=t*o**n;break;case"adaptive":s=this.calculateAdaptiveDelay(e,t,o,n);break;default:s=t*o**n}if(s=Math.min(s,r),this.options.jitterEnabled){let a=s*.1*Math.random();s+=a}return Math.round(s)}calculateAdaptiveDelay(e,t,r,o){let n=t;switch(e.errorType){case"network_error":n=t*r**o;break;case"authentication_error":n=t*r**o*2;break;case"server_error":n=t*(1+o);break;case"timeout_error":n=t*(1+o*.5);break;default:n=t*r**o}if(e.reconnectHistory.length>0){let s=e.reconnectHistory.slice(-5),a=s.filter(l=>l.success).length/s.length;a<.2?n*=1.5:a>.8&&(n*=.8)}return n}shouldReconnect(e){return e.reconnectAttempts>=this.options.maxReconnectAttempts?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8FDE\u6B21\u6570 ${this.options.maxReconnectAttempts}`),!1):e.errorType==="authentication_error"&&e.reconnectAttempts>=3?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8BA4\u8BC1\u9519\u8BEF\uFF0C\u505C\u6B62\u91CD\u8FDE`),!1):e.consecutiveFailures>=10?(this.logger.warn(`\u7AEF\u70B9 ${e.endpoint} \u8FDE\u7EED\u5931\u8D25\u6B21\u6570\u8FC7\u591A\uFF0C\u505C\u6B62\u91CD\u8FDE`),!1):!0}scheduleReconnect(e){let t=this.connectionStates.get(e);if(!t)return;if(t.lastError&&(t.errorType=this.classifyConnectionError(new Error(t.lastError))),!this.shouldReconnect(t)){t.isReconnecting=!1;return}let r=this.reconnectTimers.get(e);r&&clearTimeout(r);let o=this.calculateReconnectDelay(t);t.reconnectDelay=o,t.isReconnecting=!0,t.nextReconnectTime=new Date(Date.now()+o),this.logger.info(`\u5B89\u6392\u91CD\u8FDE ${e}\uFF0C\u5EF6\u8FDF: ${o}ms\uFF0C\u5C1D\u8BD5\u6B21\u6570: ${t.reconnectAttempts+1}\uFF0C\u9519\u8BEF\u7C7B\u578B: ${t.errorType}`);let n=setTimeout(async()=>{this.reconnectTimers.delete(e),await this.performReconnect(e)},o);this.reconnectTimers.set(e,n)}async performReconnect(e){let t=this.connectionStates.get(e),r=this.connections.get(e);if(!(!t||!r)){t.lastReconnectAttempt=new Date,t.isReconnecting=!0,this.logger.info(`\u5F00\u59CB\u91CD\u8FDE ${e}\uFF0C\u7B2C ${t.reconnectAttempts+1} \u6B21\u5C1D\u8BD5`);try{await this.connectSingleEndpoint(e,r),t.isReconnecting=!1,t.reconnectHistory.push({timestamp:new Date,success:!0,delay:t.reconnectDelay}),this.logger.info(`\u91CD\u8FDE\u6210\u529F ${e}`)}catch(o){t.isReconnecting=!1,t.reconnectHistory.push({timestamp:new Date,success:!1,error:o instanceof Error?o.message:String(o),delay:t.reconnectDelay}),this.logger.error(`\u91CD\u8FDE\u5931\u8D25 ${e}:`,o),this.scheduleReconnect(e)}t.reconnectHistory.length>20&&(t.reconnectHistory=t.reconnectHistory.slice(-20))}}clearAllReconnectTimers(){for(let[,e]of this.reconnectTimers)clearTimeout(e);this.reconnectTimers.clear()}}});async function ds(i){return console.log("\u{1F680} \u6B63\u5728\u521D\u59CB\u5316 XiaozhiConnectionManager \u5355\u4F8B..."),new wt(i)}async function Po(i){if(ie&&j==="initialized")return ie;if(X&&j==="initializing")return X;j==="failed"&&mr(),j="initializing",X=ds(i);try{return ie=await X,j="initialized",_e=`xiaozhi-connection-manager-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,Qe=null,console.log(`\u2705 XiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u6210\u529F\uFF0C\u5B9E\u4F8BID: ${_e}`),ie}catch(e){throw j="failed",Qe=e,X=null,console.error("\u274C XiaozhiConnectionManager \u5355\u4F8B\u521D\u59CB\u5316\u5931\u8D25:",e.message),e}}async function wo(){if(j==="cleanup"){console.log("\u26A0\uFE0F XiaozhiConnectionManager \u5355\u4F8B\u5DF2\u5728\u6E05\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u91CD\u590D\u6E05\u7406");return}console.log("\u{1F9F9} \u6B63\u5728\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90..."),j="cleanup";try{if(X){try{await(await X).cleanup()}catch(i){console.error("\u6E05\u7406\u521D\u59CB\u5316\u4E2D\u7684\u5B9E\u4F8B\u5931\u8D25:",i.message)}X=null}ie&&(await ie.cleanup(),ie=null),j="not_initialized",Qe=null,_e=null,console.log("\u2705 XiaozhiConnectionManager \u5355\u4F8B\u8D44\u6E90\u6E05\u7406\u5B8C\u6210")}catch(i){throw console.error("\u274C XiaozhiConnectionManager \u5355\u4F8B\u6E05\u7406\u5931\u8D25:",i.message),mr(),i}}function mr(){console.log("\u{1F504} \u91CD\u7F6E XiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001..."),X&&(X=null),ie=null,j="not_initialized",Qe=null,_e=null,console.log("\u2705 XiaozhiConnectionManager \u5355\u4F8B\u72B6\u6001\u5DF2\u91CD\u7F6E")}function ms(){return j==="initialized"&&ie!==null}function fs(){return{state:j,initializationTime:_e?new Date:void 0,lastError:Qe||void 0,instanceId:_e||void 0}}async function Cs(i){return console.log("\u{1F504} \u5F3A\u5236\u91CD\u65B0\u521D\u59CB\u5316 XiaozhiConnectionManager \u5355\u4F8B..."),await wo(),Po(i)}function vs(){return ie}async function Ss(){if(j==="initialized")return!0;if(j==="initializing"&&X)try{return await X,!0}catch{return!1}return!1}var ie,X,j,Qe,_e,Le,bo=m(()=>{"use strict";Mo();ie=null,X=null,j="not_initialized",Qe=null,_e=null;c(ds,"createInstance");c(Po,"getInstance");c(wo,"cleanup");c(mr,"reset");c(ms,"isInitialized");c(fs,"getStatus");c(Cs,"forceReinitialize");c(vs,"getCurrentInstance");c(Ss,"waitForInitialization");Le={getInstance:Po,cleanup:wo,reset:mr,isInitialized:ms,getStatus:fs,forceReinitialize:Cs,getCurrentInstance:vs,waitForInitialization:Ss};process.on("exit",()=>{Le.isInitialized()&&(console.log("\u{1F504} \u8FDB\u7A0B\u9000\u51FA\uFF0C\u6B63\u5728\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B..."),Le.reset())});process.on("uncaughtException",async i=>{console.error("\u{1F4A5} \u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B:",i);try{await Le.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}});process.on("unhandledRejection",async i=>{console.error("\u{1F4A5} \u672A\u5904\u7406\u7684Promise\u62D2\u7EDD\uFF0C\u6E05\u7406 XiaozhiConnectionManager \u5355\u4F8B:",i);try{await Le.cleanup()}catch(e){console.error("\u6E05\u7406\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e)}})});import{EventEmitter as ys}from"events";function K(){return He||(He=new fr),He}function Ro(){He&&(He.destroy(),He=null)}var fr,He,ye=m(()=>{"use strict";S();fr=class extends ys{static{c(this,"EventBus")}logger;eventStats=new Map;maxListeners=50;constructor(){super(),this.logger=g.withTag("EventBus"),this.setMaxListeners(this.maxListeners),this.setupErrorHandling()}setupErrorHandling(){this.on("error",e=>{this.logger.error("EventBus \u5185\u90E8\u9519\u8BEF:",e)}),this.on("newListener",e=>{let t=this.listenerCount(e);t>this.maxListeners*.8&&this.logger.warn(`\u4E8B\u4EF6 ${e} \u7684\u76D1\u542C\u5668\u6570\u91CF\u8FC7\u591A: ${t}`)})}emitEvent(e,t){try{return this.updateEventStats(e),this.logger.debug(`\u53D1\u5C04\u4E8B\u4EF6: ${e}`,t),this.emit(e,t)}catch(r){return this.logger.error(`\u53D1\u5C04\u4E8B\u4EF6\u5931\u8D25: ${e}`,r),!1}}onEvent(e,t){return this.logger.debug(`\u6DFB\u52A0\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.on(e,t)}onceEvent(e,t){return this.logger.debug(`\u6DFB\u52A0\u4E00\u6B21\u6027\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.once(e,t)}offEvent(e,t){return this.logger.debug(`\u79FB\u9664\u4E8B\u4EF6\u76D1\u542C\u5668: ${e}`),this.off(e,t)}updateEventStats(e){let t=this.eventStats.get(e)||{count:0,lastEmitted:new Date};t.count++,t.lastEmitted=new Date,this.eventStats.set(e,t)}getEventStats(){let e={};for(let[t,r]of this.eventStats)e[t]={...r};return e}getListenerStats(){let e={};for(let t of this.eventNames())e[t]=this.listenerCount(t);return e}clearEventStats(){this.eventStats.clear(),this.logger.info("\u4E8B\u4EF6\u7EDF\u8BA1\u5DF2\u6E05\u7406")}getStatus(){return{totalEvents:this.eventStats.size,totalListeners:Object.values(this.getListenerStats()).reduce((e,t)=>e+t,0),eventStats:this.getEventStats(),listenerStats:this.getListenerStats()}}destroy(){this.removeAllListeners(),this.eventStats.clear(),this.logger.info("EventBus \u5DF2\u9500\u6BC1")}},He=null;c(K,"getEventBus");c(Ro,"destroyEventBus")});var ae,et=m(()=>{"use strict";S();Y();ye();ae=class{static{c(this,"ConfigService")}logger;eventBus;constructor(){this.logger=g.withTag("ConfigService"),this.eventBus=K()}async getConfig(){try{let e=d.getConfig();return this.logger.debug("\u83B7\u53D6\u914D\u7F6E\u6210\u529F"),e}catch(e){throw this.logger.error("\u83B7\u53D6\u914D\u7F6E\u5931\u8D25:",e),this.eventBus.emitEvent("config:error",{error:e instanceof Error?e:new Error(String(e)),operation:"getConfig"}),e}}async updateConfig(e,t="unknown"){try{this.logger.info(`\u5F00\u59CB\u66F4\u65B0\u914D\u7F6E\uFF0C\u6765\u6E90: ${t}`),this.validateConfig(e),e.mcpEndpoint!==d.getMcpEndpoint()&&d.updateMcpEndpoint(e.mcpEndpoint);let r=d.getMcpServers();for(let[o,n]of Object.entries(e.mcpServers))JSON.stringify(r[o])!==JSON.stringify(n)&&d.updateMcpServer(o,n);for(let o of Object.keys(r))o in e.mcpServers||(d.removeMcpServer(o),d.removeServerToolsConfig(o));if(e.connection&&d.updateConnectionConfig(e.connection),e.modelscope&&d.updateModelScopeConfig(e.modelscope),e.webUI&&d.updateWebUIConfig(e.webUI),e.mcpServerConfig)for(let[o,n]of Object.entries(e.mcpServerConfig))for(let[s,a]of Object.entries(n.tools))d.setToolEnabled(o,s,a.enable);if(e?.platforms)for(let[o,n]of Object.entries(e.platforms))d.updatePlatformConfig(o,n);this.logger.info("\u914D\u7F6E\u66F4\u65B0\u6210\u529F"),this.eventBus.emitEvent("config:updated",{config:e,source:t})}catch(r){throw this.logger.error("\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",r),this.eventBus.emitEvent("config:error",{error:r instanceof Error?r:new Error(String(r)),operation:"updateConfig"}),r}}getMcpEndpoint(){try{return d.getMcpEndpoint()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",e),e}}getMcpEndpoints(){try{return d.getMcpEndpoints()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",e),e}}getMcpServers(){try{return d.getMcpServers()}catch(e){throw this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",e),e}}getConnectionConfig(){try{return d.getConnectionConfig()}catch(e){throw this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",e),e}}getWebUIPort(){try{return d.getWebUIPort()||9999}catch(e){return this.logger.error("\u83B7\u53D6 Web UI \u7AEF\u53E3\u5931\u8D25:",e),9999}}validateConfig(e){if(!e||typeof e!="object")throw new Error("\u914D\u7F6E\u5FC5\u987B\u662F\u6709\u6548\u7684\u5BF9\u8C61");if(!e.mcpEndpoint)throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B mcpEndpoint");if(!e.mcpServers||typeof e.mcpServers!="object")throw new Error("\u914D\u7F6E\u5FC5\u987B\u5305\u542B\u6709\u6548\u7684 mcpServers")}configExists(){return d.configExists()}async reloadConfig(){try{this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E"),d.reloadConfig();let e=await this.getConfig();return this.eventBus.emitEvent("config:updated",{config:e,source:"reload"}),e}catch(e){throw this.logger.error("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25:",e),this.eventBus.emitEvent("config:error",{error:e instanceof Error?e:new Error(String(e)),operation:"reloadConfig"}),e}}getConfigPath(){return d.getConfigPath()}}});var bt,Io=m(()=>{"use strict";S();et();bt=class{static{c(this,"ConfigApiHandler")}logger;configService;constructor(){this.logger=g.withTag("ConfigApiHandler"),this.configService=new ae}createErrorResponse(e,t,r){return{error:{code:e,message:t,details:r}}}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}async getConfig(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u914D\u7F6E\u8BF7\u6C42");let t=await this.configService.getConfig();return this.logger.info("\u83B7\u53D6\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async updateConfig(e){try{this.logger.debug("\u5904\u7406\u66F4\u65B0\u914D\u7F6E\u8BF7\u6C42");let t=await e.req.json();if(!t||typeof t!="object"){let r=this.createErrorResponse("INVALID_REQUEST_BODY","\u8BF7\u6C42\u4F53\u5FC5\u987B\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61");return e.json(r,400)}return await this.configService.updateConfig(t,"http-api"),this.logger.info("\u914D\u7F6E\u66F4\u65B0\u6210\u529F"),e.json(this.createSuccessResponse(null,"\u914D\u7F6E\u66F4\u65B0\u6210\u529F"))}catch(t){this.logger.error("\u914D\u7F6E\u66F4\u65B0\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_UPDATE_ERROR",t instanceof Error?t.message:"\u914D\u7F6E\u66F4\u65B0\u5931\u8D25");return e.json(r,400)}}async getMcpEndpoint(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u7AEF\u70B9\u8BF7\u6C42");let t=this.configService.getMcpEndpoint();return this.logger.debug("\u83B7\u53D6 MCP \u7AEF\u70B9\u6210\u529F"),e.json(this.createSuccessResponse({endpoint:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_ENDPOINT_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u7AEF\u70B9\u5931\u8D25");return e.json(r,500)}}async getMcpEndpoints(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u8BF7\u6C42");let t=this.configService.getMcpEndpoints();return this.logger.debug("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u6210\u529F"),e.json(this.createSuccessResponse({endpoints:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_ENDPOINTS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u7AEF\u70B9\u5217\u8868\u5931\u8D25");return e.json(r,500)}}async getMcpServers(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u8BF7\u6C42");let t=this.configService.getMcpServers();return this.logger.debug("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse({servers:t}))}catch(t){this.logger.error("\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("MCP_SERVERS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6 MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async getConnectionConfig(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u8BF7\u6C42");let t=this.configService.getConnectionConfig();return this.logger.debug("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse({connection:t}))}catch(t){this.logger.error("\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONNECTION_CONFIG_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async reloadConfig(e){try{this.logger.info("\u5904\u7406\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u8BF7\u6C42");let t=await this.configService.reloadConfig();return this.logger.info("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u6210\u529F"),e.json(this.createSuccessResponse(t,"\u914D\u7F6E\u91CD\u65B0\u52A0\u8F7D\u6210\u529F"))}catch(t){this.logger.error("\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_RELOAD_ERROR",t instanceof Error?t.message:"\u91CD\u65B0\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25");return e.json(r,500)}}async getConfigPath(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u8BF7\u6C42");let t=this.configService.getConfigPath();return this.logger.debug("\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u6210\u529F"),e.json(this.createSuccessResponse({path:t}))}catch(t){this.logger.error("\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_PATH_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25");return e.json(r,500)}}async checkConfigExists(e){try{this.logger.debug("\u5904\u7406\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u8BF7\u6C42");let t=this.configService.configExists();return this.logger.debug(`\u914D\u7F6E\u5B58\u5728\u68C0\u67E5\u7ED3\u679C: ${t}`),e.json(this.createSuccessResponse({exists:t}))}catch(t){this.logger.error("\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u5931\u8D25:",t);let r=this.createErrorResponse("CONFIG_EXISTS_CHECK_ERROR",t instanceof Error?t.message:"\u68C0\u67E5\u914D\u7F6E\u662F\u5426\u5B58\u5728\u5931\u8D25");return e.json(r,500)}}}});async function Ts(i,e=3,t=1e3){for(let r=1;r<=e;r++)try{return await i()}catch(o){if(r===e)throw o;let n=t*2**(r-1);g.warn(`\u6263\u5B50 API \u8C03\u7528\u5931\u8D25\uFF0C${n}ms \u540E\u91CD\u8BD5 (${r}/${e})`,o),await new Promise(s=>setTimeout(s,n))}throw new Error("Max retry attempts exceeded")}function Es(i,e){let t=i.status;return t===401?new ce("\u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6263\u5B50 API Token \u914D\u7F6E","AUTH_FAILED",401,e):t===429?new ce("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED",429,e):t>=500?new ce("\u6263\u5B50\u670D\u52A1\u5668\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","SERVER_ERROR",t,e):new ce(e?.msg||`API \u8C03\u7528\u5931\u8D25: ${i.statusText}`,"API_ERROR",t,e)}var Cr,ce,Rt,$o=m(()=>{"use strict";S();Cr=class{static{c(this,"CozeApiCache")}cache=new Map;TTL={workspaces:1800*1e3,workflows:300*1e3};set(e,t,r){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:this.TTL[r]})}get(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(e){if(!e){this.cache.clear();return}for(let t of this.cache.keys())t.includes(e)&&this.cache.delete(t)}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}},ce=class extends Error{static{c(this,"CozeApiErrorImpl")}code;statusCode;response;constructor(e,t,r,o){super(e),this.name="CozeApiError",this.code=t,this.statusCode=r,this.response=o}};c(Ts,"retryWithBackoff");c(Es,"handleCozeApiError");Rt=class{static{c(this,"CozeApiService")}cache=new Cr;token;API_BASE_URL="https://api.coze.cn";TIMEOUT=1e4;RETRY_ATTEMPTS=3;constructor(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("\u6263\u5B50 API Token \u4E0D\u80FD\u4E3A\u7A7A");this.token=e.trim()}async getWorkspaces(){let e="workspaces",t=this.cache.get(e);if(t)return g.debug("\u4ECE\u7F13\u5B58\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868"),t;g.info("\u83B7\u53D6\u6263\u5B50\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868");let r=await this.request("/v1/workspaces");if(r.code!==0)throw new ce(r.msg||"\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25","API_ERROR",void 0,r);let o=r.data.workspaces;return this.cache.set(e,o,"workspaces"),g.info(`\u6210\u529F\u83B7\u53D6 ${o.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),o}async getWorkflows(e){let{workspace_id:t,page_num:r=1,page_size:o=20}=e;if(!t||typeof t!="string")throw new Error("\u5DE5\u4F5C\u7A7A\u95F4ID\u4E0D\u80FD\u4E3A\u7A7A");let n=`workflows:${t}:${r}:${o}`,s=this.cache.get(n);if(s)return g.debug(`\u4ECE\u7F13\u5B58\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868: ${t}`),s;g.info(`\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684\u5DE5\u4F5C\u6D41\u5217\u8868 (\u9875\u7801: ${r}, \u6BCF\u9875: ${o})`);let a=new URLSearchParams({workspace_id:t,page_num:r.toString(),page_size:o.toString(),workflow_mode:"workflow"}),l=await this.request(`/v1/workflows?${a}`);if(l.code!==0)throw new ce(l.msg||"\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25","API_ERROR",void 0,l);let h={items:l.data.items,hasMore:l.data.has_more};return this.cache.set(n,h,"workflows"),g.info(`\u6210\u529F\u83B7\u53D6 ${h.items.length} \u4E2A\u5DE5\u4F5C\u6D41\uFF0ChasMore: ${h.hasMore}`),h}async request(e){return Ts(async()=>{let t=`${this.API_BASE_URL}${e}`;g.debug(`\u53D1\u8D77\u6263\u5B50 API \u8BF7\u6C42: ${t}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.TIMEOUT);try{let n=await fetch(t,{headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},signal:r.signal});clearTimeout(o);let s;try{s=await n.json()}catch(a){throw g.error("\u89E3\u6790\u54CD\u5E94 JSON \u5931\u8D25:",a),new ce("\u54CD\u5E94\u6570\u636E\u683C\u5F0F\u9519\u8BEF","PARSE_ERROR",n.status)}if(!n.ok)throw Es(n,s);return s}catch(n){throw clearTimeout(o),n instanceof Error&&n.name==="AbortError"?new ce(`\u8BF7\u6C42\u8D85\u65F6 (${this.TIMEOUT}ms)`,"TIMEOUT",void 0):n}},this.RETRY_ATTEMPTS)}clearCache(e){this.cache.clear(e),g.info(`\u6E05\u9664\u6263\u5B50 API \u7F13\u5B58${e?` (\u6A21\u5F0F: ${e})`:""}`)}getCacheStats(){return this.cache.getStats()}}});function It(i,e){return{success:!0,data:i,message:e}}function A(i,e,t){return{success:!1,message:i,error:e?{code:e,details:t}:void 0}}function $t(){let i=d.getCozeToken();if(!i)throw new Error("\u6263\u5B50 API Token \u672A\u914D\u7F6E\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E platforms.coze.token");return new Rt(i)}var Te,xo=m(()=>{"use strict";S();Y();$o();c(It,"createSuccessResponse");c(A,"createErrorResponse");c($t,"getCozeApiService");Te=class{static{c(this,"CozeApiHandler")}static async getWorkspaces(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=await $t().getWorkspaces();return g.info(`\u6210\u529F\u83B7\u53D6 ${r.length} \u4E2A\u5DE5\u4F5C\u7A7A\u95F4`),e.json(It({workspaces:r}))}catch(t){return g.error("\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25:",t),t instanceof Error&&t.code==="AUTH_FAILED"?e.json(A("\u6263\u5B50 API \u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 Token \u914D\u7F6E","AUTH_FAILED"),401):t instanceof Error&&t.code==="RATE_LIMITED"?e.json(A("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(A("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4\u5217\u8868\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async getWorkflows(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let t=e.req.query("workspace_id"),r=Number.parseInt(e.req.query("page_num")||"1",10),o=Number.parseInt(e.req.query("page_size")||"20",10);if(!t)return g.warn("\u7F3A\u5C11 workspace_id \u53C2\u6570"),e.json(A("\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570: workspace_id","MISSING_PARAMETER"),400);if(r<1||r>1e3)return e.json(A("page_num \u5FC5\u987B\u5728 1-1000 \u4E4B\u95F4","INVALID_PARAMETER"),400);if(o<1||o>100)return e.json(A("page_size \u5FC5\u987B\u5728 1-100 \u4E4B\u95F4","INVALID_PARAMETER"),400);let n={workspace_id:t,page_num:r,page_size:o},a=await $t().getWorkflows(n);g.info(`\u6210\u529F\u83B7\u53D6\u5DE5\u4F5C\u7A7A\u95F4 ${t} \u7684 ${a.items.length} \u4E2A\u5DE5\u4F5C\u6D41`);let l=d.getCustomMCPTools(),h=a.items.map(u=>{let p=l.find(C=>C.handler.type==="proxy"&&C.handler.platform==="coze"&&C.handler.config.workflow_id===u.workflow_id);return{...u,isAddedAsTool:!!p,toolName:p?.name||null}});return g.info(`\u5DE5\u4F5C\u6D41\u5DE5\u5177\u72B6\u6001\u68C0\u67E5\u5B8C\u6210\uFF0C\u5171 ${h.filter(u=>u.isAddedAsTool).length} \u4E2A\u5DE5\u4F5C\u6D41\u5DF2\u6DFB\u52A0\u4E3A\u5DE5\u5177`),e.json(It({items:h,has_more:a.hasMore,page_num:r,page_size:o,total_count:a.items.length}))}catch(t){return g.error("\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25:",t),t instanceof Error&&t.code==="AUTH_FAILED"?e.json(A("\u6263\u5B50 API \u8BA4\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 Token \u914D\u7F6E","AUTH_FAILED"),401):t instanceof Error&&t.code==="RATE_LIMITED"?e.json(A("\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","RATE_LIMITED"),429):t instanceof Error&&t.code==="TIMEOUT"?e.json(A("\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5","TIMEOUT"),408):e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u5DE5\u4F5C\u6D41\u5217\u8868\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async clearCache(e){try{if(g.info("\u5904\u7406\u6E05\u9664\u6263\u5B50 API \u7F13\u5B58\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let t=e.req.query("pattern"),r=$t(),o=r.getCacheStats();r.clearCache(t);let n=r.getCacheStats();return g.info(`\u7F13\u5B58\u6E05\u9664\u5B8C\u6210\uFF0C\u6E05\u9664\u524D: ${o.size} \u9879\uFF0C\u6E05\u9664\u540E: ${n.size} \u9879`),e.json(It({cleared:o.size-n.size,remaining:n.size,pattern:t||"all"},"\u7F13\u5B58\u6E05\u9664\u6210\u529F"))}catch(t){return g.error("\u6E05\u9664\u7F13\u5B58\u5931\u8D25:",t),e.json(A(t instanceof Error?t.message:"\u6E05\u9664\u7F13\u5B58\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}static async getCacheStats(e){try{if(g.info("\u5904\u7406\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u8BF7\u6C42"),!d.isCozeConfigValid())return g.warn("\u6263\u5B50\u914D\u7F6E\u65E0\u6548"),e.json(A("\u6263\u5B50\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5 platforms.coze.token \u914D\u7F6E","CONFIG_INVALID"),400);let r=$t().getCacheStats();return e.json(It(r))}catch(t){return g.error("\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25:",t),e.json(A(t instanceof Error?t.message:"\u83B7\u53D6\u7F13\u5B58\u7EDF\u8BA1\u4FE1\u606F\u5931\u8D25","INTERNAL_ERROR",process.env.NODE_ENV==="development"&&t instanceof Error?t.stack:void 0),500)}}}});var xt,Oo=m(()=>{"use strict";S();et();xt=class{static{c(this,"HeartbeatHandler")}logger;statusService;notificationService;configService;constructor(e,t){this.logger=g.withTag("HeartbeatHandler"),this.statusService=e,this.notificationService=t,this.configService=new ae}async handleClientStatus(e,t,r){try{this.logger.debug(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0: ${r}`,t.data);let o={...t.data,lastHeartbeat:Date.now()};this.statusService.updateClientInfo(o,`websocket-${r}`),await this.sendLatestConfig(e,r),this.logger.debug(`\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u6210\u529F: ${r}`)}catch(o){this.logger.error(`\u5904\u7406\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25: ${r}`,o),this.sendError(e,"CLIENT_STATUS_ERROR",o instanceof Error?o.message:"\u5BA2\u6237\u7AEF\u72B6\u6001\u66F4\u65B0\u5931\u8D25")}}async sendLatestConfig(e,t){try{let o={type:"configUpdate",data:await this.configService.getConfig(),timestamp:Date.now()};e.send(JSON.stringify(o)),this.logger.debug(`\u6700\u65B0\u914D\u7F6E\u5DF2\u53D1\u9001\u7ED9\u5BA2\u6237\u7AEF: ${t}`)}catch(r){this.logger.error(`\u53D1\u9001\u6700\u65B0\u914D\u7F6E\u5931\u8D25: ${t}`,r)}}sendError(e,t,r){try{let o={type:"error",error:{code:t,message:r,timestamp:Date.now()}};e.send(JSON.stringify(o))}catch(o){this.logger.error("\u53D1\u9001\u9519\u8BEF\u6D88\u606F\u5931\u8D25:",o)}}checkHeartbeatTimeout(){let e=this.statusService.getLastHeartbeat(),t=Date.now();e&&t-e>35e3&&(this.logger.warn("\u5BA2\u6237\u7AEF\u5FC3\u8DF3\u8D85\u65F6\uFF0C\u6807\u8BB0\u4E3A\u65AD\u5F00\u8FDE\u63A5"),this.statusService.updateClientInfo({status:"disconnected"},"heartbeat-timeout"))}startHeartbeatMonitoring(){return this.logger.info("\u542F\u52A8\u5FC3\u8DF3\u76D1\u63A7"),setInterval(()=>{this.checkHeartbeatTimeout(),this.cleanupDisconnectedClients()},1e4)}cleanupDisconnectedClients(){try{this.notificationService.cleanupDisconnectedClients()}catch(e){this.logger.error("\u6E05\u7406\u65AD\u5F00\u8FDE\u63A5\u7684\u5BA2\u6237\u7AEF\u5931\u8D25:",e)}}stopHeartbeatMonitoring(e){this.logger.info("\u505C\u6B62\u5FC3\u8DF3\u76D1\u63A7"),clearInterval(e)}getHeartbeatStats(){return{lastHeartbeat:this.statusService.getLastHeartbeat(),isConnected:this.statusService.isClientConnected(),clientStats:this.notificationService.getClientStats()}}handleClientConnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5EFA\u7ACB: ${e}`),this.statusService.updateClientInfo({status:"connected",lastHeartbeat:Date.now()},`websocket-connect-${e}`)}handleClientDisconnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5\u65AD\u5F00: ${e}`),this.statusService.updateClientInfo({status:"disconnected"},`websocket-disconnect-${e}`)}sendHeartbeatResponse(e,t){try{let r={type:"heartbeatResponse",data:{timestamp:Date.now(),status:"ok"}};e.send(JSON.stringify(r)),this.logger.debug(`\u5FC3\u8DF3\u54CD\u5E94\u5DF2\u53D1\u9001: ${t}`)}catch(r){this.logger.error(`\u53D1\u9001\u5FC3\u8DF3\u54CD\u5E94\u5931\u8D25: ${t}`,r)}}validateHeartbeatMessage(e){return e&&typeof e=="object"&&e.type==="clientStatus"&&e.data&&typeof e.data=="object"}}});import{randomUUID as Ms}from"crypto";var Ot,Ao=m(()=>{"use strict";S();gr();Pt();Ot=class{static{c(this,"MCPRouteHandler")}logger;mcpMessageHandler=null;clients=new Map;config;metrics;cleanupInterval=null;startTime;constructor(e={}){this.logger=g.withTag("MCPRouteHandler"),this.config={maxClients:e.maxClients??100,connectionTimeout:e.connectionTimeout??3e5,heartbeatInterval:e.heartbeatInterval??3e4,maxMessageSize:e.maxMessageSize??1024*1024,enableMetrics:e.enableMetrics??!0},this.metrics={totalConnections:0,activeConnections:0,totalMessages:0,errorCount:0,averageResponseTime:0,uptime:0},this.startTime=new Date,this.startCleanupTask(),this.logger.info("MCPRouteHandler \u521D\u59CB\u5316\u5B8C\u6210",{maxClients:this.config.maxClients,connectionTimeout:this.config.connectionTimeout,heartbeatInterval:this.config.heartbeatInterval})}startCleanupTask(){this.cleanupInterval=setInterval(()=>{this.cleanupStaleConnections(),this.updateMetrics()},6e4)}stopCleanupTask(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}cleanupStaleConnections(){let e=new Date,t=[];for(let[r,o]of this.clients.entries())(e.getTime()-o.lastActivity.getTime()>this.config.connectionTimeout||!o.isAlive)&&t.push(r);for(let r of t)this.logger.info(`\u6E05\u7406\u8FC7\u671F\u8FDE\u63A5: ${r}`),this.handleClientDisconnect(r,"cleanup");t.length>0&&this.logger.info(`\u6E05\u7406\u4E86 ${t.length} \u4E2A\u8FC7\u671F\u8FDE\u63A5`)}updateMetrics(){this.config.enableMetrics&&(this.metrics.activeConnections=this.clients.size,this.metrics.uptime=Date.now()-this.startTime.getTime(),this.logger.debug("\u8FDE\u63A5\u7EDF\u8BA1",{activeConnections:this.metrics.activeConnections,totalConnections:this.metrics.totalConnections,totalMessages:this.metrics.totalMessages,errorCount:this.metrics.errorCount}))}async initializeMessageHandler(){if(!this.mcpMessageHandler)try{let e=await V.getInstance();this.mcpMessageHandler=new De(e),this.logger.info("MCP \u6D88\u606F\u5904\u7406\u5668\u521D\u59CB\u5316\u6210\u529F")}catch(e){throw this.logger.error("MCP \u6D88\u606F\u5904\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",e),this.metrics.errorCount++,e}}async handlePost(e){let t=Date.now(),r=null;try{this.logger.debug("\u5904\u7406 MCP POST \u8BF7\u6C42");let o=e.req.query("sessionId");if(o)return await this.handleSSEMessage(e,o);let n=e.req.header("content-length");if(n&&Number.parseInt(n)>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Request too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);if(!e.req.header("content-type")?.includes("application/json"))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Content-Type must be application/json",null);let a=e.req.header("mcp-protocol-version")||e.req.header("MCP-Protocol-Version")||e.req.header("Mcp-Protocol-Version"),l=["2024-11-05","2025-06-18"];a&&!l.includes(a)&&this.logger.warn(`\u4E0D\u652F\u6301\u7684 MCP \u534F\u8BAE\u7248\u672C: ${a}\uFF0C\u652F\u6301\u7684\u7248\u672C: ${l.join(", ")}`);let h;try{let C=await e.req.text();if(C.length>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);h=JSON.parse(C),r=h.id||null}catch{return this.metrics.errorCount++,this.createErrorResponse(-32700,"Parse error: Invalid JSON",null)}if(!this.validateMessage(h))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Message does not conform to JSON-RPC 2.0",r);await this.initializeMessageHandler();let u=await this.mcpMessageHandler.handleMessage(h);this.metrics.totalMessages++;let p=Date.now()-t;return this.metrics.averageResponseTime=(this.metrics.averageResponseTime*(this.metrics.totalMessages-1)+p)/this.metrics.totalMessages,this.logger.debug("MCP POST \u8BF7\u6C42\u5904\u7406\u6210\u529F",{method:h.method,messageId:r,responseTime:p,isNotification:u===null}),u===null?new Response(null,{status:204,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":p.toString()}}):e.json(u,200,{"Content-Type":"application/json","MCP-Protocol-Version":"2024-11-05","X-Response-Time":p.toString()})}catch(o){this.metrics.errorCount++;let n=Date.now()-t;this.logger.error("\u5904\u7406 MCP POST \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:o instanceof Error?o.message:String(o),messageId:r,responseTime:n,stack:o instanceof Error?o.stack:void 0});let s=o instanceof Error?o.message:String(o);return this.createErrorResponse(-32603,`Internal error: ${s}`,r)}}async handleSSEMessage(e,t){let r=Date.now(),o=null;try{this.logger.debug(`\u5904\u7406 SSE \u6D88\u606F (\u4F1A\u8BDD: ${t})`);let n=this.clients.get(t);if(!n)return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Invalid or missing sessionId",null);n.lastActivity=new Date;let s=e.req.header("content-length");if(s&&Number.parseInt(s)>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);let a;try{let u=await e.req.text();if(u.length>this.config.maxMessageSize)return this.metrics.errorCount++,this.createErrorResponse(-32600,`Message too large: Maximum size is ${this.config.maxMessageSize} bytes`,null);a=JSON.parse(u),o=a.id||null}catch{return this.metrics.errorCount++,this.createErrorResponse(-32700,"Parse error: Invalid JSON",null)}if(!this.validateMessage(a))return this.metrics.errorCount++,this.createErrorResponse(-32600,"Invalid Request: Message does not conform to JSON-RPC 2.0",o);await this.initializeMessageHandler();let l=await this.mcpMessageHandler.handleMessage(a);if(n.messageCount++,this.metrics.totalMessages++,l!==null&&n.writer&&n.isAlive)try{await this.sendSSEEvent(n.writer,"message",JSON.stringify(l))}catch(u){this.logger.warn(`SSE \u5199\u5165\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${t}`,u),n.isAlive=!1}let h=Date.now()-r;return this.logger.debug(`SSE \u6D88\u606F\u5904\u7406\u5B8C\u6210 (\u4F1A\u8BDD: ${t})`,{method:a.method,messageId:o,responseTime:h,messageCount:n.messageCount,isNotification:l===null}),new Response(null,{status:202,headers:{"MCP-Protocol-Version":"2024-11-05","X-Response-Time":h.toString()}})}catch(n){this.metrics.errorCount++;let s=Date.now()-r;this.logger.error(`\u5904\u7406 SSE \u6D88\u606F\u65F6\u51FA\u9519 (\u4F1A\u8BDD: ${t}):`,{error:n instanceof Error?n.message:String(n),messageId:o,responseTime:s,stack:n instanceof Error?n.stack:void 0});let a=n instanceof Error?n.message:String(n);return this.createErrorResponse(-32603,`Internal error: ${a}`,o)}}async handleGet(e){try{if(this.logger.debug("\u5904\u7406 MCP GET \u8BF7\u6C42\uFF08SSE \u8FDE\u63A5\uFF09"),this.clients.size>=this.config.maxClients)return this.metrics.errorCount++,e.json({jsonrpc:"2.0",error:{code:-32e3,message:"Server busy: Maximum client connections reached",data:{maxClients:this.config.maxClients}},id:null},503);let t=Date.now().toString(),r=Ms(),o=new Date,n=e.req.header("user-agent"),s=e.req.header("x-forwarded-for")||e.req.header("x-real-ip")||"unknown";this.logger.info(`SSE \u5BA2\u6237\u7AEF\u8FDE\u63A5: ${t} (\u4F1A\u8BDD: ${r})`,{userAgent:n,remoteAddress:s});let{readable:a,writable:l}=new TransformStream,h=l.getWriter(),u=new AbortController,p={id:t,sessionId:r,response:new Response(a),connectedAt:o,lastActivity:o,writer:h,abortController:u,isAlive:!0,messageCount:0,userAgent:n,remoteAddress:s};this.clients.set(r,p),this.metrics.totalConnections++,this.metrics.activeConnections=this.clients.size;try{await this.sendSSEEvent(h,"connected",JSON.stringify({sessionId:r,endpoint:`/mcp?sessionId=${r}`,timestamp:o.toISOString(),protocolVersion:"2024-11-05"}))}catch(b){this.logger.error(`\u521D\u59CB SSE \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25: ${r}`,b),p.isAlive=!1}this.startHeartbeat(p);let C=new Response(a,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no","MCP-Protocol-Version":"2024-11-05","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type, MCP-Protocol-Version"}}),T=c(()=>{this.handleClientDisconnect(r,t)},"handleDisconnect");return e.req.raw.signal?.addEventListener("abort",T),u.signal.addEventListener("abort",T),C}catch(t){return this.metrics.errorCount++,this.logger.error("\u5904\u7406 MCP GET \u8BF7\u6C42\u65F6\u51FA\u9519:",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),e.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"},id:null},500)}}startHeartbeat(e){e.heartbeatInterval&&clearInterval(e.heartbeatInterval),e.heartbeatInterval=setInterval(async()=>{if(!e.isAlive||!e.writer){this.stopHeartbeat(e);return}try{await this.sendSSEEvent(e.writer,"heartbeat",JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId})),this.logger.debug(`\u5FC3\u8DF3\u53D1\u9001\u6210\u529F: ${e.sessionId}`)}catch(t){this.logger.warn(`\u5FC3\u8DF3\u53D1\u9001\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${e.sessionId}`,t),e.isAlive=!1,this.stopHeartbeat(e)}},this.config.heartbeatInterval)}stopHeartbeat(e){e.heartbeatInterval&&(clearInterval(e.heartbeatInterval),e.heartbeatInterval=void 0)}async sendSSEEvent(e,t,r){try{let o=`event: ${t}
|
|
18
39
|
data: ${r}
|
|
19
40
|
|
|
20
|
-
`;await e.write(new TextEncoder().encode(n))}catch(n){throw this.logger.error("\u53D1\u9001 SSE \u4E8B\u4EF6\u5931\u8D25:",n),n}}handleClientDisconnect(e,t){let r=this.clients.get(e);if(!r)return;let n=Date.now()-r.connectedAt.getTime();this.logger.info(`SSE \u5BA2\u6237\u7AEF\u65AD\u5F00\u8FDE\u63A5: ${r.id} (\u4F1A\u8BDD: ${e})`,{reason:t,duration:n,messageCount:r.messageCount,userAgent:r.userAgent,remoteAddress:r.remoteAddress}),this.stopHeartbeat(r),r.abortController&&r.abortController.abort();try{r.writer&&r.writer.close()}catch(o){this.logger.debug("\u5173\u95ED SSE writer \u65F6\u51FA\u9519:",o)}this.clients.delete(e),this.metrics.activeConnections=this.clients.size}validateMessage(e){return!e||typeof e!="object"?(this.logger.debug("\u6D88\u606F\u9A8C\u8BC1\u5931\u8D25: \u4E0D\u662F\u5BF9\u8C61"),!1):e.jsonrpc!=="2.0"?(this.logger.debug("\u6D88\u606F\u9A8C\u8BC1\u5931\u8D25: jsonrpc \u7248\u672C\u4E0D\u6B63\u786E",{jsonrpc:e.jsonrpc}),!1):!e.method||typeof e.method!="string"?(this.logger.debug("\u6D88\u606F\u9A8C\u8BC1\u5931\u8D25: method \u5B57\u6BB5\u65E0\u6548",{method:e.method}),!1):e.id!==void 0&&typeof e.id!="string"&&typeof e.id!="number"&&e.id!==null?(this.logger.debug("\u6D88\u606F\u9A8C\u8BC1\u5931\u8D25: id \u5B57\u6BB5\u7C7B\u578B\u65E0\u6548",{id:e.id}),!1):e.params!==void 0&&typeof e.params!="object"?(this.logger.debug("\u6D88\u606F\u9A8C\u8BC1\u5931\u8D25: params \u5B57\u6BB5\u7C7B\u578B\u65E0\u6548",{params:e.params}),!1):!0}createErrorResponse(e,t,r){let n={jsonrpc:"2.0",error:{code:e,message:t},id:r};return new Response(JSON.stringify(n),{status:400,headers:{"Content-Type":"application/json","MCP-Protocol-Version":"2024-11-05"}})}getStatus(){return{connectedClients:this.clients.size,maxClients:this.config.maxClients,isInitialized:this.mcpMessageHandler!==null,metrics:this.config.enableMetrics?this.metrics:void 0,config:{maxClients:this.config.maxClients,connectionTimeout:this.config.connectionTimeout,heartbeatInterval:this.config.heartbeatInterval,maxMessageSize:this.config.maxMessageSize}}}getDetailedStatus(){let e=Array.from(this.clients.values()).map(t=>({id:t.id,sessionId:t.sessionId,connectedAt:t.connectedAt.toISOString(),lastActivity:t.lastActivity.toISOString(),messageCount:t.messageCount,isAlive:t.isAlive,userAgent:t.userAgent,remoteAddress:t.remoteAddress}));return{...this.getStatus(),clients:e,startTime:this.startTime.toISOString()}}async broadcastMessage(e,t){let r=JSON.stringify(t),n=[];for(let[o,s]of this.clients.entries()){if(!s.isAlive||!s.writer){n.push(o);continue}try{await this.sendSSEEvent(s.writer,e,r)}catch(a){this.logger.warn(`\u5E7F\u64AD\u6D88\u606F\u5931\u8D25\uFF0C\u6807\u8BB0\u5BA2\u6237\u7AEF\u4E3A\u4E0D\u6D3B\u8DC3: ${o}`,a),s.isAlive=!1,n.push(o)}}for(let o of n)this.handleClientDisconnect(o,"broadcast-failed")}destroy(){this.logger.info("\u6B63\u5728\u9500\u6BC1 MCPRouteHandler"),this.stopCleanupTask();for(let[e]of this.clients.entries())this.handleClientDisconnect(e,"server-shutdown");this.mcpMessageHandler=null,this.logger.info("MCPRouteHandler \u9500\u6BC1\u5B8C\u6210")}}});var ht,rn=d(()=>{"use strict";y();Be();ue();ht=class{static{c(this,"RealtimeNotificationHandler")}logger;notificationService;configService;statusService;eventBus;constructor(e,t){this.logger=g.withTag("RealtimeNotificationHandler"),this.notificationService=e,this.configService=new ne,this.statusService=t,this.eventBus=q()}async handleMessage(e,t,r){try{switch(this.logger.debug(`\u5904\u7406 WebSocket \u6D88\u606F: ${t.type}`,{clientId:r}),this.eventBus.emitEvent("websocket:message:received",{type:t.type,data:t.data,clientId:r}),t.type){case"getConfig":await this.handleGetConfig(e,r);break;case"updateConfig":await this.handleUpdateConfig(e,t.data,r);break;case"getStatus":await this.handleGetStatus(e,r);break;case"restartService":await this.handleRestartService(e,r);break;default:this.logger.warn(`\u672A\u77E5\u7684 WebSocket \u6D88\u606F\u7C7B\u578B: ${t.type}`,{clientId:r}),this.sendError(e,"UNKNOWN_MESSAGE_TYPE",`\u672A\u77E5\u7684\u6D88\u606F\u7C7B\u578B: ${t.type}`)}}catch(n){this.logger.error(`\u5904\u7406 WebSocket \u6D88\u606F\u5931\u8D25: ${t.type}`,n),this.sendError(e,"MESSAGE_PROCESSING_ERROR",n instanceof Error?n.message:"\u6D88\u606F\u5904\u7406\u5931\u8D25")}}async handleGetConfig(e,t){this.logDeprecationWarning("WebSocket getConfig","GET /api/config");try{let r=await this.configService.getConfig();this.logger.debug("WebSocket: getConfig \u8BF7\u6C42\u5904\u7406\u6210\u529F",{clientId:t}),e.send(JSON.stringify({type:"config",data:r}))}catch(r){this.logger.error("WebSocket: getConfig \u8BF7\u6C42\u5904\u7406\u5931\u8D25",r),this.sendError(e,"CONFIG_READ_ERROR",r instanceof Error?r.message:"\u83B7\u53D6\u914D\u7F6E\u5931\u8D25")}}async handleUpdateConfig(e,t,r){this.logDeprecationWarning("WebSocket updateConfig","PUT /api/config");try{await this.configService.updateConfig(t,`websocket-${r}`),this.logger.debug("WebSocket: updateConfig \u8BF7\u6C42\u5904\u7406\u6210\u529F",{clientId:r})}catch(n){this.logger.error("WebSocket: updateConfig \u8BF7\u6C42\u5904\u7406\u5931\u8D25",n),this.sendError(e,"CONFIG_UPDATE_ERROR",n instanceof Error?n.message:"\u914D\u7F6E\u66F4\u65B0\u5931\u8D25")}}async handleGetStatus(e,t){this.logDeprecationWarning("WebSocket getStatus","GET /api/status");try{let r=this.statusService.getFullStatus();e.send(JSON.stringify({type:"status",data:r.client})),this.logger.debug("WebSocket: getStatus \u8BF7\u6C42\u5904\u7406\u6210\u529F",{clientId:t})}catch(r){this.logger.error("WebSocket: getStatus \u8BF7\u6C42\u5904\u7406\u5931\u8D25",r),this.sendError(e,"STATUS_READ_ERROR",r instanceof Error?r.message:"\u83B7\u53D6\u72B6\u6001\u5931\u8D25")}}async handleRestartService(e,t){this.logDeprecationWarning("WebSocket restartService","POST /api/services/restart");try{this.logger.info("WebSocket: \u6536\u5230\u670D\u52A1\u91CD\u542F\u8BF7\u6C42",{clientId:t}),this.eventBus.emitEvent("service:restart:requested",{source:`websocket-${t}`}),this.statusService.updateRestartStatus("restarting")}catch(r){this.logger.error("WebSocket: \u5904\u7406\u91CD\u542F\u8BF7\u6C42\u5931\u8D25",r),this.sendError(e,"RESTART_REQUEST_ERROR",r instanceof Error?r.message:"\u5904\u7406\u91CD\u542F\u8BF7\u6C42\u5931\u8D25")}}sendError(e,t,r){try{let n={type:"error",error:{code:t,message:r,timestamp:Date.now()}};e.send(JSON.stringify(n))}catch(n){this.logger.error("\u53D1\u9001\u9519\u8BEF\u6D88\u606F\u5931\u8D25:",n)}}logDeprecationWarning(e,t){this.logger.warn(`[DEPRECATED] ${e} \u529F\u80FD\u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u4F7F\u7528 ${t} \u66FF\u4EE3`)}async sendInitialData(e,t){try{this.logger.debug("\u53D1\u9001\u521D\u59CB\u6570\u636E\u7ED9\u5BA2\u6237\u7AEF",{clientId:t});let r=await this.configService.getConfig();e.send(JSON.stringify({type:"configUpdate",data:r}));let n=this.statusService.getFullStatus();e.send(JSON.stringify({type:"statusUpdate",data:n.client})),n.restart&&e.send(JSON.stringify({type:"restartStatus",data:n.restart})),this.logger.debug("\u521D\u59CB\u6570\u636E\u53D1\u9001\u5B8C\u6210",{clientId:t})}catch(r){this.logger.error("\u53D1\u9001\u521D\u59CB\u6570\u636E\u5931\u8D25:",r),this.sendError(e,"INITIAL_DATA_ERROR",r instanceof Error?r.message:"\u53D1\u9001\u521D\u59CB\u6570\u636E\u5931\u8D25")}}handleClientDisconnect(e){this.logger.info(`\u5BA2\u6237\u7AEF\u65AD\u5F00\u8FDE\u63A5: ${e}`),this.notificationService.unregisterClient(e)}handleClientConnect(e,t){this.logger.info(`\u5BA2\u6237\u7AEF\u8FDE\u63A5: ${t}`),this.notificationService.registerClient(t,e)}}});import{spawn as pt}from"child_process";var ut,nn=d(()=>{"use strict";y();Jt();ue();ut=class{static{c(this,"ServiceApiHandler")}logger;statusService;eventBus;constructor(e){this.logger=g.withTag("ServiceApiHandler"),this.statusService=e,this.eventBus=q()}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 de()).get("serviceManager").getStatus();if(!r.running){this.logger.warn("MCP \u670D\u52A1\u672A\u8FD0\u884C\uFF0C\u5C1D\u8BD5\u542F\u52A8\u670D\u52A1"),pt("xiaozhi",["start","--daemon"],{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u542F\u52A8\u547D\u4EE4\u5DF2\u53D1\u9001");return}let n=r.mode==="daemon",o=["restart"];n&&o.push("--daemon"),pt("xiaozhi",o,{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u91CD\u542F\u547D\u4EE4\u5DF2\u53D1\u9001")}catch(e){throw this.logger.error("\u91CD\u542F\u670D\u52A1\u5931\u8D25:",e),e}}async stopService(e){try{return this.logger.info("\u5904\u7406\u670D\u52A1\u505C\u6B62\u8BF7\u6C42"),pt("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"),pt("xiaozhi",["start","--daemon"],{detached:!0,stdio:"ignore",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}}).unref(),this.logger.info("MCP \u670D\u52A1\u542F\u52A8\u547D\u4EE4\u5DF2\u53D1\u9001"),e.json(this.createSuccessResponse(null,"\u542F\u52A8\u8BF7\u6C42\u5DF2\u63A5\u6536"))}catch(t){this.logger.error("\u5904\u7406\u542F\u52A8\u8BF7\u6C42\u5931\u8D25:",t);let r=this.createErrorResponse("START_REQUEST_ERROR",t instanceof Error?t.message:"\u5904\u7406\u542F\u52A8\u8BF7\u6C42\u5931\u8D25");return e.json(r,500)}}async getServiceStatus(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u8BF7\u6C42");let n=await(await de()).get("serviceManager").getStatus();return this.logger.debug("\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(n))}catch(t){this.logger.error("\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("SERVICE_STATUS_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u670D\u52A1\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}async getServiceHealth(e){try{this.logger.debug("\u5904\u7406\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u8BF7\u6C42");let t={status:"healthy",timestamp:Date.now(),uptime:process.uptime(),memory:process.memoryUsage(),version:process.version};return this.logger.debug("\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u6210\u529F"),e.json(this.createSuccessResponse(t))}catch(t){this.logger.error("\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u5931\u8D25:",t);let r=this.createErrorResponse("SERVICE_HEALTH_READ_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u670D\u52A1\u5065\u5EB7\u72B6\u6001\u5931\u8D25");return e.json(r,500)}}}});import{existsSync as dt}from"fs";import{readFile as Lo}from"fs/promises";import{dirname as Uo,join as ge}from"path";import{fileURLToPath as Wo}from"url";var mt,on=d(()=>{"use strict";y();mt=class{static{c(this,"StaticFileHandler")}logger;webPath=null;constructor(){this.logger=g.withTag("StaticFileHandler"),this.initializeWebPath()}initializeWebPath(){try{let e=Uo(Wo(import.meta.url));this.logger.debug(`\u5F53\u524D\u6587\u4EF6\u76EE\u5F55: ${e}`);let t=[ge(e,"..","..","web","dist"),ge(e,"..","web","dist"),ge(e,"..","..","web"),ge(e,"..","web"),ge(e,"..","..","..","web","dist"),ge(e,"..","..","..","web")];this.webPath=t.find(r=>{let n=dt(r);return this.logger.debug(`\u68C0\u67E5\u8DEF\u5F84 ${r}: ${n?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}`),n})||null,this.webPath?this.logger.info(`\u9759\u6001\u6587\u4EF6\u670D\u52A1\u8DEF\u5F84: ${this.webPath}`):(this.logger.warn("\u672A\u627E\u5230\u9759\u6001\u6587\u4EF6\u76EE\u5F55"),this.logger.debug("\u5C1D\u8BD5\u7684\u8DEF\u5F84:",t))}catch(e){this.logger.error("\u521D\u59CB\u5316\u9759\u6001\u6587\u4EF6\u8DEF\u5F84\u5931\u8D25:",e)}}async handleStaticFile(e){let t=new URL(e.req.url).pathname;try{if(this.logger.debug(`\u5904\u7406\u9759\u6001\u6587\u4EF6\u8BF7\u6C42: ${t}`),!this.webPath)return this.createErrorPage(e,"\u627E\u4E0D\u5230\u524D\u7AEF\u8D44\u6E90\u6587\u4EF6");let r=t;if(r==="/"&&(r="/index.html"),r.includes(".."))return this.logger.warn(`\u8DEF\u5F84\u904D\u5386\u653B\u51FB\u5C1D\u8BD5: ${r}`),e.text("Forbidden",403);let n=ge(this.webPath,r);if(!dt(n)){let s=ge(this.webPath,"index.html");return dt(s)?(this.logger.debug(`SPA \u56DE\u9000\u5230 index.html: ${t}`),this.serveFile(e,s,"text/html")):(this.logger.debug(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${n}`),e.text("Not Found",404))}let o=this.getContentType(n);return this.logger.debug(`\u670D\u52A1\u9759\u6001\u6587\u4EF6: ${n}, Content-Type: ${o}`),this.serveFile(e,n,o)}catch(r){return this.logger.error(`\u670D\u52A1\u9759\u6001\u6587\u4EF6\u9519\u8BEF (${t}):`,r),e.text("Internal Server Error",500)}}async serveFile(e,t,r){try{let n=await Lo(t);return r.startsWith("text/")||r.includes("javascript")||r.includes("json")?e.text(n.toString(),200,{"Content-Type":r}):e.body(new Uint8Array(n),200,{"Content-Type":r})}catch(n){throw this.logger.error(`\u8BFB\u53D6\u6587\u4EF6\u5931\u8D25: ${t}`,n),n}}getContentType(e){let t=e.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",js:"application/javascript",mjs:"application/javascript",css:"text/css",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",eot:"application/vnd.ms-fontobject",pdf:"application/pdf",txt:"text/plain",xml:"application/xml",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}createErrorPage(e,t){let r=`
|
|
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=`
|
|
21
42
|
<!DOCTYPE html>
|
|
22
43
|
<html>
|
|
23
44
|
<head>
|
|
@@ -72,7 +93,7 @@ data: ${r}
|
|
|
72
93
|
</div>
|
|
73
94
|
</body>
|
|
74
95
|
</html>
|
|
75
|
-
`;return e.html(r)}isWebPathAvailable(){return this.webPath!==null&&dt(this.webPath)}getWebPath(){return this.webPath}reinitializeWebPath(){this.initializeWebPath()}}});var ft,sn=d(()=>{"use strict";y();ft=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)}}}});import Bo from"ajv";var Ct,an=d(()=>{"use strict";y();K();st();Ct=class{static{c(this,"ToolApiHandler")}logger;ajv;constructor(){this.logger=g.withTag("ToolApiHandler"),this.ajv=new Bo({allErrors:!0,verbose:!0})}createSuccessResponse(e,t){return{success:!0,data:e,message:t}}createErrorResponse(e,t){return{success:!1,error:{code:e,message:t}}}async callTool(e){try{this.logger.info("\u5904\u7406\u5DE5\u5177\u8C03\u7528\u8BF7\u6C42");let t=await e.req.json(),{serviceName:r,toolName:n,args:o}=t;if(!r||!n){let l=this.createErrorResponse("INVALID_REQUEST","serviceName \u548C toolName \u662F\u5FC5\u9700\u7684\u53C2\u6570");return e.json(l,400)}if(this.logger.info(`\u51C6\u5907\u8C03\u7528\u5DE5\u5177: ${r}/${n}\uFF0C\u53C2\u6570:`,JSON.stringify(o)),!U.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 U.getInstance();await this.validateServiceAndTool(s,r,n),r==="customMCP"&&await this.validateCustomMCPArguments(s,n,o||{});let a;if(r==="customMCP")a=await s.callTool(n,o||{});else{let l=`${r}__${n}`;a=await s.callTool(l,o||{})}return e.json(this.createSuccessResponse(a,"\u5DE5\u5177\u8C03\u7528\u6210\u529F"))}catch(t){this.logger.error("\u5DE5\u5177\u8C03\u7528\u5931\u8D25:",t);let r=t instanceof Error?t.message:String(t),n="TOOL_CALL_ERROR";r.includes("\u4E0D\u5B58\u5728")?n="SERVICE_OR_TOOL_NOT_FOUND":r.includes("\u672A\u542F\u52A8")||r.includes("\u672A\u8FDE\u63A5")?n="SERVICE_NOT_AVAILABLE":r.includes("\u5DF2\u88AB\u7981\u7528")?n="TOOL_DISABLED":r.includes("\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25")?n="INVALID_ARGUMENTS":r.includes("CustomMCP")||r.includes("customMCP")?n="CUSTOM_MCP_ERROR":r.includes("\u5DE5\u4F5C\u6D41\u8C03\u7528\u5931\u8D25")||r.includes("API \u8BF7\u6C42\u5931\u8D25")?n="EXTERNAL_API_ERROR":r.includes("\u8D85\u65F6")&&(n="TIMEOUT_ERROR");let o=this.createErrorResponse(n,r);return e.json(o,500)}}async listTools(e){try{if(this.logger.info("\u5904\u7406\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u8BF7\u6C42"),!U.isInitialized()){let o=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(o,503)}let r=(await U.getInstance()).getAllTools(),n={};for(let o of r){let s=o.serviceName;n[s]||(n[s]=[]);let a=s==="customMCP"?o.name:o.originalName;n[s].push({name:a,fullName:o.name,description:o.description,inputSchema:o.inputSchema})}return this.logger.info(`\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u6210\u529F\uFF0C\u5171 ${r.length} \u4E2A\u5DE5\u5177`),e.json(this.createSuccessResponse({totalTools:r.length,services:n},"\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u6210\u529F"))}catch(t){this.logger.error("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25:",t);let r=this.createErrorResponse("LIST_TOOLS_ERROR",t instanceof Error?t.message:"\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25");return e.json(r,500)}}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(S=>S.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 n=m.getMcpServers();if(!n[t]){let u=Object.keys(n);throw new Error(`\u670D\u52A1 '${t}' \u4E0D\u5B58\u5728\u3002\u53EF\u7528\u670D\u52A1: ${u.join(", ")}`)}let o=e.getService(t);if(!o)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(!o.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=o.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=m.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 o=e.getCustomMCPTools().find(l=>l.name===t);if(!o)throw new Error(`customMCP \u5DE5\u5177 '${t}' \u4E0D\u5B58\u5728`);if(!o.inputSchema){this.logger.warn(`customMCP \u5DE5\u5177 '${t}' \u6CA1\u6709\u5B9A\u4E49 inputSchema\uFF0C\u8DF3\u8FC7\u53C2\u6570\u9A8C\u8BC1`);return}let s=this.ajv.compile(o.inputSchema);if(!s(r)){let u=`\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25: ${(s.errors||[]).map(p=>{let S=p.instancePath||p.schemaPath||"",R=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 $=p.params?.type||"\u672A\u77E5\u7C7B\u578B";return`\u53C2\u6570 ${S} \u7C7B\u578B\u9519\u8BEF\uFF0C\u671F\u671B: ${$}`}if(p.keyword==="enum"){let $=p.params?.allowedValues||[];return`\u53C2\u6570 ${S} \u503C\u65E0\u6548\uFF0C\u5141\u8BB8\u7684\u503C: ${$.join(", ")}`}return`\u53C2\u6570 ${S} ${R}`}).join("; ")}`;throw this.logger.error(`customMCP \u5DE5\u5177 '${t}' \u53C2\u6570\u9A8C\u8BC1\u5931\u8D25:`,u),new Error(u)}this.logger.debug(`customMCP \u5DE5\u5177 '${t}' \u53C2\u6570\u9A8C\u8BC1\u901A\u8FC7`)}catch(n){throw n instanceof Error&&n.message.includes("\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25")?n:(this.logger.error(`\u9A8C\u8BC1 customMCP \u5DE5\u5177 '${t}' \u53C2\u6570\u65F6\u51FA\u9519:`,n),new Error(`\u53C2\u6570\u9A8C\u8BC1\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF: ${n instanceof Error?n.message:"\u672A\u77E5\u9519\u8BEF"}`))}}}});var vt,cn=d(()=>{"use strict";y();ue();vt=class{static{c(this,"NotificationService")}logger;eventBus;clients=new Map;messageQueue=new Map;maxQueueSize=100;constructor(){this.logger=g.withTag("NotificationService"),this.eventBus=q(),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(n=>{t.readyState===1&&t.send(n)},"send")};this.clients.set(e,r),this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u6CE8\u518C: ${e}`),this.logger.debug(`\u5F53\u524D\u5BA2\u6237\u7AEF\u6570\u91CF: ${this.clients.size}`),this.sendQueuedMessages(e),this.eventBus.emitEvent("websocket:client:connected",{clientId:e,timestamp:Date.now()})}catch(r){this.logger.error(`\u6CE8\u518C\u5BA2\u6237\u7AEF\u5931\u8D25: ${e}`,r),this.eventBus.emitEvent("notification:error",{error:r instanceof Error?r:new Error(String(r)),type:"client:register"})}}unregisterClient(e){try{this.clients.has(e)&&(this.clients.delete(e),this.messageQueue.delete(e),this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u6CE8\u9500: ${e}`),this.logger.debug(`\u5269\u4F59\u5BA2\u6237\u7AEF\u6570\u91CF: ${this.clients.size}`),this.eventBus.emitEvent("websocket:client:disconnected",{clientId:e,timestamp:Date.now()}))}catch(t){this.logger.error(`\u6CE8\u9500\u5BA2\u6237\u7AEF\u5931\u8D25: ${e}`,t)}}broadcast(e,t){let r={type:e,data:t,timestamp:Date.now()};this.logger.debug(`\u5E7F\u64AD\u6D88\u606F: ${e}`,{clientCount:this.clients.size});for(let[n,o]of this.clients)this.sendMessageToClient(o,r,n)}sendToClient(e,t,r){let n={type:t,data:r,timestamp:Date.now()},o=this.clients.get(e);o?this.sendMessageToClient(o,n,e):this.queueMessage(e,n)}sendMessageToClient(e,t,r){try{if(e.ws.readyState===1){let n=JSON.stringify(t);e.send(n),this.logger.debug(`\u6D88\u606F\u5DF2\u53D1\u9001\u7ED9\u5BA2\u6237\u7AEF ${r}: ${t.type}`)}else this.queueMessage(r,t),this.logger.warn(`\u5BA2\u6237\u7AEF ${r} \u8FDE\u63A5\u4E0D\u53EF\u7528\uFF0C\u6D88\u606F\u5DF2\u52A0\u5165\u961F\u5217`)}catch(n){this.logger.error(`\u53D1\u9001\u6D88\u606F\u7ED9\u5BA2\u6237\u7AEF ${r} \u5931\u8D25:`,n),this.queueMessage(r,t),this.eventBus.emitEvent("notification:error",{error:n instanceof Error?n:new Error(String(n)),type:"message:send"})}}queueMessage(e,t){this.messageQueue.has(e)||this.messageQueue.set(e,[]);let r=this.messageQueue.get(e);r.push(t),r.length>this.maxQueueSize&&(r.shift(),this.logger.warn(`\u5BA2\u6237\u7AEF ${e} \u6D88\u606F\u961F\u5217\u5DF2\u6EE1\uFF0C\u79FB\u9664\u6700\u65E7\u6D88\u606F`))}sendQueuedMessages(e){let t=this.messageQueue.get(e);if(!t||t.length===0)return;let r=this.clients.get(e);if(r){this.logger.info(`\u53D1\u9001 ${t.length} \u6761\u6392\u961F\u6D88\u606F\u7ED9\u5BA2\u6237\u7AEF ${e}`);for(let n of t)this.sendMessageToClient(r,n,e);this.messageQueue.delete(e)}}broadcastConfigUpdate(e){this.broadcast("configUpdate",e)}broadcastStatusUpdate(e){this.broadcast("statusUpdate",e)}broadcastRestartStatus(e,t,r){let n={status:e,error:t,timestamp:r||Date.now()};this.broadcast("restartStatus",n)}getClientStats(){let e=Array.from(this.clients.values()).filter(r=>r.ws.readyState===1).length,t=Array.from(this.messageQueue.values()).reduce((r,n)=>r+n.length,0);return{totalClients:this.clients.size,connectedClients:e,queuedMessages:t}}cleanupDisconnectedClients(){let e=[];for(let[t,r]of this.clients)r.ws.readyState!==1&&e.push(t);for(let t of e)this.unregisterClient(t);e.length>0&&this.logger.info(`\u6E05\u7406\u4E86 ${e.length} \u4E2A\u65AD\u5F00\u7684\u5BA2\u6237\u7AEF`)}destroy(){this.logger.info("\u9500\u6BC1\u901A\u77E5\u670D\u52A1"),this.clients.clear(),this.messageQueue.clear()}}});var St,ln=d(()=>{"use strict";y();ue();St=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=q()}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 Zt={};F(Zt,{WebServer:()=>Kt});import{createServer as Vo}from"http";import{serve as Go}from"@hono/node-server";import{Hono as qo}from"hono";import{cors as Xo}from"hono/cors";import{WebSocketServer as Jo}from"ws";var Kt,Qt=d(()=>{"use strict";y();Ye();Br();K();st();Zr();Yr();en();tn();rn();nn();on();sn();an();Be();ue();cn();ln();Kt=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??m.getWebUIPort()??9999}catch{this.port=e??9999}this.logger=g.withTag("WebServer"),this.eventBus=q(),this.configService=new ne,this.statusService=new St,this.notificationService=new vt,this.configApiHandler=new ct,this.statusApiHandler=new ft(this.statusService),this.serviceApiHandler=new ut(this.statusService),this.toolApiHandler=new Ct,this.staticFileHandler=new mt,this.mcpRouteHandler=new gt,this.realtimeNotificationHandler=new ht(this.notificationService,this.statusService),this.heartbeatHandler=new lt(this.statusService,this.notificationService),this.app=new qo,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 U.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(!m.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C 'xiaozhi init' \u521D\u59CB\u5316\u914D\u7F6E");m.cleanupInvalidServerToolsConfig();let e=m.getConfig();return{mcpEndpoint:e.mcpEndpoint,mcpServers:e.mcpServers,webUIPort:e.webUI?.port??9999}}async loadMCPServicesFromConfig(e){if(!this.mcpServiceManager)throw new Error("MCPServiceManager \u672A\u521D\u59CB\u5316");for(let[t,r]of Object.entries(e)){this.logger.info(`\u6DFB\u52A0 MCP \u670D\u52A1\u914D\u7F6E: ${t}`);let n=Wr(t,r);this.mcpServiceManager.addServiceConfig(t,n)}await this.mcpServiceManager.startAllServices(),this.logger.info("\u6240\u6709 MCP \u670D\u52A1\u5DF2\u542F\u52A8")}async initializeXiaozhiConnection(e,t){let n=(Array.isArray(e)?e:[e]).filter(o=>o&&!o.includes("<\u8BF7\u586B\u5199"));if(n.length===0){this.logger.warn("\u672A\u914D\u7F6E\u6709\u6548\u7684\u5C0F\u667A\u63A5\u5165\u70B9\uFF0C\u8DF3\u8FC7\u8FDE\u63A5");return}this.logger.info(`\u521D\u59CB\u5316\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u7BA1\u7406\u5668\uFF0C\u7AEF\u70B9\u6570\u91CF: ${n.length}`),this.logger.debug("\u6709\u6548\u7AEF\u70B9\u5217\u8868:",n);try{this.xiaozhiConnectionManager=await Re.getInstance({healthCheckInterval:3e4,reconnectInterval:5e3,maxReconnectAttempts:10,loadBalanceStrategy:"round-robin",connectionTimeout:1e4}),this.mcpServiceManager&&this.xiaozhiConnectionManager.setServiceManager(this.mcpServiceManager),await this.xiaozhiConnectionManager.initialize(n,t),await this.xiaozhiConnectionManager.connect(),this.xiaozhiConnectionManager.on("configChange",o=>{this.logger.info(`\u5C0F\u667A\u8FDE\u63A5\u914D\u7F6E\u53D8\u66F4: ${o.type}`,o.data)}),this.logger.info(`\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u7BA1\u7406\u5668\u521D\u59CB\u5316\u5B8C\u6210\uFF0C\u7BA1\u7406 ${n.length} \u4E2A\u7AEF\u70B9`)}catch(o){this.logger.error("\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5\u7BA1\u7406\u5668\u521D\u59CB\u5316\u5931\u8D25:",o),this.logger.warn("\u56DE\u9000\u5230\u5355\u8FDE\u63A5\u6A21\u5F0F");let s=n[0];this.logger.info(`\u521D\u59CB\u5316\u5355\u4E2A\u5C0F\u667A\u63A5\u5165\u70B9\u8FDE\u63A5: ${s}`),this.proxyMCPServer=new le(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,n=1e3,o=3e4,s=2){let a=null;for(let l=1;l<=r;l++)try{return this.logger.info(`${t} - \u5C1D\u8BD5\u8FDE\u63A5 (${l}/${r})`),await e()}catch(h){if(a=h,this.logger.warn(`${t} - \u8FDE\u63A5\u5931\u8D25:`,h),l<r){let u=Math.min(n*s**(l-1),o);this.logger.info(`${t} - ${u}ms \u540E\u91CD\u8BD5...`),await this.sleep(u)}}throw new Error(`${t} - \u8FDE\u63A5\u5931\u8D25\uFF0C\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570: ${a?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}setupMiddleware(){this.app?.use("*",Xo({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?.post("/mcp",e=>this.mcpRouteHandler.handlePost(e)),this.app?.get("/mcp",e=>this.mcpRouteHandler.handleGet(e)),this.app?.all("/api/*",async e=>{let t=this.createErrorResponse("API_NOT_FOUND",`API \u7AEF\u70B9\u4E0D\u5B58\u5728: ${e.req.path}`);return e.json(t,404)}),this.app.get("*",e=>this.staticFileHandler.handleStaticFile(e))}setupWebSocket(){this.wss&&this.wss.on("connection",e=>{let t=`client-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u8FDE\u63A5: ${t}`),this.logger.debug(`\u5F53\u524D WebSocket \u8FDE\u63A5\u6570: ${this.wss?.clients.size||0}`),this.realtimeNotificationHandler.handleClientConnect(e,t),this.heartbeatHandler.handleClientConnect(t),e.on("message",async r=>{try{let n=JSON.parse(r.toString());n.type==="clientStatus"?await this.heartbeatHandler.handleClientStatus(e,n,t):await this.realtimeNotificationHandler.handleMessage(e,n,t)}catch(n){this.logger.error("WebSocket message error:",n);let o={type:"error",error:{code:"MESSAGE_PARSE_ERROR",message:n instanceof Error?n.message:"\u6D88\u606F\u89E3\u6790\u5931\u8D25",timestamp:Date.now()}};e.send(JSON.stringify(o))}}),e.on("close",()=>{this.logger.info(`WebSocket \u5BA2\u6237\u7AEF\u5DF2\u65AD\u5F00\u8FDE\u63A5: ${t}`),this.logger.debug(`\u5269\u4F59 WebSocket \u8FDE\u63A5\u6570: ${this.wss?.clients.size||0}`),this.realtimeNotificationHandler.handleClientDisconnect(t),this.heartbeatHandler.handleClientDisconnect(t)}),e.on("error",r=>{this.logger.error(`WebSocket \u8FDE\u63A5\u9519\u8BEF (${t}):`,r)}),this.realtimeNotificationHandler.sendInitialData(e,t)})}async start(){if(this.httpServer){this.logger.warn("Web server is already running");return}let e=Go({fetch:this.app.fetch,port:this.port,hostname:"0.0.0.0",createServer:Vo});this.httpServer=e,this.wss=new Jo({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 n of this.wss.clients)n.terminate();this.wss.close(()=>{this.httpServer?this.httpServer.close(()=>{this.logger.info("Web server stopped"),r()}):(this.logger.info("Web server stopped"),r()),setTimeout(()=>{this.logger.info("Web server force stopped"),r()},2e3)})}else this.logger.info("Web server stopped"),r()})}destroy(){this.logger.info("\u9500\u6BC1 WebServer \u5B9E\u4F8B"),this.heartbeatMonitorInterval&&(this.heartbeatHandler.stopHeartbeatMonitoring(this.heartbeatMonitorInterval),this.heartbeatMonitorInterval=void 0),this.statusService.destroy(),this.notificationService.destroy(),Qr(),this.proxyMCPServer?.disconnect(),this.logger.info("WebServer \u5B9E\u4F8B\u5DF2\u9500\u6BC1")}}});var gn={};F(gn,{ServiceManagerImpl:()=>Yt});var Yt,hn=d(()=>{"use strict";Z();Me();He();Je();Yt=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 T?t:T.startFailed(t instanceof Error?t.message:String(t))}}async stop(){try{let e=this.getStatus();if(!e.running)throw T.notRunning();await this.processManager.gracefulKillProcess(e.pid),this.processManager.cleanupPidFile()}catch(e){throw e instanceof T?e:new T(`\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 T(`\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&&V.validatePort(e.port),e.mode&&!["normal","mcp-server","stdio"].includes(e.mode))throw new T(`\u65E0\u6548\u7684\u8FD0\u884C\u6A21\u5F0F: ${e.mode}`)}checkEnvironment(){if(!this.configManager.configExists())throw pe.configNotFound();try{if(!this.configManager.getConfig())throw new pe("\u914D\u7F6E\u6587\u4EF6\u65E0\u6548")}catch(e){throw e instanceof pe?e:new pe(`\u914D\u7F6E\u6587\u4EF6\u9519\u8BEF: ${e instanceof Error?e.message:String(e)}`)}}async startNormalMode(e){let{spawn:t}=await import("child_process");e.daemon?await this.startWebServerInDaemon(e.ui||!1):await this.startWebServerInForeground(e.ui||!1)}async startMcpServerMode(e){let t=e.port||3e3,{spawn:r}=await import("child_process");if(e.daemon){let n=b.getExecutablePath("cli"),o=r("node",[n,"start","--server",t.toString()],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:b.getConfigDir(),XIAOZHI_DAEMON:"true",MCP_SERVER_MODE:"true"}});this.processManager.savePidInfo(o.pid,"daemon"),o.unref(),console.log(`\u2705 MCP Server \u5DF2\u5728\u540E\u53F0\u542F\u52A8 (PID: ${o.pid}, Port: ${t})`),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi status' \u67E5\u770B\u72B6\u6001"),process.exit(0)}else{let{MCPServer:n}=await Promise.resolve().then(()=>(Ur(),Lr)),o=new n(t),s=c(async()=>{await o.stop(),process.exit(0)},"cleanup");process.on("SIGINT",s),process.on("SIGTERM",s),await o.start()}}async startStdioMode(e){let{spawn:t}=await import("child_process"),r=b.getMcpServerProxyPath(),n=t("node",[r],{stdio:"inherit",env:{...process.env,XIAOZHI_CONFIG_DIR:b.getConfigDir()}});this.processManager.savePidInfo(n.pid,"foreground")}async startWebServerInDaemon(e){let{spawn:t}=await import("child_process"),r=b.getWebServerStandalonePath();if(!(await import("fs")).default.existsSync(r))throw new T(`WebServer \u6587\u4EF6\u4E0D\u5B58\u5728: ${r}`);let o=[r];e&&o.push("--open-browser");let s=t("node",o,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:b.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(()=>(Qt(),Zt)),r=new t,n=c(async()=>{await r.stop(),this.processManager.cleanupPidFile(),process.exit(0)},"cleanup");if(process.on("SIGINT",n),process.on("SIGTERM",n),this.processManager.savePidInfo(process.pid,"foreground"),await r.start(),e){let s=this.configManager.getConfig()?.webServer?.port||9999;await this.openBrowserUrl(`http://localhost:${s}`)}}async openBrowserUrl(e){try{let{spawn:t}=await import("child_process"),r=L.getCurrentPlatform(),n,o;r==="darwin"?(n="open",o=[e]):r==="win32"?(n="start",o=["",e]):(n="xdg-open",o=[e]),t(n,o,{detached:!0,stdio:"ignore"}),console.log(`\u{1F310} \u5DF2\u5C1D\u8BD5\u6253\u5F00\u6D4F\u89C8\u5668: ${e}`)}catch{console.log(`\u26A0\uFE0F \u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE: ${e}`)}}}});var pn={};F(pn,{TemplateManagerImpl:()=>er});import Ko from"fs";import me from"path";var er,un=d(()=>{"use strict";Z();Ne();Me();Je();er=class{static{c(this,"TemplateManagerImpl")}templateCache=new Map;async getAvailableTemplates(){try{let e=b.findTemplatesDir();if(!e)return[];let t=[],r=Ko.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name);for(let n of r)try{let o=await this.getTemplateInfo(n);o&&t.push(o)}catch{console.warn(`\u8DF3\u8FC7\u65E0\u6548\u6A21\u677F: ${n}`)}return t}catch{throw new C("\u65E0\u6CD5\u8BFB\u53D6\u6A21\u677F\u76EE\u5F55",b.findTemplatesDir()||"")}}async getTemplateInfo(e){try{if(V.validateTemplateName(e),this.templateCache.has(e))return this.templateCache.get(e);let t=b.getTemplatePath(e);if(!t)return null;let r=me.join(t,"template.json"),n={};if(M.exists(r))try{let a=M.readFile(r);n=JSON.parse(a)}catch{console.warn(`\u6A21\u677F\u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${e}`)}let o=this.getTemplateFiles(t),s={name:e,path:t,description:n.description||`${e} \u6A21\u677F`,version:n.version||"1.0.0",author:n.author,files:o};return this.templateCache.set(e,s),s}catch(t){throw t instanceof E?t:new C(`\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 C(`\u6A21\u677F\u4E0D\u5B58\u5728: ${t}`,"");let n=me.resolve(e.targetPath);if(M.exists(n))throw C.alreadyExists(n);M.ensureDir(n),await this.copyTemplateFiles(r,n,e),await this.processTemplateVariables(n,e),console.log(`\u2705 \u9879\u76EE\u521B\u5EFA\u6210\u529F: ${n}`)}catch(t){throw t instanceof C||t instanceof E?t:new C(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,e.targetPath)}}async validateTemplate(e){try{let t=await this.getTemplateInfo(e);if(!t)return!1;let r=["package.json"];for(let n of r){let o=me.join(t.path,n);if(!M.exists(o))return console.warn(`\u6A21\u677F\u7F3A\u5C11\u5FC5\u8981\u6587\u4EF6: ${n}`),!1}return!0}catch{return!1}}clearCache(){this.templateCache.clear()}getTemplateFiles(e){try{return M.listDirectory(e,{recursive:!0,includeHidden:!1}).filter(r=>{let n=me.relative(e,r);return!n.startsWith(".")&&n!=="template.json"&&!n.includes("node_modules")})}catch{return[]}}validateCreateOptions(e){V.validateRequired(e.targetPath,"targetPath"),V.validateRequired(e.projectName,"projectName"),V.validateProjectName(e.projectName),e.templateName&&V.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(n){throw new C(`\u590D\u5236\u6A21\u677F\u6587\u4EF6\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`,e.path)}}async processTemplateVariables(e,t){try{let r={PROJECT_NAME:t.projectName,PROJECT_NAME_LOWER:t.projectName.toLowerCase(),PROJECT_NAME_UPPER:t.projectName.toUpperCase(),...t.variables},n=["package.json","README.md","src/**/*.ts","src/**/*.js","src/**/*.json"];for(let o of n){let s=this.findFilesByPattern(e,o);for(let a of s)await this.replaceVariablesInFile(a,r)}}catch(r){console.warn(`\u5904\u7406\u6A21\u677F\u53D8\u91CF\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}findFilesByPattern(e,t){try{if(!t.includes("*")){let o=me.join(e,t);return M.exists(o)?[o]:[]}let r=M.listDirectory(e,{recursive:!0}),n=new RegExp(t.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*"));return r.filter(o=>{let s=me.relative(e,o);return n.test(s)})}catch{return[]}}async replaceVariablesInFile(e,t){try{let r=M.readFile(e),n=!1;for(let[o,s]of Object.entries(t)){let a=new RegExp(`{{\\s*${o}\\s*}}`,"g");a.test(r)&&(r=r.replace(a,s),n=!0)}n&&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 de(){return tr.create()}var tr,Jt=d(()=>{"use strict";y();K();Nt();Ne();Ht();Me();He();Je();Er();tr=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",()=>Ze),e.registerSingleton("platformUtils",()=>L),e.registerSingleton("formatUtils",()=>Ee),e.registerSingleton("fileUtils",()=>M),e.registerSingleton("pathUtils",()=>b),e.registerSingleton("validation",()=>V),e.registerSingleton("configManager",()=>m),e.registerSingleton("logger",()=>g),e.registerSingleton("errorHandler",()=>Q),e.registerSingleton("processManager",()=>{let t=(kt(),J(Mr));return new t.ProcessManagerImpl}),e.registerSingleton("daemonManager",()=>{let t=(br(),J(Pr)),r=e.get("processManager"),n=e.get("logger");return new t.DaemonManagerImpl(r,n)}),e.registerSingleton("serviceManager",()=>{let t=(hn(),J(gn)),r=e.get("processManager"),n=e.get("configManager"),o=e.get("logger");return new t.ServiceManagerImpl(r,n,o)}),e.registerSingleton("templateManager",()=>{let t=(un(),J(pn));return new t.TemplateManagerImpl}),e}};c(de,"createContainer")});var _,fe=d(()=>{"use strict";_=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 dn={};F(dn,{ServiceCommandHandler:()=>rr});var rr,mn=d(()=>{"use strict";fe();rr=class extends _{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:"--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{let t=this.getService("serviceManager");e.stdio?await this.startStdioMode():await t.start({daemon:e.daemon||!1,ui:e.ui||!1})}catch(t){this.handleError(t)}}async handleStop(){try{await this.getService("serviceManager").stop()}catch(e){this.handleError(e)}}async handleStatus(){try{let t=await this.getService("serviceManager").getStatus();t.running?(console.log(`\u2705 \u670D\u52A1\u6B63\u5728\u8FD0\u884C (PID: ${t.pid})`),t.uptime&&console.log(`\u23F1\uFE0F \u8FD0\u884C\u65F6\u95F4: ${t.uptime}`),t.mode&&console.log(`\u{1F527} \u8FD0\u884C\u6A21\u5F0F: ${t.mode}`)):console.log("\u274C \u670D\u52A1\u672A\u8FD0\u884C")}catch(e){this.handleError(e)}}async handleRestart(e){try{await this.getService("serviceManager").restart({daemon:e.daemon||!1,ui:e.ui||!1})}catch(t){this.handleError(t)}}async handleAttach(){try{await this.getService("daemonManager").attachToLogs()}catch(e){this.handleError(e)}}async startStdioMode(){let{spawn:e}=await import("child_process"),{fileURLToPath:t}=await import("url"),r=await import("path"),n=t(import.meta.url),o=r.dirname(n),s=r.join(o,"mcpServerProxy.js");e("node",[s],{stdio:"inherit",env:{...process.env,XIAOZHI_CONFIG_DIR:process.env.XIAOZHI_CONFIG_DIR||process.cwd()}})}}});var fn={};F(fn,{ConfigCommandHandler:()=>or});import Zo from"path";import P from"chalk";import nr from"ora";var or,Cn=d(()=>{"use strict";fe();or=class extends _{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=nr("\u521D\u59CB\u5316\u914D\u7F6E...").start();try{let r=e.format;if(r!=="json"&&r!=="json5"&&r!=="jsonc")throw new Error("\u683C\u5F0F\u5FC5\u987B\u662F json, json5 \u6216 jsonc");let n=this.getService("configManager");if(n.configExists()){t.warn("\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728"),console.log(P.yellow("\u5982\u9700\u91CD\u65B0\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u5220\u9664\u73B0\u6709\u7684\u914D\u7F6E\u6587\u4EF6"));return}n.initConfig(r),t.succeed("\u914D\u7F6E\u6587\u4EF6\u521D\u59CB\u5316\u6210\u529F");let o=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),s=`xiaozhi.config.${r}`,a=Zo.join(o,s);console.log(P.green(`\u2705 \u914D\u7F6E\u6587\u4EF6\u5DF2\u521B\u5EFA: ${s}`)),console.log(P.yellow("\u{1F4DD} \u8BF7\u7F16\u8F91\u914D\u7F6E\u6587\u4EF6\u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9:")),console.log(P.gray(` \u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84: ${a}`)),console.log(P.yellow("\u{1F4A1} \u6216\u8005\u4F7F\u7528\u547D\u4EE4\u8BBE\u7F6E:")),console.log(P.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=nr("\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(P.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}let n=r.getConfig();switch(e){case"mcpEndpoint":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let o=r.getMcpEndpoints();o.length===0?console.log(P.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):o.length===1?console.log(P.green(`MCP \u7AEF\u70B9: ${o[0]}`)):(console.log(P.green(`MCP \u7AEF\u70B9 (${o.length} \u4E2A):`)),o.forEach((s,a)=>{console.log(P.gray(` ${a+1}. ${s}`))}));break}case"mcpServers":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(P.green("MCP \u670D\u52A1:"));for(let[o,s]of Object.entries(n.mcpServers)){let a=s;"type"in a&&a.type==="sse"?console.log(P.gray(` ${o}: [SSE] ${a.url}`)):console.log(P.gray(` ${o}: ${a.command} ${a.args.join(" ")}`))}break;case"connection":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let o=r.getConnectionConfig();console.log(P.green("\u8FDE\u63A5\u914D\u7F6E:")),console.log(P.gray(` \u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${o.heartbeatInterval}ms`)),console.log(P.gray(` \u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${o.heartbeatTimeout}ms`)),console.log(P.gray(` \u91CD\u8FDE\u95F4\u9694: ${o.reconnectInterval}ms`));break}case"heartbeatInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(P.green(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${r.getHeartbeatInterval()}ms`));break;case"heartbeatTimeout":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(P.green(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${r.getHeartbeatTimeout()}ms`));break;case"reconnectInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(P.green(`\u91CD\u8FDE\u95F4\u9694: ${r.getReconnectInterval()}ms`));break;default:t.fail(`\u672A\u77E5\u7684\u914D\u7F6E\u9879: ${e}`),console.log(P.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=nr("\u66F4\u65B0\u914D\u7F6E...").start();try{let n=this.getService("configManager");if(!n.configExists()){r.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log(P.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}switch(e){case"mcpEndpoint":n.updateMcpEndpoint(t),r.succeed(`MCP \u7AEF\u70B9\u5DF2\u8BBE\u7F6E\u4E3A: ${t}`);break;case"heartbeatInterval":{let o=Number.parseInt(t);if(Number.isNaN(o)||o<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u662F\u6B63\u6574\u6570");n.updateHeartbeatInterval(o),r.succeed(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5DF2\u8BBE\u7F6E\u4E3A: ${o}ms`);break}case"heartbeatTimeout":{let o=Number.parseInt(t);if(Number.isNaN(o)||o<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u662F\u6B63\u6574\u6570");n.updateHeartbeatTimeout(o),r.succeed(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5DF2\u8BBE\u7F6E\u4E3A: ${o}ms`);break}case"reconnectInterval":{let o=Number.parseInt(t);if(Number.isNaN(o)||o<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u662F\u6B63\u6574\u6570");n.updateReconnectInterval(o),r.succeed(`\u91CD\u8FDE\u95F4\u9694\u5DF2\u8BBE\u7F6E\u4E3A: ${o}ms`);break}default:r.fail(`\u4E0D\u652F\u6301\u8BBE\u7F6E\u7684\u914D\u7F6E\u9879: ${e}`),console.log(P.yellow("\u652F\u6301\u8BBE\u7F6E\u7684\u914D\u7F6E\u9879: mcpEndpoint, heartbeatInterval, heartbeatTimeout, reconnectInterval"))}}catch(n){r.fail(`\u8BBE\u7F6E\u914D\u7F6E\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`),this.handleError(n)}}}});var vn={};F(vn,{ProjectCommandHandler:()=>ir});import Qo from"path";import I from"chalk";import Yo from"ora";var ir,Sn=d(()=>{"use strict";fe();ir=class extends _{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=Yo("\u521D\u59CB\u5316\u9879\u76EE...").start();try{let n=this.getService("templateManager"),o=this.getService("fileUtils"),s=Qo.join(process.cwd(),e);if(await o.exists(s)){r.fail(`\u76EE\u5F55 "${e}" \u5DF2\u5B58\u5728`),console.log(I.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u9009\u62E9\u4E0D\u540C\u7684\u9879\u76EE\u540D\u79F0\u6216\u5220\u9664\u73B0\u6709\u76EE\u5F55"));return}t.template?await this.createFromTemplate(e,t.template,s,r,n):await this.createBasicProject(e,s,r,n)}catch(n){r.fail(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`),this.handleError(n)}}async createFromTemplate(e,t,r,n,o){n.text="\u68C0\u67E5\u6A21\u677F...";let s=await o.getAvailableTemplates();if(s.length===0){n.fail("\u627E\u4E0D\u5230\u53EF\u7528\u6A21\u677F"),console.log(I.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u786E\u4FDD xiaozhi-client \u6B63\u786E\u5B89\u88C5"));return}let a=t;if(!await o.validateTemplate(a)){n.fail(`\u6A21\u677F "${a}" \u4E0D\u5B58\u5728`);let h=this.findSimilarTemplate(a,s);if(h)if(console.log(I.yellow(`\u{1F4A1} \u4F60\u662F\u60F3\u4F7F\u7528\u6A21\u677F "${h}" \u5417\uFF1F`)),await this.askUserConfirmation(I.cyan("\u786E\u8BA4\u4F7F\u7528\u6B64\u6A21\u677F\uFF1F(y/n): ")))a=h;else{this.showAvailableTemplates(s);return}else{this.showAvailableTemplates(s);return}}n.text=`\u4ECE\u6A21\u677F "${a}" \u521B\u5EFA\u9879\u76EE "${e}"...`,await o.createProject({templateName:a,targetPath:r,projectName:e}),n.succeed(`\u9879\u76EE "${e}" \u521B\u5EFA\u6210\u529F`),console.log(I.green("\u2705 \u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(I.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(I.gray(` cd ${e}`)),console.log(I.gray(" pnpm install # \u5B89\u88C5\u4F9D\u8D56")),console.log(I.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9")),console.log(I.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1"))}async createBasicProject(e,t,r,n){r.text=`\u521B\u5EFA\u57FA\u672C\u9879\u76EE "${e}"...`,await n.createProject({templateName:null,targetPath:t,projectName:e}),r.succeed(`\u9879\u76EE "${e}" \u521B\u5EFA\u6210\u529F`),console.log(I.green("\u2705 \u57FA\u672C\u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(I.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(I.gray(` cd ${e}`)),console.log(I.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9\u548C\u670D\u52A1")),console.log(I.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1")),console.log(I.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 --template \u9009\u9879\u53EF\u4EE5\u4ECE\u6A21\u677F\u521B\u5EFA\u9879\u76EE"))}showAvailableTemplates(e){console.log(I.yellow("\u53EF\u7528\u7684\u6A21\u677F:"));for(let t of e)console.log(I.gray(` - ${t}`))}findSimilarTemplate(e,t){let r=this.getService("formatUtils"),n=null,o=0;for(let s of t){let a=r.calculateSimilarity(e.toLowerCase(),s.toLowerCase());a>o&&a>.6&&(o=a,n=s)}return n}async askUserConfirmation(e){let r=(await import("readline")).createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{r.question(e,o=>{r.close(),n(o.toLowerCase().trim()==="y"||o.toLowerCase().trim()==="yes")})})}}});var yt,yn=d(()=>{"use strict";y();kt();K();yt=class{static{c(this,"ToolCallService")}logger;processManager;baseUrl;constructor(){this.logger=g.withTag("ToolCallService"),this.processManager=new ke;try{let e=m.getWebUIPort()??9999;this.baseUrl=`http://localhost:${e}`}catch{this.baseUrl="http://localhost:9999"}}async callTool(e,t,r){await this.validateServiceStatus();try{let n=await fetch(`${this.baseUrl}/api/tools/call`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceName:e,toolName:t,args:r})});if(!n.ok){let s=await n.json();throw new Error(s.error?.message||`HTTP ${n.status}: ${n.statusText}`)}let o=await n.json();if(!o.success)throw new Error(o.error?.message||"\u5DE5\u5177\u8C03\u7528\u5931\u8D25");return o.data}catch(n){throw this.logger.error(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e}/${t}`,n instanceof Error?n.message:String(n)),n}}parseJsonArgs(e){try{return JSON.parse(e)}catch(t){throw new Error(`\u53C2\u6570\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u4F7F\u7528\u6709\u6548\u7684 JSON \u683C\u5F0F\u3002\u9519\u8BEF\u8BE6\u60C5: ${t instanceof Error?t.message:String(t)}`)}}async validateServiceStatus(){if(!this.processManager.getServiceStatus().running)throw new Error("xiaozhi \u670D\u52A1\u672A\u542F\u52A8\u3002\u8BF7\u5148\u8FD0\u884C 'xiaozhi start' \u6216 'xiaozhi start -d' \u542F\u52A8\u670D\u52A1\u3002");try{let t=await fetch(`${this.baseUrl}/api/status`,{method:"GET",signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Web \u670D\u52A1\u5668\u54CD\u5E94\u9519\u8BEF: ${t.status}`)}catch(t){throw t instanceof Error&&t.name==="AbortError"?new Error("\u8FDE\u63A5 xiaozhi \u670D\u52A1\u8D85\u65F6\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u662F\u5426\u6B63\u5E38\u8FD0\u884C\u3002"):new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230 xiaozhi \u670D\u52A1\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002\u9519\u8BEF\u8BE6\u60C5: ${t instanceof Error?t.message:String(t)}`)}}formatOutput(e){return JSON.stringify(e)}async getServiceStatus(){try{let e=this.processManager.getServiceStatus();if(!e.running)return"\u670D\u52A1\u672A\u542F\u52A8";try{let t=await fetch(`${this.baseUrl}/api/tools/list`,{method:"GET",signal:AbortSignal.timeout(3e3)});if(t.ok){let r=await t.json();if(r.success)return`\u670D\u52A1\u5DF2\u542F\u52A8 (PID: ${e.pid}, ${r.data.totalTools} \u4E2A\u5DE5\u5177\u53EF\u7528)`}return`\u670D\u52A1\u8FDB\u7A0B\u8FD0\u884C\u4E2D (PID: ${e.pid})\uFF0C\u4F46 MCP \u670D\u52A1\u53EF\u80FD\u672A\u5B8C\u5168\u521D\u59CB\u5316`}catch{return`\u670D\u52A1\u8FDB\u7A0B\u8FD0\u884C\u4E2D (PID: ${e.pid})\uFF0C\u4F46\u65E0\u6CD5\u8FDE\u63A5\u5230 Web API`}}catch(e){return`\u670D\u52A1\u72B6\u6001\u68C0\u67E5\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`}}}});var Mt={};F(Mt,{getDisplayWidth:()=>ar,listMcpServers:()=>ei,listServerTools:()=>ti,setToolEnabled:()=>ri,truncateToWidth:()=>Et});import f from"chalk";import En from"cli-table3";import sr from"ora";function ar(i){let e=0;for(let t of i)/[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef]/.test(t)?e+=2:e+=1;return e}function Et(i,e){if(ar(i)<=e)return i;if(e<=3)return"";let t="",r=0,n=!1;for(let o of i){let s=/[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef]/.test(o)?2:1;if(r+s>e-3){if(!n)return"";t+="...";break}t+=o,r+=s,n=!0}return t}async function ei(i={}){let e=sr("\u83B7\u53D6 MCP \u670D\u52A1\u5217\u8868...").start();try{let t=m.getMcpServers(),r=Object.keys(t),n=m.getCustomMCPTools(),o=n.length>0,s=r.length+(o?1:0);if(s===0){e.warn("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u670D\u52A1\u6216 customMCP \u5DE5\u5177"),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi config' \u547D\u4EE4\u914D\u7F6E MCP \u670D\u52A1\u6216\u5728 xiaozhi.config.json \u4E2D\u914D\u7F6E customMCP \u5DE5\u5177"));return}if(e.succeed(`\u627E\u5230 ${s} \u4E2A MCP \u670D\u52A1${o?" (\u5305\u62EC customMCP)":""}`),i.tools){console.log(),console.log(f.bold("MCP \u670D\u52A1\u5DE5\u5177\u5217\u8868:")),console.log();let a=8,l=[];for(let u of r){let p=m.getServerToolsConfig(u),S=Object.keys(p);l.push(...S)}if(o){let u=n.map(p=>p.name);l.push(...u)}for(let u of l){let p=ar(u);p>a&&(a=p)}a=Math.max(10,Math.min(a+2,30));let h=new En({head:[f.bold("MCP"),f.bold("\u5DE5\u5177\u540D\u79F0"),f.bold("\u72B6\u6001"),f.bold("\u63CF\u8FF0")],colWidths:[15,a,8,40],wordWrap:!0,style:{head:[],border:[]}});if(o)for(let u of n){let p=Et(u.description||"",32);h.push(["customMCP",u.name,f.green("\u542F\u7528"),p])}for(let u of r){let p=m.getServerToolsConfig(u),S=Object.keys(p);if(S.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 R of S){let $=p[R],oe=$.enable?f.green("\u542F\u7528"):f.red("\u7981\u7528"),ie=Et($.description||"",32);h.push([u,R,oe,ie])}}}console.log(h.toString())}else{console.log(),console.log(f.bold("MCP \u670D\u52A1\u5217\u8868:")),console.log(),o&&(console.log(`${f.cyan("\u2022")} ${f.bold("customMCP")}`),console.log(` \u7C7B\u578B: ${f.gray("\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177")}`),console.log(` \u914D\u7F6E: ${f.gray("xiaozhi.config.json")}`),console.log(` \u5DE5\u5177: ${f.green(n.length)} \u542F\u7528 / ${f.yellow(n.length)} \u603B\u8BA1`),console.log());for(let a of r){let l=t[a],h=m.getServerToolsConfig(a),u=Object.keys(h).length,p=Object.values(h).filter(S=>S.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 ti(i){let e=sr(`\u83B7\u53D6 ${i} \u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868...`).start();try{if(!m.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=m.getServerToolsConfig(i),n=Object.keys(r);if(n.length===0){e.warn(`\u670D\u52A1 '${i}' \u6682\u65E0\u5DE5\u5177\u4FE1\u606F`),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u542F\u52A8\u670D\u52A1\u4EE5\u626B\u63CF\u5DE5\u5177\u5217\u8868"));return}e.succeed(`\u670D\u52A1 '${i}' \u5171\u6709 ${n.length} \u4E2A\u5DE5\u5177`),console.log(),console.log(f.bold(`${i} \u670D\u52A1\u5DE5\u5177\u5217\u8868:`)),console.log();let o=new En({head:[f.bold("\u5DE5\u5177\u540D\u79F0"),f.bold("\u72B6\u6001"),f.bold("\u63CF\u8FF0")],colWidths:[30,8,50],wordWrap:!0,style:{head:[],border:[]}});for(let s of n){let a=r[s],l=a.enable?f.green("\u542F\u7528"):f.red("\u7981\u7528"),h=Et(a.description||"",40);o.push([s,l,h])}console.log(o.toString()),console.log(),console.log(f.gray("\u{1F4A1} \u63D0\u793A:")),console.log(f.gray(` - \u4F7F\u7528 'xiaozhi mcp ${i} <\u5DE5\u5177\u540D> enable' \u542F\u7528\u5DE5\u5177`)),console.log(f.gray(` - \u4F7F\u7528 'xiaozhi mcp ${i} <\u5DE5\u5177\u540D> disable' \u7981\u7528\u5DE5\u5177`))}catch(t){e.fail("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25"),console.error(f.red(`\u9519\u8BEF: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function ri(i,e,t){let r=t?"\u542F\u7528":"\u7981\u7528",n=sr(`${r}\u5DE5\u5177 ${i}/${e}...`).start();try{if(!m.getMcpServers()[i]){n.fail(`\u670D\u52A1 '${i}' \u4E0D\u5B58\u5728`),console.log(f.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u670D\u52A1"));return}let s=m.getServerToolsConfig(i);if(!s[e]){n.fail(`\u5DE5\u5177 '${e}' \u5728\u670D\u52A1 '${i}' \u4E2D\u4E0D\u5B58\u5728`),console.log(f.yellow(`\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp ${i} list' \u67E5\u770B\u8BE5\u670D\u52A1\u7684\u6240\u6709\u5DE5\u5177`));return}m.setToolEnabled(i,e,t,s[e].description),n.succeed(`\u6210\u529F${r}\u5DE5\u5177 ${f.cyan(i)}/${f.cyan(e)}`),console.log(),console.log(f.gray("\u{1F4A1} \u63D0\u793A: \u5DE5\u5177\u72B6\u6001\u66F4\u6539\u5C06\u5728\u4E0B\u6B21\u542F\u52A8\u670D\u52A1\u65F6\u751F\u6548"))}catch(o){n.fail(`${r}\u5DE5\u5177\u5931\u8D25`),console.error(f.red(`\u9519\u8BEF: ${o instanceof Error?o.message:String(o)}`)),process.exit(1)}}var wt=d(()=>{"use strict";K();c(ar,"getDisplayWidth");c(Et,"truncateToWidth");c(ei,"listMcpServers");c(ti,"listServerTools");c(ri,"setToolEnabled")});var Mn={};F(Mn,{McpCommandHandler:()=>cr});import Ce from"chalk";var cr,wn=d(()=>{"use strict";yn();fe();cr=class extends _{static{c(this,"McpCommandHandler")}name="mcp";description="MCP \u670D\u52A1\u548C\u5DE5\u5177\u7BA1\u7406";subcommands=[{name:"list",description:"\u5217\u51FA MCP \u670D\u52A1",options:[{flags:"--tools",description:"\u663E\u793A\u6240\u6709\u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868"}],execute:c(async(e,t)=>{await this.handleList(t)},"execute")},{name:"server",description:"\u7BA1\u7406\u6307\u5B9A\u7684 MCP \u670D\u52A1",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleServer(e[0])},"execute")},{name:"tool",description:"\u542F\u7528\u6216\u7981\u7528\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177",execute:c(async(e,t)=>{this.validateArgs(e,3);let[r,n,o]=e;o!=="enable"&&o!=="disable"&&(console.error(Ce.red("\u9519\u8BEF: \u64CD\u4F5C\u5FC5\u987B\u662F 'enable' \u6216 'disable'")),process.exit(1));let s=o==="enable";await this.handleTool(r,n,s)},"execute")},{name:"call",description:"\u8C03\u7528\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177",options:[{flags:"--args <json>",description:"\u5DE5\u5177\u53C2\u6570 (JSON \u683C\u5F0F)",defaultValue:"{}"}],execute:c(async(e,t)=>{this.validateArgs(e,2);let[r,n]=e;await this.handleCall(r,n,t.args)},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("MCP \u670D\u52A1\u548C\u5DE5\u5177\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleList(e){try{let{listMcpServers:t}=await Promise.resolve().then(()=>(wt(),Mt));await t(e)}catch(t){this.handleError(t)}}async handleServer(e){try{let{listServerTools:t}=await Promise.resolve().then(()=>(wt(),Mt));await t(e)}catch(t){this.handleError(t)}}async handleTool(e,t,r){try{let{setToolEnabled:n}=await Promise.resolve().then(()=>(wt(),Mt));await n(e,t,r)}catch(n){this.handleError(n)}}async handleCall(e,t,r){try{let n=new yt,o=n.parseJsonArgs(r),s=await n.callTool(e,t,o);console.log(n.formatOutput(s))}catch(n){console.log(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e}/${t}`),console.error(Ce.red("\u9519\u8BEF:"),n.message),n.message.includes("\u670D\u52A1\u672A\u542F\u52A8")?(console.log(),console.log(Ce.yellow("\u{1F4A1} \u8BF7\u5148\u542F\u52A8\u670D\u52A1:")),console.log(Ce.gray(" xiaozhi start # \u524D\u53F0\u542F\u52A8")),console.log(Ce.gray(" xiaozhi start -d # \u540E\u53F0\u542F\u52A8"))):n.message.includes("\u53C2\u6570\u683C\u5F0F\u9519\u8BEF")&&(console.log(),console.log(Ce.yellow("\u{1F4A1} \u6B63\u786E\u683C\u5F0F\u793A\u4F8B:")),console.log(Ce.gray(` xiaozhi mcp call ${e} ${t} --args '{"param": "value"}'`))),process.exit(1)}}}});var Pn={};F(Pn,{EndpointCommandHandler:()=>lr});import xe from"chalk";import Pt from"ora";var lr,bn=d(()=>{"use strict";fe();lr=class extends _{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=Pt("\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(xe.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):(console.log(xe.green(`\u5171 ${r.length} \u4E2A\u7AEF\u70B9:`)),r.forEach((n,o)=>{console.log(xe.gray(` ${o+1}. ${n}`))}))}catch(t){e.fail(`\u8BFB\u53D6\u7AEF\u70B9\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),this.handleError(t)}}async handleAdd(e){let t=Pt("\u6DFB\u52A0\u7AEF\u70B9...").start();try{let r=this.getService("configManager");r.addMcpEndpoint(e),t.succeed(`\u6210\u529F\u6DFB\u52A0\u7AEF\u70B9: ${e}`);let n=r.getMcpEndpoints();console.log(xe.gray(`\u5F53\u524D\u5171 ${n.length} \u4E2A\u7AEF\u70B9`))}catch(r){t.fail(`\u6DFB\u52A0\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleRemove(e){let t=Pt("\u79FB\u9664\u7AEF\u70B9...").start();try{let r=this.getService("configManager");r.removeMcpEndpoint(e),t.succeed(`\u6210\u529F\u79FB\u9664\u7AEF\u70B9: ${e}`);let n=r.getMcpEndpoints();console.log(xe.gray(`\u5F53\u524D\u5269\u4F59 ${n.length} \u4E2A\u7AEF\u70B9`))}catch(r){t.fail(`\u79FB\u9664\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleSet(e){let t=Pt("\u8BBE\u7F6E\u7AEF\u70B9...").start();try{let r=this.getService("configManager");if(e.length===1)r.updateMcpEndpoint(e[0]),t.succeed(`\u6210\u529F\u8BBE\u7F6E\u7AEF\u70B9: ${e[0]}`);else{r.updateMcpEndpoint(e),t.succeed(`\u6210\u529F\u8BBE\u7F6E ${e.length} \u4E2A\u7AEF\u70B9`);for(let[n,o]of e.entries())console.log(xe.gray(` ${n+1}. ${o}`))}}catch(r){t.fail(`\u8BBE\u7F6E\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}}});var Tn={};F(Tn,{UICommandHandler:()=>gr});import ve from"chalk";import ni from"ora";var gr,Rn=d(()=>{"use strict";fe();gr=class extends _{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=ni("\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(ve.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(()=>(Qt(),Zt));await new r().start(),e.succeed("UI \u670D\u52A1\u5DF2\u542F\u52A8");let o=t.getWebUIPort();console.log(ve.green("\u2705 \u914D\u7F6E\u7BA1\u7406\u7F51\u9875\u5DF2\u542F\u52A8\uFF0C\u53EF\u901A\u8FC7\u4EE5\u4E0B\u5730\u5740\u8BBF\u95EE:")),console.log(ve.green(` \u672C\u5730\u8BBF\u95EE: http://localhost:${o}`)),console.log(ve.green(` \u7F51\u7EDC\u8BBF\u95EE: http://<\u4F60\u7684IP\u5730\u5740>:${o}`)),console.log(ve.yellow("\u{1F4A1} \u63D0\u793A: \u6309 Ctrl+C \u505C\u6B62\u670D\u52A1")),await this.openBrowser(`http://localhost:${o}`)}catch(t){e.fail(`\u542F\u52A8 UI \u670D\u52A1\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),this.handleError(t)}}async openBrowser(e){try{let{spawn:t}=await import("child_process"),r;process.platform==="darwin"?r=t("open",[e],{detached:!0,stdio:"ignore"}):process.platform==="win32"?r=t("cmd",["/c","start",e],{detached:!0,stdio:"ignore"}):r=t("xdg-open",[e],{detached:!0,stdio:"ignore"}),r.on("error",()=>{console.log(ve.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(ve.gray(`\u{1F4A1} \u63D0\u793A: \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE: ${e}`))}}}});Jt();import ae from"chalk";import{Command as oi}from"commander";Nt();var bt=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}=(mn(),J(dn));return new e(this.container)}createConfigCommandHandler(){let{ConfigCommandHandler:e}=(Cn(),J(fn));return new e(this.container)}createProjectCommandHandler(){let{ProjectCommandHandler:e}=(Sn(),J(vn));return new e(this.container)}createMcpCommandHandler(){let{McpCommandHandler:e}=(wn(),J(Mn));return new e(this.container)}createEndpointCommandHandler(){let{EndpointCommandHandler:e}=(bn(),J(Pn));return new e(this.container)}createUICommandHandler(){let{UICommandHandler:e}=(Rn(),J(Tn));return new e(this.container)}};var Tt=class{constructor(e){this.container=e;this.handlerFactory=new bt(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){Q.handle(t)}}registerHandler(e){this.handlers.push(e)}registerCommand(e,t){if(t.subcommands&&t.subcommands.length>0){let r=e.command(t.name).description(t.description);for(let n of t.subcommands){let o=n.name;n.name==="get"?o="get <key>":n.name==="set"?o="set <key> <value>":n.name==="call"&&(o="call <serviceName> <toolName>");let s=r.command(o).description(n.description);if(n.options)for(let a of n.options)s.option(a.flags,a.description,a.defaultValue);s.action(async(...a)=>{try{let h=a[a.length-1].opts();await n.execute(a.slice(0,-1),h)}catch(l){Q.handle(l)}})}r.action(async(...n)=>{try{let s=n[n.length-1].opts();await t.execute(n.slice(0,-1),s)}catch(o){Q.handle(o)}})}else{let r=t.name;t.name==="create"&&(r="create <projectName>");let n=e.command(r).description(t.description);if(t.options)for(let o of t.options)n.option(o.flags,o.description,o.defaultValue);n.action(async(...o)=>{try{let a=o[o.length-1].opts();await t.execute(o.slice(0,-1),a)}catch(s){Q.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&&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",`
|
|
76
97
|
\u793A\u4F8B:
|
|
77
98
|
xiaozhi init # \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6
|
|
78
99
|
xiaozhi start # \u542F\u52A8\u670D\u52A1
|
|
@@ -87,7 +108,7 @@ data: ${r}
|
|
|
87
108
|
xiaozhi mcp list # \u5217\u51FA MCP \u670D\u52A1
|
|
88
109
|
|
|
89
110
|
\u66F4\u591A\u4FE1\u606F\u8BF7\u8BBF\u95EE: https://github.com/your-org/xiaozhi-client
|
|
90
|
-
`)}registerLegacyServiceCommands(e,t){let r=t.find(
|
|
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",`
|
|
91
112
|
\u793A\u4F8B:
|
|
92
113
|
xiaozhi config init # \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6
|
|
93
114
|
xiaozhi start # \u542F\u52A8\u670D\u52A1
|
|
@@ -104,5 +125,5 @@ data: ${r}
|
|
|
104
125
|
xiaozhi ui # \u542F\u52A8 Web UI
|
|
105
126
|
|
|
106
127
|
\u66F4\u591A\u4FE1\u606F\u8BF7\u8BBF\u95EE: https://github.com/your-org/xiaozhi-client
|
|
107
|
-
`),process.argv.length<=2&&(
|
|
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)});
|
|
108
129
|
//# sourceMappingURL=cli.js.map
|