xiaozhi-client 2.0.0 → 2.1.0
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/Logger.js +2 -2
- package/dist/backend/Logger.js.map +1 -1
- package/dist/backend/WebServer.js +20 -20
- package/dist/backend/WebServer.js.map +1 -1
- package/dist/backend/WebServerLauncher.js +19 -19
- package/dist/backend/WebServerLauncher.js.map +1 -1
- package/dist/backend/package.json +12 -6
- package/dist/backend/templates/default/prompts/default.md +3 -0
- package/dist/backend/templates/default/xiaozhi.config.json +17 -6
- package/dist/backend/templates/hello-world/prompts/default.md +3 -0
- package/dist/backend/templates/hello-world/xiaozhi.config.json +17 -0
- package/dist/backend/templates/json5/prompts/default.md +3 -0
- package/dist/backend/templates/json5/xiaozhi.config.json5 +18 -0
- package/dist/backend/templates/jsonc/prompts/default.md +3 -0
- package/dist/backend/templates/jsonc/xiaozhi.config.jsonc +18 -0
- package/dist/backend/templates/modelscope/prompts/default.md +3 -0
- package/dist/backend/templates/modelscope/xiaozhi.config.json +17 -0
- package/dist/cli/index.js +18 -12
- package/dist/cli/index.js.map +1 -1
- package/dist/config/index.d.ts +5 -6
- package/dist/config/index.js +23 -32
- package/dist/config/index.js.map +1 -1
- package/dist/frontend/assets/index-BAV6nu4X.js +81 -0
- package/dist/frontend/assets/index-BAV6nu4X.js.map +1 -0
- package/dist/frontend/assets/index-HDlbxheg.css +1 -0
- package/dist/frontend/assets/{react-vendor-nhjYH1qO.js → react-vendor-BPQojLhf.js} +13 -13
- package/dist/frontend/assets/react-vendor-BPQojLhf.js.map +1 -0
- package/dist/frontend/assets/{utils-OFMjZRUK.js → utils-BWIWSmq9.js} +2 -2
- package/dist/frontend/assets/{utils-OFMjZRUK.js.map → utils-BWIWSmq9.js.map} +1 -1
- package/dist/frontend/index.html +4 -4
- package/package.json +11 -11
- package/templates/default/prompts/default.md +3 -0
- package/templates/default/xiaozhi.config.json +17 -6
- package/templates/hello-world/prompts/default.md +3 -0
- package/templates/hello-world/xiaozhi.config.json +17 -0
- package/templates/json5/prompts/default.md +3 -0
- package/templates/json5/xiaozhi.config.json5 +18 -0
- package/templates/jsonc/prompts/default.md +3 -0
- package/templates/jsonc/xiaozhi.config.jsonc +18 -0
- package/templates/modelscope/prompts/default.md +3 -0
- package/templates/modelscope/xiaozhi.config.json +17 -0
- package/dist/frontend/assets/index-DWj2UcGy.css +0 -1
- package/dist/frontend/assets/index-HnebiJM5.js +0 -81
- package/dist/frontend/assets/index-HnebiJM5.js.map +0 -1
- package/dist/frontend/assets/react-vendor-nhjYH1qO.js.map +0 -1
- package/dist/shared-types/api-B5HunvHc.d.ts +0 -97
- package/dist/shared-types/api.d.ts +0 -204
- package/dist/shared-types/api.js +0 -50
- package/dist/shared-types/api.js.map +0 -1
- package/dist/shared-types/app-Ceijcsur.d.ts +0 -95
- package/dist/shared-types/chunk-BMOKIX3Q.js +0 -51
- package/dist/shared-types/chunk-BMOKIX3Q.js.map +0 -1
- package/dist/shared-types/config.d.ts +0 -97
- package/dist/shared-types/config.js +0 -1
- package/dist/shared-types/config.js.map +0 -1
- package/dist/shared-types/coze.d.ts +0 -31
- package/dist/shared-types/coze.js +0 -1
- package/dist/shared-types/coze.js.map +0 -1
- package/dist/shared-types/index.d.ts +0 -188
- package/dist/shared-types/index.js +0 -23
- package/dist/shared-types/index.js.map +0 -1
- package/dist/shared-types/mcp.d.ts +0 -93
- package/dist/shared-types/mcp.js +0 -31
- package/dist/shared-types/mcp.js.map +0 -1
- package/dist/shared-types/message-BrlYWzXV.d.ts +0 -154
- package/dist/shared-types/schema-Bs4SCukS.d.ts +0 -25
- package/dist/shared-types/timeout-D1mc0P3r.d.ts +0 -39
- package/dist/shared-types/tool-definition-B6f-mWPy.d.ts +0 -93
- package/dist/shared-types/toolApi-D-G8Chst.d.ts +0 -200
- package/dist/shared-types/utils.d.ts +0 -115
- package/dist/shared-types/utils.js +0 -15
- package/dist/shared-types/utils.js.map +0 -1
- package/dist/shared-types/workflow-Dl-hsNZK.d.ts +0 -86
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
import{c as Is,d as $s,r as u,t as O,j as e,S as on,O as cn,P as Na,C as ln,a as un,D as dn,A as mn,b as fn,R as ya,e as Ca,f as hn,g as Ea,h as pn,i as xn,X as gn,k as vn,l as jn,m as Ra,n as Ta,u as Ps,o as lt,L as Se,W as sr,p as rr,q as ut,s as Sn,B as ka,v as Os,w as bn,x as Ia,F as $a,y as Ae,E as ye,G as Ce,H as wn,I as Pa,J as dt,K as Nn,M as Ls,N as yn,Q as Oa,U as Cn,V as La,Y as En,Z as Rn,_ as Aa,$ as mt,a0 as Ma,a1 as Tn,a2 as Da,a3 as qa,a4 as kn,a5 as In,a6 as $n,a7 as Ua,a8 as za,a9 as Fa,aa as Va,ab as Wa,ac as Pn,ad as _a,ae as On,af as tt,ag as Ba,ah as As,ai as nr,aj as Ms,ak as Cs,al as ar,am as Ln,an as Ga,ao as Ha,ap as Ja,aq as Xa,ar as Ya,as as Ds,at as An,au as Ka,av as Za,aw as Qa,ax as Mn,ay as eo,az as to,aA as or,aB as so,aC as ro,aD as no,aE as ao,aF as Ot,aG as ir,aH as oo,aI as io,aJ as co}from"./react-vendor-nhjYH1qO.js";import{t as lo,c as Dn,a as Pe,T as uo}from"./utils-OFMjZRUK.js";import{z as J,s as Ie,o as Ge,l as qs,d as mo,b as st,r as fo,c as cr,e as ho,_ as po,n as xo}from"./form-utils-Bskf0D3l.js";import"./radix-ui-BQCqNqg0.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function s(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=s(a);fetch(a.href,o)}})();class go{baseUrl;constructor(t){if(t)this.baseUrl=t;else{const s=window.location.protocol,n=window.location.hostname,a=window.location.port;this.baseUrl=`${s}//${n}${a?`:${a}`:""}`}}async request(t,s={}){const n=`${this.baseUrl}${t}`,a={headers:{"Content-Type":"application/json",...s.headers}},o=await fetch(n,{...a,...s});if(!o.ok){let i=`HTTP ${o.status}: ${o.statusText}`;try{i=(await o.json()).error?.message||i}catch{}throw new Error(i)}return o.json()}async getConfig(){const t=await this.request("/api/config");if(!t.success||!t.data)throw new Error("获取配置失败");return t.data}async updateConfig(t){const s=await this.request("/api/config",{method:"PUT",body:JSON.stringify(t)});if(!s.success)throw new Error(s.error?.message||"配置更新失败")}async getMcpEndpoint(){const t=await this.request("/api/config/mcp-endpoint");if(!t.success||!t.data)throw new Error("获取 MCP 端点失败");return t.data.endpoint}async getMcpEndpoints(){const t=await this.request("/api/config/mcp-endpoints");if(!t.success||!t.data)throw new Error("获取 MCP 端点列表失败");return t.data.endpoints}async getMcpServers(){const t=await this.request("/api/config/mcp-servers");if(!t.success||!t.data)throw new Error("获取 MCP 服务配置失败");return t.data.servers}async getConnectionConfig(){const t=await this.request("/api/config/connection");if(!t.success||!t.data)throw new Error("获取连接配置失败");return t.data.connection}async reloadConfig(){const t=await this.request("/api/config/reload",{method:"POST"});if(!t.success||!t.data)throw new Error("重新加载配置失败");return t.data}async getConfigPath(){const t=await this.request("/api/config/path");if(!t.success||!t.data)throw new Error("获取配置文件路径失败");return t.data.path}async checkConfigExists(){const t=await this.request("/api/config/exists");if(!t.success||t.data?.exists===void 0)throw new Error("检查配置是否存在失败");return t.data.exists}async getStatus(){const t=await this.request("/api/status");if(!t.success||!t.data)throw new Error("获取状态失败");return t.data}async getClientStatus(){const t=await this.request("/api/status/client");if(!t.success||!t.data)throw new Error("获取客户端状态失败");return t.data}async getRestartStatus(){const t=await this.request("/api/status/restart");if(!t.success)throw new Error("获取重启状态失败");return t.data||null}async checkClientConnected(){const t=await this.request("/api/status/connected");if(!t.success||t.data?.connected===void 0)throw new Error("检查客户端连接失败");return t.data.connected}async getLastHeartbeat(){const t=await this.request("/api/status/heartbeat");if(!t.success)throw new Error("获取最后心跳时间失败");return t.data?.lastHeartbeat||null}async getActiveMCPServers(){const t=await this.request("/api/status/mcp-servers");if(!t.success||!t.data)throw new Error("获取活跃 MCP 服务器失败");return t.data.servers}async updateClientStatus(t){const s=await this.request("/api/status/client",{method:"PUT",body:JSON.stringify(t)});if(!s.success)throw new Error(s.error?.message||"更新客户端状态失败")}async setActiveMCPServers(t){const s=await this.request("/api/status/mcp-servers",{method:"PUT",body:JSON.stringify({servers:t})});if(!s.success)throw new Error(s.error?.message||"设置活跃 MCP 服务器失败")}async resetStatus(){const t=await this.request("/api/status/reset",{method:"POST"});if(!t.success)throw new Error(t.error?.message||"重置状态失败")}async addCustomTool(t,s,n,a){if(typeof t=="object"&&"type"in t&&"data"in t){const d=await this.request("/api/tools/custom",{method:"POST",body:JSON.stringify(t)});if(!d.success||!d.data)throw new Error(d.error?.message||"添加自定义工具失败");return d.data.tool}const o=t,i=await this.request("/api/tools/custom",{method:"POST",body:JSON.stringify({workflow:o,customName:s,customDescription:n,parameterConfig:a})});if(!i.success||!i.data)throw new Error(i.error?.message||"添加自定义工具失败");return i.data.tool}async updateCustomTool(t,s){const n=await this.request(`/api/tools/custom/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(s)});if(!n.success||!n.data)throw new Error(n.error?.message||"更新自定义工具失败");return n.data.tool}async removeCustomTool(t){const s=await this.request(`/api/tools/custom/${encodeURIComponent(t)}`,{method:"DELETE"});if(!s.success)throw new Error(s.error?.message||"删除自定义工具失败")}async getCustomTools(){const t=await this.request("/api/tools/custom");if(!t.success||!t.data)throw new Error("获取自定义工具列表失败");return t.data.tools}async getToolsList(t="all",s){const n=new URLSearchParams;t!=="all"&&n.append("status",t),s&&n.append("sortBy",s.field);const a=`/api/tools/list${n.toString()?`?${n.toString()}`:""}`,o=await this.request(a);if(!o.success||!o.data)throw new Error("获取工具列表失败");return o.data.list}async restartService(){const t=await this.request("/api/services/restart",{method:"POST"});if(!t.success)throw new Error(t.error?.message||"重启服务失败")}async stopService(){const t=await this.request("/api/services/stop",{method:"POST"});if(!t.success)throw new Error(t.error?.message||"停止服务失败")}async startService(){const t=await this.request("/api/services/start",{method:"POST"});if(!t.success)throw new Error(t.error?.message||"启动服务失败")}async getServiceStatus(){const t=await this.request("/api/services/status");if(!t.success||!t.data)throw new Error("获取服务状态失败");return t.data}async getServiceHealth(){const t=await this.request("/api/services/health");if(!t.success||!t.data)throw new Error("获取服务健康状态失败");return t.data}async getVersion(){const t=await this.request("/api/version");if(!t.success||!t.data)throw new Error("获取版本信息失败");return t.data}async getVersionSimple(){const t=await this.request("/api/version/simple");if(!t.success||!t.data)throw new Error("获取版本号失败");return t.data}async getAvailableVersions(t="stable"){const s=new URLSearchParams;t!=="stable"&&s.append("type",t);const n=`/api/version/available${s.toString()?`?${s.toString()}`:""}`,a=await this.request(n);if(!a.success||!a.data)throw new Error("获取可用版本列表失败");return a.data}async getLatestVersion(){const t=await this.request("/api/version/latest");if(!t.success||!t.data)throw new Error("检查最新版本失败");return t.data}async clearVersionCache(){const t=await this.request("/api/version/cache/clear",{method:"POST"});if(!t.success)throw new Error(t.error?.message||"清除版本缓存失败")}async updateVersion(t){const s=await this.request("/api/update",{method:"POST",body:JSON.stringify({version:t})});if(!s.success)throw new Error(s.error?.message||"版本更新失败");return s.data}async getEndpointStatus(t){const s=await this.request("/api/endpoint/status",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success||!s.data)throw new Error("获取接入点状态失败");return s.data}async connectEndpoint(t){const s=await this.request("/api/endpoint/connect",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success)throw new Error(s.error?.message||"连接接入点失败")}async disconnectEndpoint(t){const s=await this.request("/api/endpoint/disconnect",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success)throw new Error(s.error?.message||"断开接入点失败")}async reconnectEndpoint(t){const s=await this.request("/api/endpoint/reconnect",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success)throw new Error(s.error?.message||"重连接入点失败")}async addEndpoint(t){const s=await this.request("/api/endpoint/add",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success||!s.data)throw new Error(s.error?.message||"添加接入点失败");return s.data}async removeEndpoint(t){const s=await this.request("/api/endpoint/remove",{method:"POST",body:JSON.stringify({endpoint:t})});if(!s.success)throw new Error(s.error?.message||"移除接入点失败")}async addMCPServer(t,s){const n={name:t,config:s},a=await this.request("/api/mcp-servers",{method:"POST",body:JSON.stringify(n)});if(!a.success||!a.data)throw new Error(a.error?.message||"添加 MCP 服务器失败");return a.data}async removeMCPServer(t){const s=await this.request(`/api/mcp-servers/${encodeURIComponent(t)}`,{method:"DELETE"});if(!s.success||!s.data)throw new Error(s.error?.message||"删除 MCP 服务器失败");return s.data}async getMCPServerStatus(t){const s=await this.request(`/api/mcp-servers/${encodeURIComponent(t)}/status`);if(!s.success||!s.data)throw new Error(s.error?.message||"获取 MCP 服务器状态失败");return s.data}async listMCPServers(){const t=await this.request("/api/mcp-servers");if(!t.success||!t.data)throw new Error(t.error?.message||"获取 MCP 服务器列表失败");return t.data}async checkMCPServerExists(t){try{const s=await this.request(`/api/mcp-servers/${encodeURIComponent(t)}/exists`);return s.success&&s.data?.exists||!1}catch(s){if(s instanceof Error&&s.message.includes("404"))return!1;throw s}}async updateMCPServer(t,s){const n=await this.request(`/api/mcp-servers/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({config:s})});if(!n.success||!n.data)throw new Error(n.error?.message||"更新 MCP 服务器配置失败");return n.data}async callTool(t,s,n={}){const a=await this.request("/api/tools/call",{method:"POST",body:JSON.stringify({serviceName:t,toolName:s,args:n})});if(!a.success)throw new Error(a.error?.message||"调用工具失败");return a.data}async restartMCPServer(t){const s=await this.request(`/api/mcp-servers/${encodeURIComponent(t)}/restart`,{method:"POST"});if(!s.success||!s.data)throw new Error(s.error?.message||"重启 MCP 服务器失败");return s.data}async manageMCPTool(t){const s=await this.request("/api/tools/mcp/manage",{method:"POST",body:JSON.stringify(t)});if(!s.success||!s.data)throw new Error(s.error?.message||"MCP 工具管理操作失败");return s.data}async listMCPTools(t){const s=await this.request("/api/tools/mcp/list",{method:"POST",body:JSON.stringify(t||{})});if(!s.success||!s.data)throw new Error(s.error?.message||"获取 MCP 工具列表失败");return s.data}}const U=new go,qn=1e3;var Q=(r=>(r.DISCONNECTED="disconnected",r.CONNECTING="connecting",r.CONNECTED="connected",r.RECONNECTING="reconnecting",r))(Q||{});class vo{listeners=new Map;on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>{this.off(t,s)}}off(t,s){const n=this.listeners.get(t);n&&(n.delete(s),n.size===0&&this.listeners.delete(t))}emit(t,s){const n=this.listeners.get(t);if(n)for(const a of n)try{a(s)}catch(o){console.error(`[EventBus] 事件监听器执行失败 (${t}):`,o)}}clear(){this.listeners.clear()}getListenerCount(t){return t?this.listeners.get(t)?.size||0:Array.from(this.listeners.values()).reduce((s,n)=>s+n.size,0)}}class Z{static instance=null;static isCreating=!1;ws=null;url;state="disconnected";eventBus=new vo;reconnectAttempts=0;maxReconnectAttempts;reconnectInterval;reconnectTimer;heartbeatTimer;heartbeatInterval;heartbeatTimeout;lastHeartbeat=0;constructor(t={}){this.url=t.url||this.getDefaultWebSocketUrl(),this.maxReconnectAttempts=t.maxReconnectAttempts||5,this.reconnectInterval=t.reconnectInterval||3e3,this.heartbeatInterval=t.heartbeatInterval||3e4,this.heartbeatTimeout=t.heartbeatTimeout||35e3}static getInstance(t){if(Z.instance)return Z.instance;if(Z.isCreating)throw new Error("[WebSocketManager] 检测到循环创建,请检查代码逻辑");Z.isCreating=!0;try{return Z.instance=new Z(t),console.log("[WebSocketManager] 单例实例已创建"),Z.instance}finally{Z.isCreating=!1}}static resetInstance(){Z.instance&&(Z.instance.disconnect(),Z.instance.eventBus.clear(),Z.instance=null,console.log("[WebSocketManager] 单例实例已重置"))}getDefaultWebSocketUrl(){const t=localStorage.getItem("xiaozhi-ws-url");if(t)return t;const s=window.location.protocol==="https:"?"wss:":"ws:",n=window.location.hostname;return`${s}//${n}:9999`}connect(){if(!(this.state==="connected"||this.state==="connecting")){this.state="connecting",console.log(`[WebSocket] 连接到: ${this.url}`),this.eventBus.emit("connection:connecting",void 0);try{this.ws=new WebSocket(this.url),this.setupEventHandlers()}catch(t){console.error("[WebSocket] 连接失败:",t),this.handleConnectionError(t)}}}disconnect(){console.log("[WebSocket] 主动断开连接"),this.clearTimers(),this.state="disconnected",this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}subscribe(t,s){return this.eventBus.on(t,s)}unsubscribe(t,s){this.eventBus.off(t,s)}getEventBus(){return this.eventBus}getState(){return this.state}isConnected(){return this.state==="connected"&&this.ws?.readyState===WebSocket.OPEN}setUrl(t){this.url!==t&&(this.url=t,localStorage.setItem("xiaozhi-ws-url",t),this.isConnected()&&(this.disconnect(),setTimeout(()=>this.connect(),qn)))}send(t){if(!this.isConnected())return console.warn("[WebSocket] 连接未建立,无法发送消息"),!1;try{const s=typeof t=="string"?t:JSON.stringify(t);return this.ws.send(s),!0}catch(s){return console.error("[WebSocket] 发送消息失败:",s),this.eventBus.emit("connection:error",{error:s,context:"send_message"}),!1}}getUrl(){return this.url}getConnectionStats(){return{state:this.state,url:this.url,reconnectAttempts:this.reconnectAttempts,maxReconnectAttempts:this.maxReconnectAttempts,lastHeartbeat:this.lastHeartbeat,eventListenerCount:this.eventBus.getListenerCount()}}setupEventHandlers(){this.ws&&(this.ws.onopen=()=>{console.log("[WebSocket] 连接已建立"),this.state="connected",this.reconnectAttempts=0,this.startHeartbeat(),this.eventBus.emit("connection:connected",void 0)},this.ws.onmessage=t=>{try{const s=JSON.parse(t.data);this.handleMessage(s)}catch(s){console.error("[WebSocket] 消息解析失败:",s)}},this.ws.onclose=t=>{console.log(`[WebSocket] 连接已关闭 (code: ${t.code})`),this.handleConnectionClose()},this.ws.onerror=t=>{console.error("[WebSocket] 连接错误:",t),this.handleConnectionError(new Error("WebSocket 连接错误"))})}handleMessage(t){console.log("[WebSocket] 收到消息:",t.type),this.eventBus.emit("system:message",t);try{switch(t.type){case"configUpdate":case"config":t.data&&this.eventBus.emit("data:configUpdate",t.data);break;case"statusUpdate":case"status":t.data&&this.eventBus.emit("data:statusUpdate",t.data);break;case"restartStatus":t.data&&this.eventBus.emit("data:restartStatus",t.data);break;case"endpoint_status_changed":t.data&&this.eventBus.emit("data:endpointStatusChanged",t.data);break;case"npm:install:started":t.data&&this.eventBus.emit("data:npmInstallStarted",t.data);break;case"npm:install:log":t.data&&this.eventBus.emit("data:npmInstallLog",t.data);break;case"npm:install:completed":t.data&&this.eventBus.emit("data:npmInstallCompleted",t.data);break;case"npm:install:failed":t.data&&this.eventBus.emit("data:npmInstallFailed",t.data);break;case"heartbeatResponse":this.lastHeartbeat=Date.now(),this.eventBus.emit("system:heartbeat",{timestamp:this.lastHeartbeat});break;case"error":{const s=new Error(t.error?.message||"服务器错误");console.error("[WebSocket] 服务器错误:",t.error),this.eventBus.emit("system:error",{error:s,message:t}),this.eventBus.emit("connection:error",{error:s,context:"server_error"});break}default:console.log("[WebSocket] 未处理的消息类型:",t.type)}}catch(s){console.error("[WebSocket] 消息处理失败:",s),this.eventBus.emit("system:error",{error:s,message:t})}}handleConnectionClose(){this.state="disconnected",this.clearTimers(),this.eventBus.emit("connection:disconnected",void 0),this.reconnectAttempts<this.maxReconnectAttempts?this.scheduleReconnect():(console.error("[WebSocket] 达到最大重连次数,停止重连"),this.eventBus.emit("connection:error",{error:new Error("达到最大重连次数"),context:"max_reconnect_attempts"}))}handleConnectionError(t){this.state="disconnected",this.clearTimers(),this.eventBus.emit("connection:error",{error:t,context:"connection_error"}),this.reconnectAttempts<this.maxReconnectAttempts?this.scheduleReconnect():console.error("[WebSocket] 达到最大重连次数,停止重连")}scheduleReconnect(){this.reconnectAttempts++,this.state="reconnecting",console.log(`[WebSocket] 安排重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts}) 在 ${this.reconnectInterval}ms 后`),this.eventBus.emit("connection:reconnecting",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}),this.reconnectTimer=setTimeout(()=>{this.connect()},this.reconnectInterval)}startHeartbeat(){this.lastHeartbeat=Date.now(),this.heartbeatTimer=setInterval(()=>{this.isConnected()&&(this.sendHeartbeat(),Date.now()-this.lastHeartbeat>this.heartbeatTimeout&&(console.warn("[WebSocket] 心跳超时,重新连接"),this.disconnect(),this.connect()))},this.heartbeatInterval)}sendHeartbeat(){if(this.isConnected()){const t={type:"clientStatus",data:{status:"connected",timestamp:Date.now()}};this.ws?.send(JSON.stringify(t))}}clearTimers(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}}const z=Z.getInstance(),lr={clientStatus:null,restartStatus:null,serviceStatus:null,serviceHealth:null,fullStatus:null,loading:{isLoading:!1,isRefreshing:!1,isRestarting:!1,lastUpdated:null,lastError:null},polling:{enabled:!1,interval:3e4,maxRetries:3,currentRetries:0},restartPolling:{enabled:!1,interval:1e3,maxAttempts:60,currentAttempts:0,timeout:6e4,startTime:null},lastSource:null};let rt=null,nt=null;const je=Is()($s((r,t)=>({...lr,setClientStatus:(s,n="http")=>{console.log(`[StatusStore] 设置客户端状态,来源: ${n}`),r(a=>({clientStatus:s,lastSource:n,loading:{...a.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setClientStatus")},setRestartStatus:(s,n="http")=>{console.log(`[StatusStore] 设置重启状态,来源: ${n}`),r(a=>({restartStatus:s,lastSource:n,loading:{...a.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setRestartStatus")},setServiceStatus:s=>{console.log("[StatusStore] 设置服务状态"),r({serviceStatus:s},!1,"setServiceStatus")},setServiceHealth:s=>{console.log("[StatusStore] 设置服务健康状态"),r({serviceHealth:s},!1,"setServiceHealth")},setFullStatus:(s,n="http")=>{console.log(`[StatusStore] 设置完整状态,来源: ${n}`),r(a=>({fullStatus:s,clientStatus:s.client,restartStatus:s.restart||null,lastSource:n,loading:{...a.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setFullStatus")},setLoading:s=>{r(n=>({loading:{...n.loading,...s}}),!1,"setLoading")},setError:s=>{r(n=>({loading:{...n.loading,lastError:s}}),!1,"setError")},getStatus:async()=>{const{fullStatus:s,loading:n}=t();return s&&n.lastUpdated&&Date.now()-n.lastUpdated<30*1e3?s:t().refreshStatus()},refreshStatus:async()=>{const{setLoading:s,setFullStatus:n,setError:a,polling:o}=t();try{s({isRefreshing:!0,lastError:null}),console.log("[StatusStore] 开始刷新状态");const i=await U.getStatus();return n(i,"http"),o.enabled&&t().setPollingConfig({currentRetries:0}),console.log("[StatusStore] 状态刷新成功"),i}catch(i){const d=i instanceof Error?i:new Error("状态刷新失败");if(console.error("[StatusStore] 状态刷新失败:",d),a(d),o.enabled){const l=o.currentRetries+1;t().setPollingConfig({currentRetries:l}),l>=o.maxRetries&&(console.warn("[StatusStore] 达到最大重试次数,停止轮询"),t().stopPolling())}throw d}finally{s({isRefreshing:!1})}},restartService:async()=>{const{setLoading:s,setRestartStatus:n,setError:a,startRestartPolling:o}=t();try{s({isRestarting:!0,lastError:null}),console.log("[StatusStore] 开始重启服务"),n({status:"restarting",timestamp:Date.now()},"http"),await U.restartService(),console.log("[StatusStore] 服务重启请求已发送,开始重连检查"),o()}catch(i){const d=i instanceof Error?i:new Error("服务重启失败");throw console.error("[StatusStore] 服务重启失败:",d),n({status:"failed",error:d.message,timestamp:Date.now()},"http"),a(d),s({isRestarting:!1}),d}},getServiceStatus:async()=>{try{console.log("[StatusStore] 获取服务状态");const s=await U.getServiceStatus();return t().setServiceStatus(s),s}catch(s){const n=s instanceof Error?s:new Error("获取服务状态失败");throw console.error("[StatusStore] 获取服务状态失败:",n),t().setError(n),n}},getServiceHealth:async()=>{try{console.log("[StatusStore] 获取服务健康状态");const s=await U.getServiceHealth();return t().setServiceHealth(s),s}catch(s){const n=s instanceof Error?s:new Error("获取服务健康状态失败");throw console.error("[StatusStore] 获取服务健康状态失败:",n),t().setError(n),n}},startPolling:(s=3e4)=>{const{polling:n,refreshStatus:a}=t();if(n.enabled){console.log("[StatusStore] 轮询已启用,跳过启动");return}console.log(`[StatusStore] 启动状态轮询,间隔: ${s}ms`),r(o=>({polling:{...o.polling,enabled:!0,interval:s,currentRetries:0}}),!1,"startPolling"),a().catch(o=>{console.error("[StatusStore] 轮询初始刷新失败:",o)}),rt=setInterval(()=>{t().polling.enabled&&a().catch(i=>{console.error("[StatusStore] 轮询刷新失败:",i)})},s)},stopPolling:()=>{console.log("[StatusStore] 停止状态轮询"),r(s=>({polling:{...s.polling,enabled:!1,currentRetries:0}}),!1,"stopPolling"),rt&&(clearInterval(rt),rt=null)},setPollingConfig:s=>{r(n=>({polling:{...n.polling,...s}}),!1,"setPollingConfig")},startRestartPolling:()=>{const{restartPolling:s,refreshStatus:n,setRestartStatus:a,setLoading:o}=t();if(s.enabled){console.log("[StatusStore] 重启轮询已启用,跳过启动");return}console.log("[StatusStore] 启动重启后重连检查轮询");const i=Date.now();r(d=>({restartPolling:{...d.restartPolling,enabled:!0,currentAttempts:0,startTime:i}}),!1,"startRestartPolling"),nt=setInterval(async()=>{const d=t(),{restartPolling:l}=d;if(!l.enabled)return;const m=Date.now()-(l.startTime||0),c=l.currentAttempts+1;console.log(`[StatusStore] 重启重连检查 (第 ${c} 次,已用时 ${Math.round(m/1e3)}s)`);try{if((await n()).client?.status==="connected"){console.log("[StatusStore] 服务重连成功,停止重启轮询"),a({status:"completed",timestamp:Date.now()},"polling"),d.stopRestartPolling(),o({isRestarting:!1});return}d.setRestartPollingConfig({currentAttempts:c}),(m>=l.timeout||c>=l.maxAttempts)&&(console.warn("[StatusStore] 重启重连检查超时或达到最大尝试次数"),a({status:"failed",error:"重连超时,服务可能未成功重启",timestamp:Date.now()},"polling"),d.stopRestartPolling(),o({isRestarting:!1}))}catch(p){console.log(`[StatusStore] 重启重连检查失败 (第 ${c} 次):`,p),d.setRestartPollingConfig({currentAttempts:c}),(m>=l.timeout||c>=l.maxAttempts)&&(console.error("[StatusStore] 重启重连检查超时或达到最大尝试次数"),a({status:"failed",error:"重连超时,服务可能未成功重启",timestamp:Date.now()},"polling"),d.stopRestartPolling(),o({isRestarting:!1}))}},s.interval)},stopRestartPolling:()=>{console.log("[StatusStore] 停止重启轮询"),r(s=>({restartPolling:{...s.restartPolling,enabled:!1,currentAttempts:0,startTime:null}}),!1,"stopRestartPolling"),nt&&(clearInterval(nt),nt=null)},setRestartPollingConfig:s=>{r(n=>({restartPolling:{...n.restartPolling,...s}}),!1,"setRestartPollingConfig")},reset:()=>{console.log("[StatusStore] 重置状态"),t().stopPolling(),t().stopRestartPolling(),r(lr,!1,"reset")},initialize:async()=>{const{setLoading:s,refreshStatus:n}=t();try{s({isLoading:!0}),console.log("[StatusStore] 初始化状态 Store"),z.subscribe("data:statusUpdate",a=>{console.log("[StatusStore] 收到 WebSocket 状态更新"),t().setClientStatus(a,"websocket")}),z.subscribe("data:restartStatus",a=>{console.log("[StatusStore] 收到 WebSocket 重启状态更新"),t().setRestartStatus(a,"websocket")}),await n(),console.log("[StatusStore] 状态 Store 初始化完成")}catch(a){throw console.error("[StatusStore] 状态 Store 初始化失败:",a),a}finally{s({isLoading:!1})}}}),{name:"status-store"})),jo=()=>je(r=>r.restartStatus),Un=()=>je(r=>r.restartPolling);function So(){const r=jo(),t=Un(),s=u.useRef(null),n=u.useRef(null);u.useEffect(()=>{if(!r)return;const{status:a,timestamp:o,error:i}=r;if(!(s.current===a&&n.current===o))switch(s.current=a,n.current=o,a){case"restarting":O.info("正在重启服务...",{id:"restart-status-progress",description:"请耐心等待",duration:0});break;case"completed":{const d=t.enabled?`服务重启成功!重连检查完成 (${t.currentAttempts}次检查)`:"服务重启成功!";O.dismiss("restart-status-progress"),O.success(d,{id:"restart-status-success",description:"服务已恢复正常运行"});break}case"failed":{const d=i||"服务重启失败",l=t.enabled?`重连检查超时 (${t.currentAttempts}/${t.maxAttempts}次)`:"请检查服务状态或稍后重试";O.dismiss("restart-status-progress"),O.error(d,{id:"restart-status-failed",description:l});break}}},[r,t]),u.useEffect(()=>()=>{s.current=null,n.current=null},[])}function bo(){return So(),null}function ft({showValue:r=!0,value:t=0,maxValue:s=100,size:n=60,activeColor:a="#3b82f6",inactiveColor:o="#e5e7eb",symbol:i="%",ariaLabel:d}){const l=(n-6)/2,m=l*2*Math.PI,c=m,p=s===0?m:m-t/s*m;return e.jsxs("div",{className:"relative inline-flex items-center justify-center",role:"progressbar",tabIndex:0,"aria-valuenow":t,"aria-valuemin":0,"aria-valuemax":s,"aria-label":d||`进度:${t}/${s}`,children:[e.jsxs("svg",{width:n,height:n,className:"transform -rotate-90",children:[e.jsx("circle",{cx:n/2,cy:n/2,r:l,stroke:o,strokeWidth:6,fill:"none"}),e.jsx("circle",{cx:n/2,cy:n/2,r:l,stroke:a,strokeWidth:6,fill:"none",strokeDasharray:c,strokeDashoffset:p,strokeLinecap:"round",className:"transition-all duration-300 ease-in-out"})]}),r&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{className:"text-xs font-medium",children:[t,i]})})]})}function R(...r){return lo(Dn(r))}const wo=Pe("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function de({className:r,variant:t,...s}){return e.jsx("div",{className:R(wo({variant:t}),r),...s})}const ht=Pe("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),A=u.forwardRef(({className:r,variant:t,size:s,asChild:n=!1,...a},o)=>{const i=n?on:"button";return e.jsx(i,{className:R(ht({variant:t,size:s,className:r})),ref:o,...a})});A.displayName="Button";const Us=ya,No=Ca,yo=Na,zn=u.forwardRef(({className:r,...t},s)=>e.jsx(cn,{className:R("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",r),...t,ref:s}));zn.displayName=cn.displayName;const pt=u.forwardRef(({className:r,...t},s)=>e.jsxs(yo,{children:[e.jsx(zn,{}),e.jsx(ln,{ref:s,className:R("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",r),...t})]}));pt.displayName=ln.displayName;const xt=({className:r,...t})=>e.jsx("div",{className:R("flex flex-col space-y-2 text-center sm:text-left",r),...t});xt.displayName="AlertDialogHeader";const gt=({className:r,...t})=>e.jsx("div",{className:R("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",r),...t});gt.displayName="AlertDialogFooter";const vt=u.forwardRef(({className:r,...t},s)=>e.jsx(un,{ref:s,className:R("text-lg font-semibold",r),...t}));vt.displayName=un.displayName;const jt=u.forwardRef(({className:r,...t},s)=>e.jsx(dn,{ref:s,className:R("text-sm text-muted-foreground",r),...t}));jt.displayName=dn.displayName;const St=u.forwardRef(({className:r,...t},s)=>e.jsx(mn,{ref:s,className:R(ht(),r),...t}));St.displayName=mn.displayName;const bt=u.forwardRef(({className:r,...t},s)=>e.jsx(fn,{ref:s,className:R(ht({variant:"outline"}),"mt-2 sm:mt-0",r),...t}));bt.displayName=fn.displayName;const me=Ra,ke=Ta,Co=Ea,He=xn,Fn=u.forwardRef(({className:r,...t},s)=>e.jsx(hn,{ref:s,className:R("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",r),...t}));Fn.displayName=hn.displayName;const oe=u.forwardRef(({className:r,children:t,...s},n)=>e.jsxs(Co,{children:[e.jsx(Fn,{}),e.jsxs(pn,{ref:n,className:R("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",r),...s,children:[t,e.jsxs(xn,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e.jsx(gn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));oe.displayName=pn.displayName;const ie=({className:r,...t})=>e.jsx("div",{className:R("flex flex-col space-y-1.5 text-center sm:text-left",r),...t});ie.displayName="DialogHeader";const Oe=({className:r,...t})=>e.jsx("div",{className:R("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",r),...t});Oe.displayName="DialogFooter";const ce=u.forwardRef(({className:r,...t},s)=>e.jsx(vn,{ref:s,className:R("text-lg font-semibold leading-none tracking-tight",r),...t}));ce.displayName=vn.displayName;const Ee=u.forwardRef(({className:r,...t},s)=>e.jsx(jn,{ref:s,className:R("text-sm text-muted-foreground",r),...t}));Ee.displayName=jn.displayName;const se=u.forwardRef(({className:r,type:t,...s},n)=>e.jsx("input",{type:t,className:R("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",r),ref:n,"data-1p-ignore":!0,...s}));se.displayName="Input";const ur={config:null,loading:{isLoading:!1,isUpdating:!1,isRefreshing:!1,lastUpdated:null,lastError:null},lastSource:null,mcpServerStatuses:[],mcpServerStatusLoading:!1,mcpServerStatusLastUpdate:null},xe=Is()($s((r,t)=>({...ur,setConfig:(s,n="http")=>{console.log(`[ConfigStore] 设置配置数据,来源: ${n}`),r(a=>({config:s,lastSource:n,loading:{...a.loading,lastUpdated:Date.now(),lastError:null}}),!1,"setConfig")},setLoading:s=>{r(n=>({loading:{...n.loading,...s}}),!1,"setLoading")},setError:s=>{r(n=>({loading:{...n.loading,lastError:s}}),!1,"setError")},getConfig:async()=>{const{config:s,loading:n}=t();return s&&n.lastUpdated&&Date.now()-n.lastUpdated<300*1e3?s:t().refreshConfig()},updateConfig:async s=>{const{setLoading:n,setConfig:a,setError:o}=t();try{n({isUpdating:!0,lastError:null}),console.log("[ConfigStore] 开始更新配置"),await U.updateConfig(s),a(s,"http"),console.log("[ConfigStore] 配置更新成功")}catch(i){const d=i instanceof Error?i:new Error("配置更新失败");throw console.error("[ConfigStore] 配置更新失败:",d),o(d),d}finally{n({isUpdating:!1})}},refreshConfig:async()=>{const{setLoading:s,setConfig:n,setError:a}=t();try{s({isRefreshing:!0,lastError:null}),console.log("[ConfigStore] 开始刷新配置");const o=await U.getConfig();return n(o,"http"),console.log("[ConfigStore] 配置刷新成功"),o}catch(o){const i=o instanceof Error?o:new Error("配置刷新失败");throw console.error("[ConfigStore] 配置刷新失败:",i),a(i),i}finally{s({isRefreshing:!1})}},reloadConfig:async()=>{const{setLoading:s,setConfig:n,setError:a}=t();try{s({isRefreshing:!0,lastError:null}),console.log("[ConfigStore] 开始重新加载配置");const o=await U.reloadConfig();return n(o,"http"),console.log("[ConfigStore] 配置重新加载成功"),o}catch(o){const i=o instanceof Error?o:new Error("配置重新加载失败");throw console.error("[ConfigStore] 配置重新加载失败:",i),a(i),i}finally{s({isRefreshing:!1})}},updateMcpEndpoint:async s=>{const{config:n,updateConfig:a}=t();if(!n)throw new Error("配置未加载,无法更新 MCP 端点");const o={...n,mcpEndpoint:s};await a(o)},updateMcpServers:async s=>{const{config:n,updateConfig:a}=t();if(!n)throw new Error("配置未加载,无法更新 MCP 服务");const o={...n,mcpServers:s};await a(o)},updateConnectionConfig:async s=>{const{config:n,updateConfig:a}=t();if(!n)throw new Error("配置未加载,无法更新连接配置");const o={...n,connection:s};await a(o)},updateModelScopeConfig:async s=>{const{config:n,updateConfig:a}=t();if(!n)throw new Error("配置未加载,无法更新 ModelScope 配置");const o={...n,modelscope:s};await a(o)},updateWebUIConfig:async s=>{const{config:n,updateConfig:a}=t();if(!n)throw new Error("配置未加载,无法更新 Web UI 配置");const o={...n,webUI:s};await a(o)},reset:()=>{console.log("[ConfigStore] 重置状态"),r(ur,!1,"reset")},initialize:async()=>{const{setLoading:s,refreshConfig:n}=t();try{s({isLoading:!0}),console.log("[ConfigStore] 初始化配置 Store"),z.subscribe("data:configUpdate",a=>{console.log("[ConfigStore] 收到 WebSocket 配置更新"),t().setConfig(a,"websocket")}),await n(),console.log("[ConfigStore] 配置 Store 初始化完成")}catch(a){throw console.error("[ConfigStore] 配置 Store 初始化失败:",a),a}finally{s({isLoading:!1})}},setMcpServerStatuses:s=>{r(()=>({mcpServerStatuses:s,mcpServerStatusLastUpdate:Date.now()}),!1,"setMcpServerStatuses")},setMcpServerStatusLoading:s=>{r(()=>({mcpServerStatusLoading:s}),!1,"setMcpServerStatusLoading")},refreshMcpServerStatuses:async()=>{const s=t(),{setMcpServerStatuses:n,setMcpServerStatusLoading:a,setConfig:o}=s;try{a(!0),console.log("[ConfigStore] 开始刷新 MCP 服务器状态");const i=await U.listMCPServers();if(n(i.servers),s.config){const d={};for(const l of i.servers)d[l.name]=l.config;o({...s.config,mcpServers:d},"http")}return console.log(`[ConfigStore] MCP 服务器状态刷新成功,共 ${i.servers.length} 个服务器`),i.servers}catch(i){const d=i instanceof Error?i:new Error("MCP 服务器状态刷新失败");throw console.error("[ConfigStore] MCP 服务器状态刷新失败:",d),n([]),d}finally{a(!1)}},getMcpServerStatus:s=>t().mcpServerStatuses.find(n=>n.name===s)}),{name:"config-store"})),Je=()=>xe(r=>r.config),Vn=()=>xe(r=>r.config?.mcpEndpoint),Eo=()=>xe(Ps(r=>({getConfig:r.getConfig,updateConfig:r.updateConfig,refreshConfig:r.refreshConfig,reloadConfig:r.reloadConfig,updateMcpEndpoint:r.updateMcpEndpoint,updateMcpServers:r.updateMcpServers,updateConnectionConfig:r.updateConnectionConfig,updateModelScopeConfig:r.updateModelScopeConfig,updateWebUIConfig:r.updateWebUIConfig,reset:r.reset,initialize:r.initialize}))),Wn=()=>xe(Ps(r=>({servers:r.mcpServerStatuses,loading:r.mcpServerStatusLoading,refresh:r.refreshMcpServerStatuses,lastUpdate:r.mcpServerStatusLastUpdate}))),dr=r=>`${r.slice(0,30)}...${r.slice(-10)}`,Ro=r=>{if(!r.trim())return"请输入接入点地址";if(!r.startsWith("ws://")&&!r.startsWith("wss://"))return"接入点格式无效,请输入正确的WebSocket URL (ws:// 或 wss://)";try{new URL(r)}catch{return"接入点格式无效,请输入正确的URL格式"}return null};function To(){const[r,t]=u.useState(!1),[s,n]=u.useState(!1),[a,o]=u.useState(""),[i,d]=u.useState(!1),[l,m]=u.useState(!1),[c,p]=u.useState(""),[h,x]=u.useState(!1),[v,g]=u.useState(""),[$,k]=u.useState({}),N=Je(),y=Vn(),{refreshConfig:P}=Eo(),E=u.useCallback(async f=>{try{return await U.getEndpointStatus(f)}catch(j){return console.error(`获取接入点状态失败: ${f}`,j),{endpoint:f,connected:!1,initialized:!1,isReconnecting:!1,reconnectAttempts:0,reconnectDelay:0}}},[]),I=u.useCallback((f,j)=>{k(w=>({...w,[f]:{...w[f],...j}}))},[]),M=u.useCallback(async f=>{const j={};for(const w of f)try{const T=await E(w);j[w]={connected:T.connected,isOperating:!1,lastOperation:{type:null,success:!1,message:"",timestamp:0}}}catch{j[w]={connected:!1,isOperating:!1,lastOperation:{type:null,success:!1,message:"",timestamp:0}}}k(j)},[E]),L=async f=>{I(f,{isOperating:!0});try{await U.connectEndpoint(f),I(f,{connected:!0,isOperating:!1,lastOperation:{type:"connect",success:!0,message:"连接成功",timestamp:Date.now()}}),O.success("接入点连接成功")}catch(j){I(f,{isOperating:!1,lastOperation:{type:"connect",success:!1,message:j instanceof Error?j.message:"连接失败",timestamp:Date.now()}}),O.error(j instanceof Error?j.message:"接入点连接失败")}},V=async f=>{I(f,{isOperating:!0});try{await U.disconnectEndpoint(f),I(f,{connected:!1,isOperating:!1,lastOperation:{type:"disconnect",success:!0,message:"断开成功",timestamp:Date.now()}}),O.success("接入点断开成功")}catch(j){I(f,{isOperating:!1,lastOperation:{type:"disconnect",success:!1,message:j instanceof Error?j.message:"断开失败",timestamp:Date.now()}}),O.error(j instanceof Error?j.message:"接入点断开失败")}},H=async f=>{try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(f),O.success("接入点地址已复制到剪贴板");else{const j=document.createElement("textarea");j.value=f,j.style.position="fixed",j.style.opacity="0",document.body.appendChild(j),j.select();const w=document.execCommand("copy");if(document.body.removeChild(j),w)O.success("接入点地址已复制到剪贴板");else throw new Error("复制命令执行失败")}}catch(j){console.error("复制失败:",j),O.error("复制失败,请手动复制")}},te=async()=>{d(!0);try{await U.removeEndpoint(a),await P(),k(f=>{const j={...f};return delete j[a],j}),O.success("接入点已删除"),n(!1),o("")}catch(f){console.error("删除接入点失败:",f),O.error(f instanceof Error?f.message:"删除接入点失败")}finally{d(!1)}},le=async()=>{const f=Ro(c);if(f){g(f);return}if((Array.isArray(y)?y:[y]).includes(c)){g("该接入点已存在");return}if(!N){O.error("配置数据未加载,请稍后重试");return}x(!0);try{const w=await U.addEndpoint(c);await P(),k(T=>({...T,[c]:{connected:w.connected,isOperating:!1,lastOperation:{type:null,success:!1,message:"",timestamp:0}}})),O.success("接入点添加成功"),m(!1),p(""),g("")}catch(w){console.error("添加接入点失败:",w),O.error(w instanceof Error?w.message:"添加接入点失败")}finally{x(!1)}},ue=()=>{p(""),g(""),m(!0)},S=f=>{p(f),v&&g("")},b=f=>{o(f),n(!0)},C=u.useMemo(()=>{let f=[];return Array.isArray(y)&&(f=y),typeof y=="string"&&y.length&&f.push(y),f},[y]);return u.useEffect(()=>{r&&C.length>0&&M(C)},[r,C,M]),u.useEffect(()=>{if(!r||C.length===0)return;const f=C.map(j=>z.subscribe("data:endpointStatusChanged",T=>{T.endpoint===j&&(console.log(`[McpEndpointSettingButton] 接收到端点 ${j} 状态变更:`,T),I(j,{connected:T.connected,isOperating:!1,lastOperation:{type:T.operation,success:T.success,message:T.message||(T.connected?"连接成功":"断开成功"),timestamp:T.timestamp}}),T.success?O.success(`端点 ${T.operation==="connect"?"连接":T.operation==="disconnect"?"断开":"重连"}成功`):O.error(`端点 ${T.operation==="connect"?"连接":T.operation==="disconnect"?"断开":"重连"}失败: ${T.message||"未知错误"}`))}));return()=>{for(const j of f)j()}},[r,C,I]),e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(ke,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8",children:e.jsx(lt,{className:"size-4"})})}),e.jsxs(oe,{className:"min-w-[600px] max-w-[800px] max-h-[80vh] overflow-y-auto",children:[e.jsxs(ie,{className:"mb-4",children:[e.jsx(ce,{children:"配置小智服务端接入点"}),e.jsx(Ee,{children:"点击保存后,需要重启服务才会生效。"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[C.map(f=>{const j=$[f],w=j?.connected||!1,T=j?.isOperating||!1;return e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 bg-slate-50 rounded-md font-mono gap-3 transition-all duration-200 hover:bg-slate-100",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("span",{className:"flex-1 text-ellipsis overflow-hidden whitespace-nowrap text-sm sm:text-base",children:dr(f)}),e.jsxs(de,{className:`flex items-center gap-1 transition-all duration-200 text-xs sm:text-sm ${w?"bg-green-100 text-green-800 border-green-200 hover:text-green-800 hover:border-green-200 hover:bg-green-100":"bg-gray-100 text-gray-600 border-gray-200 hover:bg-gray-100 hover:text-gray-600 hover:border-gray-200"}`,children:[T?e.jsx(Se,{className:"size-3 animate-spin"}):w?e.jsx(sr,{className:"size-3"}):e.jsx(rr,{className:"size-3"}),T?"操作中":w?"已连接":"未连接"]})]}),e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-wrap justify-end",children:[e.jsx(A,{variant:"outline",size:"icon",onClick:()=>H(f),title:"复制完整地址",className:"transition-all duration-200 hover:scale-105",children:e.jsx(ut,{className:"size-4"})}),w?e.jsx(A,{variant:"outline",size:"icon",onClick:()=>V(f),title:"断开连接",disabled:T,className:"text-red-600 hover:text-red-700 hover:bg-red-50 transition-all duration-200 hover:scale-105 disabled:scale-100 disabled:opacity-50",children:T?e.jsx(Se,{className:"size-4 animate-spin"}):e.jsx(rr,{className:"size-4"})}):e.jsx(A,{variant:"outline",size:"icon",onClick:()=>L(f),title:"连接",disabled:T,className:"text-green-600 hover:text-green-700 hover:bg-green-50 transition-all duration-200 hover:scale-105 disabled:scale-100 disabled:opacity-50",children:T?e.jsx(Se,{className:"size-4 animate-spin"}):e.jsx(sr,{className:"size-4"})}),e.jsx(A,{variant:"outline",size:"icon",onClick:()=>b(f),title:"删除此接入点",className:"transition-all duration-200 hover:scale-105 hover:text-red-600",children:e.jsx(Sn,{className:"size-4 text-red-500"})})]})]},f)}),C.length===0&&e.jsxs("div",{className:"flex flex-col items-center flex-1 text-sm text-muted-foreground text-center justify-center gap-2",children:[e.jsx(ka,{}),e.jsx("span",{children:"暂无接入点,请添加"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-center gap-2 mt-4",children:[e.jsxs(A,{className:"flex-1 flex items-center gap-2",onClick:ue,children:[e.jsx(Os,{className:"size-4"}),e.jsx("span",{className:"text-sm sm:text-base",children:"添加小智服务端接入点"})]}),e.jsx(A,{variant:"outline",className:"flex-1 flex items-center gap-2",onClick:()=>window.open("https://xiaozhi.me/console/agents","_blank"),children:e.jsx("span",{className:"text-sm sm:text-base",children:"打开小智服务端"})})]})]})]}),e.jsx(Us,{open:s,onOpenChange:n,children:e.jsxs(pt,{children:[e.jsxs(xt,{children:[e.jsx(vt,{children:"确认删除接入点"}),e.jsxs(jt,{children:['确定要删除接入点 "',dr(a),'" 吗?此操作无法撤销。']})]}),e.jsxs(gt,{children:[e.jsx(bt,{disabled:i,children:"取消"}),e.jsx(St,{onClick:te,disabled:i,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:i?"删除中...":"确定删除"})]})]})}),e.jsx(me,{open:l,onOpenChange:m,children:e.jsxs(oe,{className:"sm:max-w-[500px]",children:[e.jsxs(ie,{children:[e.jsx(ce,{children:"添加新的接入点"}),e.jsx(Ee,{children:"请输入小智服务端接入点地址"})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{placeholder:"请输入接入点地址,例如:wss://api.xiaozhi.me/mcp/?token=... 或 ws(s)://<hostname>:<port>",value:c,onChange:f=>S(f.target.value),disabled:h,className:"font-mono text-sm"}),v&&e.jsx("p",{className:"text-sm text-red-500",children:v})]})}),e.jsxs(Oe,{children:[e.jsx(He,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:h,children:"取消"})}),e.jsx(A,{onClick:le,disabled:h||!c.trim(),children:h?"添加中...":"确定"})]})]})})]})}const Le=u.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:R("rounded-lg border bg-card text-card-foreground shadow-sm",r),...t}));Le.displayName="Card";const qe=u.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:R("flex flex-col space-y-1.5 p-6",r),...t}));qe.displayName="CardHeader";const Ue=u.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:R("text-2xl font-semibold leading-none tracking-tight",r),...t}));Ue.displayName="CardTitle";const Xe=u.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:R("text-sm text-muted-foreground",r),...t}));Xe.displayName="CardDescription";const _n=u.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:R("p-6 pt-0",r),...t}));_n.displayName="CardContent";const Ye=u.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:R("flex items-center p-6 pt-0",r),...t}));Ye.displayName="CardFooter";function ko(){const r=Vn(),t=Array.isArray(r)?r.length:r?1:0;return e.jsxs(Le,{className:"@container/card",children:[e.jsxs(qe,{className:"relative",children:[e.jsx(Xe,{children:"小智接入点"}),e.jsx(Ue,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:t}),e.jsx("div",{className:"absolute right-4 top-4 flex flex-col items-center",children:e.jsx(ft,{showValue:!1,value:t,maxValue:Math.max(t,1),activeColor:"#16a34a",inactiveColor:"#f87171",size:30,symbol:""})})]}),e.jsx(Ye,{className:"flex-col items-end gap-1 text-sm",children:e.jsx(To,{})})]})}const Io=Pe("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Bn=u.forwardRef(({className:r,...t},s)=>e.jsx(bn,{ref:s,className:R(Io(),r),...t}));Bn.displayName=bn.displayName;const ze=$a,Gn=u.createContext({}),re=({...r})=>e.jsx(Gn.Provider,{value:{name:r.name},children:e.jsx(Ae,{...r})}),wt=()=>{const r=u.useContext(Gn),t=u.useContext(Hn),{getFieldState:s,formState:n}=Ia(),a=s(r.name,n);if(!r)throw new Error("useFormField should be used within <FormField>");const{id:o}=t;return{id:o,name:r.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...a}},Hn=u.createContext({}),ee=u.forwardRef(({className:r,...t},s)=>{const n=u.useId();return e.jsx(Hn.Provider,{value:{id:n},children:e.jsx("div",{ref:s,className:R("space-y-2",r),...t})})});ee.displayName="FormItem";const pe=u.forwardRef(({className:r,...t},s)=>{const{error:n,formItemId:a}=wt();return e.jsx(Bn,{ref:s,className:R(n&&"text-destructive",r),htmlFor:a,...t})});pe.displayName="FormLabel";const X=u.forwardRef(({...r},t)=>{const{error:s,formItemId:n,formDescriptionId:a,formMessageId:o}=wt();return e.jsx(on,{ref:t,id:n,"aria-describedby":s?`${a} ${o}`:`${a}`,"aria-invalid":!!s,...r})});X.displayName="FormControl";const De=u.forwardRef(({className:r,...t},s)=>{const{formDescriptionId:n}=wt();return e.jsx("p",{ref:s,id:n,className:R("text-sm text-muted-foreground",r),...t})});De.displayName="FormDescription";const ne=u.forwardRef(({className:r,children:t,...s},n)=>{const{error:a,formMessageId:o}=wt(),i=a?String(a?.message??""):t;return i?e.jsx("p",{ref:n,id:o,className:R("text-sm font-medium text-destructive",r),...s,children:i}):null});ne.displayName="FormMessage";class $o{apiClient;webSocketManager;initialized=!1;constructor(){this.apiClient=U,this.webSocketManager=z}async initialize(){this.initialized||(console.log("[NetworkService] 初始化网络服务"),this.webSocketManager.connect(),this.initialized=!0,console.log("[NetworkService] 网络服务初始化完成"))}destroy(){console.log("[NetworkService] 销毁网络服务"),this.webSocketManager.disconnect(),this.initialized=!1}async getConfig(){return this.apiClient.getConfig()}async updateConfig(t){return this.apiClient.updateConfig(t)}async getStatus(){return this.apiClient.getStatus()}async getClientStatus(){return this.apiClient.getClientStatus()}async restartService(){return this.apiClient.restartService()}async stopService(){return this.apiClient.stopService()}async startService(){return this.apiClient.startService()}async getServiceStatus(){return this.apiClient.getServiceStatus()}async getServiceHealth(){return this.apiClient.getServiceHealth()}async getMcpEndpoint(){return this.apiClient.getMcpEndpoint()}async getMcpEndpoints(){return this.apiClient.getMcpEndpoints()}async getMcpServers(){return this.apiClient.getMcpServers()}async getConnectionConfig(){return this.apiClient.getConnectionConfig()}async reloadConfig(){return this.apiClient.reloadConfig()}async getConfigPath(){return this.apiClient.getConfigPath()}async checkConfigExists(){return this.apiClient.checkConfigExists()}async getRestartStatus(){return this.apiClient.getRestartStatus()}async checkClientConnected(){return this.apiClient.checkClientConnected()}async getLastHeartbeat(){return this.apiClient.getLastHeartbeat()}async getActiveMCPServers(){return this.apiClient.getActiveMCPServers()}async updateClientStatus(t){return this.apiClient.updateClientStatus(t)}async setActiveMCPServers(t){return this.apiClient.setActiveMCPServers(t)}async resetStatus(){return this.apiClient.resetStatus()}getWebSocketState(){return this.webSocketManager.getState()}isWebSocketConnected(){return this.webSocketManager.isConnected()}setWebSocketUrl(t){this.webSocketManager.setUrl(t)}onWebSocketEvent(t,s){return this.webSocketManager.subscribe(t,s)}reconnectWebSocket(){this.webSocketManager.disconnect(),setTimeout(()=>{this.webSocketManager.connect()},1e3)}send(t){return this.webSocketManager.send(t)}async getFullAppState(){const[t,s]=await Promise.all([this.getConfig(),this.getStatus()]);return{config:t,status:s,webSocketConnected:this.isWebSocketConnected()}}async updateConfigWithNotification(t,s=5e3){return new Promise((n,a)=>{const o=this.webSocketManager.subscribe("data:configUpdate",()=>{clearTimeout(i),o(),n()}),i=setTimeout(()=>{o(),a(new Error("等待配置更新通知超时"))},s);this.updateConfig(t).catch(d=>{clearTimeout(i),o?.(),a(d)})})}async restartServiceWithNotification(t=3e4){return new Promise((s,n)=>{const a=this.webSocketManager.subscribe("data:restartStatus",i=>{i.status==="completed"?(clearTimeout(o),a(),s()):i.status==="failed"&&(clearTimeout(o),a(),n(new Error(i.error||"服务重启失败")))}),o=setTimeout(()=>{a(),n(new Error("等待重启状态通知超时"))},t);this.restartService().catch(i=>{clearTimeout(o),a?.(),n(i)})})}}const _=new $o,mr={connectionState:Q.DISCONNECTED,wsUrl:"",connectionStats:{reconnectAttempts:0,maxReconnectAttempts:5,lastHeartbeat:0,eventListenerCount:0},portChangeStatus:void 0,lastError:null,connectedAt:null,disconnectedAt:null},Ke=Is()($s((r,t)=>({...mr,setConnectionState:s=>{console.log("[WebSocketStore] 更新连接状态:",s);const n=Date.now(),a={connectionState:s};s===Q.CONNECTED?(a.connectedAt=n,a.lastError=null):s===Q.DISCONNECTED&&(a.disconnectedAt=n),r(a,!1,"setConnectionState");const o=z.getConnectionStats();t().setConnectionStats(o)},setWsUrl:s=>{console.log("[WebSocketStore] 更新 WebSocket URL:",s),r({wsUrl:s},!1,"setWsUrl")},setConnectionStats:s=>{r({connectionStats:s},!1,"setConnectionStats")},setLastError:s=>{console.log("[WebSocketStore] 更新连接错误:",s?.message),r({lastError:s},!1,"setLastError")},setPortChangeStatus:s=>{console.log("[WebSocketStore] 更新端口变更状态:",s?.status),r({portChangeStatus:s},!1,"setPortChangeStatus")},connect:async()=>{try{console.log("[WebSocketStore] 开始连接 WebSocket"),z.connect()}catch(s){const n=s instanceof Error?s:new Error("连接失败");throw console.error("[WebSocketStore] 连接失败:",n),t().setLastError(n),n}},disconnect:()=>{console.log("[WebSocketStore] 断开 WebSocket 连接"),z.disconnect()},reconnect:async()=>{try{console.log("[WebSocketStore] 重新连接 WebSocket"),z.disconnect(),await new Promise(s=>setTimeout(s,qn)),z.connect()}catch(s){const n=s instanceof Error?s:new Error("重连失败");throw console.error("[WebSocketStore] 重连失败:",n),t().setLastError(n),n}},send:s=>{try{return z.send(s)}catch(n){const a=n instanceof Error?n:new Error("发送消息失败");return console.error("[WebSocketStore] 发送消息失败:",a),t().setLastError(a),!1}},updateUrl:s=>{console.log("[WebSocketStore] 更新 WebSocket URL:",s),z.setUrl(s),t().setWsUrl(s)},getConnectionInfo:()=>{const s=t();return{state:s.connectionState,url:s.wsUrl,stats:s.connectionStats,isConnected:s.connectionState===Q.CONNECTED}},reset:()=>{console.log("[WebSocketStore] 重置状态"),r(mr,!1,"reset")},initialize:()=>{console.log("[WebSocketStore] 初始化 WebSocket Store"),z.subscribe("connection:connecting",()=>{t().setConnectionState(Q.CONNECTING)}),z.subscribe("connection:connected",()=>{t().setConnectionState(Q.CONNECTED)}),z.subscribe("connection:disconnected",()=>{t().setConnectionState(Q.DISCONNECTED)}),z.subscribe("connection:reconnecting",()=>{t().setConnectionState(Q.RECONNECTING);const n=z.getConnectionStats();t().setConnectionStats(n)}),z.subscribe("connection:error",({error:n})=>{t().setLastError(n)}),z.subscribe("system:heartbeat",()=>{const n=z.getConnectionStats();t().setConnectionStats(n)});const s=z.getConnectionStats();t().setConnectionStats(s),t().setWsUrl(z.getUrl()),console.log("[WebSocketStore] WebSocket Store 初始化完成")},setConnected:s=>{console.warn("[WebSocketStore] setConnected 方法已废弃,请使用 setConnectionState");const n=s?Q.CONNECTED:Q.DISCONNECTED;t().setConnectionState(n)}}),{name:"websocket-store"})),Jn=()=>Ke(r=>r.connectionState===Q.CONNECTED),Po=()=>Ke(r=>r.wsUrl),Oo=()=>Ke(r=>r.portChangeStatus),Lo=()=>Ke(Ps(r=>({setConnectionState:r.setConnectionState,setWsUrl:r.setWsUrl,setConnectionStats:r.setConnectionStats,setLastError:r.setLastError,setPortChangeStatus:r.setPortChangeStatus,connect:r.connect,disconnect:r.disconnect,reconnect:r.reconnect,send:r.send,updateUrl:r.updateUrl,reset:r.reset,initialize:r.initialize,getConnectionInfo:r.getConnectionInfo,setConnected:r.setConnected})));function Ao(){const r=Lo(),t=u.useRef(!1);u.useEffect(()=>{if(t.current)return;console.log("[NetworkService] 初始化网络服务"),t.current=!0,_.initialize().catch(v=>{console.error("[NetworkService] 初始化失败:",v)});const x=[_.onWebSocketEvent("connection:connected",()=>{console.log("[NetworkService] WebSocket 已连接"),r.setConnectionState(Q.CONNECTED),s()}),_.onWebSocketEvent("connection:disconnected",()=>{console.log("[NetworkService] WebSocket 已断开"),r.setConnectionState(Q.DISCONNECTED)}),_.onWebSocketEvent("data:configUpdate",v=>{console.log("[NetworkService] 收到配置更新通知"),xe.getState().setConfig(v,"websocket")}),_.onWebSocketEvent("data:statusUpdate",v=>{console.log("[NetworkService] 收到状态更新通知"),je.getState().setClientStatus(v,"websocket")}),_.onWebSocketEvent("data:restartStatus",v=>{console.log("[NetworkService] 收到重启状态通知:",v),je.getState().setRestartStatus(v,"websocket")}),_.onWebSocketEvent("system:error",({error:v})=>{console.error("[NetworkService] WebSocket 错误:",v);const g=`WebSocket 连接错误: ${v.message}`;je.getState().setError(new Error(g)),v.message.includes("ECONNREFUSED")||v.message.includes("连接被拒绝")?console.warn("[NetworkService] 连接被拒绝,可能是服务未启动"):v.message.includes("timeout")||v.message.includes("超时")?console.warn("[NetworkService] 连接超时,请检查网络连接"):console.warn("[NetworkService] 未知的 WebSocket 错误:",v)})];return()=>{console.log("[NetworkService] 清理网络服务");for(const v of x)try{v?.()}catch(g){console.error("[NetworkService] 清理事件监听器失败:",g)}_.destroy(),t.current=!1}},[r]);const s=u.useCallback(async()=>{try{console.log("[NetworkService] 加载初始数据");const[x,v]=await Promise.all([_.getConfig(),_.getClientStatus()]);console.log("[NetworkService] 初始数据加载成功"),xe.getState().setConfig(x,"http"),je.getState().setClientStatus(v,"http")}catch(x){console.error("[NetworkService] 加载初始数据失败:",x)}},[]),n=u.useCallback(async()=>{try{const x=await _.getConfig();return xe.getState().setConfig(x,"http"),x}catch(x){throw console.error("[NetworkService] 获取配置失败:",x),x}},[]),a=u.useCallback(async x=>{try{console.log("[NetworkService] 更新配置"),await _.updateConfig(x),xe.getState().setConfig(x,"http"),console.log("[NetworkService] 配置更新成功")}catch(v){throw console.error("[NetworkService] 配置更新失败:",v),v}},[]),o=u.useCallback(async()=>{try{const x=await _.getStatus();return je.getState().setClientStatus(x.client,"http"),x}catch(x){throw console.error("[NetworkService] 获取状态失败:",x),x}},[]),i=u.useCallback(async()=>{try{await o()}catch(x){console.error("[NetworkService] 刷新状态失败:",x)}},[o]),d=u.useCallback(async()=>{try{console.log("[NetworkService] 重启服务"),await _.restartService(),console.log("[NetworkService] 重启请求已发送")}catch(x){throw console.error("[NetworkService] 重启服务失败:",x),x}},[]),l=u.useCallback(async(x=3e4)=>{try{console.log("[NetworkService] 重启服务并等待通知"),await _.restartServiceWithNotification(x),console.log("[NetworkService] 服务重启完成")}catch(v){throw console.error("[NetworkService] 重启服务失败:",v),v}},[]),m=u.useCallback(async(x,v=5e3)=>{try{console.log("[NetworkService] 更新配置并等待通知"),await _.updateConfigWithNotification(x,v),console.log("[NetworkService] 配置更新完成")}catch(g){throw console.error("[NetworkService] 配置更新失败:",g),g}},[]),c=u.useCallback(x=>{console.log("[NetworkService] 设置自定义 WebSocket URL:",x),_.setWebSocketUrl(x),r.setWsUrl(x)},[r]),p=u.useCallback(async x=>{try{console.log(`[NetworkService] 切换到端口 ${x}`),r.setPortChangeStatus({status:"checking",targetPort:x,timestamp:Date.now()});const v=window.location.protocol==="https:"?"wss:":"ws:",g=window.location.hostname,$=`${v}//${g}:${x}`;await d(),await new Promise(k=>setTimeout(k,5e3)),c($),window.location.reload()}catch(v){throw console.error("[NetworkService] 端口切换失败:",v),r.setPortChangeStatus({status:"failed",targetPort:x,error:v instanceof Error?v.message:"端口切换失败",timestamp:Date.now()}),v}},[r,d,c]),h=u.useCallback(()=>{const x=localStorage.getItem("xiaozhi-ws-url");if(x)return x;const v=window.location.protocol==="https:"?"wss:":"ws:",g=window.location.hostname,$=window.location.port;return`${v}//${g}${$?`:${$}`:""}`},[]);return{getConfig:n,updateConfig:a,getStatus:o,refreshStatus:i,restartService:d,updateConfigWithNotification:m,restartServiceWithNotification:l,setCustomWsUrl:c,getWebSocketUrl:h,changePort:p,loadInitialData:s,isWebSocketConnected:()=>_.isWebSocketConnected(),getWebSocketState:()=>_.getWebSocketState()}}async function Mo(){console.log("[Stores] 开始初始化所有 stores");try{console.log("[Stores] 初始化 WebSocket store"),Ke.getState().initialize(),console.log("[Stores] 初始化配置 store"),await xe.getState().initialize(),console.log("[Stores] 初始化 MCP 服务器状态"),await xe.getState().refreshMcpServerStatuses(),console.log("[Stores] 初始化状态 store"),await je.getState().initialize(),console.log("[Stores] 所有 stores 初始化完成")}catch(r){throw console.error("[Stores] Stores 初始化失败:",r),r}}const Xn=u.createContext(null);function Do({children:r}){const t=Ao(),[s,n]=u.useState(!1);return u.useEffect(()=>{let a=!0;return(async()=>{try{console.log("[WebSocketProvider] 开始初始化 stores"),await Mo(),a&&(n(!0),console.log("[WebSocketProvider] Stores 初始化完成"))}catch(i){console.error("[WebSocketProvider] Stores 初始化失败:",i),a&&n(!0)}})(),()=>{a=!1}},[]),s?e.jsx(Xn.Provider,{value:t,children:r}):e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"正在初始化应用..."})]})})}function zs(){const r=u.useContext(Xn);if(!r)throw new Error("useNetworkServiceActions must be used within a NetworkServiceProvider");return r}const qo=Do,Uo=zs,zo=J.object({port:J.string().min(1,{message:"端口号不能为空"}).refine(r=>!Number.isNaN(Number(r)),{message:"请输入有效的数字"}).refine(r=>Number(r)>=1&&Number(r)<=65535,{message:"端口号必须在 1-65535 之间"}).refine(r=>Number.isInteger(Number(r)),{message:"端口号必须是整数"})});function Fo(){const[r,t]=u.useState(!1),[s,n]=u.useState(!1),a=Je(),o=Jn(),i=Oo(),{changePort:d}=zs(),l=ye({resolver:Ce(zo),defaultValues:{port:"9999"}});u.useEffect(()=>{a?.webUI?.port&&l.reset({port:a.webUI.port.toString()})},[a,l]);const m=()=>{if(s)return"处理中...";if(i?.status==="checking")return"检测端口...";if(i?.status==="polling"){const{currentAttempt:p,maxAttempts:h}=i;return`等待服务重启 (${p||0}/${h||45})`}return i?.status==="connecting"?"连接中...":o?"保存并重启":"保存并连接"};async function c(p){const h=Number(p.port),x=a?.webUI?.port;if(h===x){t(!1);return}console.log(`[WebUrlSettingButton] 开始端口切换: ${x} -> ${h}`),n(!0);try{O.info(o?`正在将端口从 ${x} 切换到 ${h}...`:`正在连接到端口 ${h}...`),await d(h),O.success(o?`端口已成功切换到 ${h},页面即将刷新...`:`已成功连接到端口 ${h},页面即将刷新...`),t(!1)}catch(v){console.error("端口切换失败:",v);const g=v instanceof Error?v.message:"端口切换失败";O.error(`端口切换失败: ${g}`)}finally{n(!1)}}return e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(ke,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8",children:e.jsx(lt,{className:"h-4 w-4"})})}),e.jsx(oe,{className:"sm:max-w-[250px]",children:e.jsx(ze,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(c),children:[e.jsxs(ie,{className:"mb-4",children:[e.jsx(ce,{children:"配置服务端端口"}),e.jsx(Ee,{children:o?"修改端口后将自动重启服务并重新连接。":"请输入服务端端口号,系统将尝试连接。"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{children:["ws://",window.location.hostname,":"]}),e.jsx("div",{className:"w-[100px]",children:e.jsx(re,{control:l.control,name:"port",render:({field:p})=>e.jsxs(ee,{children:[e.jsx(X,{children:e.jsx(se,{placeholder:"服务端端口,默认9999",className:"font-mono text-sm",disabled:s,type:"number",...p})}),e.jsx(ne,{})]})})})]}),e.jsxs(Oe,{className:"mt-4",children:[e.jsx(He,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:s,children:"取消"})}),e.jsx(A,{type:"submit",disabled:s||i?.status==="polling",children:m()})]})]})})})]})}function Vo(){const r=Jn(),t=Po();return e.jsxs(Le,{className:"@container/card",children:[e.jsxs(qe,{className:"relative",children:[e.jsx(Xe,{children:"Xiaozhi Client"}),e.jsx(Ue,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:r?"已连接":"未连接"}),e.jsx("div",{className:"absolute right-4 top-4",children:e.jsx(ft,{showValue:!1,value:1,maxValue:1,activeColor:r?"#16a34a":"#f87171",inactiveColor:r?"#16a34a":"#f87171",size:30,symbol:""})})]}),e.jsxs(Ye,{className:"flex items-center justify-between gap-1 text-sm",children:[e.jsx("div",{className:"text-muted-foreground",children:t}),e.jsx(Fo,{})]})]})}const Re=Da,Te=qa,be=u.forwardRef(({className:r,children:t,...s},n)=>e.jsxs(wn,{ref:n,className:R("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",r),...s,children:[t,e.jsx(Pa,{asChild:!0,children:e.jsx(dt,{className:"h-4 w-4 opacity-50"})})]}));be.displayName=wn.displayName;const Yn=u.forwardRef(({className:r,...t},s)=>e.jsx(Nn,{ref:s,className:R("flex cursor-default items-center justify-center py-1",r),...t,children:e.jsx(Ls,{className:"h-4 w-4"})}));Yn.displayName=Nn.displayName;const Kn=u.forwardRef(({className:r,...t},s)=>e.jsx(yn,{ref:s,className:R("flex cursor-default items-center justify-center py-1",r),...t,children:e.jsx(dt,{className:"h-4 w-4"})}));Kn.displayName=yn.displayName;const we=u.forwardRef(({className:r,children:t,position:s="popper",...n},a)=>e.jsx(Oa,{children:e.jsxs(Cn,{ref:a,className:R("relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",s==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r),position:s,...n,children:[e.jsx(Yn,{}),e.jsx(La,{className:R("p-1",s==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Kn,{})]})}));we.displayName=Cn.displayName;const Wo=u.forwardRef(({className:r,...t},s)=>e.jsx(En,{ref:s,className:R("py-1.5 pl-8 pr-2 text-sm font-semibold",r),...t}));Wo.displayName=En.displayName;const ae=u.forwardRef(({className:r,children:t,...s},n)=>e.jsxs(Rn,{ref:n,className:R("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Aa,{children:e.jsx(mt,{className:"h-4 w-4"})})}),e.jsx(Ma,{children:t})]}));ae.displayName=Rn.displayName;const _o=u.forwardRef(({className:r,...t},s)=>e.jsx(Tn,{ref:s,className:R("-mx-1 my-1 h-px bg-muted",r),...t}));_o.displayName=Tn.displayName;const Ze=u.forwardRef(({className:r,...t},s)=>e.jsx("textarea",{className:R("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",r),ref:s,...t}));Ze.displayName="Textarea";function Zn(r,t,s){const{name:n,type:a,label:o,required:i,placeholder:d,description:l,condition:m,options:c,inputType:p}=r;if(m&&!m(t))return null;const h=s??r.disabled,x=v=>{switch(a){case"text":return e.jsx(se,{...v,type:p,placeholder:d,disabled:h,className:r.className});case"textarea":return e.jsx(Ze,{...v,placeholder:d,className:r.className,rows:r.rows,disabled:h});case"select":return e.jsxs(Re,{value:v.value,onValueChange:v.onChange,disabled:h,children:[e.jsx(be,{children:e.jsx(Te,{placeholder:d})}),e.jsx(we,{children:c?.map(g=>e.jsx(ae,{value:g.value,children:g.label},g.value))})]});default:return null}};return e.jsx(re,{control:t.control,name:String(n),render:({field:v})=>e.jsxs(ee,{children:[e.jsxs(pe,{children:[i&&e.jsx("span",{className:"text-red-500 mr-1",children:"*"}),o]}),e.jsx(X,{children:x(v)}),typeof l=="function"?e.jsx(De,{children:l(t)}):l?e.jsx(De,{children:l}):null,e.jsx(ne,{})]})},String(n))}function Bo(r,t,s,n){const{name:a,type:o,label:i,required:d,placeholder:l,description:m,options:c}=r;return o!=="select"?(console.warn("renderSelectFieldWithHandler 只能用于 select 类型字段"),Zn(r,t,n)):e.jsx(re,{control:t.control,name:String(a),render:({field:p})=>e.jsxs(ee,{children:[e.jsxs(pe,{children:[d&&e.jsx("span",{className:"text-red-500 mr-1",children:"*"}),i]}),e.jsx(X,{children:e.jsxs(Re,{value:p.value,onValueChange:s,disabled:n??r.disabled,children:[e.jsx(be,{children:e.jsx(Te,{placeholder:l})}),e.jsx(we,{children:c?.map(h=>e.jsx(ae,{value:h.value,children:h.label},h.value))})]})}),typeof m=="function"?e.jsx(De,{children:m(t)}):m?e.jsx(De,{children:m}):null,e.jsx(ne,{})]})},String(a))}const Go=[{name:"type",type:"select",label:"MCP 类型",required:!0,placeholder:"选择 MCP 类型",description:r=>{const t=r.watch("type");return t==="stdio"?"本地通过命令行启动的 MCP 服务":t==="http"?"通过 HTTP 协议访问的远程 MCP 服务":t==="sse"?"通过 SSE 协议访问的远程 MCP 服务":""},options:[{value:"stdio",label:"本地进程 (stdio)"},{value:"http",label:"远程服务 (HTTP)"},{value:"sse",label:"服务器推送 (SSE)"}]},{name:"name",type:"text",label:"MCP 名称",required:!0,placeholder:"例如: xxx-mcp",description:"服务的唯一标识符,建议使用小写字母和连字符"},{name:"command",type:"text",label:"启动命令",required:!0,placeholder:"例如: npx -y xxx",description:"完整的启动命令,空格分隔命令和参数",condition:r=>r.watch("type")==="stdio"},{name:"env",type:"textarea",label:"环境变量 (可选)",placeholder:`KEY1=value1
|
|
2
|
-
KEY2=value2`,description:"每行一个环境变量,支持 KEY=value 或 KEY: value 格式",className:"min-h-[100px] font-mono text-sm",condition:r=>r.watch("type")==="stdio"},{name:"url",type:"text",label:"服务地址",required:!0,inputType:"url",placeholder:"https://example.com/mcp",description:"MCP 服务的完整 URL 地址",condition:r=>{const t=r.watch("type");return t==="http"||t==="sse"}},{name:"headers",type:"textarea",label:"请求头 (可选)",placeholder:`Authorization: Bearer your-key
|
|
3
|
-
Content-Type: application/json`,description:"每行一个请求头,格式: Header-Name: value",className:"min-h-[100px] font-mono text-sm",condition:r=>{const t=r.watch("type");return t==="http"||t==="sse"}}],Fs=Ie().trim(),Vs=Ie().min(1,"MCP 名称不能为空").regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,"MCP 名称只能包含小写字母、数字和连字符,且必须以字母或数字开头和结尾"),Ho=Ge({type:qs("stdio"),name:Vs,command:Ie().min(1,"启动命令不能为空"),env:Fs}),Jo=Ge({type:qs("http"),name:Vs,url:Ie().url("请输入有效的 URL 地址"),headers:Fs}),Xo=Ge({type:qs("sse"),name:Vs,url:Ie().url("请输入有效的 URL 地址"),headers:Fs}),Ws=mo("type",[Ho,Jo,Xo]);function Qn({form:r,defaultValues:t,onSubmit:s,disabled:n=!1,submitText:a="保存配置"}){const o=r||ye({resolver:Ce(Ws),defaultValues:t||{type:"stdio",name:"",command:"",env:""}}),i=d=>{o.setValue("type",d);const l=o;d==="stdio"?(l.setValue("url",""),l.setValue("headers","")):(l.setValue("command",""),l.setValue("env",""))};return e.jsx(ze,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(s),className:"space-y-4 py-2",children:[Go.map(d=>d.name==="type"?Bo(d,o,i,n):Zn(d,o,n)),e.jsx(A,{type:"submit",className:"w-full",disabled:n,children:a})]})})}const We=Ua,Qe=u.forwardRef(({className:r,...t},s)=>e.jsx(kn,{ref:s,className:R("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",r),...t}));Qe.displayName=kn.displayName;const ge=u.forwardRef(({className:r,...t},s)=>e.jsx(In,{ref:s,className:R("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",r),...t}));ge.displayName=In.displayName;const ve=u.forwardRef(({className:r,...t},s)=>e.jsx($n,{ref:s,className:R("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",r),...t}));ve.displayName=$n.displayName;function Yo(r){const t=r.trim();if(!t)throw new Error("命令不能为空");const s=[];let n="",a=!1,o="";for(let i=0;i<t.length;i++){const d=t[i];(d==='"'||d==="'")&&(i===0||t[i-1]!=="\\")?a&&d===o?(a=!1,o=""):a?n+=d:(a=!0,o=d):d===" "&&!a?n&&(s.push(n),n=""):n+=d}if(n&&s.push(n),s.length===0)throw new Error("命令不能为空");return{command:s[0],args:s.slice(1)}}function fr(r){if(r.length>=2){const t=r[0],s=r[r.length-1];if(t==='"'&&s==='"'||t==="'"&&s==="'")return r.slice(1,-1)}return r}function _s(r){const t={};for(const s of r.split(`
|
|
4
|
-
`)){const n=s.trim();if(!n||n.startsWith("#"))continue;const a=n.indexOf("=");if(a>0){const i=n.slice(0,a).trim();let d=n.slice(a+1).trim();d=fr(d),t[i]=d;continue}const o=n.indexOf(":");if(o>0){const i=n.slice(0,o).trim();let d=n.slice(o+1).trim();d=fr(d),t[i]=d}}return t}function Ko(r){const{command:t,args:s}=Yo(r.command),n=_s(r.env),a={command:t,args:s};return Object.keys(n).length>0&&(a.env=n),a}function Zo(r){const t=_s(r.headers),s={type:"streamable-http",url:r.url};return Object.keys(t).length>0&&(s.headers=t),s}function Qo(r){const t=_s(r.headers),s={type:"sse",url:r.url};return Object.keys(t).length>0&&(s.headers=t),s}function Bs(r){const{name:t,type:s}=r;let n;switch(s){case"stdio":n=Ko(r);break;case"http":n=Zo(r);break;case"sse":n=Qo(r);break;default:throw new Error("不支持的 MCP 类型")}return{name:t,config:n}}function ei(r){return"command"in r?"stdio":"type"in r&&r.type==="sse"?"sse":"http"}function ti(r){const t=[r.command];return r.args&&r.args.length>0&&t.push(...r.args),t.join(" ")}function Gs(r){return!r||Object.keys(r).length===0?"":Object.entries(r).map(([t,s])=>`${t}: ${s}`).join(`
|
|
5
|
-
`)}function si(r,t){const s=t;return{type:"stdio",name:r,command:ti(s),env:Gs(s.env)}}function ri(r,t){const s=t;return{type:"http",name:r,url:s.url,headers:Gs(s.headers)}}function ni(r,t){const s=t;return{type:"sse",name:r,url:s.url,headers:Gs(s.headers)}}function Es(r,t){switch(ei(t)){case"stdio":return si(r,t);case"http":return ri(r,t);case"sse":return ni(r,t);default:throw new Error("无法识别的 MCP 类型")}}function ea(r){try{const t=JSON.parse(r);if(t.mcpServers&&typeof t.mcpServers=="object"){const s=Object.entries(t.mcpServers);if(s.length===0)return null;const[n,a]=s[0];return Es(n,a)}if(typeof t=="object"&&t!==null&&("command"in t||"type"in t||"url"in t)){let s;return"command"in t&&t.command?s=t.command.split("/").pop()||"mcp-server":"type"in t&&t.type==="sse"?s="sse-server":s="http-server",Es(s,t)}return null}catch{return null}}function ta(r){const{name:t,config:s}=Bs(r);return JSON.stringify({mcpServers:{[t]:s}},null,2)}function ai(r,t){if(!t||typeof t!="object")return{valid:!1,error:`服务 "${r}" 的配置必须是一个对象`};const s=t,n="command"in s,a="type"in s,o="url"in s;if(n){if(!s.command||typeof s.command!="string")return{valid:!1,error:`服务 "${r}" 缺少必需的 command 字段或字段类型不正确`};if(!Array.isArray(s.args))return{valid:!1,error:`服务 "${r}" 的 args 字段必须是数组`}}else if(a&&s.type==="sse"){if(!s.url||typeof s.url!="string")return{valid:!1,error:`服务 "${r}" 缺少必需的 url 字段或字段类型不正确`}}else if(o){if(!s.url||typeof s.url!="string")return{valid:!1,error:`服务 "${r}" 缺少必需的 url 字段或字段类型不正确`}}else return{valid:!1,error:`服务 "${r}" 的配置无效: 必须包含 command 字段(stdio)、type: 'sse' 字段(sse)或 url 字段(streamable-http)`};return{valid:!0}}function sa(r){try{const t=r.trim();if(!t)return{success:!1,error:"配置不能为空"};const s=JSON.parse(t);let n;if(s.mcpServers&&typeof s.mcpServers=="object")n=s.mcpServers;else if(typeof s=="object"&&!Array.isArray(s)){const a="command"in s,o="type"in s,i="url"in s;if(a||o||i)n={[a?String(s.command).split("/").pop()||"mcp-server":o&&s.type==="sse"?"sse-server":"http-server"]:s};else return{success:!1,error:"配置格式错误: 必须是对象格式"}}else return{success:!1,error:"配置格式错误: 必须是对象格式"};for(const[a,o]of Object.entries(n)){const i=ai(a,o);if(!i.valid)return{success:!1,error:i.error}}return{success:!0,data:n}}catch(t){return{success:!1,error:`JSON 格式错误: ${t instanceof Error?t.message:"无法解析 JSON"}`}}}const oi=J.object({config:J.string().min(2,{message:"配置不能为空"})});function ii(){const[r,t]=u.useState(!1),[s,n]=u.useState(!1),[a,o]=u.useState("form"),[i,d]=u.useState(""),l=ye({resolver:Ce(Ws),defaultValues:{type:"stdio",name:"",command:"",env:""}}),m=ye({resolver:Ce(oi),defaultValues:{config:""}}),c=u.useCallback(v=>{v||(l.reset(),m.reset(),d(""),o("form")),t(v)},[l,m]),p=u.useCallback(v=>{if(!(v!=="form"&&v!=="json")){if(v==="json"&&a==="form"){const g=l.getValues();try{d(ta(g))}catch{d("")}}else if(v==="form"&&a==="json"){const g=ea(i);g&&l.reset(g)}o(v)}},[a,l,i]),h=u.useCallback(async v=>{n(!0);try{const{name:g,config:$}=Bs(v);if((await U.listMCPServers()).servers.some(y=>y.name===g)){O.error(`服务名称 "${g}" 已存在`);return}if(!await U.addMCPServer(g,$))throw new Error("添加服务器失败");O.success(`已添加 MCP 服务 "${g}"`),l.reset(),t(!1)}catch(g){console.error("更新配置失败:",g),O.error(g instanceof Error?g.message:"更新配置失败")}finally{n(!1)}},[l]),x=u.useCallback(async v=>{n(!0);try{const g=sa(v.config);if(!g.success){O.error(g.error||"配置验证失败");return}const $=g.data,k=await U.listMCPServers(),N=Object.keys($).filter(P=>k.servers.some(E=>E.name===P));if(N.length>0){O.error(`服务名称冲突: 以下服务已存在: ${N.join(", ")}`);return}for(const[P,E]of Object.entries($))if(!await U.addMCPServer(P,E))throw new Error("添加服务器失败");const y=Object.keys($).length;O.success(y===1?`已添加 MCP 服务 "${Object.keys($)[0]}"`:`已添加 ${y} 个 MCP 服务`),m.reset(),t(!1)}catch(g){console.error("更新配置失败:",g),O.error(g instanceof Error?g.message:"更新配置失败")}finally{n(!1)}},[m]);return e.jsxs(me,{open:r,onOpenChange:c,children:[e.jsx(ke,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8","aria-label":"添加MCP服务",title:"添加MCP服务",children:e.jsx(Os,{className:"size-4"})})}),e.jsxs(oe,{className:"sm:max-w-[600px]",children:[e.jsxs(ie,{className:"mb-4",children:[e.jsx(ce,{children:"添加MCP服务"}),e.jsx(Ee,{children:"添加后,需要重启服务才会生效。"})]}),e.jsxs(We,{value:a,onValueChange:p,children:[e.jsxs(Qe,{className:"grid w-full grid-cols-2",children:[e.jsx(ge,{value:"form",children:"表单模式"}),e.jsx(ge,{value:"json",children:"高级模式"})]}),e.jsx(ve,{value:"form",className:"mt-4",children:e.jsx(Qn,{form:l,onSubmit:h,disabled:s,submitText:s?"保存中...":"保存配置"})}),e.jsx(ve,{value:"json",className:"mt-4",children:e.jsx(ze,{...m,children:e.jsxs("form",{onSubmit:m.handleSubmit(x),children:[e.jsx("div",{className:"grid gap-4",children:e.jsx(re,{control:m.control,name:"config",render:({field:v})=>e.jsxs(ee,{children:[e.jsx(X,{children:e.jsx(Ze,{className:"resize-none h-[300px] font-mono text-sm",disabled:s,placeholder:`支持三种通信方式:
|
|
6
|
-
|
|
7
|
-
1. 本地进程 (stdio):
|
|
8
|
-
{
|
|
9
|
-
"mcpServers": {
|
|
10
|
-
"local-server": {
|
|
11
|
-
"command": "npx",
|
|
12
|
-
"args": ["-y", "@example/mcp-server"]
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
2. 服务器推送 (SSE):
|
|
18
|
-
{
|
|
19
|
-
"mcpServers": {
|
|
20
|
-
"sse-server": {
|
|
21
|
-
"type": "sse",
|
|
22
|
-
"url": "https://example.com/sse"
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
3. 流式 HTTP:
|
|
28
|
-
{
|
|
29
|
-
"mcpServers": {
|
|
30
|
-
"http-server": {
|
|
31
|
-
"url": "https://example.com/mcp"
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
}`,...v,onChange:g=>{v.onChange(g),d(g.target.value)}})}),e.jsx(ne,{})]})})}),e.jsxs(Oe,{className:"mt-4",children:[e.jsx(He,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:s,children:"取消"})}),e.jsx(A,{type:"submit",disabled:s,children:s?"保存中...":"保存"})]})]})})})]})]})]})}const Hs=u.createContext({size:"default"}),ci=Pe("w-full caption-bottom text-sm",{variants:{size:{default:"text-sm",compact:"text-xs"}},defaultVariants:{size:"default"}}),li=Pe("text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",{variants:{size:{default:"h-12 px-4",compact:"h-10 p-4"}},defaultVariants:{size:"default"}}),ui=Pe("align-middle [&:has([role=checkbox])]:pr-0",{variants:{size:{default:"p-4",compact:"py-2 px-4"}},defaultVariants:{size:"default"}}),Nt=u.forwardRef(({className:r,size:t,children:s,...n},a)=>{const o=t??"default";return e.jsx(Hs.Provider,{value:{size:o},children:e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:a,className:R(ci({size:o,className:r})),...n,children:s})})})});Nt.displayName="Table";const yt=u.forwardRef(({className:r,...t},s)=>e.jsx("thead",{ref:s,className:R("[&_tr]:border-b",r),...t}));yt.displayName="TableHeader";const Ct=u.forwardRef(({className:r,...t},s)=>e.jsx("tbody",{ref:s,className:R("[&_tr:last-child]:border-0",r),...t}));Ct.displayName="TableBody";const di=u.forwardRef(({className:r,...t},s)=>e.jsx("tfoot",{ref:s,className:R("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",r),...t}));di.displayName="TableFooter";const $e=u.forwardRef(({className:r,...t},s)=>e.jsx("tr",{ref:s,className:R("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",r),...t}));$e.displayName="TableRow";const B=u.forwardRef(({className:r,...t},s)=>{const{size:n}=u.useContext(Hs);return e.jsx("th",{ref:s,className:R(li({size:n,className:r})),...t})});B.displayName="TableHead";const G=u.forwardRef(({className:r,...t},s)=>{const{size:n}=u.useContext(Hs);return e.jsx("td",{ref:s,className:R(ui({size:n,className:r})),...t})});G.displayName="TableCell";const mi=u.forwardRef(({className:r,...t},s)=>e.jsx("caption",{ref:s,className:R("mt-4 text-sm text-muted-foreground",r),...t}));mi.displayName="TableCaption";const fi={stdio:"本地进程",sse:"服务器推送","streamable-http":"流式 HTTP"};function hi(r){return fi[r]}function pi(r){const[t,s]=u.useState(""),n=Array.isArray(r)?r:[],a=u.useMemo(()=>{if(!t.trim())return n;const i=t.toLowerCase();return n.filter(d=>{const l=(d?.name?.toLowerCase()||"").includes(i),m=(d?.communicationType?.toLowerCase()||"").includes(i),c=d?.communicationType?hi(d.communicationType).toLowerCase().includes(i):!1;return l||m||c})},[n,t]),o=u.useCallback(()=>{s("")},[]);return{searchValue:t,setSearchValue:s,filteredServers:a,clearSearch:o}}function ra(r){const{storageKey:t,defaultConfig:s,validFields:n,loggerName:a}=r,[o,i]=u.useState(()=>{if(typeof window<"u")try{const d=localStorage.getItem(t);if(d){const l=JSON.parse(d);if(l&&n.includes(l.field))return l;console.warn(`[${a}] 无效的排序字段,使用默认配置`)}}catch(d){console.warn(`[${a}] 读取排序配置失败:`,d)}return s});return u.useEffect(()=>{if(typeof window<"u")try{localStorage.setItem(t,JSON.stringify(o))}catch(d){console.warn(`[${a}] 保存排序配置失败:`,d)}},[o,t]),{sortConfig:o,setSortConfig:i}}const xi=["name","communicationType","toolCount"];function gi(){return ra({storageKey:"mcp-server-sort-config",defaultConfig:{field:"name"},validFields:xi,loggerName:"useServerSortPersistence"})}function na(r,t=10){const[s,n]=u.useState(1),[a,o]=u.useState(t),i=Array.isArray(r)?r:[],d=u.useMemo(()=>Math.ceil(i.length/a)||1,[i.length,a]),l=u.useMemo(()=>{const h=(s-1)*a,x=h+a;return i.slice(h,x)},[i,s,a]),m=u.useCallback(h=>{n(Math.max(1,Math.min(h,d)))},[d]),c=u.useCallback(h=>{o(h),n(1)},[]),p=u.useCallback(()=>{n(1)},[]);return{currentPage:s,pageSize:a,totalPages:d,paginatedTools:l,setPage:m,setPageSize:c,resetPage:p}}const vi=J.object({config:J.string().min(2,{message:"配置不能为空"})});function ji({mcpServer:r,mcpServerName:t}){const[s,n]=u.useState(!1),[a,o]=u.useState(!1),[i,d]=u.useState("form"),[l,m]=u.useState(""),c=Je(),{updateConfig:p}=zs(),h=Es(t,r),x=ye({resolver:Ce(Ws),defaultValues:h}),v=ye({resolver:Ce(vi),defaultValues:{config:JSON.stringify({mcpServers:{[t]:r}},null,2)}}),g=u.useCallback(y=>{y||(x.reset(h),v.reset(),m(""),d("form")),n(y)},[x,v,h]),$=u.useCallback(y=>{if(!(y!=="form"&&y!=="json")){if(y==="json"&&i==="form"){const P=x.getValues();try{m(ta(P))}catch{m("")}}else if(y==="form"&&i==="json"){const P=ea(l);P&&x.reset(P)}d(y)}},[i,x,l]),k=u.useCallback(async y=>{if(!c){O.error("配置数据未加载,请稍后重试");return}o(!0);try{const{name:P,config:E}=Bs(y);let I={...c};if(P!==t){const{[t]:L,...V}=I.mcpServers;I.mcpServers=V}I={...I,mcpServers:{...I.mcpServers,[P]:E}},await p(I);const M=P!==t;O.success(M?`MCP 服务 "${t}" 已重命名为 "${P}"`:`MCP 服务 "${P}" 配置已更新`),n(!1)}catch(P){console.error("更新配置失败:",P),O.error(P instanceof Error?P.message:"更新配置失败")}finally{o(!1)}},[c,t,p]),N=u.useCallback(async y=>{if(!c){O.error("配置数据未加载,请稍后重试");return}o(!0);try{const P=sa(y.config);if(!P.success){O.error(P.error||"配置验证失败");return}const E=P.data,I=Object.entries(E);if(I.length!==1){O.error("编辑模式只能修改单个 MCP 服务配置");return}const[M,L]=I[0];let V={...c};if(M!==t){const{[t]:te,...le}=V.mcpServers;V.mcpServers=le}V={...V,mcpServers:{...V.mcpServers,[M]:L}},await p(V);const H=M!==t;O.success(H?`MCP 服务 "${t}" 已重命名为 "${M}"`:`MCP 服务 "${M}" 配置已更新`),n(!1)}catch(P){console.error("更新配置失败:",P),O.error(P instanceof Error?P.message:"更新配置失败")}finally{o(!1)}},[c,t,p]);return e.jsxs(me,{open:s,onOpenChange:g,children:[e.jsx(ke,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 hover:cursor-pointer hover:text-primary transition-all duration-100",children:[e.jsx(lt,{size:14}),e.jsx("span",{children:"配置"})]})}),e.jsxs(oe,{className:"sm:max-w-[600px]",children:[e.jsxs(ie,{className:"mb-4",children:[e.jsxs(ce,{children:["配置 ",t," MCP"]}),e.jsx(Ee,{children:"点击保存后,需要重启服务才会生效。"})]}),e.jsxs(We,{value:i,onValueChange:$,children:[e.jsxs(Qe,{className:"grid w-full grid-cols-2",children:[e.jsx(ge,{value:"form",children:"表单模式"}),e.jsx(ge,{value:"json",children:"高级模式 (JSON)"})]}),e.jsx(ve,{value:"form",className:"mt-4",children:e.jsx(Qn,{form:x,defaultValues:h,onSubmit:k,disabled:a,submitText:a?"保存中...":"保存"})}),e.jsx(ve,{value:"json",className:"mt-4",children:e.jsx(ze,{...v,children:e.jsxs("form",{onSubmit:v.handleSubmit(N),children:[e.jsx("div",{className:"grid gap-4",children:e.jsx(re,{control:v.control,name:"config",render:({field:y})=>e.jsxs(ee,{children:[e.jsx(X,{children:e.jsx(Ze,{className:"resize-none h-[300px] font-mono text-sm",disabled:a,placeholder:`支持三种通信方式:
|
|
35
|
-
|
|
36
|
-
1. 本地进程 (stdio):
|
|
37
|
-
{
|
|
38
|
-
"mcpServers": {
|
|
39
|
-
"local-server": {
|
|
40
|
-
"command": "npx",
|
|
41
|
-
"args": ["-y", "@example/mcp-server"]
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
2. 服务器推送 (SSE):
|
|
47
|
-
{
|
|
48
|
-
"mcpServers": {
|
|
49
|
-
"sse-server": {
|
|
50
|
-
"type": "sse",
|
|
51
|
-
"url": "https://example.com/sse"
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
3. 流式 HTTP:
|
|
57
|
-
{
|
|
58
|
-
"mcpServers": {
|
|
59
|
-
"http-server": {
|
|
60
|
-
"url": "https://example.com/mcp"
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
}`,...y,onChange:P=>{y.onChange(P),m(P.target.value)}})}),e.jsx(ne,{})]})})}),e.jsxs(Oe,{className:"mt-4",children:[e.jsx(He,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:a,children:"取消"})}),e.jsx(A,{type:"submit",disabled:a,children:a?"保存中...":"保存"})]})]})})})]})]})]})}function Si({mcpServerName:r,onRemoveSuccess:t,disabled:s=!1}){const[n,a]=u.useState(!1),o=async()=>{try{if(a(!0),!await U.removeMCPServer(r))throw new Error("删除服务器失败");O.success(`MCP 服务 "${r}" 已删除`),t&&await t()}catch(i){console.error("删除 MCP 服务失败:",i),O.error(`删除 MCP 服务失败: ${i instanceof Error?i.message:"未知错误"}`)}finally{a(!1)}};return e.jsxs(Us,{children:[e.jsx(No,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:s||n,className:R("flex items-center gap-1 hover:cursor-pointer text-destructive hover:text-red-700 transition-all duration-100",(s||n)&&"opacity-50 cursor-not-allowed"),children:[e.jsx(Sn,{size:14}),e.jsx("span",{children:"卸载"})]})}),e.jsxs(pt,{children:[e.jsxs(xt,{children:[e.jsxs(vt,{children:["确定要删除这个(",r,")MCP服务吗?"]}),e.jsx(jt,{children:"删除后,对应的工具列表也会移除。"})]}),e.jsxs(gt,{children:[e.jsx(bt,{children:"取消"}),e.jsx(St,{onClick:o,disabled:s||n,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:n?"删除中...":"确定"})]})]})]})}const aa=({className:r,...t})=>e.jsx("nav",{"aria-label":"pagination",className:R("mx-auto flex w-full justify-center",r),...t});aa.displayName="Pagination";const oa=u.forwardRef(({className:r,...t},s)=>e.jsx("ul",{ref:s,className:R("flex flex-row items-center gap-1",r),...t}));oa.displayName="PaginationContent";const Me=u.forwardRef(({className:r,...t},s)=>e.jsx("li",{ref:s,className:R("",r),...t}));Me.displayName="PaginationItem";const Et=({className:r,isActive:t,size:s="icon",...n})=>e.jsx("a",{"aria-current":t?"page":void 0,className:R(ht({variant:t?"outline":"ghost",size:s}),r),...n});Et.displayName="PaginationLink";const ia=({className:r,...t})=>e.jsxs(Et,{"aria-label":"Go to previous page",size:"default",className:R("gap-1 pl-2.5",r),...t,children:[e.jsx(za,{className:"h-4 w-4"}),e.jsx("span",{children:"上一页"})]});ia.displayName="PaginationPrevious";const ca=({className:r,...t})=>e.jsxs(Et,{"aria-label":"Go to next page",size:"default",className:R("gap-1 pr-2.5",r),...t,children:[e.jsx("span",{children:"下一页"}),e.jsx(Va,{className:"h-4 w-4"})]});ca.displayName="PaginationNext";const Rs=({className:r,...t})=>e.jsxs("span",{"aria-hidden":!0,className:R("flex h-9 w-9 items-center justify-center",r),...t,children:[e.jsx(Fa,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"更多页"})]});Rs.displayName="PaginationEllipsis";function bi(r,t){const s=[];if(t<=7)for(let a=1;a<=t;a++)s.push(a);else if(r<=4){for(let a=1;a<=5;a++)s.push(a);s.push(-2,t)}else if(r>=t-3){s.push(1,-1);for(let a=t-3;a<=t;a++)s.push(a)}else s.push(1,-1,r-1,r,r+1,-2,t);return s}function la({currentPage:r,totalPages:t,setPage:s}){if(!(t>1))return null;const a=bi(r,t);return e.jsx("div",{className:"flex items-end justify-start py-4",children:e.jsx(aa,{children:e.jsxs(oa,{children:[e.jsx(Me,{children:e.jsx(ia,{onClick:()=>s(r-1),className:R("cursor-pointer",r===1&&"pointer-events-none opacity-50")})}),a.map(o=>o===-1?e.jsx(Me,{children:e.jsx(Rs,{})},"ellipsis-start"):o===-2?e.jsx(Me,{children:e.jsx(Rs,{})},"ellipsis-end"):e.jsx(Me,{children:e.jsx(Et,{onClick:()=>s(o),isActive:r===o,className:"cursor-pointer",children:o})},`page-${o}`)),e.jsx(Me,{children:e.jsx(ca,{onClick:()=>s(r+1),className:R("cursor-pointer",r===t&&"pointer-events-none opacity-50")})})]})})})}function ua({value:r,onChange:t,placeholder:s="搜索服务名、工具名、描述...",className:n}){const a=u.useRef(null),o=d=>{t(d.target.value)},i=()=>{t(""),a.current?.focus()};return e.jsx("div",{className:R("relative",n),children:e.jsxs("div",{className:"relative flex items-center",children:[e.jsx(Wa,{className:"absolute left-3 h-4 w-4 text-muted-foreground pointer-events-none"}),e.jsx(se,{ref:a,type:"text",value:r,onChange:o,placeholder:s,className:"pl-9 pr-9 w-64","aria-label":"搜索工具"}),r&&e.jsx("button",{type:"button",onClick:i,className:"absolute right-3 text-muted-foreground hover:text-foreground transition-colors","aria-label":"清除搜索",children:e.jsx(gn,{className:"h-4 w-4"})})]})})}const wi=[{value:"name",label:"按名称排序"},{value:"communicationType",label:"按通信类型排序"},{value:"toolCount",label:"按工具数量排序"}];function Ni({value:r,onChange:t}){return e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Re,{value:r.field,onValueChange:s=>t({field:s}),children:[e.jsx(be,{id:"server-sort-field",className:"w-40",children:e.jsx(Te,{})}),e.jsx(we,{children:wi.map(s=>e.jsx(ae,{value:s.value,children:s.label},s.value))})]})})}function yi({status:r}){const t={connected:"bg-green-500",disconnected:"bg-red-500",connecting:"bg-yellow-500",error:"bg-gray-500"},s={connected:"已连接",disconnected:"未连接",connecting:"连接中",error:"错误"};return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:R("flex size-2 rounded-full",t[r]),title:s[r]}),s[r]]})}function Ci(r,t,s,n,a){return{name:r,config:t,communicationType:s,toolCount:n,status:a}}function Ei(r){return"command"in r&&typeof r.command=="string"?"stdio":"type"in r&&r.type==="sse"?"sse":"streamable-http"}const Ri={stdio:"stdio",sse:"sse","streamable-http":"http"};function Ti({className:r}){const{servers:t,loading:s,refresh:n}=Wn(),{sortConfig:a,setSortConfig:o}=gi();u.useEffect(()=>{n()},[n]);const i=u.useMemo(()=>t.map(N=>Ci(N.name,N.config,Ei(N.config),N.tools.length,N.status)),[t]),d=u.useMemo(()=>{const N=[...i],{field:y}=a;return N.sort((P,E)=>{switch(y){case"name":return P.name.localeCompare(E.name,"zh-CN");case"communicationType":return P.communicationType.localeCompare(E.communicationType);case"toolCount":return(E.toolCount??0)-(P.toolCount??0);default:return 0}}),N},[i,a]),{searchValue:l,setSearchValue:m,filteredServers:c,clearSearch:p}=pi(d),{currentPage:h,totalPages:x,paginatedTools:v,setPage:g}=na(c,10),$=v,k=u.useCallback(async()=>{try{await n(),O.success("刷新成功")}catch{O.error("刷新失败")}},[n]);return u.useEffect(()=>{g(1)},[l,g]),e.jsxs("div",{className:R("flex flex-col gap-4 w-full",r),children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(Ni,{value:a,onChange:o}),e.jsx(ua,{value:l,onChange:m,placeholder:"搜索服务器名称、通信类型..."})]}),l&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:["找到 ",c.length," 个结果",c.length>0&&e.jsx("button",{type:"button",onClick:p,className:"ml-2 text-primary hover:underline",children:"清除搜索"})]}),e.jsx("div",{className:"rounded-md border",children:$.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[e.jsx(Pn,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:l?"没有找到匹配的服务器":"暂无可用服务器"}),l&&e.jsx(A,{variant:"outline",size:"sm",onClick:p,children:"清除搜索"})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Nt,{size:"compact",children:[e.jsx(yt,{children:e.jsxs($e,{children:[e.jsx(B,{children:"服务器名称"}),e.jsx(B,{className:"w-[100px]",children:"状态"}),e.jsx(B,{className:"w-[120px]",children:"通信类型"}),e.jsx(B,{className:"w-[100px] text-right",children:"工具数量"}),e.jsx(B,{className:"w-[220px] text-right",children:"操作"})]})}),e.jsx(Ct,{children:$.map(N=>e.jsxs($e,{children:[e.jsx(G,{className:"font-medium",children:N.name}),e.jsx(G,{children:N.status?e.jsx(yi,{status:N.status}):"-"}),e.jsx(G,{children:e.jsx(de,{variant:"secondary",className:"rounded-md",children:Ri[N.communicationType]})}),e.jsx(G,{className:"text-right text-muted-foreground",children:N.toolCount??"-"}),e.jsx(G,{children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(ji,{mcpServerName:N.name,mcpServer:N.config}),e.jsx(Si,{mcpServerName:N.name,onRemoveSuccess:k,disabled:s})]})})]},N.name))})]}),e.jsx(la,{currentPage:h,totalPages:x,setPage:g})]})})]})}function ki(){const[r,t]=u.useState(!1);return e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(ke,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8","aria-label":"MCP服务列表",title:"MCP服务列表",children:e.jsx(_a,{className:"size-4"})})}),e.jsxs(oe,{className:"max-w-5xl max-h-[85vh]",children:[e.jsx(ie,{children:e.jsx(ce,{children:"MCP 服务器列表"})}),e.jsx(Ti,{})]})]})}const Ne=u.forwardRef(({className:r,children:t,...s},n)=>e.jsx("div",{ref:n,className:R("relative overflow-auto",r),...s,children:t}));Ne.displayName="ScrollArea";const Ii=u.forwardRef(({className:r,orientation:t="vertical",...s},n)=>e.jsx("div",{ref:n,className:R("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 w-full border-t border-t-transparent p-[1px]",r),...s,children:e.jsx("div",{className:"relative flex-1 rounded-full bg-border"})}));Ii.displayName="ScrollBar";const da=u.forwardRef(({className:r,orientation:t="horizontal",decorative:s=!0,...n},a)=>e.jsx(On,{ref:a,decorative:s,orientation:t,className:R("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",r),...n}));da.displayName=On.displayName;const ma=r=>r?new Date(r).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):"未知时间",fa=r=>r?r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`:"-",$i=(r,t)=>{const s=r.timestamp||Date.now();return`${r.toolName}-${s}-${t}`},at=r=>{if(!r)return null;try{return JSON.stringify(r,null,2)}catch{return String(r)}};function Pi(){const[r,t]=u.useState(!1),[s,n]=u.useState([]),[a,o]=u.useState(!1),[i,d]=u.useState(!1),[l,m]=u.useState(null),[c,p]=u.useState(null),[h,x]=u.useState(null),[v]=u.useState(50),[g,$]=u.useState(0),k=u.useCallback(async(E=!1)=>{E?d(!0):o(!0),m(null);try{const M=await(await fetch(`/api/tool-calls/logs?limit=${v}`)).json();M.success&&M.data?(n(M.data.records),$(M.data.total)):m(M.error?.message||"获取日志失败")}catch(I){m("网络请求失败"),console.error("获取工具调用日志失败:",I)}finally{E?d(!1):o(!1)}},[v]);u.useEffect(()=>{r?k():(p(null),x(null))},[r,k]);const N=(E,I)=>{h!==I&&(p(E),x(I))},y=()=>{},P=()=>{p(null),x(null)};return e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(ke,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8","aria-label":"MCP工具调用日志",title:"MCP工具调用日志",children:e.jsx(tt,{className:"size-4"})})}),e.jsxs(oe,{className:"max-w-6xl max-h-[80vh]",onMouseLeave:P,children:[e.jsx(ie,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-5 w-5"}),"MCP 工具调用日志",g>0&&e.jsxs("span",{className:"text-sm font-normal text-muted-foreground ml-2",children:["(共 ",g," 条记录)"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:()=>k(!0),disabled:i,children:[e.jsx(Ba,{className:`h-4 w-4 ${i?"animate-spin":""}`}),"刷新"]})]})})}),e.jsxs("div",{className:"flex-1 flex gap-4",children:[e.jsx("div",{className:"flex-1",children:a?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Se,{className:"h-8 w-8 animate-spin text-muted-foreground"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(tt,{className:"h-4 w-4 text-muted-foreground/50"})})]}),e.jsxs("div",{className:"mt-4 text-center",children:[e.jsx("p",{className:"text-muted-foreground font-medium",children:"正在加载日志数据"}),e.jsx("p",{className:"text-muted-foreground/70 text-sm mt-1",children:"请稍候片刻..."})]})]}):l?e.jsx("div",{className:"text-center py-8",children:e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-6 max-w-md mx-auto",children:[e.jsx(As,{className:"h-12 w-12 text-destructive mx-auto mb-4"}),e.jsx("h3",{className:"text-destructive font-semibold text-lg mb-2",children:"加载失败"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4 leading-relaxed",children:l}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs(A,{onClick:()=>k(),variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(nr,{className:"h-4 w-4"}),"重试加载"]}),e.jsx(A,{onClick:()=>k(!0),variant:"ghost",size:"sm",className:"text-xs",children:"强制刷新"})]})]})}):s.length===0?e.jsx("div",{className:"text-center py-8",children:e.jsxs("div",{className:"bg-muted/30 border border-muted rounded-lg p-6 max-w-md mx-auto",children:[e.jsx(tt,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"font-medium text-lg mb-2",children:"暂无工具调用记录"}),e.jsx("p",{className:"text-muted-foreground text-sm leading-relaxed mb-4",children:"当前还没有任何工具调用记录。当您开始使用工具时,相关的调用信息会在这里显示。"}),e.jsxs(A,{onClick:()=>k(!0),variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(nr,{className:"h-4 w-4"}),"检查更新"]})]})}):e.jsx(Ne,{className:"h-[60vh]",children:e.jsxs(Nt,{children:[e.jsx(yt,{children:e.jsxs($e,{children:[e.jsx(B,{children:"工具名称"}),e.jsx(B,{children:"服务器"}),e.jsx(B,{children:"状态"}),e.jsx(B,{children:"耗时"}),e.jsx(B,{children:"时间"})]})}),e.jsx(Ct,{children:s.map((E,I)=>e.jsxs($e,{className:`cursor-pointer transition-colors ${h===I?"bg-muted/50":"hover:bg-muted/30"}`,onMouseEnter:()=>N(E,I),children:[e.jsx(G,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("div",{children:E.toolName}),E.originalToolName&&E.originalToolName!==E.toolName&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["原始: ",E.originalToolName]})]})}),e.jsx(G,{children:E.serverName||e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(G,{children:e.jsx(de,{variant:E.success?void 0:"destructive",className:`gap-1 w-[50px] text-center ${E.success?"bg-green-600 hover:bg-green-600":"bg-red-600 hover:bg-red-600"}`,children:E.success?"成功":"失败"})}),e.jsx(G,{children:fa(E.duration)}),e.jsx(G,{className:"text-muted-foreground text-sm",children:ma(E.timestamp)})]},$i(E,I)))})]})})}),c&&e.jsx("div",{className:"w-96 border-l pl-4",onMouseEnter:y,children:e.jsx(Oi,{log:c})})]})]})]})}function ot({size:r="sm",copyContent:t,className:s=""}){const[n,a]=u.useState(!1),o=u.useRef(null),i=async()=>{try{await navigator.clipboard.writeText(t),a(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{a(!1)},3e3)}catch(d){console.error("复制失败:",d)}};return u.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]),e.jsx(A,{variant:"ghost",size:r,className:`${s} ${n?"text-green-600 hover:text-green-700":""}`,onClick:i,children:n?e.jsx(mt,{}):e.jsx(ut,{})})}function Oi({log:r}){const t=s=>{try{return JSON.stringify(s,null,2)}catch{return String(s)}};return e.jsx(Le,{className:"h-[60vh]",children:e.jsxs("div",{className:"p-4 h-full flex flex-col",children:[e.jsxs(We,{defaultValue:"arguments",className:"flex-1 flex flex-col min-h-0",children:[e.jsxs(Qe,{className:"grid w-full grid-cols-3 flex-shrink-0",children:[e.jsx(ge,{value:"arguments",children:"入参"}),e.jsx(ge,{value:"result",children:"出参"}),e.jsx(ge,{value:"raw",children:"原始数据"})]}),e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx(ve,{value:"arguments",className:"h-full data-[state=active]:flex data-[state=active]:flex-col",children:e.jsx(Ne,{className:"h-full",children:r.arguments?e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto text-wrap break-words",children:at(r.arguments)}),e.jsx(ot,{copyContent:at(r.arguments)||"",className:"absolute top-2 right-2 hover:bg-slate-200 w-[30px] h-[30px]"})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-8",children:[e.jsx(Ms,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"无入参"})]})})}),e.jsx(ve,{value:"result",className:"h-full data-[state=active]:flex data-[state=active]:flex-col",children:e.jsx(Ne,{className:"h-full",children:r.success?r.result?e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto text-wrap break-words",children:at(r.result)}),e.jsx(ot,{copyContent:at(r.result)||"",className:"absolute top-2 right-2 hover:bg-slate-200 w-[30px] h-[30px]"})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-8",children:[e.jsx(Cs,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"无出参"})]}):e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 p-3 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(As,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"font-medium text-destructive",children:"调用失败"})]}),r.error&&e.jsx("pre",{className:"text-xs text-destructive/80 whitespace-pre-wrap",children:r.error})]}),r.error&&e.jsx(ot,{copyContent:r.error||"",className:"absolute top-2 right-2"})]})})}),e.jsx(ve,{value:"raw",className:"h-full data-[state=active]:flex data-[state=active]:flex-col",children:e.jsx(Ne,{className:"h-full",children:e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto text-wrap break-words",children:t(r)}),e.jsx(ot,{copyContent:t(r),className:"absolute top-2 right-2 hover:bg-slate-200 w-[30px] h-[30px]"})]})})})]})]}),e.jsx(da,{className:"my-4 flex-shrink-0"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex justify-between flex-shrink-0",children:[e.jsxs("span",{children:["耗时: ",fa(r.duration)]}),e.jsx("span",{children:ma(r.timestamp)})]})]})})}function Li(){const{servers:r}=Wn(),t=r.length,s=r.filter(n=>n.connected).length;return e.jsxs(Le,{className:"@container/card",children:[e.jsxs(qe,{className:"relative",children:[e.jsx(Xe,{children:"MCP服务"}),e.jsxs(Ue,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:[s,"/",t]}),e.jsx("div",{className:"absolute right-4 top-4",children:e.jsx(ft,{showValue:!1,value:s,maxValue:Math.max(t,1),activeColor:"#16a34a",inactiveColor:"#f87171",size:30,symbol:""})})]}),e.jsxs(Ye,{className:"flex items-center justify-between gap-1 text-sm",children:[e.jsxs("div",{className:"text-muted-foreground",children:["已连接 ",s," 个,共 ",t," 个服务"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ii,{}),e.jsx(ki,{}),e.jsx(Pi,{})]})]})]})}function Ai({disabled:r=!1,variant:t="outline",className:s="",restartingText:n="重启中...",defaultText:a="重启服务",iconMode:o=!1}){const{loading:{isRestarting:i},restartService:d}=je(),l=Un(),m=async()=>{try{await d()}catch(p){console.error("[RestartButton] 重启失败:",p)}},c=()=>i?l.enabled&&l.startTime?"重连中...":n:a;return o?e.jsx(A,{type:"button",onClick:m,variant:"secondary",size:"icon",className:"size-8",disabled:i||r,"aria-label":"重启服务",title:"重启服务",children:i?e.jsx(Se,{className:"size-4 animate-spin"}):e.jsx(ar,{className:"size-4"})}):e.jsxs(A,{type:"button",onClick:m,variant:t,disabled:i||r,className:Dn("flex items-center gap-2 w-[120px]",s),children:[i?e.jsx(Se,{className:"size-4 animate-spin"}):e.jsx(ar,{className:"size-4"}),c()]})}const Mi=J.object({modelscope:J.object({apiKey:J.string().optional()}),platforms:J.object({coze:J.object({token:J.string().optional()})}),connection:J.object({heartbeatInterval:J.number().min(1e3,{message:"心跳间隔不能小于1000毫秒"}),heartbeatTimeout:J.number().min(1e3,{message:"心跳超时不能小于1000毫秒"}),reconnectInterval:J.number().min(1e3,{message:"重连间隔不能小于1000毫秒"})})});function Di(){const[r,t]=u.useState(!1),[s,n]=u.useState(!1),a=Je(),{updateConfig:o}=Uo(),i=ye({resolver:Ce(Mi),defaultValues:{platforms:{coze:{token:a?.platforms?.coze?.token||""}},modelscope:{apiKey:a?.modelscope?.apiKey||""},connection:{heartbeatInterval:a?.connection?.heartbeatInterval||3e4,heartbeatTimeout:a?.connection?.heartbeatTimeout||1e4,reconnectInterval:a?.connection?.reconnectInterval||5e3}}});u.useEffect(()=>{i.reset({modelscope:{apiKey:a?.modelscope?.apiKey||""},connection:{heartbeatInterval:a?.connection?.heartbeatInterval||3e4,heartbeatTimeout:a?.connection?.heartbeatTimeout||1e4,reconnectInterval:a?.connection?.reconnectInterval||5e3}})},[a,i]);async function d(l){if(!a){O.error("配置数据未加载,请稍后重试");return}n(!0);try{const m={...a,modelscope:{apiKey:l.modelscope.apiKey},connection:{heartbeatInterval:l.connection.heartbeatInterval,heartbeatTimeout:l.connection.heartbeatTimeout,reconnectInterval:l.connection.reconnectInterval},platforms:{...a?.platforms??{},coze:{...a?.platforms?.coze??{},token:l.platforms.coze.token}}};await o(m),O.success("配置已更新"),t(!1)}catch(m){console.error("更新配置失败:",m),O.error(m instanceof Error?m.message:"更新配置失败")}finally{n(!1)}}return e.jsxs(me,{open:r,onOpenChange:t,children:[e.jsx(ke,{asChild:!0,children:e.jsx(A,{variant:"secondary",size:"icon",className:"size-8",children:e.jsx(lt,{className:"size-4"})})}),e.jsxs(oe,{className:"sm:max-w-[600px]",children:[e.jsxs(ie,{children:[e.jsx(ce,{children:"系统设置"}),e.jsx(Ee,{children:"配置平台认证和连接参数"})]}),e.jsx(ze,{...i,children:e.jsxs("form",{onSubmit:i.handleSubmit(d),children:[e.jsxs("div",{className:"grid gap-4 max-h-[60vh] overflow-y-auto",children:[e.jsx(re,{control:i.control,name:"modelscope.apiKey",render:({field:l})=>e.jsxs(ee,{children:[e.jsx(pe,{children:"魔搭社区 API Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(X,{children:e.jsx(se,{placeholder:"魔搭社区 API Key",className:"font-mono text-sm",type:"password",disabled:s,autoComplete:"off","data-1p-ignore":!0,...l})}),e.jsx(A,{variant:"outline",type:"button",onClick:()=>{window.open("https://www.modelscope.cn/my/myaccesstoken","_blank")},children:"打开魔搭社区"})]}),e.jsx(ne,{})]})}),e.jsx(re,{control:i.control,name:"platforms.coze.token",render:({field:l})=>e.jsxs(ee,{children:[e.jsx(pe,{children:"扣子身份凭证"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(X,{children:e.jsx(se,{placeholder:"扣子身份凭证",className:"font-mono text-sm",type:"password",autoComplete:"off","data-1p-ignore":!0,disabled:s,...l})}),e.jsx(A,{variant:"outline",type:"button",onClick:()=>{window.open("https://www.coze.cn/open/oauth/sats","_blank")},children:"打开扣子平台"})]}),e.jsx(ne,{})]})}),e.jsx(re,{control:i.control,name:"connection.heartbeatInterval",render:({field:l})=>e.jsxs(ee,{children:[e.jsx(pe,{children:"心跳间隔(毫秒)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(X,{children:e.jsx(se,{placeholder:"心跳间隔(毫秒)",className:"font-mono text-sm",type:"number",disabled:s,...l,value:l.value||"",onChange:m=>{const c=m.target.value;l.onChange(c===""?"":Number(c))}})}),e.jsx("span",{className:"text-sm text-muted-foreground w-[50px]",children:"毫秒"})]}),e.jsx(ne,{})]})}),e.jsx(re,{control:i.control,name:"connection.heartbeatTimeout",render:({field:l})=>e.jsxs(ee,{children:[e.jsx(pe,{children:"心跳超时(毫秒)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(X,{children:e.jsx(se,{placeholder:"心跳超时(毫秒)",className:"font-mono text-sm",type:"number",disabled:s,...l,value:l.value||"",onChange:m=>{const c=m.target.value;l.onChange(c===""?"":Number(c))}})}),e.jsx("span",{className:"text-sm text-muted-foreground w-[50px]",children:"毫秒"})]}),e.jsx(ne,{})]})}),e.jsx(re,{control:i.control,name:"connection.reconnectInterval",render:({field:l})=>e.jsxs(ee,{children:[e.jsx(pe,{children:"重连间隔(毫秒)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(X,{children:e.jsx(se,{placeholder:"重连间隔(毫秒)",className:"font-mono text-sm",type:"number",disabled:s,...l,value:l.value||"",onChange:m=>{const c=m.target.value;l.onChange(c===""?"":Number(c))}})}),e.jsx("span",{className:"text-sm text-muted-foreground w-[50px]",children:"毫秒"})]}),e.jsx(ne,{})]})})]}),e.jsxs(Oe,{className:"mt-4",children:[e.jsx(He,{asChild:!0,children:e.jsx(A,{variant:"outline",disabled:s,children:"取消"})}),e.jsx(A,{type:"submit",disabled:s,children:s?"保存中...":"保存"})]})]})})]})]})}const it=5;function qi(){const r=Je(),t=u.useMemo(()=>{if(!r)return 0;let n=0;return r.modelscope?.apiKey&&n++,r.platforms?.coze?.token&&n++,r.connection?.heartbeatInterval&&n++,r.connection?.heartbeatTimeout&&n++,r.connection?.reconnectInterval&&n++,n},[r]),s=t/it;return e.jsxs(Le,{className:"@container/card",children:[e.jsxs(qe,{className:"relative",children:[e.jsx(Xe,{children:"系统设置"}),e.jsxs(Ue,{className:"@[250px]/card:text-3xl text-2xl font-semibold tabular-nums",children:["已配置 ",t,"/",it]}),e.jsx("div",{className:"absolute right-4 top-4",children:e.jsx(ft,{showValue:!0,value:t,maxValue:it,activeColor:s>=.8?"#16a34a":s>=.5?"#f59e0b":"#f87171",inactiveColor:"#e5e7eb",size:30,symbol:""})})]}),e.jsxs(Ye,{className:"flex items-center justify-between gap-1 text-sm",children:[e.jsx("div",{className:"text-muted-foreground",children:s===1?"配置已完成":s>=.6?`还差 ${it-t} 项配置`:"请完善系统配置"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ai,{iconMode:!0}),e.jsx(Di,{})]})]})]})}function Ui(){return e.jsxs("div",{className:"*:data-[slot=card]:shadow-xs @xl/main:grid-cols-2 @5xl/main:grid-cols-4 grid grid-cols-1 gap-4 px-4 *:data-[slot=card]:bg-gradient-to-t *:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card dark:*:data-[slot=card]:bg-card lg:px-6",children:[e.jsx(ko,{}),e.jsx(Vo,{}),e.jsx(Li,{}),e.jsx(qi,{})]})}function zi({text:r,maxLength:t=100,storageKey:s,className:n,textSize:a="text-sm"}){const o=()=>{if(!s)return!1;try{return localStorage.getItem(s)==="true"}catch{return!1}},[i,d]=u.useState(o);u.useEffect(()=>{if(s)try{localStorage.setItem(s,String(i))}catch(p){console.warn("无法写入 localStorage:",p)}},[i,s]),u.useEffect(()=>{if(s){const p=localStorage.getItem(s);d(p==="true")}},[s]);const l=()=>{d(p=>!p)},m=r||"-",c=m.length>t;return e.jsxs("div",{className:R("flex flex-col gap-1",n),children:[i||!c?e.jsx("p",{className:R("break-words",a),children:m}):e.jsxs("p",{className:R("break-words",a),children:[m.slice(0,t),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),c&&e.jsx("button",{type:"button",onClick:l,className:R("text-primary hover:underline flex items-center gap-1 w-fit",a),children:i?e.jsxs(e.Fragment,{children:["收起 ",e.jsx(Ls,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["展开 ",e.jsx(dt,{className:"h-4 w-4"})]})})]})}const Fi=Pe("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),_e=u.forwardRef(({className:r,variant:t,...s},n)=>e.jsx("div",{ref:n,role:"alert",className:R(Fi({variant:t}),r),...s}));_e.displayName="Alert";const ha=u.forwardRef(({className:r,...t},s)=>e.jsx("h5",{ref:s,className:R("mb-1 font-medium leading-none tracking-tight",r),...t}));ha.displayName="AlertTitle";const Be=u.forwardRef(({className:r,...t},s)=>e.jsx("div",{ref:s,className:R("text-sm [&_p]:leading-relaxed",r),...t}));Be.displayName="AlertDescription";const pa=Ja,Js=Ga,Xs=Ha,Rt=u.forwardRef(({className:r,sideOffset:t=4,...s},n)=>e.jsx(Ln,{ref:n,sideOffset:t,className:R("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",r),...s}));Rt.displayName=Ln.displayName;function Ts(r){if(!r||typeof r!="object")return st();switch(r.type){case"string":{if(r.enum)return po(r.enum);let t=Ie();return r.minLength&&(t=t.min(r.minLength)),r.maxLength&&(t=t.max(r.maxLength)),r.pattern&&(t=t.regex(new RegExp(r.pattern))),t}case"number":case"integer":{let t=xo();return r.type==="integer"&&(t=t.int()),typeof r.minimum=="number"&&(t=t.min(r.minimum)),typeof r.maximum=="number"&&(t=t.max(r.maximum)),typeof r.multipleOf=="number"&&(t=t.multipleOf(r.multipleOf)),t}case"boolean":return ho();case"array":if(r.items){const t=Ts(r.items);let s=cr(t);return typeof r.minItems=="number"&&(s=s.min(r.minItems)),typeof r.maxItems=="number"&&(s=s.max(r.maxItems)),s}return cr(st());case"object":if(r.properties&&Object.keys(r.properties).length>0){const t={},s=r.required||[];for(const[n,a]of Object.entries(r.properties)){let o=Ts(a);s.includes(n)||(o=o.optional()),t[n]=o}return Ge(t)}return fo(Ie(),st());default:return st()}}function ks(r){if(r)switch(r.type){case"string":return r.enum?r.enum[0]:"";case"number":case"integer":return 0;case"boolean":return!1;case"array":return[];case"object":if(r.properties){const t={};for(const[s,n]of Object.entries(r.properties))t[s]=ks(n);return t}return{};default:return}}function Vi(r){if(!r||!r.properties)return{};const t={},s=r.required||[];for(const[n,a]of Object.entries(r.properties))if(s.includes(n))t[n]=ks(a);else{const o=ks(a);o!==void 0&&o!==""&&(t[n]=o)}return t}const Wi=u.memo(function({name:t,schema:s,form:n,renderFormField:a}){const{fields:o,append:i,remove:d}=Xa({control:n.control,name:t}),l=()=>{const m=s.items;let c;switch(m.type){case"string":c=m.enum?m.enum[0]:"";break;case"number":case"integer":c=0;break;case"boolean":c=!1;break;case"array":c=[];break;case"object":c={};break;default:c=""}i(c)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium",children:["数组项目 (",s.items?.type||"unknown",")"]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",onClick:l,className:"h-8 px-2",children:[e.jsx(Os,{className:"h-3 w-3 mr-1"}),"添加"]})]}),o.length===0?e.jsx("div",{className:"text-center py-4 border border-dashed rounded-md",children:e.jsx("span",{className:"text-sm text-muted-foreground",children:"暂无数组项目"})}):e.jsx("div",{className:"space-y-3",children:o.map((m,c)=>e.jsxs("div",{className:"relative p-3 border rounded-md bg-muted/20",children:[e.jsx("div",{className:"absolute top-2 right-2",children:e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(c),className:"h-6 w-6 p-0 text-red-500 hover:text-red-700",children:e.jsx(Ya,{className:"h-3 w-3"})})}),e.jsxs("div",{className:"pr-8",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground mb-2 block",children:["项目 ",c+1]}),e.jsx(re,{control:n.control,name:`${t}.${c}`,render:()=>e.jsx(ee,{children:s.items?.type==="object"||s.items?.type==="array"?e.jsx("div",{className:"ml-6 border-l-2 border-muted pl-4",children:a(`${t}.${c}`,s.items)}):a(`${t}.${c}`,s.items)})})]})]},m.id))})]})}),_i=u.memo(function({name:t,schema:s,form:n,renderFormField:a,getTypeBadge:o}){return!s.properties||Object.keys(s.properties).length===0?e.jsx("div",{className:"text-center py-4 border border-dashed rounded-md",children:e.jsx("span",{className:"text-sm text-muted-foreground",children:"对象无定义字段"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("span",{className:"text-sm font-medium",children:"对象字段"}),Object.entries(s.properties).map(([i,d])=>e.jsx("div",{className:"ml-6 border-l-2 border-muted pl-4",children:e.jsx(re,{control:n.control,name:`${t}.${i}`,render:()=>e.jsxs(ee,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(pe,{children:[s.required?.includes(i)&&e.jsx("span",{className:"text-red-500 mr-1",children:"*"}),i]}),e.jsx(de,{variant:"secondary",className:`text-xs ${o(d.type)}`,children:d.type}),d.description&&e.jsxs(Js,{children:[e.jsx(Xs,{children:e.jsx(Ds,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Rt,{children:e.jsx("p",{className:"max-w-xs whitespace-pre-wrap",children:d.description})})]})]}),a(`${t}.${i}`,d),d.description&&e.jsx(De,{children:d.description}),e.jsx(ne,{})]})})},`${t}-${i}`))]})}),Bi=u.memo(function(){return e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsxs("div",{className:"text-center space-y-4 max-w-sm mx-auto p-6",children:[e.jsx("div",{className:"mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center",children:e.jsx(mt,{className:"h-8 w-8 text-green-600"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"无需输入参数"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'点击"调用工具"按钮执行,无需输入任何参数。'})]})]})})}),Gi=u.memo(function({tool:t,form:s,renderFormField:n}){return t?.inputSchema?.properties?e.jsx(ze,{...s,children:e.jsx(Ne,{className:"h-full",children:e.jsx("div",{className:"space-y-4 p-2",children:Object.entries(t.inputSchema.properties).map(([a,o])=>e.jsx(re,{control:s.control,name:a,render:()=>e.jsxs(ee,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(pe,{children:[t.inputSchema.required?.includes(a)&&e.jsx("span",{className:"text-red-500 mr-1",children:"*"}),a]}),e.jsx(de,{variant:"secondary",className:`text-xs ${o.type==="string"?"bg-blue-100 text-blue-800":o.type==="number"||o.type==="integer"?"bg-green-100 text-green-800":o.type==="boolean"?"bg-purple-100 text-purple-800":o.type==="array"?"bg-orange-100 text-orange-800":(o.type==="object","bg-gray-100 text-gray-800")}`,children:o.type}),o.description&&e.jsxs(Js,{children:[e.jsx(Xs,{children:e.jsx(Ds,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Rt,{children:e.jsx("p",{className:"max-w-xs whitespace-pre-wrap",children:o.description})})]})]}),n(a,o),e.jsx(ne,{})]})},`${t.name}-${a}`))})})}):e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Ms,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-muted-foreground",children:"该工具无参数定义"})]})});function Hi({open:r,onOpenChange:t,tool:s}){const[n,a]=u.useState("form"),[o,i]=u.useState(`{
|
|
64
|
-
|
|
65
|
-
}`),[d,l]=u.useState(null),[m,c]=u.useState(!1),[p,h]=u.useState(null),[x,v]=u.useState(!1),g=u.useRef(null),$=u.useMemo(()=>s?.inputSchema?Ts(s.inputSchema):Ge({}),[s?.inputSchema]),k=u.useMemo(()=>s?.inputSchema?Vi(s.inputSchema):{},[s?.inputSchema]),N=ye({resolver:Ce($),defaultValues:k,mode:"onChange"});u.useEffect(()=>{if(s?.inputSchema){N.reset(k);try{i(JSON.stringify(k,null,2))}catch{i(`{
|
|
66
|
-
|
|
67
|
-
}`)}}else N.reset({}),i(`{
|
|
68
|
-
|
|
69
|
-
}`)},[s?.inputSchema,k,N]),u.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const y=u.useCallback(()=>{a("form"),i(`{
|
|
70
|
-
|
|
71
|
-
}`),l(null),h(null),v(!1),s?.inputSchema&&N.reset(k)},[s?.inputSchema,k,N]),P=u.useCallback(S=>{if(S==="json"&&n==="form"){const b=N.getValues();try{i(JSON.stringify(b,null,2))}catch{i(`{
|
|
72
|
-
|
|
73
|
-
}`)}}else if(S==="form"&&n==="json")try{const b=JSON.parse(o);for(const C of Object.keys(b))N.setValue(C,b[C])}catch{}a(S)},[n,o,N]),E=u.useCallback(S=>{S||y(),t(S)},[t,y]),I=u.useCallback(S=>{try{return JSON.parse(S),!0}catch{return!1}},[]),M=u.useCallback(async()=>{if(!s)return;let S;if(!s?.inputSchema?.properties||Object.keys(s.inputSchema.properties).length===0)S={};else if(n==="form"){const C=N.getValues();if(!await N.trigger()){O.error("请检查表单中的错误");return}S=C}else{if(!I(o)){O.error("输入参数不是有效的JSON格式");return}S=JSON.parse(o)}c(!0),h(null),l(null);try{const C=await U.callTool(s.serverName,s.toolName,S);l(C),O.success("工具调用成功")}catch(C){const f=C instanceof Error?C.message:"调用工具失败";h(f),O.error(f)}finally{c(!1)}},[s,n,N,o,I]),L=u.useCallback(async()=>{const S=d?JSON.stringify(d,null,2):p||"";try{await navigator.clipboard.writeText(S),v(!0),O.success("已复制到剪贴板"),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>v(!1),2e3)}catch{O.error("复制失败")}},[d,p]),V=u.useCallback(()=>{if(l(null),h(null),n==="form"&&s?.inputSchema){N.reset(k);try{i(JSON.stringify(k,null,2))}catch{i(`{
|
|
74
|
-
|
|
75
|
-
}`)}}else i(`{
|
|
76
|
-
|
|
77
|
-
}`),s?.inputSchema?N.reset(k):N.reset({})},[n,s?.inputSchema,k,N]),H=u.useMemo(()=>{const S=b=>({string:"bg-blue-100 text-blue-800",number:"bg-green-100 text-green-800",integer:"bg-green-100 text-green-800",boolean:"bg-purple-100 text-purple-800",array:"bg-orange-100 text-orange-800",object:"bg-gray-100 text-gray-800"})[b]||"bg-gray-100 text-gray-800";return(b,C)=>{switch(C.type){case"string":return C.enum?e.jsx(Ae,{name:b,control:N.control,render:({field:f})=>e.jsxs(Re,{value:f.value,onValueChange:f.onChange,children:[e.jsx(X,{children:e.jsx(be,{children:e.jsx(Te,{placeholder:`选择${b}`})})}),e.jsx(we,{children:C.enum.map(j=>e.jsx(ae,{value:j,children:j},j))})]})}):e.jsx(Ae,{name:b,control:N.control,render:({field:f})=>e.jsx(X,{children:e.jsx(se,{...f,placeholder:`输入${b}`,type:C.format==="password"?"password":"text"})})});case"number":case"integer":return e.jsx(Ae,{name:b,control:N.control,render:({field:f})=>e.jsx(X,{children:e.jsx(se,{...f,type:"number",placeholder:`输入${b}`,step:C.type==="integer"?"1":"0.1",onChange:j=>{const w=j.target.value;f.onChange(w===""?"":Number(w))}})})});case"boolean":return e.jsx(Ae,{name:b,control:N.control,render:({field:f})=>e.jsxs(Re,{value:f.value?.toString(),onValueChange:j=>f.onChange(j==="true"),children:[e.jsx(X,{children:e.jsx(be,{children:e.jsx(Te,{placeholder:`选择${b}`})})}),e.jsxs(we,{children:[e.jsx(ae,{value:"true",children:"true"}),e.jsx(ae,{value:"false",children:"false"})]})]})});case"array":return e.jsx(Wi,{name:b,schema:C,form:N,renderFormField:H});case"object":return e.jsx(_i,{name:b,schema:C,form:N,renderFormField:H,getTypeBadge:S});default:return e.jsx(Ae,{name:b,control:N.control,render:({field:f})=>e.jsx(X,{children:e.jsx(se,{...f,placeholder:`输入${b}`})})})}}},[N]),te=u.useCallback(S=>{try{return JSON.stringify(S,null,2)}catch{return String(S)}},[]),le=u.useCallback(()=>typeof window>"u"||/Mac|iPhone|iPad|iPod/.test(navigator.platform)?"⌘+Enter":"Ctrl+Enter",[]),ue=u.useCallback(async S=>{if((/Mac|iPhone|iPad|iPod/.test(navigator.platform)?S.metaKey&&S.key==="Enter":S.ctrlKey&&S.key==="Enter")&&r&&!m){if(S.preventDefault(),!(!s?.inputSchema?.properties||Object.keys(s.inputSchema.properties).length===0)&&n==="json"&&!I(o)){O.error("输入参数不是有效的JSON格式");return}await M()}},[r,m,n,o,I,M,s?.inputSchema?.properties]);return u.useEffect(()=>{if(r)return window.addEventListener("keydown",ue),()=>{window.removeEventListener("keydown",ue)}},[r,ue]),e.jsx(me,{open:r,onOpenChange:E,children:e.jsx(pa,{children:e.jsxs(oe,{className:"max-w-4xl max-h-[90vh] flex flex-col",children:[e.jsx(ie,{children:e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"工具调试"]})}),s&&e.jsxs("div",{className:"flex flex-col gap-4 h-[80vh]",children:[e.jsxs(Le,{children:[e.jsx(qe,{className:"pb-0",children:e.jsxs(Ue,{className:"text-base flex items-center gap-2",children:[e.jsx(de,{variant:"secondary",children:s.serverName}),s.toolName]})}),e.jsx(_n,{children:s.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.description})})]}),e.jsxs("div",{className:"flex-1 flex min-h-0 w-full overflow-hidden",children:[e.jsxs("div",{className:"w-1/2 flex flex-col gap-2 flex-shrink-0 overflow-hidden pr-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between h-[40px]",children:[e.jsx("h3",{className:"text-sm font-medium",children:"输入参数"}),s?.inputSchema?.properties&&Object.keys(s.inputSchema.properties).length>0&&e.jsx(We,{value:n,onValueChange:S=>P(S),children:e.jsxs(Qe,{className:"grid w-full grid-cols-2",children:[e.jsx(ge,{value:"form",className:"text-xs",children:"表单模式"}),e.jsx(ge,{value:"json",className:"text-xs",children:"高级模式"})]})})]}),e.jsx("div",{className:"flex-1 min-h-0",children:s?.inputSchema?.properties&&Object.keys(s.inputSchema.properties).length>0?e.jsxs(We,{value:n,onValueChange:S=>P(S),className:"h-full flex flex-col",children:[e.jsx(ve,{value:"form",className:"flex-1 data-[state=active]:flex data-[state=active]:flex-col mt-0",children:e.jsx(Gi,{tool:s,form:N,renderFormField:H})}),e.jsx(ve,{value:"json",className:"flex-1 data-[state=active]:flex data-[state=active]:flex-col mt-0",children:e.jsxs("div",{className:"flex-1 flex flex-col",children:[e.jsx(Ze,{value:o,onChange:S=>i(S.target.value),placeholder:"请输入JSON格式的参数...",className:"flex-1 font-mono text-sm resize-none min-h-[200px]",disabled:m}),!I(o)&&o.trim()!==`{
|
|
78
|
-
|
|
79
|
-
}`&&e.jsxs(_e,{className:"mt-2",children:[e.jsx(Ka,{className:"h-4 w-4"}),e.jsx(Be,{children:"JSON格式错误,请检查输入"})]})]})})]}):e.jsx(Bi,{})})]}),e.jsxs("div",{className:"w-1/2 flex flex-col gap-2 flex-shrink-0 overflow-hidden pl-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between h-[40px]",children:[e.jsx("h3",{className:"text-sm font-medium",children:"调用结果"}),(d||p)&&e.jsx(A,{variant:"outline",size:"sm",onClick:L,className:"gap-0",children:x?e.jsxs(e.Fragment,{children:[e.jsx(mt,{className:"h-4 w-4 mr-1"}),"已复制"]}):e.jsxs(e.Fragment,{children:[e.jsx(ut,{className:"h-4 w-4 mr-1"}),"复制结果"]})})]}),e.jsx("div",{className:"flex-1 min-h-0",children:m?e.jsx("div",{className:"h-full flex items-center justify-center border rounded-md",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Se,{className:"h-8 w-8 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"正在调用工具..."})]})}):p?e.jsx("div",{className:"h-full",children:e.jsx(_e,{variant:"destructive",className:"h-full",children:e.jsx(Be,{className:"font-mono text-sm whitespace-pre-wrap break-words",children:p})})}):d?e.jsx(Ne,{className:"h-full border rounded-md",children:e.jsx("pre",{className:"p-3 text-sm font-mono whitespace-pre-wrap break-words min-w-0",children:te(d)})}):e.jsx("div",{className:"h-full flex items-center justify-center border rounded-md",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ms,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"等待调用工具..."})]})})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsxs(A,{variant:"outline",onClick:V,disabled:m,children:[e.jsx(Za,{className:"h-4 w-4"}),"清空"]}),e.jsx(A,{onClick:M,disabled:m||!(!s?.inputSchema?.properties||Object.keys(s.inputSchema.properties).length===0)&&n==="json"&&!I(o),children:m?e.jsxs(e.Fragment,{children:[e.jsx(Se,{className:"h-4 w-4 mr-2 animate-spin"}),"调用中..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qa,{className:"h-4 w-4"}),!s?.inputSchema?.properties||Object.keys(s.inputSchema.properties).length===0?"直接调用":"调用工具"," (",le(),")"]})})]})]})]})})})}const xa=u.forwardRef(({className:r,...t},s)=>e.jsx(Mn,{className:R("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",r),...t,ref:s,children:e.jsx(eo,{className:R("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));xa.displayName=Mn.displayName;function Ji(r){const[t,s]=u.useState(""),n=Array.isArray(r)?r:[],a=u.useMemo(()=>{if(!t.trim())return n;const i=t.toLowerCase();return n.filter(d=>(d?.serverName?.toLowerCase()||"").includes(i)||(d?.toolName?.toLowerCase()||"").includes(i)||(d?.description?.toLowerCase()||"").includes(i))},[n,t]),o=u.useCallback(()=>{s("")},[]);return{searchValue:t,setSearchValue:s,filteredTools:a,clearSearch:o}}const Xi=["name","enabled","usageCount","lastUsedTime"];function Yi(){return ra({storageKey:"mcp-tool-sort-config",defaultConfig:{field:"name"},validFields:Xi,loggerName:"useToolSortPersistence"})}const Ki=[{value:"name",label:"按名称排序"},{value:"enabled",label:"按状态排序"},{value:"usageCount",label:"按使用次数排序"},{value:"lastUsedTime",label:"按最近使用排序"}];function Zi({value:r,onChange:t}){return e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Re,{value:r.field,onValueChange:s=>t({field:s}),children:[e.jsx(be,{id:"sort-field",className:"w-40",children:e.jsx(Te,{})}),e.jsx(we,{children:Ki.map(s=>e.jsx(ae,{value:s.value,children:s.label},s.value))})]})})}const Lt="未知服务",Qi="自定义服务";function ec(r){if(!r)return"-";try{const t=new Date(r),n=new Date().getTime()-t.getTime(),a=Math.floor(n/6e4);return a<1?"刚刚":a<60?`${a}分钟前`:a<1440?`${Math.floor(a/60)}小时前`:`${Math.floor(a/1440)}天前`}catch{return r}}function tc({initialStatus:r="all",className:t}){const{sortConfig:s,setSortConfig:n}=Yi(),[a,o]=u.useState([]),{searchValue:i,setSearchValue:d,filteredTools:l,clearSearch:m}=Ji(a),{currentPage:c,totalPages:p,paginatedTools:h,setPage:x,resetPage:v}=na(l,10),[g,$]=u.useState(!0),[k,N]=u.useState(null),[,y]=u.useState(!1),[P,E]=u.useState(null),[I,M]=u.useState({open:!1}),L=u.useCallback((f,j)=>{const{serviceName:w,toolName:T}=!f||!f.handler?{serviceName:Lt,toolName:f?.name||Lt}:f.handler.type==="mcp"?{serviceName:f.handler.config?.serviceName||Lt,toolName:f.handler.config?.toolName||f.name}:f.handler.type==="proxy"&&f.handler.platform==="coze"?{serviceName:"customMCP",toolName:f.name}:{serviceName:Qi,toolName:f.name};return{name:f.name,serverName:w,toolName:T,description:f.description||"",enabled:j,usageCount:f.usageCount||0,lastUsedTime:f.lastUsedTime||"",inputSchema:f.inputSchema}},[]),V=u.useCallback(async()=>{const j=(await U.getToolsList(r,s)).map(w=>L(w,w.enabled??!1));o(j)},[r,s,L]),H=u.useCallback(async()=>{$(!0),N(null);try{await V()}catch(f){console.error("获取工具列表失败:",f),N(f instanceof Error?f.message:"获取工具列表失败"),O.error("获取工具列表失败")}finally{$(!1)}},[V]),te=u.useCallback(async()=>{try{await V()}catch(f){console.error("刷新工具列表失败:",f),O.error("刷新工具列表失败")}},[V]),le=u.useCallback(async()=>{y(!0);try{await H(),O.success("刷新成功")}catch{O.error("刷新失败")}finally{y(!1)}},[H]),ue=u.useCallback(async(f,j)=>{try{const w=a.find(T=>T.name===f);if(!w){O.error("找不到对应的工具信息");return}if(w.serverName==="customMCP"){if(j){E(f);return}await U.addCustomTool({workflow_id:"",workflow_name:f,description:w.description||"",icon_url:"",app_id:""},f,w.description||""),O.success(`添加工具 ${f} 成功`)}else{const T=j?"disable":"enable";await U.manageMCPTool({action:T,serverName:w.serverName,toolName:w.toolName,description:w.description}),O.success(`${j?"禁用":"启用"}工具 ${f} 成功`)}await te()}catch(w){console.error("切换工具状态失败:",w),O.error(w instanceof Error?w.message:"切换工具状态失败")}},[a,te]),S=u.useCallback(async()=>{if(P)try{await U.removeCustomTool(P),O.success(`删除工具 ${P} 成功`),await te()}catch(f){console.error("删除 Coze 工具失败:",f),O.error(f instanceof Error?f.message:"删除 Coze 工具失败")}finally{E(null)}},[P,te]),b=u.useCallback(()=>{E(null)},[]),C=u.useCallback(f=>{M({open:!0,tool:{name:f.name,serverName:f.serverName,toolName:f.toolName,description:f.description,inputSchema:f.inputSchema}})},[]);return u.useEffect(()=>{H()},[H]),u.useEffect(()=>{v()},[i,v]),e.jsxs("div",{className:R("flex flex-col gap-4",t),children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(Zi,{value:s,onChange:n}),e.jsx(ua,{value:i,onChange:d,placeholder:"搜索服务名、工具名..."})]}),i&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:["找到 ",l.length," 个结果",l.length>0&&e.jsx("button",{type:"button",onClick:m,className:"ml-2 text-primary hover:underline",children:"清除搜索"})]}),e.jsx("div",{className:"rounded-md border",children:g?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Se,{className:"h-8 w-8 animate-spin text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"加载工具列表中..."})]})}):k?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[e.jsx("div",{className:"text-red-500 text-sm",children:k}),e.jsx(A,{variant:"outline",size:"sm",onClick:le,children:"重试"})]}):l.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[e.jsx(Pn,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:i?"没有找到匹配的工具":r==="enabled"?"没有已启用的工具":r==="disabled"?"没有已禁用的工具":"暂无可用工具"}),i&&e.jsx(A,{variant:"outline",size:"sm",onClick:m,children:"清除搜索"})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Nt,{size:"compact",children:[e.jsx(yt,{children:e.jsxs($e,{children:[e.jsx(B,{children:"服务名"}),e.jsx(B,{children:"工具名"}),e.jsx(B,{children:"描述"}),e.jsx(B,{children:"使用次数"}),e.jsx(B,{children:"最近使用"}),e.jsx(B,{children:"状态"}),e.jsx(B,{children:"操作"})]})}),e.jsx(Ct,{children:h.map(f=>e.jsxs($e,{children:[e.jsx(G,{children:e.jsx(de,{variant:"secondary",className:"rounded-md",children:f.serverName})}),e.jsx(G,{className:"font-medium",children:f.toolName}),e.jsx(G,{className:"text-muted-foreground max-w-[300px]",children:e.jsx(zi,{text:f.description,maxLength:100,textSize:"text-xs",storageKey:`mcp-tool-desc-${f.name}`})}),e.jsx(G,{className:"text-right",children:f.usageCount}),e.jsx(G,{className:"text-right text-muted-foreground",children:ec(f.lastUsedTime)}),e.jsx(G,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx(xa,{checked:f.enabled,onCheckedChange:j=>ue(f.name,!j)})})}),e.jsx(G,{children:e.jsx("div",{className:"flex items-center justify-end gap-2",children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 hover:cursor-pointer hover:text-primary transition-all duration-100",onClick:()=>C(f),title:"调试工具",children:[e.jsx(An,{size:14}),e.jsx("span",{children:"调试"})]})})})]},f.name))})]}),e.jsx(la,{currentPage:c,totalPages:p,setPage:x})]})}),e.jsx(Us,{open:P!==null,onOpenChange:f=>!f&&E(null),children:e.jsxs(pt,{children:[e.jsxs(xt,{children:[e.jsx(vt,{children:"确认移除 Coze 工作流工具"}),e.jsxs(jt,{children:['移除后需要通过【工作流集成】重新添加并配置入参,确定要移除工具 "',P,'" 吗?']})]}),e.jsxs(gt,{children:[e.jsx(bt,{onClick:b,children:"取消"}),e.jsx(St,{onClick:S,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"确认移除"})]})]})}),e.jsx(Hi,{open:I.open,onOpenChange:f=>M(j=>({...j,open:f})),tool:I.tool||null})]})}const sc=({size:r=24,color:t="currentColor",...s})=>e.jsx("svg",{width:r,height:r,viewBox:"0 0 1024 1024",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...s,children:e.jsx("path",{d:"M980.79827 694.105946c-21.144216-122.796973-109.844757-203.250162-109.844757-203.250162 12.647784-111.477622-33.792-131.26573-33.792-131.26573C827.392 14.668108 530.985514 20.67373 524.730811 20.839784 518.476108 20.67373 222.01427 14.668108 212.300108 359.590054c0 0-46.467459 19.788108-33.819676 131.26573 0 0-88.700541 80.453189-109.817081 203.250162 0 0-11.291676 207.484541 101.403676 25.40627 0 0 25.350919 69.161514 71.790703 131.26573 0 0-83.082378 28.256865-75.997405 101.625081 0 0-2.87827 81.836973 177.401081 76.218811 0 0 126.699243-9.852541 164.753297-63.515676l16.605405 0 0.276757 0 16.633081 0c38.026378 53.635459 164.725622 63.515676 164.725622 63.515676 180.224 5.618162 177.401081-76.218811 177.401081-76.218811 7.029622-73.368216-75.997405-101.625081-75.997405-101.625081 46.439784-62.104216 71.790703-131.26573 71.790703-131.26573C992.034595 901.590486 980.79827 694.105946 980.79827 694.105946z"})}),rc=({size:r=24,color:t="currentColor",...s})=>e.jsx("svg",{width:r,height:r,viewBox:"0 0 1024 1024",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...s,children:e.jsx("path",{d:"M0 524.992q0 166.016 95.488 298.496t247.488 185.504q6.016 0.992 10.016 0.992t6.496-1.504 4-3.008 2.016-4.992 0.512-4.992v-100.512q-36.992 4-66.016-0.512t-45.504-14.016-28.992-23.488-16.992-25.504-8.992-24-5.504-14.496q-8.992-15.008-27.008-27.488t-27.008-20-2.016-14.496q50.016-26.016 112.992 66.016 34.016 51.008 119.008 30.016 10.016-40.992 40-70.016Q293.984 736 237.984 670.976t-56-158.016q0-87.008 55.008-151.008-22.016-64.992 6.016-136.992 28.992-2.016 64.992 11.488t50.496 23.008 25.504 17.504q56.992-16 128.512-16t129.504 16q12.992-8.992 28.992-19.008t48.992-21.504 60.992-9.504q27.008 71.008 7.008 135.008 56 64 56 151.008 0 92.992-56.992 158.496t-172 85.504q43.008 43.008 43.008 104v128.992q0 0.992 0.992 3.008 0 6.016 0.512 8.992t4.512 6.016 12 3.008q152.992-52 250.496-185.504t97.504-300.512q0-104-40.512-199.008t-108.992-163.488-163.488-108.992T512.032 12.96 313.024 53.472 149.536 162.464t-108.992 163.488-40.512 199.008z","p-id":"4674"})});function ga(){const[r,t]=u.useState({status:"idle",logs:[]});u.useEffect(()=>{const l=z.subscribe("data:npmInstallStarted",h=>{console.log("[useNPMInstall] 安装开始:",h),t({status:"installing",version:h.version,installId:h.installId,logs:[]})}),m=z.subscribe("data:npmInstallLog",h=>{console.log("[useNPMInstall] 收到日志:",h),t(x=>x.installId===h.installId?{...x,logs:[...x.logs,{type:h.type,message:h.message,timestamp:h.timestamp}]}:x)}),c=z.subscribe("data:npmInstallCompleted",h=>{console.log("[useNPMInstall] 安装完成:",h),t(x=>x.installId===h.installId?{...x,status:"completed",duration:h.duration}:x)}),p=z.subscribe("data:npmInstallFailed",h=>{console.log("[useNPMInstall] 安装失败:",h),t(x=>x.installId===h.installId?{...x,status:"failed",error:h.error,duration:h.duration}:x)});return()=>{l(),m(),c(),p()}},[]);const s=u.useCallback(async l=>{try{console.log("[useNPMInstall] 开始安装版本:",l);const c=await(await fetch("/api/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:l})})).json();if(!c.success)throw new Error(c.error?.message||"安装请求失败");return console.log("[useNPMInstall] 安装请求已接受:",c),c}catch(m){throw console.error("[useNPMInstall] 安装请求失败:",m),t(c=>({...c,status:"failed",error:m instanceof Error?m.message:"未知错误"})),m}},[]),n=u.useCallback(()=>{console.log("[useNPMInstall] 清除安装状态"),t({status:"idle",logs:[]})},[]),a=u.useCallback(()=>{switch(r.status){case"installing":return`正在安装 xiaozhi-client@${r.version}...`;case"completed":return"安装完成!";case"failed":return`安装失败: ${r.error}`;default:return""}},[r]),o=u.useCallback(()=>{switch(r.status){case"installing":return"text-blue-600";case"completed":return"text-green-600";case"failed":return"text-red-600";default:return"text-gray-600"}},[r]),i=u.useCallback(()=>r.status==="installing",[r.status]),d=u.useCallback(()=>r.status!=="installing",[r.status]);return{installStatus:r,startInstall:s,clearStatus:n,getStatusText:a,getStatusColor:o,isInstalling:i,canCloseDialog:d}}var ct={exports:{}},At,hr;function Tt(){if(hr)return At;hr=1;const r="2.0.0",t=256,s=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,a=t-6;return At={MAX_LENGTH:t,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:a,MAX_SAFE_INTEGER:s,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},At}var Mt,pr;function kt(){if(pr)return Mt;pr=1;var r={};return Mt=typeof process=="object"&&r&&r.NODE_DEBUG&&/\bsemver\b/i.test(r.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{},Mt}var xr;function et(){return xr||(xr=1,(function(r,t){const{MAX_SAFE_COMPONENT_LENGTH:s,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=Tt(),o=kt();t=r.exports={};const i=t.re=[],d=t.safeRe=[],l=t.src=[],m=t.safeSrc=[],c=t.t={};let p=0;const h="[a-zA-Z0-9-]",x=[["\\s",1],["\\d",a],[h,n]],v=$=>{for(const[k,N]of x)$=$.split(`${k}*`).join(`${k}{0,${N}}`).split(`${k}+`).join(`${k}{1,${N}}`);return $},g=($,k,N)=>{const y=v(k),P=p++;o($,P,k),c[$]=P,l[P]=k,m[P]=y,i[P]=new RegExp(k,N?"g":void 0),d[P]=new RegExp(y,N?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),g("MAINVERSION",`(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${l[c.NONNUMERICIDENTIFIER]}|${l[c.NUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${l[c.NONNUMERICIDENTIFIER]}|${l[c.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASE",`(?:-(${l[c.PRERELEASEIDENTIFIER]}(?:\\.${l[c.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${l[c.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[c.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${h}+`),g("BUILD",`(?:\\+(${l[c.BUILDIDENTIFIER]}(?:\\.${l[c.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${l[c.MAINVERSION]}${l[c.PRERELEASE]}?${l[c.BUILD]}?`),g("FULL",`^${l[c.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${l[c.MAINVERSIONLOOSE]}${l[c.PRERELEASELOOSE]}?${l[c.BUILD]}?`),g("LOOSE",`^${l[c.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${l[c.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${l[c.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:${l[c.PRERELEASE]})?${l[c.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:${l[c.PRERELEASELOOSE]})?${l[c.BUILD]}?)?)?`),g("XRANGE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${s}})(?:\\.(\\d{1,${s}}))?(?:\\.(\\d{1,${s}}))?`),g("COERCE",`${l[c.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",l[c.COERCEPLAIN]+`(?:${l[c.PRERELEASE]})?(?:${l[c.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",l[c.COERCE],!0),g("COERCERTLFULL",l[c.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${l[c.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",g("TILDE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${l[c.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",g("CARET",`^${l[c.LONECARET]}${l[c.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${l[c.LONECARET]}${l[c.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${l[c.GTLT]}\\s*(${l[c.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]}|${l[c.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${l[c.XRANGEPLAIN]})\\s+-\\s+(${l[c.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${l[c.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[c.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(ct,ct.exports)),ct.exports}var Dt,gr;function Ys(){if(gr)return Dt;gr=1;const r=Object.freeze({loose:!0}),t=Object.freeze({});return Dt=n=>n?typeof n!="object"?r:n:t,Dt}var qt,vr;function va(){if(vr)return qt;vr=1;const r=/^[0-9]+$/,t=(n,a)=>{if(typeof n=="number"&&typeof a=="number")return n===a?0:n<a?-1:1;const o=r.test(n),i=r.test(a);return o&&i&&(n=+n,a=+a),n===a?0:o&&!i?-1:i&&!o?1:n<a?-1:1};return qt={compareIdentifiers:t,rcompareIdentifiers:(n,a)=>t(a,n)},qt}var Ut,jr;function K(){if(jr)return Ut;jr=1;const r=kt(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:s}=Tt(),{safeRe:n,t:a}=et(),o=Ys(),{compareIdentifiers:i}=va();class d{constructor(m,c){if(c=o(c),m instanceof d){if(m.loose===!!c.loose&&m.includePrerelease===!!c.includePrerelease)return m;m=m.version}else if(typeof m!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof m}".`);if(m.length>t)throw new TypeError(`version is longer than ${t} characters`);r("SemVer",m,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;const p=m.trim().match(c.loose?n[a.LOOSE]:n[a.FULL]);if(!p)throw new TypeError(`Invalid Version: ${m}`);if(this.raw=m,this.major=+p[1],this.minor=+p[2],this.patch=+p[3],this.major>s||this.major<0)throw new TypeError("Invalid major version");if(this.minor>s||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>s||this.patch<0)throw new TypeError("Invalid patch version");p[4]?this.prerelease=p[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const x=+h;if(x>=0&&x<s)return x}return h}):this.prerelease=[],this.build=p[5]?p[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(m){if(r("SemVer.compare",this.version,this.options,m),!(m instanceof d)){if(typeof m=="string"&&m===this.version)return 0;m=new d(m,this.options)}return m.version===this.version?0:this.compareMain(m)||this.comparePre(m)}compareMain(m){return m instanceof d||(m=new d(m,this.options)),this.major<m.major?-1:this.major>m.major?1:this.minor<m.minor?-1:this.minor>m.minor?1:this.patch<m.patch?-1:this.patch>m.patch?1:0}comparePre(m){if(m instanceof d||(m=new d(m,this.options)),this.prerelease.length&&!m.prerelease.length)return-1;if(!this.prerelease.length&&m.prerelease.length)return 1;if(!this.prerelease.length&&!m.prerelease.length)return 0;let c=0;do{const p=this.prerelease[c],h=m.prerelease[c];if(r("prerelease compare",c,p,h),p===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(p===void 0)return-1;if(p===h)continue;return i(p,h)}while(++c)}compareBuild(m){m instanceof d||(m=new d(m,this.options));let c=0;do{const p=this.build[c],h=m.build[c];if(r("build compare",c,p,h),p===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(p===void 0)return-1;if(p===h)continue;return i(p,h)}while(++c)}inc(m,c,p){if(m.startsWith("pre")){if(!c&&p===!1)throw new Error("invalid increment argument: identifier is empty");if(c){const h=`-${c}`.match(this.options.loose?n[a.PRERELEASELOOSE]:n[a.PRERELEASE]);if(!h||h[1]!==c)throw new Error(`invalid identifier: ${c}`)}}switch(m){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",c,p);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",c,p);break;case"prepatch":this.prerelease.length=0,this.inc("patch",c,p),this.inc("pre",c,p);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",c,p),this.inc("pre",c,p);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const h=Number(p)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let x=this.prerelease.length;for(;--x>=0;)typeof this.prerelease[x]=="number"&&(this.prerelease[x]++,x=-2);if(x===-1){if(c===this.prerelease.join(".")&&p===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(c){let x=[c,h];p===!1&&(x=[c]),i(this.prerelease[0],c)===0?isNaN(this.prerelease[1])&&(this.prerelease=x):this.prerelease=x}break}default:throw new Error(`invalid increment argument: ${m}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Ut=d,Ut}var zt,Sr;function Fe(){if(Sr)return zt;Sr=1;const r=K();return zt=(s,n,a=!1)=>{if(s instanceof r)return s;try{return new r(s,n)}catch(o){if(!a)return null;throw o}},zt}var Ft,br;function nc(){if(br)return Ft;br=1;const r=Fe();return Ft=(s,n)=>{const a=r(s,n);return a?a.version:null},Ft}var Vt,wr;function ac(){if(wr)return Vt;wr=1;const r=Fe();return Vt=(s,n)=>{const a=r(s.trim().replace(/^[=v]+/,""),n);return a?a.version:null},Vt}var Wt,Nr;function oc(){if(Nr)return Wt;Nr=1;const r=K();return Wt=(s,n,a,o,i)=>{typeof a=="string"&&(i=o,o=a,a=void 0);try{return new r(s instanceof r?s.version:s,a).inc(n,o,i).version}catch{return null}},Wt}var _t,yr;function ic(){if(yr)return _t;yr=1;const r=Fe();return _t=(s,n)=>{const a=r(s,null,!0),o=r(n,null,!0),i=a.compare(o);if(i===0)return null;const d=i>0,l=d?a:o,m=d?o:a,c=!!l.prerelease.length;if(!!m.prerelease.length&&!c){if(!m.patch&&!m.minor)return"major";if(m.compareMain(l)===0)return m.minor&&!m.patch?"minor":"patch"}const h=c?"pre":"";return a.major!==o.major?h+"major":a.minor!==o.minor?h+"minor":a.patch!==o.patch?h+"patch":"prerelease"},_t}var Bt,Cr;function cc(){if(Cr)return Bt;Cr=1;const r=K();return Bt=(s,n)=>new r(s,n).major,Bt}var Gt,Er;function lc(){if(Er)return Gt;Er=1;const r=K();return Gt=(s,n)=>new r(s,n).minor,Gt}var Ht,Rr;function uc(){if(Rr)return Ht;Rr=1;const r=K();return Ht=(s,n)=>new r(s,n).patch,Ht}var Jt,Tr;function dc(){if(Tr)return Jt;Tr=1;const r=Fe();return Jt=(s,n)=>{const a=r(s,n);return a&&a.prerelease.length?a.prerelease:null},Jt}var Xt,kr;function fe(){if(kr)return Xt;kr=1;const r=K();return Xt=(s,n,a)=>new r(s,a).compare(new r(n,a)),Xt}var Yt,Ir;function mc(){if(Ir)return Yt;Ir=1;const r=fe();return Yt=(s,n,a)=>r(n,s,a),Yt}var Kt,$r;function fc(){if($r)return Kt;$r=1;const r=fe();return Kt=(s,n)=>r(s,n,!0),Kt}var Zt,Pr;function Ks(){if(Pr)return Zt;Pr=1;const r=K();return Zt=(s,n,a)=>{const o=new r(s,a),i=new r(n,a);return o.compare(i)||o.compareBuild(i)},Zt}var Qt,Or;function hc(){if(Or)return Qt;Or=1;const r=Ks();return Qt=(s,n)=>s.sort((a,o)=>r(a,o,n)),Qt}var es,Lr;function pc(){if(Lr)return es;Lr=1;const r=Ks();return es=(s,n)=>s.sort((a,o)=>r(o,a,n)),es}var ts,Ar;function It(){if(Ar)return ts;Ar=1;const r=fe();return ts=(s,n,a)=>r(s,n,a)>0,ts}var ss,Mr;function Zs(){if(Mr)return ss;Mr=1;const r=fe();return ss=(s,n,a)=>r(s,n,a)<0,ss}var rs,Dr;function ja(){if(Dr)return rs;Dr=1;const r=fe();return rs=(s,n,a)=>r(s,n,a)===0,rs}var ns,qr;function Sa(){if(qr)return ns;qr=1;const r=fe();return ns=(s,n,a)=>r(s,n,a)!==0,ns}var as,Ur;function Qs(){if(Ur)return as;Ur=1;const r=fe();return as=(s,n,a)=>r(s,n,a)>=0,as}var os,zr;function er(){if(zr)return os;zr=1;const r=fe();return os=(s,n,a)=>r(s,n,a)<=0,os}var is,Fr;function ba(){if(Fr)return is;Fr=1;const r=ja(),t=Sa(),s=It(),n=Qs(),a=Zs(),o=er();return is=(d,l,m,c)=>{switch(l){case"===":return typeof d=="object"&&(d=d.version),typeof m=="object"&&(m=m.version),d===m;case"!==":return typeof d=="object"&&(d=d.version),typeof m=="object"&&(m=m.version),d!==m;case"":case"=":case"==":return r(d,m,c);case"!=":return t(d,m,c);case">":return s(d,m,c);case">=":return n(d,m,c);case"<":return a(d,m,c);case"<=":return o(d,m,c);default:throw new TypeError(`Invalid operator: ${l}`)}},is}var cs,Vr;function xc(){if(Vr)return cs;Vr=1;const r=K(),t=Fe(),{safeRe:s,t:n}=et();return cs=(o,i)=>{if(o instanceof r)return o;if(typeof o=="number"&&(o=String(o)),typeof o!="string")return null;i=i||{};let d=null;if(!i.rtl)d=o.match(i.includePrerelease?s[n.COERCEFULL]:s[n.COERCE]);else{const x=i.includePrerelease?s[n.COERCERTLFULL]:s[n.COERCERTL];let v;for(;(v=x.exec(o))&&(!d||d.index+d[0].length!==o.length);)(!d||v.index+v[0].length!==d.index+d[0].length)&&(d=v),x.lastIndex=v.index+v[1].length+v[2].length;x.lastIndex=-1}if(d===null)return null;const l=d[2],m=d[3]||"0",c=d[4]||"0",p=i.includePrerelease&&d[5]?`-${d[5]}`:"",h=i.includePrerelease&&d[6]?`+${d[6]}`:"";return t(`${l}.${m}.${c}${p}${h}`,i)},cs}var ls,Wr;function gc(){if(Wr)return ls;Wr=1;class r{constructor(){this.max=1e3,this.map=new Map}get(s){const n=this.map.get(s);if(n!==void 0)return this.map.delete(s),this.map.set(s,n),n}delete(s){return this.map.delete(s)}set(s,n){if(!this.delete(s)&&n!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(s,n)}return this}}return ls=r,ls}var us,_r;function he(){if(_r)return us;_r=1;const r=/\s+/g;class t{constructor(b,C){if(C=a(C),b instanceof t)return b.loose===!!C.loose&&b.includePrerelease===!!C.includePrerelease?b:new t(b.raw,C);if(b instanceof o)return this.raw=b.value,this.set=[[b]],this.formatted=void 0,this;if(this.options=C,this.loose=!!C.loose,this.includePrerelease=!!C.includePrerelease,this.raw=b.trim().replace(r," "),this.set=this.raw.split("||").map(f=>this.parseRange(f.trim())).filter(f=>f.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const f=this.set[0];if(this.set=this.set.filter(j=>!g(j[0])),this.set.length===0)this.set=[f];else if(this.set.length>1){for(const j of this.set)if(j.length===1&&$(j[0])){this.set=[j];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let b=0;b<this.set.length;b++){b>0&&(this.formatted+="||");const C=this.set[b];for(let f=0;f<C.length;f++)f>0&&(this.formatted+=" "),this.formatted+=C[f].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(b){const f=((this.options.includePrerelease&&x)|(this.options.loose&&v))+":"+b,j=n.get(f);if(j)return j;const w=this.options.loose,T=w?l[m.HYPHENRANGELOOSE]:l[m.HYPHENRANGE];b=b.replace(T,le(this.options.includePrerelease)),i("hyphen replace",b),b=b.replace(l[m.COMPARATORTRIM],c),i("comparator trim",b),b=b.replace(l[m.TILDETRIM],p),i("tilde trim",b),b=b.replace(l[m.CARETTRIM],h),i("caret trim",b);let q=b.split(" ").map(W=>N(W,this.options)).join(" ").split(/\s+/).map(W=>te(W,this.options));w&&(q=q.filter(W=>(i("loose invalid filter",W,this.options),!!W.match(l[m.COMPARATORLOOSE])))),i("range list",q);const D=new Map,F=q.map(W=>new o(W,this.options));for(const W of F){if(g(W))return[W];D.set(W.value,W)}D.size>1&&D.has("")&&D.delete("");const Y=[...D.values()];return n.set(f,Y),Y}intersects(b,C){if(!(b instanceof t))throw new TypeError("a Range is required");return this.set.some(f=>k(f,C)&&b.set.some(j=>k(j,C)&&f.every(w=>j.every(T=>w.intersects(T,C)))))}test(b){if(!b)return!1;if(typeof b=="string")try{b=new d(b,this.options)}catch{return!1}for(let C=0;C<this.set.length;C++)if(ue(this.set[C],b,this.options))return!0;return!1}}us=t;const s=gc(),n=new s,a=Ys(),o=$t(),i=kt(),d=K(),{safeRe:l,t:m,comparatorTrimReplace:c,tildeTrimReplace:p,caretTrimReplace:h}=et(),{FLAG_INCLUDE_PRERELEASE:x,FLAG_LOOSE:v}=Tt(),g=S=>S.value==="<0.0.0-0",$=S=>S.value==="",k=(S,b)=>{let C=!0;const f=S.slice();let j=f.pop();for(;C&&f.length;)C=f.every(w=>j.intersects(w,b)),j=f.pop();return C},N=(S,b)=>(S=S.replace(l[m.BUILD],""),i("comp",S,b),S=I(S,b),i("caret",S),S=P(S,b),i("tildes",S),S=L(S,b),i("xrange",S),S=H(S,b),i("stars",S),S),y=S=>!S||S.toLowerCase()==="x"||S==="*",P=(S,b)=>S.trim().split(/\s+/).map(C=>E(C,b)).join(" "),E=(S,b)=>{const C=b.loose?l[m.TILDELOOSE]:l[m.TILDE];return S.replace(C,(f,j,w,T,q)=>{i("tilde",S,f,j,w,T,q);let D;return y(j)?D="":y(w)?D=`>=${j}.0.0 <${+j+1}.0.0-0`:y(T)?D=`>=${j}.${w}.0 <${j}.${+w+1}.0-0`:q?(i("replaceTilde pr",q),D=`>=${j}.${w}.${T}-${q} <${j}.${+w+1}.0-0`):D=`>=${j}.${w}.${T} <${j}.${+w+1}.0-0`,i("tilde return",D),D})},I=(S,b)=>S.trim().split(/\s+/).map(C=>M(C,b)).join(" "),M=(S,b)=>{i("caret",S,b);const C=b.loose?l[m.CARETLOOSE]:l[m.CARET],f=b.includePrerelease?"-0":"";return S.replace(C,(j,w,T,q,D)=>{i("caret",S,j,w,T,q,D);let F;return y(w)?F="":y(T)?F=`>=${w}.0.0${f} <${+w+1}.0.0-0`:y(q)?w==="0"?F=`>=${w}.${T}.0${f} <${w}.${+T+1}.0-0`:F=`>=${w}.${T}.0${f} <${+w+1}.0.0-0`:D?(i("replaceCaret pr",D),w==="0"?T==="0"?F=`>=${w}.${T}.${q}-${D} <${w}.${T}.${+q+1}-0`:F=`>=${w}.${T}.${q}-${D} <${w}.${+T+1}.0-0`:F=`>=${w}.${T}.${q}-${D} <${+w+1}.0.0-0`):(i("no pr"),w==="0"?T==="0"?F=`>=${w}.${T}.${q}${f} <${w}.${T}.${+q+1}-0`:F=`>=${w}.${T}.${q}${f} <${w}.${+T+1}.0-0`:F=`>=${w}.${T}.${q} <${+w+1}.0.0-0`),i("caret return",F),F})},L=(S,b)=>(i("replaceXRanges",S,b),S.split(/\s+/).map(C=>V(C,b)).join(" ")),V=(S,b)=>{S=S.trim();const C=b.loose?l[m.XRANGELOOSE]:l[m.XRANGE];return S.replace(C,(f,j,w,T,q,D)=>{i("xRange",S,f,j,w,T,q,D);const F=y(w),Y=F||y(T),W=Y||y(q),Ve=W;return j==="="&&Ve&&(j=""),D=b.includePrerelease?"-0":"",F?j===">"||j==="<"?f="<0.0.0-0":f="*":j&&Ve?(Y&&(T=0),q=0,j===">"?(j=">=",Y?(w=+w+1,T=0,q=0):(T=+T+1,q=0)):j==="<="&&(j="<",Y?w=+w+1:T=+T+1),j==="<"&&(D="-0"),f=`${j+w}.${T}.${q}${D}`):Y?f=`>=${w}.0.0${D} <${+w+1}.0.0-0`:W&&(f=`>=${w}.${T}.0${D} <${w}.${+T+1}.0-0`),i("xRange return",f),f})},H=(S,b)=>(i("replaceStars",S,b),S.trim().replace(l[m.STAR],"")),te=(S,b)=>(i("replaceGTE0",S,b),S.trim().replace(l[b.includePrerelease?m.GTE0PRE:m.GTE0],"")),le=S=>(b,C,f,j,w,T,q,D,F,Y,W,Ve)=>(y(f)?C="":y(j)?C=`>=${f}.0.0${S?"-0":""}`:y(w)?C=`>=${f}.${j}.0${S?"-0":""}`:T?C=`>=${C}`:C=`>=${C}${S?"-0":""}`,y(F)?D="":y(Y)?D=`<${+F+1}.0.0-0`:y(W)?D=`<${F}.${+Y+1}.0-0`:Ve?D=`<=${F}.${Y}.${W}-${Ve}`:S?D=`<${F}.${Y}.${+W+1}-0`:D=`<=${D}`,`${C} ${D}`.trim()),ue=(S,b,C)=>{for(let f=0;f<S.length;f++)if(!S[f].test(b))return!1;if(b.prerelease.length&&!C.includePrerelease){for(let f=0;f<S.length;f++)if(i(S[f].semver),S[f].semver!==o.ANY&&S[f].semver.prerelease.length>0){const j=S[f].semver;if(j.major===b.major&&j.minor===b.minor&&j.patch===b.patch)return!0}return!1}return!0};return us}var ds,Br;function $t(){if(Br)return ds;Br=1;const r=Symbol("SemVer ANY");class t{static get ANY(){return r}constructor(c,p){if(p=s(p),c instanceof t){if(c.loose===!!p.loose)return c;c=c.value}c=c.trim().split(/\s+/).join(" "),i("comparator",c,p),this.options=p,this.loose=!!p.loose,this.parse(c),this.semver===r?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(c){const p=this.options.loose?n[a.COMPARATORLOOSE]:n[a.COMPARATOR],h=c.match(p);if(!h)throw new TypeError(`Invalid comparator: ${c}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new d(h[2],this.options.loose):this.semver=r}toString(){return this.value}test(c){if(i("Comparator.test",c,this.options.loose),this.semver===r||c===r)return!0;if(typeof c=="string")try{c=new d(c,this.options)}catch{return!1}return o(c,this.operator,this.semver,this.options)}intersects(c,p){if(!(c instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new l(c.value,p).test(this.value):c.operator===""?c.value===""?!0:new l(this.value,p).test(c.semver):(p=s(p),p.includePrerelease&&(this.value==="<0.0.0-0"||c.value==="<0.0.0-0")||!p.includePrerelease&&(this.value.startsWith("<0.0.0")||c.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&c.operator.startsWith(">")||this.operator.startsWith("<")&&c.operator.startsWith("<")||this.semver.version===c.semver.version&&this.operator.includes("=")&&c.operator.includes("=")||o(this.semver,"<",c.semver,p)&&this.operator.startsWith(">")&&c.operator.startsWith("<")||o(this.semver,">",c.semver,p)&&this.operator.startsWith("<")&&c.operator.startsWith(">")))}}ds=t;const s=Ys(),{safeRe:n,t:a}=et(),o=ba(),i=kt(),d=K(),l=he();return ds}var ms,Gr;function Pt(){if(Gr)return ms;Gr=1;const r=he();return ms=(s,n,a)=>{try{n=new r(n,a)}catch{return!1}return n.test(s)},ms}var fs,Hr;function vc(){if(Hr)return fs;Hr=1;const r=he();return fs=(s,n)=>new r(s,n).set.map(a=>a.map(o=>o.value).join(" ").trim().split(" ")),fs}var hs,Jr;function jc(){if(Jr)return hs;Jr=1;const r=K(),t=he();return hs=(n,a,o)=>{let i=null,d=null,l=null;try{l=new t(a,o)}catch{return null}return n.forEach(m=>{l.test(m)&&(!i||d.compare(m)===-1)&&(i=m,d=new r(i,o))}),i},hs}var ps,Xr;function Sc(){if(Xr)return ps;Xr=1;const r=K(),t=he();return ps=(n,a,o)=>{let i=null,d=null,l=null;try{l=new t(a,o)}catch{return null}return n.forEach(m=>{l.test(m)&&(!i||d.compare(m)===1)&&(i=m,d=new r(i,o))}),i},ps}var xs,Yr;function bc(){if(Yr)return xs;Yr=1;const r=K(),t=he(),s=It();return xs=(a,o)=>{a=new t(a,o);let i=new r("0.0.0");if(a.test(i)||(i=new r("0.0.0-0"),a.test(i)))return i;i=null;for(let d=0;d<a.set.length;++d){const l=a.set[d];let m=null;l.forEach(c=>{const p=new r(c.semver.version);switch(c.operator){case">":p.prerelease.length===0?p.patch++:p.prerelease.push(0),p.raw=p.format();case"":case">=":(!m||s(p,m))&&(m=p);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${c.operator}`)}}),m&&(!i||s(i,m))&&(i=m)}return i&&a.test(i)?i:null},xs}var gs,Kr;function wc(){if(Kr)return gs;Kr=1;const r=he();return gs=(s,n)=>{try{return new r(s,n).range||"*"}catch{return null}},gs}var vs,Zr;function tr(){if(Zr)return vs;Zr=1;const r=K(),t=$t(),{ANY:s}=t,n=he(),a=Pt(),o=It(),i=Zs(),d=er(),l=Qs();return vs=(c,p,h,x)=>{c=new r(c,x),p=new n(p,x);let v,g,$,k,N;switch(h){case">":v=o,g=d,$=i,k=">",N=">=";break;case"<":v=i,g=l,$=o,k="<",N="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(c,p,x))return!1;for(let y=0;y<p.set.length;++y){const P=p.set[y];let E=null,I=null;if(P.forEach(M=>{M.semver===s&&(M=new t(">=0.0.0")),E=E||M,I=I||M,v(M.semver,E.semver,x)?E=M:$(M.semver,I.semver,x)&&(I=M)}),E.operator===k||E.operator===N||(!I.operator||I.operator===k)&&g(c,I.semver))return!1;if(I.operator===N&&$(c,I.semver))return!1}return!0},vs}var js,Qr;function Nc(){if(Qr)return js;Qr=1;const r=tr();return js=(s,n,a)=>r(s,n,">",a),js}var Ss,en;function yc(){if(en)return Ss;en=1;const r=tr();return Ss=(s,n,a)=>r(s,n,"<",a),Ss}var bs,tn;function Cc(){if(tn)return bs;tn=1;const r=he();return bs=(s,n,a)=>(s=new r(s,a),n=new r(n,a),s.intersects(n,a)),bs}var ws,sn;function Ec(){if(sn)return ws;sn=1;const r=Pt(),t=fe();return ws=(s,n,a)=>{const o=[];let i=null,d=null;const l=s.sort((h,x)=>t(h,x,a));for(const h of l)r(h,n,a)?(d=h,i||(i=h)):(d&&o.push([i,d]),d=null,i=null);i&&o.push([i,null]);const m=[];for(const[h,x]of o)h===x?m.push(h):!x&&h===l[0]?m.push("*"):x?h===l[0]?m.push(`<=${x}`):m.push(`${h} - ${x}`):m.push(`>=${h}`);const c=m.join(" || "),p=typeof n.raw=="string"?n.raw:String(n);return c.length<p.length?c:n},ws}var Ns,rn;function Rc(){if(rn)return Ns;rn=1;const r=he(),t=$t(),{ANY:s}=t,n=Pt(),a=fe(),o=(p,h,x={})=>{if(p===h)return!0;p=new r(p,x),h=new r(h,x);let v=!1;e:for(const g of p.set){for(const $ of h.set){const k=l(g,$,x);if(v=v||k!==null,k)continue e}if(v)return!1}return!0},i=[new t(">=0.0.0-0")],d=[new t(">=0.0.0")],l=(p,h,x)=>{if(p===h)return!0;if(p.length===1&&p[0].semver===s){if(h.length===1&&h[0].semver===s)return!0;x.includePrerelease?p=i:p=d}if(h.length===1&&h[0].semver===s){if(x.includePrerelease)return!0;h=d}const v=new Set;let g,$;for(const L of p)L.operator===">"||L.operator===">="?g=m(g,L,x):L.operator==="<"||L.operator==="<="?$=c($,L,x):v.add(L.semver);if(v.size>1)return null;let k;if(g&&$){if(k=a(g.semver,$.semver,x),k>0)return null;if(k===0&&(g.operator!==">="||$.operator!=="<="))return null}for(const L of v){if(g&&!n(L,String(g),x)||$&&!n(L,String($),x))return null;for(const V of h)if(!n(L,String(V),x))return!1;return!0}let N,y,P,E,I=$&&!x.includePrerelease&&$.semver.prerelease.length?$.semver:!1,M=g&&!x.includePrerelease&&g.semver.prerelease.length?g.semver:!1;I&&I.prerelease.length===1&&$.operator==="<"&&I.prerelease[0]===0&&(I=!1);for(const L of h){if(E=E||L.operator===">"||L.operator===">=",P=P||L.operator==="<"||L.operator==="<=",g){if(M&&L.semver.prerelease&&L.semver.prerelease.length&&L.semver.major===M.major&&L.semver.minor===M.minor&&L.semver.patch===M.patch&&(M=!1),L.operator===">"||L.operator===">="){if(N=m(g,L,x),N===L&&N!==g)return!1}else if(g.operator===">="&&!n(g.semver,String(L),x))return!1}if($){if(I&&L.semver.prerelease&&L.semver.prerelease.length&&L.semver.major===I.major&&L.semver.minor===I.minor&&L.semver.patch===I.patch&&(I=!1),L.operator==="<"||L.operator==="<="){if(y=c($,L,x),y===L&&y!==$)return!1}else if($.operator==="<="&&!n($.semver,String(L),x))return!1}if(!L.operator&&($||g)&&k!==0)return!1}return!(g&&P&&!$&&k!==0||$&&E&&!g&&k!==0||M||I)},m=(p,h,x)=>{if(!p)return h;const v=a(p.semver,h.semver,x);return v>0?p:v<0||h.operator===">"&&p.operator===">="?h:p},c=(p,h,x)=>{if(!p)return h;const v=a(p.semver,h.semver,x);return v<0?p:v>0||h.operator==="<"&&p.operator==="<="?h:p};return Ns=o,Ns}var ys,nn;function Tc(){if(nn)return ys;nn=1;const r=et(),t=Tt(),s=K(),n=va(),a=Fe(),o=nc(),i=ac(),d=oc(),l=ic(),m=cc(),c=lc(),p=uc(),h=dc(),x=fe(),v=mc(),g=fc(),$=Ks(),k=hc(),N=pc(),y=It(),P=Zs(),E=ja(),I=Sa(),M=Qs(),L=er(),V=ba(),H=xc(),te=$t(),le=he(),ue=Pt(),S=vc(),b=jc(),C=Sc(),f=bc(),j=wc(),w=tr(),T=Nc(),q=yc(),D=Cc(),F=Ec(),Y=Rc();return ys={parse:a,valid:o,clean:i,inc:d,diff:l,major:m,minor:c,patch:p,prerelease:h,compare:x,rcompare:v,compareLoose:g,compareBuild:$,sort:k,rsort:N,gt:y,lt:P,eq:E,neq:I,gte:M,lte:L,cmp:V,coerce:H,Comparator:te,Range:le,satisfies:ue,toComparators:S,maxSatisfying:b,minSatisfying:C,minVersion:f,validRange:j,outside:w,gtr:T,ltr:q,intersects:D,simplifyRange:F,subset:Y,SemVer:s,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers},ys}var kc=Tc();const Ic=to(kc),wa=u.forwardRef(({className:r,value:t,status:s="idle",...n},a)=>{const o=()=>{switch(s){case"installing":return"bg-blue-500";case"completed":return"bg-green-500";case"failed":return"bg-red-500";default:return"bg-gray-300"}};return e.jsx("div",{ref:a,className:R("relative h-4 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-gray-800",r),...n,children:e.jsx("div",{className:R("h-full transition-all duration-300 ease-in-out",o()),style:{width:`${t||0}%`}})})});wa.displayName="Progress";const $c=/\[(0|31|32|33|34|35|36|37|90|91|92|93|94|95|96|97)m/g;function Pc({isOpen:r,onClose:t,version:s}){const{installStatus:n,startInstall:a,clearStatus:o,isInstalling:i,canCloseDialog:d}=ga(),l=u.useRef(null),[m,c]=u.useState(!1);u.useEffect(()=>{r&&s&&(console.log("[InstallLogDialog] 对话框打开,开始安装版本:",s),o(),a(s).catch(y=>{console.error("[InstallLogDialog] 启动安装失败:",y)}))},[r,s,a,o]),u.useEffect(()=>{const y=setTimeout(()=>{l.current&&(l.current.scrollTop=l.current.scrollHeight)},100);return()=>clearTimeout(y)});const p=()=>{switch(n.status){case"idle":return 0;case"installing":return Math.min(90,n.logs.length*2);case"completed":return 100;case"failed":return 100;default:return 0}},h=()=>{switch(n.status){case"installing":return"正在安装...";case"completed":return"安装完成";case"failed":return"安装失败";default:return"准备安装"}},x=()=>{switch(n.status){case"installing":return e.jsx(or,{className:"h-4 w-4 animate-pulse"});case"completed":return e.jsx(Cs,{className:"h-4 w-4 text-green-600"});case"failed":return e.jsx(As,{className:"h-4 w-4 text-red-600"});default:return null}},v=()=>{switch(n.status){case"installing":return"default";case"completed":return"secondary";case"failed":return"destructive";default:return"outline"}},g=y=>y.replace($c,"").split(`
|
|
80
|
-
`).filter(E=>E.trim()).map((E,I)=>e.jsx("div",{className:"leading-relaxed",children:E},`${E.slice(0,20)}-${I}`)),$=()=>{d()?(o(),t()):O.error("安装过程中无法关闭对话框,请等待安装完成")},k=y=>{y.key==="Escape"&&d()&&$()},N=()=>{c(!m)};return e.jsx(me,{open:r,onOpenChange:$,children:e.jsxs(oe,{className:"max-w-2xl max-h-[80vh] flex flex-col",onKeyDown:k,children:[e.jsx(ie,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ce,{className:"text-lg font-semibold",children:"正在安装"}),n.status!=="idle"&&e.jsxs(de,{variant:v(),className:"flex items-center gap-1",children:[x(),h()]})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"安装进度"}),n.version&&e.jsxs(de,{variant:"outline",className:"text-xs",children:["v",n.version]})]}),e.jsx(wa,{value:p(),status:n.status,className:"w-full h-2"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:h()}),n.duration&&e.jsxs("span",{children:["耗时: ",(n.duration/1e3).toFixed(1),"s"]})]})]}),n.status==="failed"&&e.jsx(_e,{variant:"destructive",children:e.jsx(Be,{children:"安装失败,请查看详细日志了解具体原因。"})}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:N,className:"flex w-full items-center justify-between h-auto p-0 gap-0 hover:bg-none bg-none text-sm mb-2",children:[e.jsx("h4",{className:"font-medium",children:"安装日志"}),e.jsx("div",{className:"flex items-center gap-1",children:m?e.jsxs(e.Fragment,{children:["收起 ",e.jsx(Ls,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["展开 ",e.jsx(dt,{className:"h-4 w-4"})]})})]}),m&&e.jsx(Ne,{ref:l,className:"h-[300px] w-full rounded-md border bg-background",children:e.jsx("div",{className:"p-4 font-mono text-xs",children:n.logs.length===0?e.jsxs("div",{className:"text-muted-foreground flex items-center gap-2",children:[e.jsx(or,{className:"h-4 w-4 animate-pulse"}),"等待日志输出..."]}):e.jsx("div",{className:"space-y-1",children:n.logs.map(y=>e.jsx("div",{className:`${y.type==="stderr"?"text-orange-600":"text-foreground"} break-words`,children:g(y.message)},`${y.timestamp}-${y.message.slice(0,50)}`))})})})]})]}),e.jsx(Oe,{className:"flex items-center justify-between pt-4 border-t",children:e.jsxs("div",{className:"flex gap-2",children:[n.status==="completed"&&e.jsxs(A,{variant:"outline",onClick:()=>window.location.reload(),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"h-4 w-4"}),"重启应用"]}),e.jsx(A,{onClick:$,disabled:!d(),variant:n.status==="failed"?"destructive":"default",children:i()?"安装中...":n.status==="completed"?"完成":(n.status==="failed","关闭")})]})})]})})}const Oc=[{value:"stable",label:"正式版"},{value:"rc",label:"预览版"},{value:"beta",label:"测试版"},{value:"all",label:"全部版本"}];function an({children:r,defaultSelectedVersion:t}){const[s,n]=u.useState(!1),[a,o]=u.useState(""),[i,d]=u.useState("stable"),[l,m]=u.useState(!1),[c,p]=u.useState([]),[h,x]=u.useState(!1),{startInstall:v}=ga(),g=u.useCallback(async E=>{try{x(!0);const I=await U.getAvailableVersions(E),M=I.versions.map(L=>({value:L,label:`v${L}`}));p(M),console.log(`[VersionUpgradeDialog] 获取到 ${I.total} 个${E}版本`),t&&I.versions.includes(t||"")&&o(t||"")}catch(I){console.error("[VersionUpgradeDialog] 获取版本列表失败:",I),p([])}finally{x(!1)}},[t]);u.useEffect(()=>{s&&g(i)},[s,i,g]);const $=E=>{d(E),o("")},k=E=>{o(E)},N=async()=>{if(a)try{console.log("[VersionUpgradeDialog] 开始安装版本:",a),n(!1),m(!0),await v(a)}catch(E){console.error("[VersionUpgradeDialog] 安装失败:",E),m(!1)}},y=()=>{m(!1),o("")},P=E=>{E||(o(""),d("stable")),n(E)};return e.jsxs(e.Fragment,{children:[e.jsxs(me,{open:s,onOpenChange:P,children:[e.jsx(ke,{asChild:!0,children:r||e.jsxs(A,{className:"flex items-center gap-2",children:[e.jsx(so,{className:"h-4 w-4"}),"升级版本"]})}),e.jsxs(oe,{className:"sm:max-w-md",children:[e.jsxs(ie,{children:[e.jsx(ce,{children:"选择安装版本"}),e.jsx(Ee,{children:"请选择要安装的 xiaozhi-client 版本"})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"version-select",className:"text-sm font-medium",children:"版本选择"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Re,{value:i,onValueChange:$,children:[e.jsx(be,{id:"version-type-select",className:"w-[150px]",children:e.jsx(Te,{placeholder:"请选择版本类型"})}),e.jsx(we,{children:Oc.map(E=>e.jsx(ae,{value:E.value,children:E.label},E.value))})]}),e.jsxs(Re,{value:a,onValueChange:k,disabled:h,children:[e.jsx(be,{id:"version-select",children:e.jsx(Te,{placeholder:h?"正在获取版本列表...":"请选择版本"})}),e.jsx(we,{children:h?e.jsx(ae,{value:"loading",disabled:!0,children:"正在获取版本列表..."}):c.length===0?e.jsx(ae,{value:"empty",disabled:!0,children:"暂无可用版本"}):c.map(E=>e.jsx(ae,{value:E.value,children:E.label},E.value))})]})]}),!h&&c.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"当前版本类型暂无可用版本"}),a&&Ic.lt(a,"1.8.0")&&e.jsxs(_e,{variant:"destructive",children:[e.jsx(ro,{size:18}),e.jsx(ha,{children:"重要提醒"}),e.jsx(Be,{children:"指定版本低于1.8.0,安装后无法再使用Web界面重装,需手动通过命令操作,请谨慎操作!"})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(A,{variant:"outline",onClick:()=>n(!1),children:"取消"}),e.jsx(A,{onClick:N,disabled:!a||h,children:"确定安装"})]})]})]}),e.jsx(Pc,{isOpen:l,onClose:y,version:a})]})}function Lc({className:r}){const[t,s]=u.useState(null),[n,a]=u.useState(null),[o,i]=u.useState(!0),[d,l]=u.useState(!0),[m,c]=u.useState(null),[p,h]=u.useState(!1),x=u.useRef(null);u.useEffect(()=>{(async()=>{try{i(!0),c(null);const N=await U.getVersion();s(N)}catch(N){c(N instanceof Error?N.message:"获取版本信息失败"),console.error("获取版本信息失败:",N)}finally{i(!1)}})()},[]),u.useEffect(()=>()=>{x.current&&clearTimeout(x.current)},[]),u.useEffect(()=>{t&&(async()=>{try{l(!0);const N=await U.getLatestVersion();a(N)}catch(N){console.error("检查更新失败:",N),a({currentVersion:t?.version||"unknown",latestVersion:null,hasUpdate:!1,error:N instanceof Error?N.message:"检查更新失败"})}finally{l(!1)}})()},[t]);const v=async()=>{if(t?.version)try{await navigator.clipboard.writeText(t.version),h(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>h(!1),2e3)}catch(k){console.error("复制版本号失败:",k)}};if(o)return e.jsx(de,{variant:"outline",className:r,children:e.jsx("span",{className:"text-xs",children:"加载中..."})});if(m||!t)return e.jsx(de,{variant:"outline",className:r,children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"版本未知"})});const g=e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"h-3 w-3"}),e.jsx("span",{className:"font-semibold",children:"版本详情"})]}),e.jsxs("div",{className:"text-xs space-y-0.5",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"名称:"})," ",t.name]}),e.jsxs("div",{children:[e.jsx("strong",{children:"版本:"})," ",t.version]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("strong",{children:"最新版本:"})," ",n.latestVersion||"未知"]}),e.jsxs("div",{children:[e.jsx("strong",{children:"状态:"}),d?"检查中...":n.hasUpdate?"有新版本":"已是最新"]})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"描述:"})," ",t.description]}),e.jsxs("div",{children:[e.jsx("strong",{children:"作者:"})," ",t.author]})]}),e.jsx("div",{className:"pt-1 border-t",children:e.jsxs("button",{type:"button",onClick:v,className:"text-xs text-primary hover:underline flex items-center gap-1",children:[e.jsx(ut,{className:"h-3 w-3"}),p?"已复制!":"复制版本号"]})})]}),$=()=>d?null:n?.hasUpdate&&n.latestVersion?e.jsx(an,{defaultSelectedVersion:n.latestVersion,children:e.jsxs(A,{variant:"link",className:"p-0 gap-1",children:[e.jsx(no,{}),"升级版本"]})}):e.jsx(an,{defaultSelectedVersion:t.version,children:e.jsx(A,{variant:"link",className:"p-0 gap-1",children:"切换版本"})});return e.jsx(pa,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[$(),e.jsxs(Js,{children:[e.jsx(Xs,{asChild:!0,children:e.jsxs("span",{className:"text-sm cursor-help",children:["v",t.version]})}),e.jsx(Rt,{children:g})]})]})})}function Ac({title:r}){return e.jsxs("header",{className:"flex h-12 shrink-0 items-center gap-2 border-b px-4",children:[e.jsx("h1",{className:"text-base font-medium",children:r}),e.jsxs("div",{className:"flex flex-1 justify-end items-center gap-4",children:[e.jsx(Lc,{}),e.jsx("a",{href:"https://qun.qq.com/universal-share/share?ac=1&authKey=c08PvS2zvAF1NN%2F%2BuaOi0ze1AElTIsvFBLwbWUMFc2ixjaZYxqZTUQHzipwd8Kka&busi_data=eyJncm91cENvZGUiOiIxMDU0ODg4NDczIiwidG9rZW4iOiJuSmJUN2cyUEVkNEQ5WXovM3RQbFVNcDluMGVibUNZTUQvL1RuQnFJRjBkZmRZQnRBRTdwU0szL3V2Y0dLc1ZmIiwidWluIjoiMzkxMTcyMDYwMCJ9&data=9cH6_zEC-sN3xYlwzKEWiYF71RLY9CId5taN-gy6XZo7axSlSWDpd1Ojui5hYMQKIgEJYSPw59XYgF5vH2wLog&svctype=4&tempid=h5_group_info",target:"_blank",rel:"noopener noreferrer",children:e.jsx(sc,{size:24,className:"text-slate-800",fill:"currentColor"})}),e.jsx("a",{href:"https://github.com/shenjingnan/xiaozhi-client",target:"_blank",rel:"noopener noreferrer",children:e.jsx(rc,{size:24,className:"text-slate-800",fill:"currentColor"})})]})]})}function Mc(){return e.jsxs("div",{className:"flex h-screen flex-col",children:[e.jsx(Ac,{title:"看板"}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"@container/main flex flex-1 flex-col gap-2",children:e.jsxs("div",{className:"flex flex-col gap-4 py-4 md:gap-6 md:py-6",children:[e.jsx(Ui,{}),e.jsx("div",{className:"flex flex-col gap-4 px-4 lg:px-6",children:e.jsx(tc,{initialStatus:"all"})})]})})})]})}function Dc(){return e.jsxs(qo,{children:[e.jsx(bo,{}),e.jsxs(ao,{children:[e.jsx(Ot,{path:"/",element:e.jsx(ir,{to:"/dashboard"})}),e.jsx(Ot,{path:"/dashboard",element:e.jsx(Mc,{})}),e.jsx(Ot,{path:"*",element:e.jsx(ir,{to:"/dashboard",replace:!0})})]}),e.jsx(uo,{richColors:!0,closeButton:!0,swipeDirections:[],toastOptions:{classNames:{description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-white group-[.toast]:text-black",error:"group toast group-[.toaster]:bg-red group-[.toaster]:text-red-600 dark:group-[.toaster]:text-foreground group-[.toaster]:shadow-lg",success:"group toast group-[.toaster]:bg-green group-[.toaster]:text-green-600 dark:group-[.toaster]:text-foreground group-[.toaster]:shadow-lg",warning:"group toast group-[.toaster]:bg-yellow group-[.toaster]:text-yellow-600 dark:group-[.toaster]:text-foreground group-[.toaster]:shadow-lg",info:"group toast group-[.toaster]:bg-blue group-[.toaster]:text-blue-600 dark:group-[.toaster]:text-foreground group-[.toaster]:shadow-lg"}}})]})}oo.createRoot(document.getElementById("root")).render(e.jsx(io.StrictMode,{children:e.jsx(co,{children:e.jsx(Dc,{})})}));
|
|
81
|
-
//# sourceMappingURL=index-HnebiJM5.js.map
|