xiaozhi-client 1.4.0 → 1.5.0-beta.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 +168 -8
- package/dist/adaptiveMCPPipe.d.ts +8 -0
- package/dist/adaptiveMCPPipe.js +12 -0
- package/dist/adaptiveMCPPipe.js.map +1 -0
- package/dist/autoCompletion.js +1 -1
- package/dist/autoCompletion.js.map +1 -1
- package/dist/cli.js +19 -9
- package/dist/cli.js.map +1 -1
- package/dist/configManager.d.ts +17 -4
- package/dist/configManager.js +1 -1
- package/dist/configManager.js.map +1 -1
- package/dist/mcpCommands.js +1 -1
- package/dist/mcpCommands.js.map +1 -1
- package/dist/mcpServerProxy.js +7 -7
- package/dist/mcpServerProxy.js.map +1 -1
- package/dist/modelScopeMCPClient.d.ts +35 -0
- package/dist/modelScopeMCPClient.js +3 -0
- package/dist/modelScopeMCPClient.js.map +1 -0
- package/dist/multiEndpointMCPPipe.d.ts +29 -0
- package/dist/multiEndpointMCPPipe.js +8 -0
- package/dist/multiEndpointMCPPipe.js.map +1 -0
- package/dist/package.json +3 -1
- package/dist/services/mcpServer.d.ts +20 -0
- package/dist/services/mcpServer.js +12 -0
- package/dist/services/mcpServer.js.map +1 -0
- package/dist/webServer.js +3 -3
- package/dist/webServer.js.map +1 -1
- package/docs/images/integrate-to-cherry-studio.png +0 -0
- package/docs/images/integrate-to-cursor.png +0 -0
- package/package.json +22 -20
- package/web/dist/assets/index-FD98vGpI.js.map +1 -1
- package/dist/mcpPipe.d.ts +0 -41
- package/dist/mcpPipe.js +0 -11
- package/dist/mcpPipe.js.map +0 -1
- package/web/README.md +0 -169
package/README.md
CHANGED
|
@@ -9,16 +9,18 @@
|
|
|
9
9
|
|
|
10
10
|

