xiaozhi-client 1.9.4-beta.9 → 1.9.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend/package.json +14 -19
- package/dist/cli/index.js +6 -6
- package/dist/cli/index.js.map +1 -1
- package/package.json +14 -19
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "xiaozhi-client",
|
|
3
|
-
"version": "1.9.4
|
|
3
|
+
"version": "1.9.4",
|
|
4
4
|
"description": "小智 AI 客户端 命令行工具",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -32,33 +32,28 @@
|
|
|
32
32
|
},
|
|
33
33
|
"scripts": {
|
|
34
34
|
"build": "nx reset && pnpm run clean:dist && nx run-many -t build --exclude=docs --parallel=false",
|
|
35
|
-
"test": "nx run-many -t test",
|
|
36
|
-
"test:coverage": "nx run-many -t test:coverage --parallel=false",
|
|
37
|
-
"lint": "nx run-many -t lint",
|
|
38
|
-
"lint:fix": "nx run-many -t lint:fix",
|
|
39
|
-
"type-check": "nx run-many -t type-check --exclude=docs",
|
|
40
|
-
"format": "biome format --write .",
|
|
41
|
-
"check:all": "pnpm run lint && pnpm run type-check && pnpm run check:spell && pnpm run duplicate:check",
|
|
42
|
-
"check:spell": "cspell .",
|
|
43
|
-
"duplicate:check": "jscpd apps/backend/",
|
|
44
|
-
"docker:update-version": "node docker/scripts/update-version.js",
|
|
45
|
-
"release": "nx release version && pnpm build && nx release publish",
|
|
46
|
-
"release:dry": "nx release version --dry-run",
|
|
47
|
-
"release:version": "nx release version",
|
|
48
|
-
"release:publish": "nx release publish",
|
|
49
|
-
"release:multi": "tsx scripts/publish.ts",
|
|
50
|
-
"release:multi:dry": "tsx scripts/publish.ts --dry-run",
|
|
51
35
|
"dev": "nx run-many -t build --exclude=docs --parallel=false && concurrently \"nx run backend:dev\" \"nx run cli:dev\" \"nx run frontend:dev\" --prefix \"[{name}]\" --names \"BACKEND,CLI,FRONTEND\"",
|
|
52
36
|
"dev:cli": "nx run cli:dev",
|
|
53
37
|
"dev:docs": "nx run docs:dev",
|
|
54
38
|
"dev:backend": "nx run backend:dev",
|
|
55
39
|
"dev:frontend": "nx run frontend:dev",
|
|
40
|
+
"test": "nx run-many -t test",
|
|
41
|
+
"test:coverage": "nx run-many -t test:coverage --parallel=false",
|
|
42
|
+
"lint": "nx run-many -t lint",
|
|
43
|
+
"lint:fix": "nx run-many -t lint:fix",
|
|
44
|
+
"check:type": "nx run-many -t type-check --exclude=docs",
|
|
45
|
+
"check:all": "pnpm run lint && pnpm run check:type && pnpm run check:spell && pnpm run check:cpd",
|
|
46
|
+
"check:spell": "cspell .",
|
|
47
|
+
"check:cpd": "jscpd apps/ packages/",
|
|
48
|
+
"release": "tsx scripts/publish.ts",
|
|
49
|
+
"release:dry": "tsx scripts/publish.ts --dry-run",
|
|
56
50
|
"clean:dist": "rimraf dist || rm -rf dist",
|
|
57
51
|
"link": "pnpm link --global",
|
|
58
|
-
"unlink": "pnpm unlink --global"
|
|
52
|
+
"unlink": "pnpm unlink --global",
|
|
53
|
+
"docker:update-version": "node docker/scripts/update-version.js"
|
|
59
54
|
},
|
|
60
55
|
"dependencies": {
|
|
61
|
-
"@xiaozhi-client/config": "1.9.4
|
|
56
|
+
"@xiaozhi-client/config": "1.9.4",
|
|
62
57
|
"@coze/api": "^1.3.9",
|
|
63
58
|
"@hono/node-server": "^1.17.1",
|
|
64
59
|
"@modelcontextprotocol/sdk": "^1.24.0",
|
package/dist/cli/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Z=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ye=Object.prototype.hasOwnProperty;var c=(s,e)=>Z(s,"name",{value:e,configurable:!0});var E=(s,e)=>()=>(s&&(e=s(s=0)),e);var F=(s,e)=>{for(var t in e)Z(s,t,{get:e[t],enumerable:!0})},et=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qe(e))!Ye.call(s,o)&&o!==t&&Z(s,o,{get:()=>e[o],enumerable:!(r=Ze(e,o))||r.enumerable});return s};var A=s=>et(Z({},"__esModule",{value:!0}),s);var ae,U,X,d,ce,q=E(()=>{"use strict";ae={NAME:"xiaozhi-mcp-service",DEFAULT_PORT:3e3,DEFAULT_WEB_UI_PORT:9999,PID_FILE:"xiaozhi.pid",LOG_FILE:"xiaozhi.log"},U={FILE_NAMES:["xiaozhi.config.json5","xiaozhi.config.jsonc","xiaozhi.config.json"],DEFAULT_FILE:"xiaozhi.config.default.json",DIR_ENV_VAR:"XIAOZHI_CONFIG_DIR"},X={WORK_DIR:".xiaozhi",TEMPLATES_DIR:"templates",LOGS_DIR:"logs"},d={GENERAL_ERROR:"GENERAL_ERROR",CONFIG_ERROR:"CONFIG_ERROR",SERVICE_ERROR:"SERVICE_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",FILE_ERROR:"FILE_ERROR",PROCESS_ERROR:"PROCESS_ERROR",NETWORK_ERROR:"NETWORK_ERROR",PERMISSION_ERROR:"PERMISSION_ERROR"},ce={PROCESS_STOP:3e3,SERVICE_START:1e4,NETWORK_REQUEST:5e3,FILE_OPERATION:2e3}});var R,z,y,p,m,j,L=E(()=>{"use strict";q();R=class s extends Error{constructor(t,r,o=1,n){super(t);this.code=r;this.exitCode=o;this.suggestions=n;this.name="CLIError",Error.captureStackTrace&&Error.captureStackTrace(this,s)}static{c(this,"CLIError")}static withSuggestions(t,r,o){return new s(t,r,1,o)}},z=class s extends R{static{c(this,"ConfigError")}constructor(e,t){super(e,d.CONFIG_ERROR,1,t),this.name="ConfigError"}static configNotFound(){return new s("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728",['\u8BF7\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6'])}static invalidFormat(e){return new s(`\u65E0\u6548\u7684\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F: ${e}`,["\u652F\u6301\u7684\u683C\u5F0F: json, json5, jsonc"])}},y=class s extends R{static{c(this,"ServiceError")}constructor(e,t){super(e,d.SERVICE_ERROR,1,t),this.name="ServiceError"}static alreadyRunning(e){return new s(`\u670D\u52A1\u5DF2\u7ECF\u5728\u8FD0\u884C (PID: ${e})`,['\u8BF7\u5148\u8FD0\u884C "xiaozhi stop" \u505C\u6B62\u73B0\u6709\u670D\u52A1','\u6216\u8005\u4F7F\u7528 "xiaozhi restart" \u91CD\u542F\u670D\u52A1'])}static autoRestarting(e){return new s(`\u68C0\u6D4B\u5230\u670D\u52A1\u5DF2\u5728\u8FD0\u884C (PID: ${e})\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u542F...`,["\u5982\u679C\u4E0D\u5E0C\u671B\u81EA\u52A8\u91CD\u542F\uFF0C\u8BF7\u4F7F\u7528 xiaozhi stop \u624B\u52A8\u505C\u6B62\u670D\u52A1"])}static notRunning(){return new s("\u670D\u52A1\u672A\u8FD0\u884C",['\u8BF7\u8FD0\u884C "xiaozhi start" \u542F\u52A8\u670D\u52A1'])}static startFailed(e){return new s(`\u670D\u52A1\u542F\u52A8\u5931\u8D25: ${e}`,["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u662F\u5426\u6B63\u786E","\u786E\u4FDD\u7AEF\u53E3\u672A\u88AB\u5360\u7528","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u4FE1\u606F"])}},p=class s extends R{static{c(this,"ValidationError")}constructor(e,t){super(`\u9A8C\u8BC1\u5931\u8D25: ${t} - ${e}`,d.VALIDATION_ERROR,1),this.name="ValidationError"}static invalidPort(e){return new s(`\u7AEF\u53E3\u53F7\u5FC5\u987B\u5728 1-65535 \u8303\u56F4\u5185\uFF0C\u5F53\u524D\u503C: ${e}`,"port")}static requiredField(e){return new s("\u5FC5\u586B\u5B57\u6BB5\u4E0D\u80FD\u4E3A\u7A7A",e)}},m=class s extends R{static{c(this,"FileError")}constructor(e,t,r){let o=t?`${e}: ${t}`:e;super(o,d.FILE_ERROR,1,r),this.name="FileError"}static notFound(e){return new s("\u6587\u4EF6\u4E0D\u5B58\u5728",e,["\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E"])}static permissionDenied(e){return new s("\u6743\u9650\u4E0D\u8DB3",e,["\u68C0\u67E5\u6587\u4EF6\u6743\u9650\u6216\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"])}static alreadyExists(e){return new s("\u6587\u4EF6\u5DF2\u5B58\u5728",e,["\u4F7F\u7528\u4E0D\u540C\u7684\u6587\u4EF6\u540D\u6216\u5220\u9664\u73B0\u6709\u6587\u4EF6"])}},j=class s extends R{static{c(this,"ProcessError")}constructor(e,t,r){let o=t?`${e} (PID: ${t})`:e;super(o,d.PROCESS_ERROR,1,r),this.name="ProcessError"}static killFailed(e){return new s("\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B",e,["\u8FDB\u7A0B\u53EF\u80FD\u5DF2\u7ECF\u505C\u6B62\u6216\u6743\u9650\u4E0D\u8DB3"])}static notFound(e){return new s("\u8FDB\u7A0B\u4E0D\u5B58\u5728",e)}}});import C from"fs";import{tmpdir as ot}from"os";import $ from"path";var f,K=E(()=>{"use strict";L();f=class s{static{c(this,"FileUtils")}static exists(e){try{return C.existsSync(e)}catch{return!1}}static ensureDir(e){try{C.existsSync(e)||C.mkdirSync(e,{recursive:!0})}catch{throw new m("\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55",e)}}static readFile(e,t="utf8"){try{if(!s.exists(e))throw m.notFound(e);return C.readFileSync(e,t)}catch(r){throw r instanceof m?r:new m("\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6",e)}}static writeFile(e,t,r){try{if(!r?.overwrite&&s.exists(e))throw m.alreadyExists(e);let o=$.dirname(e);s.ensureDir(o),C.writeFileSync(e,t,"utf8")}catch(o){throw o instanceof m?o:new m("\u65E0\u6CD5\u5199\u5165\u6587\u4EF6",e)}}static copyFile(e,t,r){try{if(!s.exists(e))throw m.notFound(e);if(!r?.overwrite&&s.exists(t))throw m.alreadyExists(t);let o=$.dirname(t);s.ensureDir(o),C.copyFileSync(e,t)}catch(o){throw o instanceof m?o:new m("\u65E0\u6CD5\u590D\u5236\u6587\u4EF6",e)}}static deleteFile(e){try{s.exists(e)&&C.unlinkSync(e)}catch{throw new m("\u65E0\u6CD5\u5220\u9664\u6587\u4EF6",e)}}static copyDirectory(e,t,r={}){try{if(!s.exists(e))throw m.notFound(e);s.ensureDir(t);let o=C.readdirSync(e);for(let n of o){if(r.exclude?.includes(n))continue;let i=$.join(e,n),a=$.join(t,n);C.statSync(i).isDirectory()?r.recursive!==!1&&s.copyDirectory(i,a,r):s.copyFile(i,a,{overwrite:r.overwrite})}}catch(o){throw o instanceof m?o:new m("\u65E0\u6CD5\u590D\u5236\u76EE\u5F55",e)}}static deleteDirectory(e,t={}){try{s.exists(e)&&C.rmSync(e,{recursive:t.recursive??!0,force:!0})}catch{throw new m("\u65E0\u6CD5\u5220\u9664\u76EE\u5F55",e)}}static getFileInfo(e){try{if(!s.exists(e))throw m.notFound(e);let t=C.statSync(e);return{size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory(),mtime:t.mtime,ctime:t.ctime}}catch(t){throw t instanceof m?t:new m("\u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F",e)}}static listDirectory(e,t={}){try{if(!s.exists(e))throw m.notFound(e);let r=C.readdirSync(e),o=[];for(let n of r){if(!t.includeHidden&&n.startsWith("."))continue;let i=$.join(e,n);if(o.push(i),t.recursive&&C.statSync(i).isDirectory()){let a=s.listDirectory(i,t);o=o.concat(a)}}return o}catch(r){throw r instanceof m?r:new m("\u65E0\u6CD5\u5217\u51FA\u76EE\u5F55\u5185\u5BB9",e)}}static createTempFile(e="xiaozhi-",t=".tmp"){let r=process.env.TMPDIR||process.env.TEMP||ot(),o=Date.now(),n=Math.random().toString(36).substring(2),i=`${e}${o}-${n}${t}`;return $.join(r,i)}static checkPermissions(e,t=C.constants.R_OK|C.constants.W_OK){try{return C.accessSync(e,t),!0}catch{return!1}}static getExtension(e){return $.extname(e).toLowerCase()}static getBaseName(e){return $.basename(e,$.extname(e))}static normalizePath(e){return $.normalize(e)}static resolvePath(e,t){return t?$.resolve(t,e):$.resolve(e)}}});var V,le=E(()=>{"use strict";V=class{static{c(this,"FormatUtils")}static formatUptime(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),o=Math.floor(r/60),n=Math.floor(o/24);return n>0?`${n}\u5929 ${o%24}\u5C0F\u65F6 ${r%60}\u5206\u949F`:o>0?`${o}\u5C0F\u65F6 ${r%60}\u5206\u949F`:r>0?`${r}\u5206\u949F ${t%60}\u79D2`:`${t}\u79D2`}static formatFileSize(e){let t=["B","KB","MB","GB","TB"],r=e,o=0;for(;r>=1024&&o<t.length-1;)r/=1024,o++;return`${r.toFixed(o===0?0:1)} ${t[o]}`}static formatTimestamp(e,t="full"){let r=new Date(e);switch(t){case"date":return r.toLocaleDateString("zh-CN");case"time":return r.toLocaleTimeString("zh-CN");default:return r.toLocaleString("zh-CN")}}static formatPid(e){return`PID: ${e}`}static formatPort(e){return`\u7AEF\u53E3: ${e}`}static formatUrl(e,t,r,o){let n=`${e}://${t}:${r}`;return o?`${n}${o}`:n}static formatConfigPair(e,t){return typeof t=="object"?`${e}: ${JSON.stringify(t,null,2)}`:`${e}: ${t}`}static formatError(e,t=!1){let r=`\u9519\u8BEF: ${e.message}`;return t&&e.stack&&(r+=`
|
|
3
3
|
\u5806\u6808\u4FE1\u606F:
|
|
4
4
|
${e.stack}`),r}static formatList(e,t="\u2022"){return e.map(r=>`${t} ${r}`).join(`
|
|
5
5
|
`)}static formatTable(e){if(e.length===0)return"";let t=Object.keys(e[0]),r=t.map(a=>Math.max(a.length,...e.map(g=>String(g[a]).length))),o=t.map((a,g)=>a.padEnd(r[g])).join(" | "),n=r.map(a=>"-".repeat(a)).join("-|-"),i=e.map(a=>t.map((g,v)=>String(a[g]).padEnd(r[v])).join(" | "));return[o,n,...i].join(`
|
|
6
|
-
`)}static formatProgressBar(e,t,r=20){let o=Math.min(e/t,1),n=Math.floor(o*r),i=r-n,a="\u2588".repeat(n)+"\u2591".repeat(i),g=Math.floor(o*100);return`[${a}] ${g}% (${e}/${t})`}static formatCommandArgs(e,t){let r=t.map(o=>o.includes(" ")?`"${o}"`:o);return`${e} ${r.join(" ")}`}static truncateText(e,t,r="..."){return e.length<=t?e:e.substring(0,t-r.length)+r}static formatJson(e,t=2){try{return JSON.stringify(e,null,t)}catch{return String(e)}}static formatBoolean(e,t="\u662F",r="\u5426"){return e?t:r}}});import{realpathSync as it}from"fs";import{tmpdir as at}from"os";import u from"path";import{fileURLToPath as be}from"url";var w,G=E(()=>{q();K();w=class s{static{c(this,"PathUtils")}static getPidFile(){let e=process.env[U.DIR_ENV_VAR]||process.cwd();return u.join(e,`.${le.NAME}.pid`)}static getLogFile(e){let t=e||process.cwd();return u.join(t,le.LOG_FILE)}static getConfigDir(){return process.env[U.DIR_ENV_VAR]||process.cwd()}static getWorkDir(){let e=s.getConfigDir();return u.join(e,J.WORK_DIR)}static getTemplatesDir(){let e=be(import.meta.url),t=u.dirname(e);return[u.join(t,J.TEMPLATES_DIR),u.join(t,"..","backend",J.TEMPLATES_DIR),u.join(t,"..","..","..","..",J.TEMPLATES_DIR)]}static findTemplatesDir(){let e=s.getTemplatesDir();for(let t of e)if(f.exists(t))return t;return null}static getTemplatePath(e){let t=s.findTemplatesDir();if(!t)return null;let r=u.join(t,e);return f.exists(r)?r:null}static getScriptDir(){let e=be(import.meta.url);return u.dirname(e)}static getProjectRoot(){let e=s.getScriptDir();return u.join(e,"..","..","..")}static getDistDir(){let e=s.getProjectRoot();return u.join(e,"dist")}static getRelativePath(e){let t=s.getProjectRoot();return u.relative(t,e)}static resolveConfigPath(e){let t=s.getConfigDir();if(e)return u.join(t,`xiaozhi.config.${e}`);for(let r of U.FILE_NAMES){let o=u.join(t,r);if(f.exists(o))return o}return u.join(t,U.FILE_NAMES[2])}static getDefaultConfigPath(){let e=s.getProjectRoot();return u.join(e,U.DEFAULT_FILE)}static validatePath(e){return!u.normalize(e).includes("..")}static ensurePathWithin(e,t){let r=u.resolve(t,e),o=u.resolve(t);if(!r.startsWith(o))throw new Error(`\u8DEF\u5F84 ${e} \u8D85\u51FA\u4E86\u5141\u8BB8\u7684\u8303\u56F4`);return r}static getExecutablePath(e){let t=process.argv[1];if(!t)return u.join(process.cwd(),`${e}.js`);let r;try{r=it(t)}catch{r=t}let o=u.dirname(r);return u.join(o,`${e}.js`)}static getWebServerLauncherPath(){return s.getExecutablePath("WebServerLauncher")}static createSafePath(...e){let t=u.join(...e),r=u.normalize(t);if(r.includes("..")||r.includes("~"))throw new Error(`\u4E0D\u5B89\u5168\u7684\u8DEF\u5F84: ${r}`);return r}static getTempDir(){return process.env.TMPDIR||process.env.TEMP||at()}static getHomeDir(){return process.env.HOME||process.env.USERPROFILE||""}}});import{execSync as xe}from"child_process";var D,ee=E(()=>{q();N();D=class s{static{c(this,"PlatformUtils")}static getCurrentPlatform(){return process.platform}static isWindows(){return process.platform==="win32"}static isMacOS(){return process.platform==="darwin"}static isLinux(){return process.platform==="linux"}static isUnixLike(){return!s.isWindows()}static isXiaozhiProcess(e){try{if(process.env.XIAOZHI_CONTAINER==="true"||process.env.NODE_ENV==="test")return process.kill(e,0),!0;try{let t="";return s.isWindows()?t=xe(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{encoding:"utf8",timeout:me.PROCESS_STOP}).toLowerCase():t=xe(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:me.PROCESS_STOP}).toLowerCase(),t.includes("node")||t.includes("xiaozhi")}catch{return process.kill(e,0),!0}}catch{return!1}}static async killProcess(e,t="SIGTERM"){try{process.kill(e,t);let r=0,o=30;for(;r<o;){await new Promise(n=>setTimeout(n,100));try{process.kill(e,0),r++}catch{return}}try{process.kill(e,0),process.kill(e,"SIGKILL"),await new Promise(n=>setTimeout(n,500))}catch{}}catch(r){throw new H(`\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B: ${r instanceof Error?r.message:String(r)}`,e)}}static processExists(e){try{return process.kill(e,0),!0}catch{return!1}}static getSystemInfo(){return{platform:s.getCurrentPlatform(),arch:process.arch,nodeVersion:process.version,isContainer:process.env.XIAOZHI_CONTAINER==="true"}}static getEnvVar(e,t){return process.env[e]||t}static setEnvVar(e,t){process.env[e]=t}static isContainerEnvironment(){return process.env.XIAOZHI_CONTAINER==="true"}static isTestEnvironment(){return process.env.NODE_ENV==="test"}static isDevelopmentEnvironment(){return process.env.NODE_ENV==="development"}static getTailCommand(e){return s.isWindows()?{command:"powershell",args:["-Command",`Get-Content -Path "${e}" -Wait`]}:{command:"tail",args:["-f",e]}}}});var M,te=E(()=>{N();M=class s{static{c(this,"Validation")}static validatePort(e){if(!Number.isInteger(e)||e<1||e>65535)throw p.invalidPort(e)}static validateConfigFormat(e){let t=["json","json5","jsonc"];if(!t.includes(e))throw new p(`\u65E0\u6548\u7684\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F: ${e}\uFF0C\u652F\u6301\u7684\u683C\u5F0F: ${t.join(", ")}`,"format");return e}static validateRequired(e,t){if(e==null||e==="")throw p.requiredField(t)}static validateStringLength(e,t,r={}){if(r.min!==void 0&&e.length<r.min)throw new p(`\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E ${r.min} \u4E2A\u5B57\u7B26\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t);if(r.max!==void 0&&e.length>r.max)throw new p(`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${r.max} \u4E2A\u5B57\u7B26\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t)}static validateUrl(e,t="url"){try{new URL(e)}catch{throw new p(`\u65E0\u6548\u7684 URL \u683C\u5F0F: ${e}`,t)}}static validateWebSocketUrl(e,t="websocket_url"){s.validateUrl(e,t);let r=new URL(e);if(!["ws:","wss:"].includes(r.protocol))throw new p(`WebSocket URL \u5FC5\u987B\u4F7F\u7528 ws:// \u6216 wss:// \u534F\u8BAE\uFF0C\u5F53\u524D\u534F\u8BAE: ${r.protocol}`,t)}static validateHttpUrl(e,t="http_url"){s.validateUrl(e,t);let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new p(`HTTP URL \u5FC5\u987B\u4F7F\u7528 http:// \u6216 https:// \u534F\u8BAE\uFF0C\u5F53\u524D\u534F\u8BAE: ${r.protocol}`,t)}static validateProjectName(e){s.validateRequired(e,"projectName"),s.validateStringLength(e,"projectName",{min:1,max:100});let t=/[<>:"/\\|?*]/,r=e.split("").some(o=>o.charCodeAt(0)<32);if(t.test(e)||r)throw new p('\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u5305\u542B\u4EE5\u4E0B\u5B57\u7B26: < > : " / \\ | ? * \u4EE5\u53CA\u63A7\u5236\u5B57\u7B26',"projectName");if(e.startsWith("."))throw new p("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4EE5\u70B9\u5F00\u5934","projectName")}static validateTemplateName(e){if(s.validateRequired(e,"templateName"),s.validateStringLength(e,"templateName",{min:1,max:50}),!/^[a-zA-Z0-9_-]+$/.test(e))throw new p("\u6A21\u677F\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\u548C\u4E0B\u5212\u7EBF","templateName")}static validateEnvVarName(e){if(s.validateRequired(e,"envVarName"),!/^[A-Z_][A-Z0-9_]*$/.test(e))throw new p("\u73AF\u5883\u53D8\u91CF\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5927\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u4EE5\u6570\u5B57\u5F00\u5934","envVarName")}static validateJson(e,t="json"){try{return JSON.parse(e)}catch(r){throw new p(`\u65E0\u6548\u7684 JSON \u683C\u5F0F: ${r instanceof Error?r.message:String(r)}`,t)}}static validateNumberRange(e,t,r={}){if(r.min!==void 0&&e<r.min)throw new p(`\u503C\u4E0D\u80FD\u5C0F\u4E8E ${r.min}\uFF0C\u5F53\u524D\u503C: ${e}`,t);if(r.max!==void 0&&e>r.max)throw new p(`\u503C\u4E0D\u80FD\u5927\u4E8E ${r.max}\uFF0C\u5F53\u524D\u503C: ${e}`,t)}static validateArrayLength(e,t,r={}){if(r.min!==void 0&&e.length<r.min)throw new p(`\u6570\u7EC4\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E ${r.min}\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t);if(r.max!==void 0&&e.length>r.max)throw new p(`\u6570\u7EC4\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${r.max}\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t)}static validateObjectProperties(e,t,r="object"){for(let o of t)if(!(o in e))throw new p(`\u7F3A\u5C11\u5FC5\u9700\u7684\u5C5E\u6027: ${o}`,r)}static validateEnum(e,t,r){if(!t.includes(e))throw new p(`\u65E0\u6548\u7684\u503C: ${e}\uFF0C\u6709\u6548\u503C: ${t.join(", ")}`,r);return e}static validateRegex(e,t="regex"){try{return new RegExp(e)}catch(r){throw new p(`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${r instanceof Error?r.message:String(r)}`,t)}}}});var Te={};j(Te,{ProcessManagerImpl:()=>Z});var Z,de=E(()=>{N();K();ge();G();ee();Z=class{static{c(this,"ProcessManagerImpl")}getPidFilePath(){return w.getPidFile()}readPidFile(){try{let e=this.getPidFilePath();if(!f.exists(e))return null;let t=f.readFile(e).trim(),[r,o,n]=t.split("|"),i=Number.parseInt(r),a=Number.parseInt(o);return Number.isNaN(i)||Number.isNaN(a)?(this.cleanupPidFile(),null):{pid:i,startTime:a,mode:n||"foreground"}}catch{return this.cleanupPidFile(),null}}writePidFile(e,t){try{let r=`${e}|${Date.now()}|${t}`,o=this.getPidFilePath();f.writeFile(o,r,{overwrite:!0})}catch{throw new m("\u65E0\u6CD5\u5199\u5165 PID \u6587\u4EF6",this.getPidFilePath())}}isXiaozhiProcess(e){return D.isXiaozhiProcess(e)}getServiceStatus(){try{let e=this.readPidFile();if(!e)return{running:!1};if(!this.isXiaozhiProcess(e.pid))return this.cleanupPidFile(),{running:!1};let t=W.formatUptime(Date.now()-e.startTime);return{running:!0,pid:e.pid,uptime:t,mode:e.mode}}catch{return{running:!1}}}savePidInfo(e,t){this.writePidFile(e,t)}async killProcess(e){try{await D.killProcess(e)}catch(t){throw new H(`\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B: ${t instanceof Error?t.message:String(t)}`,e)}}async gracefulKillProcess(e){try{process.kill(e,"SIGTERM");let t=0,r=30;for(;t<r;){await new Promise(o=>setTimeout(o,100));try{process.kill(e,0),t++}catch{return}}try{process.kill(e,0),process.kill(e,"SIGKILL"),await new Promise(o=>setTimeout(o,500))}catch{}}catch(t){throw new H(`\u65E0\u6CD5\u505C\u6B62\u8FDB\u7A0B: ${t instanceof Error?t.message:String(t)}`,e)}}cleanupPidFile(){try{let e=this.getPidFilePath();f.exists(e)&&f.deleteFile(e)}catch(e){console.warn("\u6E05\u7406 PID \u6587\u4EF6\u5931\u8D25:",e)}}processExists(e){return D.processExists(e)}cleanupContainerState(){if(D.isContainerEnvironment())try{this.cleanupPidFile()}catch{}}getProcessInfo(e){let t=this.processExists(e),r=t?this.isXiaozhiProcess(e):!1;return{exists:t,isXiaozhi:r}}validatePidFile(){try{return this.readPidFile()!==null}catch{return!1}}}});var Oe={};j(Oe,{DaemonManagerImpl:()=>pe});import{spawn as Me}from"child_process";import ne from"fs";import z from"consola";var pe,De=E(()=>{N();G();ee();pe=class{constructor(e){this.processManager=e}static{c(this,"DaemonManagerImpl")}currentDaemon=null;async startDaemon(e,t={}){try{let r=this.processManager.getServiceStatus();if(r.running)throw y.alreadyRunning(r.pid);let o=await this.spawnDaemonProcess(e,t);this.currentDaemon=o,this.processManager.savePidInfo(o.pid,"daemon"),await this.setupLogging(o,t.logFileName||"xiaozhi.log"),this.setupEventHandlers(o),o.unref(),z.info(`\u5B88\u62A4\u8FDB\u7A0B\u5DF2\u542F\u52A8 (PID: ${o.pid})`)}catch(r){throw new y(`\u542F\u52A8\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}async stopDaemon(){try{let e=this.processManager.getServiceStatus();if(!e.running)throw y.notRunning();await this.processManager.gracefulKillProcess(e.pid),this.processManager.cleanupPidFile(),this.currentDaemon=null,z.info("\u5B88\u62A4\u8FDB\u7A0B\u5DF2\u505C\u6B62")}catch(e){throw new y(`\u505C\u6B62\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async restartDaemon(e,t={}){try{this.processManager.getServiceStatus().running&&(await this.stopDaemon(),await new Promise(o=>setTimeout(o,1e3))),await this.startDaemon(e,t)}catch(r){throw new y(`\u91CD\u542F\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}getDaemonStatus(){return this.processManager.getServiceStatus()}async attachToLogs(e="xiaozhi.log"){try{let t=w.getLogFile();if(!ne.existsSync(t))throw new y("\u65E5\u5FD7\u6587\u4EF6\u4E0D\u5B58\u5728");let{command:r,args:o}=D.getTailCommand(t),n=Me(r,o,{stdio:"inherit"});process.on("SIGINT",()=>{console.log(`
|
|
7
|
-
\u65AD\u5F00\u8FDE\u63A5\uFF0C\u670D\u52A1\u7EE7\u7EED\u5728\u540E\u53F0\u8FD0\u884C`),n.kill(),process.exit(0)}),n.on("exit",()=>{process.exit(0)}),n.on("error",i=>{throw new y(`\u8FDE\u63A5\u65E5\u5FD7\u5931\u8D25: ${i.message}`)})}catch(t){throw new y(`\u8FDE\u63A5\u65E5\u5FD7\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}async spawnDaemonProcess(e,t){let o=[w.getWebServerLauncherPath()];t.openBrowser&&o.push("--open-browser");let n={...process.env,XIAOZHI_CONFIG_DIR:w.getConfigDir(),XIAOZHI_DAEMON:"true",...t.env},i
|
|
6
|
+
`)}static formatProgressBar(e,t,r=20){let o=Math.min(e/t,1),n=Math.floor(o*r),i=r-n,a="\u2588".repeat(n)+"\u2591".repeat(i),g=Math.floor(o*100);return`[${a}] ${g}% (${e}/${t})`}static formatCommandArgs(e,t){let r=t.map(o=>o.includes(" ")?`"${o}"`:o);return`${e} ${r.join(" ")}`}static truncateText(e,t,r="..."){return e.length<=t?e:e.substring(0,t-r.length)+r}static formatJson(e,t=2){try{return JSON.stringify(e,null,t)}catch{return String(e)}}static formatBoolean(e,t="\u662F",r="\u5426"){return e?t:r}}});import{realpathSync as nt}from"fs";import{tmpdir as st}from"os";import h from"path";import{fileURLToPath as Ie}from"url";var w,W=E(()=>{"use strict";q();K();w=class s{static{c(this,"PathUtils")}static getPidFile(){let e=process.env[U.DIR_ENV_VAR]||process.cwd();return h.join(e,`.${ae.NAME}.pid`)}static getLogFile(e){let t=e||process.cwd();return h.join(t,ae.LOG_FILE)}static getConfigDir(){return process.env[U.DIR_ENV_VAR]||process.cwd()}static getWorkDir(){let e=s.getConfigDir();return h.join(e,X.WORK_DIR)}static getTemplatesDir(){let e=Ie(import.meta.url),t=h.dirname(e);return[h.join(t,X.TEMPLATES_DIR),h.join(t,"..","backend",X.TEMPLATES_DIR),h.join(t,"..","..","..","..",X.TEMPLATES_DIR)]}static findTemplatesDir(){let e=s.getTemplatesDir();for(let t of e)if(f.exists(t))return t;return null}static getTemplatePath(e){let t=s.findTemplatesDir();if(!t)return null;let r=h.join(t,e);return f.exists(r)?r:null}static getScriptDir(){let e=Ie(import.meta.url);return h.dirname(e)}static getProjectRoot(){let e=s.getScriptDir();return h.join(e,"..","..","..")}static getDistDir(){let e=s.getProjectRoot();return h.join(e,"dist")}static getRelativePath(e){let t=s.getProjectRoot();return h.relative(t,e)}static resolveConfigPath(e){let t=s.getConfigDir();if(e)return h.join(t,`xiaozhi.config.${e}`);for(let r of U.FILE_NAMES){let o=h.join(t,r);if(f.exists(o))return o}return h.join(t,U.FILE_NAMES[2])}static getDefaultConfigPath(){let e=s.getProjectRoot();return h.join(e,U.DEFAULT_FILE)}static validatePath(e){return!h.normalize(e).includes("..")}static ensurePathWithin(e,t){let r=h.resolve(t,e),o=h.resolve(t);if(!r.startsWith(o))throw new Error(`\u8DEF\u5F84 ${e} \u8D85\u51FA\u4E86\u5141\u8BB8\u7684\u8303\u56F4`);return r}static getExecutablePath(e){let t=process.argv[1];if(!t)return h.join(process.cwd(),`${e}.js`);let r;try{r=nt(t)}catch{r=t}let o=h.dirname(r);return h.join(o,`${e}.js`)}static getWebServerLauncherPath(){return s.getExecutablePath("WebServerLauncher")}static createSafePath(...e){let t=h.join(...e),r=h.normalize(t);if(r.includes("..")||r.includes("~"))throw new Error(`\u4E0D\u5B89\u5168\u7684\u8DEF\u5F84: ${r}`);return r}static getTempDir(){return process.env.TMPDIR||process.env.TEMP||st()}static getHomeDir(){return process.env.HOME||process.env.USERPROFILE||""}}});import{execSync as be}from"child_process";var D,Y=E(()=>{"use strict";q();L();D=class s{static{c(this,"PlatformUtils")}static getCurrentPlatform(){return process.platform}static isWindows(){return process.platform==="win32"}static isMacOS(){return process.platform==="darwin"}static isLinux(){return process.platform==="linux"}static isUnixLike(){return!s.isWindows()}static isXiaozhiProcess(e){try{if(process.env.XIAOZHI_CONTAINER==="true"||process.env.NODE_ENV==="test")return process.kill(e,0),!0;try{let t="";return s.isWindows()?t=be(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{encoding:"utf8",timeout:ce.PROCESS_STOP}).toLowerCase():t=be(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:ce.PROCESS_STOP}).toLowerCase(),t.includes("node")||t.includes("xiaozhi")}catch{return process.kill(e,0),!0}}catch{return!1}}static async killProcess(e,t="SIGTERM"){try{process.kill(e,t);let r=0,o=30;for(;r<o;){await new Promise(n=>setTimeout(n,100));try{process.kill(e,0),r++}catch{return}}try{process.kill(e,0),process.kill(e,"SIGKILL"),await new Promise(n=>setTimeout(n,500))}catch{}}catch(r){throw new j(`\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B: ${r instanceof Error?r.message:String(r)}`,e)}}static processExists(e){try{return process.kill(e,0),!0}catch{return!1}}static getSystemInfo(){return{platform:s.getCurrentPlatform(),arch:process.arch,nodeVersion:process.version,isContainer:process.env.XIAOZHI_CONTAINER==="true"}}static getEnvVar(e,t){return process.env[e]||t}static setEnvVar(e,t){process.env[e]=t}static isContainerEnvironment(){return process.env.XIAOZHI_CONTAINER==="true"}static isTestEnvironment(){return process.env.NODE_ENV==="test"}static isDevelopmentEnvironment(){return process.env.NODE_ENV==="development"}static getTailCommand(e){return s.isWindows()?{command:"powershell",args:["-Command",`Get-Content -Path "${e}" -Wait`]}:{command:"tail",args:["-f",e]}}}});var M,ee=E(()=>{"use strict";L();M=class s{static{c(this,"Validation")}static validatePort(e){if(!Number.isInteger(e)||e<1||e>65535)throw p.invalidPort(e)}static validateConfigFormat(e){let t=["json","json5","jsonc"];if(!t.includes(e))throw new p(`\u65E0\u6548\u7684\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F: ${e}\uFF0C\u652F\u6301\u7684\u683C\u5F0F: ${t.join(", ")}`,"format");return e}static validateRequired(e,t){if(e==null||e==="")throw p.requiredField(t)}static validateStringLength(e,t,r={}){if(r.min!==void 0&&e.length<r.min)throw new p(`\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E ${r.min} \u4E2A\u5B57\u7B26\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t);if(r.max!==void 0&&e.length>r.max)throw new p(`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${r.max} \u4E2A\u5B57\u7B26\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t)}static validateUrl(e,t="url"){try{new URL(e)}catch{throw new p(`\u65E0\u6548\u7684 URL \u683C\u5F0F: ${e}`,t)}}static validateWebSocketUrl(e,t="websocket_url"){s.validateUrl(e,t);let r=new URL(e);if(!["ws:","wss:"].includes(r.protocol))throw new p(`WebSocket URL \u5FC5\u987B\u4F7F\u7528 ws:// \u6216 wss:// \u534F\u8BAE\uFF0C\u5F53\u524D\u534F\u8BAE: ${r.protocol}`,t)}static validateHttpUrl(e,t="http_url"){s.validateUrl(e,t);let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new p(`HTTP URL \u5FC5\u987B\u4F7F\u7528 http:// \u6216 https:// \u534F\u8BAE\uFF0C\u5F53\u524D\u534F\u8BAE: ${r.protocol}`,t)}static validateProjectName(e){s.validateRequired(e,"projectName"),s.validateStringLength(e,"projectName",{min:1,max:100});let t=/[<>:"/\\|?*]/,r=e.split("").some(o=>o.charCodeAt(0)<32);if(t.test(e)||r)throw new p('\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u5305\u542B\u4EE5\u4E0B\u5B57\u7B26: < > : " / \\ | ? * \u4EE5\u53CA\u63A7\u5236\u5B57\u7B26',"projectName");if(e.startsWith("."))throw new p("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4EE5\u70B9\u5F00\u5934","projectName")}static validateTemplateName(e){if(s.validateRequired(e,"templateName"),s.validateStringLength(e,"templateName",{min:1,max:50}),!/^[a-zA-Z0-9_-]+$/.test(e))throw new p("\u6A21\u677F\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\u548C\u4E0B\u5212\u7EBF","templateName")}static validateEnvVarName(e){if(s.validateRequired(e,"envVarName"),!/^[A-Z_][A-Z0-9_]*$/.test(e))throw new p("\u73AF\u5883\u53D8\u91CF\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5927\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u4EE5\u6570\u5B57\u5F00\u5934","envVarName")}static validateJson(e,t="json"){try{return JSON.parse(e)}catch(r){throw new p(`\u65E0\u6548\u7684 JSON \u683C\u5F0F: ${r instanceof Error?r.message:String(r)}`,t)}}static validateNumberRange(e,t,r={}){if(r.min!==void 0&&e<r.min)throw new p(`\u503C\u4E0D\u80FD\u5C0F\u4E8E ${r.min}\uFF0C\u5F53\u524D\u503C: ${e}`,t);if(r.max!==void 0&&e>r.max)throw new p(`\u503C\u4E0D\u80FD\u5927\u4E8E ${r.max}\uFF0C\u5F53\u524D\u503C: ${e}`,t)}static validateArrayLength(e,t,r={}){if(r.min!==void 0&&e.length<r.min)throw new p(`\u6570\u7EC4\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E ${r.min}\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t);if(r.max!==void 0&&e.length>r.max)throw new p(`\u6570\u7EC4\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${r.max}\uFF0C\u5F53\u524D\u957F\u5EA6: ${e.length}`,t)}static validateObjectProperties(e,t,r="object"){for(let o of t)if(!(o in e))throw new p(`\u7F3A\u5C11\u5FC5\u9700\u7684\u5C5E\u6027: ${o}`,r)}static validateEnum(e,t,r){if(!t.includes(e))throw new p(`\u65E0\u6548\u7684\u503C: ${e}\uFF0C\u6709\u6548\u503C: ${t.join(", ")}`,r);return e}static validateRegex(e,t="regex"){try{return new RegExp(e)}catch(r){throw new p(`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${r instanceof Error?r.message:String(r)}`,t)}}}});var Te={};F(Te,{ProcessManagerImpl:()=>J});var J,ge=E(()=>{"use strict";L();K();le();W();Y();J=class{static{c(this,"ProcessManagerImpl")}getPidFilePath(){return w.getPidFile()}readPidFile(){try{let e=this.getPidFilePath();if(!f.exists(e))return null;let t=f.readFile(e).trim(),[r,o,n]=t.split("|"),i=Number.parseInt(r),a=Number.parseInt(o);return Number.isNaN(i)||Number.isNaN(a)?(this.cleanupPidFile(),null):{pid:i,startTime:a,mode:n||"foreground"}}catch{return this.cleanupPidFile(),null}}writePidFile(e,t){try{let r=`${e}|${Date.now()}|${t}`,o=this.getPidFilePath();f.writeFile(o,r,{overwrite:!0})}catch{throw new m("\u65E0\u6CD5\u5199\u5165 PID \u6587\u4EF6",this.getPidFilePath())}}isXiaozhiProcess(e){return D.isXiaozhiProcess(e)}getServiceStatus(){try{let e=this.readPidFile();if(!e)return{running:!1};if(!this.isXiaozhiProcess(e.pid))return this.cleanupPidFile(),{running:!1};let t=V.formatUptime(Date.now()-e.startTime);return{running:!0,pid:e.pid,uptime:t,mode:e.mode}}catch{return{running:!1}}}savePidInfo(e,t){this.writePidFile(e,t)}async killProcess(e){try{await D.killProcess(e)}catch(t){throw new j(`\u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B: ${t instanceof Error?t.message:String(t)}`,e)}}async gracefulKillProcess(e){try{process.kill(e,"SIGTERM");let t=0,r=30;for(;t<r;){await new Promise(o=>setTimeout(o,100));try{process.kill(e,0),t++}catch{return}}try{process.kill(e,0),process.kill(e,"SIGKILL"),await new Promise(o=>setTimeout(o,500))}catch{}}catch(t){throw new j(`\u65E0\u6CD5\u505C\u6B62\u8FDB\u7A0B: ${t instanceof Error?t.message:String(t)}`,e)}}cleanupPidFile(){try{let e=this.getPidFilePath();f.exists(e)&&f.deleteFile(e)}catch(e){console.warn("\u6E05\u7406 PID \u6587\u4EF6\u5931\u8D25:",e)}}processExists(e){return D.processExists(e)}cleanupContainerState(){if(D.isContainerEnvironment())try{this.cleanupPidFile()}catch{}}getProcessInfo(e){let t=this.processExists(e),r=t?this.isXiaozhiProcess(e):!1;return{exists:t,isXiaozhi:r}}validatePidFile(){try{return this.readPidFile()!==null}catch{return!1}}}});var Me={};F(Me,{DaemonManagerImpl:()=>de});import{spawn as $e}from"child_process";import re from"fs";import _ from"consola";var de,Oe=E(()=>{"use strict";L();W();Y();de=class{constructor(e){this.processManager=e}static{c(this,"DaemonManagerImpl")}currentDaemon=null;async startDaemon(e,t={}){try{let r=this.processManager.getServiceStatus();if(r.running)throw y.alreadyRunning(r.pid);let o=await this.spawnDaemonProcess(e,t);this.currentDaemon=o,this.processManager.savePidInfo(o.pid,"daemon"),await this.setupLogging(o,t.logFileName||"xiaozhi.log"),this.setupEventHandlers(o),o.unref(),_.info(`\u5B88\u62A4\u8FDB\u7A0B\u5DF2\u542F\u52A8 (PID: ${o.pid})`)}catch(r){throw new y(`\u542F\u52A8\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}async stopDaemon(){try{let e=this.processManager.getServiceStatus();if(!e.running)throw y.notRunning();await this.processManager.gracefulKillProcess(e.pid),this.processManager.cleanupPidFile(),this.currentDaemon=null,_.info("\u5B88\u62A4\u8FDB\u7A0B\u5DF2\u505C\u6B62")}catch(e){throw new y(`\u505C\u6B62\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async restartDaemon(e,t={}){try{this.processManager.getServiceStatus().running&&(await this.stopDaemon(),await new Promise(o=>setTimeout(o,1e3))),await this.startDaemon(e,t)}catch(r){throw new y(`\u91CD\u542F\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}getDaemonStatus(){return this.processManager.getServiceStatus()}async attachToLogs(e="xiaozhi.log"){try{let t=w.getLogFile();if(!re.existsSync(t))throw new y("\u65E5\u5FD7\u6587\u4EF6\u4E0D\u5B58\u5728");let{command:r,args:o}=D.getTailCommand(t),n=$e(r,o,{stdio:"inherit"});process.on("SIGINT",()=>{console.log(`
|
|
7
|
+
\u65AD\u5F00\u8FDE\u63A5\uFF0C\u670D\u52A1\u7EE7\u7EED\u5728\u540E\u53F0\u8FD0\u884C`),n.kill(),process.exit(0)}),n.on("exit",()=>{process.exit(0)}),n.on("error",i=>{throw new y(`\u8FDE\u63A5\u65E5\u5FD7\u5931\u8D25: ${i.message}`)})}catch(t){throw new y(`\u8FDE\u63A5\u65E5\u5FD7\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}async spawnDaemonProcess(e,t){let o=[w.getWebServerLauncherPath()];t.openBrowser&&o.push("--open-browser");let n={...process.env,XIAOZHI_CONFIG_DIR:w.getConfigDir(),XIAOZHI_DAEMON:"true",...t.env},i=$e("node",o,{detached:!0,stdio:["ignore","pipe","pipe"],env:n,cwd:t.cwd||process.cwd()});if(!i.pid)throw new j("\u65E0\u6CD5\u542F\u52A8\u5B88\u62A4\u8FDB\u7A0B",0);return i}async setupLogging(e,t){try{let r=w.getLogFile(),n=(await import("path")).dirname(r);re.existsSync(n)||re.mkdirSync(n,{recursive:!0});let i=re.createWriteStream(r,{flags:"a"});e.stdout?.pipe(i),e.stderr?.pipe(i);let a=new Date().toISOString();i.write(`
|
|
8
8
|
[${a}] \u5B88\u62A4\u8FDB\u7A0B\u542F\u52A8 (PID: ${e.pid})
|
|
9
|
-
`)}catch(r){z.warn(`\u8BBE\u7F6E\u65E5\u5FD7\u91CD\u5B9A\u5411\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}setupEventHandlers(e){e.on("exit",(t,r)=>{t!==0&&t!==null?z.error(`\u5B88\u62A4\u8FDB\u7A0B\u5F02\u5E38\u9000\u51FA (\u4EE3\u7801: ${t}, \u4FE1\u53F7: ${r})`):z.info("\u5B88\u62A4\u8FDB\u7A0B\u6B63\u5E38\u9000\u51FA"),this.processManager.cleanupPidFile(),this.currentDaemon=null}),e.on("error",t=>{z.error(`\u5B88\u62A4\u8FDB\u7A0B\u9519\u8BEF: ${t.message}`),this.processManager.cleanupPidFile(),this.currentDaemon=null}),e.on("disconnect",()=>{z.info("\u5B88\u62A4\u8FDB\u7A0B\u65AD\u5F00\u8FDE\u63A5")})}async checkHealth(){try{let e=this.getDaemonStatus();if(!e.running||!e.pid)return!1;let t=this.processManager.getProcessInfo(e.pid);return t.exists&&t.isXiaozhi}catch{return!1}}getCurrentDaemon(){return this.currentDaemon}cleanup(){if(this.currentDaemon){try{this.currentDaemon.kill("SIGTERM")}catch(e){z.warn(`\u6E05\u7406\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}this.currentDaemon=null}}}});var Fe={};j(Fe,{ServiceManagerImpl:()=>fe});var fe,Ne=E(()=>{N();G();te();fe=class{constructor(e,t){this.processManager=e;this.configManager=t}static{c(this,"ServiceManagerImpl")}async start(e){try{this.validateStartOptions(e),this.processManager.cleanupContainerState();let t=this.getStatus();if(t.running){console.log(`\u68C0\u6D4B\u5230\u670D\u52A1\u5DF2\u5728\u8FD0\u884C (PID: ${t.pid})\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u542F...`);try{await this.processManager.gracefulKillProcess(t.pid||0),this.processManager.cleanupPidFile(),await new Promise(r=>setTimeout(r,1e3)),console.log("\u73B0\u6709\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u6B63\u5728\u542F\u52A8\u65B0\u670D\u52A1...")}catch(r){console.warn(`\u505C\u6B62\u73B0\u6709\u670D\u52A1\u65F6\u51FA\u73B0\u8B66\u544A: ${r instanceof Error?r.message:String(r)}`)}}switch(this.checkEnvironment(),e.mode){case"mcp-server":await this.startMcpServerMode(e);break;case"stdio":await this.startNormalMode(e);break;case"normal":await this.startNormalMode(e);break;default:await this.startNormalMode(e);break}}catch(t){throw t instanceof y?t:y.startFailed(t instanceof Error?t.message:String(t))}}async stop(){try{let e=this.getStatus();if(!e.running)throw y.notRunning();await this.processManager.gracefulKillProcess(e.pid||0),this.processManager.cleanupPidFile()}catch(e){throw e instanceof y?e:new y(`\u505C\u6B62\u670D\u52A1\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async restart(e){try{this.getStatus().running&&(await this.stop(),await new Promise(r=>setTimeout(r,1e3))),await this.start(e)}catch(t){throw new y(`\u91CD\u542F\u670D\u52A1\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}getStatus(){return this.processManager.getServiceStatus()}validateStartOptions(e){if(e.port!==void 0&&M.validatePort(e.port),e.mode&&!["normal","mcp-server","stdio"].includes(e.mode))throw new y(`\u65E0\u6548\u7684\u8FD0\u884C\u6A21\u5F0F: ${e.mode}`)}checkEnvironment(){if(!this.configManager.configExists())throw _.configNotFound();try{if(!this.configManager.getConfig())throw new _("\u914D\u7F6E\u6587\u4EF6\u65E0\u6548")}catch(e){throw e instanceof _?e:new _(`\u914D\u7F6E\u6587\u4EF6\u9519\u8BEF: ${e instanceof Error?e.message:String(e)}`)}}async startNormalMode(e){e.daemon?await this.startWebServerInDaemon():await this.startWebServerInForeground()}async startMcpServerMode(e){let t=e.port||3e3,{spawn:r}=await import("child_process");if(e.daemon){let o=w.getExecutablePath("cli"),n=r("node",[o,"start","--server",t.toString()],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:w.getConfigDir(),XIAOZHI_DAEMON:"true",MCP_SERVER_MODE:"true"}});this.processManager.savePidInfo(n.pid||0,"daemon"),n.unref(),console.log(`\u2705 MCP Server \u5DF2\u5728\u540E\u53F0\u542F\u52A8 (PID: ${n.pid}, Port: ${t})`),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi status' \u67E5\u770B\u72B6\u6001"),process.exit(0)}else{let{WebServer:o}=await import("../backend/WebServer.js"),n=new o(t),i=c(async()=>{await n.stop(),process.exit(0)},"cleanup");process.on("SIGINT",i),process.on("SIGTERM",i),await n.start()}}async startWebServerInDaemon(){let{spawn:e}=await import("child_process"),t=w.getWebServerLauncherPath();if(!(await import("fs")).default.existsSync(t))throw new y(`WebServer \u6587\u4EF6\u4E0D\u5B58\u5728: ${t}`);let n=e("node",[t],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:w.getConfigDir(),XIAOZHI_DAEMON:"true"}});this.processManager.savePidInfo(n.pid||0,"daemon"),n.unref(),console.log(`\u2705 \u540E\u53F0\u670D\u52A1\u5DF2\u542F\u52A8 (PID: ${n.pid})`),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi status' \u67E5\u770B\u72B6\u6001"),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi attach' \u67E5\u770B\u65E5\u5FD7"),process.exit(0)}async startWebServerInForeground(){let{WebServer:e}=await import("../backend/WebServer.js"),t=new e,r=c(async()=>{await t.stop(),this.processManager.cleanupPidFile(),process.exit(0)},"cleanup");process.on("SIGINT",r),process.on("SIGTERM",r),this.processManager.savePidInfo(process.pid,"foreground"),await t.start()}}});var Ae={};j(Ae,{TemplateManagerImpl:()=>ue});import ct from"fs";import k from"path";var ue,je=E(()=>{N();K();G();te();ue=class{static{c(this,"TemplateManagerImpl")}templateCache=new Map;async getAvailableTemplates(){try{let e=w.findTemplatesDir();if(!e)return[];let t=[],r=ct.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of r)try{let n=await this.getTemplateInfo(o);n&&t.push(n)}catch{console.warn(`\u8DF3\u8FC7\u65E0\u6548\u6A21\u677F: ${o}`)}return t}catch{throw new m("\u65E0\u6CD5\u8BFB\u53D6\u6A21\u677F\u76EE\u5F55",w.findTemplatesDir()||"")}}async getTemplateInfo(e){try{if(M.validateTemplateName(e),this.templateCache.has(e))return this.templateCache.get(e);let t=w.getTemplatePath(e);if(!t)return null;let r=k.join(t,"template.json"),o={};if(f.exists(r))try{let a=f.readFile(r);o=JSON.parse(a)}catch{console.warn(`\u6A21\u677F\u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${e}`)}let n=this.getTemplateFiles(t),i={name:e,path:t,description:o.description||`${e} \u6A21\u677F`,version:o.version||"1.0.0",author:o.author,files:n};return this.templateCache.set(e,i),i}catch(t){throw t instanceof p?t:new m(`\u65E0\u6CD5\u83B7\u53D6\u6A21\u677F\u4FE1\u606F: ${e}`,"")}}async copyTemplate(e,t){await this.createProject({templateName:e,targetPath:t,projectName:k.basename(t)})}async createProject(e){try{this.validateCreateOptions(e);let t=e.templateName||"default",r=await this.getTemplateInfo(t);if(!r)throw new m(`\u6A21\u677F\u4E0D\u5B58\u5728: ${t}`,"");let o=k.resolve(e.targetPath);if(f.exists(o))throw m.alreadyExists(o);f.ensureDir(o),await this.copyTemplateFiles(r,o,e),await this.processTemplateVariables(o,e),console.log(`\u2705 \u9879\u76EE\u521B\u5EFA\u6210\u529F: ${o}`)}catch(t){throw t instanceof m||t instanceof p?t:new m(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,e.targetPath)}}async validateTemplate(e){try{let t=await this.getTemplateInfo(e);if(!t)return!1;let r=["package.json"];for(let o of r){let n=k.join(t.path,o);if(!f.exists(n))return console.warn(`\u6A21\u677F\u7F3A\u5C11\u5FC5\u8981\u6587\u4EF6: ${o}`),!1}return!0}catch{return!1}}clearCache(){this.templateCache.clear()}getTemplateFiles(e){try{return f.listDirectory(e,{recursive:!0,includeHidden:!1}).filter(r=>{let o=k.relative(e,r);return!o.startsWith(".")&&o!=="template.json"&&!o.includes("node_modules")})}catch{return[]}}validateCreateOptions(e){M.validateRequired(e.targetPath,"targetPath"),M.validateRequired(e.projectName,"projectName"),M.validateProjectName(e.projectName),e.templateName&&M.validateTemplateName(e.templateName)}async copyTemplateFiles(e,t,r){try{f.copyDirectory(e.path,t,{exclude:["template.json",".git","node_modules"],overwrite:!1,recursive:!0})}catch(o){throw new m(`\u590D\u5236\u6A21\u677F\u6587\u4EF6\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`,e.path)}}async processTemplateVariables(e,t){try{let r={PROJECT_NAME:t.projectName,PROJECT_NAME_LOWER:t.projectName.toLowerCase(),PROJECT_NAME_UPPER:t.projectName.toUpperCase(),...t.variables},o=["package.json","README.md","src/**/*.ts","src/**/*.js","src/**/*.json"];for(let n of o){let i=this.findFilesByPattern(e,n);for(let a of i)await this.replaceVariablesInFile(a,r)}}catch(r){console.warn(`\u5904\u7406\u6A21\u677F\u53D8\u91CF\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}findFilesByPattern(e,t){try{if(!t.includes("*")){let n=k.join(e,t);return f.exists(n)?[n]:[]}let r=f.listDirectory(e,{recursive:!0}),o=new RegExp(t.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*"));return r.filter(n=>{let i=k.relative(e,n).split(k.sep).join("/");return o.test(i)})}catch{return[]}}async replaceVariablesInFile(e,t){try{let r=f.readFile(e),o=!1;for(let[n,i]of Object.entries(t)){let a=new RegExp(`{{\\s*${n}\\s*}}`,"g");a.test(r)&&(r=r.replace(a,i),o=!0)}o&&f.writeFile(e,r,{overwrite:!0})}catch(r){console.warn(`\u66FF\u6362\u6587\u4EF6\u53D8\u91CF\u5931\u8D25 ${e}: ${r instanceof Error?r.message:String(r)}`)}}}});var O,B=E(()=>{O=class{constructor(e){this.container=e}static{c(this,"BaseCommandHandler")}options;subcommands;getService(e){return this.container.get(e)}handleError(e){this.getService("errorHandler").handle(e)}validateArgs(e,t){if(e.length<t)throw new Error(`\u547D\u4EE4\u9700\u8981\u81F3\u5C11 ${t} \u4E2A\u53C2\u6570\uFF0C\u4F46\u53EA\u63D0\u4F9B\u4E86 ${e.length} \u4E2A`)}}});var Le={};j(Le,{ServiceCommandHandler:()=>he});import mt from"consola";var he,He=E(()=>{B();he=class extends O{static{c(this,"ServiceCommandHandler")}name="service";description="\u670D\u52A1\u7BA1\u7406\u547D\u4EE4";subcommands=[{name:"start",description:"\u542F\u52A8\u670D\u52A1",options:[{flags:"-d, --daemon",description:"\u5728\u540E\u53F0\u8FD0\u884C\u670D\u52A1"},{flags:"--debug",description:"\u542F\u7528\u8C03\u8BD5\u6A21\u5F0F (\u8F93\u51FADEBUG\u7EA7\u522B\u65E5\u5FD7)"},{flags:"--stdio",description:"\u4EE5 stdio \u6A21\u5F0F\u8FD0\u884C MCP Server (\u7528\u4E8E Cursor \u7B49\u5BA2\u6237\u7AEF)"}],execute:c(async(e,t)=>{await this.handleStart(t)},"execute")},{name:"stop",description:"\u505C\u6B62\u670D\u52A1",execute:c(async(e,t)=>{await this.handleStop()},"execute")},{name:"status",description:"\u68C0\u67E5\u670D\u52A1\u72B6\u6001",execute:c(async(e,t)=>{await this.handleStatus()},"execute")},{name:"restart",description:"\u91CD\u542F\u670D\u52A1",options:[{flags:"-d, --daemon",description:"\u5728\u540E\u53F0\u8FD0\u884C\u670D\u52A1"}],execute:c(async(e,t)=>{await this.handleRestart(t)},"execute")},{name:"attach",description:"\u8FDE\u63A5\u5230\u540E\u53F0\u670D\u52A1\u67E5\u770B\u65E5\u5FD7",execute:c(async(e,t)=>{await this.handleAttach()},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("\u670D\u52A1\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleStart(e){try{e.debug&&(mt.level="debug");let t=this.getService("serviceManager");if(e.stdio){this.showStdioMigrationGuide();return}await t.start({daemon:e.daemon||!1})}catch(t){this.handleError(t)}}async handleStop(){try{await this.getService("serviceManager").stop()}catch(e){this.handleError(e)}}async handleStatus(){try{let t=await this.getService("serviceManager").getStatus();t.running?(console.log(`\u2705 \u670D\u52A1\u6B63\u5728\u8FD0\u884C (PID: ${t.pid})`),t.uptime&&console.log(`\u23F1\uFE0F \u8FD0\u884C\u65F6\u95F4: ${t.uptime}`),t.mode&&console.log(`\u{1F527} \u8FD0\u884C\u6A21\u5F0F: ${t.mode}`)):console.log("\u274C \u670D\u52A1\u672A\u8FD0\u884C")}catch(e){this.handleError(e)}}async handleRestart(e){try{await this.getService("serviceManager").restart({daemon:e.daemon||!1})}catch(t){this.handleError(t)}}async handleAttach(){try{await this.getService("daemonManager").attachToLogs()}catch(e){this.handleError(e)}}showStdioMigrationGuide(){console.log(`
|
|
9
|
+
`)}catch(r){_.warn(`\u8BBE\u7F6E\u65E5\u5FD7\u91CD\u5B9A\u5411\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}setupEventHandlers(e){e.on("exit",(t,r)=>{t!==0&&t!==null?_.error(`\u5B88\u62A4\u8FDB\u7A0B\u5F02\u5E38\u9000\u51FA (\u4EE3\u7801: ${t}, \u4FE1\u53F7: ${r})`):_.info("\u5B88\u62A4\u8FDB\u7A0B\u6B63\u5E38\u9000\u51FA"),this.processManager.cleanupPidFile(),this.currentDaemon=null}),e.on("error",t=>{_.error(`\u5B88\u62A4\u8FDB\u7A0B\u9519\u8BEF: ${t.message}`),this.processManager.cleanupPidFile(),this.currentDaemon=null}),e.on("disconnect",()=>{_.info("\u5B88\u62A4\u8FDB\u7A0B\u65AD\u5F00\u8FDE\u63A5")})}async checkHealth(){try{let e=this.getDaemonStatus();if(!e.running||!e.pid)return!1;let t=this.processManager.getProcessInfo(e.pid);return t.exists&&t.isXiaozhi}catch{return!1}}getCurrentDaemon(){return this.currentDaemon}cleanup(){if(this.currentDaemon){try{this.currentDaemon.kill("SIGTERM")}catch(e){_.warn(`\u6E05\u7406\u5B88\u62A4\u8FDB\u7A0B\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}this.currentDaemon=null}}}});var De={};F(De,{ServiceManagerImpl:()=>pe});var pe,Ne=E(()=>{"use strict";L();W();ee();pe=class{constructor(e,t){this.processManager=e;this.configManager=t}static{c(this,"ServiceManagerImpl")}async start(e){try{this.validateStartOptions(e),this.processManager.cleanupContainerState();let t=this.getStatus();if(t.running){console.log(`\u68C0\u6D4B\u5230\u670D\u52A1\u5DF2\u5728\u8FD0\u884C (PID: ${t.pid})\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u542F...`);try{await this.processManager.gracefulKillProcess(t.pid||0),this.processManager.cleanupPidFile(),await new Promise(r=>setTimeout(r,1e3)),console.log("\u73B0\u6709\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u6B63\u5728\u542F\u52A8\u65B0\u670D\u52A1...")}catch(r){console.warn(`\u505C\u6B62\u73B0\u6709\u670D\u52A1\u65F6\u51FA\u73B0\u8B66\u544A: ${r instanceof Error?r.message:String(r)}`)}}switch(this.checkEnvironment(),e.mode){case"mcp-server":await this.startMcpServerMode(e);break;case"stdio":await this.startNormalMode(e);break;case"normal":await this.startNormalMode(e);break;default:await this.startNormalMode(e);break}}catch(t){throw t instanceof y?t:y.startFailed(t instanceof Error?t.message:String(t))}}async stop(){try{let e=this.getStatus();if(!e.running)throw y.notRunning();await this.processManager.gracefulKillProcess(e.pid||0),this.processManager.cleanupPidFile()}catch(e){throw e instanceof y?e:new y(`\u505C\u6B62\u670D\u52A1\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}async restart(e){try{this.getStatus().running&&(await this.stop(),await new Promise(r=>setTimeout(r,1e3))),await this.start(e)}catch(t){throw new y(`\u91CD\u542F\u670D\u52A1\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`)}}getStatus(){return this.processManager.getServiceStatus()}validateStartOptions(e){if(e.port!==void 0&&M.validatePort(e.port),e.mode&&!["normal","mcp-server","stdio"].includes(e.mode))throw new y(`\u65E0\u6548\u7684\u8FD0\u884C\u6A21\u5F0F: ${e.mode}`)}checkEnvironment(){if(!this.configManager.configExists())throw z.configNotFound();try{if(!this.configManager.getConfig())throw new z("\u914D\u7F6E\u6587\u4EF6\u65E0\u6548")}catch(e){throw e instanceof z?e:new z(`\u914D\u7F6E\u6587\u4EF6\u9519\u8BEF: ${e instanceof Error?e.message:String(e)}`)}}async startNormalMode(e){e.daemon?await this.startWebServerInDaemon():await this.startWebServerInForeground()}async startMcpServerMode(e){let t=e.port||3e3,{spawn:r}=await import("child_process");if(e.daemon){let o=w.getExecutablePath("cli"),n=r("node",[o,"start","--server",t.toString()],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:w.getConfigDir(),XIAOZHI_DAEMON:"true",MCP_SERVER_MODE:"true"}});this.processManager.savePidInfo(n.pid||0,"daemon"),n.unref(),console.log(`\u2705 MCP Server \u5DF2\u5728\u540E\u53F0\u542F\u52A8 (PID: ${n.pid}, Port: ${t})`),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi status' \u67E5\u770B\u72B6\u6001"),process.exit(0)}else{let{WebServer:o}=await import("../backend/WebServer.js"),n=new o(t),i=c(async()=>{await n.stop(),process.exit(0)},"cleanup");process.on("SIGINT",i),process.on("SIGTERM",i),await n.start()}}async startWebServerInDaemon(){let{spawn:e}=await import("child_process"),t=w.getWebServerLauncherPath();if(!(await import("fs")).default.existsSync(t))throw new y(`WebServer \u6587\u4EF6\u4E0D\u5B58\u5728: ${t}`);let n=e("node",[t],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,XIAOZHI_CONFIG_DIR:w.getConfigDir(),XIAOZHI_DAEMON:"true"}});this.processManager.savePidInfo(n.pid||0,"daemon"),n.unref(),console.log(`\u2705 \u540E\u53F0\u670D\u52A1\u5DF2\u542F\u52A8 (PID: ${n.pid})`),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi status' \u67E5\u770B\u72B6\u6001"),console.log("\u{1F4A1} \u4F7F\u7528 'xiaozhi attach' \u67E5\u770B\u65E5\u5FD7"),process.exit(0)}async startWebServerInForeground(){let{WebServer:e}=await import("../backend/WebServer.js"),t=new e,r=c(async()=>{await t.stop(),this.processManager.cleanupPidFile(),process.exit(0)},"cleanup");process.on("SIGINT",r),process.on("SIGTERM",r),this.processManager.savePidInfo(process.pid,"foreground"),await t.start()}}});var Fe={};F(Fe,{TemplateManagerImpl:()=>fe});import it from"fs";import H from"path";var fe,Ae=E(()=>{"use strict";L();K();W();ee();fe=class{static{c(this,"TemplateManagerImpl")}templateCache=new Map;async getAvailableTemplates(){try{let e=w.findTemplatesDir();if(!e)return[];let t=[],r=it.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of r)try{let n=await this.getTemplateInfo(o);n&&t.push(n)}catch{console.warn(`\u8DF3\u8FC7\u65E0\u6548\u6A21\u677F: ${o}`)}return t}catch{throw new m("\u65E0\u6CD5\u8BFB\u53D6\u6A21\u677F\u76EE\u5F55",w.findTemplatesDir()||"")}}async getTemplateInfo(e){try{if(M.validateTemplateName(e),this.templateCache.has(e))return this.templateCache.get(e);let t=w.getTemplatePath(e);if(!t)return null;let r=H.join(t,"template.json"),o={};if(f.exists(r))try{let a=f.readFile(r);o=JSON.parse(a)}catch{console.warn(`\u6A21\u677F\u914D\u7F6E\u6587\u4EF6\u89E3\u6790\u5931\u8D25: ${e}`)}let n=this.getTemplateFiles(t),i={name:e,path:t,description:o.description||`${e} \u6A21\u677F`,version:o.version||"1.0.0",author:o.author,files:n};return this.templateCache.set(e,i),i}catch(t){throw t instanceof p?t:new m(`\u65E0\u6CD5\u83B7\u53D6\u6A21\u677F\u4FE1\u606F: ${e}`,"")}}async copyTemplate(e,t){await this.createProject({templateName:e,targetPath:t,projectName:H.basename(t)})}async createProject(e){try{this.validateCreateOptions(e);let t=e.templateName||"default",r=await this.getTemplateInfo(t);if(!r)throw new m(`\u6A21\u677F\u4E0D\u5B58\u5728: ${t}`,"");let o=H.resolve(e.targetPath);if(f.exists(o))throw m.alreadyExists(o);f.ensureDir(o),await this.copyTemplateFiles(r,o,e),await this.processTemplateVariables(o,e),console.log(`\u2705 \u9879\u76EE\u521B\u5EFA\u6210\u529F: ${o}`)}catch(t){throw t instanceof m||t instanceof p?t:new m(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,e.targetPath)}}async validateTemplate(e){try{let t=await this.getTemplateInfo(e);if(!t)return!1;let r=["package.json"];for(let o of r){let n=H.join(t.path,o);if(!f.exists(n))return console.warn(`\u6A21\u677F\u7F3A\u5C11\u5FC5\u8981\u6587\u4EF6: ${o}`),!1}return!0}catch{return!1}}clearCache(){this.templateCache.clear()}getTemplateFiles(e){try{return f.listDirectory(e,{recursive:!0,includeHidden:!1}).filter(r=>{let o=H.relative(e,r);return!o.startsWith(".")&&o!=="template.json"&&!o.includes("node_modules")})}catch{return[]}}validateCreateOptions(e){M.validateRequired(e.targetPath,"targetPath"),M.validateRequired(e.projectName,"projectName"),M.validateProjectName(e.projectName),e.templateName&&M.validateTemplateName(e.templateName)}async copyTemplateFiles(e,t,r){try{f.copyDirectory(e.path,t,{exclude:["template.json",".git","node_modules"],overwrite:!1,recursive:!0})}catch(o){throw new m(`\u590D\u5236\u6A21\u677F\u6587\u4EF6\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`,e.path)}}async processTemplateVariables(e,t){try{let r={PROJECT_NAME:t.projectName,PROJECT_NAME_LOWER:t.projectName.toLowerCase(),PROJECT_NAME_UPPER:t.projectName.toUpperCase(),...t.variables},o=["package.json","README.md","src/**/*.ts","src/**/*.js","src/**/*.json"];for(let n of o){let i=this.findFilesByPattern(e,n);for(let a of i)await this.replaceVariablesInFile(a,r)}}catch(r){console.warn(`\u5904\u7406\u6A21\u677F\u53D8\u91CF\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`)}}findFilesByPattern(e,t){try{if(!t.includes("*")){let n=H.join(e,t);return f.exists(n)?[n]:[]}let r=f.listDirectory(e,{recursive:!0}),o=new RegExp(t.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*"));return r.filter(n=>{let i=H.relative(e,n).split(H.sep).join("/");return o.test(i)})}catch{return[]}}async replaceVariablesInFile(e,t){try{let r=f.readFile(e),o=!1;for(let[n,i]of Object.entries(t)){let a=new RegExp(`{{\\s*${n}\\s*}}`,"g");a.test(r)&&(r=r.replace(a,i),o=!0)}o&&f.writeFile(e,r,{overwrite:!0})}catch(r){console.warn(`\u66FF\u6362\u6587\u4EF6\u53D8\u91CF\u5931\u8D25 ${e}: ${r instanceof Error?r.message:String(r)}`)}}}});var O,G=E(()=>{"use strict";O=class{constructor(e){this.container=e}static{c(this,"BaseCommandHandler")}options;subcommands;getService(e){return this.container.get(e)}handleError(e){this.getService("errorHandler").handle(e)}validateArgs(e,t){if(e.length<t)throw new Error(`\u547D\u4EE4\u9700\u8981\u81F3\u5C11 ${t} \u4E2A\u53C2\u6570\uFF0C\u4F46\u53EA\u63D0\u4F9B\u4E86 ${e.length} \u4E2A`)}}});var je={};F(je,{ServiceCommandHandler:()=>he});import ct from"consola";var he,Le=E(()=>{"use strict";G();he=class extends O{static{c(this,"ServiceCommandHandler")}name="service";description="\u670D\u52A1\u7BA1\u7406\u547D\u4EE4";subcommands=[{name:"start",description:"\u542F\u52A8\u670D\u52A1",options:[{flags:"-d, --daemon",description:"\u5728\u540E\u53F0\u8FD0\u884C\u670D\u52A1"},{flags:"--debug",description:"\u542F\u7528\u8C03\u8BD5\u6A21\u5F0F (\u8F93\u51FADEBUG\u7EA7\u522B\u65E5\u5FD7)"},{flags:"--stdio",description:"\u4EE5 stdio \u6A21\u5F0F\u8FD0\u884C MCP Server (\u7528\u4E8E Cursor \u7B49\u5BA2\u6237\u7AEF)"}],execute:c(async(e,t)=>{await this.handleStart(t)},"execute")},{name:"stop",description:"\u505C\u6B62\u670D\u52A1",execute:c(async(e,t)=>{await this.handleStop()},"execute")},{name:"status",description:"\u68C0\u67E5\u670D\u52A1\u72B6\u6001",execute:c(async(e,t)=>{await this.handleStatus()},"execute")},{name:"restart",description:"\u91CD\u542F\u670D\u52A1",options:[{flags:"-d, --daemon",description:"\u5728\u540E\u53F0\u8FD0\u884C\u670D\u52A1"}],execute:c(async(e,t)=>{await this.handleRestart(t)},"execute")},{name:"attach",description:"\u8FDE\u63A5\u5230\u540E\u53F0\u670D\u52A1\u67E5\u770B\u65E5\u5FD7",execute:c(async(e,t)=>{await this.handleAttach()},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("\u670D\u52A1\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleStart(e){try{e.debug&&(ct.level=5);let t=this.getService("serviceManager");if(e.stdio){this.showStdioMigrationGuide();return}await t.start({daemon:e.daemon||!1})}catch(t){this.handleError(t)}}async handleStop(){try{await this.getService("serviceManager").stop()}catch(e){this.handleError(e)}}async handleStatus(){try{let t=await this.getService("serviceManager").getStatus();t.running?(console.log(`\u2705 \u670D\u52A1\u6B63\u5728\u8FD0\u884C (PID: ${t.pid})`),t.uptime&&console.log(`\u23F1\uFE0F \u8FD0\u884C\u65F6\u95F4: ${t.uptime}`),t.mode&&console.log(`\u{1F527} \u8FD0\u884C\u6A21\u5F0F: ${t.mode}`)):console.log("\u274C \u670D\u52A1\u672A\u8FD0\u884C")}catch(e){this.handleError(e)}}async handleRestart(e){try{await this.getService("serviceManager").restart({daemon:e.daemon||!1})}catch(t){this.handleError(t)}}async handleAttach(){try{await this.getService("daemonManager").attachToLogs()}catch(e){this.handleError(e)}}showStdioMigrationGuide(){console.log(`
|
|
10
10
|
\u274C stdio \u6A21\u5F0F\u5DF2\u5E9F\u5F03
|
|
11
11
|
`),console.log(`\u5C0F\u667A\u5BA2\u6237\u7AEF\u5DF2\u8FC1\u79FB\u5230\u7EAF HTTP \u67B6\u6784\uFF0C\u8BF7\u4F7F\u7528\u4EE5\u4E0B\u65B9\u5F0F\uFF1A
|
|
12
12
|
`),console.log("1. \u542F\u52A8 Web \u670D\u52A1\uFF1A"),console.log(` xiaozhi start
|
|
13
13
|
`),console.log("2. \u5728 Cursor \u4E2D\u914D\u7F6E HTTP \u7AEF\u70B9\uFF1A"),console.log(' "mcpServers": {'),console.log(' "xiaozhi-client": {'),console.log(' "type": "streamableHttp",'),console.log(' "url": "http://localhost:9999/mcp"'),console.log(" }"),console.log(` }
|
|
14
|
-
`)}}});var ze={};j(ze,{ConfigCommandHandler:()=>ye});import gt from"path";import h from"chalk";import ve from"ora";var ye,ke=E(()=>{B();ye=class extends O{static{c(this,"ConfigCommandHandler")}name="config";description="\u914D\u7F6E\u7BA1\u7406\u547D\u4EE4";subcommands=[{name:"init",description:"\u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6",options:[{flags:"-f, --format <format>",description:"\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F (json, json5, jsonc)",defaultValue:"json"}],execute:c(async(e,t)=>{await this.handleInit(t)},"execute")},{name:"get",description:"\u67E5\u770B\u914D\u7F6E\u503C",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleGet(e[0])},"execute")},{name:"set",description:"\u8BBE\u7F6E\u914D\u7F6E\u503C",execute:c(async(e,t)=>{this.validateArgs(e,2),await this.handleSet(e[0],e[1])},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("\u914D\u7F6E\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleInit(e){let t=ve("\u521D\u59CB\u5316\u914D\u7F6E...").start();try{let r=e.format;if(r!=="json"&&r!=="json5"&&r!=="jsonc")throw new Error("\u683C\u5F0F\u5FC5\u987B\u662F json, json5 \u6216 jsonc");let o=this.getService("configManager");if(o.configExists()){t.warn("\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728"),console.log(h.yellow("\u5982\u9700\u91CD\u65B0\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u5220\u9664\u73B0\u6709\u7684\u914D\u7F6E\u6587\u4EF6"));return}o.initConfig(r),t.succeed("\u914D\u7F6E\u6587\u4EF6\u521D\u59CB\u5316\u6210\u529F");let n=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),i=`xiaozhi.config.${r}`,a=gt.join(n,i);console.log(h.green(`\u2705 \u914D\u7F6E\u6587\u4EF6\u5DF2\u521B\u5EFA: ${i}`)),console.log(h.yellow("\u{1F4DD} \u8BF7\u7F16\u8F91\u914D\u7F6E\u6587\u4EF6\u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9:")),console.log(h.gray(` \u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84: ${a}`)),console.log(h.yellow("\u{1F4A1} \u6216\u8005\u4F7F\u7528\u547D\u4EE4\u8BBE\u7F6E:")),console.log(h.gray(" xiaozhi config set mcpEndpoint <your-endpoint-url>"))}catch(r){t.fail(`\u521D\u59CB\u5316\u914D\u7F6E\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleGet(e){let t=ve("\u8BFB\u53D6\u914D\u7F6E...").start();try{let r=this.getService("configManager");if(!r.configExists()){t.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log(h.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}let o=r.getConfig();switch(e){case"mcpEndpoint":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let n=r.getMcpEndpoints();n.length===0?console.log(h.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):n.length===1?console.log(h.green(`MCP \u7AEF\u70B9: ${n[0]}`)):(console.log(h.green(`MCP \u7AEF\u70B9 (${n.length} \u4E2A):`)),n.forEach((i,a)=>{console.log(h.gray(` ${a+1}. ${i}`))}));break}case"mcpServers":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(h.green("MCP \u670D\u52A1:"));for(let[n,i]of Object.entries(o.mcpServers)){let a=i;"type"in a&&a.type==="sse"?console.log(h.gray(` ${n}: [SSE] ${a.url}`)):console.log(h.gray(` ${n}: ${a.command} ${a.args.join(" ")}`))}break;case"connection":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let n=r.getConnectionConfig();console.log(h.green("\u8FDE\u63A5\u914D\u7F6E:")),console.log(h.gray(` \u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${n.heartbeatInterval}ms`)),console.log(h.gray(` \u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${n.heartbeatTimeout}ms`)),console.log(h.gray(` \u91CD\u8FDE\u95F4\u9694: ${n.reconnectInterval}ms`));break}case"heartbeatInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(h.green(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${r.getHeartbeatInterval()}ms`));break;case"heartbeatTimeout":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(h.green(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${r.getHeartbeatTimeout()}ms`));break;case"reconnectInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(h.green(`\u91CD\u8FDE\u95F4\u9694: ${r.getReconnectInterval()}ms`));break;default:t.fail(`\u672A\u77E5\u7684\u914D\u7F6E\u9879: ${e}`),console.log(h.yellow("\u652F\u6301\u7684\u914D\u7F6E\u9879: mcpEndpoint, mcpServers, connection, heartbeatInterval, heartbeatTimeout, reconnectInterval"))}}catch(r){t.fail(`\u8BFB\u53D6\u914D\u7F6E\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleSet(e,t){let r=ve("\u66F4\u65B0\u914D\u7F6E...").start();try{let o=this.getService("configManager");if(!o.configExists()){r.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log(h.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}switch(e){case"mcpEndpoint":o.updateMcpEndpoint(t),r.succeed(`MCP \u7AEF\u70B9\u5DF2\u8BBE\u7F6E\u4E3A: ${t}`);break;case"heartbeatInterval":{let n=Number.parseInt(t);if(Number.isNaN(n)||n<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u662F\u6B63\u6574\u6570");o.updateHeartbeatInterval(n),r.succeed(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5DF2\u8BBE\u7F6E\u4E3A: ${n}ms`);break}case"heartbeatTimeout":{let n=Number.parseInt(t);if(Number.isNaN(n)||n<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u662F\u6B63\u6574\u6570");o.updateHeartbeatTimeout(n),r.succeed(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5DF2\u8BBE\u7F6E\u4E3A: ${n}ms`);break}case"reconnectInterval":{let n=Number.parseInt(t);if(Number.isNaN(n)||n<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u662F\u6B63\u6574\u6570");o.updateReconnectInterval(n),r.succeed(`\u91CD\u8FDE\u95F4\u9694\u5DF2\u8BBE\u7F6E\u4E3A: ${n}ms`);break}default:r.fail(`\u4E0D\u652F\u6301\u8BBE\u7F6E\u7684\u914D\u7F6E\u9879: ${e}`),console.log(h.yellow("\u652F\u6301\u8BBE\u7F6E\u7684\u914D\u7F6E\u9879: mcpEndpoint, heartbeatInterval, heartbeatTimeout, reconnectInterval"))}}catch(o){r.fail(`\u8BBE\u7F6E\u914D\u7F6E\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`),this.handleError(o)}}}});var _e={};j(_e,{ProjectCommandHandler:()=>we});import dt from"path";import S from"chalk";import pt from"ora";var we,Ve=E(()=>{B();we=class extends O{static{c(this,"ProjectCommandHandler")}name="create";description="\u521B\u5EFA\u9879\u76EE";options=[{flags:"-t, --template <templateName>",description:"\u4F7F\u7528\u6307\u5B9A\u6A21\u677F\u521B\u5EFA\u9879\u76EE"}];constructor(e){super(e)}async execute(e,t){this.validateArgs(e,1);let r=e[0];await this.handleCreate(r,t)}async handleCreate(e,t){let r=pt("\u521D\u59CB\u5316\u9879\u76EE...").start();try{let o=this.getService("templateManager"),n=this.getService("fileUtils"),i=dt.join(process.cwd(),e);if(await n.exists(i)){r.fail(`\u76EE\u5F55 "${e}" \u5DF2\u5B58\u5728`),console.log(S.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u9009\u62E9\u4E0D\u540C\u7684\u9879\u76EE\u540D\u79F0\u6216\u5220\u9664\u73B0\u6709\u76EE\u5F55"));return}t.template?await this.createFromTemplate(e,t.template,i,r,o):await this.createBasicProject(e,i,r,o)}catch(o){r.fail(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`),this.handleError(o)}}async createFromTemplate(e,t,r,o,n){o.text="\u68C0\u67E5\u6A21\u677F...";let i=await n.getAvailableTemplates();if(i.length===0){o.fail("\u627E\u4E0D\u5230\u53EF\u7528\u6A21\u677F"),console.log(S.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u786E\u4FDD xiaozhi-client \u6B63\u786E\u5B89\u88C5"));return}let a=t;if(!await n.validateTemplate(a)){o.fail(`\u6A21\u677F "${a}" \u4E0D\u5B58\u5728`);let v=this.findSimilarTemplate(a,i);if(v)if(console.log(S.yellow(`\u{1F4A1} \u4F60\u662F\u60F3\u4F7F\u7528\u6A21\u677F "${v}" \u5417\uFF1F`)),await this.askUserConfirmation(S.cyan("\u786E\u8BA4\u4F7F\u7528\u6B64\u6A21\u677F\uFF1F(y/n): ")))a=v;else{this.showAvailableTemplates(i);return}else{this.showAvailableTemplates(i);return}}o.text=`\u4ECE\u6A21\u677F "${a}" \u521B\u5EFA\u9879\u76EE "${e}"...`,await n.createProject({templateName:a,targetPath:r,projectName:e}),o.succeed(`\u9879\u76EE "${e}" \u521B\u5EFA\u6210\u529F`),console.log(S.green("\u2705 \u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(S.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(S.gray(` cd ${e}`)),console.log(S.gray(" pnpm install # \u5B89\u88C5\u4F9D\u8D56")),console.log(S.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9")),console.log(S.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1"))}async createBasicProject(e,t,r,o){r.text=`\u521B\u5EFA\u57FA\u672C\u9879\u76EE "${e}"...`,await o.createProject({templateName:null,targetPath:t,projectName:e}),r.succeed(`\u9879\u76EE "${e}" \u521B\u5EFA\u6210\u529F`),console.log(S.green("\u2705 \u57FA\u672C\u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(S.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(S.gray(` cd ${e}`)),console.log(S.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9\u548C\u670D\u52A1")),console.log(S.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1")),console.log(S.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 --template \u9009\u9879\u53EF\u4EE5\u4ECE\u6A21\u677F\u521B\u5EFA\u9879\u76EE"))}showAvailableTemplates(e){console.log(S.yellow("\u53EF\u7528\u7684\u6A21\u677F:"));for(let t of e)console.log(S.gray(` - ${t}`))}findSimilarTemplate(e,t){let r=this.getService("formatUtils"),o=null,n=0;for(let i of t){let a=r.calculateSimilarity(e.toLowerCase(),i.toLowerCase());a>n&&a>.6&&(n=a,o=i)}return o}async askUserConfirmation(e){let r=(await import("readline")).createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{r.question(e,n=>{r.close(),o(n.toLowerCase().trim()==="y"||n.toLowerCase().trim()==="yes")})})}}});function Ue(s){let e=s;return typeof e=="object"&&e!==null&&"command"in e&&"args"in e&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")}var We=E(()=>{c(Ue,"isLocalMCPServerConfig")});var Be={};j(Be,{McpCommandHandler:()=>Se});import{configManager as F}from"@xiaozhi-client/config";import l from"chalk";import Ge from"cli-table3";import ft from"consola";import Ee from"ora";var Se,Xe=E(()=>{B();We();de();Se=class s extends O{static{c(this,"McpCommandHandler")}processManager;baseUrl;constructor(...e){super(...e),this.processManager=new Z;try{let t=F.getWebUIPort()??9999;this.baseUrl=`http://localhost:${t}`}catch{this.baseUrl="http://localhost:9999"}}static CHINESE_CHAR_REGEX=/[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef]/;static getDisplayWidth(e){let t=0;for(let r of e)s.CHINESE_CHAR_REGEX.test(r)?t+=2:t+=1;return t}static truncateToWidth(e,t){if(s.getDisplayWidth(e)<=t)return e;if(t<=3)return"";let r="",o=0,n=!1;for(let i of e){let a=s.CHINESE_CHAR_REGEX.test(i)?2:1;if(o+a>t-3){if(!n)return"";r+="...";break}r+=i,o+=a,n=!0}return r}static parseJsonArgs(e){try{return JSON.parse(e)}catch(t){throw new Error(`\u53C2\u6570\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u4F7F\u7528\u6709\u6548\u7684 JSON \u683C\u5F0F\u3002\u9519\u8BEF\u8BE6\u60C5: ${t instanceof Error?t.message:String(t)}`)}}static formatToolCallResult(e){return JSON.stringify(e)}name="mcp";description="MCP \u670D\u52A1\u548C\u5DE5\u5177\u7BA1\u7406";subcommands=[{name:"list",description:"\u5217\u51FA MCP \u670D\u52A1",options:[{flags:"--tools",description:"\u663E\u793A\u6240\u6709\u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868"}],execute:c(async(e,t)=>{await this.handleList(t)},"execute")},{name:"server",description:"\u7BA1\u7406\u6307\u5B9A\u7684 MCP \u670D\u52A1",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleServer(e[0])},"execute")},{name:"tool",description:"\u542F\u7528\u6216\u7981\u7528\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177",execute:c(async(e,t)=>{this.validateArgs(e,3);let[r,o,n]=e;n!=="enable"&&n!=="disable"&&(console.error(l.red("\u9519\u8BEF: \u64CD\u4F5C\u5FC5\u987B\u662F 'enable' \u6216 'disable'")),process.exit(1));let i=n==="enable";await this.handleTool(r,o,i)},"execute")},{name:"call",description:"\u8C03\u7528\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177",options:[{flags:"--args <json>",description:"\u5DE5\u5177\u53C2\u6570 (JSON \u683C\u5F0F)",defaultValue:"{}"}],execute:c(async(e,t)=>{this.validateArgs(e,2);let[r,o]=e;await this.handleCall(r,o,t.args??"{}")},"execute")}];async execute(e,t){console.log("MCP \u670D\u52A1\u548C\u5DE5\u5177\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleList(e){try{await this.handleListInternal(e)}catch(t){this.handleError(t)}}async handleServer(e){try{await this.handleServerInternal(e)}catch(t){this.handleError(t)}}async handleTool(e,t,r){try{await this.handleToolInternal(e,t,r)}catch(o){this.handleError(o)}}async validateServiceStatus(){if(!this.processManager.getServiceStatus().running)throw new Error("xiaozhi \u670D\u52A1\u672A\u542F\u52A8\u3002\u8BF7\u5148\u8FD0\u884C 'xiaozhi start' \u6216 'xiaozhi start -d' \u542F\u52A8\u670D\u52A1\u3002");try{let t=await fetch(`${this.baseUrl}/api/status`,{method:"GET",signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Web \u670D\u52A1\u5668\u54CD\u5E94\u9519\u8BEF: ${t.status}`)}catch(t){if(t instanceof Error&&t.name==="AbortError")throw new Error("\u8FDE\u63A5 xiaozhi \u670D\u52A1\u8D85\u65F6\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u662F\u5426\u6B63\u5E38\u8FD0\u884C\u3002");if(t instanceof Error)throw t instanceof TypeError&&/fetch|network|failed/i.test(t.message)?new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230 xiaozhi \u670D\u52A1\uFF08\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF09\u3002\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u6216\u670D\u52A1\u5730\u5740\u662F\u5426\u6B63\u786E\u3002\u539F\u59CB\u9519\u8BEF: ${t.message}`):new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230 xiaozhi \u670D\u52A1\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002\u539F\u59CB\u9519\u8BEF: ${t.message}`);let r;try{r=JSON.stringify(t)}catch{r=String(t)}throw new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230 xiaozhi \u670D\u52A1\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002\u9519\u8BEF\u8BE6\u60C5: ${r}`)}}async callToolInternal(e,t,r){await this.validateServiceStatus();try{let o=await fetch(`${this.baseUrl}/api/tools/call`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceName:e,toolName:t,args:r})});if(!o.ok){let i=`HTTP ${o.status}: ${o.statusText}`;try{let a=await o.json(),g=a?.error?.message??a?.message;typeof g=="string"&&g.trim()&&(i=g)}catch{}throw new Error(i)}let n=await o.json();if(!n.success)throw new Error(n.error?.message||"\u5DE5\u5177\u8C03\u7528\u5931\u8D25");return n.data}catch(o){throw ft.error(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e}/${t}`,o instanceof Error?o.message:String(o)),o}}async handleCall(e,t,r){try{let o=s.parseJsonArgs(r),n=await this.callToolInternal(e,t,o);console.log(s.formatToolCallResult(n))}catch(o){console.log(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e}/${t}`),console.error(l.red("\u9519\u8BEF:"),o.message);let n=o.message;if(n.includes("\u670D\u52A1\u672A\u542F\u52A8")?(console.log(),console.log(l.yellow("\u{1F4A1} \u8BF7\u5148\u542F\u52A8\u670D\u52A1:")),console.log(l.gray(" xiaozhi start # \u524D\u53F0\u542F\u52A8")),console.log(l.gray(" xiaozhi start -d # \u540E\u53F0\u542F\u52A8"))):n.includes("\u53C2\u6570\u683C\u5F0F\u9519\u8BEF")&&(console.log(),console.log(l.yellow("\u{1F4A1} \u6B63\u786E\u683C\u5F0F\u793A\u4F8B:")),console.log(l.gray(` xiaozhi mcp call ${e} ${t} --args '{"param": "value"}'`))),process.env.NODE_ENV==="test")throw new Error("process.exit called");process.exit(1)}}async handleListInternal(e={}){let t=Ee("\u83B7\u53D6 MCP \u670D\u52A1\u5217\u8868...").start();try{let r=F.getMcpServers(),o=Object.keys(r),n=F.getCustomMCPTools(),i=n.length>0,a=o.length+(i?1:0);if(a===0){t.warn("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u670D\u52A1\u6216 customMCP \u5DE5\u5177"),console.log(l.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi config' \u547D\u4EE4\u914D\u7F6E MCP \u670D\u52A1\u6216\u5728 xiaozhi.config.json \u4E2D\u914D\u7F6E customMCP \u5DE5\u5177"));return}if(t.succeed(`\u627E\u5230 ${a} \u4E2A MCP \u670D\u52A1${i?" (\u5305\u62EC customMCP)":""}`),e.tools){console.log(),console.log(l.bold("MCP \u670D\u52A1\u5DE5\u5177\u5217\u8868:")),console.log();let g=8,v=[];for(let P of o){let b=F.getServerToolsConfig(P),V=Object.keys(b);v.push(...V)}if(i){let P=n.map(b=>b.name);v.push(...P)}for(let P of v){let b=s.getDisplayWidth(P);b>g&&(g=b)}g=Math.max(10,Math.min(g+2,30));let x=new Ge({head:[l.bold("MCP"),l.bold("\u5DE5\u5177\u540D\u79F0"),l.bold("\u72B6\u6001"),l.bold("\u63CF\u8FF0")],colWidths:[15,g,8,40],wordWrap:!0,style:{head:[],border:[]}});if(i)for(let P of n){let b=s.truncateToWidth(P.description||"",32);x.push(["customMCP",P.name,l.green("\u542F\u7528"),b])}for(let P of o){let b=F.getServerToolsConfig(P),V=Object.keys(b);if(V.length===0)x.push([l.gray(P),l.gray("-"),l.gray("-"),l.gray("\u6682\u672A\u8BC6\u522B\u5230\u76F8\u5173\u5DE5\u5177")]);else{x.length>0&&x.push([{colSpan:4,content:""}]);for(let Re of V){let Ie=b[Re],Ze=Ie.enable?l.green("\u542F\u7528"):l.red("\u7981\u7528"),Qe=s.truncateToWidth(Ie.description||"",32);x.push([P,Re,Ze,Qe])}}}console.log(x.toString())}else{console.log(),console.log(l.bold("MCP \u670D\u52A1\u5217\u8868:")),console.log(),i&&(console.log(`${l.cyan("\u2022")} ${l.bold("customMCP")}`),console.log(` \u7C7B\u578B: ${l.gray("\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177")}`),console.log(` \u914D\u7F6E: ${l.gray("xiaozhi.config.json")}`),console.log(` \u5DE5\u5177: ${l.green(n.length)} \u542F\u7528 / ${l.yellow(n.length)} \u603B\u8BA1`),console.log());for(let g of o){let v=r[g],x=F.getServerToolsConfig(g),P=Object.keys(x).length,b=Object.values(x).filter(V=>V.enable!==!1).length;console.log(`${l.cyan("\u2022")} ${l.bold(g)}`),"url"in v?("type"in v&&v.type==="sse"?console.log(` \u7C7B\u578B: ${l.gray("SSE")}`):console.log(` \u7C7B\u578B: ${l.gray("Streamable HTTP")}`),console.log(` URL: ${l.gray(v.url)}`)):Ue(v)&&console.log(` \u547D\u4EE4: ${l.gray(v.command)} ${l.gray(v.args.join(" "))}`),P>0?console.log(` \u5DE5\u5177: ${l.green(b)} \u542F\u7528 / ${l.yellow(P)} \u603B\u8BA1`):console.log(` \u5DE5\u5177: ${l.gray("\u672A\u626B\u63CF (\u8BF7\u5148\u542F\u52A8\u670D\u52A1)")}`),console.log()}}console.log(l.gray("\u{1F4A1} \u63D0\u793A:")),console.log(l.gray(" - \u4F7F\u7528 'xiaozhi mcp list --tools' \u67E5\u770B\u6240\u6709\u5DE5\u5177")),console.log(l.gray(" - \u4F7F\u7528 'xiaozhi mcp <\u670D\u52A1\u540D> list' \u67E5\u770B\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177")),console.log(l.gray(" - \u4F7F\u7528 'xiaozhi mcp <\u670D\u52A1\u540D> <\u5DE5\u5177\u540D> enable/disable' \u542F\u7528/\u7981\u7528\u5DE5\u5177"))}catch(r){t.fail("\u83B7\u53D6 MCP \u670D\u52A1\u5217\u8868\u5931\u8D25"),console.error(l.red(`\u9519\u8BEF: ${r instanceof Error?r.message:String(r)}`)),process.exit(1)}}async handleServerInternal(e){let t=Ee(`\u83B7\u53D6 ${e} \u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868...`).start();try{if(!F.getMcpServers()[e]){t.fail(`\u670D\u52A1 '${e}' \u4E0D\u5B58\u5728`),console.log(l.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u670D\u52A1"));return}let o=F.getServerToolsConfig(e),n=Object.keys(o);if(n.length===0){t.warn(`\u670D\u52A1 '${e}' \u6682\u65E0\u5DE5\u5177\u4FE1\u606F`),console.log(l.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u542F\u52A8\u670D\u52A1\u4EE5\u626B\u63CF\u5DE5\u5177\u5217\u8868"));return}t.succeed(`\u670D\u52A1 '${e}' \u5171\u6709 ${n.length} \u4E2A\u5DE5\u5177`),console.log(),console.log(l.bold(`${e} \u670D\u52A1\u5DE5\u5177\u5217\u8868:`)),console.log();let i=new Ge({head:[l.bold("\u5DE5\u5177\u540D\u79F0"),l.bold("\u72B6\u6001"),l.bold("\u63CF\u8FF0")],colWidths:[30,8,50],wordWrap:!0,style:{head:[],border:[]}});for(let a of n){let g=o[a],v=g.enable?l.green("\u542F\u7528"):l.red("\u7981\u7528"),x=s.truncateToWidth(g.description||"",40);i.push([a,v,x])}console.log(i.toString()),console.log(),console.log(l.gray("\u{1F4A1} \u63D0\u793A:")),console.log(l.gray(` - \u4F7F\u7528 'xiaozhi mcp ${e} <\u5DE5\u5177\u540D> enable' \u542F\u7528\u5DE5\u5177`)),console.log(l.gray(` - \u4F7F\u7528 'xiaozhi mcp ${e} <\u5DE5\u5177\u540D> disable' \u7981\u7528\u5DE5\u5177`))}catch(r){t.fail("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25"),console.error(l.red(`\u9519\u8BEF: ${r instanceof Error?r.message:String(r)}`)),process.exit(1)}}async handleToolInternal(e,t,r){let o=r?"\u542F\u7528":"\u7981\u7528",n=Ee(`${o}\u5DE5\u5177 ${e}/${t}...`).start();try{if(!F.getMcpServers()[e]){n.fail(`\u670D\u52A1 '${e}' \u4E0D\u5B58\u5728`),console.log(l.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u670D\u52A1"));return}let a=F.getServerToolsConfig(e);if(!a[t]){n.fail(`\u5DE5\u5177 '${t}' \u5728\u670D\u52A1 '${e}' \u4E2D\u4E0D\u5B58\u5728`),console.log(l.yellow(`\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp ${e} list' \u67E5\u770B\u8BE5\u670D\u52A1\u7684\u6240\u6709\u5DE5\u5177`));return}F.setToolEnabled(e,t,r,a[t].description),n.succeed(`\u6210\u529F${o}\u5DE5\u5177 ${l.cyan(e)}/${l.cyan(t)}`),console.log(),console.log(l.gray("\u{1F4A1} \u63D0\u793A: \u5DE5\u5177\u72B6\u6001\u66F4\u6539\u5C06\u5728\u4E0B\u6B21\u542F\u52A8\u670D\u52A1\u65F6\u751F\u6548"))}catch(i){n.fail(`${o}\u5DE5\u5177\u5931\u8D25`),console.error(l.red(`\u9519\u8BEF: ${i instanceof Error?i.message:String(i)}`)),process.exit(1)}}}});var Je={};j(Je,{EndpointCommandHandler:()=>Ce});import X from"chalk";import ie from"ora";var Ce,qe=E(()=>{B();Ce=class extends O{static{c(this,"EndpointCommandHandler")}name="endpoint";description="\u7BA1\u7406 MCP \u7AEF\u70B9";subcommands=[{name:"list",description:"\u5217\u51FA\u6240\u6709 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{await this.handleList()},"execute")},{name:"add",description:"\u6DFB\u52A0\u65B0\u7684 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleAdd(e[0])},"execute")},{name:"remove",description:"\u79FB\u9664\u6307\u5B9A\u7684 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleRemove(e[0])},"execute")},{name:"set",description:"\u8BBE\u7F6E MCP \u7AEF\u70B9\uFF08\u53EF\u4EE5\u662F\u5355\u4E2A\u6216\u591A\u4E2A\uFF09",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleSet(e)},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("MCP \u7AEF\u70B9\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleList(){let e=ie("\u8BFB\u53D6\u7AEF\u70B9\u914D\u7F6E...").start();try{let r=this.getService("configManager").getMcpEndpoints();e.succeed("\u7AEF\u70B9\u5217\u8868"),r.length===0?console.log(X.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):(console.log(X.green(`\u5171 ${r.length} \u4E2A\u7AEF\u70B9:`)),r.forEach((o,n)=>{console.log(X.gray(` ${n+1}. ${o}`))}))}catch(t){e.fail(`\u8BFB\u53D6\u7AEF\u70B9\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),this.handleError(t)}}async handleAdd(e){let t=ie("\u6DFB\u52A0\u7AEF\u70B9...").start();try{let r=this.getService("configManager");r.addMcpEndpoint(e),t.succeed(`\u6210\u529F\u6DFB\u52A0\u7AEF\u70B9: ${e}`);let o=r.getMcpEndpoints();console.log(X.gray(`\u5F53\u524D\u5171 ${o.length} \u4E2A\u7AEF\u70B9`))}catch(r){t.fail(`\u6DFB\u52A0\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleRemove(e){let t=ie("\u79FB\u9664\u7AEF\u70B9...").start();try{let r=this.getService("configManager");r.removeMcpEndpoint(e),t.succeed(`\u6210\u529F\u79FB\u9664\u7AEF\u70B9: ${e}`);let o=r.getMcpEndpoints();console.log(X.gray(`\u5F53\u524D\u5269\u4F59 ${o.length} \u4E2A\u7AEF\u70B9`))}catch(r){t.fail(`\u79FB\u9664\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleSet(e){let t=ie("\u8BBE\u7F6E\u7AEF\u70B9...").start();try{let r=this.getService("configManager");if(e.length===1)r.updateMcpEndpoint(e[0]),t.succeed(`\u6210\u529F\u8BBE\u7F6E\u7AEF\u70B9: ${e[0]}`);else{r.updateMcpEndpoint(e),t.succeed(`\u6210\u529F\u8BBE\u7F6E ${e.length} \u4E2A\u7AEF\u70B9`);for(let[o,n]of e.entries())console.log(X.gray(` ${o+1}. ${n}`))}}catch(r){t.fail(`\u8BBE\u7F6E\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}}});import{Command as ut}from"commander";import{configManager as lt}from"@xiaozhi-client/config";import I from"chalk";q();var ot={[d.CONFIG_ERROR]:'\u8FD0\u884C "xiaozhi --help" \u67E5\u770B\u914D\u7F6E\u76F8\u5173\u547D\u4EE4',[d.SERVICE_ERROR]:'\u8FD0\u884C "xiaozhi status" \u68C0\u67E5\u670D\u52A1\u72B6\u6001',[d.VALIDATION_ERROR]:"\u68C0\u67E5\u8F93\u5165\u53C2\u6570\u662F\u5426\u6B63\u786E",[d.FILE_ERROR]:"\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u548C\u6743\u9650",[d.PROCESS_ERROR]:"\u68C0\u67E5\u8FDB\u7A0B\u72B6\u6001\u548C\u6743\u9650",[d.NETWORK_ERROR]:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C\u9632\u706B\u5899\u8BBE\u7F6E",[d.PERMISSION_ERROR]:"\u5C1D\u8BD5\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"},nt={config_not_found:['\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6',"\u68C0\u67E5\u5F53\u524D\u76EE\u5F55\u662F\u5426\u4E3A\u9879\u76EE\u6839\u76EE\u5F55","\u8BBE\u7F6E XIAOZHI_CONFIG_DIR \u73AF\u5883\u53D8\u91CF\u6307\u5B9A\u914D\u7F6E\u76EE\u5F55"],service_port_occupied:["\u68C0\u67E5\u7AEF\u53E3\u662F\u5426\u88AB\u5176\u4ED6\u7A0B\u5E8F\u5360\u7528",'\u4F7F\u7528 "lsof -i :\u7AEF\u53E3\u53F7" \u67E5\u770B\u7AEF\u53E3\u4F7F\u7528\u60C5\u51B5',"\u66F4\u6539\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u7AEF\u53E3\u8BBE\u7F6E"],permission_denied:["\u68C0\u67E5\u6587\u4EF6\u548C\u76EE\u5F55\u6743\u9650","\u4F7F\u7528 sudo \u6216\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C","\u786E\u4FDD\u5F53\u524D\u7528\u6237\u6709\u8DB3\u591F\u7684\u6743\u9650"],service_start_failed:["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u662F\u5426\u6B63\u786E","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F","\u786E\u4FDD\u6240\u6709\u4F9D\u8D56\u670D\u52A1\u6B63\u5E38\u8FD0\u884C"]},Y=class{static{c(this,"ERROR_MESSAGES")}static getHelpMessage(e){return ot[e]}static getSolutions(e){return nt[e]||[]}static formatError(e,t){return`${t?`[${t}] `:""}${e.message}`}static getFriendlyMessage(e){return{[d.CONFIG_ERROR]:"\u914D\u7F6E\u6587\u4EF6\u76F8\u5173\u9519\u8BEF",[d.SERVICE_ERROR]:"\u670D\u52A1\u8FD0\u884C\u76F8\u5173\u9519\u8BEF",[d.VALIDATION_ERROR]:"\u8F93\u5165\u9A8C\u8BC1\u9519\u8BEF",[d.FILE_ERROR]:"\u6587\u4EF6\u64CD\u4F5C\u9519\u8BEF",[d.PROCESS_ERROR]:"\u8FDB\u7A0B\u7BA1\u7406\u9519\u8BEF",[d.NETWORK_ERROR]:"\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF",[d.PERMISSION_ERROR]:"\u6743\u9650\u4E0D\u8DB3\u9519\u8BEF"}[e]||"\u672A\u77E5\u9519\u8BEF"}static isRecoverable(e){return[d.NETWORK_ERROR,d.FILE_ERROR,d.SERVICE_ERROR].includes(e)}static getSeverity(e){return{[d.VALIDATION_ERROR]:"low",[d.FILE_ERROR]:"medium",[d.CONFIG_ERROR]:"medium",[d.NETWORK_ERROR]:"medium",[d.SERVICE_ERROR]:"high",[d.PROCESS_ERROR]:"high",[d.PERMISSION_ERROR]:"critical"}[e]||"medium"}};N();var $=class s{static{c(this,"ErrorHandler")}static handle(e){e instanceof R?s.handleCLIError(e):s.handleUnknownError(e),process.exit(1)}static handleCLIError(e){if(console.error(I.red(`\u274C \u9519\u8BEF: ${e.message}`)),process.env.DEBUG&&console.error(I.gray(`\u9519\u8BEF\u7801: ${e.code}`)),e.suggestions&&e.suggestions.length>0){console.log(I.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of e.suggestions)console.log(I.gray(` ${r}`))}let t=Y.getHelpMessage(e.code);t&&console.log(I.blue(`\u2139\uFE0F ${t}`))}static handleUnknownError(e){console.error(I.red(`\u274C \u672A\u77E5\u9519\u8BEF: ${e.message}`)),process.env.DEBUG||process.env.NODE_ENV==="development"?(console.error(I.gray("\u5806\u6808\u4FE1\u606F:")),console.error(I.gray(e.stack))):console.log(I.yellow("\u{1F4A1} \u63D0\u793A: \u8BBE\u7F6E DEBUG=1 \u73AF\u5883\u53D8\u91CF\u67E5\u770B\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F"))}static async handleAsync(e,t){try{return await e()}catch(r){throw r instanceof R?r:r instanceof Error?new R(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new R(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static handleSync(e,t){try{return e()}catch(r){throw r instanceof R?r:r instanceof Error?new R(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new R(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static warn(e,t){if(console.warn(I.yellow(`\u26A0\uFE0F \u8B66\u544A: ${e}`)),t&&t.length>0){console.log(I.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of t)console.log(I.gray(` ${r}`))}}static info(e){console.log(I.blue(`\u2139\uFE0F ${e}`))}static success(e){console.log(I.green(`\u2705 ${e}`))}};K();ge();G();ee();te();N();import re from"fs";import A from"path";import{fileURLToPath as $e}from"url";var oe=class s{static{c(this,"VersionUtils")}static cachedVersion=null;static getVersion(){if(s.cachedVersion)return s.cachedVersion;try{let e=$e(import.meta.url),t=A.dirname(e),r=[A.join(t,"package.json"),A.join(t,"..","package.json"),A.join(t,"..","..","..","package.json"),A.join(t,"..","..","..","..","package.json")];for(let o of r)if(re.existsSync(o)){let n=JSON.parse(re.readFileSync(o,"utf8"));if(n.version)return s.cachedVersion=n.version,n.version}return s.cachedVersion="unknown","unknown"}catch(e){return console.warn("\u65E0\u6CD5\u4ECE package.json \u8BFB\u53D6\u7248\u672C\u4FE1\u606F:",e),s.cachedVersion="unknown","unknown"}}static getVersionInfo(){try{let e=$e(import.meta.url),t=A.dirname(e),r=[A.join(t,"package.json"),A.join(t,"..","package.json"),A.join(t,"..","..","..","package.json"),A.join(t,"..","..","..","..","package.json")];for(let o of r)if(re.existsSync(o)){let n=JSON.parse(re.readFileSync(o,"utf8"));return{version:n.version||"unknown",name:n.name,description:n.description,author:n.author}}return{version:"unknown"}}catch{throw new m("\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C\u4FE1\u606F","package.json")}}static compareVersions(e,t){let r=e.split(".").map(Number),o=t.split(".").map(Number),n=Math.max(r.length,o.length);for(let i=0;i<n;i++){let a=r[i]||0,g=o[i]||0;if(a>g)return 1;if(a<g)return-1}return 0}static isValidVersion(e){return/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?$/.test(e)}static clearCache(){s.cachedVersion=null}};var se=class s{static{c(this,"DIContainer")}instances=new Map;factories=new Map;asyncFactories=new Map;singletons=new Set;register(e,t,r=!1){this.factories.set(e,t),r&&this.singletons.add(e)}registerSingleton(e,t){this.register(e,t,!0)}registerInstance(e,t){this.instances.set(e,t),this.singletons.add(e)}get(e){if(this.singletons.has(e)&&this.instances.has(e))return this.instances.get(e);let t=this.factories.get(e);if(!t)throw new Error(`Service ${e} not registered`);let r=t();return this.singletons.has(e)&&this.instances.set(e,r),r}has(e){return this.factories.has(e)||this.instances.has(e)}clear(){this.instances.clear(),this.factories.clear(),this.singletons.clear()}getRegisteredKeys(){let e=Array.from(this.factories.keys()),t=Array.from(this.instances.keys());return[...new Set([...e,...t])]}static create(){let e=new s;return e.registerSingleton("versionUtils",()=>oe),e.registerSingleton("platformUtils",()=>D),e.registerSingleton("formatUtils",()=>W),e.registerSingleton("fileUtils",()=>f),e.registerSingleton("pathUtils",()=>w),e.registerSingleton("validation",()=>M),e.registerSingleton("configManager",()=>lt),e.registerSingleton("errorHandler",()=>$),e.registerSingleton("processManager",()=>{let t=(de(),L(Te));return new t.ProcessManagerImpl}),e.registerSingleton("daemonManager",()=>{let t=(De(),L(Oe)),r=e.get("processManager");return new t.DaemonManagerImpl(r)}),e.registerSingleton("serviceManager",()=>{let t=(Ne(),L(Fe)),r=e.get("processManager"),o=e.get("configManager");return new t.ServiceManagerImpl(r,o)}),e.registerSingleton("templateManager",()=>{let t=(je(),L(Ae));return new t.TemplateManagerImpl}),e}};var ae=class{constructor(e){this.container=e}static{c(this,"CommandHandlerFactory")}createHandlers(){return[this.createHandler("service"),this.createHandler("config"),this.createHandler("project"),this.createHandler("mcp"),this.createHandler("endpoint")]}createHandler(e){switch(e){case"service":return this.createServiceCommandHandler();case"config":return this.createConfigCommandHandler();case"project":return this.createProjectCommandHandler();case"mcp":return this.createMcpCommandHandler();case"endpoint":return this.createEndpointCommandHandler();default:throw new Error(`\u672A\u77E5\u7684\u547D\u4EE4\u5904\u7406\u5668\u7C7B\u578B: ${e}`)}}createServiceCommandHandler(){let{ServiceCommandHandler:e}=(He(),L(Le));return new e(this.container)}createConfigCommandHandler(){let{ConfigCommandHandler:e}=(ke(),L(ze));return new e(this.container)}createProjectCommandHandler(){let{ProjectCommandHandler:e}=(Ve(),L(_e));return new e(this.container)}createMcpCommandHandler(){let{McpCommandHandler:e}=(Xe(),L(Be));return new e(this.container)}createEndpointCommandHandler(){let{EndpointCommandHandler:e}=(qe(),L(Je));return new e(this.container)}};var ce=class{constructor(e){this.container=e;this.handlerFactory=new ae(e)}static{c(this,"CommandRegistry")}handlers=[];handlerFactory;async registerCommands(e){try{this.registerVersionCommand(e),this.registerHelpCommand(e);let t=this.handlerFactory.createHandlers();for(let r of t)this.registerHandler(r),this.registerCommand(e,r);this.registerLegacyServiceCommands(e,t)}catch(t){$.handle(t)}}registerHandler(e){this.handlers.push(e)}registerCommand(e,t){if(t.subcommands&&t.subcommands.length>0){let r=e.command(t.name).description(t.description);for(let o of t.subcommands){let n=o.name;o.name==="get"?n="get <key>":o.name==="set"?n="set <key> <value>":o.name==="call"&&(n="call <serviceName> <toolName>");let i=r.command(n).description(o.description);if(o.options)for(let a of o.options)i.option(a.flags,a.description,a.defaultValue);i.action(async(...a)=>{try{let v=a[a.length-1].opts();await o.execute(a.slice(0,-1),v)}catch(g){$.handle(g)}})}r.action(async(...o)=>{try{let i=o[o.length-1].opts();await t.execute(o.slice(0,-1),i)}catch(n){$.handle(n)}})}else{let r=t.name;t.name==="create"&&(r="create <projectName>");let o=e.command(r).description(t.description);if(t.options)for(let n of t.options)o.option(n.flags,n.description,n.defaultValue);o.action(async(...n)=>{try{let a=n[n.length-1].opts();await t.execute(n.slice(0,-1),a)}catch(i){$.handle(i)}})}}registerVersionCommand(e){let t=this.container.get("versionUtils");e.version(t.getVersion(),"-v, --version","\u663E\u793A\u7248\u672C\u4FE1\u606F"),e.option("--info","\u663E\u793A\u8BE6\u7EC6\u4FE1\u606F"),e.option("--version-info","\u663E\u793A\u8BE6\u7EC6\u7248\u672C\u4FE1\u606F")}registerHelpCommand(e){e.helpOption("-h, --help","\u663E\u793A\u5E2E\u52A9\u4FE1\u606F").addHelpText("after",`
|
|
14
|
+
`)}}});var _e={};F(_e,{ConfigCommandHandler:()=>ve});import lt from"path";import u from"chalk";import ue from"ora";var ve,He=E(()=>{"use strict";G();ve=class extends O{static{c(this,"ConfigCommandHandler")}name="config";description="\u914D\u7F6E\u7BA1\u7406\u547D\u4EE4";subcommands=[{name:"init",description:"\u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6",options:[{flags:"-f, --format <format>",description:"\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F (json, json5, jsonc)",defaultValue:"json"}],execute:c(async(e,t)=>{await this.handleInit(t)},"execute")},{name:"get",description:"\u67E5\u770B\u914D\u7F6E\u503C",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleGet(e[0])},"execute")},{name:"set",description:"\u8BBE\u7F6E\u914D\u7F6E\u503C",execute:c(async(e,t)=>{this.validateArgs(e,2),await this.handleSet(e[0],e[1])},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("\u914D\u7F6E\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleInit(e){let t=ue("\u521D\u59CB\u5316\u914D\u7F6E...").start();try{let r=e.format;if(r!=="json"&&r!=="json5"&&r!=="jsonc")throw new Error("\u683C\u5F0F\u5FC5\u987B\u662F json, json5 \u6216 jsonc");let o=this.getService("configManager");if(o.configExists()){t.warn("\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728"),console.log(u.yellow("\u5982\u9700\u91CD\u65B0\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u5220\u9664\u73B0\u6709\u7684\u914D\u7F6E\u6587\u4EF6"));return}o.initConfig(r),t.succeed("\u914D\u7F6E\u6587\u4EF6\u521D\u59CB\u5316\u6210\u529F");let n=process.env.XIAOZHI_CONFIG_DIR||process.cwd(),i=`xiaozhi.config.${r}`,a=lt.join(n,i);console.log(u.green(`\u2705 \u914D\u7F6E\u6587\u4EF6\u5DF2\u521B\u5EFA: ${i}`)),console.log(u.yellow("\u{1F4DD} \u8BF7\u7F16\u8F91\u914D\u7F6E\u6587\u4EF6\u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9:")),console.log(u.gray(` \u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84: ${a}`)),console.log(u.yellow("\u{1F4A1} \u6216\u8005\u4F7F\u7528\u547D\u4EE4\u8BBE\u7F6E:")),console.log(u.gray(" xiaozhi config set mcpEndpoint <your-endpoint-url>"))}catch(r){t.fail(`\u521D\u59CB\u5316\u914D\u7F6E\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleGet(e){let t=ue("\u8BFB\u53D6\u914D\u7F6E...").start();try{let r=this.getService("configManager");if(!r.configExists()){t.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log(u.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}let o=r.getConfig();switch(e){case"mcpEndpoint":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let n=r.getMcpEndpoints();n.length===0?console.log(u.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):n.length===1?console.log(u.green(`MCP \u7AEF\u70B9: ${n[0]}`)):(console.log(u.green(`MCP \u7AEF\u70B9 (${n.length} \u4E2A):`)),n.forEach((i,a)=>{console.log(u.gray(` ${a+1}. ${i}`))}));break}case"mcpServers":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(u.green("MCP \u670D\u52A1:"));for(let[n,i]of Object.entries(o.mcpServers)){let a=i;"type"in a&&a.type==="sse"?console.log(u.gray(` ${n}: [SSE] ${a.url}`)):console.log(u.gray(` ${n}: ${a.command} ${a.args.join(" ")}`))}break;case"connection":{t.succeed("\u914D\u7F6E\u4FE1\u606F");let n=r.getConnectionConfig();console.log(u.green("\u8FDE\u63A5\u914D\u7F6E:")),console.log(u.gray(` \u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${n.heartbeatInterval}ms`)),console.log(u.gray(` \u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${n.heartbeatTimeout}ms`)),console.log(u.gray(` \u91CD\u8FDE\u95F4\u9694: ${n.reconnectInterval}ms`));break}case"heartbeatInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(u.green(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694: ${r.getHeartbeatInterval()}ms`));break;case"heartbeatTimeout":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(u.green(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4: ${r.getHeartbeatTimeout()}ms`));break;case"reconnectInterval":t.succeed("\u914D\u7F6E\u4FE1\u606F"),console.log(u.green(`\u91CD\u8FDE\u95F4\u9694: ${r.getReconnectInterval()}ms`));break;default:t.fail(`\u672A\u77E5\u7684\u914D\u7F6E\u9879: ${e}`),console.log(u.yellow("\u652F\u6301\u7684\u914D\u7F6E\u9879: mcpEndpoint, mcpServers, connection, heartbeatInterval, heartbeatTimeout, reconnectInterval"))}}catch(r){t.fail(`\u8BFB\u53D6\u914D\u7F6E\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleSet(e,t){let r=ue("\u66F4\u65B0\u914D\u7F6E...").start();try{let o=this.getService("configManager");if(!o.configExists()){r.fail("\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728"),console.log(u.yellow('\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u8FD0\u884C "xiaozhi config init" \u521D\u59CB\u5316\u914D\u7F6E'));return}switch(e){case"mcpEndpoint":o.updateMcpEndpoint(t),r.succeed(`MCP \u7AEF\u70B9\u5DF2\u8BBE\u7F6E\u4E3A: ${t}`);break;case"heartbeatInterval":{let n=Number.parseInt(t);if(Number.isNaN(n)||n<=0)throw new Error("\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5FC5\u987B\u662F\u6B63\u6574\u6570");o.updateHeartbeatInterval(n),r.succeed(`\u5FC3\u8DF3\u68C0\u6D4B\u95F4\u9694\u5DF2\u8BBE\u7F6E\u4E3A: ${n}ms`);break}case"heartbeatTimeout":{let n=Number.parseInt(t);if(Number.isNaN(n)||n<=0)throw new Error("\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5FC5\u987B\u662F\u6B63\u6574\u6570");o.updateHeartbeatTimeout(n),r.succeed(`\u5FC3\u8DF3\u8D85\u65F6\u65F6\u95F4\u5DF2\u8BBE\u7F6E\u4E3A: ${n}ms`);break}case"reconnectInterval":{let n=Number.parseInt(t);if(Number.isNaN(n)||n<=0)throw new Error("\u91CD\u8FDE\u95F4\u9694\u5FC5\u987B\u662F\u6B63\u6574\u6570");o.updateReconnectInterval(n),r.succeed(`\u91CD\u8FDE\u95F4\u9694\u5DF2\u8BBE\u7F6E\u4E3A: ${n}ms`);break}default:r.fail(`\u4E0D\u652F\u6301\u8BBE\u7F6E\u7684\u914D\u7F6E\u9879: ${e}`),console.log(u.yellow("\u652F\u6301\u8BBE\u7F6E\u7684\u914D\u7F6E\u9879: mcpEndpoint, heartbeatInterval, heartbeatTimeout, reconnectInterval"))}}catch(o){r.fail(`\u8BBE\u7F6E\u914D\u7F6E\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`),this.handleError(o)}}}});var ze={};F(ze,{ProjectCommandHandler:()=>ye});import mt from"path";import S from"chalk";import gt from"ora";var ye,ke=E(()=>{"use strict";G();ye=class extends O{static{c(this,"ProjectCommandHandler")}name="create";description="\u521B\u5EFA\u9879\u76EE";options=[{flags:"-t, --template <templateName>",description:"\u4F7F\u7528\u6307\u5B9A\u6A21\u677F\u521B\u5EFA\u9879\u76EE"}];constructor(e){super(e)}async execute(e,t){this.validateArgs(e,1);let r=e[0];await this.handleCreate(r,t)}async handleCreate(e,t){let r=gt("\u521D\u59CB\u5316\u9879\u76EE...").start();try{let o=this.getService("templateManager"),n=this.getService("fileUtils"),i=mt.join(process.cwd(),e);if(await n.exists(i)){r.fail(`\u76EE\u5F55 "${e}" \u5DF2\u5B58\u5728`),console.log(S.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u9009\u62E9\u4E0D\u540C\u7684\u9879\u76EE\u540D\u79F0\u6216\u5220\u9664\u73B0\u6709\u76EE\u5F55"));return}t.template?await this.createFromTemplate(e,t.template,i,r,o):await this.createBasicProject(e,i,r,o)}catch(o){r.fail(`\u521B\u5EFA\u9879\u76EE\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`),this.handleError(o)}}async createFromTemplate(e,t,r,o,n){o.text="\u68C0\u67E5\u6A21\u677F...";let i=await n.getAvailableTemplates();if(i.length===0){o.fail("\u627E\u4E0D\u5230\u53EF\u7528\u6A21\u677F"),console.log(S.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u786E\u4FDD xiaozhi-client \u6B63\u786E\u5B89\u88C5"));return}let a=t;if(!await n.validateTemplate(a)){o.fail(`\u6A21\u677F "${a}" \u4E0D\u5B58\u5728`);let v=this.findSimilarTemplate(a,i);if(v)if(console.log(S.yellow(`\u{1F4A1} \u4F60\u662F\u60F3\u4F7F\u7528\u6A21\u677F "${v}" \u5417\uFF1F`)),await this.askUserConfirmation(S.cyan("\u786E\u8BA4\u4F7F\u7528\u6B64\u6A21\u677F\uFF1F(y/n): ")))a=v;else{this.showAvailableTemplates(i);return}else{this.showAvailableTemplates(i);return}}o.text=`\u4ECE\u6A21\u677F "${a}" \u521B\u5EFA\u9879\u76EE "${e}"...`,await n.createProject({templateName:a,targetPath:r,projectName:e}),o.succeed(`\u9879\u76EE "${e}" \u521B\u5EFA\u6210\u529F`),console.log(S.green("\u2705 \u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(S.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(S.gray(` cd ${e}`)),console.log(S.gray(" pnpm install # \u5B89\u88C5\u4F9D\u8D56")),console.log(S.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9")),console.log(S.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1"))}async createBasicProject(e,t,r,o){r.text=`\u521B\u5EFA\u57FA\u672C\u9879\u76EE "${e}"...`,await o.createProject({templateName:null,targetPath:t,projectName:e}),r.succeed(`\u9879\u76EE "${e}" \u521B\u5EFA\u6210\u529F`),console.log(S.green("\u2705 \u57FA\u672C\u9879\u76EE\u521B\u5EFA\u5B8C\u6210!")),console.log(S.yellow("\u{1F4DD} \u63A5\u4E0B\u6765\u7684\u6B65\u9AA4:")),console.log(S.gray(` cd ${e}`)),console.log(S.gray(" # \u7F16\u8F91 xiaozhi.config.json \u8BBE\u7F6E\u4F60\u7684 MCP \u7AEF\u70B9\u548C\u670D\u52A1")),console.log(S.gray(" xiaozhi start # \u542F\u52A8\u670D\u52A1")),console.log(S.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 --template \u9009\u9879\u53EF\u4EE5\u4ECE\u6A21\u677F\u521B\u5EFA\u9879\u76EE"))}showAvailableTemplates(e){console.log(S.yellow("\u53EF\u7528\u7684\u6A21\u677F:"));for(let t of e)console.log(S.gray(` - ${t}`))}findSimilarTemplate(e,t){let r=this.getService("formatUtils"),o=null,n=0;for(let i of t){let a=r.calculateSimilarity(e.toLowerCase(),i.toLowerCase());a>n&&a>.6&&(n=a,o=i)}return o}async askUserConfirmation(e){let r=(await import("readline")).createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{r.question(e,n=>{r.close(),o(n.toLowerCase().trim()==="y"||n.toLowerCase().trim()==="yes")})})}}});function Ue(s){let e=s;return typeof e=="object"&&e!==null&&"command"in e&&"args"in e&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")}var Ve=E(()=>{"use strict";c(Ue,"isLocalMCPServerConfig")});var Ge={};F(Ge,{McpCommandHandler:()=>Ee});import{configManager as N}from"@xiaozhi-client/config";import l from"chalk";import We from"cli-table3";import dt from"consola";import we from"ora";var Ee,Be=E(()=>{"use strict";G();Ve();ge();Ee=class s extends O{static{c(this,"McpCommandHandler")}processManager;baseUrl;constructor(...e){super(...e),this.processManager=new J;try{let t=N.getWebUIPort()??9999;this.baseUrl=`http://localhost:${t}`}catch{this.baseUrl="http://localhost:9999"}}static CHINESE_CHAR_REGEX=/[\u4e00-\u9fff\u3400-\u4dbf\uff00-\uffef]/;static getDisplayWidth(e){let t=0;for(let r of e)s.CHINESE_CHAR_REGEX.test(r)?t+=2:t+=1;return t}static truncateToWidth(e,t){if(s.getDisplayWidth(e)<=t)return e;if(t<=3)return"";let r="",o=0,n=!1;for(let i of e){let a=s.CHINESE_CHAR_REGEX.test(i)?2:1;if(o+a>t-3){if(!n)return"";r+="...";break}r+=i,o+=a,n=!0}return r}static parseJsonArgs(e){try{return JSON.parse(e)}catch(t){throw new Error(`\u53C2\u6570\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u4F7F\u7528\u6709\u6548\u7684 JSON \u683C\u5F0F\u3002\u9519\u8BEF\u8BE6\u60C5: ${t instanceof Error?t.message:String(t)}`)}}static formatToolCallResult(e){return JSON.stringify(e)}name="mcp";description="MCP \u670D\u52A1\u548C\u5DE5\u5177\u7BA1\u7406";subcommands=[{name:"list",description:"\u5217\u51FA MCP \u670D\u52A1",options:[{flags:"--tools",description:"\u663E\u793A\u6240\u6709\u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868"}],execute:c(async(e,t)=>{await this.handleList(t)},"execute")},{name:"server",description:"\u7BA1\u7406\u6307\u5B9A\u7684 MCP \u670D\u52A1",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleServer(e[0])},"execute")},{name:"tool",description:"\u542F\u7528\u6216\u7981\u7528\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177",execute:c(async(e,t)=>{this.validateArgs(e,3);let[r,o,n]=e;n!=="enable"&&n!=="disable"&&(console.error(l.red("\u9519\u8BEF: \u64CD\u4F5C\u5FC5\u987B\u662F 'enable' \u6216 'disable'")),process.exit(1));let i=n==="enable";await this.handleTool(r,o,i)},"execute")},{name:"call",description:"\u8C03\u7528\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177",options:[{flags:"--args <json>",description:"\u5DE5\u5177\u53C2\u6570 (JSON \u683C\u5F0F)",defaultValue:"{}"}],execute:c(async(e,t)=>{this.validateArgs(e,2);let[r,o]=e;await this.handleCall(r,o,t.args??"{}")},"execute")}];async execute(e,t){console.log("MCP \u670D\u52A1\u548C\u5DE5\u5177\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleList(e){try{await this.handleListInternal(e)}catch(t){this.handleError(t)}}async handleServer(e){try{await this.handleServerInternal(e)}catch(t){this.handleError(t)}}async handleTool(e,t,r){try{await this.handleToolInternal(e,t,r)}catch(o){this.handleError(o)}}async validateServiceStatus(){if(!this.processManager.getServiceStatus().running)throw new Error("xiaozhi \u670D\u52A1\u672A\u542F\u52A8\u3002\u8BF7\u5148\u8FD0\u884C 'xiaozhi start' \u6216 'xiaozhi start -d' \u542F\u52A8\u670D\u52A1\u3002");try{let t=await fetch(`${this.baseUrl}/api/status`,{method:"GET",signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Web \u670D\u52A1\u5668\u54CD\u5E94\u9519\u8BEF: ${t.status}`)}catch(t){if(t instanceof Error&&t.name==="AbortError")throw new Error("\u8FDE\u63A5 xiaozhi \u670D\u52A1\u8D85\u65F6\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u662F\u5426\u6B63\u5E38\u8FD0\u884C\u3002");if(t instanceof Error)throw t instanceof TypeError&&/fetch|network|failed/i.test(t.message)?new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230 xiaozhi \u670D\u52A1\uFF08\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF09\u3002\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u6216\u670D\u52A1\u5730\u5740\u662F\u5426\u6B63\u786E\u3002\u539F\u59CB\u9519\u8BEF: ${t.message}`):new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230 xiaozhi \u670D\u52A1\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002\u539F\u59CB\u9519\u8BEF: ${t.message}`);let r;try{r=JSON.stringify(t)}catch{r=String(t)}throw new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230 xiaozhi \u670D\u52A1\u3002\u8BF7\u68C0\u67E5\u670D\u52A1\u72B6\u6001\u3002\u9519\u8BEF\u8BE6\u60C5: ${r}`)}}async callToolInternal(e,t,r){await this.validateServiceStatus();try{let o=await fetch(`${this.baseUrl}/api/tools/call`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceName:e,toolName:t,args:r})});if(!o.ok){let i=`HTTP ${o.status}: ${o.statusText}`;try{let a=await o.json(),g=a?.error?.message??a?.message;typeof g=="string"&&g.trim()&&(i=g)}catch{}throw new Error(i)}let n=await o.json();if(!n.success)throw new Error(n.error?.message||"\u5DE5\u5177\u8C03\u7528\u5931\u8D25");return n.data}catch(o){throw dt.error(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e}/${t}`,o instanceof Error?o.message:String(o)),o}}async handleCall(e,t,r){try{let o=s.parseJsonArgs(r),n=await this.callToolInternal(e,t,o);console.log(s.formatToolCallResult(n))}catch(o){console.log(`\u5DE5\u5177\u8C03\u7528\u5931\u8D25: ${e}/${t}`),console.error(l.red("\u9519\u8BEF:"),o.message);let n=o.message;if(n.includes("\u670D\u52A1\u672A\u542F\u52A8")?(console.log(),console.log(l.yellow("\u{1F4A1} \u8BF7\u5148\u542F\u52A8\u670D\u52A1:")),console.log(l.gray(" xiaozhi start # \u524D\u53F0\u542F\u52A8")),console.log(l.gray(" xiaozhi start -d # \u540E\u53F0\u542F\u52A8"))):n.includes("\u53C2\u6570\u683C\u5F0F\u9519\u8BEF")&&(console.log(),console.log(l.yellow("\u{1F4A1} \u6B63\u786E\u683C\u5F0F\u793A\u4F8B:")),console.log(l.gray(` xiaozhi mcp call ${e} ${t} --args '{"param": "value"}'`))),process.env.NODE_ENV==="test")throw new Error("process.exit called");process.exit(1)}}async handleListInternal(e={}){let t=we("\u83B7\u53D6 MCP \u670D\u52A1\u5217\u8868...").start();try{let r=N.getMcpServers(),o=Object.keys(r),n=N.getCustomMCPTools(),i=n.length>0,a=o.length+(i?1:0);if(a===0){t.warn("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u670D\u52A1\u6216 customMCP \u5DE5\u5177"),console.log(l.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi config' \u547D\u4EE4\u914D\u7F6E MCP \u670D\u52A1\u6216\u5728 xiaozhi.config.json \u4E2D\u914D\u7F6E customMCP \u5DE5\u5177"));return}if(t.succeed(`\u627E\u5230 ${a} \u4E2A MCP \u670D\u52A1${i?" (\u5305\u62EC customMCP)":""}`),e.tools){console.log(),console.log(l.bold("MCP \u670D\u52A1\u5DE5\u5177\u5217\u8868:")),console.log();let g=8,v=[];for(let P of o){let b=N.getServerToolsConfig(P),k=Object.keys(b);v.push(...k)}if(i){let P=n.map(b=>b.name);v.push(...P)}for(let P of v){let b=s.getDisplayWidth(P);b>g&&(g=b)}g=Math.max(10,Math.min(g+2,30));let x=new We({head:[l.bold("MCP"),l.bold("\u5DE5\u5177\u540D\u79F0"),l.bold("\u72B6\u6001"),l.bold("\u63CF\u8FF0")],colWidths:[15,g,8,40],wordWrap:!0,style:{head:[],border:[]}});if(i)for(let P of n){let b=s.truncateToWidth(P.description||"",32);x.push(["customMCP",P.name,l.green("\u542F\u7528"),b])}for(let P of o){let b=N.getServerToolsConfig(P),k=Object.keys(b);if(k.length===0)x.push([l.gray(P),l.gray("-"),l.gray("-"),l.gray("\u6682\u672A\u8BC6\u522B\u5230\u76F8\u5173\u5DE5\u5177")]);else{x.length>0&&x.push([{colSpan:4,content:""}]);for(let Pe of k){let Re=b[Pe],Ke=Re.enable?l.green("\u542F\u7528"):l.red("\u7981\u7528"),Je=s.truncateToWidth(Re.description||"",32);x.push([P,Pe,Ke,Je])}}}console.log(x.toString())}else{console.log(),console.log(l.bold("MCP \u670D\u52A1\u5217\u8868:")),console.log(),i&&(console.log(`${l.cyan("\u2022")} ${l.bold("customMCP")}`),console.log(` \u7C7B\u578B: ${l.gray("\u81EA\u5B9A\u4E49 MCP \u5DE5\u5177")}`),console.log(` \u914D\u7F6E: ${l.gray("xiaozhi.config.json")}`),console.log(` \u5DE5\u5177: ${l.green(n.length)} \u542F\u7528 / ${l.yellow(n.length)} \u603B\u8BA1`),console.log());for(let g of o){let v=r[g],x=N.getServerToolsConfig(g),P=Object.keys(x).length,b=Object.values(x).filter(k=>k.enable!==!1).length;console.log(`${l.cyan("\u2022")} ${l.bold(g)}`),"url"in v?("type"in v&&v.type==="sse"?console.log(` \u7C7B\u578B: ${l.gray("SSE")}`):console.log(` \u7C7B\u578B: ${l.gray("Streamable HTTP")}`),console.log(` URL: ${l.gray(v.url)}`)):Ue(v)&&console.log(` \u547D\u4EE4: ${l.gray(v.command)} ${l.gray(v.args.join(" "))}`),P>0?console.log(` \u5DE5\u5177: ${l.green(b)} \u542F\u7528 / ${l.yellow(P)} \u603B\u8BA1`):console.log(` \u5DE5\u5177: ${l.gray("\u672A\u626B\u63CF (\u8BF7\u5148\u542F\u52A8\u670D\u52A1)")}`),console.log()}}console.log(l.gray("\u{1F4A1} \u63D0\u793A:")),console.log(l.gray(" - \u4F7F\u7528 'xiaozhi mcp list --tools' \u67E5\u770B\u6240\u6709\u5DE5\u5177")),console.log(l.gray(" - \u4F7F\u7528 'xiaozhi mcp <\u670D\u52A1\u540D> list' \u67E5\u770B\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177")),console.log(l.gray(" - \u4F7F\u7528 'xiaozhi mcp <\u670D\u52A1\u540D> <\u5DE5\u5177\u540D> enable/disable' \u542F\u7528/\u7981\u7528\u5DE5\u5177"))}catch(r){t.fail("\u83B7\u53D6 MCP \u670D\u52A1\u5217\u8868\u5931\u8D25"),console.error(l.red(`\u9519\u8BEF: ${r instanceof Error?r.message:String(r)}`)),process.exit(1)}}async handleServerInternal(e){let t=we(`\u83B7\u53D6 ${e} \u670D\u52A1\u7684\u5DE5\u5177\u5217\u8868...`).start();try{if(!N.getMcpServers()[e]){t.fail(`\u670D\u52A1 '${e}' \u4E0D\u5B58\u5728`),console.log(l.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u670D\u52A1"));return}let o=N.getServerToolsConfig(e),n=Object.keys(o);if(n.length===0){t.warn(`\u670D\u52A1 '${e}' \u6682\u65E0\u5DE5\u5177\u4FE1\u606F`),console.log(l.yellow("\u{1F4A1} \u63D0\u793A: \u8BF7\u5148\u542F\u52A8\u670D\u52A1\u4EE5\u626B\u63CF\u5DE5\u5177\u5217\u8868"));return}t.succeed(`\u670D\u52A1 '${e}' \u5171\u6709 ${n.length} \u4E2A\u5DE5\u5177`),console.log(),console.log(l.bold(`${e} \u670D\u52A1\u5DE5\u5177\u5217\u8868:`)),console.log();let i=new We({head:[l.bold("\u5DE5\u5177\u540D\u79F0"),l.bold("\u72B6\u6001"),l.bold("\u63CF\u8FF0")],colWidths:[30,8,50],wordWrap:!0,style:{head:[],border:[]}});for(let a of n){let g=o[a],v=g.enable?l.green("\u542F\u7528"):l.red("\u7981\u7528"),x=s.truncateToWidth(g.description||"",40);i.push([a,v,x])}console.log(i.toString()),console.log(),console.log(l.gray("\u{1F4A1} \u63D0\u793A:")),console.log(l.gray(` - \u4F7F\u7528 'xiaozhi mcp ${e} <\u5DE5\u5177\u540D> enable' \u542F\u7528\u5DE5\u5177`)),console.log(l.gray(` - \u4F7F\u7528 'xiaozhi mcp ${e} <\u5DE5\u5177\u540D> disable' \u7981\u7528\u5DE5\u5177`))}catch(r){t.fail("\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u5931\u8D25"),console.error(l.red(`\u9519\u8BEF: ${r instanceof Error?r.message:String(r)}`)),process.exit(1)}}async handleToolInternal(e,t,r){let o=r?"\u542F\u7528":"\u7981\u7528",n=we(`${o}\u5DE5\u5177 ${e}/${t}...`).start();try{if(!N.getMcpServers()[e]){n.fail(`\u670D\u52A1 '${e}' \u4E0D\u5B58\u5728`),console.log(l.yellow("\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp list' \u67E5\u770B\u6240\u6709\u53EF\u7528\u670D\u52A1"));return}let a=N.getServerToolsConfig(e);if(!a[t]){n.fail(`\u5DE5\u5177 '${t}' \u5728\u670D\u52A1 '${e}' \u4E2D\u4E0D\u5B58\u5728`),console.log(l.yellow(`\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 'xiaozhi mcp ${e} list' \u67E5\u770B\u8BE5\u670D\u52A1\u7684\u6240\u6709\u5DE5\u5177`));return}N.setToolEnabled(e,t,r,a[t].description),n.succeed(`\u6210\u529F${o}\u5DE5\u5177 ${l.cyan(e)}/${l.cyan(t)}`),console.log(),console.log(l.gray("\u{1F4A1} \u63D0\u793A: \u5DE5\u5177\u72B6\u6001\u66F4\u6539\u5C06\u5728\u4E0B\u6B21\u542F\u52A8\u670D\u52A1\u65F6\u751F\u6548"))}catch(i){n.fail(`${o}\u5DE5\u5177\u5931\u8D25`),console.error(l.red(`\u9519\u8BEF: ${i instanceof Error?i.message:String(i)}`)),process.exit(1)}}}});var Xe={};F(Xe,{EndpointCommandHandler:()=>Se});import B from"chalk";import ne from"ora";var Se,qe=E(()=>{"use strict";G();Se=class extends O{static{c(this,"EndpointCommandHandler")}name="endpoint";description="\u7BA1\u7406 MCP \u7AEF\u70B9";subcommands=[{name:"list",description:"\u5217\u51FA\u6240\u6709 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{await this.handleList()},"execute")},{name:"add",description:"\u6DFB\u52A0\u65B0\u7684 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleAdd(e[0])},"execute")},{name:"remove",description:"\u79FB\u9664\u6307\u5B9A\u7684 MCP \u7AEF\u70B9",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleRemove(e[0])},"execute")},{name:"set",description:"\u8BBE\u7F6E MCP \u7AEF\u70B9\uFF08\u53EF\u4EE5\u662F\u5355\u4E2A\u6216\u591A\u4E2A\uFF09",execute:c(async(e,t)=>{this.validateArgs(e,1),await this.handleSet(e)},"execute")}];constructor(e){super(e)}async execute(e,t){console.log("MCP \u7AEF\u70B9\u7BA1\u7406\u547D\u4EE4\u3002\u4F7F\u7528 --help \u67E5\u770B\u53EF\u7528\u7684\u5B50\u547D\u4EE4\u3002")}async handleList(){let e=ne("\u8BFB\u53D6\u7AEF\u70B9\u914D\u7F6E...").start();try{let r=this.getService("configManager").getMcpEndpoints();e.succeed("\u7AEF\u70B9\u5217\u8868"),r.length===0?console.log(B.yellow("\u672A\u914D\u7F6E\u4EFB\u4F55 MCP \u7AEF\u70B9")):(console.log(B.green(`\u5171 ${r.length} \u4E2A\u7AEF\u70B9:`)),r.forEach((o,n)=>{console.log(B.gray(` ${n+1}. ${o}`))}))}catch(t){e.fail(`\u8BFB\u53D6\u7AEF\u70B9\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),this.handleError(t)}}async handleAdd(e){let t=ne("\u6DFB\u52A0\u7AEF\u70B9...").start();try{let r=this.getService("configManager");r.addMcpEndpoint(e),t.succeed(`\u6210\u529F\u6DFB\u52A0\u7AEF\u70B9: ${e}`);let o=r.getMcpEndpoints();console.log(B.gray(`\u5F53\u524D\u5171 ${o.length} \u4E2A\u7AEF\u70B9`))}catch(r){t.fail(`\u6DFB\u52A0\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleRemove(e){let t=ne("\u79FB\u9664\u7AEF\u70B9...").start();try{let r=this.getService("configManager");r.removeMcpEndpoint(e),t.succeed(`\u6210\u529F\u79FB\u9664\u7AEF\u70B9: ${e}`);let o=r.getMcpEndpoints();console.log(B.gray(`\u5F53\u524D\u5269\u4F59 ${o.length} \u4E2A\u7AEF\u70B9`))}catch(r){t.fail(`\u79FB\u9664\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}async handleSet(e){let t=ne("\u8BBE\u7F6E\u7AEF\u70B9...").start();try{let r=this.getService("configManager");if(e.length===1)r.updateMcpEndpoint(e[0]),t.succeed(`\u6210\u529F\u8BBE\u7F6E\u7AEF\u70B9: ${e[0]}`);else{r.updateMcpEndpoint(e),t.succeed(`\u6210\u529F\u8BBE\u7F6E ${e.length} \u4E2A\u7AEF\u70B9`);for(let[o,n]of e.entries())console.log(B.gray(` ${o+1}. ${n}`))}}catch(r){t.fail(`\u8BBE\u7F6E\u7AEF\u70B9\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),this.handleError(r)}}}});import{Command as pt}from"commander";import{configManager as at}from"@xiaozhi-client/config";import I from"chalk";q();var tt={[d.CONFIG_ERROR]:'\u8FD0\u884C "xiaozhi --help" \u67E5\u770B\u914D\u7F6E\u76F8\u5173\u547D\u4EE4',[d.SERVICE_ERROR]:'\u8FD0\u884C "xiaozhi status" \u68C0\u67E5\u670D\u52A1\u72B6\u6001',[d.VALIDATION_ERROR]:"\u68C0\u67E5\u8F93\u5165\u53C2\u6570\u662F\u5426\u6B63\u786E",[d.FILE_ERROR]:"\u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u548C\u6743\u9650",[d.PROCESS_ERROR]:"\u68C0\u67E5\u8FDB\u7A0B\u72B6\u6001\u548C\u6743\u9650",[d.NETWORK_ERROR]:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C\u9632\u706B\u5899\u8BBE\u7F6E",[d.PERMISSION_ERROR]:"\u5C1D\u8BD5\u4F7F\u7528\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C"},rt={config_not_found:['\u8FD0\u884C "xiaozhi init" \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6',"\u68C0\u67E5\u5F53\u524D\u76EE\u5F55\u662F\u5426\u4E3A\u9879\u76EE\u6839\u76EE\u5F55","\u8BBE\u7F6E XIAOZHI_CONFIG_DIR \u73AF\u5883\u53D8\u91CF\u6307\u5B9A\u914D\u7F6E\u76EE\u5F55"],service_port_occupied:["\u68C0\u67E5\u7AEF\u53E3\u662F\u5426\u88AB\u5176\u4ED6\u7A0B\u5E8F\u5360\u7528",'\u4F7F\u7528 "lsof -i :\u7AEF\u53E3\u53F7" \u67E5\u770B\u7AEF\u53E3\u4F7F\u7528\u60C5\u51B5',"\u66F4\u6539\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u7AEF\u53E3\u8BBE\u7F6E"],permission_denied:["\u68C0\u67E5\u6587\u4EF6\u548C\u76EE\u5F55\u6743\u9650","\u4F7F\u7528 sudo \u6216\u7BA1\u7406\u5458\u6743\u9650\u8FD0\u884C","\u786E\u4FDD\u5F53\u524D\u7528\u6237\u6709\u8DB3\u591F\u7684\u6743\u9650"],service_start_failed:["\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u662F\u5426\u6B63\u786E","\u67E5\u770B\u65E5\u5FD7\u6587\u4EF6\u83B7\u53D6\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F","\u786E\u4FDD\u6240\u6709\u4F9D\u8D56\u670D\u52A1\u6B63\u5E38\u8FD0\u884C"]},Q=class{static{c(this,"ERROR_MESSAGES")}static getHelpMessage(e){return tt[e]}static getSolutions(e){return rt[e]||[]}static formatError(e,t){return`${t?`[${t}] `:""}${e.message}`}static getFriendlyMessage(e){return{[d.CONFIG_ERROR]:"\u914D\u7F6E\u6587\u4EF6\u76F8\u5173\u9519\u8BEF",[d.SERVICE_ERROR]:"\u670D\u52A1\u8FD0\u884C\u76F8\u5173\u9519\u8BEF",[d.VALIDATION_ERROR]:"\u8F93\u5165\u9A8C\u8BC1\u9519\u8BEF",[d.FILE_ERROR]:"\u6587\u4EF6\u64CD\u4F5C\u9519\u8BEF",[d.PROCESS_ERROR]:"\u8FDB\u7A0B\u7BA1\u7406\u9519\u8BEF",[d.NETWORK_ERROR]:"\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF",[d.PERMISSION_ERROR]:"\u6743\u9650\u4E0D\u8DB3\u9519\u8BEF"}[e]||"\u672A\u77E5\u9519\u8BEF"}static isRecoverable(e){return[d.NETWORK_ERROR,d.FILE_ERROR,d.SERVICE_ERROR].includes(e)}static getSeverity(e){return{[d.VALIDATION_ERROR]:"low",[d.FILE_ERROR]:"medium",[d.CONFIG_ERROR]:"medium",[d.NETWORK_ERROR]:"medium",[d.SERVICE_ERROR]:"high",[d.PROCESS_ERROR]:"high",[d.PERMISSION_ERROR]:"critical"}[e]||"medium"}};L();var T=class s{static{c(this,"ErrorHandler")}static handle(e){e instanceof R?s.handleCLIError(e):s.handleUnknownError(e),process.exit(1)}static handleCLIError(e){if(console.error(I.red(`\u274C \u9519\u8BEF: ${e.message}`)),process.env.DEBUG&&console.error(I.gray(`\u9519\u8BEF\u7801: ${e.code}`)),e.suggestions&&e.suggestions.length>0){console.log(I.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of e.suggestions)console.log(I.gray(` ${r}`))}let t=Q.getHelpMessage(e.code);t&&console.log(I.blue(`\u2139\uFE0F ${t}`))}static handleUnknownError(e){console.error(I.red(`\u274C \u672A\u77E5\u9519\u8BEF: ${e.message}`)),process.env.DEBUG||process.env.NODE_ENV==="development"?(console.error(I.gray("\u5806\u6808\u4FE1\u606F:")),console.error(I.gray(e.stack))):console.log(I.yellow("\u{1F4A1} \u63D0\u793A: \u8BBE\u7F6E DEBUG=1 \u73AF\u5883\u53D8\u91CF\u67E5\u770B\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F"))}static async handleAsync(e,t){try{return await e()}catch(r){throw r instanceof R?r:r instanceof Error?new R(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new R(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static handleSync(e,t){try{return e()}catch(r){throw r instanceof R?r:r instanceof Error?new R(`${t}\u5931\u8D25: ${r.message}`,"OPERATION_FAILED",1):new R(`${t}\u5931\u8D25: \u672A\u77E5\u9519\u8BEF`,"OPERATION_FAILED",1)}}static warn(e,t){if(console.warn(I.yellow(`\u26A0\uFE0F \u8B66\u544A: ${e}`)),t&&t.length>0){console.log(I.yellow("\u{1F4A1} \u5EFA\u8BAE:"));for(let r of t)console.log(I.gray(` ${r}`))}}static info(e){console.log(I.blue(`\u2139\uFE0F ${e}`))}static success(e){console.log(I.green(`\u2705 ${e}`))}};K();le();W();Y();ee();var me="1.9.4",xe="xiaozhi-client";var te=class{static{c(this,"VersionUtils")}static getVersion(){return me}static getVersionInfo(){return{version:me,name:xe}}static compareVersions(e,t){let r=e.split(".").map(Number),o=t.split(".").map(Number),n=Math.max(r.length,o.length);for(let i=0;i<n;i++){let a=r[i]||0,g=o[i]||0;if(a>g)return 1;if(a<g)return-1}return 0}static isValidVersion(e){return/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?$/.test(e)}};var oe=class s{static{c(this,"DIContainer")}instances=new Map;factories=new Map;asyncFactories=new Map;singletons=new Set;register(e,t,r=!1){this.factories.set(e,t),r&&this.singletons.add(e)}registerSingleton(e,t){this.register(e,t,!0)}registerInstance(e,t){this.instances.set(e,t),this.singletons.add(e)}get(e){if(this.singletons.has(e)&&this.instances.has(e))return this.instances.get(e);let t=this.factories.get(e);if(!t)throw new Error(`Service ${e} not registered`);let r=t();return this.singletons.has(e)&&this.instances.set(e,r),r}has(e){return this.factories.has(e)||this.instances.has(e)}clear(){this.instances.clear(),this.factories.clear(),this.singletons.clear()}getRegisteredKeys(){let e=Array.from(this.factories.keys()),t=Array.from(this.instances.keys());return[...new Set([...e,...t])]}static create(){let e=new s;return e.registerSingleton("versionUtils",()=>te),e.registerSingleton("platformUtils",()=>D),e.registerSingleton("formatUtils",()=>V),e.registerSingleton("fileUtils",()=>f),e.registerSingleton("pathUtils",()=>w),e.registerSingleton("validation",()=>M),e.registerSingleton("configManager",()=>at),e.registerSingleton("errorHandler",()=>T),e.registerSingleton("processManager",()=>{let t=(ge(),A(Te));return new t.ProcessManagerImpl}),e.registerSingleton("daemonManager",()=>{let t=(Oe(),A(Me)),r=e.get("processManager");return new t.DaemonManagerImpl(r)}),e.registerSingleton("serviceManager",()=>{let t=(Ne(),A(De)),r=e.get("processManager"),o=e.get("configManager");return new t.ServiceManagerImpl(r,o)}),e.registerSingleton("templateManager",()=>{let t=(Ae(),A(Fe));return new t.TemplateManagerImpl}),e}};var se=class{constructor(e){this.container=e}static{c(this,"CommandHandlerFactory")}createHandlers(){return[this.createHandler("service"),this.createHandler("config"),this.createHandler("project"),this.createHandler("mcp"),this.createHandler("endpoint")]}createHandler(e){switch(e){case"service":return this.createServiceCommandHandler();case"config":return this.createConfigCommandHandler();case"project":return this.createProjectCommandHandler();case"mcp":return this.createMcpCommandHandler();case"endpoint":return this.createEndpointCommandHandler();default:throw new Error(`\u672A\u77E5\u7684\u547D\u4EE4\u5904\u7406\u5668\u7C7B\u578B: ${e}`)}}createServiceCommandHandler(){let{ServiceCommandHandler:e}=(Le(),A(je));return new e(this.container)}createConfigCommandHandler(){let{ConfigCommandHandler:e}=(He(),A(_e));return new e(this.container)}createProjectCommandHandler(){let{ProjectCommandHandler:e}=(ke(),A(ze));return new e(this.container)}createMcpCommandHandler(){let{McpCommandHandler:e}=(Be(),A(Ge));return new e(this.container)}createEndpointCommandHandler(){let{EndpointCommandHandler:e}=(qe(),A(Xe));return new e(this.container)}};var ie=class{constructor(e){this.container=e;this.handlerFactory=new se(e)}static{c(this,"CommandRegistry")}handlers=[];handlerFactory;async registerCommands(e){try{this.registerVersionCommand(e),this.registerHelpCommand(e);let t=this.handlerFactory.createHandlers();for(let r of t)this.registerHandler(r),this.registerCommand(e,r);this.registerLegacyServiceCommands(e,t)}catch(t){T.handle(t)}}registerHandler(e){this.handlers.push(e)}registerCommand(e,t){if(t.subcommands&&t.subcommands.length>0){let r=e.command(t.name).description(t.description);for(let o of t.subcommands){let n=o.name;o.name==="get"?n="get <key>":o.name==="set"?n="set <key> <value>":o.name==="call"&&(n="call <serviceName> <toolName>");let i=r.command(n).description(o.description);if(o.options)for(let a of o.options)i.option(a.flags,a.description,a.defaultValue);i.action(async(...a)=>{try{let v=a[a.length-1].opts();await o.execute(a.slice(0,-1),v)}catch(g){T.handle(g)}})}r.action(async(...o)=>{try{let i=o[o.length-1].opts();await t.execute(o.slice(0,-1),i)}catch(n){T.handle(n)}})}else{let r=t.name;t.name==="create"&&(r="create <projectName>");let o=e.command(r).description(t.description);if(t.options)for(let n of t.options)o.option(n.flags,n.description,n.defaultValue);o.action(async(...n)=>{try{let a=n[n.length-1].opts();await t.execute(n.slice(0,-1),a)}catch(i){T.handle(i)}})}}registerVersionCommand(e){let t=this.container.get("versionUtils");e.version(t.getVersion(),"-v, --version","\u663E\u793A\u7248\u672C\u4FE1\u606F"),e.option("--info","\u663E\u793A\u8BE6\u7EC6\u4FE1\u606F"),e.option("--version-info","\u663E\u793A\u8BE6\u7EC6\u7248\u672C\u4FE1\u606F")}registerHelpCommand(e){e.helpOption("-h, --help","\u663E\u793A\u5E2E\u52A9\u4FE1\u606F").addHelpText("after",`
|
|
15
15
|
\u793A\u4F8B:
|
|
16
16
|
xiaozhi init # \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6
|
|
17
17
|
xiaozhi start # \u542F\u52A8\u670D\u52A1\uFF08\u5305\u542B Web UI\uFF09
|
|
@@ -25,5 +25,5 @@ ${e.stack}`),r}static formatList(e,t="\u2022"){return e.map(r=>`${t} ${r}`).join
|
|
|
25
25
|
xiaozhi mcp list # \u5217\u51FA MCP \u670D\u52A1
|
|
26
26
|
|
|
27
27
|
\u66F4\u591A\u4FE1\u606F\u8BF7\u8BBF\u95EE: https://github.com/your-org/xiaozhi-client
|
|
28
|
-
`)}registerLegacyServiceCommands(e,t){let r=t.find(o=>o.name==="service");if(!(!r||!r.subcommands))for(let o of r.subcommands){let n=e.command(o.name).description(o.description);if(o.options)for(let i of o.options)n.option(i.flags,i.description,i.defaultValue);n.action(async(...i)=>{try{let g=i[i.length-1].opts();await o.execute(i.slice(0,-1),g)}catch(a){
|
|
28
|
+
`)}registerLegacyServiceCommands(e,t){let r=t.find(o=>o.name==="service");if(!(!r||!r.subcommands))for(let o of r.subcommands){let n=e.command(o.name).description(o.description);if(o.options)for(let i of o.options)n.option(i.flags,i.description,i.defaultValue);n.action(async(...i)=>{try{let g=i[i.length-1].opts();await o.execute(i.slice(0,-1),g)}catch(a){T.handle(a)}})}}};var Ce=new pt;async function ft(){try{let s=oe.create();await new ie(s).registerCommands(Ce),Ce.name("xiaozhi").description("\u5C0F\u667A MCP \u5BA2\u6237\u7AEF").helpOption("-h, --help","\u663E\u793A\u5E2E\u52A9\u4FE1\u606F"),await Ce.parseAsync(process.argv)}catch(s){T.handle(s)}}c(ft,"initializeCLI");ft();export{ft as initializeCLI};
|
|
29
29
|
//# sourceMappingURL=index.js.map
|