@easbot/gateway 0.2.1 → 0.2.3
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/chunks/chunk-34MFQLJP.cjs +2 -0
- package/dist/chunks/chunk-4PHQN25U.cjs +2 -0
- package/dist/chunks/chunk-5ETPYYQR.cjs +7 -0
- package/dist/chunks/chunk-6TRL3CVJ.mjs +7 -0
- package/dist/chunks/chunk-AVBAZ6OJ.cjs +1 -0
- package/dist/chunks/{chunk-5RLC2FW2.mjs → chunk-GRBXQALD.mjs} +1 -1
- package/dist/chunks/chunk-GY3SWWW3.cjs +1 -0
- package/dist/chunks/chunk-HAMGVOQD.mjs +1 -0
- package/dist/chunks/chunk-K2WP2GA3.mjs +2 -0
- package/dist/chunks/chunk-KT3LOK7X.mjs +1 -0
- package/dist/chunks/{chunk-2DDZUOLB.cjs → chunk-OTZE7MGS.cjs} +1 -1
- package/dist/chunks/chunk-YU4JG7OA.mjs +2 -0
- package/dist/chunks/global-N3LSJP4X.mjs +1 -0
- package/dist/chunks/global-VJ6XBERK.cjs +1 -0
- package/dist/chunks/log-B5SORET6.cjs +1 -0
- package/dist/chunks/log-K67H67P2.mjs +1 -0
- package/dist/chunks/package-LIXBTRLN.mjs +1 -0
- package/dist/chunks/package-ZAW6IG3H.cjs +1 -0
- package/dist/chunks/server-C5W7D4CU.mjs +1 -0
- package/dist/chunks/server-HQL7QNZY.cjs +1 -0
- package/dist/cli.cjs +7 -32
- package/dist/cli.mjs +7 -32
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +14 -52
- package/dist/index.d.ts +14 -52
- package/dist/index.mjs +8 -8
- package/package.json +25 -17
- package/dist/chunks/chunk-NJHJCACX.cjs +0 -2
- package/dist/chunks/chunk-O3U6QY4W.mjs +0 -2
- package/dist/chunks/chunk-OSZ6KMPF.cjs +0 -1
- package/dist/chunks/chunk-P3MN336E.cjs +0 -8
- package/dist/chunks/chunk-SIOB4FC7.cjs +0 -1
- package/dist/chunks/chunk-SJNPXLNN.mjs +0 -1
- package/dist/chunks/chunk-SSKI3TXN.mjs +0 -8
- package/dist/chunks/chunk-TY6W6O7O.mjs +0 -1
- package/dist/chunks/chunk-UCF5C44I.mjs +0 -1
- package/dist/chunks/chunk-XQVVSJRM.cjs +0 -1
- package/dist/chunks/global-BCWJXCJA.cjs +0 -1
- package/dist/chunks/global-C2YB6FKX.mjs +0 -1
- package/dist/chunks/package-HISKEB3S.cjs +0 -1
- package/dist/chunks/package-VYOXRMBW.mjs +0 -1
- package/dist/chunks/server-5P63VGLE.mjs +0 -1
- package/dist/chunks/server-EFOLB7OJ.cjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
'use strict';var chunkOSZ6KMPF_cjs=require('./chunks/chunk-OSZ6KMPF.cjs'),chunkNJHJCACX_cjs=require('./chunks/chunk-NJHJCACX.cjs'),chunkP3MN336E_cjs=require('./chunks/chunk-P3MN336E.cjs'),chunkSIOB4FC7_cjs=require('./chunks/chunk-SIOB4FC7.cjs'),chunkXQVVSJRM_cjs=require('./chunks/chunk-XQVVSJRM.cjs');chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var u=chunkP3MN336E_cjs.a.create({service:"gateway:agent-registry"}),k=class{constructor(n={}){chunkXQVVSJRM_cjs.e(this,"config");chunkXQVVSJRM_cjs.e(this,"agents",new Map);chunkXQVVSJRM_cjs.e(this,"heartbeatTimer",null);chunkXQVVSJRM_cjs.e(this,"roundRobinIndex",0);this.config={...chunkNJHJCACX_cjs.j,...n};}async register(n){if(this.agents.has(n.id))throw new Error(`Agent with ID "${n.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),t={...n,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(n.id,t),u.info("Agent registered",{agentId:n.id,name:n.name,capabilities:n.capabilities,address:n.address,totalAgents:this.agents.size});}async deregister(n){let e=this.agents.get(n);if(!e){u.warn("Attempted to deregister unknown agent",{agentId:n});return}this.agents.delete(n),u.info("Agent deregistered",{agentId:n,name:e.name,totalAgents:this.agents.size});}async heartbeat(n,e){let t=this.agents.get(n);if(!t)throw u.warn("Heartbeat received from unknown agent",{agentId:n}),new Error(`Agent "${n}" is not registered`);t.lastHeartbeat=Date.now(),t.status="healthy",e&&(t.metadata={...t.metadata,...e}),u.debug("Agent heartbeat received",{agentId:n,lastHeartbeat:t.lastHeartbeat});}getAgent(n){return this.agents.get(n)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(n=>n.status==="healthy")}selectAgent(n){let{strategy:e,capabilities:t,healthyOnly:s=true}=n,i=s?this.getHealthyAgents():this.getAllAgents();if(t&&t.length>0&&(i=i.filter(o=>t.every(p=>o.capabilities.includes(p)))),i.length===0){u.warn("No agents available for selection",{strategy:e,capabilities:t,healthyOnly:s,totalAgents:this.agents.size});return}let a;switch(e){case "random":a=this.selectRandom(i);break;case "round-robin":a=this.selectRoundRobin(i);break;case "least-connections":a=this.selectLeastConnections(i);break;default:a=this.selectRandom(i);}return u.debug("Agent selected",{agentId:a.id,strategy:e,connectionCount:a.connectionCount}),a}incrementConnection(n){let e=this.agents.get(n);e&&(e.connectionCount++,u.debug("Agent connection incremented",{agentId:n,connectionCount:e.connectionCount}));}decrementConnection(n){let e=this.agents.get(n);e&&e.connectionCount>0&&(e.connectionCount--,u.debug("Agent connection decremented",{agentId:n,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){u.warn("Heartbeat check is already running");return}u.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,u.info("Heartbeat check stopped"));}checkHeartbeats(){let n=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:t}=this.config,s=[],i=0;for(let[a,o]of this.agents.entries()){let p=n-o.lastHeartbeat;if(p>t){s.push(a);continue}p>e&&o.status==="healthy"&&(o.status="unhealthy",i++,u.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:a,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:p,timeout:e}));}for(let a of s){let o=this.agents.get(a);o&&(u.info("Auto-deregistering agent due to timeout",{agentId:a,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:t}),this.agents.delete(a));}(i>0||s.length>0)&&u.info("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(n){let e=Math.floor(Math.random()*n.length);return n[e]}selectRoundRobin(n){this.roundRobinIndex=this.roundRobinIndex%n.length;let e=n[this.roundRobinIndex];return this.roundRobinIndex++,e}selectLeastConnections(n){return n.reduce((e,t)=>t.connectionCount<e.connectionCount?t:e)}getStats(){let n=this.getAllAgents();return {totalAgents:n.length,healthyAgents:n.filter(e=>e.status==="healthy").length,unhealthyAgents:n.filter(e=>e.status==="unhealthy").length,offlineAgents:n.filter(e=>e.status==="offline").length,totalConnections:n.reduce((e,t)=>e+t.connectionCount,0)}}setAgentStatus(n,e){let t=this.agents.get(n);t&&(t.status=e);}setLastHeartbeat(n,e){let t=this.agents.get(n);t&&(t.lastHeartbeat=e);}};chunkSIOB4FC7_cjs.a();var c=chunkP3MN336E_cjs.a.create({service:"gateway:agent-sync-manager"}),T=class{constructor(n){chunkXQVVSJRM_cjs.e(this,"config");chunkXQVVSJRM_cjs.e(this,"registry");chunkXQVVSJRM_cjs.e(this,"localNodeId");chunkXQVVSJRM_cjs.e(this,"localNodeName");chunkXQVVSJRM_cjs.e(this,"remoteNodes",new Map);chunkXQVVSJRM_cjs.e(this,"remoteAgents",new Map);chunkXQVVSJRM_cjs.e(this,"syncTimer",null);chunkXQVVSJRM_cjs.e(this,"running",false);chunkXQVVSJRM_cjs.e(this,"httpClient");this.registry=n.registry,this.localNodeId=n.localNodeId,this.localNodeName=n.localNodeName,this.config={...chunkNJHJCACX_cjs.k,...n.config},this.httpClient=n.httpClient||{fetch:globalThis.fetch.bind(globalThis)};}async start(){if(this.running){c.warn("Agent sync manager is already running");return}c.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let n of this.config.remoteNodes)this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.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,c.info("Agent sync manager started");}async stop(){if(!this.running){c.warn("Agent sync manager is not running");return}c.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,c.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[n]of this.remoteNodes.entries())try{await this.pullFromNode(n);}catch(e){c.error("Failed to pull from node",{nodeId:n,error:e.message});}}async pullFromNode(n){let e=this.remoteNodes.get(n);if(!e)throw new Error(`Unknown remote node: ${n}`);e.status="syncing";let t=this.config.remoteNodes.find(s=>s.id===n);if(!t)throw new Error(`Remote node not found in config: ${n}`);c.debug("Pulling agent list from node",{nodeId:n,address:t.address});try{let s=`http://${t.address}:${t.port}/sync/agents`,i=await this.httpClient.fetch(s,{method:"GET",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);let o=(await i.json()).agents||[];for(let p of o)p.sourceGatewayId=n,this.remoteAgents.set(p.id,p);return e.lastSyncAt=Date.now(),e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",delete e.error,c.info("Pulled agent list from node",{nodeId:n,agentCount:o.length,lastSyncAt:e.lastSyncAt}),o}catch(s){throw e.status="error",e.error=s.message,e.info.status="offline",c.error("Failed to pull from node",{nodeId:n,error:s.message}),s}}async pushEvent(n){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[t]of this.remoteNodes.entries())e.push(this.pushToNode(t,n));await Promise.allSettled(e);}async pushToNode(n,e){let t=this.config.remoteNodes.find(s=>s.id===n);if(!t){c.warn("Unknown remote node for push",{nodeId:n});return}try{let s=`http://${t.address}:${t.port}/sync/events`,i=await this.httpClient.fetch(s,{method:"POST",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId},body:JSON.stringify(e)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);c.debug("Pushed event to node",{nodeId:n,eventType:e.type});}catch(s){c.error("Failed to push to node",{nodeId:n,eventType:e.type,error:s.message});}}async handleSyncMessage(n){switch(c.debug("Received sync message",{type:n.type,sourceNodeId:n.sourceNodeId}),n.type){case "agent_list_request":await this.handleAgentListRequest(n);break;case "agent_list_response":await this.handleAgentListResponse(n);break;case "agent_register":await this.handleAgentRegister(n);break;case "agent_deregister":await this.handleAgentDeregister(n);break;case "agent_heartbeat":await this.handleAgentHeartbeat(n);break;case "agent_status_change":await this.handleAgentStatusChange(n);break;default:c.warn("Unknown sync message type",{type:n.type});}}async handleAgentListRequest(n){let e=this.getLocalAgentsForSync(),t={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:n.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(n.sourceNodeId,t);}async handleAgentListResponse(n){for(let e of n.agents)this.remoteAgents.set(e.id,e);c.info("Received agent list response",{sourceNodeId:n.sourceNodeId,agentCount:n.agents.length});}async handleAgentRegister(n){let{agent:e}=n,t=this.remoteAgents.get(e.id);if(t){let s=this.resolveConflict(t,e);this.remoteAgents.set(e.id,s);}else this.remoteAgents.set(e.id,e);c.info("Remote agent registered",{agentId:e.id,name:e.name,sourceNodeId:n.sourceNodeId});}async handleAgentDeregister(n){let{agentId:e}=n;this.remoteAgents.delete(e),c.info("Remote agent deregistered",{agentId:e,sourceNodeId:n.sourceNodeId});}async handleAgentHeartbeat(n){let{agentId:e,heartbeatAt:t,status:s}=n,i=this.remoteAgents.get(e);i&&(i.updatedAt=t,i.status=s),c.debug("Remote agent heartbeat received",{agentId:e,status:s,sourceNodeId:n.sourceNodeId});}async handleAgentStatusChange(n){let{agentId:e,newStatus:t,changedAt:s}=n,i=this.remoteAgents.get(e);i&&(i.status=t,i.updatedAt=s),c.info("Remote agent status changed",{agentId:e,newStatus:t,sourceNodeId:n.sourceNodeId});}resolveConflict(n,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>n.updatedAt?e:n;case "local":return n;case "remote":return e;default:return e.updatedAt>n.updatedAt?e:n}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(e=>({id:e.id,name:e.name,sourceGatewayId:this.localNodeId,address:e.address,capabilities:e.capabilities,status:e.status,updatedAt:e.lastHeartbeat,metadata:e.metadata}))}getMergedAgentList(){let n=new Map;for(let e of this.getLocalAgentsForSync())n.set(e.id,e);for(let[e,t]of this.remoteAgents.entries())n.has(e)||n.set(e,t);return Array.from(n.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let n=this.registry.getAllAgents(),e=0,t=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:t++;let s=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(s||0)&&(s=i.lastSyncAt);return {localAgentCount:n.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:n.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:t,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(n){this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),c.info("Remote node added",{nodeId:n.id,address:n.address});}removeRemoteNode(n){this.remoteNodes.delete(n);for(let[e,t]of this.remoteAgents.entries())t.sourceGatewayId===n&&this.remoteAgents.delete(e);c.info("Remote node removed",{nodeId:n});}};chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var l=class{constructor(){chunkXQVVSJRM_cjs.e(this,"version","1.0.0");chunkXQVVSJRM_cjs.e(this,"log");chunkXQVVSJRM_cjs.e(this,"config",null);chunkXQVVSJRM_cjs.e(this,"messageHandler",null);chunkXQVVSJRM_cjs.e(this,"_status","stopped");chunkXQVVSJRM_cjs.e(this,"lastActivity",0);}initLog(){this.log=chunkP3MN336E_cjs.a.create({service:`channel:${this.platform}`});}async start(n,e){if(this._status==="running"){this.log.warn("plugin is already running");return}this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=n,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(t)}),t}}async stop(){if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}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(n){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(n)}),n}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(n){return {healthy:false,lastCheck:Date.now(),error:n instanceof Error?n.message:String(n)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}async handleMessage(n){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:n.id});return}this.updateActivity(),await this.messageHandler.onMessage(n);}async handleEvent(n,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:n});return}await this.messageHandler.onEvent({type:n,channelId:this.id,data:e,timestamp:Date.now()});}};chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var x=class{constructor(n){chunkXQVVSJRM_cjs.e(this,"log");chunkXQVVSJRM_cjs.e(this,"config");chunkXQVVSJRM_cjs.e(this,"ws",null);chunkXQVVSJRM_cjs.e(this,"state","disconnected");chunkXQVVSJRM_cjs.e(this,"subscriptions",new Map);chunkXQVVSJRM_cjs.e(this,"messageCallbacks",new Set);chunkXQVVSJRM_cjs.e(this,"agentListCallbacks",new Set);chunkXQVVSJRM_cjs.e(this,"cachedAgentList",[]);chunkXQVVSJRM_cjs.e(this,"localAgentList",[]);chunkXQVVSJRM_cjs.e(this,"reconnectAttempts",0);chunkXQVVSJRM_cjs.e(this,"reconnectTimer",null);chunkXQVVSJRM_cjs.e(this,"heartbeatTimer",null);chunkXQVVSJRM_cjs.e(this,"agentListRequestId",null);chunkXQVVSJRM_cjs.e(this,"agentListRequestResolve",null);this.config={url:n.url,type:n.type,id:n.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:n.reconnect?.enabled??true,maxAttempts:n.reconnect?.maxAttempts??5,delay:n.reconnect?.delay??3e3},heartbeat:{enabled:n.heartbeat?.enabled??true,interval:n.heartbeat?.interval??3e4}},this.log=chunkP3MN336E_cjs.a.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((n,e)=>{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(),n();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onclose=t=>{this.handleClose(t.code,t.reason);},this.ws.onerror=t=>{this.log.error("WebSocket error",{error:String(t)}),this.state==="connecting"&&e(new Error("Connection failed"));};}catch(t){this.state="disconnected",e(t);}})}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(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:n,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:n});}async unsubscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:n,clientId:this.config.id}),this.subscriptions.delete(n),this.log.info("unsubscribed from session",{sessionId:n});}async send(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:n});}onMessage(n){this.messageCallbacks.add(n);}offMessage(n){this.messageCallbacks.delete(n);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(n){this.localAgentList=n,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((n,e)=>{let t=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=t,this.agentListRequestResolve=n,this.sendData({type:"agent_list_request",requestId:t}),setTimeout(()=>{this.agentListRequestId===t&&(this.agentListRequestId=null,this.agentListRequestResolve=null,e(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(n={}){let{localAgents:e,preferLocal:t=true,filterOffline:s=true}=n,i=e||this.localAgentList,a=this.cachedAgentList,o=this.mergeAgentLists(i,a,t);return s?o.filter(p=>p.status!=="offline"):o}onAgentListChange(n){this.agentListCallbacks.add(n);}offAgentListChange(n){this.agentListCallbacks.delete(n);}mergeAgentLists(n,e,t){let s=new Map,i=t?e:n,a=t?n:e;for(let o of i)s.set(o.id,o);for(let o of a)s.set(o.id,o);return Array.from(s.values())}updateMergedAgentList(){let n=this.getConnectableAgents({filterOffline:false});for(let e of this.agentListCallbacks)try{e(n);}catch(t){this.log.error("agent list callback error",{error:String(t)});}}handleAgentListResponse(n,e){e&&this.agentListRequestId===e&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(n),this.agentListRequestResolve=null),this.cachedAgentList=n,this.updateMergedAgentList(),this.log.debug("received agent list",{count:n.length});}sendData(n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(n));}handleMessage(n){try{let e=JSON.parse(n);switch(e.type){case "message":this.handleGatewayMessage(e.message);break;case "subscribed":this.subscriptions.set(e.sessionId,e.subscription);break;case "unsubscribed":this.subscriptions.delete(e.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(e.agents||[],e.requestId);break;case "agent_update":this.handleAgentUpdate(e.agent,e.action);break;default:this.log.debug("unknown message type",{type:e.type});}}catch(e){this.log.error("failed to parse message",{error:String(e)});}}handleAgentUpdate(n,e){switch(e){case "add":case "update":{let t=this.cachedAgentList.findIndex(s=>s.id===n.id);t>=0?this.cachedAgentList[t]=n:this.cachedAgentList.push(n);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(t=>t.id!==n.id);break}this.updateMergedAgentList();}handleGatewayMessage(n){for(let e of this.messageCallbacks)try{e(n);}catch(t){this.log.error("message callback error",{error:String(t)});}}handleClose(n,e){this.log.info("connection closed",{code:n,reason:e}),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 n=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:n}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(e){this.log.error("reconnect failed",{error:String(e)});}},n);}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 n of this.subscriptions.keys())try{await this.subscribe(n);}catch(e){this.log.error("failed to resubscribe",{sessionId:n,error:String(e)});}}};chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var y=class extends l{constructor(e="telegram-main"){super();chunkXQVVSJRM_cjs.e(this,"id");chunkXQVVSJRM_cjs.e(this,"platform","telegram");chunkXQVVSJRM_cjs.e(this,"name","Telegram Bot");chunkXQVVSJRM_cjs.e(this,"botConfig",null);chunkXQVVSJRM_cjs.e(this,"pollingInterval",null);chunkXQVVSJRM_cjs.e(this,"lastUpdateId",0);chunkXQVVSJRM_cjs.e(this,"baseUrl","");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.baseUrl=`https://api.telegram.org/bot${this.botConfig.botToken}`;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.stopPolling(),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Chat ID is required");let s=this.extractText(e);return (await this.sendMessage(t,s)).message_id.toString()}startPolling(){if(this.pollingInterval)return;let e=this.botConfig?.polling?.interval??1e3;this.pollingInterval=setInterval(async()=>{try{await this.poll();}catch(t){this.log.error("Polling error",{error:String(t)});}},e),this.log.info("Polling started",{interval:e});}stopPolling(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null,this.log.info("Polling stopped"));}async poll(){let e=await this.getUpdates(this.lastUpdateId+1,100,0);for(let t of e)this.lastUpdateId=t.update_id,t.message&&await this.handleTelegramMessage(t.message);}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return chunkNJHJCACX_cjs.c(t,"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()}})}parseContent(e){let t=[];if(e.text&&t.push({type:"text",text:e.text}),e.photo&&e.photo.length>0){let s=e.photo[e.photo.length-1];s&&t.push({type:"image",image:s.file_id,mime:"image/jpeg"});}if(e.document&&t.push({type:"file",data:e.document.file_id,mime:e.document.mime_type}),e.caption&&t.length>0){let s=t[0];s&&s.type==="text"?t[0]={type:"text",text:`${s.text}
|
|
1
|
+
'use strict';var chunkAVBAZ6OJ_cjs=require('./chunks/chunk-AVBAZ6OJ.cjs'),chunk34MFQLJP_cjs=require('./chunks/chunk-34MFQLJP.cjs'),chunk4PHQN25U_cjs=require('./chunks/chunk-4PHQN25U.cjs'),chunk5ETPYYQR_cjs=require('./chunks/chunk-5ETPYYQR.cjs'),chunkGY3SWWW3_cjs=require('./chunks/chunk-GY3SWWW3.cjs');var u=chunk5ETPYYQR_cjs.a.create({service:"gateway:agent-registry"}),P=class{constructor(n={}){chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"agents",new Map);chunkGY3SWWW3_cjs.a(this,"heartbeatTimer",null);chunkGY3SWWW3_cjs.a(this,"roundRobinIndex",0);this.config={...chunk34MFQLJP_cjs.j,...n};}async register(n){if(this.agents.has(n.id))throw new Error(`Agent with ID "${n.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),t={...n,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(n.id,t),u.info("Agent registered",{agentId:n.id,name:n.name,capabilities:n.capabilities,address:n.address,totalAgents:this.agents.size});}async deregister(n){let e=this.agents.get(n);if(!e){u.warn("Attempted to deregister unknown agent",{agentId:n});return}this.agents.delete(n),u.info("Agent deregistered",{agentId:n,name:e.name,totalAgents:this.agents.size});}async heartbeat(n,e){let t=this.agents.get(n);if(!t)throw u.warn("Heartbeat received from unknown agent",{agentId:n}),new Error(`Agent "${n}" is not registered`);t.lastHeartbeat=Date.now(),t.status="healthy",e&&(t.metadata={...t.metadata,...e}),u.debug("Agent heartbeat received",{agentId:n,lastHeartbeat:t.lastHeartbeat});}getAgent(n){return this.agents.get(n)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(n=>n.status==="healthy")}selectAgent(n){let{strategy:e,capabilities:t,healthyOnly:s=true}=n,i=s?this.getHealthyAgents():this.getAllAgents();if(t&&t.length>0&&(i=i.filter(o=>t.every(p=>o.capabilities.includes(p)))),i.length===0){u.warn("No agents available for selection",{strategy:e,capabilities:t,healthyOnly:s,totalAgents:this.agents.size});return}let a;switch(e){case "random":a=this.selectRandom(i);break;case "round-robin":a=this.selectRoundRobin(i);break;case "least-connections":a=this.selectLeastConnections(i);break;default:a=this.selectRandom(i);}return u.debug("Agent selected",{agentId:a.id,strategy:e,connectionCount:a.connectionCount}),a}incrementConnection(n){let e=this.agents.get(n);e&&(e.connectionCount++,u.debug("Agent connection incremented",{agentId:n,connectionCount:e.connectionCount}));}decrementConnection(n){let e=this.agents.get(n);e&&e.connectionCount>0&&(e.connectionCount--,u.debug("Agent connection decremented",{agentId:n,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){u.warn("Heartbeat check is already running");return}u.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,u.info("Heartbeat check stopped"));}checkHeartbeats(){let n=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:t}=this.config,s=[],i=0;for(let[a,o]of this.agents.entries()){let p=n-o.lastHeartbeat;if(p>t){s.push(a);continue}p>e&&o.status==="healthy"&&(o.status="unhealthy",i++,u.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:a,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:p,timeout:e}));}for(let a of s){let o=this.agents.get(a);o&&(u.info("Auto-deregistering agent due to timeout",{agentId:a,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:t}),this.agents.delete(a));}(i>0||s.length>0)&&u.info("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(n){let e=Math.floor(Math.random()*n.length);return n[e]}selectRoundRobin(n){this.roundRobinIndex=this.roundRobinIndex%n.length;let e=n[this.roundRobinIndex];return this.roundRobinIndex++,e}selectLeastConnections(n){return n.reduce((e,t)=>t.connectionCount<e.connectionCount?t:e)}getStats(){let n=this.getAllAgents();return {totalAgents:n.length,healthyAgents:n.filter(e=>e.status==="healthy").length,unhealthyAgents:n.filter(e=>e.status==="unhealthy").length,offlineAgents:n.filter(e=>e.status==="offline").length,totalConnections:n.reduce((e,t)=>e+t.connectionCount,0)}}setAgentStatus(n,e){let t=this.agents.get(n);t&&(t.status=e);}setLastHeartbeat(n,e){let t=this.agents.get(n);t&&(t.lastHeartbeat=e);}};var g=chunk5ETPYYQR_cjs.a.create({service:"gateway:agent-sync-manager"}),k=class{constructor(n){chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"registry");chunkGY3SWWW3_cjs.a(this,"localNodeId");chunkGY3SWWW3_cjs.a(this,"localNodeName");chunkGY3SWWW3_cjs.a(this,"remoteNodes",new Map);chunkGY3SWWW3_cjs.a(this,"remoteAgents",new Map);chunkGY3SWWW3_cjs.a(this,"syncTimer",null);chunkGY3SWWW3_cjs.a(this,"running",false);chunkGY3SWWW3_cjs.a(this,"httpClient");this.registry=n.registry,this.localNodeId=n.localNodeId,this.localNodeName=n.localNodeName,this.config={...chunk34MFQLJP_cjs.k,...n.config},this.httpClient=n.httpClient||{fetch:globalThis.fetch.bind(globalThis)};}async start(){if(this.running){g.warn("Agent sync manager is already running");return}g.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let n of this.config.remoteNodes)this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.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,g.info("Agent sync manager started");}async stop(){if(!this.running){g.warn("Agent sync manager is not running");return}g.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,g.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[n]of this.remoteNodes.entries())try{await this.pullFromNode(n);}catch(e){g.error("Failed to pull from node",{nodeId:n,error:e.message});}}async pullFromNode(n){let e=this.remoteNodes.get(n);if(!e)throw new Error(`Unknown remote node: ${n}`);e.status="syncing";let t=this.config.remoteNodes.find(s=>s.id===n);if(!t)throw new Error(`Remote node not found in config: ${n}`);g.debug("Pulling agent list from node",{nodeId:n,address:t.address});try{let s=`http://${t.address}:${t.port}/sync/agents`,i=await this.httpClient.fetch(s,{method:"GET",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);let o=(await i.json()).agents||[];for(let p of o)p.sourceGatewayId=n,this.remoteAgents.set(p.id,p);return e.lastSyncAt=Date.now(),e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",delete e.error,g.info("Pulled agent list from node",{nodeId:n,agentCount:o.length,lastSyncAt:e.lastSyncAt}),o}catch(s){throw e.status="error",e.error=s.message,e.info.status="offline",g.error("Failed to pull from node",{nodeId:n,error:s.message}),s}}async pushEvent(n){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[t]of this.remoteNodes.entries())e.push(this.pushToNode(t,n));await Promise.allSettled(e);}async pushToNode(n,e){let t=this.config.remoteNodes.find(s=>s.id===n);if(!t){g.warn("Unknown remote node for push",{nodeId:n});return}try{let s=`http://${t.address}:${t.port}/sync/events`,i=await this.httpClient.fetch(s,{method:"POST",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId},body:JSON.stringify(e)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);g.debug("Pushed event to node",{nodeId:n,eventType:e.type});}catch(s){g.error("Failed to push to node",{nodeId:n,eventType:e.type,error:s.message});}}async handleSyncMessage(n){switch(g.debug("Received sync message",{type:n.type,sourceNodeId:n.sourceNodeId}),n.type){case "agent_list_request":await this.handleAgentListRequest(n);break;case "agent_list_response":await this.handleAgentListResponse(n);break;case "agent_register":await this.handleAgentRegister(n);break;case "agent_deregister":await this.handleAgentDeregister(n);break;case "agent_heartbeat":await this.handleAgentHeartbeat(n);break;case "agent_status_change":await this.handleAgentStatusChange(n);break;default:g.warn("Unknown sync message type",{type:n.type});}}async handleAgentListRequest(n){let e=this.getLocalAgentsForSync(),t={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:n.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(n.sourceNodeId,t);}async handleAgentListResponse(n){for(let e of n.agents)this.remoteAgents.set(e.id,e);g.info("Received agent list response",{sourceNodeId:n.sourceNodeId,agentCount:n.agents.length});}async handleAgentRegister(n){let{agent:e}=n,t=this.remoteAgents.get(e.id);if(t){let s=this.resolveConflict(t,e);this.remoteAgents.set(e.id,s);}else this.remoteAgents.set(e.id,e);g.info("Remote agent registered",{agentId:e.id,name:e.name,sourceNodeId:n.sourceNodeId});}async handleAgentDeregister(n){let{agentId:e}=n;this.remoteAgents.delete(e),g.info("Remote agent deregistered",{agentId:e,sourceNodeId:n.sourceNodeId});}async handleAgentHeartbeat(n){let{agentId:e,heartbeatAt:t,status:s}=n,i=this.remoteAgents.get(e);i&&(i.updatedAt=t,i.status=s),g.debug("Remote agent heartbeat received",{agentId:e,status:s,sourceNodeId:n.sourceNodeId});}async handleAgentStatusChange(n){let{agentId:e,newStatus:t,changedAt:s}=n,i=this.remoteAgents.get(e);i&&(i.status=t,i.updatedAt=s),g.info("Remote agent status changed",{agentId:e,newStatus:t,sourceNodeId:n.sourceNodeId});}resolveConflict(n,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>n.updatedAt?e:n;case "local":return n;case "remote":return e;default:return e.updatedAt>n.updatedAt?e:n}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(e=>({id:e.id,name:e.name,sourceGatewayId:this.localNodeId,address:e.address,capabilities:e.capabilities,status:e.status,updatedAt:e.lastHeartbeat,metadata:e.metadata}))}getMergedAgentList(){let n=new Map;for(let e of this.getLocalAgentsForSync())n.set(e.id,e);for(let[e,t]of this.remoteAgents.entries())n.has(e)||n.set(e,t);return Array.from(n.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let n=this.registry.getAllAgents(),e=0,t=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:t++;let s=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(s||0)&&(s=i.lastSyncAt);return {localAgentCount:n.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:n.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:t,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(n){this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),g.info("Remote node added",{nodeId:n.id,address:n.address});}removeRemoteNode(n){this.remoteNodes.delete(n);for(let[e,t]of this.remoteAgents.entries())t.sourceGatewayId===n&&this.remoteAgents.delete(e);g.info("Remote node removed",{nodeId:n});}};var c=class{constructor(){chunkGY3SWWW3_cjs.a(this,"version","1.0.0");chunkGY3SWWW3_cjs.a(this,"log");chunkGY3SWWW3_cjs.a(this,"config",null);chunkGY3SWWW3_cjs.a(this,"messageHandler",null);chunkGY3SWWW3_cjs.a(this,"_status","stopped");chunkGY3SWWW3_cjs.a(this,"lastActivity",0);}initLog(){this.log=chunk5ETPYYQR_cjs.a.create({service:`channel:${this.platform}`});}async start(n,e){if(this._status==="running"){this.log.warn("plugin is already running");return}this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=n,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(t)}),t}}async stop(){if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}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(n){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(n)}),n}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(n){return {healthy:false,lastCheck:Date.now(),error:n instanceof Error?n.message:String(n)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}async handleMessage(n){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:n.id});return}this.updateActivity(),await this.messageHandler.onMessage(n);}async handleEvent(n,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:n});return}await this.messageHandler.onEvent({type:n,channelId:this.id,data:e,timestamp:Date.now()});}};var T=class{constructor(n){chunkGY3SWWW3_cjs.a(this,"log");chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"ws",null);chunkGY3SWWW3_cjs.a(this,"state","disconnected");chunkGY3SWWW3_cjs.a(this,"subscriptions",new Map);chunkGY3SWWW3_cjs.a(this,"messageCallbacks",new Set);chunkGY3SWWW3_cjs.a(this,"agentListCallbacks",new Set);chunkGY3SWWW3_cjs.a(this,"cachedAgentList",[]);chunkGY3SWWW3_cjs.a(this,"localAgentList",[]);chunkGY3SWWW3_cjs.a(this,"reconnectAttempts",0);chunkGY3SWWW3_cjs.a(this,"reconnectTimer",null);chunkGY3SWWW3_cjs.a(this,"heartbeatTimer",null);chunkGY3SWWW3_cjs.a(this,"agentListRequestId",null);chunkGY3SWWW3_cjs.a(this,"agentListRequestResolve",null);this.config={url:n.url,type:n.type,id:n.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:n.reconnect?.enabled??true,maxAttempts:n.reconnect?.maxAttempts??5,delay:n.reconnect?.delay??3e3},heartbeat:{enabled:n.heartbeat?.enabled??true,interval:n.heartbeat?.interval??3e4}},this.log=chunk5ETPYYQR_cjs.a.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((n,e)=>{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(),n();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onclose=t=>{this.handleClose(t.code,t.reason);},this.ws.onerror=t=>{this.log.error("WebSocket error",{error:String(t)}),this.state==="connecting"&&e(new Error("Connection failed"));};}catch(t){this.state="disconnected",e(t);}})}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(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:n,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:n});}async unsubscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:n,clientId:this.config.id}),this.subscriptions.delete(n),this.log.info("unsubscribed from session",{sessionId:n});}async send(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:n});}onMessage(n){this.messageCallbacks.add(n);}offMessage(n){this.messageCallbacks.delete(n);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(n){this.localAgentList=n,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((n,e)=>{let t=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=t,this.agentListRequestResolve=n,this.sendData({type:"agent_list_request",requestId:t}),setTimeout(()=>{this.agentListRequestId===t&&(this.agentListRequestId=null,this.agentListRequestResolve=null,e(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(n={}){let{localAgents:e,preferLocal:t=true,filterOffline:s=true}=n,i=e||this.localAgentList,a=this.cachedAgentList,o=this.mergeAgentLists(i,a,t);return s?o.filter(p=>p.status!=="offline"):o}onAgentListChange(n){this.agentListCallbacks.add(n);}offAgentListChange(n){this.agentListCallbacks.delete(n);}mergeAgentLists(n,e,t){let s=new Map,i=t?e:n,a=t?n:e;for(let o of i)s.set(o.id,o);for(let o of a)s.set(o.id,o);return Array.from(s.values())}updateMergedAgentList(){let n=this.getConnectableAgents({filterOffline:false});for(let e of this.agentListCallbacks)try{e(n);}catch(t){this.log.error("agent list callback error",{error:String(t)});}}handleAgentListResponse(n,e){e&&this.agentListRequestId===e&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(n),this.agentListRequestResolve=null),this.cachedAgentList=n,this.updateMergedAgentList(),this.log.debug("received agent list",{count:n.length});}sendData(n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(n));}handleMessage(n){try{let e=JSON.parse(n);switch(e.type){case "message":this.handleGatewayMessage(e.message);break;case "subscribed":this.subscriptions.set(e.sessionId,e.subscription);break;case "unsubscribed":this.subscriptions.delete(e.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(e.agents||[],e.requestId);break;case "agent_update":this.handleAgentUpdate(e.agent,e.action);break;default:this.log.debug("unknown message type",{type:e.type});}}catch(e){this.log.error("failed to parse message",{error:String(e)});}}handleAgentUpdate(n,e){switch(e){case "add":case "update":{let t=this.cachedAgentList.findIndex(s=>s.id===n.id);t>=0?this.cachedAgentList[t]=n:this.cachedAgentList.push(n);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(t=>t.id!==n.id);break}this.updateMergedAgentList();}handleGatewayMessage(n){for(let e of this.messageCallbacks)try{e(n);}catch(t){this.log.error("message callback error",{error:String(t)});}}handleClose(n,e){this.log.info("connection closed",{code:n,reason:e}),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 n=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:n}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(e){this.log.error("reconnect failed",{error:String(e)});}},n);}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 n of this.subscriptions.keys())try{await this.subscribe(n);}catch(e){this.log.error("failed to resubscribe",{sessionId:n,error:String(e)});}}};var m=class extends c{constructor(e="telegram-main"){super();chunkGY3SWWW3_cjs.a(this,"id");chunkGY3SWWW3_cjs.a(this,"platform","telegram");chunkGY3SWWW3_cjs.a(this,"name","Telegram Bot");chunkGY3SWWW3_cjs.a(this,"botConfig",null);chunkGY3SWWW3_cjs.a(this,"pollingInterval",null);chunkGY3SWWW3_cjs.a(this,"lastUpdateId",0);chunkGY3SWWW3_cjs.a(this,"baseUrl","");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.baseUrl=`https://api.telegram.org/bot${this.botConfig.botToken}`;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.stopPolling(),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Chat ID is required");let s=this.extractText(e);return (await this.sendMessage(t,s)).message_id.toString()}startPolling(){if(this.pollingInterval)return;let e=this.botConfig?.polling?.interval??1e3;this.pollingInterval=setInterval(async()=>{try{await this.poll();}catch(t){this.log.error("Polling error",{error:String(t)});}},e),this.log.info("Polling started",{interval:e});}stopPolling(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null,this.log.info("Polling stopped"));}async poll(){let e=await this.getUpdates(this.lastUpdateId+1,100,0);for(let t of e)this.lastUpdateId=t.update_id,t.message&&await this.handleTelegramMessage(t.message);}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return chunk34MFQLJP_cjs.c(t,"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()}})}parseContent(e){let t=[];if(e.text&&t.push({type:"text",text:e.text}),e.photo&&e.photo.length>0){let s=e.photo[e.photo.length-1];s&&t.push({type:"image",image:s.file_id,mime:"image/jpeg"});}if(e.document&&t.push({type:"file",data:e.document.file_id,mime:e.document.mime_type}),e.caption&&t.length>0){let s=t[0];s&&s.type==="text"?t[0]={type:"text",text:`${s.text}
|
|
2
2
|
|
|
3
3
|
${e.caption}`}:t.unshift({type:"text",text:e.caption});}return t}getSessionId(e){let t=e.chat.id.toString(),s=e.from?.id.toString();return e.chat.type==="private"?`telegram_${this.id}_${t}`:`telegram_${this.id}_${t}_${s}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
|
|
4
|
-
`)}async getMe(){return (await this.request("getMe")).result}async getUpdates(e,t,s){return (await this.request("getUpdates",{offset:e,limit:t,timeout:s})).result||[]}async sendMessage(e,t){return (await this.request("sendMessage",{chat_id:e,text:t,parse_mode:"Markdown"})).result}async request(e,t={}){let s=`${this.baseUrl}/${e}`,a=await(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(!a.ok)throw new Error(`Telegram API error: ${a.description}`);return a}};
|
|
5
|
-
`)}async getCurrentUser(){return this.request("GET","/users/@me")}async getGatewayBot(){return this.request("GET","/gateway/bot")}async createMessage(e,t,s){let i={content:t};return s&&(i.message_reference={message_id:s}),this.request("POST",`/channels/${e}/messages`,i)}async request(e,t,s){let i=`${this.baseUrl}${t}`,a=await fetch(i,{method:e,headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0});if(!a.ok){let o=await a.text();throw new Error(`Discord API error: ${o}`)}return a.json()}};
|
|
6
|
-
`)}async authTest(){return await this.request("auth.test")}async postMessage(e,t,s){let i={channel:e,text:t};return s&&(i.thread_ts=s),await this.request("chat.postMessage",i)}async request(e,t={}){let s=`${this.baseUrl}/${e}`,a=await(await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${this.botConfig?.botToken}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(t)})).json();if(!a.ok)throw new Error(`Slack API error: ${a.error}`);return a}};
|
|
4
|
+
`)}async getMe(){return (await this.request("getMe")).result}async getUpdates(e,t,s){return (await this.request("getUpdates",{offset:e,limit:t,timeout:s})).result||[]}async sendMessage(e,t){return (await this.request("sendMessage",{chat_id:e,text:t,parse_mode:"Markdown"})).result}async request(e,t={}){let s=`${this.baseUrl}/${e}`,a=await(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(!a.ok)throw new Error(`Telegram API error: ${a.description}`);return a}};var y=class extends c{constructor(e="discord-main"){super();chunkGY3SWWW3_cjs.a(this,"id");chunkGY3SWWW3_cjs.a(this,"platform","discord");chunkGY3SWWW3_cjs.a(this,"name","Discord Bot");chunkGY3SWWW3_cjs.a(this,"botConfig",null);chunkGY3SWWW3_cjs.a(this,"baseUrl","https://discord.com/api/v10");chunkGY3SWWW3_cjs.a(this,"gatewayWs",null);chunkGY3SWWW3_cjs.a(this,"heartbeatInterval",null);chunkGY3SWWW3_cjs.a(this,"sessionId",null);chunkGY3SWWW3_cjs.a(this,"sequenceNumber",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");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.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.gatewayWs&&(this.gatewayWs.close(),this.gatewayWs=null),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Channel ID is required");let s=this.extractText(e);return (await this.createMessage(t,s,e.metadata.context?.replyTo)).id}async startGateway(){let t=`${(await this.getGatewayBot()).url}/?v=10&encoding=json`;this.gatewayWs=new WebSocket(t),this.gatewayWs.onmessage=s=>{this.handleGatewayMessage(JSON.parse(s.data.toString()));},this.gatewayWs.onclose=()=>{this.log.info("Gateway disconnected"),setTimeout(()=>this.startGateway(),5e3);},this.gatewayWs.onerror=s=>{this.log.error("Gateway error",{error:String(s)});};}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,t){e==="MESSAGE_CREATE"&&this.handleDiscordMessage(t);}async handleDiscordMessage(e){if(e.author.bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return chunk34MFQLJP_cjs.c(t,"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 t=[];e.content&&t.push({type:"text",text:e.content});for(let s of e.attachments)s.content_type?.startsWith("image/")?t.push({type:"image",image:s.url,mime:s.content_type}):t.push({type:"file",data:s.url,mime:s.content_type});return t}getSessionId(e){let t=e.channel_id,s=e.author.id;return `discord_${this.id}_${t}_${s}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
|
|
5
|
+
`)}async getCurrentUser(){return this.request("GET","/users/@me")}async getGatewayBot(){return this.request("GET","/gateway/bot")}async createMessage(e,t,s){let i={content:t};return s&&(i.message_reference={message_id:s}),this.request("POST",`/channels/${e}/messages`,i)}async request(e,t,s){let i=`${this.baseUrl}${t}`,a=await fetch(i,{method:e,headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0});if(!a.ok){let o=await a.text();throw new Error(`Discord API error: ${o}`)}return a.json()}};var b=class extends c{constructor(e="slack-main"){super();chunkGY3SWWW3_cjs.a(this,"id");chunkGY3SWWW3_cjs.a(this,"platform","slack");chunkGY3SWWW3_cjs.a(this,"name","Slack Bot");chunkGY3SWWW3_cjs.a(this,"botConfig",null);chunkGY3SWWW3_cjs.a(this,"baseUrl","");chunkGY3SWWW3_cjs.a(this,"socketModeClient",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.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.socketModeClient&&(this.socketModeClient.close(),this.socketModeClient=null),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Channel ID is required");let s=this.extractText(e);return (await this.postMessage(t,s,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 t=>{try{let s=JSON.parse(t.data.toString());await this.handleSocketModeEvent(s);}catch(s){this.log.error("Socket mode event error",{error:String(s)});}},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 t=e.payload.event;t.type==="message"&&!t.subtype&&await this.handleSlackMessage(t);}}async handleSlackMessage(e){this.updateActivity();let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return chunk34MFQLJP_cjs.c(t,"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 t=[];if(e.text&&t.push({type:"text",text:e.text}),e.files)for(let s of e.files)t.push({type:"file",data:s.url_private,mime:s.mimetype});return t}getSessionId(e){let t=e.channel,s=e.user;return `slack_${this.id}_${t}_${s}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
|
|
6
|
+
`)}async authTest(){return await this.request("auth.test")}async postMessage(e,t,s){let i={channel:e,text:t};return s&&(i.thread_ts=s),await this.request("chat.postMessage",i)}async request(e,t={}){let s=`${this.baseUrl}/${e}`,a=await(await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${this.botConfig?.botToken}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(t)})).json();if(!a.ok)throw new Error(`Slack API error: ${a.error}`);return a}};var C=class extends c{constructor(e="feishu-main"){super();chunkGY3SWWW3_cjs.a(this,"id");chunkGY3SWWW3_cjs.a(this,"platform","feishu");chunkGY3SWWW3_cjs.a(this,"name","Feishu Bot");chunkGY3SWWW3_cjs.a(this,"botConfig",null);chunkGY3SWWW3_cjs.a(this,"baseUrl","https://open.feishu.cn/open-apis");chunkGY3SWWW3_cjs.a(this,"tenantAccessToken",null);chunkGY3SWWW3_cjs.a(this,"tokenExpireTime",0);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");await this.refreshTenantAccessToken(),this.log.info("Feishu bot connected",{app_id:this.botConfig.appId});}async doStop(){this.botConfig=null,this.tenantAccessToken=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Chat ID is required");await this.ensureTokenValid();let s=this.extractText(e);return (await this.sendMessage(t,s)).message_id}async handleWebhookEvent(e){if(this.updateActivity(),this.botConfig?.verificationToken,e.event?.message){let t=this.toGatewayMessage(e);await this.handleMessage(t);}}toGatewayMessage(e){let t=e.event.message,s=this.getSessionId(e);return chunk34MFQLJP_cjs.c(s,"input",this.parseContent(t),{channel:{platform:"feishu",channelId:this.id,userId:t.sender.sender_id.open_id,chatId:t.chat_id,messageId:t.message_id,rootId:t.root_id,parentId:t.parent_id,tenantKey:e.tenant_key},context:{threadId:t.root_id,conversationId:t.chat_id}})}parseContent(e){let t=[];try{let s=JSON.parse(e.content);switch(e.message_type){case "text":s.text&&t.push({type:"text",text:s.text});break;case "post":if(s.content){let i=this.extractPostContent(s.content);t.push({type:"text",text:i});}break;case "image":s.image_key&&t.push({type:"image",image:s.image_key,mime:"image/jpeg"});break;case "file":s.file_key&&t.push({type:"file",data:s.file_key,mime:s.file_type});break;default:t.push({type:"text",text:JSON.stringify(s)});}}catch{t.push({type:"text",text:e.content});}return t}extractPostContent(e){let t=[];for(let s of e)if(typeof s=="object"&&s!==null){let i=s;i.text&&t.push(String(i.text)),Array.isArray(i.children)&&t.push(this.extractPostContent(i.children));}return t.join(`
|
|
7
7
|
`)}getSessionId(e){let t=e.event.message,s=t.chat_id,i=t.sender.sender_id.open_id;return `feishu_${this.id}_${s}_${i}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
|
|
8
|
-
`)}async refreshTenantAccessToken(){let t=await(await fetch(`${this.baseUrl}/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:this.botConfig?.appId,app_secret:this.botConfig?.appSecret})})).json();if(t.code!==0)throw new Error(`Feishu API error: ${t.msg}`);this.tenantAccessToken=t.tenant_access_token,this.tokenExpireTime=Date.now()+t.expire*1e3-6e4;}async ensureTokenValid(){(!this.tenantAccessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshTenantAccessToken();}async sendMessage(e,t){let i=await(await fetch(`${this.baseUrl}/im/v1/messages?receive_id_type=chat_id`,{method:"POST",headers:{Authorization:`Bearer ${this.tenantAccessToken}`,"Content-Type":"application/json"},body:JSON.stringify({receive_id:e,msg_type:"text",content:JSON.stringify({text:t})})})).json();if(i.code!==0)throw new Error(`Feishu API error: ${i.msg}`);return i.data}};
|
|
9
|
-
`)}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 s=await(await fetch(e)).json();if(s.errcode&&s.errcode!==0)throw new Error(`WeChat API error: ${s.errmsg}`);this.accessToken=s.access_token,this.tokenExpireTime=Date.now()+s.expires_in*1e3-6e4;}async ensureTokenValid(){(!this.accessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshAccessToken();}async sendOfficialMessage(e,t){let i=await(await fetch(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({touser:e,msgtype:"text",text:{content:t}})})).json();if(i.errcode!==0)throw new Error(`WeChat API error: ${i.errmsg}`);return i.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,t){let i=await(await fetch(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${this.accessToken}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({touser:e,msgtype:"text",agentid:this.botConfig?.agentId,text:{content:t}})})).json();if(i.errcode!==0)throw new Error(`WeCom API error: ${i.errmsg}`);return i.msgid??Date.now().toString()}};
|
|
10
|
-
`)}async getAccountInfo(){return await this.request("GET",`/v1/accounts/${this.botConfig?.phoneNumber}`)}async receiveMessages(e){let t=e>0?`?since=${e}`:"";return await this.request("GET",`/v1/receive/${this.botConfig?.phoneNumber}${t}`)||[]}async sendMessage(e,t){return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:t})}async request(e,t,s){let i=`${this.botConfig?.serviceUrl}${t}`,a={"Content-Type":"application/json"};this.botConfig?.password&&(a.Authorization=`Basic ${Buffer.from(`${this.botConfig.phoneNumber}:${this.botConfig.password}`).toString("base64")}`);let o=await fetch(i,{method:e,headers:a,body:s?JSON.stringify(s):void 0});if(!o.ok){let p=await o.text();throw new Error(`Signal API error: ${p}`)}return o.json()}};
|
|
11
|
-
`)}subscribeToRelay(e,t,s){let i=["REQ",t,s];e.send(JSON.stringify(i));}async createEvent(e,t){let s=[];t&&s.push(["e",t]);let i={id:"",pubkey:this.botConfig?.publicKey??"",created_at:Math.floor(Date.now()/1e3),kind:1,tags:s,content:e,sig:""};return i.id=await this.computeEventId(i),i.sig=await this.signEvent(i),i}async computeEventId(e){let t=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),i=new TextEncoder().encode(t),a=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(a)).map(p=>p.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 t=["EVENT",e];for(let s of this.relayConnections.values())s.readyState===WebSocket.OPEN&&s.send(JSON.stringify(t));}};
|
|
8
|
+
`)}async refreshTenantAccessToken(){let t=await(await fetch(`${this.baseUrl}/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:this.botConfig?.appId,app_secret:this.botConfig?.appSecret})})).json();if(t.code!==0)throw new Error(`Feishu API error: ${t.msg}`);this.tenantAccessToken=t.tenant_access_token,this.tokenExpireTime=Date.now()+t.expire*1e3-6e4;}async ensureTokenValid(){(!this.tenantAccessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshTenantAccessToken();}async sendMessage(e,t){let i=await(await fetch(`${this.baseUrl}/im/v1/messages?receive_id_type=chat_id`,{method:"POST",headers:{Authorization:`Bearer ${this.tenantAccessToken}`,"Content-Type":"application/json"},body:JSON.stringify({receive_id:e,msg_type:"text",content:JSON.stringify({text:t})})})).json();if(i.code!==0)throw new Error(`Feishu API error: ${i.msg}`);return i.data}};var v=class extends c{constructor(e="wechat-main"){super();chunkGY3SWWW3_cjs.a(this,"id");chunkGY3SWWW3_cjs.a(this,"platform","wechat");chunkGY3SWWW3_cjs.a(this,"name","WeChat Bot");chunkGY3SWWW3_cjs.a(this,"botConfig",null);chunkGY3SWWW3_cjs.a(this,"accessToken",null);chunkGY3SWWW3_cjs.a(this,"tokenExpireTime",0);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");await this.refreshAccessToken(),this.log.info("WeChat bot connected",{app_id:this.botConfig.appId,mode:this.botConfig.mode});}async doStop(){this.botConfig=null,this.accessToken=null;}async send(e){let t=e.metadata.channel.userId;if(!t)throw new Error("User ID is required");await this.ensureTokenValid();let s=this.extractText(e);return this.botConfig?.mode==="wecom"?await this.sendWeComMessage(t,s):await this.sendOfficialMessage(t,s)}async handleWebhookMessage(e){this.updateActivity();let t=this.parseXmlMessage(e);if(t){let s=this.toGatewayMessage(t);await this.handleMessage(s);}}parseXmlMessage(e){let t=a=>e.match(new RegExp(`<${a}><!\\[CDATA\\[(.*?)\\]\\]></${a}>`))?.[1],s=a=>{let o=e.match(new RegExp(`<${a}>(\\d+)</${a}>`));return o?.[1]?parseInt(o[1],10):void 0},i=t("MsgType");return i?{ToUserName:t("ToUserName")??"",FromUserName:t("FromUserName")??"",CreateTime:s("CreateTime")??0,MsgType:i,Content:t("Content"),MsgId:s("MsgId"),PicUrl:t("PicUrl"),MediaId:t("MediaId")}:null}toGatewayMessage(e){let t=this.getSessionId(e);return chunk34MFQLJP_cjs.c(t,"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 t=[];switch(e.MsgType){case "text":e.Content&&t.push({type:"text",text:e.Content});break;case "image":(e.PicUrl||e.MediaId)&&t.push({type:"image",image:e.PicUrl??e.MediaId??"",mime:"image/jpeg"});break;case "voice":e.MediaId&&t.push({type:"file",data:e.MediaId,mime:"audio/amr"}),"Recognition"in e&&e.Recognition&&t.push({type:"text",text:e.Recognition});break;case "video":case "shortvideo":e.MediaId&&t.push({type:"file",data:e.MediaId,mime:"video/mp4"});break;default:e.Content&&t.push({type:"text",text:e.Content});}return t}getSessionId(e){let t=e.FromUserName;return `wechat_${this.id}_${t}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
|
|
9
|
+
`)}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 s=await(await fetch(e)).json();if(s.errcode&&s.errcode!==0)throw new Error(`WeChat API error: ${s.errmsg}`);this.accessToken=s.access_token,this.tokenExpireTime=Date.now()+s.expires_in*1e3-6e4;}async ensureTokenValid(){(!this.accessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshAccessToken();}async sendOfficialMessage(e,t){let i=await(await fetch(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({touser:e,msgtype:"text",text:{content:t}})})).json();if(i.errcode!==0)throw new Error(`WeChat API error: ${i.errmsg}`);return i.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,t){let i=await(await fetch(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${this.accessToken}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({touser:e,msgtype:"text",agentid:this.botConfig?.agentId,text:{content:t}})})).json();if(i.errcode!==0)throw new Error(`WeCom API error: ${i.errmsg}`);return i.msgid??Date.now().toString()}};var w=class extends c{constructor(e="webchat-main"){super();chunkGY3SWWW3_cjs.a(this,"id");chunkGY3SWWW3_cjs.a(this,"platform","webchat");chunkGY3SWWW3_cjs.a(this,"name","WebChat");chunkGY3SWWW3_cjs.a(this,"webChatConfig",null);chunkGY3SWWW3_cjs.a(this,"connections",new Map);chunkGY3SWWW3_cjs.a(this,"heartbeatInterval",null);chunkGY3SWWW3_cjs.a(this,"wsServer",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");this.webChatConfig=this.config.platform,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 chunk34MFQLJP_cjs.r(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.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;}async send(e){let t=e.sessionId,s=e.metadata.channel.userId;if(this.wsServer&&t){let o={type:"message",sessionId:t,properties:{sessionID:t,content:e.content,timestamp:e.timestamp||Date.now()}};return this.wsServer.broadcastToSession(t,o),e.id}if(!s)throw new Error("User ID is required");let i=this.findConnectionByUser(s);if(!i)throw new Error("User not connected");let a={type:"message",sessionId:t,content:e.content,metadata:e.metadata};return i.ws.send(JSON.stringify(a)),i.lastActivity=Date.now(),e.id}pushEvent(e,t){this.wsServer&&this.wsServer.broadcastToSession(e,t);}getWebSocketServer(){return this.wsServer}async handleConnection(e,t){let s=this.generateConnectionId();if(this.connections.size>=(this.webChatConfig?.maxConnections??1e3)){e.close(1013,"Maximum connections reached");return}let i={id:s,ws:e,userId:t,lastActivity:Date.now()};this.connections.set(s,i),e.onmessage=a=>{this.handleWebSocketMessage(i,a.data.toString());},e.onclose=()=>{this.connections.delete(s),this.log.debug("WebSocket closed",{connId:s,userId:t});},e.onerror=a=>{this.log.error("WebSocket error",{connId:s,userId:t,error:String(a)});},this.log.info("WebSocket connected",{connId:s,userId:t});}async handleWebSocketMessage(e,t){this.updateActivity(),e.lastActivity=Date.now();try{let s=JSON.parse(t);switch(s.type){case "message":await this.handleChatMessage(e,s);break;case "ping":e.ws.send(JSON.stringify({type:"pong"}));break;case "subscribe":s.sessionId&&(e.sessionId=s.sessionId);break;case "unsubscribe":e.sessionId=void 0;break}}catch(s){this.log.error("Failed to handle WebSocket message",{error:String(s)});}}async handleChatMessage(e,t){if(!t.content||!t.sessionId)return;let s=chunk34MFQLJP_cjs.c(t.sessionId,"input",t.content,{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:t.sessionId,connectionId:e.id},context:{conversationId:t.sessionId},...t.metadata});await this.handleMessage(s);}startHeartbeat(){let e=this.webChatConfig?.heartbeatInterval??3e4;this.heartbeatInterval=setInterval(()=>{let t=Date.now(),s=this.webChatConfig?.connectionTimeout??6e4;for(let[i,a]of this.connections)t-a.lastActivity>s&&(this.log.info("Closing inactive connection",{connId:i}),a.ws.close(1001,"Connection timeout"),this.connections.delete(i));},e);}findConnectionByUser(e){for(let t of this.connections.values())if(t.userId===e)return t}generateConnectionId(){return `conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}getConnectionCount(){return this.connections.size}getWsServerConnectionCount(){return this.wsServer?.getConnectionCount()??0}};var S=class extends c{constructor(e="signal-main"){super();chunkGY3SWWW3_cjs.a(this,"id");chunkGY3SWWW3_cjs.a(this,"platform","signal");chunkGY3SWWW3_cjs.a(this,"name","Signal Bot");chunkGY3SWWW3_cjs.a(this,"botConfig",null);chunkGY3SWWW3_cjs.a(this,"pollingInterval",null);chunkGY3SWWW3_cjs.a(this,"lastTimestamp",0);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");let e=await this.getAccountInfo();this.log.info("Signal bot connected",{number:this.botConfig.phoneNumber,address:e.address}),this.startPolling();}async doStop(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.botConfig=null;}async send(e){let t=e.metadata.channel.userId;if(!t)throw new Error("Recipient is required");let s=this.extractText(e);return (await this.sendMessage(t,s)).timestamp.toString()}startPolling(){this.pollingInterval=setInterval(async()=>{try{await this.poll();}catch(t){this.log.error("Polling error",{error:String(t)});}},5e3),this.log.info("Polling started",{interval:5e3});}async poll(){let e=await this.receiveMessages(this.lastTimestamp);for(let t of e)this.lastTimestamp=t.envelope.timestamp,t.envelope.dataMessage&&await this.handleSignalMessage(t);}async handleSignalMessage(e){this.updateActivity();let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e),s=e.envelope.dataMessage;return chunk34MFQLJP_cjs.c(t,"input",this.parseContent(s),{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 t=[];if(!e)return t;if(e.message&&t.push({type:"text",text:e.message}),e.attachments)for(let s of e.attachments)s.contentType.startsWith("image/")?t.push({type:"image",image:s.id,mime:s.contentType}):t.push({type:"file",data:s.id,mime:s.contentType});return t}getSessionId(e){let t=e.envelope.sourceNumber;return `signal_${this.id}_${t}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
|
|
10
|
+
`)}async getAccountInfo(){return await this.request("GET",`/v1/accounts/${this.botConfig?.phoneNumber}`)}async receiveMessages(e){let t=e>0?`?since=${e}`:"";return await this.request("GET",`/v1/receive/${this.botConfig?.phoneNumber}${t}`)||[]}async sendMessage(e,t){return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:t})}async request(e,t,s){let i=`${this.botConfig?.serviceUrl}${t}`,a={"Content-Type":"application/json"};this.botConfig?.password&&(a.Authorization=`Basic ${Buffer.from(`${this.botConfig.phoneNumber}:${this.botConfig.password}`).toString("base64")}`);let o=await fetch(i,{method:e,headers:a,body:s?JSON.stringify(s):void 0});if(!o.ok){let p=await o.text();throw new Error(`Signal API error: ${p}`)}return o.json()}};var A=class extends c{constructor(e="nostr-main"){super();chunkGY3SWWW3_cjs.a(this,"id");chunkGY3SWWW3_cjs.a(this,"platform","nostr");chunkGY3SWWW3_cjs.a(this,"name","Nostr Bot");chunkGY3SWWW3_cjs.a(this,"botConfig",null);chunkGY3SWWW3_cjs.a(this,"relayConnections",new Map);chunkGY3SWWW3_cjs.a(this,"subscriptions",new Map);chunkGY3SWWW3_cjs.a(this,"eventHandlers",new Map);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");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(){for(let[e,t]of this.relayConnections)t.close();this.relayConnections.clear(),this.subscriptions.clear(),this.eventHandlers.clear(),this.botConfig=null;}async send(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required for sending messages");let t=this.extractText(e),s=await this.createEvent(t,e.metadata.context?.replyTo);return await this.publishEvent(s),s.id}async connectToRelay(e){let t=new WebSocket(e);t.onopen=()=>{this.log.info("Connected to relay",{relay:e});for(let[s,i]of this.subscriptions)this.subscribeToRelay(t,s,i);},t.onmessage=s=>{this.handleRelayMessage(e,s.data.toString());},t.onclose=()=>{this.log.info("Disconnected from relay",{relay:e}),this.relayConnections.delete(e),setTimeout(()=>this.connectToRelay(e),5e3);},t.onerror=s=>{this.log.error("Relay error",{relay:e,error:String(s)});},this.relayConnections.set(e,t);}handleRelayMessage(e,t){this.updateActivity();try{let s=JSON.parse(t);if(s[0]==="EVENT"&&s[2]){let i=s[2];this.handleNostrEvent(i);}if(s[0]==="OK"){let i=s[1],a=s[2];this.log.debug("Event published",{eventId:i,success:a});}}catch(s){this.log.error("Failed to handle relay message",{error:String(s)});}return Promise.resolve()}async handleNostrEvent(e){if(e.kind!==1||e.pubkey===this.botConfig?.publicKey)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return chunk34MFQLJP_cjs.c(t,"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 t=[];e.content&&t.push({type:"text",text:e.content});for(let s of e.tags)if(s[0]==="url"&&s[1]){let i=s[1];i.match(/\.(jpg|jpeg|png|gif|webp)$/i)&&t.push({type:"image",image:i});}return t}findReplyTo(e){for(let t of e)if(t[0]==="e"&&t[1])return t[1]}getSessionId(e){return `nostr_${this.id}_${e.pubkey}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
|
|
11
|
+
`)}subscribeToRelay(e,t,s){let i=["REQ",t,s];e.send(JSON.stringify(i));}async createEvent(e,t){let s=[];t&&s.push(["e",t]);let i={id:"",pubkey:this.botConfig?.publicKey??"",created_at:Math.floor(Date.now()/1e3),kind:1,tags:s,content:e,sig:""};return i.id=await this.computeEventId(i),i.sig=await this.signEvent(i),i}async computeEventId(e){let t=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),i=new TextEncoder().encode(t),a=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(a)).map(p=>p.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 t=["EVENT",e];for(let s of this.relayConnections.values())s.readyState===WebSocket.OPEN&&s.send(JSON.stringify(t));}};var x=class extends c{constructor(e){super();chunkGY3SWWW3_cjs.a(this,"id");chunkGY3SWWW3_cjs.a(this,"platform");chunkGY3SWWW3_cjs.a(this,"name");chunkGY3SWWW3_cjs.a(this,"version");chunkGY3SWWW3_cjs.a(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 t=e;this.options.actions?.beforeSend&&(t=await this.options.actions.beforeSend(e));let s=await this.options.messaging.send(t);return this.options.actions?.afterSend&&await this.options.actions.afterSend(t,s),s}async healthCheck(){return this.options.status?.healthCheck?{healthy:await this.options.status.healthCheck(),lastCheck:Date.now()}:{healthy:true,lastCheck:Date.now()}}};function N(l){return new x(l)}var R={telegram:m,discord:y,slack:b,feishu:C,wechat:v,webchat:w,signal:S,nostr:A};function Ee(){return Object.keys(R)}async function Sn(l){let{Log:n}=await import('./chunks/log-B5SORET6.cjs'),e=false;await n.init({logDir:l.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:l.print??false,dev:l.dev??e,level:l.level??("INFO")});}Object.defineProperty(exports,"Gateway",{enumerable:true,get:function(){return chunkAVBAZ6OJ_cjs.a}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.q}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.j}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.l}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.k}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.i}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.h}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.s}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.p}});Object.defineProperty(exports,"MessageLockManager",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.a}});Object.defineProperty(exports,"MessageRetryManager",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.b}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.m}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.n}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.o}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.f}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.c}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.d}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.e}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunk34MFQLJP_cjs.g}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.p}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.k}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.j}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.h}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.o}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.m}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.c}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.l}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.s}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.r}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.i}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.n}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.g}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.q}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.f}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.b}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.a}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.d}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.e}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.z}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.G}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.J}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.C}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.F}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.K}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.x}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.A}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.D}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.L}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.I}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.M}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.E}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.B}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.H}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.y}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.w}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.u}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunk4PHQN25U_cjs.t}});exports.AgentRegistry=P;exports.AgentSyncManager=k;exports.BaseChannelPlugin=c;exports.ChannelPluginRegistry=R;exports.DiscordPlugin=y;exports.FeishuPlugin=C;exports.GatewayClient=T;exports.NostrPlugin=A;exports.SignalPlugin=S;exports.SlackPlugin=b;exports.TelegramPlugin=m;exports.WeChatPlugin=v;exports.WebChatPlugin=w;exports.createChannelPlugin=N;exports.getSupportedPlatforms=Ee;exports.initLog=Sn;
|
package/dist/index.d.cts
CHANGED
|
@@ -262,8 +262,8 @@ declare const AuthConfigSchema: z.ZodObject<{
|
|
|
262
262
|
type AuthConfig = z.infer<typeof AuthConfigSchema>;
|
|
263
263
|
declare const AgentSyncConfigSchema: z.ZodObject<{
|
|
264
264
|
mode: z.ZodDefault<z.ZodEnum<{
|
|
265
|
-
pull: "pull";
|
|
266
265
|
push: "push";
|
|
266
|
+
pull: "pull";
|
|
267
267
|
both: "both";
|
|
268
268
|
}>>;
|
|
269
269
|
interval: z.ZodDefault<z.ZodNumber>;
|
|
@@ -297,8 +297,8 @@ declare const GatewayClusterConfigSchema: z.ZodObject<{
|
|
|
297
297
|
}, z.core.$strip>>>;
|
|
298
298
|
sync: z.ZodOptional<z.ZodObject<{
|
|
299
299
|
mode: z.ZodDefault<z.ZodEnum<{
|
|
300
|
-
pull: "pull";
|
|
301
300
|
push: "push";
|
|
301
|
+
pull: "pull";
|
|
302
302
|
both: "both";
|
|
303
303
|
}>>;
|
|
304
304
|
interval: z.ZodDefault<z.ZodNumber>;
|
|
@@ -545,8 +545,8 @@ declare const GatewayConfigSchema: z.ZodObject<{
|
|
|
545
545
|
}, z.core.$strip>>>;
|
|
546
546
|
sync: z.ZodOptional<z.ZodObject<{
|
|
547
547
|
mode: z.ZodDefault<z.ZodEnum<{
|
|
548
|
-
pull: "pull";
|
|
549
548
|
push: "push";
|
|
549
|
+
pull: "pull";
|
|
550
550
|
both: "both";
|
|
551
551
|
}>>;
|
|
552
552
|
interval: z.ZodDefault<z.ZodNumber>;
|
|
@@ -791,54 +791,7 @@ interface RouteResult {
|
|
|
791
791
|
}
|
|
792
792
|
declare function generateSubscriptionId(subscriberId: string, sessionId: string): string;
|
|
793
793
|
|
|
794
|
-
declare const DEFAULT_WEBSOCKET_SERVER_CONFIG:
|
|
795
|
-
enabled: boolean;
|
|
796
|
-
port: number;
|
|
797
|
-
hostname: string;
|
|
798
|
-
path: string;
|
|
799
|
-
maxConnections: number;
|
|
800
|
-
connectionTimeout: number;
|
|
801
|
-
heartbeatInterval: number;
|
|
802
|
-
sessionExpireMs: number;
|
|
803
|
-
cors: boolean;
|
|
804
|
-
mdns: boolean;
|
|
805
|
-
mdnsDomain: string;
|
|
806
|
-
https?: {
|
|
807
|
-
enabled: boolean;
|
|
808
|
-
cert: string;
|
|
809
|
-
key: string;
|
|
810
|
-
forceRedirect: boolean;
|
|
811
|
-
httpPort: number;
|
|
812
|
-
certPath?: string | undefined;
|
|
813
|
-
keyPath?: string | undefined;
|
|
814
|
-
ca?: string | undefined;
|
|
815
|
-
} | undefined;
|
|
816
|
-
auth?: {
|
|
817
|
-
type: "token" | "oauth2";
|
|
818
|
-
token?: {
|
|
819
|
-
enabled: boolean;
|
|
820
|
-
tokens: {
|
|
821
|
-
name: string;
|
|
822
|
-
value: string;
|
|
823
|
-
permissions: string[];
|
|
824
|
-
expiresAt?: number | undefined;
|
|
825
|
-
description?: string | undefined;
|
|
826
|
-
}[];
|
|
827
|
-
onInvalid: "reject" | "anonymous";
|
|
828
|
-
allowAnonymous: boolean;
|
|
829
|
-
defaultPermissions: string[];
|
|
830
|
-
} | undefined;
|
|
831
|
-
oauth2?: {
|
|
832
|
-
enabled: boolean;
|
|
833
|
-
authorizationServer: string;
|
|
834
|
-
clientId: string;
|
|
835
|
-
clientSecret: string;
|
|
836
|
-
tokenValidationEndpoint: string;
|
|
837
|
-
scope: string[];
|
|
838
|
-
} | undefined;
|
|
839
|
-
} | undefined;
|
|
840
|
-
corsOrigins?: string[] | undefined;
|
|
841
|
-
}>;
|
|
794
|
+
declare const DEFAULT_WEBSOCKET_SERVER_CONFIG: GatewayServerConfig;
|
|
842
795
|
type ClientMessageType = 'initialize' | 'subscribe' | 'unsubscribe' | 'message' | 'ping' | 'interrupt' | 'releaseSubscription' | 'agent_list_request' | 'agent_subscribe';
|
|
843
796
|
type ServerMessageType = 'connected' | 'initialize_response' | 'subscribed' | 'unsubscribed' | 'event' | 'response' | 'error' | 'pong' | 'interrupted' | 'session_closed' | 'subscriptionReleased' | 'agent_list_response' | 'agent_update';
|
|
844
797
|
interface WebSocketMessageBase {
|
|
@@ -1750,6 +1703,7 @@ declare class GatewayServer implements IGatewayServer {
|
|
|
1750
1703
|
private sessionManager;
|
|
1751
1704
|
private pluginLoader;
|
|
1752
1705
|
private messageStore;
|
|
1706
|
+
private wsServer;
|
|
1753
1707
|
private running;
|
|
1754
1708
|
private connections;
|
|
1755
1709
|
constructor(config: GatewayServerConfig$1);
|
|
@@ -2235,4 +2189,12 @@ declare function createChannelPlugin<TConfig = unknown, TProbe = unknown>(option
|
|
|
2235
2189
|
declare const ChannelPluginRegistry: Record<string, new (id?: string) => ChannelPlugin>;
|
|
2236
2190
|
declare function getSupportedPlatforms(): string[];
|
|
2237
2191
|
|
|
2238
|
-
|
|
2192
|
+
declare function initLog(options: {
|
|
2193
|
+
print: boolean;
|
|
2194
|
+
logDir: string;
|
|
2195
|
+
logFile?: string;
|
|
2196
|
+
dev?: boolean;
|
|
2197
|
+
level?: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
|
|
2198
|
+
}): Promise<void>;
|
|
2199
|
+
|
|
2200
|
+
export { type AgentDeregisterMessage, type AgentHealthStatus, type AgentHeartbeat, type AgentHeartbeatSyncMessage, type AgentListRequestMessage, type AgentListResponseMessage, type AgentRegisterMessage, type AgentRegistration, type AgentRegistrationRequest, AgentRegistry, type AgentRegistryConfig, AgentRegistryConfigSchema, type AgentRegistryStats, type AgentSelectionOptions, type AgentSelectionRecord, type AgentSelectionStrategy, type AgentStatusChangeMessage, type AgentSyncConfig, AgentSyncConfigSchema, type AgentSyncInfo, AgentSyncManager, type AuthConfig, AuthConfigSchema, type AuthResult, BaseChannelPlugin, type CancelEvent, type CancelEventHandler, type ChannelConfig, ChannelConfigSchema, type ChannelEvent, type ChannelEventType, type ChannelHealth, type ChannelPlugin, ChannelPluginLoader, ChannelPluginRegistry, type SessionConfig as ChannelSessionConfig, type ChannelStatus, type ChannelStatusType, type ChannelType, type CircuitBreakerConfig, CircuitBreakerConfigSchema, type ConnectionState as ClientConnectionState, type ClientInitializeMessage, type ClientInterruptMessage, type ClientMessage, type ClientMessageMessage, type ClientMessageType, type ClientPingMessage, type ClientReleaseSubscriptionMessage, type ClientSubscribeMessage, type ClientSubscription, type ClientUnsubscribeMessage, type ConflictResolutionStrategy, type ConnectionCloser, type ConnectionFactory, type ConnectionHealthChecker, type ConnectionPoolConfig, ConnectionPoolConfigSchema, type ConnectionPoolEvent, type ConnectionPoolEventCallback, type ConnectionPoolEventType, type ConnectionPoolStats, type ConnectionState$1 as ConnectionState, type CreateSessionRequest, type CreateSessionResponse, DEFAULT_AGENT_REGISTRY_CONFIG, DEFAULT_CONNECTION_POOL_CONFIG, DEFAULT_SYNC_CONFIG, DEFAULT_TOKEN_AUTH_CONFIG, DEFAULT_WEBSOCKET_SERVER_CONFIG, type DiscordBotConfig, DiscordPlugin, type FeishuBotConfig, type FeishuChannelConfig, FeishuChannelConfigSchema, FeishuPlugin, Gateway, GatewayClient, type GatewayClientConfig, type GatewayClusterConfig, GatewayClusterConfigSchema, type GatewayConfig, GatewayConfigSchema, type GatewayNodeConfig, type GatewayNodeInfo, GatewayServer, type GatewayServerConfig, GatewayServerConfigSchema, type GatewaySession, GatewaySessionManager, type HTTPSConfig, HTTPSConfigSchema, type HealthCheckResponse, type IAuthProvider, type MessageCallback, type MessageHandler, MessageLockManager, type MessagePriority, type MessageQueueConfig, MessageQueueConfigSchema, type MessageRecord, MessageRetryManager, MessageRouter, type MessageStatus, MessageStore, type MessageStoreConfig, type NostrBotConfig, type NostrChannelConfig, NostrChannelConfigSchema, NostrPlugin, type OAuth2AuthConfig, type PluginLoaderConfig, type PooledConnection, type PushEventType, type RouteResult, type RoutingConfig, type SendMessageRequest, type SendMessageResponse, type SerializableSession, type ServerConnectedMessage, type ServerErrorMessage, type ServerEventMessage, type ServerInitializeResponseMessage, type ServerInterruptedMessage, type ServerMessage, type ServerMessageType, type ServerPongMessage, type ServerResponseMessage, type ServerSessionClosedMessage, type ServerStatusResponse, type ServerSubscribedMessage, type ServerSubscriptionReleasedMessage, type ServerUnsubscribedMessage, type SessionChannelInfo, type SessionConfig$1 as SessionConfig, SessionConfigSchema, type SessionContext, type SessionEventPayload, type SessionEventType, type SessionFilter, type SessionManagerConfig, type SessionResetPolicy, type SessionState, type SessionStatusType, SessionStore, type SessionStoreConfig, type SignalBotConfig, type SignalChannelConfig, SignalChannelConfigSchema, SignalPlugin, type SlackBotConfig, type SlackChannelConfig, SlackChannelConfigSchema, SlackPlugin, type Subscriber, type SubscriberConnection, type SubscriberType, type Subscription, type SubscriptionOptions, type SubscriptionsResponse, type SyncConfig, type SyncMessage, type SyncMode, type SyncState, type SyncStats, type TelegramBotConfig, type TelegramChannelConfig, TelegramChannelConfigSchema, TelegramPlugin, type TokenAuthConfig, type TokenAuthItem, type TokenConfig, type WeChatBotConfig, type WeChatChannelConfig, WeChatChannelConfigSchema, WeChatPlugin, type WebChatChannelConfig, WebChatChannelConfigSchema, type WebChatConfig, WebChatPlugin, type WebSocketConnectionInfo, type WebSocketConnectionState, type WebSocketMessage, type WebSocketMessageBase, clearConfigCache, createChannelPlugin, createDefaultSessionState, createGatewayMessage, createTextMessage, generateSessionId, generateSubscriptionId, getAgentRegistryConfig, getAuthConfig, getChannelConfig, getCircuitBreakerConfig, getClusterConfig, getConfig, getConfigDirectory, getConnectionPoolConfig, getDefaultAgent, getHTTPSConfig, getLogLevel, getMessageQueueConfig, getServerConfig, getSessionConfig, getSupportedPlatforms, initLog, isConfigLoaded, loadConfig, parsePartialConfig, validateConfig };
|
package/dist/index.d.ts
CHANGED
|
@@ -262,8 +262,8 @@ declare const AuthConfigSchema: z.ZodObject<{
|
|
|
262
262
|
type AuthConfig = z.infer<typeof AuthConfigSchema>;
|
|
263
263
|
declare const AgentSyncConfigSchema: z.ZodObject<{
|
|
264
264
|
mode: z.ZodDefault<z.ZodEnum<{
|
|
265
|
-
pull: "pull";
|
|
266
265
|
push: "push";
|
|
266
|
+
pull: "pull";
|
|
267
267
|
both: "both";
|
|
268
268
|
}>>;
|
|
269
269
|
interval: z.ZodDefault<z.ZodNumber>;
|
|
@@ -297,8 +297,8 @@ declare const GatewayClusterConfigSchema: z.ZodObject<{
|
|
|
297
297
|
}, z.core.$strip>>>;
|
|
298
298
|
sync: z.ZodOptional<z.ZodObject<{
|
|
299
299
|
mode: z.ZodDefault<z.ZodEnum<{
|
|
300
|
-
pull: "pull";
|
|
301
300
|
push: "push";
|
|
301
|
+
pull: "pull";
|
|
302
302
|
both: "both";
|
|
303
303
|
}>>;
|
|
304
304
|
interval: z.ZodDefault<z.ZodNumber>;
|
|
@@ -545,8 +545,8 @@ declare const GatewayConfigSchema: z.ZodObject<{
|
|
|
545
545
|
}, z.core.$strip>>>;
|
|
546
546
|
sync: z.ZodOptional<z.ZodObject<{
|
|
547
547
|
mode: z.ZodDefault<z.ZodEnum<{
|
|
548
|
-
pull: "pull";
|
|
549
548
|
push: "push";
|
|
549
|
+
pull: "pull";
|
|
550
550
|
both: "both";
|
|
551
551
|
}>>;
|
|
552
552
|
interval: z.ZodDefault<z.ZodNumber>;
|
|
@@ -791,54 +791,7 @@ interface RouteResult {
|
|
|
791
791
|
}
|
|
792
792
|
declare function generateSubscriptionId(subscriberId: string, sessionId: string): string;
|
|
793
793
|
|
|
794
|
-
declare const DEFAULT_WEBSOCKET_SERVER_CONFIG:
|
|
795
|
-
enabled: boolean;
|
|
796
|
-
port: number;
|
|
797
|
-
hostname: string;
|
|
798
|
-
path: string;
|
|
799
|
-
maxConnections: number;
|
|
800
|
-
connectionTimeout: number;
|
|
801
|
-
heartbeatInterval: number;
|
|
802
|
-
sessionExpireMs: number;
|
|
803
|
-
cors: boolean;
|
|
804
|
-
mdns: boolean;
|
|
805
|
-
mdnsDomain: string;
|
|
806
|
-
https?: {
|
|
807
|
-
enabled: boolean;
|
|
808
|
-
cert: string;
|
|
809
|
-
key: string;
|
|
810
|
-
forceRedirect: boolean;
|
|
811
|
-
httpPort: number;
|
|
812
|
-
certPath?: string | undefined;
|
|
813
|
-
keyPath?: string | undefined;
|
|
814
|
-
ca?: string | undefined;
|
|
815
|
-
} | undefined;
|
|
816
|
-
auth?: {
|
|
817
|
-
type: "token" | "oauth2";
|
|
818
|
-
token?: {
|
|
819
|
-
enabled: boolean;
|
|
820
|
-
tokens: {
|
|
821
|
-
name: string;
|
|
822
|
-
value: string;
|
|
823
|
-
permissions: string[];
|
|
824
|
-
expiresAt?: number | undefined;
|
|
825
|
-
description?: string | undefined;
|
|
826
|
-
}[];
|
|
827
|
-
onInvalid: "reject" | "anonymous";
|
|
828
|
-
allowAnonymous: boolean;
|
|
829
|
-
defaultPermissions: string[];
|
|
830
|
-
} | undefined;
|
|
831
|
-
oauth2?: {
|
|
832
|
-
enabled: boolean;
|
|
833
|
-
authorizationServer: string;
|
|
834
|
-
clientId: string;
|
|
835
|
-
clientSecret: string;
|
|
836
|
-
tokenValidationEndpoint: string;
|
|
837
|
-
scope: string[];
|
|
838
|
-
} | undefined;
|
|
839
|
-
} | undefined;
|
|
840
|
-
corsOrigins?: string[] | undefined;
|
|
841
|
-
}>;
|
|
794
|
+
declare const DEFAULT_WEBSOCKET_SERVER_CONFIG: GatewayServerConfig;
|
|
842
795
|
type ClientMessageType = 'initialize' | 'subscribe' | 'unsubscribe' | 'message' | 'ping' | 'interrupt' | 'releaseSubscription' | 'agent_list_request' | 'agent_subscribe';
|
|
843
796
|
type ServerMessageType = 'connected' | 'initialize_response' | 'subscribed' | 'unsubscribed' | 'event' | 'response' | 'error' | 'pong' | 'interrupted' | 'session_closed' | 'subscriptionReleased' | 'agent_list_response' | 'agent_update';
|
|
844
797
|
interface WebSocketMessageBase {
|
|
@@ -1750,6 +1703,7 @@ declare class GatewayServer implements IGatewayServer {
|
|
|
1750
1703
|
private sessionManager;
|
|
1751
1704
|
private pluginLoader;
|
|
1752
1705
|
private messageStore;
|
|
1706
|
+
private wsServer;
|
|
1753
1707
|
private running;
|
|
1754
1708
|
private connections;
|
|
1755
1709
|
constructor(config: GatewayServerConfig$1);
|
|
@@ -2235,4 +2189,12 @@ declare function createChannelPlugin<TConfig = unknown, TProbe = unknown>(option
|
|
|
2235
2189
|
declare const ChannelPluginRegistry: Record<string, new (id?: string) => ChannelPlugin>;
|
|
2236
2190
|
declare function getSupportedPlatforms(): string[];
|
|
2237
2191
|
|
|
2238
|
-
|
|
2192
|
+
declare function initLog(options: {
|
|
2193
|
+
print: boolean;
|
|
2194
|
+
logDir: string;
|
|
2195
|
+
logFile?: string;
|
|
2196
|
+
dev?: boolean;
|
|
2197
|
+
level?: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
|
|
2198
|
+
}): Promise<void>;
|
|
2199
|
+
|
|
2200
|
+
export { type AgentDeregisterMessage, type AgentHealthStatus, type AgentHeartbeat, type AgentHeartbeatSyncMessage, type AgentListRequestMessage, type AgentListResponseMessage, type AgentRegisterMessage, type AgentRegistration, type AgentRegistrationRequest, AgentRegistry, type AgentRegistryConfig, AgentRegistryConfigSchema, type AgentRegistryStats, type AgentSelectionOptions, type AgentSelectionRecord, type AgentSelectionStrategy, type AgentStatusChangeMessage, type AgentSyncConfig, AgentSyncConfigSchema, type AgentSyncInfo, AgentSyncManager, type AuthConfig, AuthConfigSchema, type AuthResult, BaseChannelPlugin, type CancelEvent, type CancelEventHandler, type ChannelConfig, ChannelConfigSchema, type ChannelEvent, type ChannelEventType, type ChannelHealth, type ChannelPlugin, ChannelPluginLoader, ChannelPluginRegistry, type SessionConfig as ChannelSessionConfig, type ChannelStatus, type ChannelStatusType, type ChannelType, type CircuitBreakerConfig, CircuitBreakerConfigSchema, type ConnectionState as ClientConnectionState, type ClientInitializeMessage, type ClientInterruptMessage, type ClientMessage, type ClientMessageMessage, type ClientMessageType, type ClientPingMessage, type ClientReleaseSubscriptionMessage, type ClientSubscribeMessage, type ClientSubscription, type ClientUnsubscribeMessage, type ConflictResolutionStrategy, type ConnectionCloser, type ConnectionFactory, type ConnectionHealthChecker, type ConnectionPoolConfig, ConnectionPoolConfigSchema, type ConnectionPoolEvent, type ConnectionPoolEventCallback, type ConnectionPoolEventType, type ConnectionPoolStats, type ConnectionState$1 as ConnectionState, type CreateSessionRequest, type CreateSessionResponse, DEFAULT_AGENT_REGISTRY_CONFIG, DEFAULT_CONNECTION_POOL_CONFIG, DEFAULT_SYNC_CONFIG, DEFAULT_TOKEN_AUTH_CONFIG, DEFAULT_WEBSOCKET_SERVER_CONFIG, type DiscordBotConfig, DiscordPlugin, type FeishuBotConfig, type FeishuChannelConfig, FeishuChannelConfigSchema, FeishuPlugin, Gateway, GatewayClient, type GatewayClientConfig, type GatewayClusterConfig, GatewayClusterConfigSchema, type GatewayConfig, GatewayConfigSchema, type GatewayNodeConfig, type GatewayNodeInfo, GatewayServer, type GatewayServerConfig, GatewayServerConfigSchema, type GatewaySession, GatewaySessionManager, type HTTPSConfig, HTTPSConfigSchema, type HealthCheckResponse, type IAuthProvider, type MessageCallback, type MessageHandler, MessageLockManager, type MessagePriority, type MessageQueueConfig, MessageQueueConfigSchema, type MessageRecord, MessageRetryManager, MessageRouter, type MessageStatus, MessageStore, type MessageStoreConfig, type NostrBotConfig, type NostrChannelConfig, NostrChannelConfigSchema, NostrPlugin, type OAuth2AuthConfig, type PluginLoaderConfig, type PooledConnection, type PushEventType, type RouteResult, type RoutingConfig, type SendMessageRequest, type SendMessageResponse, type SerializableSession, type ServerConnectedMessage, type ServerErrorMessage, type ServerEventMessage, type ServerInitializeResponseMessage, type ServerInterruptedMessage, type ServerMessage, type ServerMessageType, type ServerPongMessage, type ServerResponseMessage, type ServerSessionClosedMessage, type ServerStatusResponse, type ServerSubscribedMessage, type ServerSubscriptionReleasedMessage, type ServerUnsubscribedMessage, type SessionChannelInfo, type SessionConfig$1 as SessionConfig, SessionConfigSchema, type SessionContext, type SessionEventPayload, type SessionEventType, type SessionFilter, type SessionManagerConfig, type SessionResetPolicy, type SessionState, type SessionStatusType, SessionStore, type SessionStoreConfig, type SignalBotConfig, type SignalChannelConfig, SignalChannelConfigSchema, SignalPlugin, type SlackBotConfig, type SlackChannelConfig, SlackChannelConfigSchema, SlackPlugin, type Subscriber, type SubscriberConnection, type SubscriberType, type Subscription, type SubscriptionOptions, type SubscriptionsResponse, type SyncConfig, type SyncMessage, type SyncMode, type SyncState, type SyncStats, type TelegramBotConfig, type TelegramChannelConfig, TelegramChannelConfigSchema, TelegramPlugin, type TokenAuthConfig, type TokenAuthItem, type TokenConfig, type WeChatBotConfig, type WeChatChannelConfig, WeChatChannelConfigSchema, WeChatPlugin, type WebChatChannelConfig, WebChatChannelConfigSchema, type WebChatConfig, WebChatPlugin, type WebSocketConnectionInfo, type WebSocketConnectionState, type WebSocketMessage, type WebSocketMessageBase, clearConfigCache, createChannelPlugin, createDefaultSessionState, createGatewayMessage, createTextMessage, generateSessionId, generateSubscriptionId, getAgentRegistryConfig, getAuthConfig, getChannelConfig, getCircuitBreakerConfig, getClusterConfig, getConfig, getConfigDirectory, getConnectionPoolConfig, getDefaultAgent, getHTTPSConfig, getLogLevel, getMessageQueueConfig, getServerConfig, getSessionConfig, getSupportedPlatforms, initLog, isConfigLoaded, loadConfig, parsePartialConfig, validateConfig };
|