|
|
11
11
|
|
|
12
|
-
##
|
|
12
|
+
## 功能特色
|
|
13
13
|
|
|
14
14
|
- 支持 小智(xiaozhi.me) 官方服务器接入点
|
|
15
|
-
- 支持
|
|
16
|
-
- 支持
|
|
17
|
-
- 支持
|
|
18
|
-
- 支持 动态控制 MCP Server
|
|
19
|
-
- 支持
|
|
20
|
-
- 支持
|
|
21
|
-
- 支持
|
|
15
|
+
- 支持 作为普通 MCP Server 集成到 Cursor/Cherry Studio 等客户端
|
|
16
|
+
- 支持 配置多个小智接入点,实现多个小智设备共享一个 MCP 配置
|
|
17
|
+
- 支持 通过标准方式聚合多个 MCP Server
|
|
18
|
+
- 支持 动态控制 MCP Server 工具的可见性,避免由于无用工具过多导致的小智服务端异常
|
|
19
|
+
- 支持 本地化部署的开源服务端集成,你可以使用和小智官方服务端一样的 RPC 通信或直接使用标准 MCP 集成方式
|
|
20
|
+
- 支持 Web 网页可视化配置(允许自定义 IP 和端口,你能将 xiaozhi-client 部署在设备 A,然后在设备 B 通过网页控制 xiaozhi-client)
|
|
21
|
+
- 支持 集成 ModelScope 的远程MCP服务
|
|
22
|
+
- 支持 通过模板创建 xiaozhi-client 项目 (xiaozhi create \<my-app\> --template hello-world)
|
|
23
|
+
- 支持 后台运行(xiaozhi start -d)
|
|
22
24
|
|
|
23
25
|
## 快速上手
|
|
24
26
|
|
|
@@ -94,6 +96,78 @@ xiaozhi mcp list
|
|
|
94
96
|
xiaozhi mcp list --tools
|
|
95
97
|
```
|
|
96
98
|
|
|
99
|
+
## 多接入点配置
|
|
100
|
+
|
|
101
|
+
xiaozhi-client 支持同时连接多个小智 AI 接入点
|
|
102
|
+
|
|
103
|
+
### 配置方式
|
|
104
|
+
|
|
105
|
+
在 `xiaozhi.config.json` 中,`mcpEndpoint` 字段支持两种配置方式:
|
|
106
|
+
|
|
107
|
+
#### 方式一:单接入点配置(字符串)
|
|
108
|
+
|
|
109
|
+
```json
|
|
110
|
+
{
|
|
111
|
+
"mcpEndpoint": "wss://api.xiaozhi.me/mcp/your-endpoint-id"
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
#### 方式二:多接入点配置(字符串数组)
|
|
116
|
+
|
|
117
|
+
```json
|
|
118
|
+
{
|
|
119
|
+
"mcpEndpoint": [
|
|
120
|
+
"wss://api.xiaozhi.me/mcp/endpoint-1",
|
|
121
|
+
"wss://api.xiaozhi.me/mcp/endpoint-2",
|
|
122
|
+
"wss://api.xiaozhi.me/mcp/endpoint-3"
|
|
123
|
+
]
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### 使用命令管理接入点
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
# 查看当前配置的所有接入点
|
|
131
|
+
xiaozhi endpoint list
|
|
132
|
+
|
|
133
|
+
# 添加新的接入点
|
|
134
|
+
xiaozhi endpoint add wss://api.xiaozhi.me/mcp/new-endpoint
|
|
135
|
+
|
|
136
|
+
# 移除指定的接入点
|
|
137
|
+
xiaozhi endpoint remove wss://api.xiaozhi.me/mcp/old-endpoint
|
|
138
|
+
|
|
139
|
+
# 设置接入点(覆盖现有配置)
|
|
140
|
+
xiaozhi endpoint set wss://api.xiaozhi.me/mcp/endpoint-1 wss://api.xiaozhi.me/mcp/endpoint-2
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### 示例配置
|
|
144
|
+
|
|
145
|
+
```json
|
|
146
|
+
{
|
|
147
|
+
"mcpEndpoint": [
|
|
148
|
+
"wss://api.xiaozhi.me/mcp/305847/abc123",
|
|
149
|
+
"wss://api.xiaozhi.me/mcp/468832/def456"
|
|
150
|
+
],
|
|
151
|
+
"mcpServers": {
|
|
152
|
+
"calculator": {
|
|
153
|
+
"command": "node",
|
|
154
|
+
"args": ["./mcpServers/calculator.js"]
|
|
155
|
+
},
|
|
156
|
+
"datetime": {
|
|
157
|
+
"command": "node",
|
|
158
|
+
"args": ["./mcpServers/datetime.js"]
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### 注意事项
|
|
165
|
+
|
|
166
|
+
- 多接入点配置时,每个接入点会启动独立的 MCP 进程
|
|
167
|
+
- 确保每个接入点的 URL 都是有效的
|
|
168
|
+
- 接入点之间相互独立,一个接入点的故障不会影响其他接入点
|
|
169
|
+
- 建议根据实际需求合理配置接入点数量
|
|
170
|
+
|
|
97
171
|
## ModelScope MCP 服务集成
|
|
98
172
|
|
|
99
173
|
xiaozhi-client 现已支持接入 [ModelScope](https://www.modelscope.cn/mcp) 托管的 MCP 服务。
|
|
@@ -139,6 +213,7 @@ xiaozhi-client 现已支持接入 [ModelScope](https://www.modelscope.cn/mcp)
|
|
|
139
213
|
```
|
|
140
214
|
|
|
141
215
|
3. 启动服务:
|
|
216
|
+
|
|
142
217
|
```bash
|
|
143
218
|
xiaozhi start
|
|
144
219
|
```
|
|
@@ -302,3 +377,88 @@ xiaozhi-client 提供了一个现代化的 Web UI 界面,让配置 MCP 服务
|
|
|
302
377
|
```bash
|
|
303
378
|
xiaozhi ui
|
|
304
379
|
```
|
|
380
|
+
|
|
381
|
+
## 作为 MCP Server 集成到其他客户端
|
|
382
|
+
|
|
383
|
+
> 需升级至 `1.5.0` 及以上版本
|
|
384
|
+
|
|
385
|
+
xiaozhi-client 不仅可以作为小智 AI 的客户端使用,还可以作为标准的 MCP Server 被 Cursor、Cherry Studio 等支持 MCP 协议的客户端集成。
|
|
386
|
+
|
|
387
|
+
这样做的好处是你无需在多个客户端中重复配置 MCP Server,只需要在 xiaozhi.config.json 中配置一遍 MCP 服务,即可在任意客户端集成。
|
|
388
|
+
|
|
389
|
+
并且,由于 xiaozhi-client 允许你自定义暴露哪些 MCP Server tools 因此你可以选择性的定制自己的工具集。
|
|
390
|
+
|
|
391
|
+

|
|
392
|
+

|
|
393
|
+
|
|
394
|
+
### 方式一:使用 stdio 模式(推荐)
|
|
395
|
+
|
|
396
|
+
第一步:确保已全局安装 xiaozhi-client:
|
|
397
|
+
|
|
398
|
+
```bash
|
|
399
|
+
npm install -g xiaozhi-client
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
第二步:在 客户端 的 MCP 配置中添加:
|
|
403
|
+
|
|
404
|
+
```json
|
|
405
|
+
{
|
|
406
|
+
"mcpServers": {
|
|
407
|
+
"xiaozhi-client": {
|
|
408
|
+
"command": "xiaozhi",
|
|
409
|
+
"args": ["start", "--stdio"]
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
提示:如果需要指定配置文件位置,可以使用环境变量
|
|
416
|
+
|
|
417
|
+
配置文件的查找顺序
|
|
418
|
+
|
|
419
|
+
1. 当前工作目录
|
|
420
|
+
2. 通过 `XIAOZHI_CONFIG_DIR` 环境变量指定的目录
|
|
421
|
+
|
|
422
|
+
```json
|
|
423
|
+
{
|
|
424
|
+
"mcpServers": {
|
|
425
|
+
"xiaozhi-client": {
|
|
426
|
+
"command": "xiaozhi",
|
|
427
|
+
"args": ["start", "--stdio"],
|
|
428
|
+
"env": {
|
|
429
|
+
"XIAOZHI_CONFIG_DIR": "/path/to/your/config/directory"
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
### 方式二:使用 HTTP Server 模式
|
|
437
|
+
|
|
438
|
+
> 如果你将 xiaozhi-client 装在 docker 中使用,可以通过 http server 的方式暴露给外部客户端
|
|
439
|
+
|
|
440
|
+
第一步:启动 xiaozhi-client 的 HTTP Server:
|
|
441
|
+
|
|
442
|
+
```bash
|
|
443
|
+
# 使用默认端口 3000
|
|
444
|
+
xiaozhi start --server
|
|
445
|
+
|
|
446
|
+
# 使用自定义端口
|
|
447
|
+
xiaozhi start --server 8080
|
|
448
|
+
|
|
449
|
+
# 后台运行
|
|
450
|
+
xiaozhi start --server --daemon
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
第二步:在 客户端 中配置 SSE 连接:
|
|
454
|
+
|
|
455
|
+
```json
|
|
456
|
+
{
|
|
457
|
+
"mcpServers": {
|
|
458
|
+
"xiaozhi-client": {
|
|
459
|
+
"type": "sse",
|
|
460
|
+
"url": "http://localhost:3000/sse"
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var $=Object.defineProperty;var l=(s,e)=>$(s,"name",{value:e,configurable:!0});import c from"process";import{fileURLToPath as H}from"url";import{config as G}from"dotenv";import{copyFileSync as R,existsSync as I,readFileSync as A,writeFileSync as x}from"fs";import{dirname as O,resolve as P}from"path";import{fileURLToPath as F}from"url";var D=O(F(import.meta.url)),w={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},S=class s{static{l(this,"ConfigManager")}static instance;defaultConfigPath;config=null;constructor(){this.defaultConfigPath=P(D,"xiaozhi.config.default.json")}getConfigFilePath(){let e=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return P(e,"xiaozhi.config.json")}static getInstance(){return s.instance||(s.instance=new s),s.instance}configExists(){let e=this.getConfigFilePath();return I(e)}initConfig(){if(!I(this.defaultConfigPath))throw new Error("\u9ED8\u8BA4\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.default.json \u4E0D\u5B58\u5728");if(this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.json \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u521D\u59CB\u5316");let e=this.getConfigFilePath();R(this.defaultConfigPath,e),this.config=null}loadConfig(){if(!this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.json \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C xiaozhi init \u521D\u59CB\u5316\u914D\u7F6E");try{let e=this.getConfigFilePath(),t=A(e,"utf8"),n=JSON.parse(t);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 n of t.mcpEndpoint)if(typeof n!="string"||n.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[n,o]of Object.entries(t.mcpServers)){if(!o||typeof o!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${n} \u65E0\u6548`);let i=o;if(i.type==="sse"){if(!i.url||typeof i.url!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${n}.url \u65E0\u6548`)}else{if(!i.command||typeof i.command!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${n}.command \u65E0\u6548`);if(!Array.isArray(i.args))throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${n}.args \u5FC5\u987B\u662F\u6570\u7EC4`);if(i.env&&typeof i.env!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${n}.env \u5FC5\u987B\u662F\u5BF9\u8C61`)}}}getConfig(){return this.config||(this.config=this.loadConfig()),JSON.parse(JSON.stringify(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 o of e)if(!o||typeof o!="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 n={...this.getConfig(),mcpEndpoint:e};this.saveConfig(n)}addMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getConfig(),n=this.getMcpEndpoints();if(n.includes(e))throw new Error(`MCP \u7AEF\u70B9 ${e} \u5DF2\u5B58\u5728`);let o=[...n,e],i={...t,mcpEndpoint:o};this.saveConfig(i)}removeMcpEndpoint(e){if(!e||typeof e!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t=this.getConfig(),n=this.getMcpEndpoints();if(n.indexOf(e)===-1)throw new Error(`MCP \u7AEF\u70B9 ${e} \u4E0D\u5B58\u5728`);if(n.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");let i=n.filter(u=>u!==e),a={...t,mcpEndpoint:i};this.saveConfig(a)}updateMcpServer(e,t){if(!e||typeof e!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if("type"in t&&t.type==="sse"){if(!t.url||typeof t.url!="string")throw new Error("SSE \u670D\u52A1\u914D\u7F6E\u7684 url \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else{let i=t;if(!i.command||typeof i.command!="string")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 command \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!Array.isArray(i.args))throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4");if(i.env&&typeof i.env!="object")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61")}let n=this.getConfig(),o={...n,mcpServers:{...n.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 n={...t.mcpServers};delete n[e];let o={...t,mcpServers:n};this.saveConfig(o)}updateServerToolsConfig(e,t){let o={...this.getConfig()};o.mcpServerConfig||(o.mcpServerConfig={}),o.mcpServerConfig[e]={tools:t},this.saveConfig(o)}setToolEnabled(e,t,n,o){let a={...this.getConfig()};a.mcpServerConfig||(a.mcpServerConfig={}),a.mcpServerConfig[e]||(a.mcpServerConfig[e]={tools:{}}),a.mcpServerConfig[e].tools[t]={enable:n,...o&&{description:o}},this.saveConfig(a)}saveConfig(e){try{this.validateConfig(e);let t=this.getConfigFilePath(),n=JSON.stringify(e,null,2);x(t,n,"utf8"),this.config=e}catch(t){throw new Error(`\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}reloadConfig(){this.config=null}getConfigPath(){return this.getConfigFilePath()}getDefaultConfigPath(){return this.defaultConfigPath}getConnectionConfig(){let t=this.getConfig().connection||{};return{heartbeatInterval:t.heartbeatInterval??w.heartbeatInterval,heartbeatTimeout:t.heartbeatTimeout??w.heartbeatTimeout,reconnectInterval:t.reconnectInterval??w.reconnectInterval}}getHeartbeatInterval(){return this.getConnectionConfig().heartbeatInterval}getHeartbeatTimeout(){return this.getConnectionConfig().heartbeatTimeout}getReconnectInterval(){return this.getConnectionConfig().reconnectInterval}updateConnectionConfig(e){let t=this.getConfig(),o={...t.connection||{},...e},i={...t,connection:o};this.saveConfig(i)}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.getConfig(),o={...t.modelscope||{},...e},i={...t,modelscope:o};this.saveConfig(i)}setModelScopeApiKey(e){if(!e||typeof e!="string")throw new Error("API Key \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");this.updateModelScopeConfig({apiKey:e})}getWebUIConfig(){return this.getConfig().webUI||{}}getWebUIPort(){return this.getWebUIConfig().port??9999}updateWebUIConfig(e){let t=this.getConfig(),o={...t.webUI||{},...e},i={...t,webUI:o};this.saveConfig(i)}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})}},p=S.getInstance();import m from"fs";import N from"path";import C from"chalk";import{createConsola as W}from"consola";function k(s){let e=s.getFullYear(),t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0"),o=String(s.getHours()).padStart(2,"0"),i=String(s.getMinutes()).padStart(2,"0"),a=String(s.getSeconds()).padStart(2,"0");return`${e}-${t}-${n} ${o}:${i}:${a}`}l(k,"formatDateTime");var E=class{static{l(this,"Logger")}logFilePath=null;writeStream=null;consolaInstance;isDaemonMode;constructor(){this.isDaemonMode=process.env.XIAOZHI_DAEMON==="true",this.consolaInstance=W({formatOptions:{date:!1,colors:!0,compact:!0},fancy:!1});let e=this.isDaemonMode;this.consolaInstance.setReporters([{log:l(t=>{let n={info:"INFO",success:"SUCCESS",warn:"WARN",error:"ERROR",debug:"DEBUG",log:"LOG"},o={info:C.blue,success:C.green,warn:C.yellow,error:C.red,debug:C.gray,log:l(d=>d,"log")},i=n[t.type]||t.type.toUpperCase(),a=o[t.type]||(d=>d),u=k(new Date),T=a(`[${i}]`),y=`[${u}] ${T} ${t.args.join(" ")}`;if(!e)try{console.error(y)}catch(d){if(d instanceof Error&&d.message?.includes("EPIPE"))return;throw d}},"log")}])}initLogFile(e){this.logFilePath=N.join(e,"xiaozhi.log"),m.existsSync(this.logFilePath)||m.writeFileSync(this.logFilePath,""),this.writeStream=m.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"})}logToFile(e,t,...n){if(this.writeStream){let i=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${t}`,a=n.length>0?`${i} ${n.map(u=>typeof u=="object"?JSON.stringify(u):String(u)).join(" ")}`:i;this.writeStream.write(`${a}
|
|
3
|
+
`)}}enableFileLogging(e){e&&!this.writeStream&&this.logFilePath?this.writeStream=m.createWriteStream(this.logFilePath,{flags:"a",encoding:"utf8"}):!e&&this.writeStream&&(this.writeStream.end(),this.writeStream=null)}info(e,...t){this.consolaInstance.info(e,...t),this.logToFile("info",e,...t)}success(e,...t){this.consolaInstance.success(e,...t),this.logToFile("success",e,...t)}warn(e,...t){this.consolaInstance.warn(e,...t),this.logToFile("warn",e,...t)}error(e,...t){this.consolaInstance.error(e,...t),this.logToFile("error",e,...t)}debug(e,...t){this.consolaInstance.debug(e,...t),this.logToFile("debug",e,...t)}log(e,...t){this.consolaInstance.log(e,...t),this.logToFile("log",e,...t)}withTag(e){return this}close(){this.writeStream&&(this.writeStream.end(),this.writeStream=null)}},h=new E;import{spawn as _}from"child_process";import f from"process";import b from"ws";var r=h.withTag("MULTI_MCP_PIPE");f.env.XIAOZHI_DAEMON==="true"&&f.env.XIAOZHI_CONFIG_DIR&&(h.initLogFile(f.env.XIAOZHI_CONFIG_DIR),h.enableFileLogging(!0));var v=class{static{l(this,"MultiEndpointMCPPipe")}mcpScript;endpoints;shouldReconnect;shutdownResolve;connectionConfig;constructor(e,t){this.mcpScript=e,this.endpoints=new Map,this.shouldReconnect=!0,r.info(t.length===1?`\u521D\u59CB\u5316\u5355\u7AEF\u70B9\u8FDE\u63A5: ${t[0]}`:`\u521D\u59CB\u5316\u591A\u7AEF\u70B9\u8FDE\u63A5\uFF08${t.length} \u4E2A\u7AEF\u70B9\uFF09`);for(let n of t)this.endpoints.set(n,{url:n,websocket:null,isConnected:!1,reconnectAttempt:0,process:null,stdoutBuffer:""});try{this.connectionConfig=p.getConnectionConfig(),r.info(`\u8FDE\u63A5\u914D\u7F6E: \u5FC3\u8DF3\u95F4\u9694=${this.connectionConfig.heartbeatInterval}ms, \u5FC3\u8DF3\u8D85\u65F6=${this.connectionConfig.heartbeatTimeout}ms, \u91CD\u8FDE\u95F4\u9694=${this.connectionConfig.reconnectInterval}ms`)}catch(n){this.connectionConfig={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},r.warn(`\u65E0\u6CD5\u83B7\u53D6\u8FDE\u63A5\u914D\u7F6E\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u503C: ${n instanceof Error?n.message:String(n)}`)}}async start(){return await this.connectToAllEndpoints(),this.reportStatusToWebUI(),new Promise(e=>{this.shutdownResolve=e})}async connectToAllEndpoints(){let e=[];for(let[t,n]of this.endpoints)e.push(this.connectToEndpoint(t));await Promise.allSettled(e)}async connectToEndpoint(e){let t=this.endpoints.get(e);if(!t||t.isConnected)return;this.startMCPProcessForEndpoint(e),r.info(`\u6B63\u5728\u8FDE\u63A5\u5230 WebSocket \u670D\u52A1\u5668: ${e}`);let n=new b(e);t.websocket=n,n.on("open",()=>{r.info(`\u6210\u529F\u8FDE\u63A5\u5230 WebSocket \u670D\u52A1\u5668: ${e}`),t.isConnected=!0,t.reconnectAttempt=0,this.reportStatusToWebUI(),this.startHeartbeat(e)}),n.on("message",o=>{let i=o.toString();r.info(`<< [${e}] WebSocket\u6536\u5230\u6D88\u606F: ${i}`),t.process?.stdin&&!t.process.stdin.destroyed&&t.process.stdin.write(`${i}
|
|
4
|
+
`)}),n.on("close",(o,i)=>{r.error(`[${e}] WebSocket \u8FDE\u63A5\u5DF2\u5173\u95ED: ${o} ${i}`),t.isConnected=!1,t.websocket=null,this.stopHeartbeat(e),this.reportStatusToWebUI(),this.shouldReconnect&&o!==4004&&this.scheduleReconnect(e)}),n.on("error",o=>{r.error(`[${e}] WebSocket \u9519\u8BEF: ${o.message}`),t.isConnected=!1,this.stopHeartbeat(e)}),n.on("pong",()=>{t.heartbeatTimeoutTimer&&(clearTimeout(t.heartbeatTimeoutTimer),t.heartbeatTimeoutTimer=void 0)})}scheduleReconnect(e){let t=this.endpoints.get(e);!t||!this.shouldReconnect||(t.reconnectTimer&&clearTimeout(t.reconnectTimer),t.reconnectAttempt++,r.info(`[${e}] \u8BA1\u5212\u5728 ${(this.connectionConfig.reconnectInterval/1e3).toFixed(2)} \u79D2\u540E\u8FDB\u884C\u7B2C ${t.reconnectAttempt} \u6B21\u91CD\u8FDE\u5C1D\u8BD5...`),t.reconnectTimer=setTimeout(()=>{this.shouldReconnect&&((!t.process||t.process.killed)&&r.info(`[${e}] MCP \u8FDB\u7A0B\u672A\u8FD0\u884C\uFF0C\u5C06\u5728\u91CD\u8FDE\u65F6\u542F\u52A8...`),this.connectToEndpoint(e))},this.connectionConfig.reconnectInterval))}startMCPProcessForEndpoint(e){let t=this.endpoints.get(e);if(!t){r.error(`\u7AEF\u70B9\u4E0D\u5B58\u5728: ${e}`);return}if(t.process){r.info(`[${e}] MCP \u8FDB\u7A0B\u5DF2\u5728\u8FD0\u884C`);return}r.info(`[${e}] \u6B63\u5728\u542F\u52A8 MCP \u8FDB\u7A0B`),t.process=_("node",[this.mcpScript],{stdio:["pipe","pipe","pipe"]}),t.process.stdout?.on("data",n=>{t.stdoutBuffer+=n.toString();let o=t.stdoutBuffer.split(`
|
|
5
|
+
`);t.stdoutBuffer=o.pop()||"";for(let i of o)i.trim()&&this.handleMCPMessage(e,i)}),t.process.stderr?.on("data",n=>{if(f.env.XIAOZHI_DAEMON!=="true")try{f.stderr.write(n)}catch{}}),t.process.on("exit",(n,o)=>{r.warn(`[${e}] MCP \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF0C\u9000\u51FA\u7801: ${n}, \u4FE1\u53F7: ${o}`),t.process=null,this.shouldReconnect&&o!=="SIGTERM"&&o!=="SIGKILL"&&r.info(`[${e}] MCP \u8FDB\u7A0B\u610F\u5916\u9000\u51FA\uFF0C\u5C06\u5728\u4E0B\u6B21\u91CD\u8FDE\u65F6\u5C1D\u8BD5\u91CD\u542F`)}),t.process.on("error",n=>{r.error(`[${e}] \u8FDB\u7A0B\u9519\u8BEF: ${n.message}`),t.process=null,this.shouldReconnect&&r.info(`[${e}] MCP \u8FDB\u7A0B\u53D1\u751F\u9519\u8BEF\uFF0C\u5C06\u5728\u4E0B\u6B21\u91CD\u8FDE\u65F6\u5C1D\u8BD5\u91CD\u542F`)})}handleMCPMessage(e,t){r.info(`>> [${e}] mcpServerProxy\u53D1\u9001\u6D88\u606F\u957F\u5EA6: ${t.length} \u5B57\u8282`),r.info(`>> [${e}] mcpServerProxy\u53D1\u9001\u6D88\u606F: ${t.substring(0,500)}...`),this.sendToEndpoint(e,t)}sendToEndpoint(e,t){let n=this.endpoints.get(e);if(!n||!n.websocket||n.websocket.readyState!==b.OPEN){r.warn(`[${e}] \u7AEF\u70B9\u4E0D\u53EF\u7528\uFF0C\u6D88\u606F\u65E0\u6CD5\u53D1\u9001`);return}try{n.websocket.send(`${t}
|
|
6
|
+
`),r.info(`>> [${e}] \u6210\u529F\u53D1\u9001\u6D88\u606F\u5230 WebSocket`)}catch(o){r.error(`>> [${e}] \u53D1\u9001\u6D88\u606F\u5230 WebSocket \u5931\u8D25: ${o}`)}}startHeartbeat(e){let t=this.endpoints.get(e);t&&(this.stopHeartbeat(e),t.heartbeatTimer=setInterval(()=>{t.websocket&&t.websocket.readyState===b.OPEN&&(t.websocket.ping(),t.heartbeatTimeoutTimer=setTimeout(()=>{r.warn(`[${e}] \u5FC3\u8DF3\u8D85\u65F6\uFF0C\u65AD\u5F00\u8FDE\u63A5`),t.websocket?.close()},this.connectionConfig.heartbeatTimeout))},this.connectionConfig.heartbeatInterval))}stopHeartbeat(e){let t=this.endpoints.get(e);t&&(t.heartbeatTimer&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0),t.heartbeatTimeoutTimer&&(clearTimeout(t.heartbeatTimeoutTimer),t.heartbeatTimeoutTimer=void 0))}cleanup(){for(let e of this.endpoints.keys())this.stopHeartbeat(e);for(let[e,t]of this.endpoints){if(t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.stdoutBuffer="",t.process){r.info(`[${e}] \u6B63\u5728\u7EC8\u6B62 MCP \u8FDB\u7A0B`);try{t.process.kill("SIGTERM"),setTimeout(()=>{t.process&&!t.process.killed&&t.process.kill("SIGKILL")},5e3)}catch(n){r.error(`[${e}] \u7EC8\u6B62\u8FDB\u7A0B\u65F6\u51FA\u9519: ${n instanceof Error?n.message:String(n)}`)}t.process=null}if(t.websocket){try{t.websocket.close()}catch(n){r.warn(`[${e}] \u5173\u95ED WebSocket \u65F6\u51FA\u9519: ${n}`)}t.websocket=null}}}shutdown(){r.info("\u6B63\u5728\u5173\u95ED Multi-Endpoint MCP Pipe..."),this.shouldReconnect=!1;for(let e of this.endpoints.values())e.isConnected=!1;this.reportStatusToWebUI(),this.cleanup(),this.shutdownResolve&&this.shutdownResolve(),setTimeout(()=>{f.exit(0)},100)}async reportStatusToWebUI(){if(!(f.env.NODE_ENV==="test"||f.env.VITEST==="true"))try{let e=p.getWebUIPort(),t=new b(`ws://localhost:${e}`);t.on("open",()=>{let n=[];for(let[i,a]of this.endpoints)n.push({url:i,connected:a.isConnected});let o={type:"clientStatus",data:{status:this.hasAnyConnection()?"connected":"disconnected",mcpEndpoints:n,activeMCPServers:[],lastHeartbeat:Date.now()}};t.send(JSON.stringify(o)),r.debug("\u5DF2\u5411 Web UI \u62A5\u544A\u72B6\u6001"),setTimeout(()=>{t.close()},1e3)}),t.on("error",n=>{r.debug(`Web UI \u8FDE\u63A5\u5931\u8D25\uFF08\u53EF\u80FD\u672A\u8FD0\u884C\uFF09: ${n.message}`)})}catch(e){r.debug(`\u5411 Web UI \u62A5\u544A\u72B6\u6001\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}hasAnyConnection(){for(let e of this.endpoints.values())if(e.isConnected)return!0;return!1}};function M(s){let e=f.env.XIAOZHI_DAEMON==="true";f.on("SIGINT",()=>{r.info("\u6536\u5230\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u6B63\u5728\u5173\u95ED..."),s.shutdown()}),f.on("SIGTERM",()=>{r.info("\u6536\u5230\u7EC8\u6B62\u4FE1\u53F7\uFF0C\u6B63\u5728\u5173\u95ED..."),s.shutdown()}),e&&(f.on("SIGHUP",()=>{r.info("\u6536\u5230 SIGHUP \u4FE1\u53F7\uFF08\u7EC8\u7AEF\u5DF2\u5173\u95ED\uFF09\uFF0C\u7EE7\u7EED\u5728\u5B88\u62A4\u8FDB\u7A0B\u6A21\u5F0F\u4E0B\u8FD0\u884C...")}),f.on("uncaughtException",t=>{t.message?.includes("EPIPE")||r.error(`\u672A\u6355\u83B7\u7684\u5F02\u5E38: ${t.message||t}
|
|
7
|
+
${t.stack||""}`)}),f.on("unhandledRejection",(t,n)=>{r.error(`\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${t instanceof Error?t.message:String(t)}`)}))}l(M,"setupSignalHandlers");G();var g=h.withTag("ADAPTIVE_MCP_PIPE");c.env.XIAOZHI_DAEMON==="true"&&c.env.XIAOZHI_CONFIG_DIR&&(h.initLogFile(c.env.XIAOZHI_CONFIG_DIR),h.enableFileLogging(!0));async function L(){c.argv.length<3&&(g.error("\u7528\u6CD5: node adaptiveMCPPipe.js <mcp_script>"),c.exit(1));let s=c.argv[2],e;try{if(c.env.XIAOZHI_DAEMON!=="true")try{c.stderr.write(`[DEBUG] XIAOZHI_CONFIG_DIR: ${c.env.XIAOZHI_CONFIG_DIR}
|
|
8
|
+
`),c.stderr.write(`[DEBUG] process.cwd(): ${c.cwd()}
|
|
9
|
+
`),c.stderr.write(`[DEBUG] configManager.getConfigPath(): ${p.getConfigPath()}
|
|
10
|
+
`),c.stderr.write(`[DEBUG] configManager.configExists(): ${p.configExists()}
|
|
11
|
+
`)}catch{}if(p.configExists())e=p.getMcpEndpoints(),g.info(`\u4F7F\u7528\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684 MCP \u7AEF\u70B9\uFF08${e.length} \u4E2A\uFF09`);else{let o=c.env.MCP_ENDPOINT;o||(g.error("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\u4E14\u672A\u8BBE\u7F6E MCP_ENDPOINT \u73AF\u5883\u53D8\u91CF"),g.error('\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\uFF0C\u6216\u8BBE\u7F6E MCP_ENDPOINT \u73AF\u5883\u53D8\u91CF'),c.exit(1)),e=[o],g.info("\u4F7F\u7528\u73AF\u5883\u53D8\u91CF\u4E2D\u7684 MCP \u7AEF\u70B9\uFF08\u5EFA\u8BAE\u4F7F\u7528\u914D\u7F6E\u6587\u4EF6\uFF09")}}catch(o){g.error(`\u8BFB\u53D6\u914D\u7F6E\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`);let i=c.env.MCP_ENDPOINT;i||(g.error('\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\uFF0C\u6216\u8BBE\u7F6E MCP_ENDPOINT \u73AF\u5883\u53D8\u91CF'),c.exit(1)),e=[i],g.info("\u4F7F\u7528\u73AF\u5883\u53D8\u91CF\u4E2D\u7684 MCP \u7AEF\u70B9\u4F5C\u4E3A\u5907\u7528\u65B9\u6848")}e.length===0&&(g.error("\u6CA1\u6709\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9"),c.exit(1));let t=e.filter(o=>!o||o.includes("<\u8BF7\u586B\u5199")?(g.warn(`\u8DF3\u8FC7\u65E0\u6548\u7AEF\u70B9: ${o}`),!1):!0);t.length===0&&(g.error("\u6CA1\u6709\u6709\u6548\u7684 MCP \u7AEF\u70B9"),g.error('\u8BF7\u8FD0\u884C "xiaozhi config mcpEndpoint <your-endpoint-url>" \u8BBE\u7F6E\u7AEF\u70B9'),c.exit(1)),g.info(t.length===1?"\u542F\u52A8\u5355\u7AEF\u70B9\u8FDE\u63A5":`\u542F\u52A8\u591A\u7AEF\u70B9\u8FDE\u63A5\uFF08${t.length} \u4E2A\u7AEF\u70B9\uFF09`);let n=new v(s,t);M(n);try{await n.start()}catch(o){g.error(`\u7A0B\u5E8F\u6267\u884C\u9519\u8BEF: ${o instanceof Error?o.message:String(o)}`),c.exit(1)}}l(L,"main");var j=import.meta.url,B=H(j),X=c.argv[1];B===X&&L().catch(s=>{g.error(`\u672A\u5904\u7406\u7684\u9519\u8BEF: ${s instanceof Error?s.message:String(s)}`),c.exit(1)});export{L as main};
|
|
12
|
+
//# sourceMappingURL=adaptiveMCPPipe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adaptiveMCPPipe.ts","../src/configManager.ts","../src/logger.ts","../src/multiEndpointMCPPipe.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * Adaptive MCP Pipe - 自适应选择单端点或多端点模式\n * 根据配置自动选择使用 MCPPipe 或 MultiEndpointMCPPipe\n */\n\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\nimport { config } from \"dotenv\";\nimport { configManager } from \"./configManager.js\";\nimport { logger as globalLogger } from \"./logger.js\";\nimport {\n MultiEndpointMCPPipe,\n setupSignalHandlers,\n} from \"./multiEndpointMCPPipe.js\";\n\n// Load environment variables\nconfig();\n\n// 为 Adaptive MCP Pipe 创建带标签的 logger\nconst logger = globalLogger.withTag(\"ADAPTIVE_MCP_PIPE\");\n\n// 如果在守护进程模式下运行,初始化日志文件\nif (process.env.XIAOZHI_DAEMON === \"true\" && process.env.XIAOZHI_CONFIG_DIR) {\n globalLogger.initLogFile(process.env.XIAOZHI_CONFIG_DIR);\n globalLogger.enableFileLogging(true);\n}\n\n// Main function\nexport async function main() {\n if (process.argv.length < 3) {\n logger.error(\"用法: node adaptiveMCPPipe.js <mcp_script>\");\n process.exit(1);\n }\n\n const mcpScript = process.argv[2];\n\n // 获取端点配置\n let endpoints: string[];\n\n try {\n // 调试信息 - 只在非守护进程模式下输出\n if (process.env.XIAOZHI_DAEMON !== \"true\") {\n try {\n process.stderr.write(\n `[DEBUG] XIAOZHI_CONFIG_DIR: ${process.env.XIAOZHI_CONFIG_DIR}\\n`\n );\n process.stderr.write(`[DEBUG] process.cwd(): ${process.cwd()}\\n`);\n process.stderr.write(\n `[DEBUG] configManager.getConfigPath(): ${configManager.getConfigPath()}\\n`\n );\n process.stderr.write(\n `[DEBUG] configManager.configExists(): ${configManager.configExists()}\\n`\n );\n } catch (error) {\n // 忽略写入错误\n }\n }\n\n // 首先尝试从配置文件读取\n if (configManager.configExists()) {\n endpoints = configManager.getMcpEndpoints();\n logger.info(`使用配置文件中的 MCP 端点(${endpoints.length} 个)`);\n } else {\n // 如果配置文件不存在,尝试从环境变量读取(向后兼容)\n const envEndpoint = process.env.MCP_ENDPOINT;\n if (!envEndpoint) {\n logger.error(\"配置文件不存在且未设置 MCP_ENDPOINT 环境变量\");\n logger.error(\n '请运行 \"xiaozhi init\" 初始化配置,或设置 MCP_ENDPOINT 环境变量'\n );\n process.exit(1);\n }\n endpoints = [envEndpoint];\n logger.info(\"使用环境变量中的 MCP 端点(建议使用配置文件)\");\n }\n } catch (error) {\n logger.error(\n `读取配置失败: ${error instanceof Error ? error.message : String(error)}`\n );\n\n // 尝试从环境变量读取作为备用方案\n const envEndpoint = process.env.MCP_ENDPOINT;\n if (!envEndpoint) {\n logger.error(\n '请运行 \"xiaozhi init\" 初始化配置,或设置 MCP_ENDPOINT 环境变量'\n );\n process.exit(1);\n }\n endpoints = [envEndpoint];\n logger.info(\"使用环境变量中的 MCP 端点作为备用方案\");\n }\n\n // 验证端点\n if (endpoints.length === 0) {\n logger.error(\"没有配置任何 MCP 端点\");\n process.exit(1);\n }\n\n // 过滤无效端点\n const validEndpoints = endpoints.filter((endpoint) => {\n if (!endpoint || endpoint.includes(\"<请填写\")) {\n logger.warn(`跳过无效端点: ${endpoint}`);\n return false;\n }\n return true;\n });\n\n if (validEndpoints.length === 0) {\n logger.error(\"没有有效的 MCP 端点\");\n logger.error(\n '请运行 \"xiaozhi config mcpEndpoint <your-endpoint-url>\" 设置端点'\n );\n process.exit(1);\n }\n\n // 统一使用 MultiEndpointMCPPipe 处理所有情况\n // 无论是单端点还是多端点,都作为数组处理,简化架构\n logger.info(\n validEndpoints.length === 1\n ? \"启动单端点连接\"\n : `启动多端点连接(${validEndpoints.length} 个端点)`\n );\n\n const mcpPipe = new MultiEndpointMCPPipe(mcpScript, validEndpoints);\n setupSignalHandlers(mcpPipe);\n\n try {\n await mcpPipe.start();\n } catch (error) {\n logger.error(\n `程序执行错误: ${error instanceof Error ? error.message : String(error)}`\n );\n process.exit(1);\n }\n}\n\n// Run if this file is executed directly\nconst currentFileUrl = import.meta.url;\nconst scriptPath = fileURLToPath(currentFileUrl);\nconst argv1Path = process.argv[1];\n\nif (scriptPath === argv1Path) {\n main().catch((error) => {\n logger.error(\n `未处理的错误: ${error instanceof Error ? error.message : String(error)}`\n );\n process.exit(1);\n });\n}\n","import { copyFileSync, existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n// 在 ESM 中,需要从 import.meta.url 获取当前文件目录\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// 默认连接配置\nconst DEFAULT_CONNECTION_CONFIG: Required<ConnectionConfig> = {\n heartbeatInterval: 30000, // 30秒心跳间隔\n heartbeatTimeout: 10000, // 10秒心跳超时\n reconnectInterval: 5000, // 5秒重连间隔\n};\n\n// 配置文件接口定义\n// 本地 MCP 服务配置\nexport interface LocalMCPServerConfig {\n command: string;\n args: string[];\n env?: Record<string, string>;\n}\n\n// ModelScope SSE MCP 服务配置\nexport interface SSEMCPServerConfig {\n type: \"sse\";\n url: string;\n}\n\n// 统一的 MCP 服务配置\nexport type MCPServerConfig = LocalMCPServerConfig | SSEMCPServerConfig;\n\nexport interface MCPToolConfig {\n description?: string;\n enable: boolean;\n}\n\nexport interface MCPServerToolsConfig {\n tools: Record<string, MCPToolConfig>;\n}\n\nexport interface ConnectionConfig {\n heartbeatInterval?: number; // 心跳检测间隔(毫秒),默认30000\n heartbeatTimeout?: number; // 心跳超时时间(毫秒),默认10000\n reconnectInterval?: number; // 重连间隔(毫秒),默认5000\n}\n\nexport interface ModelScopeConfig {\n apiKey?: string; // ModelScope API 密钥\n}\n\nexport interface WebUIConfig {\n port?: number; // Web UI 端口号,默认 9999\n}\n\nexport interface AppConfig {\n mcpEndpoint: string | string[];\n mcpServers: Record<string, MCPServerConfig>;\n mcpServerConfig?: Record<string, MCPServerToolsConfig>;\n connection?: ConnectionConfig; // 连接配置(可选,用于向后兼容)\n modelscope?: ModelScopeConfig; // ModelScope 配置(可选)\n webUI?: WebUIConfig; // Web UI 配置(可选)\n}\n\n/**\n * 配置管理类\n * 负责管理应用配置,提供只读访问和安全的配置更新功能\n */\nexport class ConfigManager {\n private static instance: ConfigManager;\n private defaultConfigPath: string;\n private config: AppConfig | null = null;\n\n private constructor() {\n this.defaultConfigPath = resolve(__dirname, \"xiaozhi.config.default.json\");\n }\n\n /**\n * 获取配置文件路径(动态计算)\n */\n private getConfigFilePath(): string {\n // 配置文件路径 - 优先使用环境变量指定的目录,否则使用当前工作目录\n const configDir = process.env.XIAOZHI_CONFIG_DIR || process.cwd();\n return resolve(configDir, \"xiaozhi.config.json\");\n }\n\n /**\n * 获取配置管理器单例实例\n */\n public static getInstance(): ConfigManager {\n if (!ConfigManager.instance) {\n ConfigManager.instance = new ConfigManager();\n }\n return ConfigManager.instance;\n }\n\n /**\n * 检查配置文件是否存在\n */\n public configExists(): boolean {\n const configPath = this.getConfigFilePath();\n return existsSync(configPath);\n }\n\n /**\n * 初始化配置文件\n * 从 config.default.json 复制到 config.json\n */\n public initConfig(): void {\n if (!existsSync(this.defaultConfigPath)) {\n throw new Error(\"默认配置文件 xiaozhi.config.default.json 不存在\");\n }\n\n if (this.configExists()) {\n throw new Error(\"配置文件 xiaozhi.config.json 已存在,无需重复初始化\");\n }\n\n const configPath = this.getConfigFilePath();\n copyFileSync(this.defaultConfigPath, configPath);\n this.config = null; // 重置缓存\n }\n\n /**\n * 加载配置文件\n */\n private loadConfig(): AppConfig {\n if (!this.configExists()) {\n throw new Error(\n \"配置文件 xiaozhi.config.json 不存在,请先运行 xiaozhi init 初始化配置\"\n );\n }\n\n try {\n const configPath = this.getConfigFilePath();\n const configData = readFileSync(configPath, \"utf8\");\n const config = JSON.parse(configData) as AppConfig;\n\n // 验证配置结构\n this.validateConfig(config);\n\n return config;\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new Error(`配置文件格式错误: ${error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * 验证配置文件结构\n */\n private validateConfig(config: unknown): void {\n if (!config || typeof config !== \"object\") {\n throw new Error(\"配置文件格式错误:根对象无效\");\n }\n\n const configObj = config as Record<string, unknown>;\n\n if (configObj.mcpEndpoint === undefined || configObj.mcpEndpoint === null) {\n throw new Error(\"配置文件格式错误:mcpEndpoint 字段无效\");\n }\n\n // 验证 mcpEndpoint 类型(字符串或字符串数组)\n if (typeof configObj.mcpEndpoint === \"string\") {\n // 空字符串是允许的,getMcpEndpoints 会返回空数组\n } else if (Array.isArray(configObj.mcpEndpoint)) {\n if (configObj.mcpEndpoint.length === 0) {\n throw new Error(\"配置文件格式错误:mcpEndpoint 数组不能为空\");\n }\n for (const endpoint of configObj.mcpEndpoint) {\n if (typeof endpoint !== \"string\" || endpoint.trim() === \"\") {\n throw new Error(\n \"配置文件格式错误:mcpEndpoint 数组中的每个元素必须是非空字符串\"\n );\n }\n }\n } else {\n throw new Error(\"配置文件格式错误:mcpEndpoint 必须是字符串或字符串数组\");\n }\n\n if (!configObj.mcpServers || typeof configObj.mcpServers !== \"object\") {\n throw new Error(\"配置文件格式错误:mcpServers 字段无效\");\n }\n\n // 验证每个 MCP 服务配置\n for (const [serverName, serverConfig] of Object.entries(\n configObj.mcpServers as Record<string, unknown>\n )) {\n if (!serverConfig || typeof serverConfig !== \"object\") {\n throw new Error(`配置文件格式错误:mcpServers.${serverName} 无效`);\n }\n\n const sc = serverConfig as Record<string, unknown>;\n\n // 检查是否是 SSE 类型\n if (sc.type === \"sse\") {\n // SSE 类型的验证\n if (!sc.url || typeof sc.url !== \"string\") {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.url 无效`\n );\n }\n } else {\n // 本地类型的验证\n if (!sc.command || typeof sc.command !== \"string\") {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.command 无效`\n );\n }\n\n if (!Array.isArray(sc.args)) {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.args 必须是数组`\n );\n }\n\n if (sc.env && typeof sc.env !== \"object\") {\n throw new Error(\n `配置文件格式错误:mcpServers.${serverName}.env 必须是对象`\n );\n }\n }\n }\n }\n\n /**\n * 获取配置(只读)\n */\n public getConfig(): Readonly<AppConfig> {\n if (!this.config) {\n this.config = this.loadConfig();\n }\n\n // 返回深度只读副本\n return JSON.parse(JSON.stringify(this.config));\n }\n\n /**\n * 获取 MCP 端点(向后兼容)\n * @deprecated 使用 getMcpEndpoints() 获取所有端点\n */\n public getMcpEndpoint(): string {\n const config = this.getConfig();\n if (Array.isArray(config.mcpEndpoint)) {\n return config.mcpEndpoint[0] || \"\";\n }\n return config.mcpEndpoint;\n }\n\n /**\n * 获取所有 MCP 端点\n */\n public getMcpEndpoints(): string[] {\n const config = this.getConfig();\n if (Array.isArray(config.mcpEndpoint)) {\n return [...config.mcpEndpoint];\n }\n return config.mcpEndpoint ? [config.mcpEndpoint] : [];\n }\n\n /**\n * 获取 MCP 服务配置\n */\n public getMcpServers(): Readonly<Record<string, MCPServerConfig>> {\n const config = this.getConfig();\n return config.mcpServers;\n }\n\n /**\n * 获取 MCP 服务工具配置\n */\n public getMcpServerConfig(): Readonly<Record<string, MCPServerToolsConfig>> {\n const config = this.getConfig();\n return config.mcpServerConfig || {};\n }\n\n /**\n * 获取指定服务的工具配置\n */\n public getServerToolsConfig(\n serverName: string\n ): Readonly<Record<string, MCPToolConfig>> {\n const serverConfig = this.getMcpServerConfig();\n return serverConfig[serverName]?.tools || {};\n }\n\n /**\n * 检查工具是否启用\n */\n public isToolEnabled(serverName: string, toolName: string): boolean {\n const toolsConfig = this.getServerToolsConfig(serverName);\n const toolConfig = toolsConfig[toolName];\n return toolConfig?.enable !== false; // 默认启用\n }\n\n /**\n * 更新 MCP 端点(支持字符串或数组)\n */\n public updateMcpEndpoint(endpoint: string | string[]): void {\n if (Array.isArray(endpoint)) {\n if (endpoint.length === 0) {\n throw new Error(\"MCP 端点数组不能为空\");\n }\n for (const ep of endpoint) {\n if (!ep || typeof ep !== \"string\") {\n throw new Error(\"MCP 端点数组中的每个元素必须是非空字符串\");\n }\n }\n } else {\n if (!endpoint || typeof endpoint !== \"string\") {\n throw new Error(\"MCP 端点必须是非空字符串\");\n }\n }\n\n const config = this.getConfig();\n const newConfig = { ...config, mcpEndpoint: endpoint };\n this.saveConfig(newConfig);\n }\n\n /**\n * 添加 MCP 端点\n */\n public addMcpEndpoint(endpoint: string): void {\n if (!endpoint || typeof endpoint !== \"string\") {\n throw new Error(\"MCP 端点必须是非空字符串\");\n }\n\n const config = this.getConfig();\n const currentEndpoints = this.getMcpEndpoints();\n\n // 检查是否已存在\n if (currentEndpoints.includes(endpoint)) {\n throw new Error(`MCP 端点 ${endpoint} 已存在`);\n }\n\n const newEndpoints = [...currentEndpoints, endpoint];\n const newConfig = { ...config, mcpEndpoint: newEndpoints };\n this.saveConfig(newConfig);\n }\n\n /**\n * 移除 MCP 端点\n */\n public removeMcpEndpoint(endpoint: string): void {\n if (!endpoint || typeof endpoint !== \"string\") {\n throw new Error(\"MCP 端点必须是非空字符串\");\n }\n\n const config = this.getConfig();\n const currentEndpoints = this.getMcpEndpoints();\n\n // 检查是否存在\n const index = currentEndpoints.indexOf(endpoint);\n if (index === -1) {\n throw new Error(`MCP 端点 ${endpoint} 不存在`);\n }\n\n // 不允许删除最后一个端点\n if (currentEndpoints.length === 1) {\n throw new Error(\"不能删除最后一个 MCP 端点\");\n }\n\n const newEndpoints = currentEndpoints.filter((ep) => ep !== endpoint);\n const newConfig = { ...config, mcpEndpoint: newEndpoints };\n this.saveConfig(newConfig);\n }\n\n /**\n * 更新 MCP 服务配置\n */\n public updateMcpServer(\n serverName: string,\n serverConfig: MCPServerConfig\n ): void {\n if (!serverName || typeof serverName !== \"string\") {\n throw new Error(\"服务名称必须是非空字符串\");\n }\n\n // 验证服务配置\n if (\"type\" in serverConfig && serverConfig.type === \"sse\") {\n // SSE 类型的验证\n if (!serverConfig.url || typeof serverConfig.url !== \"string\") {\n throw new Error(\"SSE 服务配置的 url 字段必须是非空字符串\");\n }\n } else {\n // 本地类型的验证\n const localConfig = serverConfig as LocalMCPServerConfig;\n if (!localConfig.command || typeof localConfig.command !== \"string\") {\n throw new Error(\"服务配置的 command 字段必须是非空字符串\");\n }\n\n if (!Array.isArray(localConfig.args)) {\n throw new Error(\"服务配置的 args 字段必须是数组\");\n }\n\n if (localConfig.env && typeof localConfig.env !== \"object\") {\n throw new Error(\"服务配置的 env 字段必须是对象\");\n }\n }\n\n const config = this.getConfig();\n const newConfig = {\n ...config,\n mcpServers: {\n ...config.mcpServers,\n [serverName]: serverConfig,\n },\n };\n this.saveConfig(newConfig);\n }\n\n /**\n * 删除 MCP 服务配置\n */\n public removeMcpServer(serverName: string): void {\n if (!serverName || typeof serverName !== \"string\") {\n throw new Error(\"服务名称必须是非空字符串\");\n }\n\n const config = this.getConfig();\n if (!config.mcpServers[serverName]) {\n throw new Error(`服务 ${serverName} 不存在`);\n }\n\n const newMcpServers = { ...config.mcpServers };\n delete newMcpServers[serverName];\n\n const newConfig = {\n ...config,\n mcpServers: newMcpServers,\n };\n this.saveConfig(newConfig);\n }\n\n /**\n * 更新服务工具配置\n */\n public updateServerToolsConfig(\n serverName: string,\n toolsConfig: Record<string, MCPToolConfig>\n ): void {\n const config = this.getConfig();\n const newConfig = { ...config };\n\n // 确保 mcpServerConfig 存在\n if (!newConfig.mcpServerConfig) {\n newConfig.mcpServerConfig = {};\n }\n\n // 更新指定服务的工具配置\n newConfig.mcpServerConfig[serverName] = {\n tools: toolsConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置工具启用状态\n */\n public setToolEnabled(\n serverName: string,\n toolName: string,\n enabled: boolean,\n description?: string\n ): void {\n const config = this.getConfig();\n const newConfig = { ...config };\n\n // 确保 mcpServerConfig 存在\n if (!newConfig.mcpServerConfig) {\n newConfig.mcpServerConfig = {};\n }\n\n // 确保服务配置存在\n if (!newConfig.mcpServerConfig[serverName]) {\n newConfig.mcpServerConfig[serverName] = { tools: {} };\n }\n\n // 更新工具配置\n newConfig.mcpServerConfig[serverName].tools[toolName] = {\n enable: enabled,\n ...(description && { description }),\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 保存配置到文件\n */\n private saveConfig(config: AppConfig): void {\n try {\n // 验证配置\n this.validateConfig(config);\n\n // 格式化 JSON 并保存\n const configPath = this.getConfigFilePath();\n const configJson = JSON.stringify(config, null, 2);\n writeFileSync(configPath, configJson, \"utf8\");\n\n // 更新缓存\n this.config = config;\n } catch (error) {\n throw new Error(\n `保存配置失败: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * 重新加载配置(清除缓存)\n */\n public reloadConfig(): void {\n this.config = null;\n }\n\n /**\n * 获取配置文件路径\n */\n public getConfigPath(): string {\n return this.getConfigFilePath();\n }\n\n /**\n * 获取默认配置文件路径\n */\n public getDefaultConfigPath(): string {\n return this.defaultConfigPath;\n }\n\n /**\n * 获取连接配置(包含默认值)\n */\n public getConnectionConfig(): Required<ConnectionConfig> {\n const config = this.getConfig();\n const connectionConfig = config.connection || {};\n\n return {\n heartbeatInterval:\n connectionConfig.heartbeatInterval ??\n DEFAULT_CONNECTION_CONFIG.heartbeatInterval,\n heartbeatTimeout:\n connectionConfig.heartbeatTimeout ??\n DEFAULT_CONNECTION_CONFIG.heartbeatTimeout,\n reconnectInterval:\n connectionConfig.reconnectInterval ??\n DEFAULT_CONNECTION_CONFIG.reconnectInterval,\n };\n }\n\n /**\n * 获取心跳检测间隔(毫秒)\n */\n public getHeartbeatInterval(): number {\n return this.getConnectionConfig().heartbeatInterval;\n }\n\n /**\n * 获取心跳超时时间(毫秒)\n */\n public getHeartbeatTimeout(): number {\n return this.getConnectionConfig().heartbeatTimeout;\n }\n\n /**\n * 获取重连间隔(毫秒)\n */\n public getReconnectInterval(): number {\n return this.getConnectionConfig().reconnectInterval;\n }\n\n /**\n * 更新连接配置\n */\n public updateConnectionConfig(\n connectionConfig: Partial<ConnectionConfig>\n ): void {\n const config = this.getConfig();\n const currentConnectionConfig = config.connection || {};\n\n const newConnectionConfig = {\n ...currentConnectionConfig,\n ...connectionConfig,\n };\n\n const newConfig = {\n ...config,\n connection: newConnectionConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置心跳检测间隔\n */\n public setHeartbeatInterval(interval: number): void {\n if (interval <= 0) {\n throw new Error(\"心跳检测间隔必须大于0\");\n }\n this.updateConnectionConfig({ heartbeatInterval: interval });\n }\n\n /**\n * 设置心跳超时时间\n */\n public setHeartbeatTimeout(timeout: number): void {\n if (timeout <= 0) {\n throw new Error(\"心跳超时时间必须大于0\");\n }\n this.updateConnectionConfig({ heartbeatTimeout: timeout });\n }\n\n /**\n * 设置重连间隔\n */\n public setReconnectInterval(interval: number): void {\n if (interval <= 0) {\n throw new Error(\"重连间隔必须大于0\");\n }\n this.updateConnectionConfig({ reconnectInterval: interval });\n }\n\n /**\n * 获取 ModelScope 配置\n */\n public getModelScopeConfig(): Readonly<ModelScopeConfig> {\n const config = this.getConfig();\n return config.modelscope || {};\n }\n\n /**\n * 获取 ModelScope API Key\n * 优先从配置文件读取,其次从环境变量读取\n */\n public getModelScopeApiKey(): string | undefined {\n const modelScopeConfig = this.getModelScopeConfig();\n return modelScopeConfig.apiKey || process.env.MODELSCOPE_API_TOKEN;\n }\n\n /**\n * 更新 ModelScope 配置\n */\n public updateModelScopeConfig(\n modelScopeConfig: Partial<ModelScopeConfig>\n ): void {\n const config = this.getConfig();\n const currentModelScopeConfig = config.modelscope || {};\n\n const newModelScopeConfig = {\n ...currentModelScopeConfig,\n ...modelScopeConfig,\n };\n\n const newConfig = {\n ...config,\n modelscope: newModelScopeConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置 ModelScope API Key\n */\n public setModelScopeApiKey(apiKey: string): void {\n if (!apiKey || typeof apiKey !== \"string\") {\n throw new Error(\"API Key 必须是非空字符串\");\n }\n this.updateModelScopeConfig({ apiKey });\n }\n\n /**\n * 获取 Web UI 配置\n */\n public getWebUIConfig(): Readonly<WebUIConfig> {\n const config = this.getConfig();\n return config.webUI || {};\n }\n\n /**\n * 获取 Web UI 端口号\n */\n public getWebUIPort(): number {\n const webUIConfig = this.getWebUIConfig();\n return webUIConfig.port ?? 9999; // 默认端口 9999\n }\n\n /**\n * 更新 Web UI 配置\n */\n public updateWebUIConfig(webUIConfig: Partial<WebUIConfig>): void {\n const config = this.getConfig();\n const currentWebUIConfig = config.webUI || {};\n\n const newWebUIConfig = {\n ...currentWebUIConfig,\n ...webUIConfig,\n };\n\n const newConfig = {\n ...config,\n webUI: newWebUIConfig,\n };\n\n this.saveConfig(newConfig);\n }\n\n /**\n * 设置 Web UI 端口号\n */\n public setWebUIPort(port: number): void {\n if (!Number.isInteger(port) || port <= 0 || port > 65535) {\n throw new Error(\"端口号必须是 1-65535 之间的整数\");\n }\n this.updateWebUIConfig({ port });\n }\n}\n\n// 导出单例实例\nexport const configManager = ConfigManager.getInstance();\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport chalk from \"chalk\";\nimport { type consola, createConsola } from \"consola\";\n\nfunction formatDateTime(date: Date) {\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n const day = String(date.getDate()).padStart(2, \"0\");\n const hours = String(date.getHours()).padStart(2, \"0\");\n const minutes = String(date.getMinutes()).padStart(2, \"0\");\n const seconds = String(date.getSeconds()).padStart(2, \"0\");\n\n return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;\n}\n\nexport class Logger {\n private logFilePath: string | null = null;\n private writeStream: fs.WriteStream | null = null;\n private consolaInstance: typeof consola;\n private isDaemonMode: boolean;\n\n constructor() {\n // 检查是否为守护进程模式\n this.isDaemonMode = process.env.XIAOZHI_DAEMON === \"true\";\n // 创建自定义的 consola 实例,禁用图标并自定义格式\n this.consolaInstance = createConsola({\n formatOptions: {\n date: false,\n colors: true,\n compact: true,\n },\n fancy: false,\n });\n\n // 保存对当前实例的引用,以便在闭包中访问\n const isDaemonMode = this.isDaemonMode;\n\n // 自定义格式化器\n this.consolaInstance.setReporters([\n {\n log: (logObj) => {\n const levelMap: Record<string, string> = {\n info: \"INFO\",\n success: \"SUCCESS\",\n warn: \"WARN\",\n error: \"ERROR\",\n debug: \"DEBUG\",\n log: \"LOG\",\n };\n\n const colorMap: Record<string, (text: string) => string> = {\n info: chalk.blue,\n success: chalk.green,\n warn: chalk.yellow,\n error: chalk.red,\n debug: chalk.gray,\n log: (text: string) => text,\n };\n\n const level = levelMap[logObj.type] || logObj.type.toUpperCase();\n const colorFn = colorMap[logObj.type] || ((text: string) => text);\n const timestamp = formatDateTime(new Date());\n\n // 为级别添加颜色\n const coloredLevel = colorFn(`[${level}]`);\n const message = `[${timestamp}] ${coloredLevel} ${logObj.args.join(\n \" \"\n )}`;\n\n // 守护进程模式下不输出到控制台,只写入文件\n if (!isDaemonMode) {\n // 输出到 stderr(与原来保持一致)\n try {\n console.error(message);\n } catch (error) {\n // 忽略 EPIPE 错误\n if (error instanceof Error && error.message?.includes(\"EPIPE\")) {\n return;\n }\n throw error;\n }\n }\n },\n },\n ]);\n }\n\n /**\n * 初始化日志文件\n * @param projectDir 项目目录\n */\n initLogFile(projectDir: string): void {\n this.logFilePath = path.join(projectDir, \"xiaozhi.log\");\n\n // 确保日志文件存在\n if (!fs.existsSync(this.logFilePath)) {\n fs.writeFileSync(this.logFilePath, \"\");\n }\n\n // 创建写入流,追加模式\n this.writeStream = fs.createWriteStream(this.logFilePath, {\n flags: \"a\",\n encoding: \"utf8\",\n });\n }\n\n /**\n * 记录日志到文件\n * @param level 日志级别\n * @param message 日志消息\n * @param args 额外参数\n */\n private logToFile(level: string, message: string, ...args: any[]): void {\n if (this.writeStream) {\n const timestamp = new Date().toISOString();\n const formattedMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;\n const fullMessage =\n args.length > 0\n ? `${formattedMessage} ${args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n )\n .join(\" \")}`\n : formattedMessage;\n\n this.writeStream.write(`${fullMessage}\\n`);\n }\n }\n\n /**\n * 设置是否启用文件日志\n * @param enable 是否启用\n */\n enableFileLogging(enable: boolean): void {\n if (enable && !this.writeStream && this.logFilePath) {\n this.writeStream = fs.createWriteStream(this.logFilePath, {\n flags: \"a\",\n encoding: \"utf8\",\n });\n } else if (!enable && this.writeStream) {\n this.writeStream.end();\n this.writeStream = null;\n }\n }\n\n /**\n * 日志方法\n */\n info(message: string, ...args: any[]): void {\n this.consolaInstance.info(message, ...args);\n this.logToFile(\"info\", message, ...args);\n }\n\n success(message: string, ...args: any[]): void {\n this.consolaInstance.success(message, ...args);\n this.logToFile(\"success\", message, ...args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.consolaInstance.warn(message, ...args);\n this.logToFile(\"warn\", message, ...args);\n }\n\n error(message: string, ...args: any[]): void {\n this.consolaInstance.error(message, ...args);\n this.logToFile(\"error\", message, ...args);\n }\n\n debug(message: string, ...args: any[]): void {\n this.consolaInstance.debug(message, ...args);\n this.logToFile(\"debug\", message, ...args);\n }\n\n log(message: string, ...args: any[]): void {\n this.consolaInstance.log(message, ...args);\n this.logToFile(\"log\", message, ...args);\n }\n\n /**\n * 创建一个带标签的日志实例(已废弃,直接返回原实例)\n * @param tag 标签(不再使用)\n * @deprecated 标签功能已移除\n */\n withTag(tag: string): Logger {\n // 不再添加标签,直接返回共享实例\n return this;\n }\n\n /**\n * 关闭日志文件流\n */\n close(): void {\n if (this.writeStream) {\n this.writeStream.end();\n this.writeStream = null;\n }\n }\n}\n\n// 导出单例实例\nexport const logger = new Logger();\n","#!/usr/bin/env node\n\n/**\n * Multi-Endpoint MCP Pipe - 支持多个 MCP 接入点\n * 管理多个 WebSocket 连接,并正确路由消息到对应的接入点\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport process from \"node:process\";\nimport WebSocket from \"ws\";\nimport { configManager } from \"./configManager.js\";\nimport { logger as globalLogger } from \"./logger.js\";\n\n// 为 MultiEndpointMCPPipe 创建带标签的 logger\nconst logger = globalLogger.withTag(\"MULTI_MCP_PIPE\");\n\n// 如果在守护进程模式下运行,初始化日志文件\nif (process.env.XIAOZHI_DAEMON === \"true\" && process.env.XIAOZHI_CONFIG_DIR) {\n globalLogger.initLogFile(process.env.XIAOZHI_CONFIG_DIR);\n globalLogger.enableFileLogging(true);\n}\n\ninterface EndpointConnection {\n url: string;\n websocket: WebSocket | null;\n isConnected: boolean;\n reconnectAttempt: number;\n reconnectTimer?: NodeJS.Timeout;\n heartbeatTimer?: NodeJS.Timeout;\n heartbeatTimeoutTimer?: NodeJS.Timeout;\n process: ChildProcess | null; // 每个端点独立的 MCP 进程\n stdoutBuffer: string; // 每个端点独立的输出缓冲区\n}\n\nexport class MultiEndpointMCPPipe {\n private mcpScript: string;\n private endpoints: Map<string, EndpointConnection>;\n private shouldReconnect: boolean;\n private shutdownResolve?: () => void;\n private connectionConfig: {\n heartbeatInterval: number;\n heartbeatTimeout: number;\n reconnectInterval: number;\n };\n\n constructor(mcpScript: string, endpointUrls: string[]) {\n this.mcpScript = mcpScript;\n this.endpoints = new Map();\n this.shouldReconnect = true;\n\n // 记录端点数量,明确表示支持单端点和多端点\n logger.info(\n endpointUrls.length === 1\n ? `初始化单端点连接: ${endpointUrls[0]}`\n : `初始化多端点连接(${endpointUrls.length} 个端点)`\n );\n\n // 初始化所有端点\n for (const url of endpointUrls) {\n this.endpoints.set(url, {\n url,\n websocket: null,\n isConnected: false,\n reconnectAttempt: 0,\n process: null,\n stdoutBuffer: \"\",\n });\n }\n\n // 获取连接配置\n try {\n this.connectionConfig = configManager.getConnectionConfig();\n logger.info(\n `连接配置: 心跳间隔=${this.connectionConfig.heartbeatInterval}ms, ` +\n `心跳超时=${this.connectionConfig.heartbeatTimeout}ms, ` +\n `重连间隔=${this.connectionConfig.reconnectInterval}ms`\n );\n } catch (error) {\n this.connectionConfig = {\n heartbeatInterval: 30000,\n heartbeatTimeout: 10000,\n reconnectInterval: 5000,\n };\n logger.warn(\n `无法获取连接配置,使用默认值: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n async start() {\n // 连接到所有端点(每个端点会启动自己的 MCP 进程)\n await this.connectToAllEndpoints();\n\n // 报告状态到 Web UI\n this.reportStatusToWebUI();\n\n // 保持进程运行\n return new Promise<void>((resolve) => {\n this.shutdownResolve = resolve;\n });\n }\n\n async connectToAllEndpoints() {\n const connectionPromises: Promise<void>[] = [];\n\n for (const [url, endpoint] of this.endpoints) {\n connectionPromises.push(this.connectToEndpoint(url));\n }\n\n await Promise.allSettled(connectionPromises);\n }\n\n async connectToEndpoint(endpointUrl: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (!endpoint || endpoint.isConnected) {\n return;\n }\n\n // 先为该端点启动 MCP 进程\n this.startMCPProcessForEndpoint(endpointUrl);\n\n logger.info(`正在连接到 WebSocket 服务器: ${endpointUrl}`);\n\n const ws = new WebSocket(endpointUrl);\n endpoint.websocket = ws;\n\n ws.on(\"open\", () => {\n logger.info(`成功连接到 WebSocket 服务器: ${endpointUrl}`);\n endpoint.isConnected = true;\n endpoint.reconnectAttempt = 0;\n\n // 报告状态\n this.reportStatusToWebUI();\n\n // 启动心跳检测\n this.startHeartbeat(endpointUrl);\n });\n\n ws.on(\"message\", (data: WebSocket.Data) => {\n const message = data.toString();\n logger.info(`<< [${endpointUrl}] WebSocket收到消息: ${message}`);\n\n // 将消息写入对应端点的进程标准输入\n if (endpoint.process?.stdin && !endpoint.process.stdin.destroyed) {\n endpoint.process.stdin.write(`${message}\\n`);\n }\n });\n\n ws.on(\"close\", (code: number, reason: Buffer) => {\n logger.error(`[${endpointUrl}] WebSocket 连接已关闭: ${code} ${reason}`);\n endpoint.isConnected = false;\n endpoint.websocket = null;\n\n // 停止心跳检测\n this.stopHeartbeat(endpointUrl);\n\n // 报告断开状态\n this.reportStatusToWebUI();\n\n // 如果应该重连且不是永久错误\n if (this.shouldReconnect && code !== 4004) {\n this.scheduleReconnect(endpointUrl);\n }\n });\n\n ws.on(\"error\", (error: Error) => {\n logger.error(`[${endpointUrl}] WebSocket 错误: ${error.message}`);\n endpoint.isConnected = false;\n\n // 停止心跳检测\n this.stopHeartbeat(endpointUrl);\n });\n\n // 处理 pong 响应\n ws.on(\"pong\", () => {\n // 收到 pong 响应,清除心跳超时定时器\n if (endpoint.heartbeatTimeoutTimer) {\n clearTimeout(endpoint.heartbeatTimeoutTimer);\n endpoint.heartbeatTimeoutTimer = undefined;\n }\n });\n }\n\n scheduleReconnect(endpointUrl: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (!endpoint || !this.shouldReconnect) return;\n\n // 清除之前的重连定时器\n if (endpoint.reconnectTimer) {\n clearTimeout(endpoint.reconnectTimer);\n }\n\n endpoint.reconnectAttempt++;\n\n logger.info(\n `[${endpointUrl}] 计划在 ${(\n this.connectionConfig.reconnectInterval / 1000\n ).toFixed(2)} 秒后进行第 ${endpoint.reconnectAttempt} 次重连尝试...`\n );\n\n endpoint.reconnectTimer = setTimeout(() => {\n if (this.shouldReconnect) {\n // 如果MCP进程不存在,先尝试重启\n if (!endpoint.process || endpoint.process.killed) {\n logger.info(`[${endpointUrl}] MCP 进程未运行,将在重连时启动...`);\n }\n this.connectToEndpoint(endpointUrl);\n }\n }, this.connectionConfig.reconnectInterval);\n }\n\n startMCPProcessForEndpoint(endpointUrl: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (!endpoint) {\n logger.error(`端点不存在: ${endpointUrl}`);\n return;\n }\n\n if (endpoint.process) {\n logger.info(`[${endpointUrl}] MCP 进程已在运行`);\n return;\n }\n\n logger.info(`[${endpointUrl}] 正在启动 MCP 进程`);\n\n endpoint.process = spawn(\"node\", [this.mcpScript], {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n\n // 处理进程标准输出 - 发送到对应的 WebSocket\n endpoint.process.stdout?.on(\"data\", (data: Buffer) => {\n // 将数据添加到缓冲区\n endpoint.stdoutBuffer += data.toString();\n\n // 按换行符分割消息\n const lines = endpoint.stdoutBuffer.split(\"\\n\");\n endpoint.stdoutBuffer = lines.pop() || \"\"; // 保留最后一个不完整的行\n\n // 处理每个完整的消息\n for (const line of lines) {\n if (line.trim()) {\n this.handleMCPMessage(endpointUrl, line);\n }\n }\n });\n\n // 处理进程标准错误\n endpoint.process.stderr?.on(\"data\", (data: Buffer) => {\n if (process.env.XIAOZHI_DAEMON !== \"true\") {\n try {\n process.stderr.write(data);\n } catch (error) {\n // 忽略 EPIPE 错误\n }\n }\n });\n\n // 处理进程退出\n endpoint.process.on(\n \"exit\",\n (code: number | null, signal: NodeJS.Signals | null) => {\n logger.warn(\n `[${endpointUrl}] MCP 进程已退出,退出码: ${code}, 信号: ${signal}`\n );\n endpoint.process = null;\n\n if (\n this.shouldReconnect &&\n signal !== \"SIGTERM\" &&\n signal !== \"SIGKILL\"\n ) {\n logger.info(\n `[${endpointUrl}] MCP 进程意外退出,将在下次重连时尝试重启`\n );\n }\n }\n );\n\n // 处理进程错误\n endpoint.process.on(\"error\", (error: Error) => {\n logger.error(`[${endpointUrl}] 进程错误: ${error.message}`);\n endpoint.process = null;\n\n if (this.shouldReconnect) {\n logger.info(\n `[${endpointUrl}] MCP 进程发生错误,将在下次重连时尝试重启`\n );\n }\n });\n }\n\n handleMCPMessage(endpointUrl: string, line: string) {\n logger.info(\n `>> [${endpointUrl}] mcpServerProxy发送消息长度: ${line.length} 字节`\n );\n logger.info(\n `>> [${endpointUrl}] mcpServerProxy发送消息: ${line.substring(0, 500)}...`\n );\n\n // 直接发送回对应的端点\n this.sendToEndpoint(endpointUrl, line);\n }\n\n sendToEndpoint(endpointUrl: string, message: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (\n !endpoint ||\n !endpoint.websocket ||\n endpoint.websocket.readyState !== WebSocket.OPEN\n ) {\n logger.warn(`[${endpointUrl}] 端点不可用,消息无法发送`);\n return;\n }\n\n try {\n endpoint.websocket.send(`${message}\\n`);\n logger.info(`>> [${endpointUrl}] 成功发送消息到 WebSocket`);\n } catch (error) {\n logger.error(`>> [${endpointUrl}] 发送消息到 WebSocket 失败: ${error}`);\n }\n }\n\n startHeartbeat(endpointUrl: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (!endpoint) return;\n\n // 清除之前的心跳定时器\n this.stopHeartbeat(endpointUrl);\n\n // 设置心跳定时器\n endpoint.heartbeatTimer = setInterval(() => {\n if (\n endpoint.websocket &&\n endpoint.websocket.readyState === WebSocket.OPEN\n ) {\n // 发送 ping\n endpoint.websocket.ping();\n\n // 设置心跳超时定时器\n endpoint.heartbeatTimeoutTimer = setTimeout(() => {\n logger.warn(`[${endpointUrl}] 心跳超时,断开连接`);\n endpoint.websocket?.close();\n }, this.connectionConfig.heartbeatTimeout);\n }\n }, this.connectionConfig.heartbeatInterval);\n }\n\n stopHeartbeat(endpointUrl: string) {\n const endpoint = this.endpoints.get(endpointUrl);\n if (!endpoint) return;\n\n if (endpoint.heartbeatTimer) {\n clearInterval(endpoint.heartbeatTimer);\n endpoint.heartbeatTimer = undefined;\n }\n\n if (endpoint.heartbeatTimeoutTimer) {\n clearTimeout(endpoint.heartbeatTimeoutTimer);\n endpoint.heartbeatTimeoutTimer = undefined;\n }\n }\n\n cleanup() {\n // 停止所有心跳检测\n for (const url of this.endpoints.keys()) {\n this.stopHeartbeat(url);\n }\n\n // 清除所有重连定时器,清理进程和缓冲区\n for (const [url, endpoint] of this.endpoints) {\n if (endpoint.reconnectTimer) {\n clearTimeout(endpoint.reconnectTimer);\n endpoint.reconnectTimer = undefined;\n }\n\n // 清空每个端点的缓冲区\n endpoint.stdoutBuffer = \"\";\n\n // 终止每个端点的进程\n if (endpoint.process) {\n logger.info(`[${url}] 正在终止 MCP 进程`);\n try {\n endpoint.process.kill(\"SIGTERM\");\n\n // 强制终止\n setTimeout(() => {\n if (endpoint.process && !endpoint.process.killed) {\n endpoint.process.kill(\"SIGKILL\");\n }\n }, 5000);\n } catch (error) {\n logger.error(\n `[${url}] 终止进程时出错: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n endpoint.process = null;\n }\n\n // 关闭 WebSocket 连接\n if (endpoint.websocket) {\n try {\n endpoint.websocket.close();\n } catch (error) {\n logger.warn(`[${url}] 关闭 WebSocket 时出错: ${error}`);\n }\n endpoint.websocket = null;\n }\n }\n }\n\n shutdown() {\n logger.info(\"正在关闭 Multi-Endpoint MCP Pipe...\");\n this.shouldReconnect = false;\n\n // 报告断开状态\n for (const endpoint of this.endpoints.values()) {\n endpoint.isConnected = false;\n }\n this.reportStatusToWebUI();\n\n this.cleanup();\n\n if (this.shutdownResolve) {\n this.shutdownResolve();\n }\n\n // 给状态报告一点时间\n setTimeout(() => {\n process.exit(0);\n }, 100);\n }\n\n // 报告状态到 Web UI 服务器\n private async reportStatusToWebUI() {\n // 在测试环境中跳过\n if (process.env.NODE_ENV === \"test\" || process.env.VITEST === \"true\") {\n return;\n }\n\n try {\n // 从配置获取 WebUI 端口\n const port = configManager.getWebUIPort();\n const statusWs = new WebSocket(`ws://localhost:${port}`);\n\n statusWs.on(\"open\", () => {\n // 收集所有端点的状态\n const endpointStatuses: { url: string; connected: boolean }[] = [];\n for (const [url, endpoint] of this.endpoints) {\n endpointStatuses.push({\n url,\n connected: endpoint.isConnected,\n });\n }\n\n const status = {\n type: \"clientStatus\",\n data: {\n status: this.hasAnyConnection() ? \"connected\" : \"disconnected\",\n mcpEndpoints: endpointStatuses,\n activeMCPServers: [], // 由 mcpServerProxy 填充\n lastHeartbeat: Date.now(),\n },\n };\n statusWs.send(JSON.stringify(status));\n logger.debug(\"已向 Web UI 报告状态\");\n\n // 发送状态后关闭连接\n setTimeout(() => {\n statusWs.close();\n }, 1000);\n });\n\n statusWs.on(\"error\", (error) => {\n logger.debug(`Web UI 连接失败(可能未运行): ${error.message}`);\n });\n } catch (error) {\n logger.debug(\n `向 Web UI 报告状态失败: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n\n hasAnyConnection(): boolean {\n for (const endpoint of this.endpoints.values()) {\n if (endpoint.isConnected) {\n return true;\n }\n }\n return false;\n }\n}\n\n// 信号处理器\nexport function setupSignalHandlers(mcpPipe: MultiEndpointMCPPipe): void {\n const isDaemon = process.env.XIAOZHI_DAEMON === \"true\";\n\n process.on(\"SIGINT\", () => {\n logger.info(\"收到中断信号,正在关闭...\");\n mcpPipe.shutdown();\n });\n\n process.on(\"SIGTERM\", () => {\n logger.info(\"收到终止信号,正在关闭...\");\n mcpPipe.shutdown();\n });\n\n // 守护进程模式下的额外信号处理\n if (isDaemon) {\n process.on(\"SIGHUP\", () => {\n logger.info(\n \"收到 SIGHUP 信号(终端已关闭),继续在守护进程模式下运行...\"\n );\n });\n\n process.on(\"uncaughtException\", (error) => {\n if (error.message?.includes(\"EPIPE\")) {\n return;\n }\n logger.error(\n `未捕获的异常: ${error.message || error}\\n${error.stack || \"\"}`\n );\n });\n\n process.on(\"unhandledRejection\", (reason, promise) => {\n logger.error(\n `未处理的 Promise 拒绝: ${\n reason instanceof Error ? reason.message : String(reason)\n }`\n );\n });\n }\n}\n"],"mappings":";+EAOA,OAAOA,MAAa,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AAiBJ,EAAU,OAAQK,GACnC,CAACA,GAAYA,EAAS,SAAS,qBAAM,GACvCT,EAAO,KAAK,yCAAWS,CAAQ,EAAE,EAC1B,IAEF,EACR,EAEGD,EAAe,SAAW,IAC5BR,EAAO,MAAM,iDAAc,EAC3BA,EAAO,MACL,8FACF,EACAC,EAAQ,KAAK,CAAC,GAKhBD,EAAO,KACLQ,EAAe,SAAW,EACtB,6CACA,mDAAWA,EAAe,MAAM,2BACtC,EAEA,IAAME,EAAU,IAAIC,EAAqBR,EAAWK,CAAc,EAClEI,EAAoBF,CAAO,EAE3B,GAAI,CACF,MAAMA,EAAQ,MAAM,CACtB,OAASH,EAAO,CACdP,EAAO,MACL,yCAAWO,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EACnE,EACAN,EAAQ,KAAK,CAAC,CAChB,CACF,CA1GsBY,EAAAX,EAAA,QA6GtB,IAAMY,EAAiB,YAAY,IAC7BC,EAAaC,EAAcF,CAAc,EACzCG,EAAYhB,EAAQ,KAAK,CAAC,EAE5Bc,IAAeE,GACjBf,EAAK,EAAE,MAAOK,GAAU,CACtBP,EAAO,MACL,yCAAWO,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EACnE,EACAN,EAAQ,KAAK,CAAC,CAChB,CAAC","names":["process","fileURLToPath","config","copyFileSync","existsSync","readFileSync","writeFileSync","dirname","resolve","fileURLToPath","__dirname","dirname","fileURLToPath","DEFAULT_CONNECTION_CONFIG","ConfigManager","_ConfigManager","__name","resolve","configDir","configPath","existsSync","copyFileSync","configData","readFileSync","config","error","configObj","endpoint","serverName","serverConfig","sc","toolName","ep","newConfig","currentEndpoints","newEndpoints","localConfig","newMcpServers","toolsConfig","enabled","description","configJson","writeFileSync","connectionConfig","newConnectionConfig","interval","timeout","modelScopeConfig","newModelScopeConfig","apiKey","webUIConfig","newWebUIConfig","port","configManager","fs","path","chalk","createConsola","formatDateTime","date","year","month","day","hours","minutes","seconds","__name","Logger","createConsola","isDaemonMode","logObj","levelMap","colorMap","chalk","text","level","colorFn","timestamp","coloredLevel","message","error","projectDir","path","fs","args","formattedMessage","fullMessage","arg","enable","tag","logger","spawn","process","WebSocket","logger","process","MultiEndpointMCPPipe","__name","mcpScript","endpointUrls","url","configManager","error","resolve","connectionPromises","endpoint","endpointUrl","ws","WebSocket","data","message","code","reason","spawn","lines","line","signal","port","statusWs","endpointStatuses","status","setupSignalHandlers","mcpPipe","isDaemon","promise","config","logger","process","main","mcpScript","endpoints","configManager","envEndpoint","error","validEndpoints","endpoint","mcpPipe","MultiEndpointMCPPipe","setupSignalHandlers","__name","currentFileUrl","scriptPath","fileURLToPath","argv1Path"]}
|
package/dist/autoCompletion.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var S=Object.defineProperty;var l=(r,o)=>S(r,"name",{value:o,configurable:!0});import y from"omelette";import{copyFileSync as w,existsSync as b,readFileSync as I,writeFileSync as E}from"fs";import{dirname as M,resolve as d}from"path";import{fileURLToPath as P}from"url";var x=M(P(import.meta.url)),u={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},m=class r{static{l(this,"ConfigManager")}static instance;defaultConfigPath;config=null;constructor(){this.defaultConfigPath=d(x,"xiaozhi.config.default.json")}getConfigFilePath(){let o=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return d(o,"xiaozhi.config.json")}static getInstance(){return r.instance||(r.instance=new r),r.instance}configExists(){let o=this.getConfigFilePath();return b(o)}initConfig(){if(!b(this.defaultConfigPath))throw new Error("\u9ED8\u8BA4\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.default.json \u4E0D\u5B58\u5728");if(this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.json \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u521D\u59CB\u5316");let o=this.getConfigFilePath();w(this.defaultConfigPath,o),this.config=null}loadConfig(){if(!this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.json \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C xiaozhi init \u521D\u59CB\u5316\u914D\u7F6E");try{let o=this.getConfigFilePath(),e=I(o,"utf8"),i=JSON.parse(e);return this.validateConfig(i),i}catch(o){throw o instanceof SyntaxError?new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF: ${o.message}`):o}}validateConfig(o){if(!o||typeof o!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A\u6839\u5BF9\u8C61\u65E0\u6548");let e=o;if(!e.mcpEndpoint||typeof e.mcpEndpoint!="string")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5B57\u6BB5\u65E0\u6548");if(!e.mcpServers||typeof e.mcpServers!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers \u5B57\u6BB5\u65E0\u6548");for(let[i,n]of Object.entries(e.mcpServers)){if(!n||typeof n!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${i} \u65E0\u6548`);let t=n;if(t.type==="sse"){if(!t.url||typeof t.url!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${i}.url \u65E0\u6548`)}else{if(!t.command||typeof t.command!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${i}.command \u65E0\u6548`);if(!Array.isArray(t.args))throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${i}.args \u5FC5\u987B\u662F\u6570\u7EC4`);if(t.env&&typeof t.env!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${i}.env \u5FC5\u987B\u662F\u5BF9\u8C61`)}}}getConfig(){return this.config||(this.config=this.loadConfig()),JSON.parse(JSON.stringify(this.config))}getMcpEndpoint(){return this.getConfig().mcpEndpoint}getMcpServers(){return this.getConfig().mcpServers}getMcpServerConfig(){return this.getConfig().mcpServerConfig||{}}getServerToolsConfig(o){return this.getMcpServerConfig()[o]?.tools||{}}isToolEnabled(o,e){return this.getServerToolsConfig(o)[e]?.enable!==!1}updateMcpEndpoint(o){if(!o||typeof o!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let i={...this.getConfig(),mcpEndpoint:o};this.saveConfig(i)}updateMcpServer(o,e){if(!o||typeof o!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if("type"in e&&e.type==="sse"){if(!e.url||typeof e.url!="string")throw new Error("SSE \u670D\u52A1\u914D\u7F6E\u7684 url \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else{let t=e;if(!t.command||typeof t.command!="string")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 command \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!Array.isArray(t.args))throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4");if(t.env&&typeof t.env!="object")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61")}let i=this.getConfig(),n={...i,mcpServers:{...i.mcpServers,[o]:e}};this.saveConfig(n)}removeMcpServer(o){if(!o||typeof o!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let e=this.getConfig();if(!e.mcpServers[o])throw new Error(`\u670D\u52A1 ${o} \u4E0D\u5B58\u5728`);let i={...e.mcpServers};delete i[o];let n={...e,mcpServers:i};this.saveConfig(n)}updateServerToolsConfig(o,e){let n={...this.getConfig()};n.mcpServerConfig||(n.mcpServerConfig={}),n.mcpServerConfig[o]={tools:e},this.saveConfig(n)}setToolEnabled(o,e,i,n){let a={...this.getConfig()};a.mcpServerConfig||(a.mcpServerConfig={}),a.mcpServerConfig[o]||(a.mcpServerConfig[o]={tools:{}}),a.mcpServerConfig[o].tools[e]={enable:i,...n&&{description:n}},this.saveConfig(a)}saveConfig(o){try{this.validateConfig(o);let e=this.getConfigFilePath(),i=JSON.stringify(o,null,2);E(e,i,"utf8"),this.config=o}catch(e){throw new Error(`\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}reloadConfig(){this.config=null}getConfigPath(){return this.getConfigFilePath()}getDefaultConfigPath(){return this.defaultConfigPath}getConnectionConfig(){let e=this.getConfig().connection||{};return{heartbeatInterval:e.heartbeatInterval??u.heartbeatInterval,heartbeatTimeout:e.heartbeatTimeout??u.heartbeatTimeout,reconnectInterval:e.reconnectInterval??u.reconnectInterval}}getHeartbeatInterval(){return this.getConnectionConfig().heartbeatInterval}getHeartbeatTimeout(){return this.getConnectionConfig().heartbeatTimeout}getReconnectInterval(){return this.getConnectionConfig().reconnectInterval}updateConnectionConfig(o){let e=this.getConfig(),n={...e.connection||{},...o},t={...e,connection:n};this.saveConfig(t)}setHeartbeatInterval(o){if(o<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatInterval:o})}setHeartbeatTimeout(o){if(o<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatTimeout:o})}setReconnectInterval(o){if(o<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({reconnectInterval:o})}getModelScopeConfig(){return this.getConfig().modelscope||{}}getModelScopeApiKey(){return this.getModelScopeConfig().apiKey||process.env.MODELSCOPE_API_TOKEN}updateModelScopeConfig(o){let e=this.getConfig(),n={...e.modelscope||{},...o},t={...e,modelscope:n};this.saveConfig(t)}setModelScopeApiKey(o){if(!o||typeof o!="string")throw new Error("API Key \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");this.updateModelScopeConfig({apiKey:o})}getWebUIConfig(){return this.getConfig().webUI||{}}getWebUIPort(){return this.getWebUIConfig().port??9999}updateWebUIConfig(o){let e=this.getConfig(),n={...e.webUI||{},...o},t={...e,webUI:n};this.saveConfig(t)}setWebUIPort(o){if(!Number.isInteger(o)||o<=0||o>65535)throw new Error("\u7AEF\u53E3\u53F7\u5FC5\u987B\u662F 1-65535 \u4E4B\u95F4\u7684\u6574\u6570");this.updateWebUIConfig({port:o})}},C=m.getInstance();function T(){try{if(!C.configExists())return[];let r=C.getMcpServers();return Object.keys(r)}catch{return[]}}l(T,"getMcpServerNames");function z(r){try{if(!C.configExists())return[];let o=C.getServerToolsConfig(r);return Object.keys(o)}catch{return[]}}l(z,"getServerToolNames");function $(){let r=y("xiaozhi <command>");if(r.on("command",({reply:o})=>{o(["create","init","config","start","stop","status","attach","restart","mcp","completion"])}),r.on("complete",(o,{line:e,before:i,reply:n})=>{process.env.XIAOZHI_DEBUG_COMPLETION&&console.error(`Debug completion - line: "${e}", before: "${i}", fragment: "${o}"`);let t=e.trim().split(/\s+/),p=e!==e.trim()?t.length:t.length-1;if(t[1]==="mcp"){let h=t[2];if(p===2){let c=["list","server","tool"],s=t[2]||"",g=c.filter(f=>f.startsWith(s));n(g);return}if(p===3){switch(h){case"list":{let c=["--tools"],s=t[3]||"",g=c.filter(f=>f.startsWith(s));n(g);break}case"server":case"tool":{let c=T(),s=t[3]||"",g=c.filter(f=>f.startsWith(s));n(g);break}default:n([])}return}if(p===4&&h==="tool"){let c=t[3],s=z(c),g=t[4]||"",f=s.filter(v=>v.startsWith(g));n(f);return}if(p===5&&h==="tool"){let c=["enable","disable"],s=t[5]||"",g=c.filter(f=>f.startsWith(s));n(g);return}}if(p===2){switch(t[1]){case"create":n(["--template","-t"]);break;case"start":case"restart":n(["--daemon","-d"]);break;case"completion":n(["install","uninstall"]);break;default:n([])}return}n([])}),process.argv.includes("--completion")){try{console.log(r.setupShellInitFile())}catch(o){console.error("\u751F\u6210\u81EA\u52A8\u8865\u5168\u811A\u672C\u65F6\u51FA\u9519:",o)}process.exit(0)}process.argv.includes("--completion-fish")&&(console.log(r.setupShellInitFile("fish")),process.exit(0)),process.argv.includes("--compzsh")||process.argv.includes("--compbash"),r.init()}l($,"setupAutoCompletion");function N(){console.log("\u{1F680} xiaozhi \u81EA\u52A8\u8865\u5168\u8BBE\u7F6E"),console.log(),console.log("\u8981\u542F\u7528\u81EA\u52A8\u8865\u5168\uFF0C\u8BF7\u6839\u636E\u4F60\u7684shell\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\uFF1A"),console.log(),console.log("\u{1F4DD} Zsh (\u63A8\u8350):"),console.log(" xiaozhi --completion >> ~/.xiaozhi-completion.zsh"),console.log(" echo 'source ~/.xiaozhi-completion.zsh' >> ~/.zshrc"),console.log(" source ~/.zshrc"),console.log(),console.log("\u{1F4DD} Bash:"),console.log(" xiaozhi --completion >> ~/.xiaozhi-completion.bash"),console.log(" echo 'source ~/.xiaozhi-completion.bash' >> ~/.bash_profile"),console.log(" source ~/.bash_profile"),console.log(),console.log("\u{1F4DD} Fish:"),console.log(" xiaozhi --completion-fish >> ~/.config/fish/completions/xiaozhi.fish"),console.log(),console.log("\u2728 \u8BBE\u7F6E\u5B8C\u6210\u540E\uFF0C\u4F60\u5C31\u53EF\u4EE5\u4F7F\u7528 Tab \u952E\u8FDB\u884C\u81EA\u52A8\u8865\u5168\u4E86\uFF01"),console.log(),console.log("\u{1F4A1} \u793A\u4F8B:"),console.log(" xiaozhi m<Tab> # \u2192 mcp"),console.log(" xiaozhi mcp l<Tab> # \u2192 list"),console.log(" xiaozhi mcp tool <Tab> # \u2192 \u663E\u793A\u6240\u6709\u670D\u52A1\u5668\u540D\u79F0")}l(N,"showCompletionHelp");export{$ as setupAutoCompletion,N as showCompletionHelp};
|
|
1
|
+
var w=Object.defineProperty;var p=(r,o)=>w(r,"name",{value:o,configurable:!0});import x from"omelette";import{copyFileSync as S,existsSync as d,readFileSync as E,writeFileSync as M}from"fs";import{dirname as I,resolve as b}from"path";import{fileURLToPath as P}from"url";var y=I(P(import.meta.url)),u={heartbeatInterval:3e4,heartbeatTimeout:1e4,reconnectInterval:5e3},m=class r{static{p(this,"ConfigManager")}static instance;defaultConfigPath;config=null;constructor(){this.defaultConfigPath=b(y,"xiaozhi.config.default.json")}getConfigFilePath(){let o=process.env.XIAOZHI_CONFIG_DIR||process.cwd();return b(o,"xiaozhi.config.json")}static getInstance(){return r.instance||(r.instance=new r),r.instance}configExists(){let o=this.getConfigFilePath();return d(o)}initConfig(){if(!d(this.defaultConfigPath))throw new Error("\u9ED8\u8BA4\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.default.json \u4E0D\u5B58\u5728");if(this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.json \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u521D\u59CB\u5316");let o=this.getConfigFilePath();S(this.defaultConfigPath,o),this.config=null}loadConfig(){if(!this.configExists())throw new Error("\u914D\u7F6E\u6587\u4EF6 xiaozhi.config.json \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u8FD0\u884C xiaozhi init \u521D\u59CB\u5316\u914D\u7F6E");try{let o=this.getConfigFilePath(),n=E(o,"utf8"),t=JSON.parse(n);return this.validateConfig(t),t}catch(o){throw o instanceof SyntaxError?new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF: ${o.message}`):o}}validateConfig(o){if(!o||typeof o!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1A\u6839\u5BF9\u8C61\u65E0\u6548");let n=o;if(n.mcpEndpoint===void 0||n.mcpEndpoint===null)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u5B57\u6BB5\u65E0\u6548");if(typeof n.mcpEndpoint!="string")if(Array.isArray(n.mcpEndpoint)){if(n.mcpEndpoint.length===0)throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpEndpoint \u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let t of n.mcpEndpoint)if(typeof t!="string"||t.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(!n.mcpServers||typeof n.mcpServers!="object")throw new Error("\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers \u5B57\u6BB5\u65E0\u6548");for(let[t,e]of Object.entries(n.mcpServers)){if(!e||typeof e!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${t} \u65E0\u6548`);let i=e;if(i.type==="sse"){if(!i.url||typeof i.url!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${t}.url \u65E0\u6548`)}else{if(!i.command||typeof i.command!="string")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${t}.command \u65E0\u6548`);if(!Array.isArray(i.args))throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${t}.args \u5FC5\u987B\u662F\u6570\u7EC4`);if(i.env&&typeof i.env!="object")throw new Error(`\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF\uFF1AmcpServers.${t}.env \u5FC5\u987B\u662F\u5BF9\u8C61`)}}}getConfig(){return this.config||(this.config=this.loadConfig()),JSON.parse(JSON.stringify(this.config))}getMcpEndpoint(){let o=this.getConfig();return Array.isArray(o.mcpEndpoint)?o.mcpEndpoint[0]||"":o.mcpEndpoint}getMcpEndpoints(){let o=this.getConfig();return Array.isArray(o.mcpEndpoint)?[...o.mcpEndpoint]:o.mcpEndpoint?[o.mcpEndpoint]:[]}getMcpServers(){return this.getConfig().mcpServers}getMcpServerConfig(){return this.getConfig().mcpServerConfig||{}}getServerToolsConfig(o){return this.getMcpServerConfig()[o]?.tools||{}}isToolEnabled(o,n){return this.getServerToolsConfig(o)[n]?.enable!==!1}updateMcpEndpoint(o){if(Array.isArray(o)){if(o.length===0)throw new Error("MCP \u7AEF\u70B9\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A");for(let e of o)if(!e||typeof e!="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(!o||typeof o!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let t={...this.getConfig(),mcpEndpoint:o};this.saveConfig(t)}addMcpEndpoint(o){if(!o||typeof o!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let n=this.getConfig(),t=this.getMcpEndpoints();if(t.includes(o))throw new Error(`MCP \u7AEF\u70B9 ${o} \u5DF2\u5B58\u5728`);let e=[...t,o],i={...n,mcpEndpoint:e};this.saveConfig(i)}removeMcpEndpoint(o){if(!o||typeof o!="string")throw new Error("MCP \u7AEF\u70B9\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let n=this.getConfig(),t=this.getMcpEndpoints();if(t.indexOf(o)===-1)throw new Error(`MCP \u7AEF\u70B9 ${o} \u4E0D\u5B58\u5728`);if(t.length===1)throw new Error("\u4E0D\u80FD\u5220\u9664\u6700\u540E\u4E00\u4E2A MCP \u7AEF\u70B9");let i=t.filter(l=>l!==o),c={...n,mcpEndpoint:i};this.saveConfig(c)}updateMcpServer(o,n){if(!o||typeof o!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if("type"in n&&n.type==="sse"){if(!n.url||typeof n.url!="string")throw new Error("SSE \u670D\u52A1\u914D\u7F6E\u7684 url \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32")}else{let i=n;if(!i.command||typeof i.command!="string")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 command \u5B57\u6BB5\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!Array.isArray(i.args))throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 args \u5B57\u6BB5\u5FC5\u987B\u662F\u6570\u7EC4");if(i.env&&typeof i.env!="object")throw new Error("\u670D\u52A1\u914D\u7F6E\u7684 env \u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61")}let t=this.getConfig(),e={...t,mcpServers:{...t.mcpServers,[o]:n}};this.saveConfig(e)}removeMcpServer(o){if(!o||typeof o!="string")throw new Error("\u670D\u52A1\u540D\u79F0\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let n=this.getConfig();if(!n.mcpServers[o])throw new Error(`\u670D\u52A1 ${o} \u4E0D\u5B58\u5728`);let t={...n.mcpServers};delete t[o];let e={...n,mcpServers:t};this.saveConfig(e)}updateServerToolsConfig(o,n){let e={...this.getConfig()};e.mcpServerConfig||(e.mcpServerConfig={}),e.mcpServerConfig[o]={tools:n},this.saveConfig(e)}setToolEnabled(o,n,t,e){let c={...this.getConfig()};c.mcpServerConfig||(c.mcpServerConfig={}),c.mcpServerConfig[o]||(c.mcpServerConfig[o]={tools:{}}),c.mcpServerConfig[o].tools[n]={enable:t,...e&&{description:e}},this.saveConfig(c)}saveConfig(o){try{this.validateConfig(o);let n=this.getConfigFilePath(),t=JSON.stringify(o,null,2);M(n,t,"utf8"),this.config=o}catch(n){throw new Error(`\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25: ${n instanceof Error?n.message:String(n)}`)}}reloadConfig(){this.config=null}getConfigPath(){return this.getConfigFilePath()}getDefaultConfigPath(){return this.defaultConfigPath}getConnectionConfig(){let n=this.getConfig().connection||{};return{heartbeatInterval:n.heartbeatInterval??u.heartbeatInterval,heartbeatTimeout:n.heartbeatTimeout??u.heartbeatTimeout,reconnectInterval:n.reconnectInterval??u.reconnectInterval}}getHeartbeatInterval(){return this.getConnectionConfig().heartbeatInterval}getHeartbeatTimeout(){return this.getConnectionConfig().heartbeatTimeout}getReconnectInterval(){return this.getConnectionConfig().reconnectInterval}updateConnectionConfig(o){let n=this.getConfig(),e={...n.connection||{},...o},i={...n,connection:e};this.saveConfig(i)}setHeartbeatInterval(o){if(o<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatInterval:o})}setHeartbeatTimeout(o){if(o<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({heartbeatTimeout:o})}setReconnectInterval(o){if(o<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u5927\u4E8E0");this.updateConnectionConfig({reconnectInterval:o})}getModelScopeConfig(){return this.getConfig().modelscope||{}}getModelScopeApiKey(){return this.getModelScopeConfig().apiKey||process.env.MODELSCOPE_API_TOKEN}updateModelScopeConfig(o){let n=this.getConfig(),e={...n.modelscope||{},...o},i={...n,modelscope:e};this.saveConfig(i)}setModelScopeApiKey(o){if(!o||typeof o!="string")throw new Error("API Key \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");this.updateModelScopeConfig({apiKey:o})}getWebUIConfig(){return this.getConfig().webUI||{}}getWebUIPort(){return this.getWebUIConfig().port??9999}updateWebUIConfig(o){let n=this.getConfig(),e={...n.webUI||{},...o},i={...n,webUI:e};this.saveConfig(i)}setWebUIPort(o){if(!Number.isInteger(o)||o<=0||o>65535)throw new Error("\u7AEF\u53E3\u53F7\u5FC5\u987B\u662F 1-65535 \u4E4B\u95F4\u7684\u6574\u6570");this.updateWebUIConfig({port:o})}},h=m.getInstance();function T(){try{if(!h.configExists())return[];let r=h.getMcpServers();return Object.keys(r)}catch{return[]}}p(T,"getMcpServerNames");function A(r){try{if(!h.configExists())return[];let o=h.getServerToolsConfig(r);return Object.keys(o)}catch{return[]}}p(A,"getServerToolNames");function k(){let r=x("xiaozhi <command>");if(r.on("command",({reply:o})=>{o(["create","init","config","start","stop","status","attach","restart","mcp","completion"])}),r.on("complete",(o,{line:n,before:t,reply:e})=>{process.env.XIAOZHI_DEBUG_COMPLETION&&console.error(`Debug completion - line: "${n}", before: "${t}", fragment: "${o}"`);let i=n.trim().split(/\s+/),l=n!==n.trim()?i.length:i.length-1;if(i[1]==="mcp"){let C=i[2];if(l===2){let s=["list","server","tool"],g=i[2]||"",f=s.filter(a=>a.startsWith(g));e(f);return}if(l===3){switch(C){case"list":{let s=["--tools"],g=i[3]||"",f=s.filter(a=>a.startsWith(g));e(f);break}case"server":case"tool":{let s=T(),g=i[3]||"",f=s.filter(a=>a.startsWith(g));e(f);break}default:e([])}return}if(l===4&&C==="tool"){let s=i[3],g=A(s),f=i[4]||"",a=g.filter(v=>v.startsWith(f));e(a);return}if(l===5&&C==="tool"){let s=["enable","disable"],g=i[5]||"",f=s.filter(a=>a.startsWith(g));e(f);return}}if(l===2){switch(i[1]){case"create":e(["--template","-t"]);break;case"start":case"restart":e(["--daemon","-d"]);break;case"completion":e(["install","uninstall"]);break;default:e([])}return}e([])}),process.argv.includes("--completion")){try{console.log(r.setupShellInitFile())}catch(o){console.error("\u751F\u6210\u81EA\u52A8\u8865\u5168\u811A\u672C\u65F6\u51FA\u9519:",o)}process.exit(0)}process.argv.includes("--completion-fish")&&(console.log(r.setupShellInitFile("fish")),process.exit(0)),process.argv.includes("--compzsh")||process.argv.includes("--compbash"),r.init()}p(k,"setupAutoCompletion");function N(){console.log("\u{1F680} xiaozhi \u81EA\u52A8\u8865\u5168\u8BBE\u7F6E"),console.log(),console.log("\u8981\u542F\u7528\u81EA\u52A8\u8865\u5168\uFF0C\u8BF7\u6839\u636E\u4F60\u7684shell\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\uFF1A"),console.log(),console.log("\u{1F4DD} Zsh (\u63A8\u8350):"),console.log(" xiaozhi --completion >> ~/.xiaozhi-completion.zsh"),console.log(" echo 'source ~/.xiaozhi-completion.zsh' >> ~/.zshrc"),console.log(" source ~/.zshrc"),console.log(),console.log("\u{1F4DD} Bash:"),console.log(" xiaozhi --completion >> ~/.xiaozhi-completion.bash"),console.log(" echo 'source ~/.xiaozhi-completion.bash' >> ~/.bash_profile"),console.log(" source ~/.bash_profile"),console.log(),console.log("\u{1F4DD} Fish:"),console.log(" xiaozhi --completion-fish >> ~/.config/fish/completions/xiaozhi.fish"),console.log(),console.log("\u2728 \u8BBE\u7F6E\u5B8C\u6210\u540E\uFF0C\u4F60\u5C31\u53EF\u4EE5\u4F7F\u7528 Tab \u952E\u8FDB\u884C\u81EA\u52A8\u8865\u5168\u4E86\uFF01"),console.log(),console.log("\u{1F4A1} \u793A\u4F8B:"),console.log(" xiaozhi m<Tab> # \u2192 mcp"),console.log(" xiaozhi mcp l<Tab> # \u2192 list"),console.log(" xiaozhi mcp tool <Tab> # \u2192 \u663E\u793A\u6240\u6709\u670D\u52A1\u5668\u540D\u79F0")}p(N,"showCompletionHelp");export{k as setupAutoCompletion,N as showCompletionHelp};
|
|
2
2
|
//# sourceMappingURL=autoCompletion.js.map
|