@easbot/gateway 0.2.26 → 0.2.28

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/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import {v,Q,_,$}from'./chunks/chunk-BJV43DSB.mjs';export{p as AgentRegistryConfigSchema,k as AgentSyncConfigSchema,j as AuthConfigSchema,ha as BaseChannelPlugin,h as ChannelConfigSchema,fa as ChannelPluginLoader,ra as ChannelPluginRegistry,o as CircuitBreakerConfigSchema,m as ConnectionPoolConfigSchema,_ as DEFAULT_AGENT_REGISTRY_CONFIG,aa as DEFAULT_CONNECTION_POOL_CONFIG,$ as DEFAULT_SYNC_CONFIG,Z as DEFAULT_TOKEN_AUTH_CONFIG,Y as DEFAULT_WEBSOCKET_SERVER_CONFIG,ja as DiscordPlugin,c as FeishuChannelConfigSchema,la as FeishuPlugin,l as GatewayClusterConfigSchema,s as GatewayConfigSchema,ta as GatewayServer,r as GatewayServerConfigSchema,ea as GatewaySessionManager,i as HTTPSConfigSchema,R as MessageLockManager,n as MessageQueueConfigSchema,S as MessageRetryManager,ba as MessageRouter,ca as MessageStore,g as NostrChannelConfigSchema,pa as NostrPlugin,q as SessionConfigSchema,da as SessionStore,f as SignalChannelConfigSchema,oa as SignalPlugin,b as SlackChannelConfigSchema,ka as SlackPlugin,a as TelegramChannelConfigSchema,ia as TelegramPlugin,d as WeChatChannelConfigSchema,ma as WeChatPlugin,e as WebChatChannelConfigSchema,na as WebChatPlugin,y as clearConfigCache,qa as createChannelPlugin,W as createDefaultSessionState,T as createGatewayMessage,U as createTextMessage,V as generateSessionId,X as generateSubscriptionId,N as getAgentAdapter,F as getAgentRegistryConfig,I as getAuthConfig,B as getChannelConfig,E as getCircuitBreakerConfig,J as getClusterConfig,w as getConfig,z as getConfigDirectory,C as getConnectionPoolConfig,K as getDefaultAgent,H as getHTTPSConfig,L as getLogLevel,D as getMessageQueueConfig,A as getServerConfig,G as getSessionConfig,sa as getSupportedPlatforms,O as hasAgentAdapter,x as isConfigLoaded,v as loadConfig,u as parsePartialConfig,P as requireAgentAdapter,M as setAgentAdapter,t as validateConfig}from'./chunks/chunk-BJV43DSB.mjs';import {a as a$1}from'./chunks/chunk-7OFQ65NG.mjs';import {a as a$2}from'./chunks/chunk-HAMGVOQD.mjs';import {Fetch}from'@easbot/utils';var a=a$1.create({service:"gateway"}),m=class g extends Error{constructor(t,n,s){super(t);a$2(this,"type");a$2(this,"stage");a$2(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=s,Error.captureStackTrace&&Error.captureStackTrace(this,g);}};function H(g){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=g.code;return e.includes(t??"")}function tt(){process.on("unhandledRejection",g=>{let e=g instanceof Error?g:new Error(String(g));H(e)||a.error("unhandled promise rejection",{error:e.message,stack:e.stack});}),process.on("uncaughtException",g=>{H(g)||(a.error("uncaught exception",{error:g.message,stack:g.stack}),process.exit(1));});}var x;(it=>{let g={initialized:false,initPromise:null,directory:".easbot",config:null},e,t={server:null,config:null,initialized:false,status:"stopped"};async function n(u={}){if(g.initialized)return;if(g.initPromise)return g.initPromise;let d={directory:u.directory??".easbot",printLogs:u.printLogs??false,logLevel:u.logLevel??"INFO"};return g.directory=d.directory,g.initPromise=(async()=>{let{Global:b}=await import('./chunks/global-5GMGC2RN.mjs');try{await b.init();}catch(l){throw new m("Failed to initialize global directories","global",l instanceof Error?l:void 0)}try{await a$1.init({logDir:b.Path.log,print:d.printLogs,level:d.logLevel});}catch(l){throw new m("Failed to initialize log infrastructure","log",l instanceof Error?l:void 0)}try{tt();}catch(l){throw new m("Failed to install unhandled exception handlers","server",l instanceof Error?l:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),a.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{g.config=await v(d.directory);}catch(l){throw new m("Failed to load gateway configuration","config",l instanceof Error?l:void 0)}g.initialized=true,a.info("gateway runtime initialized",{directory:d.directory,logLevel:d.logLevel});})(),g.initPromise}it.init=n;function s(){return g.initialized}it.isInitialized=s;function r(){return e||(e=async()=>{if(!g.initialized)throw new m("Gateway not initialized. Call init() first.","server");let u=Q(),d=await v(u.directory);return d.server?.enabled?(t={server:null,config:d,initialized:true,status:"stopped"},a.info("gateway initialized",{port:d.server?.port,hostname:d.server?.hostname}),t):(a.debug("gateway server disabled or not configured"),{server:null,config:d,initialized:true,status:"stopped"})}),e}function i(){return r()()}it.state=i;async function c(){return (await i()).server}it.get=c;async function p(){return (await i()).config?.server?.enabled??false}it.isEnabled=p;async function k(){return (await i()).config}it.config=k;function st(){return t.status}it.getStatus=st;async function O(u){a.debug("Gateway.start: called"),g.initialized||(a.debug("Gateway.start: calling init()"),await n(),a.debug("Gateway.start: init() completed")),a.debug("Gateway.start: calling state()");let d=await i();if(a.debug("Gateway.start: state() completed",{status:d.status}),!(d.config?.server?.enabled??true))throw a.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){a.info("gateway server is already running");return}if(t.status==="starting"){a.info("gateway server is starting");return}t.status="starting",a.debug("Gateway.start: status set to starting");try{let l={...d.config?.server,...u};a.debug("gateway start: creating server with config",{port:l.port,hostname:l.hostname,path:l.path,https:l.https?.enabled}),a.debug("Gateway.start: calling createGatewayServer");let R=await D(l);a.debug("Gateway.start: createGatewayServer completed"),a.debug("gateway start: server created, updating state"),t.server=R,t.status="running",t.error=void 0,a.info("gateway server started",{port:l.port,hostname:l.hostname});}catch(l){throw t.status="error",t.error=l instanceof Error?l.message:String(l),a.error("failed to start gateway server",{error:t.error}),l}}it.start=O;async function F(){if(t.status==="stopped"){a.info("gateway server is already stopped");return}if(t.status==="stopping"){a.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,await a$1.close(),a.info("gateway server stopped");}catch(u){throw t.status="error",t.error=u instanceof Error?u.message:String(u),a.error("failed to stop gateway server",{error:t.error}),u}}it.stop=F;async function rt(u){a.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await F(),await O(u);}it.restart=rt;async function at(){let u=Q(),d=await v(u.directory);return t.config=d,g.config=d,a.info("gateway config reloaded"),d}it.reloadConfig=at;async function D(u,d){a.debug("createGatewayServer: starting");let{GatewayServer:b}=await import('./chunks/server-Y336TWLM.mjs');a.debug("createGatewayServer: GatewayServer imported");let l=new b(u);a.debug("createGatewayServer: server instance created"),a.debug("createGatewayServer: created server instance, calling start()");let R=d?.startupTimeout??3e4;if(await(async()=>{let A=new Promise((v,q)=>{setTimeout(()=>{q(new Error(`Gateway server startup timeout after ${R}ms`));},R);});try{a.debug("createGatewayServer: calling server.start()"),await Promise.race([l.start(),A]),a.debug("createGatewayServer: server.start() completed");}catch(v){a.error("gateway server start failed, attempting cleanup",{error:v instanceof Error?v.message:String(v)});try{await l.stop();}catch{}throw v}})(),d?.onStarted)try{await d.onStarted(l);}catch(A){a.warn("server started but onStarted callback failed",{error:A instanceof Error?A.message:String(A)});}return a.info("gateway server created and started",{port:u.port,hostname:u.hostname}),l}it.createGatewayServer=D;})(x||(x={}));var f=a$1.create({service:"gateway:agent-registry"}),M=class{constructor(e={}){a$2(this,"config");a$2(this,"agents",new Map);a$2(this,"heartbeatTimer",null);a$2(this,"roundRobinIndex",0);this.config={..._,...e};}async register(e){if(this.agents.has(e.id))throw new Error(`Agent with ID "${e.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let t=Date.now(),n={...e,status:"healthy",lastHeartbeat:t,registeredAt:t,connectionCount:0};this.agents.set(e.id,n),f.info("Agent registered",{agentId:e.id,name:e.name,capabilities:e.capabilities,address:e.address,totalAgents:this.agents.size});}async deregister(e){let t=this.agents.get(e);if(!t){f.warn("Attempted to deregister unknown agent",{agentId:e});return}this.agents.delete(e),f.info("Agent deregistered",{agentId:e,name:t.name,totalAgents:this.agents.size});}async heartbeat(e,t){let n=this.agents.get(e);if(!n)throw f.warn("Heartbeat received from unknown agent",{agentId:e}),new Error(`Agent "${e}" is not registered`);n.lastHeartbeat=Date.now(),n.status="healthy",t&&(n.metadata={...n.metadata,...t}),f.debug("Agent heartbeat received",{agentId:e,lastHeartbeat:n.lastHeartbeat});}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(e=>e.status==="healthy")}selectAgent(e){let{strategy:t,capabilities:n,healthyOnly:s=true}=e,r=s?this.getHealthyAgents():this.getAllAgents();if(n&&n.length>0&&(r=r.filter(c=>n.every(p=>c.capabilities.includes(p)))),r.length===0){f.warn("No agents available for selection",{strategy:t,capabilities:n,healthyOnly:s,totalAgents:this.agents.size});return}let i;switch(t){case "random":i=this.selectRandom(r);break;case "round-robin":i=this.selectRoundRobin(r);break;case "least-connections":i=this.selectLeastConnections(r);break;default:i=this.selectRandom(r);}return f.debug("Agent selected",{agentId:i.id,strategy:t,connectionCount:i.connectionCount}),i}incrementConnection(e){let t=this.agents.get(e);t&&(t.connectionCount++,f.debug("Agent connection incremented",{agentId:e,connectionCount:t.connectionCount}));}decrementConnection(e){let t=this.agents.get(e);t&&t.connectionCount>0&&(t.connectionCount--,f.debug("Agent connection decremented",{agentId:e,connectionCount:t.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){f.warn("Heartbeat check is already running");return}f.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,f.info("Heartbeat check stopped"));}checkHeartbeats(){let e=Date.now(),{heartbeatTimeout:t,autoDeregisterTimeout:n}=this.config,s=[],r=0;for(let[i,c]of this.agents.entries()){let p=e-c.lastHeartbeat;if(p>n){s.push(i);continue}p>t&&c.status==="healthy"&&(c.status="unhealthy",r++,f.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:i,lastHeartbeat:c.lastHeartbeat,timeSinceLastHeartbeat:p,timeout:t}));}for(let i of s){let c=this.agents.get(i);c&&(f.info("Auto-deregistering agent due to timeout",{agentId:i,name:c.name,lastHeartbeat:c.lastHeartbeat,timeout:n}),this.agents.delete(i));}(r>0||s.length>0)&&f.info("Heartbeat check completed",{unhealthyCount:r,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(e){let t=Math.floor(Math.random()*e.length);return e[t]}selectRoundRobin(e){this.roundRobinIndex=this.roundRobinIndex%e.length;let t=e[this.roundRobinIndex];return this.roundRobinIndex++,t}selectLeastConnections(e){return e.reduce((t,n)=>n.connectionCount<t.connectionCount?n:t)}getStats(){let e=this.getAllAgents();return {totalAgents:e.length,healthyAgents:e.filter(t=>t.status==="healthy").length,unhealthyAgents:e.filter(t=>t.status==="unhealthy").length,offlineAgents:e.filter(t=>t.status==="offline").length,totalConnections:e.reduce((t,n)=>t+n.connectionCount,0)}}setAgentStatus(e,t){let n=this.agents.get(e);n&&(n.status=t);}setLastHeartbeat(e,t){let n=this.agents.get(e);n&&(n.lastHeartbeat=t);}};var h=a$1.create({service:"gateway:agent-sync-manager"}),T=class{constructor(e){a$2(this,"config");a$2(this,"registry");a$2(this,"localNodeId");a$2(this,"localNodeName");a$2(this,"remoteNodes",new Map);a$2(this,"remoteAgents",new Map);a$2(this,"syncTimer",null);a$2(this,"running",false);this.registry=e.registry,this.localNodeId=e.localNodeId,this.localNodeName=e.localNodeName,this.config={...$,...e.config};}async start(){if(this.running){h.warn("Agent sync manager is already running");return}h.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let e of this.config.remoteNodes)this.remoteNodes.set(e.id,{info:{id:e.id,name:e.id,address:e.address,port:e.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.running=true,h.info("Agent sync manager started");}async stop(){if(!this.running){h.warn("Agent sync manager is not running");return}h.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,h.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[e]of this.remoteNodes.entries())try{await this.pullFromNode(e);}catch(t){h.error("Failed to pull from node",{nodeId:e,error:t.message});}}async pullFromNode(e){let t=this.remoteNodes.get(e);if(!t)throw new Error(`Unknown remote node: ${e}`);t.status="syncing";let n=this.config.remoteNodes.find(s=>s.id===e);if(!n)throw new Error(`Remote node not found in config: ${e}`);h.debug("Pulling agent list from node",{nodeId:e,address:n.address});try{let s=`http://${n.address}:${n.port}/sync/agents`,r=await Fetch.get(s,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);let i=r.data.agents||[];for(let c of i)c.sourceGatewayId=e,this.remoteAgents.set(c.id,c);return t.lastSyncAt=Date.now(),t.status="synced",t.info.lastSyncAt=t.lastSyncAt,t.info.status="online",delete t.error,h.info("Pulled agent list from node",{nodeId:e,agentCount:i.length,lastSyncAt:t.lastSyncAt}),i}catch(s){throw t.status="error",t.error=s.message,t.info.status="offline",h.error("Failed to pull from node",{nodeId:e,error:s.message}),s}}async pushEvent(e){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let t=[];for(let[n]of this.remoteNodes.entries())t.push(this.pushToNode(n,e));await Promise.allSettled(t);}async pushToNode(e,t){let n=this.config.remoteNodes.find(s=>s.id===e);if(!n){h.warn("Unknown remote node for push",{nodeId:e});return}try{let s=`http://${n.address}:${n.port}/sync/events`,r=await Fetch.post(s,t,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);h.debug("Pushed event to node",{nodeId:e,eventType:t.type});}catch(s){h.error("Failed to push to node",{nodeId:e,eventType:t.type,error:s.message});}}async handleSyncMessage(e){switch(h.debug("Received sync message",{type:e.type,sourceNodeId:e.sourceNodeId}),e.type){case "agent_list_request":await this.handleAgentListRequest(e);break;case "agent_list_response":await this.handleAgentListResponse(e);break;case "agent_register":await this.handleAgentRegister(e);break;case "agent_deregister":await this.handleAgentDeregister(e);break;case "agent_heartbeat":await this.handleAgentHeartbeat(e);break;case "agent_status_change":await this.handleAgentStatusChange(e);break;default:h.warn("Unknown sync message type",{type:e.type});}}async handleAgentListRequest(e){let t=this.getLocalAgentsForSync(),n={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:e.requestId,agents:t,fullList:true,syncAt:Date.now()};await this.pushToNode(e.sourceNodeId,n);}async handleAgentListResponse(e){for(let t of e.agents)this.remoteAgents.set(t.id,t);h.info("Received agent list response",{sourceNodeId:e.sourceNodeId,agentCount:e.agents.length});}async handleAgentRegister(e){let{agent:t}=e,n=this.remoteAgents.get(t.id);if(n){let s=this.resolveConflict(n,t);this.remoteAgents.set(t.id,s);}else this.remoteAgents.set(t.id,t);h.info("Remote agent registered",{agentId:t.id,name:t.name,sourceNodeId:e.sourceNodeId});}async handleAgentDeregister(e){let{agentId:t}=e;this.remoteAgents.delete(t),h.info("Remote agent deregistered",{agentId:t,sourceNodeId:e.sourceNodeId});}async handleAgentHeartbeat(e){let{agentId:t,heartbeatAt:n,status:s}=e,r=this.remoteAgents.get(t);r&&(r.updatedAt=n,r.status=s),h.debug("Remote agent heartbeat received",{agentId:t,status:s,sourceNodeId:e.sourceNodeId});}async handleAgentStatusChange(e){let{agentId:t,newStatus:n,changedAt:s}=e,r=this.remoteAgents.get(t);r&&(r.status=n,r.updatedAt=s),h.info("Remote agent status changed",{agentId:t,newStatus:n,sourceNodeId:e.sourceNodeId});}resolveConflict(e,t){switch(this.config.conflictResolution){case "latest":return t.updatedAt>e.updatedAt?t:e;case "local":return e;case "remote":return t;default:return t.updatedAt>e.updatedAt?t:e}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(t=>({id:t.id,name:t.name,sourceGatewayId:this.localNodeId,address:t.address,capabilities:t.capabilities,status:t.status,updatedAt:t.lastHeartbeat,metadata:t.metadata}))}getMergedAgentList(){let e=new Map;for(let t of this.getLocalAgentsForSync())e.set(t.id,t);for(let[t,n]of this.remoteAgents.entries())e.has(t)||e.set(t,n);return Array.from(e.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let e=this.registry.getAllAgents(),t=0,n=0;for(let r of this.remoteNodes.values())r.info.status==="online"?t++:n++;let s=null;for(let r of this.remoteNodes.values())r.lastSyncAt>(s||0)&&(s=r.lastSyncAt);return {localAgentCount:e.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:e.length+this.remoteAgents.size,onlineNodeCount:t,offlineNodeCount:n,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(e){this.remoteNodes.set(e.id,{info:{id:e.id,name:e.id,address:e.address,port:e.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),h.info("Remote node added",{nodeId:e.id,address:e.address});}removeRemoteNode(e){this.remoteNodes.delete(e);for(let[t,n]of this.remoteAgents.entries())n.sourceGatewayId===e&&this.remoteAgents.delete(t);h.info("Remote node removed",{nodeId:e});}};var N=class{constructor(e){a$2(this,"log");a$2(this,"config");a$2(this,"ws",null);a$2(this,"state","disconnected");a$2(this,"subscriptions",new Map);a$2(this,"messageCallbacks",new Set);a$2(this,"agentListCallbacks",new Set);a$2(this,"cachedAgentList",[]);a$2(this,"localAgentList",[]);a$2(this,"reconnectAttempts",0);a$2(this,"reconnectTimer",null);a$2(this,"heartbeatTimer",null);a$2(this,"agentListRequestId",null);a$2(this,"agentListRequestResolve",null);this.config={url:e.url,type:e.type,id:e.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:e.reconnect?.enabled??true,maxAttempts:e.reconnect?.maxAttempts??5,delay:e.reconnect?.delay??3e3},heartbeat:{enabled:e.heartbeat?.enabled??true,interval:e.heartbeat?.interval??3e4}},this.log=a$1.create({service:`gateway:client:${this.config.id}`});}async connect(){if(this.state==="connected"||this.state==="connecting"){this.log.warn("already connected or connecting");return}return this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),new Promise((e,t)=>{try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{this.state="connected",this.reconnectAttempts=0,this.log.info("connected to gateway"),this.config.heartbeat.enabled&&this.startHeartbeat(),this.resubscribeAll(),e();},this.ws.onmessage=n=>{this.handleMessage(n.data);},this.ws.onclose=n=>{this.handleClose(n.code,n.reason);},this.ws.onerror=n=>{this.log.error("WebSocket error",{error:String(n)}),this.state==="connecting"&&t(new Error("Connection failed"));};}catch(n){this.state="disconnected",t(n);}})}async disconnect(){this.state!=="disconnected"&&(this.log.info("disconnecting from gateway"),this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"));}async subscribe(e,t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:e,backendSessionId:t,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:e,backendSessionId:t});}async unsubscribe(e){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:e,clientId:this.config.id}),this.subscriptions.delete(e),this.log.info("unsubscribed from session",{sessionId:e});}async send(e){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:e});}onMessage(e){this.messageCallbacks.add(e);}offMessage(e){this.messageCallbacks.delete(e);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(e){this.localAgentList=e,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((e,t)=>{let n=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=n,this.agentListRequestResolve=e,this.sendData({type:"agent_list_request",requestId:n}),setTimeout(()=>{this.agentListRequestId===n&&(this.agentListRequestId=null,this.agentListRequestResolve=null,t(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(e={}){let{localAgents:t,preferLocal:n=true,filterOffline:s=true}=e,r=t||this.localAgentList,i=this.cachedAgentList,c=this.mergeAgentLists(r,i,n);return s?c.filter(p=>p.status!=="offline"):c}onAgentListChange(e){this.agentListCallbacks.add(e);}offAgentListChange(e){this.agentListCallbacks.delete(e);}mergeAgentLists(e,t,n){let s=new Map,r=n?t:e,i=n?e:t;for(let c of r)s.set(c.id,c);for(let c of i)s.set(c.id,c);return Array.from(s.values())}updateMergedAgentList(){let e=this.getConnectableAgents({filterOffline:false});for(let t of this.agentListCallbacks)try{t(e);}catch(n){this.log.error("agent list callback error",{error:String(n)});}}handleAgentListResponse(e,t){t&&this.agentListRequestId===t&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(e),this.agentListRequestResolve=null),this.cachedAgentList=e,this.updateMergedAgentList(),this.log.debug("received agent list",{count:e.length});}sendData(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(e));}handleMessage(e){try{let t=JSON.parse(e);switch(t.type){case "message":this.handleGatewayMessage(t.message);break;case "subscribed":this.subscriptions.set(t.sessionId,t.subscription);break;case "unsubscribed":this.subscriptions.delete(t.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(t.agents||[],t.requestId);break;case "agent_update":this.handleAgentUpdate(t.agent,t.action);break;default:this.log.debug("unknown message type",{type:t.type});}}catch(t){this.log.error("failed to parse message",{error:String(t)});}}handleAgentUpdate(e,t){switch(t){case "add":case "update":{let n=this.cachedAgentList.findIndex(s=>s.id===e.id);n>=0?this.cachedAgentList[n]=e:this.cachedAgentList.push(e);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(n=>n.id!==e.id);break}this.updateMergedAgentList();}handleGatewayMessage(e){for(let t of this.messageCallbacks)try{t(e);}catch(n){this.log.error("message callback error",{error:String(n)});}}handleClose(e,t){this.log.info("connection closed",{code:e,reason:t}),this.state="disconnected",this.ws=null,this.stopHeartbeat(),this.config.reconnect.enabled&&this.scheduleReconnect();}scheduleReconnect(){if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){this.log.error("max reconnect attempts reached");return}this.reconnectAttempts++,this.state="reconnecting";let e=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:e}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(t){this.log.error("reconnect failed",{error:String(t)});}},e);}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.state==="connected"&&this.sendData({type:"ping"});},this.config.heartbeat.interval);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}async resubscribeAll(){for(let e of this.subscriptions.keys())try{await this.subscribe(e);}catch(t){this.log.error("failed to resubscribe",{sessionId:e,error:String(t)});}}getHttpUrl(){return this.config.url.replace(/^ws:/,"http:").replace(/^wss:/,"https:").replace(/\/$/,"")}async httpRequest(e,t={}){let n=`${this.getHttpUrl()}${e}`,s=t.method||"GET",{signal:r,...i}=t,c=await Fetch.request(n,{method:s,...i,headers:{"Content-Type":"application/json",...i.headers},...r?{signal:r}:{}});if(!c.ok){let p=c.data,k=typeof p=="object"?JSON.stringify(p):String(p||"Unknown error");throw new Error(`HTTP ${c.status}: ${k}`)}return c.data}async healthCheck(){return this.httpRequest("/health")}async getStatus(){return this.httpRequest("/status")}async listChannels(){return this.httpRequest("/channels")}async listContacts(e,t={}){let n=new URLSearchParams({platform:e,limit:String(t.limit??100),offset:String(t.offset??0)});return this.httpRequest(`/contacts?${n}`)}async getContact(e){return this.httpRequest(`/contacts/${encodeURIComponent(e)}`)}async getSession(e){return this.httpRequest(`/sessions/${encodeURIComponent(e)}`)}async createSession(e){return this.httpRequest("/session",{method:"POST",body:JSON.stringify(e??{})})}async getOrCreateSession(e){if(e.sessionId)try{return await this.getSession(e.sessionId),{sessionId:e.sessionId,created:!1}}catch{this.log.debug("session not found, will create new",{sessionId:e.sessionId});}if(e.platform||e.channel||e.userId){try{let r=await this.listSessions({platform:e.platform,channelId:e.channel,userId:e.userId});if(r.sessions.length>0){let i=r.sessions[0];if(i)return this.log.info("found existing session",{sessionId:i.id,channel:e.channel,userId:e.userId}),{sessionId:i.id,created:!1}}}catch(r){this.log.warn("failed to search sessions",{error:String(r)});}let n={};e.channel&&(n.channel=e.channel),e.userId&&(n.userId=e.userId),e.platform&&(n.platform=e.platform);let s=await this.createSession(n);return this.log.info("session created",{sessionId:s.id,params:n}),{sessionId:s.id,created:true}}let t=await this.createSession({});return this.log.info("session created (default)",{sessionId:t.id}),{sessionId:t.id,created:true}}async listSessions(e={}){let t=new URLSearchParams;return t.set("limit",String(e.limit??100)),t.set("offset",String(e.offset??0)),e.platform&&t.set("platform",e.platform),e.channelId&&t.set("channelId",e.channelId),e.userId&&t.set("userId",e.userId),this.httpRequest(`/sessions?${t}`)}async sendMessage(e,t){return this.httpRequest(`/session/${encodeURIComponent(e)}/prompt`,{method:"POST",body:JSON.stringify(t)})}};async function $t(g){let{Log:e}=await import('./chunks/log-MIT4H7S5.mjs'),t=false;await e.init({logDir:g.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:g.print??false,dev:g.dev??t,level:g.level??("INFO")});}
2
- export{M as AgentRegistry,T as AgentSyncManager,x as Gateway,N as GatewayClient,$t as initLog};
1
+ import {v,Q,Z,_}from'./chunks/chunk-7MRTMPLX.mjs';export{p as AgentRegistryConfigSchema,k as AgentSyncConfigSchema,j as AuthConfigSchema,ga as BaseChannelPlugin,h as ChannelConfigSchema,ea as ChannelPluginLoader,qa as ChannelPluginRegistry,o as CircuitBreakerConfigSchema,m as ConnectionPoolConfigSchema,Z as DEFAULT_AGENT_REGISTRY_CONFIG,$ as DEFAULT_CONNECTION_POOL_CONFIG,_ as DEFAULT_SYNC_CONFIG,Y as DEFAULT_TOKEN_AUTH_CONFIG,X as DEFAULT_WEBSOCKET_SERVER_CONFIG,ia as DiscordPlugin,c as FeishuChannelConfigSchema,ka as FeishuPlugin,l as GatewayClusterConfigSchema,s as GatewayConfigSchema,sa as GatewayServer,r as GatewayServerConfigSchema,da as GatewaySessionManager,i as HTTPSConfigSchema,n as MessageQueueConfigSchema,aa as MessageRouter,ba as MessageStore,g as NostrChannelConfigSchema,oa as NostrPlugin,q as SessionConfigSchema,ca as SessionStore,f as SignalChannelConfigSchema,na as SignalPlugin,b as SlackChannelConfigSchema,ja as SlackPlugin,a as TelegramChannelConfigSchema,ha as TelegramPlugin,d as WeChatChannelConfigSchema,la as WeChatPlugin,e as WebChatChannelConfigSchema,ma as WebChatPlugin,y as clearConfigCache,T as convertToGatewayMessage,pa as createChannelPlugin,V as createDefaultSessionState,R as createGatewayMessage,S as createTextMessage,U as generateSessionId,W as generateSubscriptionId,N as getAgentAdapter,F as getAgentRegistryConfig,I as getAuthConfig,B as getChannelConfig,E as getCircuitBreakerConfig,J as getClusterConfig,w as getConfig,z as getConfigDirectory,C as getConnectionPoolConfig,K as getDefaultAgent,H as getHTTPSConfig,L as getLogLevel,D as getMessageQueueConfig,A as getServerConfig,G as getSessionConfig,ra as getSupportedPlatforms,O as hasAgentAdapter,x as isConfigLoaded,v as loadConfig,u as parsePartialConfig,P as requireAgentAdapter,M as setAgentAdapter,t as validateConfig}from'./chunks/chunk-7MRTMPLX.mjs';import {a as a$1}from'./chunks/chunk-7OFQ65NG.mjs';import {a as a$2}from'./chunks/chunk-HAMGVOQD.mjs';import {Fetch}from'@easbot/utils';var a=a$1.create({service:"gateway"}),m=class c extends Error{constructor(t,n,s){super(t);a$2(this,"type");a$2(this,"stage");a$2(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=s,Error.captureStackTrace&&Error.captureStackTrace(this,c);}};function H(c){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=c.code;return e.includes(t??"")}function et(){process.on("unhandledRejection",c=>{let e=c instanceof Error?c:new Error(String(c));H(e)||a.error("unhandled promise rejection",{error:e.message,stack:e.stack});}),process.on("uncaughtException",c=>{H(c)||(a.error("uncaught exception",{error:c.message,stack:c.stack}),process.exit(1));});}var x;(at=>{let c={initialized:false,initPromise:null,directory:".easbot",config:null},e,t={server:null,config:null,initialized:false,status:"stopped"};async function n(u={}){if(c.initialized)return;if(c.initPromise)return c.initPromise;let d={directory:u.directory??".easbot",printLogs:u.printLogs??false,logLevel:u.logLevel??"INFO"};return c.directory=d.directory,c.initPromise=(async()=>{let{Global:b}=await import('./chunks/global-3C3XWTXD.mjs');try{await b.init();}catch(l){throw new m("Failed to initialize global directories","global",l instanceof Error?l:void 0)}try{await a$1.init({logDir:b.Path.log,print:d.printLogs,level:d.logLevel});}catch(l){throw new m("Failed to initialize log infrastructure","log",l instanceof Error?l:void 0)}try{et();}catch(l){throw new m("Failed to install unhandled exception handlers","server",l instanceof Error?l:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),a.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{c.config=await v(d.directory);}catch(l){throw new m("Failed to load gateway configuration","config",l instanceof Error?l:void 0)}c.initialized=true,a.info("gateway runtime initialized",{directory:d.directory,logLevel:d.logLevel});})(),c.initPromise}at.init=n;function s(){return c.initialized}at.isInitialized=s;function r(){return e||(e=async()=>{if(!c.initialized)throw new m("Gateway not initialized. Call init() first.","server");let u=Q(),d=await v(u.directory);return d.server?.enabled?(t={server:null,config:d,initialized:true,status:"stopped"},a.info("gateway initialized",{port:d.server?.port,hostname:d.server?.hostname}),t):(a.debug("gateway server disabled or not configured"),{server:null,config:d,initialized:true,status:"stopped"})}),e}function i(){return r()()}at.state=i;async function o(){return (await i()).server}at.get=o;async function p(){return (await i()).config?.server?.enabled??false}at.isEnabled=p;async function G(){return (await i()).config}at.config=G;function nt(){return t.status}at.getStatus=nt;async function O(u){a.debug("Gateway.start: called"),c.initialized||(a.debug("Gateway.start: calling init()"),await n(),a.debug("Gateway.start: init() completed")),a.debug("Gateway.start: calling state()");let d=await i();if(a.debug("Gateway.start: state() completed",{status:d.status}),!(d.config?.server?.enabled??true))throw a.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){a.info("gateway server is already running");return}if(t.status==="starting"){a.info("gateway server is starting");return}t.status="starting",a.debug("Gateway.start: status set to starting");try{let l={...d.config?.server,...u};a.debug("gateway start: creating server with config",{port:l.port,hostname:l.hostname,path:l.path,https:l.https?.enabled}),a.debug("Gateway.start: calling createGatewayServer");let I=await D(l);a.debug("Gateway.start: createGatewayServer completed"),a.debug("gateway start: server created, updating state"),t.server=I,t.status="running",t.error=void 0,a.info("gateway server started",{port:l.port,hostname:l.hostname});}catch(l){throw t.status="error",t.error=l instanceof Error?l.message:String(l),a.error("failed to start gateway server",{error:t.error}),l}}at.start=O;async function F(){if(t.status==="stopped"){a.info("gateway server is already stopped");return}if(t.status==="stopping"){a.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,await a$1.close(),a.info("gateway server stopped");}catch(u){throw t.status="error",t.error=u instanceof Error?u.message:String(u),a.error("failed to stop gateway server",{error:t.error}),u}}at.stop=F;async function st(u){a.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await F(),await O(u);}at.restart=st;async function rt(){let u=Q(),d=await v(u.directory);return t.config=d,c.config=d,a.info("gateway config reloaded"),d}at.reloadConfig=rt;async function D(u,d){a.debug("createGatewayServer: starting");let{GatewayServer:b}=await import('./chunks/server-XIYWSC63.mjs');a.debug("createGatewayServer: GatewayServer imported");let l=new b(u);a.debug("createGatewayServer: server instance created"),a.debug("createGatewayServer: created server instance, calling start()");let I=d?.startupTimeout??3e4;if(await(async()=>{let A=new Promise((v,q)=>{setTimeout(()=>{q(new Error(`Gateway server startup timeout after ${I}ms`));},I);});try{a.debug("createGatewayServer: calling server.start()"),await Promise.race([l.start(),A]),a.debug("createGatewayServer: server.start() completed");}catch(v){a.error("gateway server start failed, attempting cleanup",{error:v instanceof Error?v.message:String(v)});try{await l.stop();}catch{}throw v}})(),d?.onStarted)try{await d.onStarted(l);}catch(A){a.warn("server started but onStarted callback failed",{error:A instanceof Error?A.message:String(A)});}return a.info("gateway server created and started",{port:u.port,hostname:u.hostname}),l}at.createGatewayServer=D;})(x||(x={}));var f=a$1.create({service:"gateway:agent-registry"}),T=class{constructor(e={}){a$2(this,"config");a$2(this,"agents",new Map);a$2(this,"heartbeatTimer",null);a$2(this,"roundRobinIndex",0);this.config={...Z,...e};}async register(e){if(this.agents.has(e.id))throw new Error(`Agent with ID "${e.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let t=Date.now(),n={...e,status:"healthy",lastHeartbeat:t,registeredAt:t,connectionCount:0};this.agents.set(e.id,n),f.info("Agent registered",{agentId:e.id,name:e.name,capabilities:e.capabilities,address:e.address,totalAgents:this.agents.size});}async deregister(e){let t=this.agents.get(e);if(!t){f.warn("Attempted to deregister unknown agent",{agentId:e});return}this.agents.delete(e),f.info("Agent deregistered",{agentId:e,name:t.name,totalAgents:this.agents.size});}async heartbeat(e,t){let n=this.agents.get(e);if(!n)throw f.warn("Heartbeat received from unknown agent",{agentId:e}),new Error(`Agent "${e}" is not registered`);n.lastHeartbeat=Date.now(),n.status="healthy",t&&(n.metadata={...n.metadata,...t}),f.debug("Agent heartbeat received",{agentId:e,lastHeartbeat:n.lastHeartbeat});}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(e=>e.status==="healthy")}selectAgent(e){let{strategy:t,capabilities:n,healthyOnly:s=true}=e,r=s?this.getHealthyAgents():this.getAllAgents();if(n&&n.length>0&&(r=r.filter(o=>n.every(p=>o.capabilities.includes(p)))),r.length===0){f.warn("No agents available for selection",{strategy:t,capabilities:n,healthyOnly:s,totalAgents:this.agents.size});return}let i;switch(t){case "random":i=this.selectRandom(r);break;case "round-robin":i=this.selectRoundRobin(r);break;case "least-connections":i=this.selectLeastConnections(r);break;default:i=this.selectRandom(r);}return f.debug("Agent selected",{agentId:i.id,strategy:t,connectionCount:i.connectionCount}),i}incrementConnection(e){let t=this.agents.get(e);t&&(t.connectionCount++,f.debug("Agent connection incremented",{agentId:e,connectionCount:t.connectionCount}));}decrementConnection(e){let t=this.agents.get(e);t&&t.connectionCount>0&&(t.connectionCount--,f.debug("Agent connection decremented",{agentId:e,connectionCount:t.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){f.warn("Heartbeat check is already running");return}f.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,f.info("Heartbeat check stopped"));}checkHeartbeats(){let e=Date.now(),{heartbeatTimeout:t,autoDeregisterTimeout:n}=this.config,s=[],r=0;for(let[i,o]of this.agents.entries()){let p=e-o.lastHeartbeat;if(p>n){s.push(i);continue}p>t&&o.status==="healthy"&&(o.status="unhealthy",r++,f.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:i,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:p,timeout:t}));}for(let i of s){let o=this.agents.get(i);o&&(f.info("Auto-deregistering agent due to timeout",{agentId:i,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:n}),this.agents.delete(i));}(r>0||s.length>0)&&f.info("Heartbeat check completed",{unhealthyCount:r,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(e){let t=Math.floor(Math.random()*e.length);return e[t]}selectRoundRobin(e){this.roundRobinIndex=this.roundRobinIndex%e.length;let t=e[this.roundRobinIndex];return this.roundRobinIndex++,t}selectLeastConnections(e){return e.reduce((t,n)=>n.connectionCount<t.connectionCount?n:t)}getStats(){let e=this.getAllAgents();return {totalAgents:e.length,healthyAgents:e.filter(t=>t.status==="healthy").length,unhealthyAgents:e.filter(t=>t.status==="unhealthy").length,offlineAgents:e.filter(t=>t.status==="offline").length,totalConnections:e.reduce((t,n)=>t+n.connectionCount,0)}}setAgentStatus(e,t){let n=this.agents.get(e);n&&(n.status=t);}setLastHeartbeat(e,t){let n=this.agents.get(e);n&&(n.lastHeartbeat=t);}};var h=a$1.create({service:"gateway:agent-sync-manager"}),M=class{constructor(e){a$2(this,"config");a$2(this,"registry");a$2(this,"localNodeId");a$2(this,"localNodeName");a$2(this,"remoteNodes",new Map);a$2(this,"remoteAgents",new Map);a$2(this,"syncTimer",null);a$2(this,"running",false);this.registry=e.registry,this.localNodeId=e.localNodeId,this.localNodeName=e.localNodeName,this.config={..._,...e.config};}async start(){if(this.running){h.warn("Agent sync manager is already running");return}h.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let e of this.config.remoteNodes)this.remoteNodes.set(e.id,{info:{id:e.id,name:e.id,address:e.address,port:e.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.running=true,h.info("Agent sync manager started");}async stop(){if(!this.running){h.warn("Agent sync manager is not running");return}h.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,h.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[e]of this.remoteNodes.entries())try{await this.pullFromNode(e);}catch(t){h.error("Failed to pull from node",{nodeId:e,error:t.message});}}async pullFromNode(e){let t=this.remoteNodes.get(e);if(!t)throw new Error(`Unknown remote node: ${e}`);t.status="syncing";let n=this.config.remoteNodes.find(s=>s.id===e);if(!n)throw new Error(`Remote node not found in config: ${e}`);h.debug("Pulling agent list from node",{nodeId:e,address:n.address});try{let s=`http://${n.address}:${n.port}/sync/agents`,r=await Fetch.get(s,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);let i=r.data.agents||[];for(let o of i)o.sourceGatewayId=e,this.remoteAgents.set(o.id,o);return t.lastSyncAt=Date.now(),t.status="synced",t.info.lastSyncAt=t.lastSyncAt,t.info.status="online",delete t.error,h.info("Pulled agent list from node",{nodeId:e,agentCount:i.length,lastSyncAt:t.lastSyncAt}),i}catch(s){throw t.status="error",t.error=s.message,t.info.status="offline",h.error("Failed to pull from node",{nodeId:e,error:s.message}),s}}async pushEvent(e){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let t=[];for(let[n]of this.remoteNodes.entries())t.push(this.pushToNode(n,e));await Promise.allSettled(t);}async pushToNode(e,t){let n=this.config.remoteNodes.find(s=>s.id===e);if(!n){h.warn("Unknown remote node for push",{nodeId:e});return}try{let s=`http://${n.address}:${n.port}/sync/events`,r=await Fetch.post(s,t,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);h.debug("Pushed event to node",{nodeId:e,eventType:t.type});}catch(s){h.error("Failed to push to node",{nodeId:e,eventType:t.type,error:s.message});}}async handleSyncMessage(e){switch(h.debug("Received sync message",{type:e.type,sourceNodeId:e.sourceNodeId}),e.type){case "agent_list_request":await this.handleAgentListRequest(e);break;case "agent_list_response":await this.handleAgentListResponse(e);break;case "agent_register":await this.handleAgentRegister(e);break;case "agent_deregister":await this.handleAgentDeregister(e);break;case "agent_heartbeat":await this.handleAgentHeartbeat(e);break;case "agent_status_change":await this.handleAgentStatusChange(e);break;default:h.warn("Unknown sync message type",{type:e.type});}}async handleAgentListRequest(e){let t=this.getLocalAgentsForSync(),n={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:e.requestId,agents:t,fullList:true,syncAt:Date.now()};await this.pushToNode(e.sourceNodeId,n);}async handleAgentListResponse(e){for(let t of e.agents)this.remoteAgents.set(t.id,t);h.info("Received agent list response",{sourceNodeId:e.sourceNodeId,agentCount:e.agents.length});}async handleAgentRegister(e){let{agent:t}=e,n=this.remoteAgents.get(t.id);if(n){let s=this.resolveConflict(n,t);this.remoteAgents.set(t.id,s);}else this.remoteAgents.set(t.id,t);h.info("Remote agent registered",{agentId:t.id,name:t.name,sourceNodeId:e.sourceNodeId});}async handleAgentDeregister(e){let{agentId:t}=e;this.remoteAgents.delete(t),h.info("Remote agent deregistered",{agentId:t,sourceNodeId:e.sourceNodeId});}async handleAgentHeartbeat(e){let{agentId:t,heartbeatAt:n,status:s}=e,r=this.remoteAgents.get(t);r&&(r.updatedAt=n,r.status=s),h.debug("Remote agent heartbeat received",{agentId:t,status:s,sourceNodeId:e.sourceNodeId});}async handleAgentStatusChange(e){let{agentId:t,newStatus:n,changedAt:s}=e,r=this.remoteAgents.get(t);r&&(r.status=n,r.updatedAt=s),h.info("Remote agent status changed",{agentId:t,newStatus:n,sourceNodeId:e.sourceNodeId});}resolveConflict(e,t){switch(this.config.conflictResolution){case "latest":return t.updatedAt>e.updatedAt?t:e;case "local":return e;case "remote":return t;default:return t.updatedAt>e.updatedAt?t:e}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(t=>({id:t.id,name:t.name,sourceGatewayId:this.localNodeId,address:t.address,capabilities:t.capabilities,status:t.status,updatedAt:t.lastHeartbeat,metadata:t.metadata}))}getMergedAgentList(){let e=new Map;for(let t of this.getLocalAgentsForSync())e.set(t.id,t);for(let[t,n]of this.remoteAgents.entries())e.has(t)||e.set(t,n);return Array.from(e.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let e=this.registry.getAllAgents(),t=0,n=0;for(let r of this.remoteNodes.values())r.info.status==="online"?t++:n++;let s=null;for(let r of this.remoteNodes.values())r.lastSyncAt>(s||0)&&(s=r.lastSyncAt);return {localAgentCount:e.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:e.length+this.remoteAgents.size,onlineNodeCount:t,offlineNodeCount:n,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(e){this.remoteNodes.set(e.id,{info:{id:e.id,name:e.id,address:e.address,port:e.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),h.info("Remote node added",{nodeId:e.id,address:e.address});}removeRemoteNode(e){this.remoteNodes.delete(e);for(let[t,n]of this.remoteAgents.entries())n.sourceGatewayId===e&&this.remoteAgents.delete(t);h.info("Remote node removed",{nodeId:e});}};var N=class{constructor(e){a$2(this,"log");a$2(this,"config");a$2(this,"ws",null);a$2(this,"state","disconnected");a$2(this,"subscriptions",new Map);a$2(this,"messageCallbacks",new Set);a$2(this,"agentListCallbacks",new Set);a$2(this,"cachedAgentList",[]);a$2(this,"localAgentList",[]);a$2(this,"reconnectAttempts",0);a$2(this,"reconnectTimer",null);a$2(this,"heartbeatTimer",null);a$2(this,"agentListRequestId",null);a$2(this,"agentListRequestResolve",null);this.config={url:e.url,type:e.type,id:e.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:e.reconnect?.enabled??true,maxAttempts:e.reconnect?.maxAttempts??5,delay:e.reconnect?.delay??3e3},heartbeat:{enabled:e.heartbeat?.enabled??true,interval:e.heartbeat?.interval??3e4}},this.log=a$1.create({service:`gateway:client:${this.config.id}`});}async connect(){if(this.state==="connected"||this.state==="connecting"){this.log.warn("already connected or connecting");return}return this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),new Promise((e,t)=>{try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{this.state="connected",this.reconnectAttempts=0,this.log.info("connected to gateway"),this.config.heartbeat.enabled&&this.startHeartbeat(),this.resubscribeAll(),e();},this.ws.onmessage=n=>{this.handleMessage(n.data);},this.ws.onclose=n=>{this.handleClose(n.code,n.reason);},this.ws.onerror=n=>{this.log.error("WebSocket error",{error:String(n)}),this.state==="connecting"&&t(new Error("Connection failed"));};}catch(n){this.state="disconnected",t(n);}})}async disconnect(){this.state!=="disconnected"&&(this.log.info("disconnecting from gateway"),this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"));}async subscribe(e,t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:e,backendSessionId:t,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:e,backendSessionId:t});}async unsubscribe(e){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:e,clientId:this.config.id}),this.subscriptions.delete(e),this.log.info("unsubscribed from session",{sessionId:e});}async send(e){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:e});}onMessage(e){this.messageCallbacks.add(e);}offMessage(e){this.messageCallbacks.delete(e);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(e){this.localAgentList=e,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((e,t)=>{let n=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=n,this.agentListRequestResolve=e,this.sendData({type:"agent_list_request",requestId:n}),setTimeout(()=>{this.agentListRequestId===n&&(this.agentListRequestId=null,this.agentListRequestResolve=null,t(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(e={}){let{localAgents:t,preferLocal:n=true,filterOffline:s=true}=e,r=t||this.localAgentList,i=this.cachedAgentList,o=this.mergeAgentLists(r,i,n);return s?o.filter(p=>p.status!=="offline"):o}onAgentListChange(e){this.agentListCallbacks.add(e);}offAgentListChange(e){this.agentListCallbacks.delete(e);}mergeAgentLists(e,t,n){let s=new Map,r=n?t:e,i=n?e:t;for(let o of r)s.set(o.id,o);for(let o of i)s.set(o.id,o);return Array.from(s.values())}updateMergedAgentList(){let e=this.getConnectableAgents({filterOffline:false});for(let t of this.agentListCallbacks)try{t(e);}catch(n){this.log.error("agent list callback error",{error:String(n)});}}handleAgentListResponse(e,t){t&&this.agentListRequestId===t&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(e),this.agentListRequestResolve=null),this.cachedAgentList=e,this.updateMergedAgentList(),this.log.debug("received agent list",{count:e.length});}sendData(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(e));}handleMessage(e){try{let t=JSON.parse(e);switch(t.type){case "message":this.handleGatewayMessage(t.message);break;case "subscribed":this.subscriptions.set(t.sessionId,t.subscription);break;case "unsubscribed":this.subscriptions.delete(t.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(t.agents||[],t.requestId);break;case "agent_update":this.handleAgentUpdate(t.agent,t.action);break;default:this.log.debug("unknown message type",{type:t.type});}}catch(t){this.log.error("failed to parse message",{error:String(t)});}}handleAgentUpdate(e,t){switch(t){case "add":case "update":{let n=this.cachedAgentList.findIndex(s=>s.id===e.id);n>=0?this.cachedAgentList[n]=e:this.cachedAgentList.push(e);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(n=>n.id!==e.id);break}this.updateMergedAgentList();}handleGatewayMessage(e){for(let t of this.messageCallbacks)try{t(e);}catch(n){this.log.error("message callback error",{error:String(n)});}}handleClose(e,t){this.log.info("connection closed",{code:e,reason:t}),this.state="disconnected",this.ws=null,this.stopHeartbeat(),this.config.reconnect.enabled&&this.scheduleReconnect();}scheduleReconnect(){if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){this.log.error("max reconnect attempts reached");return}this.reconnectAttempts++,this.state="reconnecting";let e=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:e}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(t){this.log.error("reconnect failed",{error:String(t)});}},e);}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.state==="connected"&&this.sendData({type:"ping"});},this.config.heartbeat.interval);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}async resubscribeAll(){for(let e of this.subscriptions.keys())try{await this.subscribe(e);}catch(t){this.log.error("failed to resubscribe",{sessionId:e,error:String(t)});}}getHttpUrl(){return this.config.url.replace(/^ws:/,"http:").replace(/^wss:/,"https:").replace(/\/$/,"")}async httpRequest(e,t={}){let n=`${this.getHttpUrl()}${e}`,s=t.method||"GET",{signal:r,...i}=t,o=await Fetch.request(n,{method:s,...i,headers:{"Content-Type":"application/json",...i.headers},...r?{signal:r}:{}});if(!o.ok){let p=o.data,G=typeof p=="object"?JSON.stringify(p):String(p||"Unknown error");throw new Error(`HTTP ${o.status}: ${G}`)}return o.data}async healthCheck(){return this.httpRequest("/health")}async getStatus(){return this.httpRequest("/status")}async listChannels(){return this.httpRequest("/channels")}async listContacts(e,t={}){let n=new URLSearchParams({platform:e,limit:String(t.limit??100),offset:String(t.offset??0)});return this.httpRequest(`/contacts?${n}`)}async getContact(e){return this.httpRequest(`/contacts/${encodeURIComponent(e)}`)}async getSession(e){return this.httpRequest(`/sessions/${encodeURIComponent(e)}`)}async createSession(e){return this.httpRequest("/session",{method:"POST",body:JSON.stringify(e??{})})}async getOrCreateSession(e){if(e.sessionId)try{return await this.getSession(e.sessionId),{sessionId:e.sessionId,created:!1}}catch{this.log.debug("session not found, will create new",{sessionId:e.sessionId});}if(e.platform||e.channel||e.userId){let n=e.chatId??e.userId;try{let i=await this.listSessions({platform:e.platform,channelId:e.channel,userId:e.userId,chatId:n});if(i.sessions.length>0){let o=i.sessions[0];if(o)return this.log.info("found existing session",{sessionId:o.id,channel:e.channel,userId:e.userId,chatId:n}),{sessionId:o.id,created:!1}}}catch(i){this.log.warn("failed to search sessions",{error:String(i)});}let s={channel:{platform:e.platform,channelId:e.channel,userId:e.userId,chatId:n}},r=await this.createSession(s);return this.log.info("session created",{sessionId:r.id,params:s}),{sessionId:r.id,created:true}}let t=await this.createSession({channel:{platform:"api",channelId:"default"}});return this.log.info("session created (default)",{sessionId:t.id}),{sessionId:t.id,created:true}}async listSessions(e={}){let t=new URLSearchParams;return t.set("limit",String(e.limit??100)),t.set("offset",String(e.offset??0)),e.platform&&t.set("platform",e.platform),e.channelId&&t.set("channelId",e.channelId),e.userId&&t.set("userId",e.userId),e.chatId&&t.set("chatId",e.chatId),this.httpRequest(`/sessions?${t}`)}async sendMessage(e,t){return this.httpRequest(`/session/${encodeURIComponent(e)}/prompt`,{method:"POST",body:JSON.stringify(t)})}};async function zt(c){let{Log:e}=await import('./chunks/log-MIT4H7S5.mjs'),t=false;await e.init({logDir:c.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:c.print??false,dev:c.dev??t,level:c.level??("INFO")});}
2
+ export{T as AgentRegistry,M as AgentSyncManager,x as Gateway,N as GatewayClient,zt as initLog};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/gateway",
3
- "version": "0.2.26",
3
+ "version": "0.2.28",
4
4
  "description": "EASBot Gateway - AI Agent Server and Multi-channel Integration Platform - 支持 WebSocket、HTTP、Discord、Telegram、Slack 等多渠道集成",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -67,10 +67,10 @@
67
67
  "ws": "^8.20.0",
68
68
  "xdg-basedir": "^5.1.0",
69
69
  "zod": "^4.4.3",
70
- "@easbot/plugin": "0.2.26",
71
- "@easbot/types": "0.2.26",
72
- "@easbot/sdk": "0.2.26",
73
- "@easbot/utils": "0.2.26"
70
+ "@easbot/plugin": "0.2.28",
71
+ "@easbot/sdk": "0.2.28",
72
+ "@easbot/types": "0.2.28",
73
+ "@easbot/utils": "0.2.28"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@biomejs/biome": "^2.4.14",
@@ -90,8 +90,8 @@
90
90
  "access": "public"
91
91
  },
92
92
  "scripts": {
93
- "dev": "cross-env NODE_ENV=development tsx src/cli.ts -- start",
94
- "start": "cross-env NODE_ENV=production node dist/cli.mjs start",
93
+ "dev": "tsup --watch --env.NODE_ENV development",
94
+ "start": "echo norun",
95
95
  "build": "tsup --env.NODE_ENV production",
96
96
  "test": "vitest",
97
97
  "test:run": "vitest run",
@@ -1,14 +0,0 @@
1
- import {a}from'./chunk-7OFQ65NG.mjs';import {a as a$2}from'./chunk-HAMGVOQD.mjs';import a$1 from'zod';import*as N from'path';import N__default from'path';import*as _ from'fs';import ___default,{existsSync}from'fs';import*as I from'fs/promises';import I__default from'fs/promises';import {createServer,Fetch}from'@easbot/utils';import {WebSocketServer}from'ws';import rs from'https';import os from'http';import {HookEvent}from'@easbot/plugin';var ne=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:lock"}));a$2(this,"config");a$2(this,"locks",new Map);a$2(this,"cleanupTimer",null);this.config={defaultTimeout:t.defaultTimeout??6e4,checkInterval:t.checkInterval??1e4};}tryAcquire(t,e,s,n){let i=this.locks.get(t);if(i)if(this.isLockExpired(i))this.log.warn("lock expired, releasing",{sessionId:t,oldHolder:i.holderId,newHolder:s}),this.locks.delete(t);else return this.log.debug("lock already held",{sessionId:t,holder:i.holderId,messageId:i.messageId}),false;let r={sessionId:t,messageId:e,holderId:s,acquiredAt:Date.now(),timeout:n??this.config.defaultTimeout};return this.locks.set(t,r),this.log.debug("lock acquired",{sessionId:t,messageId:e,subscriberId:s}),true}release(t,e){let s=this.locks.get(t);return s?s.holderId!==e?(this.log.warn("cannot release lock held by another",{sessionId:t,holder:s.holderId,requester:e}),false):(this.locks.delete(t),this.log.debug("lock released",{sessionId:t,subscriberId:e}),true):(this.log.debug("no lock to release",{sessionId:t}),false)}forceRelease(t){let e=this.locks.get(t);return e?(this.locks.delete(t),this.log.warn("lock force released",{sessionId:t,holder:e.holderId,messageId:e.messageId}),true):false}isLockExpired(t){return Date.now()-t.acquiredAt>t.timeout}getLock(t){return this.locks.get(t)}isLocked(t){let e=this.locks.get(t);return e?this.isLockExpired(e)?(this.locks.delete(t),false):true:false}getHolder(t){let e=this.locks.get(t);if(!(!e||this.isLockExpired(e)))return e.holderId}startCleanup(){this.cleanupTimer||(this.cleanupTimer=setInterval(()=>{this.cleanupExpired();},this.config.checkInterval),this.log.info("lock cleanup started",{interval:this.config.checkInterval}));}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null,this.log.info("lock cleanup stopped"));}cleanupExpired(){let t=0;for(let[e,s]of this.locks)this.isLockExpired(s)&&(this.locks.delete(e),t++,this.log.warn("expired lock cleaned up",{sessionId:e,holder:s.holderId,messageId:s.messageId}));return t>0&&this.log.info("cleaned up expired locks",{count:t}),t}getAllLocks(){return [...this.locks.values()]}getLockCount(){return this.locks.size}};var ie=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:retry"}));a$2(this,"policy");a$2(this,"retryQueue",new Map);a$2(this,"retryTimer",null);a$2(this,"handlers",new Map);this.policy={maxRetries:t.maxRetries??3,initialDelay:t.initialDelay??1e3,maxDelay:t.maxDelay??3e4,backoffMultiplier:t.backoffMultiplier??2};}registerHandler(t,e){this.handlers.set(t,e);}unregisterHandler(t){this.handlers.delete(t);}scheduleRetry(t,e){let s=t.id,n=this.retryQueue.get(s);if(n||(n={messageId:s,retryCount:0,nextRetryAt:0,errors:[]},this.retryQueue.set(s,n)),n.errors.push({error:e.message,timestamp:Date.now()}),n.retryCount>=this.policy.maxRetries)return this.log.error("max retries exceeded",{messageId:s,retryCount:n.retryCount,maxRetries:this.policy.maxRetries}),false;let i=Math.min(this.policy.initialDelay*this.policy.backoffMultiplier**n.retryCount,this.policy.maxDelay);return n.retryCount++,n.nextRetryAt=Date.now()+i,this.log.warn("retry scheduled",{messageId:s,retryCount:n.retryCount,delay:i,error:e.message}),true}getPendingRetries(){let t=Date.now(),e=[];for(let s of this.retryQueue.values())s.nextRetryAt<=t&&s.retryCount<=this.policy.maxRetries&&e.push(s);return e}async executeRetry(t){if(!this.handlers.get(t.messageId))return this.log.warn("no handler for retry",{messageId:t.messageId}),false;this.retryQueue.delete(t.messageId);try{return this.log.info("executing retry",{messageId:t.messageId,retryCount:t.retryCount}),!0}catch(s){return this.log.error("retry execution failed",{messageId:t.messageId,error:String(s)}),false}}clearRetry(t){this.retryQueue.delete(t),this.handlers.delete(t),this.log.debug("retry cleared",{messageId:t});}startProcessing(){this.retryTimer||(this.retryTimer=setInterval(async()=>{let t=this.getPendingRetries();for(let e of t)await this.executeRetry(e);},1e3),this.log.info("retry processing started"));}stopProcessing(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null,this.log.info("retry processing stopped"));}getStats(){let t=0;for(let e of this.retryQueue.values())t+=e.errors.length;return {pendingCount:this.retryQueue.size,totalErrors:t}}};function v(c,t,e,s){return {id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c,type:t,content:e,metadata:{channel:{platform:s?.channel?.platform??"api",channelId:s?.channel?.channelId??"default",userId:s?.channel?.userId,chatId:s?.channel?.chatId,...Object.fromEntries(Object.entries(s?.channel??{}).filter(([n])=>!["platform","channelId","userId","chatId"].includes(n)))},context:s?.context,agent:s?.agent},timestamp:Date.now()}}function at(c,t,e,s){return v(c,t,[{type:"text",text:e}],s)}function ke(c){let t=[c.platform,c.channelId];return c.chatId&&t.push(c.chatId),c.userId&&t.push(c.userId),t.join("_")}function Te(){return {status:"active",messageCount:0,lastMessageAt:null}}function re(c,t){if(!c||!t)throw new Error("platform and stableId are required");return `${c}:${t}`}function oe(c){if(!c||typeof c!="string")return null;let t=c.indexOf(":");if(t<=0||t>=c.length-1)return null;let e=c.slice(0,t),s=c.slice(t+1);return !e||!s?null:{platform:e,stableId:s}}function Ee(c){let{platform:t,stableId:e,profile:s={},aliases:n={},metadata:i}=c;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:re(t,e),platform:t,stableId:e,aliases:{...n},profile:{...s},createdAt:r,lastSeenAt:r,metadata:i}}function Re(c,t){return `sub_${c}_${t}`}var ct=a.create({service:"gateway:config"});a$1.enum(["telegram","slack","feishu","wechat","webchat","signal","nostr"]);a$1.enum(["low","medium","high","critical"]);var ce=a$1.object({enabled:a$1.boolean().default(true),botToken:a$1.string().describe("Telegram Bot Token"),webhookUrl:a$1.string().optional().describe("Webhook URL for receiving updates"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),le=a$1.object({enabled:a$1.boolean().default(true),botToken:a$1.string().describe("Slack Bot Token (xoxb-*)"),appToken:a$1.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:a$1.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),ge=a$1.object({enabled:a$1.boolean().default(true),appId:a$1.string().describe("Feishu App ID"),appSecret:a$1.string().describe("Feishu App Secret"),encryptKey:a$1.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:a$1.string().optional().describe("Feishu Verification Token"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),de=a$1.object({enabled:a$1.boolean().default(true),mode:a$1.enum(["official","wecom"]).default("official"),appId:a$1.string().describe("WeChat App ID"),appSecret:a$1.string().describe("WeChat App Secret"),token:a$1.string().optional().describe("WeChat Token for message verification"),encodingAESKey:a$1.string().optional().describe("WeChat Encoding AES Key"),agentId:a$1.string().optional().describe("WeCom Agent ID"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),ue=a$1.object({enabled:a$1.boolean().default(true),path:a$1.string().optional().default("/"),heartbeatInterval:a$1.number().int().positive().optional().default(3e4),connectionTimeout:a$1.number().int().positive().optional().default(6e4),maxConnections:a$1.number().int().positive().optional().default(1e3),cors:a$1.boolean().optional().default(true)}),he=a$1.object({enabled:a$1.boolean().default(true),serviceUrl:a$1.string().optional().default("https://chat.signal.org"),phoneNumber:a$1.string().describe("Signal phone number"),password:a$1.string().optional().describe("Signal account password"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),pe=a$1.object({enabled:a$1.boolean().default(true),relays:a$1.array(a$1.string()).min(1).describe("Nostr relay URLs"),privateKey:a$1.string().optional().describe("Nostr private key (hex)"),publicKey:a$1.string().optional().describe("Nostr public key (hex)"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),$e=a$1.object({telegram:ce.optional(),slack:le.optional(),feishu:ge.optional(),wechat:de.optional(),webchat:ue.optional(),signal:he.optional(),nostr:pe.optional()}),je=a$1.object({enabled:a$1.boolean().default(false),cert:a$1.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:a$1.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:a$1.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:a$1.string().optional().describe("Path to SSL key file (alias of key)"),ca:a$1.string().optional().describe("Path to CA certificate file"),forceRedirect:a$1.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:a$1.number().int().positive().optional().default(80).describe("HTTP redirect port")}),lt=a$1.object({name:a$1.string().describe("Token name/description"),value:a$1.string().describe("Token value"),permissions:a$1.array(a$1.string()).default(["*"]).describe("Associated permissions"),expiresAt:a$1.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:a$1.string().optional().describe("Token description")}),gt=a$1.object({enabled:a$1.boolean().default(true),tokens:a$1.array(lt).default([]).describe("List of valid tokens"),onInvalid:a$1.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:a$1.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:a$1.array(a$1.string()).default([]).describe("Default permissions for anonymous users")}),dt=a$1.object({enabled:a$1.boolean().default(false),authorizationServer:a$1.string().describe("OAuth2 authorization server URL"),clientId:a$1.string().describe("OAuth2 client ID"),clientSecret:a$1.string().describe("OAuth2 client secret"),tokenValidationEndpoint:a$1.string().describe("OAuth2 token validation endpoint"),scope:a$1.array(a$1.string()).default([]).describe("OAuth2 scopes")}),qe=a$1.object({type:a$1.enum(["token","oauth2"]).default("token"),token:gt.optional(),oauth2:dt.optional()}),Ke=a$1.object({mode:a$1.enum(["pull","push","both"]).default("both"),interval:a$1.number().int().positive().default(3e4),pushEvents:a$1.array(a$1.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:a$1.enum(["latest","local","remote"]).default("latest")}),ut=a$1.object({id:a$1.string().describe("Gateway node ID"),address:a$1.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:a$1.boolean().default(true),metadata:a$1.record(a$1.string(),a$1.any()).optional()}),Ve=a$1.object({nodeId:a$1.string().describe("Current gateway node ID"),nodes:a$1.array(ut).default([]).describe("Other gateway nodes in the cluster"),sync:Ke.optional()}),fe=a$1.object({maxConnectionsPerChannel:a$1.number().int().positive().default(100),idleTimeout:a$1.number().int().positive().default(3e5),reuseStrategy:a$1.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:a$1.number().int().positive().default(6e4),acquireTimeout:a$1.number().int().positive().default(5e3),warmupCount:a$1.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),me=a$1.object({maxLength:a$1.number().int().positive().default(1e4),concurrency:a$1.number().int().positive().default(100),batchSize:a$1.number().int().positive().default(10),batchTimeout:a$1.number().int().positive().default(100),priorityLevels:a$1.number().int().positive().default(4)}),ye=a$1.object({failureThreshold:a$1.number().int().positive().default(5),successThreshold:a$1.number().int().positive().default(3),timeout:a$1.number().int().positive().default(3e4),halfOpenDuration:a$1.number().int().positive().default(15e3)}),be=a$1.object({heartbeatInterval:a$1.number().int().positive().default(3e4),heartbeatTimeout:a$1.number().int().positive().default(9e4),heartbeatCheckInterval:a$1.number().int().positive().default(1e4),autoDeregisterTimeout:a$1.number().int().positive().default(3e5),maxAgents:a$1.number().int().positive().default(100),persistenceFile:a$1.string().optional().describe("Path to persist agent registrations"),maxRegistrations:a$1.number().int().positive().default(1e3)}),Ce=a$1.object({sessionTimeout:a$1.number().int().positive().default(18e5),resumeGracePeriod:a$1.number().int().positive().default(3e5),maxSessions:a$1.number().int().positive().default(1e4),persistenceFile:a$1.string().optional().describe("Path to persist sessions")}),Se=a$1.object({enabled:a$1.boolean().default(true),port:a$1.number().int().positive().default(8080),hostname:a$1.string().default("localhost"),path:a$1.string().optional().default("/"),maxConnections:a$1.number().int().positive().optional().default(1e3),connectionTimeout:a$1.number().int().positive().optional().default(6e4),heartbeatInterval:a$1.number().int().positive().optional().default(3e4),sessionExpireMs:a$1.number().int().positive().optional().default(3e5),https:je.optional(),auth:qe.optional(),cors:a$1.boolean().default(true),corsOrigins:a$1.array(a$1.string()).optional(),mdns:a$1.boolean().default(false),mdnsDomain:a$1.string().optional().default("gateway.easbot.local")}),ht=a$1.object({channel:a$1.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:a$1.array(a$1.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),ae=a$1.object({server:Se.optional(),channels:$e.optional(),cluster:Ve.optional(),connectionPool:fe.optional(),messageQueue:me.optional(),circuitBreaker:ye.optional(),agentRegistry:be.optional(),session:Ce.optional(),defaults:ht.optional(),defaultAgent:a$1.string().optional().describe("Default agent ID for routing"),logLevel:a$1.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(a$1.unknown());function _e(c){let t=ae.safeParse(c);return t.success||ct.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:ae.parse({})}function pt(c){return ae.parse(c)}var ft=a.create({service:"gateway:interfaces"}),P;function Ws(c){P=c,ft.debug("Agent adapter registered",{hasSubAgentRunner:!!c.subAgentRunner});}function Bs(){return P}function T(){return P!==void 0}function E(){if(!P)throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");return P}var mt={Path:{home:process.env.HOME||process.env.USERPROFILE||"",data:".easbot",cache:".easbot/cache",config:".easbot",state:".easbot/state",log:".easbot/log",bin:".easbot/bin"}},yt={directory:process.cwd(),worktree:process.cwd()};function O(){return P?P.global:mt}function Ne(){return P?P.instance:yt}var x=a.create({service:"gateway:config"}),ve={enabled:true,port:8080,hostname:"localhost",path:"",maxConnections:1e3,connectionTimeout:6e4,heartbeatInterval:3e4,sessionExpireMs:3e5,cors:true,mdns:false,mdnsDomain:"gateway.easbot.local",https:{enabled:false,cert:"",key:"",certPath:void 0,keyPath:void 0,ca:void 0,forceRedirect:false,httpPort:80}},St={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},vt={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},wt={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},It={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3},Pt={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e4},xt={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Mt={enabled:true,botToken:"",maxConnections:100,timeout:3e4},At={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},kt={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},Tt={enabled:true,path:"/ws",heartbeatInterval:3e4,connectionTimeout:6e4,maxConnections:1e3,cors:true},Et={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},Rt={enabled:true,relays:[],maxConnections:100,timeout:3e4},U,W=null;async function Ze(c){try{if(!existsSync(c))return null;let t=await I__default.readFile(c,"utf-8");t=t.replace(/\{env:([^}]+)\}/g,(r,l)=>{let g=process.env[l];return g===void 0?(x.debug("Environment variable not found",{varName:l,file:c}),""):g});let e=t,s=!1,n=!1,i=[];for(let r=0;r<t.length;r++){let l=t[r];if(n){i.push(l),n=!1;continue}if(l==="\\"){i.push(l),n=!0;continue}if(l==='"'){s=!s,i.push(l);continue}if(!s&&l==="/"&&t[r+1]==="/"){for(;r<t.length&&t[r]!==`
2
- `&&t[r]!=="\r";)r++;continue}if(!s&&l==="/"&&t[r+1]==="*"){for(r+=2;r<t.length-1;){if(t[r]==="*"&&t[r+1]==="/"){r+=2;break}r++;}continue}i.push(l);}return e=i.join("").trim(),e?JSON.parse(e):null}catch(t){return x.debug("Failed to load config file",{file:c,error:String(t)}),null}}function F(c,t){let e={...c,...t};return (c.server||t.server)&&(e.server={...c.server,...t.server}),(c.channels||t.channels)&&(e.channels={...c.channels,...t.channels}),e}async function _t(){let c=O(),t=Ne(),e=[],s=N__default.join(c.Path.config);e.push(s),e.push(t.directory);try{let{Filesystem:i}=await import('@easbot/utils'),r=await Array.fromAsync(i.up({targets:[".easbot"],start:t.directory,stop:t.worktree}));e.push(...r);}catch{x.debug("Filesystem utils not available, using basic directories");}let n=process.env.EASBOT_CONFIG_DIR;return n&&(e.push(n),x.debug("Using EASBOT_CONFIG_DIR",{path:n})),[...new Set(e)]}async function Nt(c){let t=["gateway.json"],e={};for(let s of t){let n=N__default.join(c,s),i=await Ze(n);if(i)if("gateway"in i&&i.gateway){let r=i.gateway;"server"in r||"channels"in r||"cluster"in r?e=F(e,r):e=F(e,{server:r}),x.debug("Loaded gateway config from file (nested format)",{file:n});}else "gateway"in i||(e=F(e,i),x.debug("Loaded gateway config from file (direct format)",{file:n}));}return e}async function Gt(c){let t=["easbot.json"];for(let e of t){let s=N__default.join(c,e),n=await Ze(s);if(n?.gateway)return x.debug("Loaded gateway config from easbot.json",{file:s}),n.gateway}return {}}function Dt(){return U||(U=async()=>{let c=await _t(),t={};for(let s of c){let n=await Nt(s);t=F(t,n);let i=await Gt(s);t=F(t,i);}let e=_e(t);return W=e,x.info("Gateway config loaded",{directories:c.length,port:e.server?.port,logLevel:e.logLevel}),{config:e,directories:c}}),U}async function w(){return Dt()()}async function Je(c){return c&&(U=void 0,W=null),(await w()).config}function Qe(){return W}function Xe(){return W!==null}function Lt(){U=void 0,W=null,x.debug("Config cache cleared");}function Ot(){return Ne().directory}async function Ut(){let{config:c}=await w();return Se.parse({...ve,...c.server})}async function Ft(c){let{config:t}=await w(),e=t.channels?.[c],n={telegram:ce.parse(xt),slack:le.parse(Mt),feishu:ge.parse(At),wechat:de.parse(kt),webchat:ue.parse(Tt),signal:he.parse(Et),nostr:pe.parse(Rt)}[c];if(!n)throw new Error(`Unknown channel type: ${c}`);return {...n,...e}}async function Wt(){let{config:c}=await w();return fe.parse({...St,...c.connectionPool})}async function Bt(){let{config:c}=await w();return me.parse({...vt,...c.messageQueue})}async function Ht(){let{config:c}=await w();return ye.parse({...wt,...c.circuitBreaker})}async function zt(){let{config:c}=await w();return be.parse({...It,...c.agentRegistry})}async function $t(){let{config:c}=await w();return Ce.parse({...Pt,...c.session})}async function jt(){let{config:c}=await w();return c.server?.https}async function qt(){let{config:c}=await w();return c.server?.auth}async function Kt(){let{config:c}=await w();return c.cluster}async function Vt(){let{config:c}=await w();return c.defaultAgent}async function Ye(){let{config:c}=await w();return c.logLevel??"INFO"}var De=ve,B={maxConnections:1e3,connectionTimeout:6e4,sessionExpireMs:3e5};var Jt={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var Qt={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3};var Xt={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};var Yt={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var M=class c extends Error{constructor(e,s){super(e);a$2(this,"code");a$2(this,"recoverable");a$2(this,"details");a$2(this,"cause");this.name="GatewayError",this.code=s.code,this.recoverable=s.recoverable,this.details=s.details,this.cause=s.cause,Error.captureStackTrace&&Error.captureStackTrace(this,c);}toJSON(){return {name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,details:this.details,cause:this.cause?.message,stack:this.stack}}static isRecoverable(e){if(e instanceof c)return e.recoverable;let s=e.code;return ["ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH"].includes(s??"")}};function R(c,t,e,s=true){return new M(e,{code:t,recoverable:s,details:{channelId:c}})}var we=class{constructor(){a$2(this,"log",a.create({service:"gateway:router"}));a$2(this,"subscribers",new Map);a$2(this,"subscriptions",new Map);a$2(this,"sessionSubscriptions",new Map);a$2(this,"channelPlugins",new Map);a$2(this,"lockManager");a$2(this,"retryManager");a$2(this,"cancelHandlers",new Set);this.lockManager=new ne,this.retryManager=new ie,this.lockManager.startCleanup();}onCancel(t){this.cancelHandlers.add(t);}offCancel(t){this.cancelHandlers.delete(t);}async emitCancel(t){for(let e of this.cancelHandlers)try{await e(t);}catch(s){this.log.error("cancel handler error",{error:String(s)});}}async route(t){this.log.debug("routing message",{id:t.id,sessionId:t.sessionId,type:t.type});let e=this.sessionSubscriptions.get(t.sessionId);if(!e||e.size===0)return this.log.debug("no subscribers for session",{sessionId:t.sessionId}),{success:true,broadcastCount:0,dispatchedToSubAgent:false};let s=0,n=null,i=[];for(let r of e){let l=this.subscriptions.get(r);if(!l)continue;let g=this.subscribers.get(l.subscriberId);if(g){if(t.type==="input"){if(!this.lockManager.tryAcquire(t.sessionId,t.id,g.id)){this.log.debug("skipping subscriber, lock held by another",{subscriberId:g.id,holder:this.lockManager.getHolder(t.sessionId)});continue}n=g.id;}try{await g.connection.send(t),s++,g.lastActiveAt=Date.now();}catch(d){this.log.warn("failed to send message to subscriber",{subscriberId:g.id,error:String(d)}),i.push(d instanceof Error?d:new Error(String(d))),n===g.id&&(this.lockManager.release(t.sessionId,g.id),n=null);}}}return this.log.debug("message routed",{id:t.id,broadcastCount:s,errorCount:i.length,processedBy:n}),{success:i.length===0,broadcastCount:s,dispatchedToSubAgent:false,error:i.length>0?i.map(r=>r.message).join("; "):void 0}}async completeMessage(t,e,s,n="completed"){this.lockManager.release(t,s),await this.emitCancel({sessionId:t,messageId:e,processedBy:s,reason:n,timestamp:Date.now()}),this.log.info("message completed",{sessionId:t,messageId:e,subscriberId:s,reason:n});}scheduleRetry(t,e){return this.retryManager.scheduleRetry(t,e)}async subscribe(t,e){let s=Re(e.id,t);if(this.subscriptions.has(s))return this.log.debug("already subscribed",{subscriberId:e.id,sessionId:t}),this.subscriptions.get(s);let n={id:s,subscriberId:e.id,sessionId:t,createdAt:Date.now()};return this.subscribers.has(e.id)||this.subscribers.set(e.id,e),this.subscriptions.set(s,n),this.sessionSubscriptions.has(t)||this.sessionSubscriptions.set(t,new Set),this.sessionSubscriptions.get(t).add(s),e.sessions.add(t),this.log.info("subscribed to session",{subscriberId:e.id,sessionId:t,subscriptionId:s}),n}async unsubscribe(t){let e=this.subscriptions.get(t);if(!e){this.log.warn("subscription not found",{subscriptionId:t});return}this.subscriptions.delete(t);let s=this.sessionSubscriptions.get(e.sessionId);s&&(s.delete(t),s.size===0&&this.sessionSubscriptions.delete(e.sessionId));let n=this.subscribers.get(e.subscriberId);n&&n.sessions.delete(e.sessionId),this.log.info("unsubscribed from session",{subscriberId:e.subscriberId,sessionId:e.sessionId,subscriptionId:t});}async unsubscribeAll(t){let e=this.subscribers.get(t);if(!e)return;let s=[...e.sessions];for(let n of s){let i=this.sessionSubscriptions.get(n);if(i)for(let r of i)this.subscriptions.get(r)?.subscriberId===t&&await this.unsubscribe(r);}this.subscribers.delete(t),this.log.info("all subscriptions removed for subscriber",{subscriberId:t});}registerChannel(t){this.channelPlugins.set(t.id,t),this.log.info("channel plugin registered",{id:t.id,platform:t.platform});}unregisterChannel(t){this.channelPlugins.delete(t),this.log.info("channel plugin unregistered",{id:t});}getSubscriber(t){return this.subscribers.get(t)}getSubscription(t){return this.subscriptions.get(t)}getSubscriberCount(t){return this.sessionSubscriptions.get(t)?.size??0}getStats(){return {subscribers:this.subscribers.size,subscriptions:this.subscriptions.size,sessions:this.sessionSubscriptions.size}}async shutdown(){this.lockManager.stopCleanup(),this.subscribers.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.channelPlugins.clear(),this.cancelHandlers.clear(),this.log.info("router shutdown");}};var H=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:message-store"}));a$2(this,"config");a$2(this,"messages",new Map);a$2(this,"sessionMessages",new Map);a$2(this,"cleanupTimer",null);a$2(this,"accessOrder",[]);a$2(this,"storagePath");a$2(this,"dirty",false);this.config={storagePath:t.storagePath??"./data/gateway-messages",maxRetentionDays:t.maxRetentionDays??7,maxRecords:t.maxRecords??5e4,cleanupIntervalMs:t.cleanupIntervalMs??36e5,cleanupBatchSize:t.cleanupBatchSize??1e3,lruEnabled:t.lruEnabled??true,lruMaxMemory:t.lruMaxMemory??0},this.storagePath=this.config.storagePath,this.ensureDir(this.storagePath),this.startCleanupTimer();}async ensureDir(t){try{await I.mkdir(t,{recursive:!0});}catch(e){e.code!=="EEXIST"&&this.log.warn("failed to create storage directory",{dirPath:t,error:String(e)});}}getMessageFilePath(t){return N.join(this.storagePath,`${this.sanitizeFileName(t)}.json`)}getSessionDir(t){return N.join(this.storagePath,"sessions",this.sanitizeFileName(t))}sanitizeFileName(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}startCleanupTimer(){this.cleanupTimer||(this.cleanupTimer=setInterval(()=>{this.performCleanup().catch(t=>{this.log.error("Cleanup error",{error:String(t)});});},this.config.cleanupIntervalMs),this.cleanupTimer.unref?.(),this.log.info("Cleanup timer started",{intervalMs:this.config.cleanupIntervalMs}));}performCleanup(){return new Promise(t=>{let e=this.cleanup();this.log.info("Periodic cleanup completed",{deleted:e}),t();})}async store(t){this.messages.size>=this.config.maxRecords&&this.evictLRU(1e3),this.config.lruEnabled&&this.updateAccessOrder(t.id);let e={message:t,status:"pending",processedBy:null,processedAt:null,retryCount:0,error:null,createdAt:Date.now(),updatedAt:Date.now()};return this.messages.set(t.id,e),this.sessionMessages.has(t.sessionId)||this.sessionMessages.set(t.sessionId,new Set),this.sessionMessages.get(t.sessionId).add(t.id),this.dirty=true,await this.saveMessageToFile(e),this.log.debug("message stored",{id:t.id,sessionId:t.sessionId,type:t.type,total:this.messages.size}),e}async saveMessageToFile(t){try{let e=this.getSessionDir(t.message.sessionId);await this.ensureDir(e);let s=N.join(e,`${this.sanitizeFileName(t.message.id)}.json`);await I.writeFile(s,JSON.stringify(t,null,2),"utf-8");}catch(e){this.log.warn("failed to save message to file",{messageId:t.message.id,error:String(e)});}}get(t){let e=this.messages.get(t);return e&&this.config.lruEnabled&&this.updateAccessOrder(t),e}async updateStatus(t,e,s={}){let n=this.messages.get(t);if(!n){this.log.warn("message not found for status update",{messageId:t});return}n.status=e,n.updatedAt=Date.now(),s.processedBy&&(n.processedBy=s.processedBy),(e==="completed"||e==="failed")&&(n.processedAt=Date.now()),s.error&&(n.error=s.error),this.dirty=true,await this.saveMessageToFile(n),this.log.debug("message status updated",{id:t,status:e,processedBy:s.processedBy});}async incrementRetry(t){let e=this.messages.get(t);return e?(e.retryCount++,e.updatedAt=Date.now(),this.dirty=true,await this.saveMessageToFile(e),e.retryCount):0}isProcessed(t){let e=this.messages.get(t);return e?e.status==="completed"||e.status==="processing":false}getSessionHistory(t,e=100){let s=this.sessionMessages.get(t);if(!s)return [];let n=[];for(let i of s){let r=this.messages.get(i);r&&n.push(r);}return n.sort((i,r)=>i.createdAt-r.createdAt),n.slice(-e)}getPendingMessages(t){let e=[];for(let s of this.messages.values())s.status==="pending"&&(!t||s.message.sessionId===t)&&e.push(s);return e}getFailedMessages(t=3){let e=[];for(let s of this.messages.values())s.status==="failed"&&s.retryCount<t&&e.push(s);return e}cleanup(){let t=Date.now(),e=this.config.maxRetentionDays*24*60*60*1e3,s=[];for(let[n,i]of this.messages)if((t-i.createdAt>e||i.status==="completed")&&(s.push(n),s.length>=this.config.cleanupBatchSize))break;for(let n of s)this.deleteMessage(n);return s.length>0&&this.log.info("cleanup completed",{deleted:s.length,remaining:this.messages.size}),s.length}evictLRU(t){if(!this.config.lruEnabled||this.accessOrder.length===0)return;let e=0;for(;e<t&&this.accessOrder.length>0;){let s=this.accessOrder.shift();s&&(this.deleteMessage(s),e++);}this.log.info("LRU eviction completed",{evicted:e,remaining:this.messages.size});}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e>-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t);}deleteMessage(t){let e=this.messages.get(t);if(e){let s=this.sessionMessages.get(e.message.sessionId);s&&(s.delete(t),s.size===0&&this.sessionMessages.delete(e.message.sessionId)),this.messages.delete(t);let n=this.accessOrder.indexOf(t);n>-1&&this.accessOrder.splice(n,1);}}getStats(){let t={total:this.messages.size,pending:0,processing:0,completed:0,failed:0,cancelled:0,sessions:this.sessionMessages.size};for(let e of this.messages.values())t[e.status]++;return t}async close(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.messages.clear(),this.sessionMessages.clear(),this.accessOrder=[],this.log.info("MessageStore closed");}};var z=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:session-store"}));a$2(this,"config");a$2(this,"sessions",new Map);a$2(this,"channelSessions",new Map);a$2(this,"autoSaveTimer",null);a$2(this,"isDirty",false);this.config={storagePath:t.storagePath??"./data/gateway-sessions",autoSaveInterval:t.autoSaveInterval??6e4,maxRetentionDays:t.maxRetentionDays??7,enablePersistence:t.enablePersistence??true};}async initialize(){if(!this.config.enablePersistence){this.log.info("session persistence disabled");return}await this.ensureStorageDir(),await this.load(),this.startAutoSave(),this.log.info("session store initialized",{sessionCount:this.sessions.size,storagePath:this.config.storagePath});}async close(){this.stopAutoSave(),this.isDirty&&await this.save(),this.log.info("session store closed");}async set(t){this.sessions.set(t.id,t),this.channelSessions.has(t.channel.channelId)||this.channelSessions.set(t.channel.channelId,new Set),this.channelSessions.get(t.channel.channelId).add(t.id),this.markDirty(),await this.save();}get(t){return this.sessions.get(t)}async delete(t){let e=this.sessions.get(t);if(!e)return;this.sessions.delete(t);let s=this.channelSessions.get(e.channel.channelId);s&&(s.delete(t),s.size===0&&this.channelSessions.delete(e.channel.channelId)),this.markDirty(),await this.save();}getAll(){return [...this.sessions.values()]}getByChannel(t){let e=this.channelSessions.get(t);return e?[...e].map(s=>this.sessions.get(s)).filter(s=>s!==void 0):[]}size(){return this.sessions.size}markDirty(){this.isDirty=true;}async save(){if(!this.config.enablePersistence)return;let t=this.getSessionFilePath(),e=this.serializeAll();try{await this.ensureStorageDir(),await _.promises.writeFile(t,JSON.stringify(e,null,2),"utf-8"),this.isDirty=!1,this.log.debug("sessions saved",{count:e.length});}catch(s){throw this.log.error("failed to save sessions",{error:s}),s}}async load(){if(!this.config.enablePersistence)return;let t=this.getSessionFilePath();try{if(!_.existsSync(t)){this.log.debug("no saved sessions found");return}let e=await _.promises.readFile(t,"utf-8"),s=JSON.parse(e);this.sessions.clear(),this.channelSessions.clear();let n=Date.now(),i=this.config.maxRetentionDays*24*60*60*1e3;for(let r of s){if(n-r.lastActiveAt>i)continue;let l={id:r.id,channel:r.channel,backendSessionId:r.backendSessionId,subscribers:new Set(r.subscribers),state:r.state,createdAt:r.createdAt,lastActiveAt:r.lastActiveAt};this.sessions.set(l.id,l),this.channelSessions.has(l.channel.channelId)||this.channelSessions.set(l.channel.channelId,new Set),this.channelSessions.get(l.channel.channelId).add(l.id);}this.log.info("sessions loaded",{loaded:this.sessions.size,skipped:s.length-this.sessions.size});}catch(e){this.log.error("failed to load sessions",{error:e});}}serializeAll(){let t=[];for(let e of this.sessions.values())t.push(this.serialize(e));return t}serialize(t){return {id:t.id,channel:t.channel,backendSessionId:t.backendSessionId,subscribers:[...t.subscribers],state:t.state,createdAt:t.createdAt,lastActiveAt:t.lastActiveAt}}getSessionFilePath(){return N.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){_.existsSync(this.config.storagePath)||await _.promises.mkdir(this.config.storagePath,{recursive:true});}startAutoSave(){this.autoSaveTimer||(this.autoSaveTimer=setInterval(async()=>{this.isDirty&&await this.save();},this.config.autoSaveInterval));}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null);}async cleanup(){let t=Date.now(),e=this.config.maxRetentionDays*24*60*60*1e3,s=[];for(let n of this.sessions.values())t-n.lastActiveAt>e&&s.push(n.id);for(let n of s)await this.delete(n);return s.length>0&&(this.log.info("cleaned up expired sessions",{count:s.length}),await this.save()),s.length}getStats(){let t={total:this.sessions.size,byStatus:{active:0,idle:0,closed:0},byPlatform:{}};for(let e of this.sessions.values()){t.byStatus[e.state.status]++;let s=e.channel.platform;t.byPlatform[s]=(t.byPlatform[s]||0)+1;}return t}};var Zt="./data/gateway",es="contacts",ts="index.json",$=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:contact-store"}));a$2(this,"baseDir");a$2(this,"contactDir");a$2(this,"indexPath");a$2(this,"index");a$2(this,"indexFileMap");a$2(this,"dirty",false);a$2(this,"saveTimer",null);a$2(this,"SAVE_DEBOUNCE_MS",1e3);this.baseDir=t.baseDir??Zt,this.contactDir=N.join(this.baseDir,es),this.indexPath=N.join(this.contactDir,ts),this.index={byUid:{},byUsername:{},byEmail:{},byPhone:{},byPlatform:{},updatedAt:0},this.indexFileMap={};}async initialize(){await this.ensureDir(this.contactDir),await this.loadIndex(),this.log.info("contact store initialized",{baseDir:this.baseDir,contactCount:Object.keys(this.index.byUid).length});}async ensureDir(t){try{await I.mkdir(t,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async loadIndex(){try{let t=await I.readFile(this.indexPath,"utf-8");this.index=JSON.parse(t),await this.rebuildFileMap();}catch(t){t.code!=="ENOENT"&&this.log.warn("failed to load contact index, starting fresh",{error:String(t)}),this.index={byUid:{},byUsername:{},byEmail:{},byPhone:{},byPlatform:{},updatedAt:0};}}async saveIndex(){this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=setTimeout(async()=>{await this.doSaveIndex();},this.SAVE_DEBOUNCE_MS);}async doSaveIndex(){try{this.index.updatedAt=Date.now(),await I.writeFile(this.indexPath,JSON.stringify(this.index,null,2),"utf-8"),this.dirty=!1;}catch(t){this.log.error("failed to save contact index",{error:String(t)});}}async rebuildFileMap(){this.indexFileMap={};for(let t of Object.keys(this.index.byUid)){let e=oe(t);if(e){let s=this.getFilePath(e.platform,e.stableId);this.indexFileMap[t]=s;}}}getFilePath(t,e){let s=this.sanitizeFilename(e);return N.join(this.contactDir,t,`${s}.json`)}sanitizeFilename(t){return t.replace(/[/\\:*?"<>|]/g,"_")}getPlatformDir(t){return N.join(this.contactDir,t)}async save(t){let{platform:e,stableId:s,uid:n}=t,i=this.getFilePath(e,s);return await this.ensureDir(N.dirname(i)),await I.writeFile(i,JSON.stringify(t,null,2),"utf-8"),this.index.byUid[n]=i,this.indexFileMap[n]=i,this.index.byPlatform[e]||(this.index.byPlatform[e]=[]),this.index.byPlatform[e].includes(n)||this.index.byPlatform[e].push(n),this.updateSearchIndices(t),this.dirty=true,await this.saveIndex(),this.log.debug("contact saved",{uid:n,platform:e,stableId:s}),t}async create(t){let e=Ee(t);return this.save(e)}async getOrCreate(t,e,s){let n=await this.findByPlatformId(t,e);return n||this.create({platform:t,stableId:e,profile:s})}async findByUid(t){let e=oe(t);return e?this.findByPlatformId(e.platform,e.stableId):null}async findByPlatformId(t,e){let s=re(t,e),n=this.index.byUid[s];if(n)try{let r=await I.readFile(n,"utf-8");return JSON.parse(r)}catch(r){r.code!=="ENOENT"&&this.log.warn("failed to read contact file",{uid:s,filePath:n,error:String(r)}),delete this.index.byUid[s],this.dirty=true;}let i=this.getFilePath(t,e);try{let r=await I.readFile(i,"utf-8"),l=JSON.parse(r);return this.index.byUid[s]=i,this.indexFileMap[s]=i,this.dirty=!0,await this.saveIndex(),l}catch{return null}}async update(t,e){let s=await this.findByUid(t);if(!s)return null;let n={...s,profile:e.profile?{...s.profile,...e.profile}:s.profile,aliases:e.aliases?{...s.aliases,...e.aliases}:s.aliases,metadata:e.metadata?{...s.metadata,...e.metadata}:s.metadata,lastSeenAt:Date.now()};return this.save(n)}async touch(t){let e=await this.findByUid(t);e&&(e.lastSeenAt=Date.now(),await this.save(e));}async delete(t){let e=await this.findByUid(t);if(!e)return false;let{platform:s,stableId:n}=e,i=this.index.byUid[t]||this.getFilePath(s,n);try{await I.unlink(i);}catch(r){r.code!=="ENOENT"&&this.log.warn("failed to delete contact file",{uid:t,filePath:i,error:String(r)});}return delete this.index.byUid[t],delete this.indexFileMap[t],this.index.byPlatform[s]&&(this.index.byPlatform[s]=this.index.byPlatform[s].filter(r=>r!==t)),this.removeFromSearchIndices(e),this.dirty=true,await this.saveIndex(),this.log.debug("contact deleted",{uid:t}),true}async listByPlatform(t,e=100,s=0){let n=this.index.byPlatform[t]||[],i=n.length,r=n.slice(s,s+e),l=[];for(let g of r){let d=await this.findByUid(g);d&&l.push(d);}return {contacts:l,total:i,hasMore:s+e<i}}async findByUsername(t){let e=t.toLowerCase(),s=this.index.byUsername[e];return s?this.findByUid(s):null}async findByEmail(t){let e=t.toLowerCase(),s=this.index.byEmail[e];return s?this.findByUid(s):null}async findByPhone(t){let e=t.replace(/\s/g,""),s=this.index.byPhone[e];return s?this.findByUid(s):null}async search(t){if(t.platform){let g=await this.listByPlatform(t.platform,t.limit,t.offset),d=g.contacts;if(t.username){let y=t.username.toLowerCase();d=d.filter(b=>b.profile.username?.toLowerCase().includes(y));}if(t.email){let y=t.email.toLowerCase();d=d.filter(b=>b.profile.email?.toLowerCase().includes(y));}if(t.phone){let y=t.phone.replace(/\s/g,"");d=d.filter(b=>b.profile.phone?.replace(/\s/g,"").includes(y));}return {contacts:d,total:g.total,hasMore:g.hasMore}}let e=[];for(let g of Object.keys(this.index.byPlatform)){let d=await this.listByPlatform(g,1e3,0);e.push(...d.contacts);}let s=e;if(t.username){let g=t.username.toLowerCase();s=s.filter(d=>d.profile.username?.toLowerCase().includes(g));}if(t.email){let g=t.email.toLowerCase();s=s.filter(d=>d.profile.email?.toLowerCase().includes(g));}if(t.phone){let g=t.phone.replace(/\s/g,"");s=s.filter(d=>d.profile.phone?.replace(/\s/g,"").includes(g));}let n=s.length,i=t.limit??100,r=t.offset??0;return {contacts:s.slice(r,r+i),total:n,hasMore:r+i<n}}async count(t){return t?(this.index.byPlatform[t]||[]).length:Object.keys(this.index.byUid).length}async exists(t){return await this.findByUid(t)!==null}async addAlias(t,e,s){let n=await this.findByUid(t);if(!n)return null;let i={...n,aliases:{...n.aliases,[e]:{...n.aliases[e],...s}},lastSeenAt:Date.now()};return this.save(i)}async close(){this.saveTimer&&clearTimeout(this.saveTimer),this.dirty&&await this.doSaveIndex(),this.log.info("contact store closed");}updateSearchIndices(t){let{uid:e,profile:s}=t;s.username&&(this.index.byUsername[s.username.toLowerCase()]=e),s.email&&(this.index.byEmail[s.email.toLowerCase()]=e),s.phone&&(this.index.byPhone[s.phone.replace(/\s/g,"")]=e);}removeFromSearchIndices(t){let{uid:e,profile:s}=t;if(s.username){let n=s.username.toLowerCase();this.index.byUsername[n]===e&&delete this.index.byUsername[n];}if(s.email){let n=s.email.toLowerCase();this.index.byEmail[n]===e&&delete this.index.byEmail[n];}if(s.phone){let n=s.phone.replace(/\s/g,"");this.index.byPhone[n]===e&&delete this.index.byPhone[n];}}};var Le=class{constructor(t){a$2(this,"cache",new Map);a$2(this,"maxSize");this.maxSize=t;}get(t){let e=this.cache.get(t);return e!==void 0&&(this.cache.delete(t),this.cache.set(t,e)),e}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s);}this.cache.set(t,e);}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear();}get size(){return this.cache.size}},j=class{constructor(t,e={}){a$2(this,"store",t);a$2(this,"cache");a$2(this,"usernameIndex");a$2(this,"emailIndex");a$2(this,"phoneIndex");a$2(this,"platformIndex");a$2(this,"initialized",false);this.cache=new Le(e.cacheSize??1e3),this.usernameIndex=new Map,this.emailIndex=new Map,this.phoneIndex=new Map,this.platformIndex=new Map;}async initialize(){this.initialized||("initialize"in this.store&&typeof this.store.initialize=="function"&&await this.store.initialize(),await this.warmCache(),this.initialized=true);}async warmCache(){try{let t=["telegram","discord","slack","feishu","wechat","webchat","signal","nostr"];for(let e of t)try{let s=await this.store.listByPlatform(e,1e3,0);for(let n of s.contacts)this.cacheContact(n);}catch{}}catch{}}cacheContact(t){let{uid:e,profile:s}=t;this.cache.set(e,t),s.username&&this.usernameIndex.set(s.username.toLowerCase(),e),s.email&&this.emailIndex.set(s.email.toLowerCase(),e),s.phone&&this.phoneIndex.set(s.phone.replace(/\s/g,""),e),this.platformIndex.has(t.platform)||this.platformIndex.set(t.platform,new Set),this.platformIndex.get(t.platform).add(e);}invalidateContact(t){let{uid:e,profile:s}=t;if(this.cache.delete(e),s.username){let i=s.username.toLowerCase();this.usernameIndex.get(i)===e&&this.usernameIndex.delete(i);}if(s.email){let i=s.email.toLowerCase();this.emailIndex.get(i)===e&&this.emailIndex.delete(i);}if(s.phone){let i=s.phone.replace(/\s/g,"");this.phoneIndex.get(i)===e&&this.phoneIndex.delete(i);}let n=this.platformIndex.get(t.platform);n&&n.delete(e);}async save(t){this.invalidateContact(t);let e=await this.store.save(t);return this.cacheContact(e),e}async create(t){let e=await this.store.create(t);return this.cacheContact(e),e}async getOrCreate(t,e,s){let n=this.cache.get(`${t}:${e}`);if(n)return n;let i=await this.store.getOrCreate(t,e,s);return this.cacheContact(i),i}async findByUid(t){let e=this.cache.get(t);if(e)return e;let s=await this.store.findByUid(t);return s&&this.cacheContact(s),s}async findByPlatformId(t,e){return this.findByUid(`${t}:${e}`)}async update(t,e){let s=await this.cache.get(t);s&&this.invalidateContact(s);let n=await this.store.update(t,e);return n&&this.cacheContact(n),n}async touch(t){await this.store.touch(t);}async delete(t){let e=await this.cache.get(t);return e&&this.invalidateContact(e),this.store.delete(t)}async listByPlatform(t,e=100,s=0){return this.store.listByPlatform(t,e,s)}async findByUsername(t){let e=t.toLowerCase(),s=this.usernameIndex.get(e);return s?this.findByUid(s):this.store.findByUsername(t)}async findByEmail(t){let e=t.toLowerCase(),s=this.emailIndex.get(e);return s?this.findByUid(s):this.store.findByEmail(t)}async findByPhone(t){let e=t.replace(/\s/g,""),s=this.phoneIndex.get(e);return s?this.findByUid(s):this.store.findByPhone(t)}async search(t){return this.store.search(t)}async count(t){return t?this.platformIndex.get(t)?.size??0:this.cache.size}async exists(t){return this.cache.has(t)?true:this.store.exists(t)}async addAlias(t,e,s){let n=await this.store.addAlias(t,e,s);return n&&(this.invalidateContact(n),this.cacheContact(n)),n}async close(){this.cache.clear(),this.usernameIndex.clear(),this.emailIndex.clear(),this.phoneIndex.clear(),this.platformIndex.clear(),"close"in this.store&&typeof this.store.close=="function"&&await this.store.close();}};var q=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:session"}));a$2(this,"sessionStore");a$2(this,"config");a$2(this,"initialized",false);this.config={enablePersistence:t.enablePersistence??true,storagePath:t.storagePath??"./data/gateway-sessions",autoSaveInterval:t.autoSaveInterval??6e4,maxRetentionDays:t.maxRetentionDays??7},this.sessionStore=new z({storagePath:this.config.storagePath,autoSaveInterval:this.config.autoSaveInterval,maxRetentionDays:this.config.maxRetentionDays,enablePersistence:this.config.enablePersistence});}async initialize(){this.initialized||(await this.sessionStore.initialize(),this.initialized=true,this.log.info("session manager initialized",{sessionCount:this.sessionStore.size(),persistenceEnabled:this.config.enablePersistence}));}async close(){await this.sessionStore.close(),this.log.info("session manager closed");}async getOrCreate(t,e={}){let s=ke(t),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),this.log.debug("session found",{sessionId:s}),n):(n={id:s,channel:t,backendSessionId:null,subscribers:new Set,state:Te(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(n),this.log.info("session created",{sessionId:s,platform:t.platform,channelId:t.channelId,chatId:t.chatId,userId:t.userId}),n)}get(t){return this.sessionStore.get(t)}async closeSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.state.status="closed",await this.sessionStore.delete(t),this.log.info("session closed",{sessionId:t});}async closeById(t){return this.closeSession(t)}async bindBackendSession(t,e){let s=this.sessionStore.get(t);if(!s)throw new Error(`Session not found: ${t}`);s.backendSessionId=e,await this.sessionStore.set(s),this.log.info("backend session bound",{gatewaySessionId:t,backendSessionId:e});}async unbindBackendSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.backendSessionId=null,await this.sessionStore.set(e),this.log.info("backend session unbound",{gatewaySessionId:t});}getState(t){return this.sessionStore.get(t)?.state}async incrementMessageCountOrCreate(t,e){let s=this.sessionStore.get(t);if(!s){let n=e??{platform:"api",channelId:"default"};s=await this.getOrCreate(n);}return s.state.messageCount++,s.state.lastMessageAt=Date.now(),s.lastActiveAt=Date.now(),await this.sessionStore.set(s),s}async incrementMessageCount(t){let e=this.sessionStore.get(t);e&&(e.state.messageCount++,e.state.lastMessageAt=Date.now(),e.lastActiveAt=Date.now(),await this.sessionStore.set(e));}async addSubscriber(t,e){let s=this.sessionStore.get(t);if(!s){this.log.warn("session not found",{sessionId:t});return}s.subscribers.add(e),await this.sessionStore.set(s),this.log.debug("subscriber added to session",{sessionId:t,subscriberId:e});}async removeSubscriber(t,e){let s=this.sessionStore.get(t);s&&(s.subscribers.delete(e),await this.sessionStore.set(s),this.log.debug("subscriber removed from session",{sessionId:t,subscriberId:e}));}query(t){let e=this.sessionStore.getAll();return t.platform&&(e=e.filter(s=>s.channel.platform===t.platform)),t.channelId&&(e=e.filter(s=>s.channel.channelId===t.channelId)),t.userId&&(e=e.filter(s=>s.channel.userId===t.userId)),t.status&&(e=e.filter(s=>s.state.status===t.status)),e}getSessionsByChannel(t){return this.sessionStore.getByChannel(t)}getAllSessions(){return this.sessionStore.getAll()}getSessionCount(){return this.sessionStore.size()}async cleanupIdleSessions(t){let e=Date.now(),s=[];for(let n of this.sessionStore.getAll())n.state.status==="idle"&&e-n.lastActiveAt>t&&s.push(n.id);for(let n of s)await this.closeSession(n);return s.length>0&&this.log.info("cleaned up idle sessions",{count:s.length}),s.length}async save(){this.log.debug("session save triggered");}getStats(){return this.sessionStore.getStats()}};var K=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:plugin-loader"}));a$2(this,"plugins",new Map);a$2(this,"messageHandler",null);a$2(this,"healthCheckTimer",null);a$2(this,"config");a$2(this,"backoffPolicy");this.config={pluginDir:t.pluginDir??"./plugins",autoDiscover:t.autoDiscover??false,healthCheckInterval:t.healthCheckInterval??6e4,healthCheckTimeout:t.healthCheckTimeout??5e3,autoReconnect:t.autoReconnect??true,maxReconnectAttempts:t.maxReconnectAttempts??10,reconnectInitialDelay:t.reconnectInitialDelay??5e3,reconnectMaxDelay:t.reconnectMaxDelay??3e5},this.backoffPolicy={initialMs:this.config.reconnectInitialDelay,maxMs:this.config.reconnectMaxDelay,factor:2,jitter:.1};}setMessageHandler(t){this.messageHandler=t;}async register(t,e){if(this.plugins.has(t.id)){this.log.warn("plugin already registered",{id:t.id});return}this.plugins.set(t.id,{plugin:t,config:e,started:false,reconnectAttempts:0}),this.log.info("plugin registered",{id:t.id,platform:t.platform,name:t.name});}async unregister(t){let e=this.plugins.get(t);if(!e){this.log.warn("plugin not found",{id:t});return}this.cancelReconnect(t),e.started&&await this.stop(t),this.plugins.delete(t),this.log.info("plugin unregistered",{id:t});}async start(t){let e=this.plugins.get(t);if(!e)throw new M(`Plugin not found: ${t}`,{code:"PLUGIN_NOT_FOUND",recoverable:false});if(e.started){this.log.warn("plugin already started",{id:t});return}if(!this.messageHandler)throw new M("Message handler not set",{code:"PLUGIN_ERROR",recoverable:false});if(!e.config.enabled){this.log.warn("plugin is disabled",{id:t});return}this.log.info("starting plugin",{id:t});try{await e.plugin.start(e.config,this.messageHandler),e.started=!0,e.reconnectAttempts=0,this.log.info("plugin started",{id:t});}catch(s){throw this.log.error("failed to start plugin",{id:t,error:String(s)}),this.scheduleReconnect(t),s}}async stop(t){let e=this.plugins.get(t);if(!e){this.log.warn("plugin not found",{id:t});return}if(!e.started){this.log.warn("plugin not started",{id:t});return}this.cancelReconnect(t),this.log.info("stopping plugin",{id:t});try{await e.plugin.stop(),e.started=!1,this.log.info("plugin stopped",{id:t});}catch(s){e.started=false,this.log.error("failed to stop plugin",{id:t,error:String(s)});}}async startAll(){let t=[];for(let[e,s]of this.plugins){if(!s.config.enabled){this.log.debug("skipping disabled plugin",{id:e});continue}try{await this.start(e);}catch(n){t.push({id:e,error:n instanceof Error?n:new Error(String(n))});}}t.length>0&&this.log.warn("some plugins failed to start",{count:t.length,errors:t.map(e=>({id:e.id,error:e.error.message}))});}async stopAll(){this.stopHealthCheckTimer();for(let[t]of this.plugins)await this.stop(t);}getPlugin(t){return this.plugins.get(t)?.plugin}getAllPlugins(){return [...this.plugins.values()].map(t=>t.plugin)}getRunningPlugins(){return [...this.plugins.values()].filter(t=>t.started).map(t=>t.plugin)}isRunning(t){return this.plugins.get(t)?.started??false}async healthCheck(t){let e=this.plugins.get(t);if(!e)return {healthy:false,lastCheck:Date.now(),error:"Plugin not found"};if(!e.started)return {healthy:false,lastCheck:Date.now(),error:"Plugin not running"};try{let s=await Promise.race([e.plugin.healthCheck(),new Promise((n,i)=>setTimeout(()=>i(new Error("Health check timeout")),this.config.healthCheckTimeout))]);return e.lastHealthCheck=s,s}catch(s){let n={healthy:false,lastCheck:Date.now(),error:s instanceof Error?s.message:String(s)};return e.lastHealthCheck=n,n}}async healthCheckAll(){let t=new Map;for(let[e]of this.plugins)t.set(e,await this.healthCheck(e));return t}startHealthCheckTimer(){this.healthCheckTimer||(this.healthCheckTimer=setInterval(async()=>{for(let[t,e]of this.plugins){if(!e.started)continue;let s=await this.healthCheck(t);s.healthy||(this.log.warn("plugin health check failed",{id:t,error:s.error}),this.config.autoReconnect&&(e.started=false,this.scheduleReconnect(t)));}},this.config.healthCheckInterval),this.log.info("health check timer started",{interval:this.config.healthCheckInterval}));}stopHealthCheckTimer(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null,this.log.info("health check timer stopped"));}scheduleReconnect(t){if(!this.config.autoReconnect)return;let e=this.plugins.get(t);if(!e)return;if(e.reconnectAttempts>=this.config.maxReconnectAttempts){this.log.error("max reconnect attempts reached",{id:t,attempts:e.reconnectAttempts});return}let s=this.calculateBackoffDelay(e.reconnectAttempts);e.reconnectAttempts++,this.log.info("scheduling reconnect",{id:t,attempt:e.reconnectAttempts,delay:s}),e.reconnectTimer=setTimeout(async()=>{try{await this.start(t),this.log.info("reconnect successful",{id:t});}catch(n){this.log.warn("reconnect failed",{id:t,error:String(n)}),this.scheduleReconnect(t);}},s),e.reconnectTimer.unref?.();}cancelReconnect(t){let e=this.plugins.get(t);e&&e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0);}calculateBackoffDelay(t){let e=Math.min(this.backoffPolicy.initialMs*this.backoffPolicy.factor**t,this.backoffPolicy.maxMs),s=e*this.backoffPolicy.jitter*(Math.random()*2-1);return Math.floor(e+s)}};var A=class extends Error{constructor(e,s,n){super(e);a$2(this,"code",s);a$2(this,"configuredChannels",n);this.name="ChannelSelectionError";}},V=a.create({service:"gateway:channel-selection"});function D(c){if(!(!c||typeof c!="string"))return c.toLowerCase().trim()}async function Ue(c){let{channel:t,sessionId:e,userId:s,defaultChannel:n,fallbackChannels:i,sessionManager:r,pluginLoader:l,contactStore:g}=c,d=D(t);if(d){let f=Oe(d,l);if(f){if(s&&g){let S=await ss(d,s,g,l);if(S)return S}return f}if(e){let S=st(e,r);if(S)return V.debug("explicit channel unavailable, using session-bound channel as fallback",{explicitChannel:d,sessionChannel:S.channel}),S}throw new A(`Channel \u4E0D\u53EF\u7528\u6216\u672A\u914D\u7F6E: ${d}`,"CHANNEL_UNAVAILABLE",[])}if(e){let f=st(e,r);if(f)return f}if(s&&g){let f=await ns(s,g,l);if(f)return f}let y=Fe(l);if(y.length===0)throw new A("\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684 Channel\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F\u3002\u8BF7\u81F3\u5C11\u914D\u7F6E\u4E00\u4E2A Channel\u3002","NO_CHANNEL",[]);let b=D(n);if(b){let f=Oe(b,l);if(f)return V.debug("using default channel",{channel:b}),{...f,source:"default"};V.warn("default channel unavailable",{channel:b});}if(y.length===1){let f=y[0],S=l?.getPlugin(f);return {channel:f,source:"single-configured",channelInfo:{platform:S?.platform??"api",channelId:f}}}let k=(i??[]).map(D).filter(f=>f!==void 0);for(let f of k){let S=Oe(f,l);if(S)return V.debug("using fallback channel",{channel:f}),{...S,source:"fallback"};V.debug("fallback channel unavailable, trying next",{channel:f});}throw b?new A(`\u914D\u7F6E\u7684\u9ED8\u8BA4 Channel \u4E0D\u53EF\u7528: ${b}`,"CHANNEL_UNAVAILABLE",y):new A(`\u9700\u8981\u660E\u786E\u6307\u5B9A Channel\uFF08\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF09: ${y.join(", ")}\u3002\u8BF7\u901A\u8FC7 channel \u53C2\u6570\u6307\u5B9A\u8981\u4F7F\u7528\u7684 Channel\uFF0C\u6216\u5728 gateway.json \u4E2D\u914D\u7F6E defaults.channel\u3002`,"MULTIPLE_CHANNELS",y)}function Oe(c,t){if(!t)return null;let e=t.getPlugin(c);if(e&&t.isRunning(c))return {channel:c,source:"explicit",channelInfo:{platform:e.platform,channelId:c}};let s=D(c);if(!s)return null;let n=t.getAllPlugins();for(let i of n)if(t.isRunning(i.id)&&D(i.platform)===s)return {channel:i.id,source:"explicit",channelInfo:{platform:i.platform,channelId:i.id}};return null}function st(c,t){if(!t)return null;let e=t.get(c);return e?{channel:e.channel.channelId,source:"session-bound",channelInfo:e.channel}:null}async function ss(c,t,e,s){let n=s?.getPlugin(c);if(!n)return null;let i=await e.findByPlatformId(n.platform,t);return i?{channel:c,source:"explicit",channelInfo:{platform:n.platform,channelId:c,userId:i.stableId,chatId:i.stableId}}:null}async function ns(c,t,e){let s=Fe(e);if(s.length===0)return null;for(let n of s){let i=e?.getPlugin(n);if(!i)continue;let r=await t.findByPlatformId(i.platform,c);if(r)return {channel:n,source:"single-configured",channelInfo:{platform:i.platform,channelId:n,userId:r.stableId,chatId:r.stableId}}}return null}function Fe(c){if(!c)return [];let t=[],e=c.getAllPlugins();for(let s of e)c.isRunning(s.id)&&t.push(s.id);return t}function We(c){switch(c.code){case "NO_CHANNEL":return "\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684 Channel\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F\u3002\u8BF7\u5728 gateway.json \u4E2D\u914D\u7F6E\u81F3\u5C11\u4E00\u4E2A Channel\u3002";case "MULTIPLE_CHANNELS":return `\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF0C\u9700\u8981\u660E\u786E\u6307\u5B9A: ${c.configuredChannels?.join(", ")||""}\u3002\u8BF7\u901A\u8FC7 channel \u53C2\u6570\u6307\u5B9A\u8981\u4F7F\u7528\u7684 Channel\uFF0C\u6216\u5728 gateway.json \u4E2D\u914D\u7F6E defaults.channel \u4F5C\u4E3A\u9ED8\u8BA4\u503C\u3002`;case "CHANNEL_UNAVAILABLE":return c.message;case "UNKNOWN_CHANNEL":return `\u672A\u77E5\u7684 Channel: ${c.message}\u3002\u8BF7\u68C0\u67E5 Channel ID \u662F\u5426\u6B63\u786E\u3002`;default:return c.message}}var u=a.create({service:"gateway:websocket-server"});function as(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xe(c,t){for(let[e,s]of t.entries())if(s===c)return e;return null}var G=class{constructor(t={}){a$2(this,"config");a$2(this,"server",null);a$2(this,"wss",null);a$2(this,"httpsServer",null);a$2(this,"httpRedirectServer",null);a$2(this,"connections",new Map);a$2(this,"subscriptions",new Map);a$2(this,"sessionSubscriptions",new Map);a$2(this,"sessionLastActivity",new Map);a$2(this,"cleanupInterval",null);a$2(this,"heartbeatInterval",null);a$2(this,"startTime",0);a$2(this,"running",false);a$2(this,"channelResolveParams",null);a$2(this,"messageSender",null);a$2(this,"pluginLoaderRef",null);this.config={...De,...t};}setChannelResolveDeps(t){this.channelResolveParams=t,u.debug("channel resolve deps set",{hasSessionManager:!!t.sessionManager,hasPluginLoader:!!t.pluginLoader,hasContactStore:!!t.contactStore});}setMessageSender(t){this.messageSender=t,u.debug("message sender set",{hasSender:!!t});}setPluginLoader(t){this.pluginLoaderRef=t;}getChannelResolveParams(){return this.channelResolveParams?this.channelResolveParams:{}}async start(){if(this.running){u.warn("WebSocket server is already running");return}u.debug("WebSocket server start: checking configuration",{port:this.config.port,hostname:this.config.hostname,path:this.config.path,https:this.config.https?.enabled??false}),this.startTime=Date.now();let t={onOpen:(n,i)=>{this.handleConnection(i);},onMessage:async(n,i)=>{try{let r=JSON.parse(n.data.toString());await this.handleMessage(i,r);}catch(r){u.error("Error processing WebSocket message",{error:r.message}),this.sendError(i,r.message);}},onClose:(n,i)=>{this.handleDisconnection(i);},onError:(n,i)=>{u.error("WebSocket error",{error:n.type});}},e=this.config.https?.enabled??false;u.debug("WebSocket server start: choosing server type",{https:e});try{e?(u.debug("WebSocket server start: starting HTTPS server"),await this.startHTTPSServer(t)):(u.debug("WebSocket server start: starting HTTP server"),await this.startHTTPServer(t)),u.debug("WebSocket server start: HTTP/HTTPS server started successfully");}catch(n){throw u.error("WebSocket server start: HTTP/HTTPS server failed",{error:n instanceof Error?n.message:String(n)}),n}u.debug("WebSocket server start: server initialization complete"),this.cleanupInterval=setInterval(()=>this.cleanupExpiredSessions(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let s=e?"wss":"ws";u.info("WebSocket server started",{url:`${s}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(t){u.debug("HTTP server start: creating server",{port:this.config.port,hostname:this.config.hostname}),this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true}),u.debug("HTTP server start: server created, checking raw server");let e=this.server.raw;e?(u.debug("HTTP server start: raw server available, setting up WebSocket upgrade"),this.setupWebSocketUpgrade(e,t),u.debug("HTTP server start: WebSocket upgrade configured")):u.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(t){let e=this.config.https,s=this.loadSSLCertificates(e);if(!s){u.error("Failed to load SSL certificates, falling back to HTTP"),await this.startHTTPServer(t);return}this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let n=this.server.raw;this.httpsServer=rs.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,t),await new Promise(i=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{u.info("HTTPS server started",{port:this.config.port,hostname:this.config.hostname}),i();});}),e.forceRedirect&&e.httpPort&&this.startHTTPRedirectServer(e.httpPort);}loadSSLCertificates(t){try{return t.cert&&t.key?{cert:t.cert,key:t.key}:t.certPath&&t.keyPath?{cert:___default.readFileSync(t.certPath),key:___default.readFileSync(t.keyPath)}:null}catch(e){return u.error("Failed to load SSL certificates",{error:e.message}),null}}setupWebSocketUpgrade(t,e){this.wss=new WebSocketServer({noServer:true}),t.on("upgrade",(s,n,i)=>{try{let l=new URL(s.url||"/",`http://${s.headers.host}`).pathname,g=this.config.path||"";(l===g||g===""&&(l==="/"||l===""))&&this.wss.handleUpgrade(s,n,i,d=>{e.onOpen?.({type:"open"},d),d.on("message",y=>{e.onMessage?.({data:y},d);}),d.on("close",(y,b)=>{e.onClose?.({code:y,reason:b},d);}),d.on("error",y=>{e.onError?.({type:"error",message:y.message},d);});});}catch{}});}startHTTPRedirectServer(t){this.httpRedirectServer=os.createServer((e,s)=>{let i=`https://${e.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${e.url}`;u.debug("Redirecting HTTP to HTTPS",{from:e.url,to:i}),s.writeHead(301,{Location:i,"Content-Type":"text/plain"}),s.end(`Redirecting to ${i}`);}),this.httpRedirectServer.listen(t,this.config.hostname,()=>{u.info("HTTP redirect server started",{port:t,hostname:this.config.hostname});});}async stop(){if(!this.running){u.warn("WebSocket server is not running");return}u.info("Stopping WebSocket server"),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let[t,e]of this.connections.entries())try{e.close(1e3,"Server shutting down");}catch(s){u.debug("Error closing connection",{clientId:t,error:String(s)});}this.connections.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.sessionLastActivity.clear(),this.wss&&(this.wss.close(),this.wss=null),this.httpsServer&&(await new Promise(t=>{this.httpsServer.close(()=>t());}),this.httpsServer=null),this.httpRedirectServer&&(await new Promise(t=>{this.httpRedirectServer.close(()=>t());}),this.httpRedirectServer=null),this.server&&(await this.server.stop(),this.server=null),this.running=false,u.info("WebSocket server stopped");}broadcastToSession(t,e){this.touchSession(t);let s=this.sessionSubscriptions.get(t);if(!s||s.size===0){u.debug("No clients subscribed to session",{sessionId:t});return}let n=e?.properties?.sessionID;if(typeof n=="string"&&n&&n!==t)return;let i=JSON.stringify({type:"event",sessionId:t,payload:e});for(let r of s){let l=this.subscriptions.get(r);if(l&&l.ws.readyState===l.ws.OPEN&&l.subscribedSessions.has(t)){if(l.subscribedEventTypes.size>0&&!l.subscribedEventTypes.has(e.type)){u.debug("Event type not subscribed, skipping",{clientId:r,sessionId:t,eventType:e.type,subscribedTypes:Array.from(l.subscribedEventTypes)});continue}l.ws.send(i),u.debug("Event pushed to client",{clientId:r,sessionId:t,eventType:e.type});}}}getConnectionCount(){return this.connections.size}getSubscriptionCount(){return this.sessionSubscriptions.size}getConnectionInfos(){let t=[];for(let[e,s]of this.subscriptions.entries())t.push({clientId:e,state:s.ws.readyState===s.ws.OPEN?"connected":"disconnected",connectedAt:s.connectedAt,lastActivityAt:s.lastActivityAt,authInfo:s.authInfo});return t}isRunning(){return this.running}handleConnection(t){if(this.connections.size>=(this.config.maxConnections??B.maxConnections)){u.warn("Maximum connections reached, rejecting new connection"),t.close(1013,"Maximum connections reached");return}let e=as();this.connections.set(e,t),this.subscriptions.set(e,{clientId:e,ws:t,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()}),u.info("WebSocket client connected",{clientId:e,totalConnections:this.connections.size}),this.sendMessage(t,{type:"connected",clientId:e,payload:{version:"1.0.0",capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}handleDisconnection(t){let e=xe(t,this.connections);if(!e)return;this.connections.delete(e);let s=this.subscriptions.get(e);if(s){for(let n of s.subscribedSessions){let i=this.sessionSubscriptions.get(n);i&&(i.delete(e),i.size===0&&this.sessionSubscriptions.delete(n));}this.subscriptions.delete(e);}u.info("WebSocket client disconnected",{clientId:e,totalConnections:this.connections.size});}async handleMessage(t,e){let s=xe(t,this.connections);if(!s){this.sendError(t,"Client not found");return}let n=this.subscriptions.get(s);switch(n&&(n.lastActivityAt=Date.now()),e.type){case "ping":this.sendMessage(t,{type:"pong"});break;case "initialize":await this.handleInitialize(t,e);break;case "subscribe":await this.handleSubscribe(t,e);break;case "unsubscribe":await this.handleUnsubscribe(t,e);break;case "message":await this.handleMessageRequest(t,e);break;case "interrupt":await this.handleInterrupt(t,e);break;case "releaseSubscription":await this.handleReleaseSubscription(t,e);break;default:this.sendError(t,`Unknown message type: ${e.type}`);}}async handleInitialize(t,e){this.sendMessage(t,{type:"initialize_response",success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}async handleSubscribe(t,e){if(e.type!=="subscribe"||!e.sessionId){this.sendError(t,"Invalid subscribe request");return}let s=xe(t,this.connections);if(!s){this.sendError(t,"Client not found");return}let n=this.subscriptions.get(s);if(!n){this.sendError(t,"Subscription not found");return}n.subscribedSessions.add(e.sessionId),this.sessionSubscriptions.has(e.sessionId)||this.sessionSubscriptions.set(e.sessionId,new Set),this.sessionSubscriptions.get(e.sessionId).add(s);let i=e;if(i.backendSessionId){let r=this.getChannelResolveParams();if(r.sessionManager)try{await r.sessionManager.bindBackendSession(i.sessionId,i.backendSessionId),u.info("backend session bound on subscribe",{gatewaySessionId:i.sessionId,backendSessionId:i.backendSessionId});}catch(l){u.warn("failed to bind backend session on subscribe",{sessionId:i.sessionId,backendSessionId:i.backendSessionId,error:String(l)});}}if(this.touchSession(e.sessionId),e.payload?.eventTypes)for(let r of e.payload.eventTypes)n.subscribedEventTypes.add(r);u.info("Client subscribed to session",{clientId:s,sessionId:e.sessionId,backendSessionId:i.backendSessionId}),this.sendMessage(t,{type:"subscribed",sessionId:e.sessionId});}async handleUnsubscribe(t,e){if(e.type!=="unsubscribe"||!e.sessionId){this.sendError(t,"Invalid unsubscribe request");return}let s=xe(t,this.connections);if(!s)return;let n=this.subscriptions.get(s);if(!n)return;n.subscribedSessions.delete(e.sessionId);let i=this.sessionSubscriptions.get(e.sessionId);i&&(i.delete(s),i.size===0&&this.sessionSubscriptions.delete(e.sessionId)),u.info("Client unsubscribed from session",{clientId:s,sessionId:e.sessionId}),this.sendMessage(t,{type:"unsubscribed",sessionId:e.sessionId});}async handleMessageRequest(t,e){if(e.type!=="message"||!e.sessionId||!e.payload){this.sendError(t,"Invalid message request");return}u.debug("Message received",{sessionId:e.sessionId}),this.sendMessage(t,{type:"response",sessionId:e.sessionId,success:true,result:{received:true}});}async handleInterrupt(t,e){if(e.type!=="interrupt"||!e.sessionId){this.sendError(t,"Invalid interrupt request");return}u.info("Interrupt requested via WebSocket",{sessionId:e.sessionId}),this.sendMessage(t,{type:"interrupted",sessionId:e.sessionId,success:true});}async handleReleaseSubscription(t,e){if(e.type!=="releaseSubscription"||!e.sessionId){this.sendError(t,"Invalid releaseSubscription request");return}u.info("Release subscription requested via WebSocket",{sessionId:e.sessionId}),this.releaseSessionResources(e.sessionId),this.sendMessage(t,{type:"subscriptionReleased",sessionId:e.sessionId});}touchSession(t){this.sessionLastActivity.set(t,Date.now());}checkConnectionTimeout(){let t=Date.now(),e=this.config.connectionTimeout??B.connectionTimeout,s=[];for(let[n,i]of this.subscriptions.entries())t-i.lastActivityAt>e&&s.push(n);for(let n of s){let i=this.subscriptions.get(n);if(i){u.info("Closing inactive connection",{clientId:n,lastActivityAt:i.lastActivityAt,timeoutMs:e});try{i.ws.close(1001,"Connection timeout");}catch(r){u.debug("Error closing timed out connection",{clientId:n,error:String(r)});}}}s.length>0&&u.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size-s.length});}cleanupExpiredSessions(){let t=Date.now(),e=[],s=this.config.sessionExpireMs??B.sessionExpireMs;for(let[n,i]of this.sessionLastActivity.entries())t-i>s&&e.push(n);for(let n of e)u.info("Session expired due to inactivity, releasing resources",{sessionId:n,lastActivity:this.sessionLastActivity.get(n),expireMs:s}),this.releaseSessionResources(n),this.sessionLastActivity.delete(n);e.length>0&&u.debug("Cleaned up expired sessions",{count:e.length,remainingActive:this.sessionLastActivity.size});}releaseSessionResources(t){let e=this.sessionSubscriptions.get(t);if(e){for(let s of e){let n=this.subscriptions.get(s);n&&n.ws.readyState===n.ws.OPEN&&this.sendMessage(n.ws,{type:"session_closed",sessionId:t,payload:{reason:"Session resources released due to expiration or explicit release"}});}for(let s of e){let n=this.subscriptions.get(s);n&&n.subscribedSessions.delete(t);}this.sessionSubscriptions.delete(t),u.info("Session resources released",{sessionId:t,clientCount:e.size});}}sendMessage(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e));}sendError(t,e,s){this.sendMessage(t,{type:"error",message:e,code:s});}createRoutes(){return [{method:"get",path:"/health",handler:t=>{let e={status:"healthy",timestamp:Date.now(),version:"1.0.0"};return t.json(e)}},{method:"get",path:"/status",handler:t=>{let e={status:this.running?"running":"stopped",connections:this.connections.size,sessions:this.sessionSubscriptions.size,subscriptions:this.subscriptions.size,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0"};return t.json(e)}},{method:"get",path:"/channels",handler:async t=>{let e=this.channelResolveParams?.pluginLoader;if(!e)return t.json({error:"Plugin loader not available"},503);let n=e.getAllPlugins().map(i=>({id:i.id,platform:i.platform,name:i.name,version:i.version}));return t.json({channels:n,total:n.length})}},{method:"get",path:"/contacts",handler:async t=>{let e=t.req.query("platform"),s=parseInt(t.req.query("limit")||"100",10),n=parseInt(t.req.query("offset")||"0",10),i=this.channelResolveParams?.contactStore;if(!i)return t.json({error:"Contact store not available"},503);try{if(e){let r=await i.listByPlatform(e,s,n);return t.json({contacts:r.contacts.map(l=>({uid:l.uid,platform:l.platform,stableId:l.stableId,profile:l.profile,lastSeenAt:l.lastSeenAt,createdAt:l.createdAt})),total:r.total,hasMore:r.hasMore})}else {let r=await i.count();return t.json({total:r,message:"Specify platform query parameter to list contacts"})}}catch(r){return u.error("failed to list contacts",{error:String(r)}),t.json({error:String(r)},500)}}},{method:"get",path:"/contacts/:uid",handler:async t=>{let e=t.req.param("uid"),s=this.channelResolveParams?.contactStore;if(!s)return t.json({error:"Contact store not available"},503);try{let n=await s.findByUid(e);return n?t.json({uid:n.uid,platform:n.platform,stableId:n.stableId,profile:n.profile,aliases:n.aliases,lastSeenAt:n.lastSeenAt,createdAt:n.createdAt}):t.json({error:"Contact not found"},404)}catch(n){return u.error("failed to get contact",{uid:e,error:String(n)}),t.json({error:String(n)},500)}}},{method:"get",path:"/sessions",handler:async t=>{let e=parseInt(t.req.query("limit")||"100",10),s=parseInt(t.req.query("offset")||"0",10),n=t.req.query("platform"),i=t.req.query("channelId"),r=t.req.query("userId"),l=[];for(let[d,y]of this.sessionSubscriptions){let b=d.split("_"),k=b[0],f=b[1],S=b[b.length-1];(!n||k===n)&&(!i||f===i)&&(!r||S===r)&&l.push({id:d,platform:k,channelId:f,userId:S,state:"active",createdAt:this.sessionLastActivity.get(d)||Date.now(),lastActiveAt:this.sessionLastActivity.get(d)||Date.now()});}let g=l.slice(s,s+e);return t.json({sessions:g,total:l.length,hasMore:s+e<l.length})}},{method:"get",path:"/sessions/:sessionId",handler:async t=>{let e=t.req.param("sessionId"),s=this.sessionSubscriptions.get(e);return s?t.json({id:e,state:"active",subscriberCount:s.size,lastActiveAt:this.sessionLastActivity.get(e)||Date.now()}):t.json({error:"Session not found"},404)}},{method:"post",path:"/initialize",handler:async t=>{let e=await t.req.json().catch(()=>({}));return u.debug("ACP initialize request received",{body:e}),t.json({success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"],version:"1.0.0"}})}},{method:"post",path:"/session",handler:async t=>{await t.req.json().catch(()=>({}));let n={id:`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,createdAt:Date.now()};return t.json(n)}},{method:"post",path:"/session/:sessionId/prompt",handler:async t=>{let e=t.req.param("sessionId"),s=await t.req.json().catch(()=>({}));if(!e)return t.json({error:"No sessionId provided"},400);try{let n=this.getChannelResolveParams(),i=await Ue({...n,sessionId:e,channel:s.channel,userId:s.userId});u.debug("channel resolved for message",{sessionId:e,channel:i.channel,source:i.source,channelInfo:i.channelInfo});let r=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,l={...i.channelInfo};s.userId&&!l.chatId&&(l.chatId=s.userId,l.userId=s.userId);let g={id:r,sessionId:e,type:"output",content:typeof s.content=="string"?[{type:"text",text:s.content}]:s.content||[],metadata:{channel:l,replyToMessageId:s.replyToMessageId},timestamp:Date.now()};if(this.server)await this.server.sendToChannel(i.channel,g,{replyToMessageId:s.replyToMessageId}),u.debug("message sent via server.sendToChannel",{messageId:r,channel:i.channel});else if(this.pluginLoaderRef)try{await this.pluginLoaderRef.send(i.channel,g),u.debug("message sent via pluginLoader",{messageId:r,channel:i.channel});}catch(y){return u.error("failed to send message",{sessionId:e,error:String(y)}),t.json({error:String(y)},500)}let d={messageId:r,sessionId:e,createdAt:Date.now(),metadata:{channel:i.channel,channelSource:i.source,channelInfo:i.channelInfo}};return t.status(202),t.json(d)}catch(n){return n instanceof A?(u.warn("channel selection failed",{sessionId:e,error:n.message}),t.json({error:We(n),code:n.code},400)):(u.error("send message error",{sessionId:e,error:String(n)}),t.json({error:String(n)},500))}}},{method:"get",path:"/subscriptions",handler:t=>{let e=Array.from(this.sessionSubscriptions.entries()).map(([n,i])=>({sessionId:n,subscriberCount:i.size,subscribers:Array.from(i)})),s={subscriptions:e,total:e.length};return t.json(s)}}]}};var C=class{constructor(){a$2(this,"version","1.0.0");a$2(this,"log");a$2(this,"config",null);a$2(this,"messageHandler",null);a$2(this,"_status","stopped");a$2(this,"lastActivity",0);a$2(this,"startPromise",null);a$2(this,"stopPromise",null);}initLog(){this.log=a.create({service:`channel:${this.platform}`});}async start(t,e){if(this.startPromise)return this.log.warn("plugin start already in progress"),this.startPromise;if(this._status==="running"){this.log.warn("plugin is already running");return}this.startPromise=this.doStartInternal(t,e);try{await this.startPromise;}finally{this.startPromise=null;}}async doStartInternal(t,e){this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=t,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(s){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(s)}),s}}async stop(){if(this.stopPromise)return this.log.warn("plugin stop already in progress"),this.stopPromise;if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}this.stopPromise=this.doStopInternal();try{await this.stopPromise;}finally{this.stopPromise=null;}}async doStopInternal(){this.log.info("stopping channel plugin",{id:this.id}),this._status="stopping";try{await this.doStop(),this._status="stopped",this.log.info("channel plugin stopped",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(t)}),t}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(t){return {healthy:false,lastCheck:Date.now(),error:t instanceof Error?t.message:String(t)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}extractText(t){return t.content.filter(e=>e.type==="text").map(e=>e.text??"").join(`
3
- `)}buildSessionId(t,e,s){let n=[this.platform,t,e];return s&&n.push(s),n.join("_")}async handleMessage(t){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:t.id});return}this.updateActivity(),await this.messageHandler.onMessage(t);}async handleEvent(t,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:t});return}await this.messageHandler.onEvent({type:t,channelId:this.id,data:e,timestamp:Date.now()});}};var J=class extends C{constructor(e="telegram-main"){super();a$2(this,"id");a$2(this,"platform","telegram");a$2(this,"name","Telegram Bot");a$2(this,"botConfig",null);a$2(this,"baseUrl","");a$2(this,"abortController",null);a$2(this,"lastUpdateId",0);a$2(this,"typingTimers",new Map);a$2(this,"commandRouter",new Map);a$2(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});this.id=e,this.initLog();}async doStart(){if(!this.config)throw R(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw R(this.id,"CONFIG_MISSING_REQUIRED","Bot token is required");if(this.baseUrl=`https://api.telegram.org/bot${this.botConfig.botToken}`,this.botConfig.retry&&(this.retryState={attempts:0,maxAttempts:this.botConfig.retry.maxAttempts??3,initialDelay:this.botConfig.retry.initialDelay??1e3,maxDelay:this.botConfig.retry.maxDelay??3e4}),this.botConfig.commands)for(let s of this.botConfig.commands)this.commandRouter.set(`/${s.command}`,s);let e=await this.getMe();this.log.info("Telegram bot connected",{id:e.id,username:e.username,first_name:e.first_name}),this.botConfig.polling?.enabled!==false&&this.startPolling();}async doStop(){this.abortController?.abort(),this.abortController=null,this.clearAllTyping(),this.commandRouter.clear(),this.botConfig=null,this.log.info("Telegram plugin stopped");}async send(e){let s=e.metadata.channel.chatId;if(!s)throw R(this.id,"MESSAGE_SEND_FAILED","Chat ID is required");let n=this.detectParseMode(e),i=e.metadata.context?.replyTo;return this.sendApiMessage(s,this.extractText(e),{parseMode:n,replyTo:i?parseInt(i,10):void 0})}async sendTyping(e){await this.sendChatAction(e,"typing");}async sendChatAction(e,s){await this.request("sendChatAction",{chat_id:e,action:s}),this.scheduleTypingStop(e,5e3);}scheduleTypingStop(e,s){let n=this.typingTimers.get(e);n&&clearTimeout(n);let i=setTimeout(()=>{this.typingTimers.delete(e);},s);this.typingTimers.set(e,i);}clearAllTyping(){for(let e of this.typingTimers.values())clearTimeout(e);this.typingTimers.clear();}detectParseMode(e){let s=this.extractText(e);return s.includes("<")&&s.includes("</")?"HTML":s.includes("*")||s.includes("_")||s.includes("`")?"Markdown":"None"}startPolling(){this.abortController=new AbortController,this.pollLoop(),this.log.info("Polling started");}pollLoop(){(async()=>{try{await this.poll(),this.abortController?.signal.aborted||this.pollLoop();}catch(s){this.handlePollingError(s);}})();}async poll(){let e=this.botConfig?.polling?.timeout??0,s=await this.getUpdates(this.lastUpdateId+1,100,e);for(let n of s)this.lastUpdateId=Math.max(this.lastUpdateId,n.update_id),n.message&&await this.handleTelegramMessage(n.message),n.edited_message&&await this.handleTelegramMessage(n.edited_message);this.retryState.attempts=0;}handlePollingError(e){if(!this.abortController?.signal.aborted)if(this.log.error("Polling error",{error:String(e)}),this.retryState.attempts<this.retryState.maxAttempts){let s=Math.min(this.retryState.initialDelay*2**this.retryState.attempts,this.retryState.maxDelay);this.retryState.attempts++,this.log.info("Retrying polling",{attempt:this.retryState.attempts,delay:s}),this.sleep(s).then(()=>this.pollLoop());}else this.log.error("Polling failed after max attempts",{attempts:this.retryState.maxAttempts});}sleep(e){return new Promise(s=>setTimeout(s,e))}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot||e.text?.startsWith("/")&&await this.handleCommand(e))return;await this.sendTyping(e.chat.id.toString());let s=this.toGatewayMessage(e);await this.handleMessage(s);}async handleCommand(e){let s=(e.text??"").split(" "),n=s[0]?.toLowerCase()??"",i=s.slice(1),r=this.commandRouter.get(n);if(!r)return false;let l={chatId:e.chat.id.toString(),userId:e.from?.id.toString(),args:i,messageId:e.message_id,reply:async(g,d)=>this.sendApiMessage(e.chat.id.toString(),g,d)};try{return await r.handler(l),!0}catch(g){return this.log.error("Command handler error",{command:n,error:String(g)}),true}}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return v(s,"input",this.parseContent(e),{channel:{platform:"telegram",channelId:this.id,userId:e.from?.id.toString(),chatId:e.chat.id.toString(),username:e.from?.username,firstName:e.from?.first_name,lastName:e.from?.last_name,chatType:e.chat.type,chatTitle:e.chat.title},context:{replyTo:e.reply_to_message?.message_id.toString(),messageId:e.message_id.toString()}})}parseContent(e){let s=[],n=e.text??e.caption??"";if(e.photo&&e.photo.length>0){let i=e.photo[e.photo.length-1];i&&s.push({type:"image",image:i.file_id,mime:"image/jpeg"});}return e.document&&s.push({type:"file",data:e.document.file_id,mime:e.document.mime_type}),n&&s.push({type:"text",text:n}),s}buildSessionId(e,s,n){return n?`telegram_${e}_${s}_${n}`:`telegram_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.chat.id.toString(),n=e.from?.id.toString();return e.chat.type==="private"?this.buildSessionId(this.id,s):this.buildSessionId(this.id,s,n)}async getMe(){return (await this.request("getMe")).result}async getUpdates(e,s,n){let i={offset:e,limit:s};return n>0&&(i.timeout=n),(await this.request("getUpdates",i)).result||[]}async sendApiMessage(e,s,n){let i={chat_id:e,text:s};return n?.parseMode&&n.parseMode!=="None"&&(i.parse_mode=n.parseMode),n?.replyTo&&(i.reply_to_message_id=n.replyTo),n?.replyMarkup&&(i.reply_markup=n.replyMarkup),(await this.request("sendMessage",i)).result.message_id.toString()}async request(e,s={}){let n=`${this.baseUrl}/${e}`,i;for(let r=0;r<=this.retryState.maxAttempts;r++)try{let l=await Fetch.post(n,s,{timeout:this.retryState.maxDelay,retries:0,headers:{"Content-Type":"application/json"},signal:this.abortController?.signal}),g=l.data;if(!g.ok){if(g.error_code===429){this.log.warn("Rate limited, retrying after",{retryAfter:l.headers.get("Retry-After")});let d=parseInt(l.headers.get("Retry-After")??"1",10)*1e3;await this.sleep(d);continue}throw R(this.id,"CHANNEL_CONNECTION_FAILED",`Telegram API error: ${g.description}`,g.error_code!==400&&g.error_code!==401)}return g}catch(l){if(l instanceof M||this.abortController?.signal.aborted)throw l;if(i=l instanceof Error?l:new Error(String(l)),this.log.warn("Request failed, retrying",{method:e,attempt:r+1,error:i.message}),r<this.retryState.maxAttempts){let g=Math.min(this.retryState.initialDelay*2**r,this.retryState.maxDelay);await this.sleep(g);}}throw R(this.id,"CHANNEL_CONNECTION_FAILED",`Failed after ${this.retryState.maxAttempts+1} attempts: ${i?.message}`,true)}};var Q=class extends C{constructor(e="discord-main"){super();a$2(this,"id");a$2(this,"platform","discord");a$2(this,"name","Discord Bot");a$2(this,"botConfig",null);a$2(this,"baseUrl","https://discord.com/api/v10");a$2(this,"gatewayWs",null);a$2(this,"heartbeatInterval",null);a$2(this,"sessionId",null);a$2(this,"sequenceNumber",null);a$2(this,"abortController",null);a$2(this,"reconnectAttempts",0);a$2(this,"maxReconnectAttempts",5);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");let e=await this.getCurrentUser();this.log.info("Discord bot connected",{id:e.id,username:e.username}),this.botConfig.gateway?.enabled!==false&&await this.startGateway();}async doStop(){this.abortController?.abort(),this.abortController=null,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.gatewayWs&&(this.gatewayWs.close(),this.gatewayWs=null),this.botConfig=null,this.reconnectAttempts=0,this.log.info("Discord plugin stopped");}async send(e){let s=e.metadata.channel.chatId;if(!s)throw new Error("Channel ID is required");let n=this.extractText(e);return (await this.createMessage(s,n,e.metadata.context?.replyTo)).id}async startGateway(){if(this.abortController?.signal.aborted)return;let s=`${(await this.getGatewayBot()).url}/?v=10&encoding=json`;this.gatewayWs=new WebSocket(s),this.gatewayWs.onmessage=n=>{this.handleGatewayMessage(JSON.parse(n.data.toString()));},this.gatewayWs.onclose=()=>{if(!this.abortController?.signal.aborted)if(this.log.info("Gateway disconnected"),this.reconnectAttempts<this.maxReconnectAttempts){let n=Math.min(1e3*2**this.reconnectAttempts,3e4);this.reconnectAttempts++,this.log.info("Attempting to reconnect",{attempt:this.reconnectAttempts,delay:n}),setTimeout(()=>this.startGateway(),n);}else this.log.error("Max reconnect attempts reached");},this.gatewayWs.onerror=n=>{this.log.error("Gateway error",{error:String(n)});};}handleGatewayMessage(e){switch(this.updateActivity(),e.op){case 10:this.handleHello(e.d);break;case 11:this.log.debug("Heartbeat ACK");break;case 0:e.s&&(this.sequenceNumber=e.s),this.handleDispatch(e.t,e.d);break;case 9:this.log.warn("Invalid session, reconnecting"),this.gatewayWs?.close();break}return Promise.resolve()}handleHello(e){this.heartbeatInterval=setInterval(()=>{this.gatewayWs?.send(JSON.stringify({op:1,d:this.sequenceNumber}));},e.heartbeat_interval),this.gatewayWs?.send(JSON.stringify({op:2,d:{token:this.botConfig?.botToken,intents:this.botConfig?.gateway?.intents??513,properties:{os:"linux",browser:"easbot",device:"easbot"}}}));}handleDispatch(e,s){e==="MESSAGE_CREATE"&&this.handleDiscordMessage(s);}async handleDiscordMessage(e){if(e.author.bot)return;let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return v(s,"input",this.parseContent(e),{channel:{platform:"discord",channelId:this.id,userId:e.author.id,chatId:e.channel_id,messageId:e.id,guildId:e.guild_id,username:e.author.username,discriminator:e.author.discriminator},context:{threadId:e.message_reference?.message_id,conversationId:e.channel_id}})}parseContent(e){let s=[];e.content&&s.push({type:"text",text:e.content});for(let n of e.attachments)n.content_type?.startsWith("image/")?s.push({type:"image",image:n.url,mime:n.content_type}):s.push({type:"file",data:n.url,mime:n.content_type});return s}buildSessionId(e,s,n){return n?`discord_${e}_${s}_${n}`:`discord_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.channel_id,n=e.author.id;return this.buildSessionId(this.id,s,n)}async getCurrentUser(){return this.request("GET","/users/@me")}async getGatewayBot(){return this.request("GET","/gateway/bot")}async createMessage(e,s,n){let i={content:s};return n&&(i.message_reference={message_id:n}),this.request("POST",`/channels/${e}/messages`,i)}async request(e,s,n){let i=`${this.baseUrl}${s}`,r;if(e==="GET"?r=await Fetch.get(i,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}):e==="POST"?r=await Fetch.post(i,n,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}):e==="DELETE"?r=await Fetch.del(i,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}):r=await Fetch.request(i,{method:e,body:n,headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}),!r.ok)throw new Error(`Discord API error: ${r.data}`);return r.data}};var X=class extends C{constructor(e="slack-main"){super();a$2(this,"id");a$2(this,"platform","slack");a$2(this,"name","Slack Bot");a$2(this,"botConfig",null);a$2(this,"baseUrl","");a$2(this,"socketModeClient",null);a$2(this,"abortController",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");this.abortController=new AbortController,this.baseUrl="https://slack.com/api";let e=await this.authTest();this.log.info("Slack bot connected",{user:e.user,team:e.team,bot_id:e.bot_id}),this.botConfig.socketMode&&this.botConfig.appToken&&await this.startSocketMode();}async doStop(){this.abortController?.abort(),this.abortController=null,this.socketModeClient&&(this.socketModeClient.close(),this.socketModeClient=null),this.botConfig=null,this.log.info("Slack plugin stopped");}async send(e){let s=e.metadata.channel.chatId;if(!s)throw new Error("Channel ID is required");let n=this.extractText(e);return (await this.postMessage(s,n,e.metadata.context?.threadId)).ts}async startSocketMode(){if(!this.botConfig?.appToken)return;let e="wss://wss-primary.slack.com/socket";this.socketModeClient=new WebSocket(e),this.socketModeClient.onmessage=async s=>{try{let n=JSON.parse(s.data.toString());await this.handleSocketModeEvent(n);}catch(n){this.log.error("Socket mode event error",{error:String(n)});}},this.log.info("Socket mode started");}async handleSocketModeEvent(e){if(e.envelope_id&&this.socketModeClient?.send(JSON.stringify({envelope_id:e.envelope_id})),e.type==="events_api"&&e.payload?.event){let s=e.payload.event;s.type==="message"&&!s.subtype&&await this.handleSlackMessage(s);}}async handleSlackMessage(e){this.updateActivity();let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return v(s,"input",this.parseContent(e),{channel:{platform:"slack",channelId:this.id,userId:e.user,chatId:e.channel,ts:e.ts,threadTs:e.thread_ts},context:{threadId:e.thread_ts,conversationId:e.channel}})}parseContent(e){let s=[];if(e.text&&s.push({type:"text",text:e.text}),e.files)for(let n of e.files)s.push({type:"file",data:n.url_private,mime:n.mimetype});return s}buildSessionId(e,s,n){return n?`slack_${e}_${s}_${n}`:`slack_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.channel,n=e.user;return this.buildSessionId(this.id,s,n)}async authTest(){return await this.request("auth.test")}async postMessage(e,s,n){let i={channel:e,text:s};return n&&(i.thread_ts=n),await this.request("chat.postMessage",i)}async request(e,s={}){let n=`${this.baseUrl}/${e}`,i=await Fetch.post(n,s,{headers:{Authorization:`Bearer ${this.botConfig?.botToken}`,"Content-Type":"application/json; charset=utf-8"}});if(!i.data.ok)throw new Error(`Slack API error: ${i.data.error}`);return i.data}};var Y=class extends C{constructor(e="feishu-main"){super();a$2(this,"id");a$2(this,"platform","feishu");a$2(this,"name","Feishu Bot");a$2(this,"botConfig",null);a$2(this,"baseUrl","https://open.feishu.cn/open-apis");a$2(this,"tenantAccessToken",null);a$2(this,"tokenExpireTime",0);a$2(this,"abortController",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw new Error("App ID and App Secret are required");this.abortController=new AbortController,await this.refreshTenantAccessToken(),this.log.info("Feishu bot connected",{app_id:this.botConfig.appId});}async doStop(){this.abortController?.abort(),this.abortController=null,this.botConfig=null,this.tenantAccessToken=null,this.log.info("Feishu plugin stopped");}async send(e){let s=e.metadata.channel.chatId;if(!s)throw new Error("Chat ID is required");await this.ensureTokenValid();let n=this.extractText(e);return (await this.sendMessage(s,n)).message_id}async handleWebhookEvent(e){if(this.updateActivity(),this.botConfig?.verificationToken,e.event?.message){let s=this.toGatewayMessage(e);await this.handleMessage(s);}}toGatewayMessage(e){let s=e.event.message,n=this.processMessageAndGetSessionId(e);return v(n,"input",this.parseContent(s),{channel:{platform:"feishu",channelId:this.id,userId:s.sender.sender_id.open_id,chatId:s.chat_id,messageId:s.message_id,rootId:s.root_id,parentId:s.parent_id,tenantKey:e.tenant_key},context:{threadId:s.root_id,conversationId:s.chat_id}})}parseContent(e){let s=[];try{let n=JSON.parse(e.content);switch(e.message_type){case "text":n.text&&s.push({type:"text",text:n.text});break;case "post":if(n.content){let i=this.extractPostContent(n.content);s.push({type:"text",text:i});}break;case "image":n.image_key&&s.push({type:"image",image:n.image_key,mime:"image/jpeg"});break;case "file":n.file_key&&s.push({type:"file",data:n.file_key,mime:n.file_type});break;default:s.push({type:"text",text:JSON.stringify(n)});}}catch{s.push({type:"text",text:e.content});}return s}extractPostContent(e){let s=[];for(let n of e)if(typeof n=="object"&&n!==null){let i=n;i.text&&s.push(String(i.text)),Array.isArray(i.children)&&s.push(this.extractPostContent(i.children));}return s.join(`
4
- `)}buildSessionId(e,s,n){return n?`feishu_${e}_${s}_${n}`:`feishu_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.event.message,n=s.chat_id,i=s.sender.sender_id.open_id;return this.buildSessionId(this.id,n,i)}async refreshTenantAccessToken(){let s=(await Fetch.post(`${this.baseUrl}/auth/v3/tenant_access_token/internal`,{app_id:this.botConfig?.appId,app_secret:this.botConfig?.appSecret},{headers:{"Content-Type":"application/json"}})).data;if(s.code!==0)throw new Error(`Feishu API error: ${s.msg}`);this.tenantAccessToken=s.tenant_access_token,this.tokenExpireTime=Date.now()+s.expire*1e3-6e4;}async ensureTokenValid(){(!this.tenantAccessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshTenantAccessToken();}async sendMessage(e,s){let i=(await Fetch.post(`${this.baseUrl}/im/v1/messages?receive_id_type=chat_id`,{receive_id:e,msg_type:"text",content:JSON.stringify({text:s})},{headers:{Authorization:`Bearer ${this.tenantAccessToken}`,"Content-Type":"application/json"}})).data;if(i.code!==0)throw new Error(`Feishu API error: ${i.msg}`);return i.data}};var Z=class extends C{constructor(e="wechat-main"){super();a$2(this,"id");a$2(this,"platform","wechat");a$2(this,"name","WeChat Bot");a$2(this,"botConfig",null);a$2(this,"accessToken",null);a$2(this,"tokenExpireTime",0);a$2(this,"abortController",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw new Error("App ID and App Secret are required");this.abortController=new AbortController,await this.refreshAccessToken(),this.log.info("WeChat bot connected",{app_id:this.botConfig.appId,mode:this.botConfig.mode});}async doStop(){this.abortController?.abort(),this.abortController=null,this.botConfig=null,this.accessToken=null,this.log.info("WeChat plugin stopped");}async send(e){let s=e.metadata.channel.userId;if(!s)throw new Error("User ID is required");await this.ensureTokenValid();let n=this.extractText(e);return this.botConfig?.mode==="wecom"?await this.sendWeComMessage(s,n):await this.sendOfficialMessage(s,n)}async handleWebhookMessage(e){this.updateActivity();let s=this.parseXmlMessage(e);if(s){let n=this.toGatewayMessage(s);await this.handleMessage(n);}}parseXmlMessage(e){let s=r=>e.match(new RegExp(`<${r}><!\\[CDATA\\[(.*?)\\]\\]></${r}>`))?.[1],n=r=>{let l=e.match(new RegExp(`<${r}>(\\d+)</${r}>`));return l?.[1]?parseInt(l[1],10):void 0},i=s("MsgType");return i?{ToUserName:s("ToUserName")??"",FromUserName:s("FromUserName")??"",CreateTime:n("CreateTime")??0,MsgType:i,Content:s("Content"),MsgId:n("MsgId"),PicUrl:s("PicUrl"),MediaId:s("MediaId")}:null}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return v(s,"input",this.parseContent(e),{channel:{platform:"wechat",channelId:this.id,userId:e.FromUserName,chatId:e.FromUserName,toUser:e.ToUserName,msgId:e.MsgId?.toString(),mode:this.botConfig?.mode},context:{conversationId:e.FromUserName}})}parseContent(e){let s=[];switch(e.MsgType){case "text":e.Content&&s.push({type:"text",text:e.Content});break;case "image":(e.PicUrl||e.MediaId)&&s.push({type:"image",image:e.PicUrl??e.MediaId??"",mime:"image/jpeg"});break;case "voice":e.MediaId&&s.push({type:"file",data:e.MediaId,mime:"audio/amr"}),"Recognition"in e&&e.Recognition&&s.push({type:"text",text:e.Recognition});break;case "video":case "shortvideo":e.MediaId&&s.push({type:"file",data:e.MediaId,mime:"video/mp4"});break;default:e.Content&&s.push({type:"text",text:e.Content});}return s}buildSessionId(e,s,n){return n?`wechat_${e}_${s}_${n}`:`wechat_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.FromUserName;return this.buildSessionId(this.id,s)}async refreshAccessToken(){let e;this.botConfig?.mode==="wecom"?e=`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${this.botConfig.appId}&corpsecret=${this.botConfig.appSecret}`:e=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.botConfig?.appId}&secret=${this.botConfig?.appSecret}`;let n=(await Fetch.get(e)).data;if(n.errcode&&n.errcode!==0)throw new Error(`WeChat API error: ${n.errmsg}`);this.accessToken=n.access_token,this.tokenExpireTime=Date.now()+n.expires_in*1e3-6e4;}async ensureTokenValid(){(!this.accessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshAccessToken();}async sendOfficialMessage(e,s){let i=(await Fetch.post(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{touser:e,msgtype:"text",text:{content:s}},{headers:{"Content-Type":"application/json"}})).data;if(i.errcode!==0)throw new Error(`WeChat API error: ${i.errmsg}`);return i.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,s){let i=(await Fetch.post(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${this.accessToken}`,{touser:e,msgtype:"text",agentid:this.botConfig?.agentId,text:{content:s}},{headers:{"Content-Type":"application/json"}})).data;if(i.errcode!==0)throw new Error(`WeCom API error: ${i.errmsg}`);return i.msgid??Date.now().toString()}};var ee=class extends C{constructor(e="webchat-main"){super();a$2(this,"id");a$2(this,"platform","webchat");a$2(this,"name","WebChat");a$2(this,"webChatConfig",null);a$2(this,"connections",new Map);a$2(this,"heartbeatInterval",null);a$2(this,"abortController",null);a$2(this,"wsServer",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");this.webChatConfig=this.config.platform,this.abortController=new AbortController,await this.startWebSocketServer(),this.startHeartbeat(),this.log.info("WebChat plugin started",{port:this.webChatConfig.port,hostname:this.webChatConfig.hostname,path:this.webChatConfig.path,maxConnections:this.webChatConfig.maxConnections});}async startWebSocketServer(){if(!this.webChatConfig)return;let e={port:this.webChatConfig.port,hostname:this.webChatConfig.hostname,path:this.webChatConfig.path,maxConnections:this.webChatConfig.maxConnections,connectionTimeout:this.webChatConfig.connectionTimeout,heartbeatInterval:this.webChatConfig.heartbeatInterval,sessionExpireMs:this.webChatConfig.sessionExpireMs,https:this.webChatConfig.https};this.wsServer=new G(e),await this.wsServer.start(),this.log.info("WebSocket server started",{url:`${this.webChatConfig.https?.enabled?"wss":"ws"}://${this.webChatConfig.hostname}:${this.webChatConfig.port}${this.webChatConfig.path}`});}async doStop(){this.abortController?.abort(),this.abortController=null,this.wsServer&&(await this.wsServer.stop(),this.wsServer=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let e of this.connections.values())e.ws.close();this.connections.clear(),this.webChatConfig=null,this.log.info("WebChat plugin stopped");}async send(e){let s=e.sessionId,n=e.metadata.channel.userId;if(this.wsServer&&s){let l={type:"message",sessionId:s,properties:{sessionID:s,content:e.content,timestamp:e.timestamp||Date.now()}};return this.wsServer.broadcastToSession(s,l),e.id}if(!n)throw new Error("User ID is required");let i=this.findConnectionByUser(n);if(!i)throw new Error("User not connected");let r={type:"message",sessionId:s,content:e.content,metadata:e.metadata};return i.ws.send(JSON.stringify(r)),i.lastActivity=Date.now(),e.id}pushEvent(e,s){this.wsServer&&this.wsServer.broadcastToSession(e,s);}getWebSocketServer(){return this.wsServer}async handleConnection(e,s){let n=this.generateConnectionId();if(this.connections.size>=(this.webChatConfig?.maxConnections??1e3)){e.close(1013,"Maximum connections reached");return}let i={id:n,ws:e,userId:s,lastActivity:Date.now()};this.connections.set(n,i),e.onmessage=r=>{this.handleWebSocketMessage(i,r.data.toString());},e.onclose=()=>{this.connections.delete(n),this.log.debug("WebSocket closed",{connId:n,userId:s});},e.onerror=r=>{this.log.error("WebSocket error",{connId:n,userId:s,error:String(r)});},this.log.info("WebSocket connected",{connId:n,userId:s});}async handleWebSocketMessage(e,s){this.updateActivity(),e.lastActivity=Date.now();try{let n=JSON.parse(s);switch(n.type){case "message":await this.handleChatMessage(e,n);break;case "ping":e.ws.send(JSON.stringify({type:"pong"}));break;case "subscribe":n.sessionId&&(e.sessionId=n.sessionId);break;case "unsubscribe":e.sessionId=void 0;break}}catch(n){this.log.error("Failed to handle WebSocket message",{error:String(n)});}}async handleChatMessage(e,s){if(!s.content||!s.sessionId)return;let n=v(s.sessionId,"input",s.content,{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},context:{conversationId:s.sessionId},...s.metadata});await this.handleMessage(n);}startHeartbeat(){let e=this.webChatConfig?.heartbeatInterval??3e4;this.heartbeatInterval=setInterval(()=>{let s=Date.now(),n=this.webChatConfig?.connectionTimeout??6e4;for(let[i,r]of this.connections)s-r.lastActivity>n&&(this.log.info("Closing inactive connection",{connId:i}),r.ws.close(1001,"Connection timeout"),this.connections.delete(i));},e);}findConnectionByUser(e){for(let s of this.connections.values())if(s.userId===e)return s}generateConnectionId(){return `conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}getConnectionCount(){return this.connections.size}getWsServerConnectionCount(){return this.wsServer?.getConnectionCount()??0}};var te=class extends C{constructor(e="signal-main"){super();a$2(this,"id");a$2(this,"platform","signal");a$2(this,"name","Signal Bot");a$2(this,"botConfig",null);a$2(this,"abortController",null);a$2(this,"lastTimestamp",0);a$2(this,"pollingIntervalMs",5e3);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.phoneNumber)throw new Error("Phone number is required");this.abortController=new AbortController;let e=await this.getAccountInfo();this.log.info("Signal bot connected",{number:this.botConfig.phoneNumber,address:e.address}),this.startPolling();}async doStop(){this.abortController?.abort(),this.abortController=null,this.botConfig=null,this.lastTimestamp=0,this.log.info("Signal plugin stopped");}async send(e){let s=e.metadata.channel.userId;if(!s)throw new Error("Recipient is required");let n=this.extractText(e);return (await this.sendMessage(s,n)).timestamp.toString()}startPolling(){this.pollLoop(),this.log.info("Polling started",{interval:this.pollingIntervalMs});}pollLoop(){if(this.abortController?.signal.aborted)return;(async()=>{try{await this.poll();}catch(s){this.log.error("Polling error",{error:String(s)});}})().then(()=>{this.abortController?.signal.aborted||setTimeout(()=>this.pollLoop(),this.pollingIntervalMs);});}async poll(){let e=await this.receiveMessages(this.lastTimestamp);for(let s of e)this.lastTimestamp=s.envelope.timestamp,s.envelope.dataMessage&&await this.handleSignalMessage(s);}async handleSignalMessage(e){this.updateActivity();let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e),n=e.envelope.dataMessage;return v(s,"input",this.parseContent(n),{channel:{platform:"signal",channelId:this.id,userId:e.envelope.sourceNumber,chatId:e.envelope.sourceNumber,sourceUuid:e.envelope.sourceUuid,timestamp:e.envelope.timestamp},context:{conversationId:e.envelope.sourceNumber}})}parseContent(e){let s=[];if(!e)return s;if(e.message&&s.push({type:"text",text:e.message}),e.attachments)for(let n of e.attachments)n.contentType.startsWith("image/")?s.push({type:"image",image:n.id,mime:n.contentType}):s.push({type:"file",data:n.id,mime:n.contentType});return s}buildSessionId(e,s,n){return n?`signal_${e}_${s}_${n}`:`signal_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.envelope.sourceNumber;return this.buildSessionId(this.id,s)}async getAccountInfo(){return await this.request("GET",`/v1/accounts/${this.botConfig?.phoneNumber}`)}async receiveMessages(e){let s=e>0?`?since=${e}`:"";return await this.request("GET",`/v1/receive/${this.botConfig?.phoneNumber}${s}`)||[]}async sendMessage(e,s){return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:s})}async request(e,s,n){let i=`${this.botConfig?.serviceUrl}${s}`,r={"Content-Type":"application/json"};this.botConfig?.password&&(r.Authorization=`Basic ${Buffer.from(`${this.botConfig.phoneNumber}:${this.botConfig.password}`).toString("base64")}`);let l;if(e==="GET"?l=await Fetch.get(i,{headers:r}):e==="POST"?l=await Fetch.post(i,n,{headers:r}):e==="DELETE"?l=await Fetch.del(i,{headers:r}):l=await Fetch.request(i,{method:e,body:n,headers:r}),!l.ok)throw new Error(`Signal API error: ${l.data}`);return l.data}};var se=class extends C{constructor(e="nostr-main"){super();a$2(this,"id");a$2(this,"platform","nostr");a$2(this,"name","Nostr Bot");a$2(this,"botConfig",null);a$2(this,"relayConnections",new Map);a$2(this,"subscriptions",new Map);a$2(this,"eventHandlers",new Map);a$2(this,"abortController",null);a$2(this,"relayReconnectAttempts",new Map);a$2(this,"maxReconnectAttempts",5);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.relays||this.botConfig.relays.length===0)throw new Error("At least one relay is required");this.abortController=new AbortController;for(let e of this.botConfig.relays)await this.connectToRelay(e);this.log.info("Nostr bot connected",{relays:this.botConfig.relays,pubkey:this.botConfig.publicKey?.substring(0,16)+"..."});}async doStop(){this.abortController?.abort(),this.abortController=null;for(let[e,s]of this.relayConnections)s.close();this.relayConnections.clear(),this.subscriptions.clear(),this.eventHandlers.clear(),this.relayReconnectAttempts.clear(),this.botConfig=null,this.log.info("Nostr plugin stopped");}async send(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required for sending messages");let s=this.extractText(e),n=await this.createEvent(s,e.metadata.context?.replyTo);return await this.publishEvent(n),n.id}async connectToRelay(e){if(this.abortController?.signal.aborted)return;let s=new WebSocket(e);s.onopen=()=>{this.log.info("Connected to relay",{relay:e}),this.relayReconnectAttempts.set(e,0);for(let[n,i]of this.subscriptions)this.subscribeToRelay(s,n,i);},s.onmessage=n=>{this.handleRelayMessage(e,n.data.toString());},s.onclose=()=>{if(this.abortController?.signal.aborted)return;this.log.info("Disconnected from relay",{relay:e}),this.relayConnections.delete(e);let n=this.relayReconnectAttempts.get(e)??0;if(n<this.maxReconnectAttempts){let i=Math.min(1e3*2**n,3e4);this.relayReconnectAttempts.set(e,n+1),this.log.info("Attempting to reconnect to relay",{relay:e,attempt:n+1,delay:i}),setTimeout(()=>this.connectToRelay(e),i);}else this.log.error("Max reconnect attempts reached for relay",{relay:e});},s.onerror=n=>{this.log.error("Relay error",{relay:e,error:String(n)});},this.relayConnections.set(e,s);}handleRelayMessage(e,s){this.updateActivity();try{let n=JSON.parse(s);if(n[0]==="EVENT"&&n[2]){let i=n[2];this.handleNostrEvent(i);}if(n[0]==="OK"){let i=n[1],r=n[2];this.log.debug("Event published",{eventId:i,success:r});}}catch(n){this.log.error("Failed to handle relay message",{error:String(n)});}return Promise.resolve()}async handleNostrEvent(e){if(e.kind!==1||e.pubkey===this.botConfig?.publicKey)return;let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return v(s,"input",this.parseContent(e),{channel:{platform:"nostr",channelId:this.id,userId:e.pubkey,chatId:e.pubkey,eventId:e.id,createdAt:e.created_at,tags:e.tags},context:{replyTo:this.findReplyTo(e.tags),conversationId:e.pubkey}})}parseContent(e){let s=[];e.content&&s.push({type:"text",text:e.content});for(let n of e.tags)if(n[0]==="url"&&n[1]){let i=n[1];i.match(/\.(jpg|jpeg|png|gif|webp)$/i)&&s.push({type:"image",image:i});}return s}findReplyTo(e){for(let s of e)if(s[0]==="e"&&s[1])return s[1]}buildSessionId(e,s,n){return n?`nostr_${e}_${s}_${n}`:`nostr_${e}_${s}`}processMessageAndGetSessionId(e){return this.buildSessionId(this.id,e.pubkey)}subscribeToRelay(e,s,n){let i=["REQ",s,n];e.send(JSON.stringify(i));}async createEvent(e,s){let n=[];s&&n.push(["e",s]);let i={id:"",pubkey:this.botConfig?.publicKey??"",created_at:Math.floor(Date.now()/1e3),kind:1,tags:n,content:e,sig:""};return i.id=await this.computeEventId(i),i.sig=await this.signEvent(i),i}async computeEventId(e){let s=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),i=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(r)).map(g=>g.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required");return "signature_placeholder"}async publishEvent(e){let s=["EVENT",e];for(let n of this.relayConnections.values())n.readyState===WebSocket.OPEN&&n.send(JSON.stringify(s));}};var He=class extends C{constructor(e){super();a$2(this,"id");a$2(this,"platform");a$2(this,"name");a$2(this,"version");a$2(this,"options");this.id=e.id,this.platform=e.platform||"custom",this.name=e.name,this.version=e.version||"1.0.0",this.options=e,this.initLog();}async doStart(){this.options.setup?.initialize&&await this.options.setup.initialize(),this.log.info("Channel plugin started",{id:this.id,platform:this.platform});}async doStop(){this.options.setup?.destroy&&await this.options.setup.destroy(),this.log.info("Channel plugin stopped",{id:this.id});}async send(e){let s=e;this.options.actions?.beforeSend&&(s=await this.options.actions.beforeSend(e));let n=await this.options.messaging.send(s);return this.options.actions?.afterSend&&await this.options.actions.afterSend(s,n),n}async healthCheck(){return this.options.status?.healthCheck?{healthy:await this.options.status.healthCheck(),lastCheck:Date.now()}:{healthy:true,lastCheck:Date.now()}}};function gs(c){return new He(c)}var ze={telegram:J,discord:Q,slack:X,feishu:Y,wechat:Z,webchat:ee,signal:te,nostr:se};function co(){return Object.keys(ze)}function ds(c){let t={platform:c.channel?.platform??"api",channelId:c.channel?.channelId??"unknown",chatId:c.channel?.chatId,userId:c.channel?.userId};return {id:c.messageId??`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c.sessionId,type:c.type,content:Array.isArray(c.content)?c.content:[{type:"text",text:String(c.content??"")}],metadata:{channel:t,replyToMessageId:c.replyToMessageId},timestamp:c.timestamp??Date.now()}}var ot=class{constructor(t){a$2(this,"log",a.create({service:"gateway:server"}));a$2(this,"config");a$2(this,"router");a$2(this,"sessionManager");a$2(this,"pluginLoader");a$2(this,"messageStore");a$2(this,"contactStore",null);a$2(this,"wsServer",null);a$2(this,"running",false);a$2(this,"connections",0);this.log.debug("GatewayServer.constructor: starting"),this.config=t,this.log.debug("GatewayServer.constructor: creating MessageRouter"),this.router=new we,this.log.debug("GatewayServer.constructor: creating GatewaySessionManager");let e=O();this.sessionManager=new q({storagePath:`${e.Path.data}/gateway/sessions`,enablePersistence:true}),this.log.debug("GatewayServer.constructor: creating ChannelPluginLoader"),this.pluginLoader=new K({healthCheckInterval:6e4}),this.log.debug("GatewayServer.constructor: pluginLoader created");let s=T();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:s}),this.messageStore=new H({storagePath:`${e.Path.data}/gateway/messages`}),s&&(this.log.debug("GatewayServer.constructor: adapter exists, setting message storage"),E().setMessageStorage({store:async i=>{let r=ds(i);await this.messageStore.store(r);},updateStatus:async(i,r,l)=>{await this.messageStore.updateStatus(i,r,l);}})),this.pluginLoader.setMessageHandler({onMessage:n=>this.onMessage(n),onEvent:n=>this.onEvent(n)}),this.log.debug("GatewayServer.constructor: completed");}async loadChannelPlugins(){try{let{config:t}=await w(),e=t.channels;if(!e){this.log.debug("no channel config found, skipping plugin loading");return}for(let[s,n]of Object.entries(e)){if(!n?.enabled){this.log.debug("channel disabled or not configured",{platform:s});continue}let i=ze[s];if(!i){this.log.warn("no plugin class found for platform",{platform:s});continue}let r=`${s}-main`,l=new i(r),g={enabled:!0,platform:n,session:{autoCreate:!0,resetPolicy:"onNewConversation"},routing:{broadcast:!0,dispatchToSubAgent:!0}};try{await this.pluginLoader.register(l,g),this.log.info("channel plugin registered",{platform:s,id:r});}catch(d){this.log.error("failed to register channel plugin",{platform:s,error:String(d)});}}}catch(t){this.log.error("failed to load channel plugins",{error:String(t)});}}async start(){if(this.log.debug("GatewayServer.start: called"),this.running){this.log.warn("gateway server is already running");return}this.log.info("starting gateway server",{port:this.config.port,hostname:this.config.hostname}),this.log.debug("GatewayServer.start: initializing sessionManager"),await this.sessionManager.initialize(),this.log.debug("GatewayServer.start: sessionManager initialized"),this.log.debug("GatewayServer.start: initializing contactStore");let e=`${O().Path.data}/gateway`,s=new $({baseDir:e});this.contactStore=new j(s,{cacheSize:1e3}),this.contactStore.initialize&&await this.contactStore.initialize(),this.log.debug("GatewayServer.start: contactStore initialized"),this.log.debug("GatewayServer.start: creating WebSocket server"),this.wsServer=new G({port:this.config.port,hostname:this.config.hostname,path:String(this.config.path??"/")}),this.log.debug("GatewayServer.start: calling wsServer.start()"),await this.wsServer.start(),this.log.debug("GatewayServer.start: wsServer started"),await this.loadChannelPlugins(),this.log.debug("GatewayServer.start: starting plugins in background"),this.pluginLoader.startAll().catch(r=>{this.log.error("plugin startup error",{error:String(r)});}),this.log.debug("GatewayServer.start: plugins startup initiated"),this.log.debug("GatewayServer.start: starting health check timer"),this.pluginLoader.startHealthCheckTimer();let{config:n}=await w(),i=n.defaults;this.wsServer.setChannelResolveDeps({sessionManager:{get:r=>this.sessionManager.get(r),bindBackendSession:(r,l)=>this.sessionManager.bindBackendSession(r,l)},pluginLoader:{getPlugin:r=>this.pluginLoader.getPlugin(r),getAllPlugins:()=>this.pluginLoader.getAllPlugins(),isRunning:r=>this.pluginLoader.isRunning(r)},defaultChannel:i?.channel,fallbackChannels:i?.fallbackChannels,contactStore:this.contactStore?{findByPlatformId:(r,l)=>this.contactStore.findByPlatformId(r,l),findByUid:r=>this.contactStore.findByUid(r),listByPlatform:(r,l,g)=>this.contactStore.listByPlatform(r,l,g),count:r=>this.contactStore.count(r)}:void 0}),this.wsServer.setPluginLoader({send:(r,l)=>this.sendToChannel(r,l)}),this.running=true,this.log.debug("GatewayServer.start: completed"),this.log.info("gateway server started");}async stop(){if(!this.running){this.log.warn("gateway server is not running");return}this.log.info("stopping gateway server"),this.wsServer&&(this.log.debug("stopping WebSocket server"),await this.wsServer.stop(),this.wsServer=null,this.log.debug("WebSocket server stopped")),this.pluginLoader.stopHealthCheckTimer(),await this.pluginLoader.stopAll(),await this.router.shutdown(),await this.sessionManager.close(),await this.messageStore.close(),this.contactStore?.close&&await this.contactStore.close(),this.running=false,this.log.info("gateway server stopped");}getStatus(){return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections}}async onMessage(t){if(this.log.debug("message received",{id:t.id,sessionId:t.sessionId,type:t.type}),this.messageStore.isProcessed(t.id)){this.log.warn("message already processed, skipping",{id:t.id});return}await this.storeMessage(t),t.type==="input"&&await this.saveContactFromMessage(t),await this.sessionManager.incrementMessageCountOrCreate(t.sessionId,t.metadata.channel),(await this.router.route(t)).broadcastCount===0&&t.type==="input"&&(this.log.debug("no subscribers, dispatching to local SubAgent",{id:t.id}),await this.dispatchToSubAgent(t));}async saveContactFromMessage(t){if(!this.contactStore)return;let{platform:e,channelId:s,userId:n,chatId:i}=t.metadata.channel;if(!e||e==="api")return;let r=n||i;if(r)try{let l=await this.contactStore.getOrCreate(e,r,{username:t.metadata.channel?.username,displayName:t.metadata.channel?.firstName});this.log.debug("contact saved",{uid:l.uid});}catch(l){this.log.warn("failed to save contact",{platform:e,stableId:r,error:String(l)});}}async dispatchToSubAgent(t){if(!T()){this.log.debug("no agent adapter, message remains pending",{id:t.id});return}try{let s=E().subAgentRunner;if(!s){this.log.debug("no SubAgentRunner available, message remains pending",{id:t.id});return}this.log.info("dispatching message to local SubAgent",{id:t.id,sessionId:t.sessionId});let n=this.sessionManager.get(t.sessionId),i=n?.backendSessionId||void 0;await this.triggerHook(HookEvent.GatewayMessageProcess,{messageId:t.id,sessionId:t.sessionId,backendSessionId:i,processorId:"subagent",processType:"subagent",agent:"default",timestamp:Date.now()});let r=t.metadata.channel,l=r?.platform||"unknown",g=r?.userId||r?.chatId||"unknown user",d=`${l}:${g}`,y=`## External Channel Message
5
- - Platform: ${l}
6
- - From: ${g} (contactUid: ${d})
7
- - Channel: ${r?.channelId||"default"}
8
- - Session: ${t.sessionId}
9
-
10
- ## Instructions
11
- - Reply the message directly if it's a simple response.
12
- - Use gateway_channel tool to proactively send messages: \`\`\`json
13
- {"operation": "send", "contactUid": "${d}", "content": "Your message here"}
14
- \`\`\``,b={source:t.sessionId,title:`[${l}] Message from ${g}`,agent:"gateway",sessionId:i,parts:t.content,system:y,channel:{platform:l,contactUid:d,channelId:r?.channelId,userId:g}},k=await s.run(b),f=k.metadata?.sessionId;if(f&&n&&n.backendSessionId!==f&&(await this.sessionManager.bindBackendSession(t.sessionId,f),this.log.info("backend session bound",{gatewaySessionId:t.sessionId,backendSessionId:f})),await this.triggerHook(HookEvent.GatewayMessageComplete,{messageId:t.id,sessionId:t.sessionId,backendSessionId:f||i,processorId:"subagent",status:"completed",timestamp:Date.now()}),k.output){let S=t.metadata.channel;S?.channelId&&await this.sendToChannel(S.channelId,{id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:t.sessionId,type:"output",content:[{type:"text",text:k.output}],metadata:{channel:S},timestamp:Date.now()});}this.log.info("SubAgent response sent",{id:t.id});}catch(e){this.log.error("SubAgent dispatch failed",{id:t.id,error:String(e)});}}async triggerHook(t,e){if(T())try{await E().hookRegistry.emit({name:t,data:e});}catch{this.log.debug("hook trigger skipped",{event:t});}}async storeMessage(t){let e={messageId:t.id,sessionId:t.sessionId,type:t.type,content:t.content,channel:t.metadata.channel,replyToMessageId:t.metadata.replyToMessageId,timestamp:t.timestamp||Date.now()};if(T())try{await E().hookRegistry.emit({name:HookEvent.GatewayMessageReceive,data:e}),this.log.debug("message stored via hook",{messageId:t.id});return}catch{this.log.debug("hook trigger skipped, using local storage");}await this.messageStore.store(t),this.log.debug("message stored locally",{messageId:t.id});}async processMessage(t,e,s,n={}){if(await this.messageStore.updateStatus(e,"processing",{processedBy:s}),T())try{await E().hookRegistry.emit({name:HookEvent.GatewayMessageProcess,data:{messageId:e,sessionId:t,processorId:s,processType:n.processType||"direct",agent:n.agent,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}}async completeMessage(t,e,s,n={}){let{success:i=true,error:r,responseMessageId:l,tokens:g,duration:d}=n;if(await this.messageStore.updateStatus(e,i?"completed":"failed",{processedBy:s,error:r}),T())try{await E().hookRegistry.emit({name:HookEvent.GatewayMessageComplete,data:{messageId:e,sessionId:t,processorId:s,status:i?"completed":"failed",error:r,responseMessageId:l,tokens:g,duration:d,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}await this.router.completeMessage(t,e,s,i?"completed":"failed");}async onEvent(t){switch(this.log.debug("channel event",{type:t.type,channelId:t.channelId}),t.type){case "connected":this.connections++;break;case "disconnected":this.connections--;break;case "error":this.log.error("channel error",{channelId:t.channelId,data:t.data});break}}async registerChannel(t,e){let s=e??{enabled:true,platform:{},session:{autoCreate:true,resetPolicy:"onNewConversation"},routing:{broadcast:true,dispatchToSubAgent:false}};await this.pluginLoader.register(t,s),this.running&&await this.pluginLoader.start(t.id);}async unregisterChannel(t){await this.pluginLoader.unregister(t);}async subscribe(t,e){await this.router.subscribe(t,e),await this.sessionManager.addSubscriber(t,e.id);}async unsubscribe(t){await this.router.unsubscribe(t);}async send(t){await this.onMessage(t);}async sendToChannel(t,e,s={}){let{proactive:n=false,replyToMessageId:i}=s;if(await this.messageStore.store(e),this.log.debug("message stored",{messageId:e.id,proactive:n}),i&&(await this.messageStore.updateStatus(i,"completed",{processedBy:"gateway"}),this.log.debug("original message status updated to completed",{replyToMessageId:i})),T())try{await E().hookRegistry.emit({name:HookEvent.GatewayMessageSend,data:{messageId:e.id,sessionId:e.sessionId,type:e.type,channel:e.metadata.channel,proactive:n,replyToMessageId:i,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}let r=this.pluginLoader.getPlugin(t);if(!r)throw new Error(`Plugin not found: ${t}`);return r.send(e)}async sendProactiveMessage(t,e,s,n){let i={id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:e,type:"output",content:s,metadata:{channel:n},timestamp:Date.now()};return this.sendToChannel(t,i,{proactive:true})}getSessionManager(){return this.sessionManager}getRouter(){return this.router}getPluginLoader(){return this.pluginLoader}getMessageStore(){return this.messageStore}getContactStore(){return this.contactStore}async getMessageHistory(t,e){return this.messageStore.getSessionHistory(t,e)}};export{Xt as $,Ut as A,Ft as B,Wt as C,Bt as D,Ht as E,zt as F,$t as G,jt as H,qt as I,Kt as J,Vt as K,Ye as L,Ws as M,Bs as N,T as O,E as P,Ne as Q,ne as R,ie as S,v as T,at as U,ke as V,Te as W,Re as X,De as Y,Jt as Z,Qt as _,ce as a,Yt as aa,le as b,we as ba,ge as c,H as ca,de as d,z as da,ue as e,q as ea,he as f,K as fa,pe as g,G as ga,$e as h,C as ha,je as i,J as ia,qe as j,Q as ja,Ke as k,X as ka,Ve as l,Y as la,fe as m,Z as ma,me as n,ee as na,ye as o,te as oa,be as p,se as pa,Ce as q,gs as qa,Se as r,ze as ra,ae as s,co as sa,_e as t,ot as ta,pt as u,Je as v,Qe as w,Xe as x,Lt as y,Ot as z};