@easbot/gateway 0.2.24 → 0.2.25
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-OHUELRXK.mjs +14 -0
- package/dist/chunks/chunk-U32NADBK.cjs +14 -0
- package/dist/chunks/{global-DVGSJ3V3.mjs → global-JYEIXTJ2.mjs} +1 -1
- package/dist/chunks/{global-WNXPJXAS.cjs → global-Y53VDBKD.cjs} +1 -1
- package/dist/chunks/server-MTS5PR2P.mjs +1 -0
- package/dist/chunks/{server-ZWJPPFTK.cjs → server-ZPM3AQHL.cjs} +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +4 -9
- package/dist/index.d.ts +4 -9
- package/dist/index.mjs +2 -2
- package/package.json +5 -5
- package/dist/chunks/chunk-GQFBXITJ.mjs +0 -5
- package/dist/chunks/chunk-LR37LRDG.cjs +0 -5
- package/dist/chunks/server-HGRZI7JT.mjs +0 -1
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {a}from'./chunk-OBW6CNOG.mjs';import {a as a$2}from'./chunk-HAMGVOQD.mjs';import a$1 from'zod';import*as _ from'path';import ___default from'path';import*as R from'fs';import R__default,{existsSync}from'fs';import*as I from'fs/promises';import I__default from'fs/promises';import {createServer,Fetch}from'@easbot/utils';import {WebSocketServer}from'ws';import sn from'https';import rn from'http';import {HookEvent}from'@easbot/plugin';var se=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:lock"}));a$2(this,"config");a$2(this,"locks",new Map);a$2(this,"cleanupTimer",null);this.config={defaultTimeout:t.defaultTimeout??6e4,checkInterval:t.checkInterval??1e4};}tryAcquire(t,e,n,s){let i=this.locks.get(t);if(i)if(this.isLockExpired(i))this.log.warn("lock expired, releasing",{sessionId:t,oldHolder:i.holderId,newHolder:n}),this.locks.delete(t);else return this.log.debug("lock already held",{sessionId:t,holder:i.holderId,messageId:i.messageId}),false;let r={sessionId:t,messageId:e,holderId:n,acquiredAt:Date.now(),timeout:s??this.config.defaultTimeout};return this.locks.set(t,r),this.log.debug("lock acquired",{sessionId:t,messageId:e,subscriberId:n}),true}release(t,e){let n=this.locks.get(t);return n?n.holderId!==e?(this.log.warn("cannot release lock held by another",{sessionId:t,holder:n.holderId,requester:e}),false):(this.locks.delete(t),this.log.debug("lock released",{sessionId:t,subscriberId:e}),true):(this.log.debug("no lock to release",{sessionId:t}),false)}forceRelease(t){let e=this.locks.get(t);return e?(this.locks.delete(t),this.log.warn("lock force released",{sessionId:t,holder:e.holderId,messageId:e.messageId}),true):false}isLockExpired(t){return Date.now()-t.acquiredAt>t.timeout}getLock(t){return this.locks.get(t)}isLocked(t){let e=this.locks.get(t);return e?this.isLockExpired(e)?(this.locks.delete(t),false):true:false}getHolder(t){let e=this.locks.get(t);if(!(!e||this.isLockExpired(e)))return e.holderId}startCleanup(){this.cleanupTimer||(this.cleanupTimer=setInterval(()=>{this.cleanupExpired();},this.config.checkInterval),this.log.info("lock cleanup started",{interval:this.config.checkInterval}));}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null,this.log.info("lock cleanup stopped"));}cleanupExpired(){let t=0;for(let[e,n]of this.locks)this.isLockExpired(n)&&(this.locks.delete(e),t++,this.log.warn("expired lock cleaned up",{sessionId:e,holder:n.holderId,messageId:n.messageId}));return t>0&&this.log.info("cleaned up expired locks",{count:t}),t}getAllLocks(){return [...this.locks.values()]}getLockCount(){return this.locks.size}};var ie=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:retry"}));a$2(this,"policy");a$2(this,"retryQueue",new Map);a$2(this,"retryTimer",null);a$2(this,"handlers",new Map);this.policy={maxRetries:t.maxRetries??3,initialDelay:t.initialDelay??1e3,maxDelay:t.maxDelay??3e4,backoffMultiplier:t.backoffMultiplier??2};}registerHandler(t,e){this.handlers.set(t,e);}unregisterHandler(t){this.handlers.delete(t);}scheduleRetry(t,e){let n=t.id,s=this.retryQueue.get(n);if(s||(s={messageId:n,retryCount:0,nextRetryAt:0,errors:[]},this.retryQueue.set(n,s)),s.errors.push({error:e.message,timestamp:Date.now()}),s.retryCount>=this.policy.maxRetries)return this.log.error("max retries exceeded",{messageId:n,retryCount:s.retryCount,maxRetries:this.policy.maxRetries}),false;let i=Math.min(this.policy.initialDelay*this.policy.backoffMultiplier**s.retryCount,this.policy.maxDelay);return s.retryCount++,s.nextRetryAt=Date.now()+i,this.log.warn("retry scheduled",{messageId:n,retryCount:s.retryCount,delay:i,error:e.message}),true}getPendingRetries(){let t=Date.now(),e=[];for(let n of this.retryQueue.values())n.nextRetryAt<=t&&n.retryCount<=this.policy.maxRetries&&e.push(n);return e}async executeRetry(t){if(!this.handlers.get(t.messageId))return this.log.warn("no handler for retry",{messageId:t.messageId}),false;this.retryQueue.delete(t.messageId);try{return this.log.info("executing retry",{messageId:t.messageId,retryCount:t.retryCount}),!0}catch(n){return this.log.error("retry execution failed",{messageId:t.messageId,error:String(n)}),false}}clearRetry(t){this.retryQueue.delete(t),this.handlers.delete(t),this.log.debug("retry cleared",{messageId:t});}startProcessing(){this.retryTimer||(this.retryTimer=setInterval(async()=>{let t=this.getPendingRetries();for(let e of t)await this.executeRetry(e);},1e3),this.log.info("retry processing started"));}stopProcessing(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null,this.log.info("retry processing stopped"));}getStats(){let t=0;for(let e of this.retryQueue.values())t+=e.errors.length;return {pendingCount:this.retryQueue.size,totalErrors:t}}};function b(c,t,e,n){return {id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c,type:t,content:e,metadata:{channel:{platform:n?.channel?.platform??"api",channelId:n?.channel?.channelId??"default",userId:n?.channel?.userId,chatId:n?.channel?.chatId,...Object.fromEntries(Object.entries(n?.channel??{}).filter(([s])=>!["platform","channelId","userId","chatId"].includes(s)))},context:n?.context,agent:n?.agent},timestamp:Date.now()}}function rt(c,t,e,n){return b(c,t,[{type:"text",text:e}],n)}function Me(c){let t=[c.platform,c.channelId];return c.chatId&&t.push(c.chatId),c.userId&&t.push(c.userId),t.join("_")}function Ae(){return {status:"active",messageCount:0,lastMessageAt:null}}function re(c,t){if(!c||!t)throw new Error("platform and stableId are required");return `${c}:${t}`}function oe(c){if(!c||typeof c!="string")return null;let t=c.indexOf(":");if(t<=0||t>=c.length-1)return null;let e=c.slice(0,t),n=c.slice(t+1);return !e||!n?null:{platform:e,stableId:n}}function ke(c){let{platform:t,stableId:e,profile:n={},aliases:s={},metadata:i}=c;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:re(t,e),platform:t,stableId:e,aliases:{...s},profile:{...n},createdAt:r,lastSeenAt:r,metadata:i}}function Te(c,t){return `sub_${c}_${t}`}var ot=a.create({service:"gateway:config"});a$1.enum(["telegram","slack","feishu","wechat","webchat","signal","nostr"]);a$1.enum(["low","medium","high","critical"]);var ce=a$1.object({enabled:a$1.boolean().default(true),botToken:a$1.string().describe("Telegram Bot Token"),webhookUrl:a$1.string().optional().describe("Webhook URL for receiving updates"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),le=a$1.object({enabled:a$1.boolean().default(true),botToken:a$1.string().describe("Slack Bot Token (xoxb-*)"),appToken:a$1.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:a$1.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),ge=a$1.object({enabled:a$1.boolean().default(true),appId:a$1.string().describe("Feishu App ID"),appSecret:a$1.string().describe("Feishu App Secret"),encryptKey:a$1.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:a$1.string().optional().describe("Feishu Verification Token"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),de=a$1.object({enabled:a$1.boolean().default(true),mode:a$1.enum(["official","wecom"]).default("official"),appId:a$1.string().describe("WeChat App ID"),appSecret:a$1.string().describe("WeChat App Secret"),token:a$1.string().optional().describe("WeChat Token for message verification"),encodingAESKey:a$1.string().optional().describe("WeChat Encoding AES Key"),agentId:a$1.string().optional().describe("WeCom Agent ID"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),ue=a$1.object({enabled:a$1.boolean().default(true),path:a$1.string().optional().default("/"),heartbeatInterval:a$1.number().int().positive().optional().default(3e4),connectionTimeout:a$1.number().int().positive().optional().default(6e4),maxConnections:a$1.number().int().positive().optional().default(1e3),cors:a$1.boolean().optional().default(true)}),he=a$1.object({enabled:a$1.boolean().default(true),serviceUrl:a$1.string().optional().default("https://chat.signal.org"),phoneNumber:a$1.string().describe("Signal phone number"),password:a$1.string().optional().describe("Signal account password"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),pe=a$1.object({enabled:a$1.boolean().default(true),relays:a$1.array(a$1.string()).min(1).describe("Nostr relay URLs"),privateKey:a$1.string().optional().describe("Nostr private key (hex)"),publicKey:a$1.string().optional().describe("Nostr public key (hex)"),maxConnections:a$1.number().int().positive().optional().default(100),timeout:a$1.number().int().positive().optional().default(3e4)}),He=a$1.object({telegram:ce.optional(),slack:le.optional(),feishu:ge.optional(),wechat:de.optional(),webchat:ue.optional(),signal:he.optional(),nostr:pe.optional()}),ze=a$1.object({enabled:a$1.boolean().default(false),cert:a$1.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:a$1.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:a$1.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:a$1.string().optional().describe("Path to SSL key file (alias of key)"),ca:a$1.string().optional().describe("Path to CA certificate file"),forceRedirect:a$1.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:a$1.number().int().positive().optional().default(80).describe("HTTP redirect port")}),at=a$1.object({name:a$1.string().describe("Token name/description"),value:a$1.string().describe("Token value"),permissions:a$1.array(a$1.string()).default(["*"]).describe("Associated permissions"),expiresAt:a$1.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:a$1.string().optional().describe("Token description")}),ct=a$1.object({enabled:a$1.boolean().default(true),tokens:a$1.array(at).default([]).describe("List of valid tokens"),onInvalid:a$1.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:a$1.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:a$1.array(a$1.string()).default([]).describe("Default permissions for anonymous users")}),lt=a$1.object({enabled:a$1.boolean().default(false),authorizationServer:a$1.string().describe("OAuth2 authorization server URL"),clientId:a$1.string().describe("OAuth2 client ID"),clientSecret:a$1.string().describe("OAuth2 client secret"),tokenValidationEndpoint:a$1.string().describe("OAuth2 token validation endpoint"),scope:a$1.array(a$1.string()).default([]).describe("OAuth2 scopes")}),$e=a$1.object({type:a$1.enum(["token","oauth2"]).default("token"),token:ct.optional(),oauth2:lt.optional()}),je=a$1.object({mode:a$1.enum(["pull","push","both"]).default("both"),interval:a$1.number().int().positive().default(3e4),pushEvents:a$1.array(a$1.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:a$1.enum(["latest","local","remote"]).default("latest")}),gt=a$1.object({id:a$1.string().describe("Gateway node ID"),address:a$1.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:a$1.boolean().default(true),metadata:a$1.record(a$1.string(),a$1.any()).optional()}),qe=a$1.object({nodeId:a$1.string().describe("Current gateway node ID"),nodes:a$1.array(gt).default([]).describe("Other gateway nodes in the cluster"),sync:je.optional()}),fe=a$1.object({maxConnectionsPerChannel:a$1.number().int().positive().default(100),idleTimeout:a$1.number().int().positive().default(3e5),reuseStrategy:a$1.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:a$1.number().int().positive().default(6e4),acquireTimeout:a$1.number().int().positive().default(5e3),warmupCount:a$1.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),me=a$1.object({maxLength:a$1.number().int().positive().default(1e4),concurrency:a$1.number().int().positive().default(100),batchSize:a$1.number().int().positive().default(10),batchTimeout:a$1.number().int().positive().default(100),priorityLevels:a$1.number().int().positive().default(4)}),ye=a$1.object({failureThreshold:a$1.number().int().positive().default(5),successThreshold:a$1.number().int().positive().default(3),timeout:a$1.number().int().positive().default(3e4),halfOpenDuration:a$1.number().int().positive().default(15e3)}),be=a$1.object({heartbeatInterval:a$1.number().int().positive().default(3e4),heartbeatTimeout:a$1.number().int().positive().default(9e4),heartbeatCheckInterval:a$1.number().int().positive().default(1e4),autoDeregisterTimeout:a$1.number().int().positive().default(3e5),maxAgents:a$1.number().int().positive().default(100),persistenceFile:a$1.string().optional().describe("Path to persist agent registrations"),maxRegistrations:a$1.number().int().positive().default(1e3)}),Ce=a$1.object({sessionTimeout:a$1.number().int().positive().default(18e5),resumeGracePeriod:a$1.number().int().positive().default(3e5),maxSessions:a$1.number().int().positive().default(1e4),persistenceFile:a$1.string().optional().describe("Path to persist sessions")}),Se=a$1.object({enabled:a$1.boolean().default(true),port:a$1.number().int().positive().default(8080),hostname:a$1.string().default("localhost"),path:a$1.string().optional().default("/"),maxConnections:a$1.number().int().positive().optional().default(1e3),connectionTimeout:a$1.number().int().positive().optional().default(6e4),heartbeatInterval:a$1.number().int().positive().optional().default(3e4),sessionExpireMs:a$1.number().int().positive().optional().default(3e5),https:ze.optional(),auth:$e.optional(),cors:a$1.boolean().default(true),corsOrigins:a$1.array(a$1.string()).optional(),mdns:a$1.boolean().default(false),mdnsDomain:a$1.string().optional().default("gateway.easbot.local")}),dt=a$1.object({channel:a$1.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:a$1.array(a$1.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),ae=a$1.object({server:Se.optional(),channels:He.optional(),cluster:qe.optional(),connectionPool:fe.optional(),messageQueue:me.optional(),circuitBreaker:ye.optional(),agentRegistry:be.optional(),session:Ce.optional(),defaults:dt.optional(),defaultAgent:a$1.string().optional().describe("Default agent ID for routing"),logLevel:a$1.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(a$1.unknown());function Ee(c){let t=ae.safeParse(c);return t.success||ot.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:ae.parse({})}function ut(c){return ae.parse(c)}var ht=a.create({service:"gateway:interfaces"}),P;function Ln(c){P=c,ht.debug("Agent adapter registered",{hasSubAgentRunner:!!c.subAgentRunner});}function On(){return P}function k(){return P!==void 0}function T(){if(!P)throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");return P}var pt={Path:{home:process.env.HOME||process.env.USERPROFILE||"",data:".easbot",cache:".easbot/cache",config:".easbot",state:".easbot/state",log:".easbot/log",bin:".easbot/bin"}},ft={directory:process.cwd(),worktree:process.cwd()};function O(){return P?P.global:pt}function Re(){return P?P.instance:ft}var x=a.create({service:"gateway:config"}),ve={enabled:true,port:8080,hostname:"localhost",path:"/",maxConnections:1e3,connectionTimeout:6e4,heartbeatInterval:3e4,sessionExpireMs:3e5,cors:true,mdns:false,mdnsDomain:"gateway.easbot.local",https:{enabled:false,cert:"",key:"",certPath:void 0,keyPath:void 0,ca:void 0,forceRedirect:false,httpPort:80}},bt={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},Ct={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},St={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},vt={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3},wt={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e4},It={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Pt={enabled:true,botToken:"",maxConnections:100,timeout:3e4},xt={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},Mt={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},At={enabled:true,path:"/ws",heartbeatInterval:3e4,connectionTimeout:6e4,maxConnections:1e3,cors:true},kt={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},Tt={enabled:true,relays:[],maxConnections:100,timeout:3e4},U,W=null;async function Ye(c){try{if(!existsSync(c))return null;let t=await I__default.readFile(c,"utf-8");t=t.replace(/\{env:([^}]+)\}/g,(r,l)=>{let g=process.env[l];return g===void 0?(x.debug("Environment variable not found",{varName:l,file:c}),""):g});let e=t,n=!1,s=!1,i=[];for(let r=0;r<t.length;r++){let l=t[r];if(s){i.push(l),s=!1;continue}if(l==="\\"){i.push(l),s=!0;continue}if(l==='"'){n=!n,i.push(l);continue}if(!n&&l==="/"&&t[r+1]==="/"){for(;r<t.length&&t[r]!==`
|
|
2
|
+
`&&t[r]!=="\r";)r++;continue}if(!n&&l==="/"&&t[r+1]==="*"){for(r+=2;r<t.length-1;){if(t[r]==="*"&&t[r+1]==="/"){r+=2;break}r++;}continue}i.push(l);}return e=i.join("").trim(),e?JSON.parse(e):null}catch(t){return x.debug("Failed to load config file",{file:c,error:String(t)}),null}}function F(c,t){let e={...c,...t};return (c.server||t.server)&&(e.server={...c.server,...t.server}),(c.channels||t.channels)&&(e.channels={...c.channels,...t.channels}),e}async function Et(){let c=O(),t=Re(),e=[],n=___default.join(c.Path.config);e.push(n),e.push(t.directory);try{let{Filesystem:i}=await import('@easbot/utils'),r=await Array.fromAsync(i.up({targets:[".easbot"],start:t.directory,stop:t.worktree}));e.push(...r);}catch{x.debug("Filesystem utils not available, using basic directories");}let s=process.env.EASBOT_CONFIG_DIR;return s&&(e.push(s),x.debug("Using EASBOT_CONFIG_DIR",{path:s})),[...new Set(e)]}async function Rt(c){let t=["gateway.json"],e={};for(let n of t){let s=___default.join(c,n),i=await Ye(s);if(i)if("gateway"in i&&i.gateway){let r=i.gateway;"server"in r||"channels"in r||"cluster"in r?e=F(e,r):e=F(e,{server:r}),x.debug("Loaded gateway config from file (nested format)",{file:s});}else "gateway"in i||(e=F(e,i),x.debug("Loaded gateway config from file (direct format)",{file:s}));}return e}async function _t(c){let t=["easbot.json"];for(let e of t){let n=___default.join(c,e),s=await Ye(n);if(s?.gateway)return x.debug("Loaded gateway config from easbot.json",{file:n}),s.gateway}return {}}function Nt(){return U||(U=async()=>{let c=await Et(),t={};for(let n of c){let s=await Rt(n);t=F(t,s);let i=await _t(n);t=F(t,i);}let e=Ee(t);return W=e,x.info("Gateway config loaded",{directories:c.length,port:e.server?.port,logLevel:e.logLevel}),{config:e,directories:c}}),U}async function S(){return Nt()()}async function Ke(c){return c&&(U=void 0,W=null),(await S()).config}function Ve(){return W}function Je(){return W!==null}function Gt(){U=void 0,W=null,x.debug("Config cache cleared");}function Dt(){return Re().directory}async function Lt(){let{config:c}=await S();return Se.parse({...ve,...c.server})}async function Ot(c){let{config:t}=await S(),e=t.channels?.[c],s={telegram:ce.parse(It),slack:le.parse(Pt),feishu:ge.parse(xt),wechat:de.parse(Mt),webchat:ue.parse(At),signal:he.parse(kt),nostr:pe.parse(Tt)}[c];if(!s)throw new Error(`Unknown channel type: ${c}`);return {...s,...e}}async function Ut(){let{config:c}=await S();return fe.parse({...bt,...c.connectionPool})}async function Ft(){let{config:c}=await S();return me.parse({...Ct,...c.messageQueue})}async function Wt(){let{config:c}=await S();return ye.parse({...St,...c.circuitBreaker})}async function Bt(){let{config:c}=await S();return be.parse({...vt,...c.agentRegistry})}async function Ht(){let{config:c}=await S();return Ce.parse({...wt,...c.session})}async function zt(){let{config:c}=await S();return c.server?.https}async function $t(){let{config:c}=await S();return c.server?.auth}async function jt(){let{config:c}=await S();return c.cluster}async function qt(){let{config:c}=await S();return c.defaultAgent}async function Qe(){let{config:c}=await S();return c.logLevel??"INFO"}var Ne=ve,B={maxConnections:1e3,connectionTimeout:6e4,sessionExpireMs:3e5};var Kt={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var Vt={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3};var Jt={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};var Qt={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var M=class c extends Error{constructor(e,n){super(e);a$2(this,"code");a$2(this,"recoverable");a$2(this,"details");a$2(this,"cause");this.name="GatewayError",this.code=n.code,this.recoverable=n.recoverable,this.details=n.details,this.cause=n.cause,Error.captureStackTrace&&Error.captureStackTrace(this,c);}toJSON(){return {name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,details:this.details,cause:this.cause?.message,stack:this.stack}}static isRecoverable(e){if(e instanceof c)return e.recoverable;let n=e.code;return ["ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH"].includes(n??"")}};function E(c,t,e,n=true){return new M(e,{code:t,recoverable:n,details:{channelId:c}})}var we=class{constructor(){a$2(this,"log",a.create({service:"gateway:router"}));a$2(this,"subscribers",new Map);a$2(this,"subscriptions",new Map);a$2(this,"sessionSubscriptions",new Map);a$2(this,"channelPlugins",new Map);a$2(this,"lockManager");a$2(this,"retryManager");a$2(this,"cancelHandlers",new Set);this.lockManager=new se,this.retryManager=new ie,this.lockManager.startCleanup();}onCancel(t){this.cancelHandlers.add(t);}offCancel(t){this.cancelHandlers.delete(t);}async emitCancel(t){for(let e of this.cancelHandlers)try{await e(t);}catch(n){this.log.error("cancel handler error",{error:String(n)});}}async route(t){this.log.debug("routing message",{id:t.id,sessionId:t.sessionId,type:t.type});let e=this.sessionSubscriptions.get(t.sessionId);if(!e||e.size===0)return this.log.debug("no subscribers for session",{sessionId:t.sessionId}),{success:true,broadcastCount:0,dispatchedToSubAgent:false};let n=0,s=null,i=[];for(let r of e){let l=this.subscriptions.get(r);if(!l)continue;let g=this.subscribers.get(l.subscriberId);if(g){if(t.type==="input"){if(!this.lockManager.tryAcquire(t.sessionId,t.id,g.id)){this.log.debug("skipping subscriber, lock held by another",{subscriberId:g.id,holder:this.lockManager.getHolder(t.sessionId)});continue}s=g.id;}try{await g.connection.send(t),n++,g.lastActiveAt=Date.now();}catch(u){this.log.warn("failed to send message to subscriber",{subscriberId:g.id,error:String(u)}),i.push(u instanceof Error?u:new Error(String(u))),s===g.id&&(this.lockManager.release(t.sessionId,g.id),s=null);}}}return this.log.debug("message routed",{id:t.id,broadcastCount:n,errorCount:i.length,processedBy:s}),{success:i.length===0,broadcastCount:n,dispatchedToSubAgent:false,error:i.length>0?i.map(r=>r.message).join("; "):void 0}}async completeMessage(t,e,n,s="completed"){this.lockManager.release(t,n),await this.emitCancel({sessionId:t,messageId:e,processedBy:n,reason:s,timestamp:Date.now()}),this.log.info("message completed",{sessionId:t,messageId:e,subscriberId:n,reason:s});}scheduleRetry(t,e){return this.retryManager.scheduleRetry(t,e)}async subscribe(t,e){let n=Te(e.id,t);if(this.subscriptions.has(n))return this.log.debug("already subscribed",{subscriberId:e.id,sessionId:t}),this.subscriptions.get(n);let s={id:n,subscriberId:e.id,sessionId:t,createdAt:Date.now()};return this.subscribers.has(e.id)||this.subscribers.set(e.id,e),this.subscriptions.set(n,s),this.sessionSubscriptions.has(t)||this.sessionSubscriptions.set(t,new Set),this.sessionSubscriptions.get(t).add(n),e.sessions.add(t),this.log.info("subscribed to session",{subscriberId:e.id,sessionId:t,subscriptionId:n}),s}async unsubscribe(t){let e=this.subscriptions.get(t);if(!e){this.log.warn("subscription not found",{subscriptionId:t});return}this.subscriptions.delete(t);let n=this.sessionSubscriptions.get(e.sessionId);n&&(n.delete(t),n.size===0&&this.sessionSubscriptions.delete(e.sessionId));let s=this.subscribers.get(e.subscriberId);s&&s.sessions.delete(e.sessionId),this.log.info("unsubscribed from session",{subscriberId:e.subscriberId,sessionId:e.sessionId,subscriptionId:t});}async unsubscribeAll(t){let e=this.subscribers.get(t);if(!e)return;let n=[...e.sessions];for(let s of n){let i=this.sessionSubscriptions.get(s);if(i)for(let r of i)this.subscriptions.get(r)?.subscriberId===t&&await this.unsubscribe(r);}this.subscribers.delete(t),this.log.info("all subscriptions removed for subscriber",{subscriberId:t});}registerChannel(t){this.channelPlugins.set(t.id,t),this.log.info("channel plugin registered",{id:t.id,platform:t.platform});}unregisterChannel(t){this.channelPlugins.delete(t),this.log.info("channel plugin unregistered",{id:t});}getSubscriber(t){return this.subscribers.get(t)}getSubscription(t){return this.subscriptions.get(t)}getSubscriberCount(t){return this.sessionSubscriptions.get(t)?.size??0}getStats(){return {subscribers:this.subscribers.size,subscriptions:this.subscriptions.size,sessions:this.sessionSubscriptions.size}}async shutdown(){this.lockManager.stopCleanup(),this.subscribers.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.channelPlugins.clear(),this.cancelHandlers.clear(),this.log.info("router shutdown");}};var H=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:message-store"}));a$2(this,"config");a$2(this,"messages",new Map);a$2(this,"sessionMessages",new Map);a$2(this,"cleanupTimer",null);a$2(this,"accessOrder",[]);this.config={storagePath:t.storagePath??"./data/gateway-messages",maxRetentionDays:t.maxRetentionDays??7,maxRecords:t.maxRecords??5e4,cleanupIntervalMs:t.cleanupIntervalMs??36e5,cleanupBatchSize:t.cleanupBatchSize??1e3,lruEnabled:t.lruEnabled??true,lruMaxMemory:t.lruMaxMemory??0},this.startCleanupTimer();}startCleanupTimer(){this.cleanupTimer||(this.cleanupTimer=setInterval(()=>{this.performCleanup().catch(t=>{this.log.error("Cleanup error",{error:String(t)});});},this.config.cleanupIntervalMs),this.cleanupTimer.unref?.(),this.log.info("Cleanup timer started",{intervalMs:this.config.cleanupIntervalMs}));}performCleanup(){return new Promise(t=>{let e=this.cleanup();this.log.info("Periodic cleanup completed",{deleted:e}),t();})}async store(t){this.messages.size>=this.config.maxRecords&&this.evictLRU(1e3),this.config.lruEnabled&&this.updateAccessOrder(t.id);let e={message:t,status:"pending",processedBy:null,processedAt:null,retryCount:0,error:null,createdAt:Date.now(),updatedAt:Date.now()};return this.messages.set(t.id,e),this.sessionMessages.has(t.sessionId)||this.sessionMessages.set(t.sessionId,new Set),this.sessionMessages.get(t.sessionId).add(t.id),this.log.debug("message stored",{id:t.id,sessionId:t.sessionId,type:t.type,total:this.messages.size}),e}get(t){let e=this.messages.get(t);return e&&this.config.lruEnabled&&this.updateAccessOrder(t),e}async updateStatus(t,e,n={}){let s=this.messages.get(t);if(!s){this.log.warn("message not found for status update",{messageId:t});return}s.status=e,s.updatedAt=Date.now(),n.processedBy&&(s.processedBy=n.processedBy),(e==="completed"||e==="failed")&&(s.processedAt=Date.now()),n.error&&(s.error=n.error),this.log.debug("message status updated",{id:t,status:e,processedBy:n.processedBy});}incrementRetry(t){let e=this.messages.get(t);return e?(e.retryCount++,e.updatedAt=Date.now(),e.retryCount):0}isProcessed(t){let e=this.messages.get(t);return e?e.status==="completed"||e.status==="processing":false}getSessionHistory(t,e=100){let n=this.sessionMessages.get(t);if(!n)return [];let s=[];for(let i of n){let r=this.messages.get(i);r&&s.push(r);}return s.sort((i,r)=>i.createdAt-r.createdAt),s.slice(-e)}getPendingMessages(t){let e=[];for(let n of this.messages.values())n.status==="pending"&&(!t||n.message.sessionId===t)&&e.push(n);return e}getFailedMessages(t=3){let e=[];for(let n of this.messages.values())n.status==="failed"&&n.retryCount<t&&e.push(n);return e}cleanup(){let t=Date.now(),e=this.config.maxRetentionDays*24*60*60*1e3,n=[];for(let[s,i]of this.messages)if((t-i.createdAt>e||i.status==="completed")&&(n.push(s),n.length>=this.config.cleanupBatchSize))break;for(let s of n)this.deleteMessage(s);return n.length>0&&this.log.info("cleanup completed",{deleted:n.length,remaining:this.messages.size}),n.length}evictLRU(t){if(!this.config.lruEnabled||this.accessOrder.length===0)return;let e=0;for(;e<t&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&(this.deleteMessage(n),e++);}this.log.info("LRU eviction completed",{evicted:e,remaining:this.messages.size});}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e>-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t);}deleteMessage(t){let e=this.messages.get(t);if(e){let n=this.sessionMessages.get(e.message.sessionId);n&&(n.delete(t),n.size===0&&this.sessionMessages.delete(e.message.sessionId)),this.messages.delete(t);let s=this.accessOrder.indexOf(t);s>-1&&this.accessOrder.splice(s,1);}}getStats(){let t={total:this.messages.size,pending:0,processing:0,completed:0,failed:0,cancelled:0,sessions:this.sessionMessages.size};for(let e of this.messages.values())t[e.status]++;return t}async close(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.messages.clear(),this.sessionMessages.clear(),this.accessOrder=[],this.log.info("MessageStore closed");}};var z=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:session-store"}));a$2(this,"config");a$2(this,"sessions",new Map);a$2(this,"channelSessions",new Map);a$2(this,"autoSaveTimer",null);a$2(this,"isDirty",false);this.config={storagePath:t.storagePath??"./data/gateway-sessions",autoSaveInterval:t.autoSaveInterval??6e4,maxRetentionDays:t.maxRetentionDays??7,enablePersistence:t.enablePersistence??true};}async initialize(){if(!this.config.enablePersistence){this.log.info("session persistence disabled");return}await this.ensureStorageDir(),await this.load(),this.startAutoSave(),this.log.info("session store initialized",{sessionCount:this.sessions.size,storagePath:this.config.storagePath});}async close(){this.stopAutoSave(),this.isDirty&&await this.save(),this.log.info("session store closed");}async set(t){this.sessions.set(t.id,t),this.channelSessions.has(t.channel.channelId)||this.channelSessions.set(t.channel.channelId,new Set),this.channelSessions.get(t.channel.channelId).add(t.id),this.markDirty();}get(t){return this.sessions.get(t)}async delete(t){let e=this.sessions.get(t);if(!e)return;this.sessions.delete(t);let n=this.channelSessions.get(e.channel.channelId);n&&(n.delete(t),n.size===0&&this.channelSessions.delete(e.channel.channelId)),this.markDirty();}getAll(){return [...this.sessions.values()]}getByChannel(t){let e=this.channelSessions.get(t);return e?[...e].map(n=>this.sessions.get(n)).filter(n=>n!==void 0):[]}size(){return this.sessions.size}markDirty(){this.isDirty=true;}async save(){if(!this.config.enablePersistence)return;let t=this.getSessionFilePath(),e=this.serializeAll();try{await this.ensureStorageDir(),await R.promises.writeFile(t,JSON.stringify(e,null,2),"utf-8"),this.isDirty=!1,this.log.debug("sessions saved",{count:e.length});}catch(n){throw this.log.error("failed to save sessions",{error:n}),n}}async load(){if(!this.config.enablePersistence)return;let t=this.getSessionFilePath();try{if(!R.existsSync(t)){this.log.debug("no saved sessions found");return}let e=await R.promises.readFile(t,"utf-8"),n=JSON.parse(e);this.sessions.clear(),this.channelSessions.clear();let s=Date.now(),i=this.config.maxRetentionDays*24*60*60*1e3;for(let r of n){if(s-r.lastActiveAt>i)continue;let l={id:r.id,channel:r.channel,backendSessionId:r.backendSessionId,subscribers:new Set(r.subscribers),state:r.state,createdAt:r.createdAt,lastActiveAt:r.lastActiveAt};this.sessions.set(l.id,l),this.channelSessions.has(l.channel.channelId)||this.channelSessions.set(l.channel.channelId,new Set),this.channelSessions.get(l.channel.channelId).add(l.id);}this.log.info("sessions loaded",{loaded:this.sessions.size,skipped:n.length-this.sessions.size});}catch(e){this.log.error("failed to load sessions",{error:e});}}serializeAll(){let t=[];for(let e of this.sessions.values())t.push(this.serialize(e));return t}serialize(t){return {id:t.id,channel:t.channel,backendSessionId:t.backendSessionId,subscribers:[...t.subscribers],state:t.state,createdAt:t.createdAt,lastActiveAt:t.lastActiveAt}}getSessionFilePath(){return _.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){R.existsSync(this.config.storagePath)||await R.promises.mkdir(this.config.storagePath,{recursive:true});}startAutoSave(){this.autoSaveTimer||(this.autoSaveTimer=setInterval(async()=>{this.isDirty&&await this.save();},this.config.autoSaveInterval));}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null);}async cleanup(){let t=Date.now(),e=this.config.maxRetentionDays*24*60*60*1e3,n=[];for(let s of this.sessions.values())t-s.lastActiveAt>e&&n.push(s.id);for(let s of n)await this.delete(s);return n.length>0&&(this.log.info("cleaned up expired sessions",{count:n.length}),await this.save()),n.length}getStats(){let t={total:this.sessions.size,byStatus:{active:0,idle:0,closed:0},byPlatform:{}};for(let e of this.sessions.values()){t.byStatus[e.state.status]++;let n=e.channel.platform;t.byPlatform[n]=(t.byPlatform[n]||0)+1;}return t}};var Yt="./data/gateway",Xt="contacts",Zt="index.json",$=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:contact-store"}));a$2(this,"baseDir");a$2(this,"contactDir");a$2(this,"indexPath");a$2(this,"index");a$2(this,"indexFileMap");a$2(this,"dirty",false);a$2(this,"saveTimer",null);a$2(this,"SAVE_DEBOUNCE_MS",1e3);this.baseDir=t.baseDir??Yt,this.contactDir=_.join(this.baseDir,Xt),this.indexPath=_.join(this.contactDir,Zt),this.index={byUid:{},byUsername:{},byEmail:{},byPhone:{},byPlatform:{},updatedAt:0},this.indexFileMap={};}async initialize(){await this.ensureDir(this.contactDir),await this.loadIndex(),this.log.info("contact store initialized",{baseDir:this.baseDir,contactCount:Object.keys(this.index.byUid).length});}async ensureDir(t){try{await I.mkdir(t,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async loadIndex(){try{let t=await I.readFile(this.indexPath,"utf-8");this.index=JSON.parse(t),await this.rebuildFileMap();}catch(t){t.code!=="ENOENT"&&this.log.warn("failed to load contact index, starting fresh",{error:String(t)}),this.index={byUid:{},byUsername:{},byEmail:{},byPhone:{},byPlatform:{},updatedAt:0};}}async saveIndex(){this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=setTimeout(async()=>{await this.doSaveIndex();},this.SAVE_DEBOUNCE_MS);}async doSaveIndex(){try{this.index.updatedAt=Date.now(),await I.writeFile(this.indexPath,JSON.stringify(this.index,null,2),"utf-8"),this.dirty=!1;}catch(t){this.log.error("failed to save contact index",{error:String(t)});}}async rebuildFileMap(){this.indexFileMap={};for(let t of Object.keys(this.index.byUid)){let e=oe(t);if(e){let n=this.getFilePath(e.platform,e.stableId);this.indexFileMap[t]=n;}}}getFilePath(t,e){let n=this.sanitizeFilename(e);return _.join(this.contactDir,t,`${n}.json`)}sanitizeFilename(t){return t.replace(/[/\\:*?"<>|]/g,"_")}getPlatformDir(t){return _.join(this.contactDir,t)}async save(t){let{platform:e,stableId:n,uid:s}=t,i=this.getFilePath(e,n);return await this.ensureDir(_.dirname(i)),await I.writeFile(i,JSON.stringify(t,null,2),"utf-8"),this.index.byUid[s]=i,this.indexFileMap[s]=i,this.index.byPlatform[e]||(this.index.byPlatform[e]=[]),this.index.byPlatform[e].includes(s)||this.index.byPlatform[e].push(s),this.updateSearchIndices(t),this.dirty=true,await this.saveIndex(),this.log.debug("contact saved",{uid:s,platform:e,stableId:n}),t}async create(t){let e=ke(t);return this.save(e)}async getOrCreate(t,e,n){let s=await this.findByPlatformId(t,e);return s||this.create({platform:t,stableId:e,profile:n})}async findByUid(t){let e=oe(t);return e?this.findByPlatformId(e.platform,e.stableId):null}async findByPlatformId(t,e){let n=re(t,e),s=this.index.byUid[n];if(s)try{let r=await I.readFile(s,"utf-8");return JSON.parse(r)}catch(r){r.code!=="ENOENT"&&this.log.warn("failed to read contact file",{uid:n,filePath:s,error:String(r)}),delete this.index.byUid[n],this.dirty=true;}let i=this.getFilePath(t,e);try{let r=await I.readFile(i,"utf-8"),l=JSON.parse(r);return this.index.byUid[n]=i,this.indexFileMap[n]=i,this.dirty=!0,await this.saveIndex(),l}catch{return null}}async update(t,e){let n=await this.findByUid(t);if(!n)return null;let s={...n,profile:e.profile?{...n.profile,...e.profile}:n.profile,aliases:e.aliases?{...n.aliases,...e.aliases}:n.aliases,metadata:e.metadata?{...n.metadata,...e.metadata}:n.metadata,lastSeenAt:Date.now()};return this.save(s)}async touch(t){let e=await this.findByUid(t);e&&(e.lastSeenAt=Date.now(),await this.save(e));}async delete(t){let e=await this.findByUid(t);if(!e)return false;let{platform:n,stableId:s}=e,i=this.index.byUid[t]||this.getFilePath(n,s);try{await I.unlink(i);}catch(r){r.code!=="ENOENT"&&this.log.warn("failed to delete contact file",{uid:t,filePath:i,error:String(r)});}return delete this.index.byUid[t],delete this.indexFileMap[t],this.index.byPlatform[n]&&(this.index.byPlatform[n]=this.index.byPlatform[n].filter(r=>r!==t)),this.removeFromSearchIndices(e),this.dirty=true,await this.saveIndex(),this.log.debug("contact deleted",{uid:t}),true}async listByPlatform(t,e=100,n=0){let s=this.index.byPlatform[t]||[],i=s.length,r=s.slice(n,n+e),l=[];for(let g of r){let u=await this.findByUid(g);u&&l.push(u);}return {contacts:l,total:i,hasMore:n+e<i}}async findByUsername(t){let e=t.toLowerCase(),n=this.index.byUsername[e];return n?this.findByUid(n):null}async findByEmail(t){let e=t.toLowerCase(),n=this.index.byEmail[e];return n?this.findByUid(n):null}async findByPhone(t){let e=t.replace(/\s/g,""),n=this.index.byPhone[e];return n?this.findByUid(n):null}async search(t){if(t.platform){let g=await this.listByPlatform(t.platform,t.limit,t.offset),u=g.contacts;if(t.username){let C=t.username.toLowerCase();u=u.filter(w=>w.profile.username?.toLowerCase().includes(C));}if(t.email){let C=t.email.toLowerCase();u=u.filter(w=>w.profile.email?.toLowerCase().includes(C));}if(t.phone){let C=t.phone.replace(/\s/g,"");u=u.filter(w=>w.profile.phone?.replace(/\s/g,"").includes(C));}return {contacts:u,total:g.total,hasMore:g.hasMore}}let e=[];for(let g of Object.keys(this.index.byPlatform)){let u=await this.listByPlatform(g,1e3,0);e.push(...u.contacts);}let n=e;if(t.username){let g=t.username.toLowerCase();n=n.filter(u=>u.profile.username?.toLowerCase().includes(g));}if(t.email){let g=t.email.toLowerCase();n=n.filter(u=>u.profile.email?.toLowerCase().includes(g));}if(t.phone){let g=t.phone.replace(/\s/g,"");n=n.filter(u=>u.profile.phone?.replace(/\s/g,"").includes(g));}let s=n.length,i=t.limit??100,r=t.offset??0;return {contacts:n.slice(r,r+i),total:s,hasMore:r+i<s}}async count(t){return t?(this.index.byPlatform[t]||[]).length:Object.keys(this.index.byUid).length}async exists(t){return await this.findByUid(t)!==null}async addAlias(t,e,n){let s=await this.findByUid(t);if(!s)return null;let i={...s,aliases:{...s.aliases,[e]:{...s.aliases[e],...n}},lastSeenAt:Date.now()};return this.save(i)}async close(){this.saveTimer&&clearTimeout(this.saveTimer),this.dirty&&await this.doSaveIndex(),this.log.info("contact store closed");}updateSearchIndices(t){let{uid:e,profile:n}=t;n.username&&(this.index.byUsername[n.username.toLowerCase()]=e),n.email&&(this.index.byEmail[n.email.toLowerCase()]=e),n.phone&&(this.index.byPhone[n.phone.replace(/\s/g,"")]=e);}removeFromSearchIndices(t){let{uid:e,profile:n}=t;if(n.username){let s=n.username.toLowerCase();this.index.byUsername[s]===e&&delete this.index.byUsername[s];}if(n.email){let s=n.email.toLowerCase();this.index.byEmail[s]===e&&delete this.index.byEmail[s];}if(n.phone){let s=n.phone.replace(/\s/g,"");this.index.byPhone[s]===e&&delete this.index.byPhone[s];}}};var Ge=class{constructor(t){a$2(this,"cache",new Map);a$2(this,"maxSize");this.maxSize=t;}get(t){let e=this.cache.get(t);return e!==void 0&&(this.cache.delete(t),this.cache.set(t,e)),e}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n);}this.cache.set(t,e);}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear();}get size(){return this.cache.size}},j=class{constructor(t,e={}){a$2(this,"store",t);a$2(this,"cache");a$2(this,"usernameIndex");a$2(this,"emailIndex");a$2(this,"phoneIndex");a$2(this,"platformIndex");a$2(this,"initialized",false);this.cache=new Ge(e.cacheSize??1e3),this.usernameIndex=new Map,this.emailIndex=new Map,this.phoneIndex=new Map,this.platformIndex=new Map;}async initialize(){this.initialized||("initialize"in this.store&&typeof this.store.initialize=="function"&&await this.store.initialize(),await this.warmCache(),this.initialized=true);}async warmCache(){try{let t=["telegram","discord","slack","feishu","wechat","webchat","signal","nostr"];for(let e of t)try{let n=await this.store.listByPlatform(e,1e3,0);for(let s of n.contacts)this.cacheContact(s);}catch{}}catch{}}cacheContact(t){let{uid:e,profile:n}=t;this.cache.set(e,t),n.username&&this.usernameIndex.set(n.username.toLowerCase(),e),n.email&&this.emailIndex.set(n.email.toLowerCase(),e),n.phone&&this.phoneIndex.set(n.phone.replace(/\s/g,""),e),this.platformIndex.has(t.platform)||this.platformIndex.set(t.platform,new Set),this.platformIndex.get(t.platform).add(e);}invalidateContact(t){let{uid:e,profile:n}=t;if(this.cache.delete(e),n.username){let i=n.username.toLowerCase();this.usernameIndex.get(i)===e&&this.usernameIndex.delete(i);}if(n.email){let i=n.email.toLowerCase();this.emailIndex.get(i)===e&&this.emailIndex.delete(i);}if(n.phone){let i=n.phone.replace(/\s/g,"");this.phoneIndex.get(i)===e&&this.phoneIndex.delete(i);}let s=this.platformIndex.get(t.platform);s&&s.delete(e);}async save(t){this.invalidateContact(t);let e=await this.store.save(t);return this.cacheContact(e),e}async create(t){let e=await this.store.create(t);return this.cacheContact(e),e}async getOrCreate(t,e,n){let s=this.cache.get(`${t}:${e}`);if(s)return s;let i=await this.store.getOrCreate(t,e,n);return this.cacheContact(i),i}async findByUid(t){let e=this.cache.get(t);if(e)return e;let n=await this.store.findByUid(t);return n&&this.cacheContact(n),n}async findByPlatformId(t,e){return this.findByUid(`${t}:${e}`)}async update(t,e){let n=await this.cache.get(t);n&&this.invalidateContact(n);let s=await this.store.update(t,e);return s&&this.cacheContact(s),s}async touch(t){await this.store.touch(t);}async delete(t){let e=await this.cache.get(t);return e&&this.invalidateContact(e),this.store.delete(t)}async listByPlatform(t,e=100,n=0){return this.store.listByPlatform(t,e,n)}async findByUsername(t){let e=t.toLowerCase(),n=this.usernameIndex.get(e);return n?this.findByUid(n):this.store.findByUsername(t)}async findByEmail(t){let e=t.toLowerCase(),n=this.emailIndex.get(e);return n?this.findByUid(n):this.store.findByEmail(t)}async findByPhone(t){let e=t.replace(/\s/g,""),n=this.phoneIndex.get(e);return n?this.findByUid(n):this.store.findByPhone(t)}async search(t){return this.store.search(t)}async count(t){return t?this.platformIndex.get(t)?.size??0:this.cache.size}async exists(t){return this.cache.has(t)?true:this.store.exists(t)}async addAlias(t,e,n){let s=await this.store.addAlias(t,e,n);return s&&(this.invalidateContact(s),this.cacheContact(s)),s}async close(){this.cache.clear(),this.usernameIndex.clear(),this.emailIndex.clear(),this.phoneIndex.clear(),this.platformIndex.clear(),"close"in this.store&&typeof this.store.close=="function"&&await this.store.close();}};var q=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:session"}));a$2(this,"sessionStore");a$2(this,"config");a$2(this,"initialized",false);this.config={enablePersistence:t.enablePersistence??true,storagePath:t.storagePath??"./data/gateway-sessions",autoSaveInterval:t.autoSaveInterval??6e4,maxRetentionDays:t.maxRetentionDays??7},this.sessionStore=new z({storagePath:this.config.storagePath,autoSaveInterval:this.config.autoSaveInterval,maxRetentionDays:this.config.maxRetentionDays,enablePersistence:this.config.enablePersistence});}async initialize(){this.initialized||(await this.sessionStore.initialize(),this.initialized=true,this.log.info("session manager initialized",{sessionCount:this.sessionStore.size(),persistenceEnabled:this.config.enablePersistence}));}async close(){await this.sessionStore.close(),this.log.info("session manager closed");}async getOrCreate(t,e={}){let n=Me(t),s=this.sessionStore.get(n);return s?(s.lastActiveAt=Date.now(),this.log.debug("session found",{sessionId:n}),s):(s={id:n,channel:t,backendSessionId:null,subscribers:new Set,state:Ae(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(s),this.log.info("session created",{sessionId:n,platform:t.platform,channelId:t.channelId,chatId:t.chatId,userId:t.userId}),s)}get(t){return this.sessionStore.get(t)}async closeSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.state.status="closed",await this.sessionStore.delete(t),this.log.info("session closed",{sessionId:t});}async closeById(t){return this.closeSession(t)}async bindBackendSession(t,e){let n=this.sessionStore.get(t);if(!n)throw new Error(`Session not found: ${t}`);n.backendSessionId=e,await this.sessionStore.set(n),this.log.info("backend session bound",{gatewaySessionId:t,backendSessionId:e});}async unbindBackendSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.backendSessionId=null,await this.sessionStore.set(e),this.log.info("backend session unbound",{gatewaySessionId:t});}getState(t){return this.sessionStore.get(t)?.state}async incrementMessageCountOrCreate(t,e){let n=this.sessionStore.get(t);if(!n){let s=e??{platform:"api",channelId:"default"};n=await this.getOrCreate(s);}return n.state.messageCount++,n.state.lastMessageAt=Date.now(),n.lastActiveAt=Date.now(),await this.sessionStore.set(n),n}async incrementMessageCount(t){let e=this.sessionStore.get(t);e&&(e.state.messageCount++,e.state.lastMessageAt=Date.now(),e.lastActiveAt=Date.now(),await this.sessionStore.set(e));}async addSubscriber(t,e){let n=this.sessionStore.get(t);if(!n){this.log.warn("session not found",{sessionId:t});return}n.subscribers.add(e),await this.sessionStore.set(n),this.log.debug("subscriber added to session",{sessionId:t,subscriberId:e});}async removeSubscriber(t,e){let n=this.sessionStore.get(t);n&&(n.subscribers.delete(e),await this.sessionStore.set(n),this.log.debug("subscriber removed from session",{sessionId:t,subscriberId:e}));}query(t){let e=this.sessionStore.getAll();return t.platform&&(e=e.filter(n=>n.channel.platform===t.platform)),t.channelId&&(e=e.filter(n=>n.channel.channelId===t.channelId)),t.userId&&(e=e.filter(n=>n.channel.userId===t.userId)),t.status&&(e=e.filter(n=>n.state.status===t.status)),e}getSessionsByChannel(t){return this.sessionStore.getByChannel(t)}getAllSessions(){return this.sessionStore.getAll()}getSessionCount(){return this.sessionStore.size()}async cleanupIdleSessions(t){let e=Date.now(),n=[];for(let s of this.sessionStore.getAll())s.state.status==="idle"&&e-s.lastActiveAt>t&&n.push(s.id);for(let s of n)await this.closeSession(s);return n.length>0&&this.log.info("cleaned up idle sessions",{count:n.length}),n.length}async save(){this.log.debug("session save triggered");}getStats(){return this.sessionStore.getStats()}};var K=class{constructor(t={}){a$2(this,"log",a.create({service:"gateway:plugin-loader"}));a$2(this,"plugins",new Map);a$2(this,"messageHandler",null);a$2(this,"healthCheckTimer",null);a$2(this,"config");a$2(this,"backoffPolicy");this.config={pluginDir:t.pluginDir??"./plugins",autoDiscover:t.autoDiscover??false,healthCheckInterval:t.healthCheckInterval??6e4,healthCheckTimeout:t.healthCheckTimeout??5e3,autoReconnect:t.autoReconnect??true,maxReconnectAttempts:t.maxReconnectAttempts??10,reconnectInitialDelay:t.reconnectInitialDelay??5e3,reconnectMaxDelay:t.reconnectMaxDelay??3e5},this.backoffPolicy={initialMs:this.config.reconnectInitialDelay,maxMs:this.config.reconnectMaxDelay,factor:2,jitter:.1};}setMessageHandler(t){this.messageHandler=t;}async register(t,e){if(this.plugins.has(t.id)){this.log.warn("plugin already registered",{id:t.id});return}this.plugins.set(t.id,{plugin:t,config:e,started:false,reconnectAttempts:0}),this.log.info("plugin registered",{id:t.id,platform:t.platform,name:t.name});}async unregister(t){let e=this.plugins.get(t);if(!e){this.log.warn("plugin not found",{id:t});return}this.cancelReconnect(t),e.started&&await this.stop(t),this.plugins.delete(t),this.log.info("plugin unregistered",{id:t});}async start(t){let e=this.plugins.get(t);if(!e)throw new M(`Plugin not found: ${t}`,{code:"PLUGIN_NOT_FOUND",recoverable:false});if(e.started){this.log.warn("plugin already started",{id:t});return}if(!this.messageHandler)throw new M("Message handler not set",{code:"PLUGIN_ERROR",recoverable:false});if(!e.config.enabled){this.log.warn("plugin is disabled",{id:t});return}this.log.info("starting plugin",{id:t});try{await e.plugin.start(e.config,this.messageHandler),e.started=!0,e.reconnectAttempts=0,this.log.info("plugin started",{id:t});}catch(n){throw this.log.error("failed to start plugin",{id:t,error:String(n)}),this.scheduleReconnect(t),n}}async stop(t){let e=this.plugins.get(t);if(!e){this.log.warn("plugin not found",{id:t});return}if(!e.started){this.log.warn("plugin not started",{id:t});return}this.cancelReconnect(t),this.log.info("stopping plugin",{id:t});try{await e.plugin.stop(),e.started=!1,this.log.info("plugin stopped",{id:t});}catch(n){e.started=false,this.log.error("failed to stop plugin",{id:t,error:String(n)});}}async startAll(){let t=[];for(let[e,n]of this.plugins){if(!n.config.enabled){this.log.debug("skipping disabled plugin",{id:e});continue}try{await this.start(e);}catch(s){t.push({id:e,error:s instanceof Error?s:new Error(String(s))});}}t.length>0&&this.log.warn("some plugins failed to start",{count:t.length,errors:t.map(e=>({id:e.id,error:e.error.message}))});}async stopAll(){this.stopHealthCheckTimer();for(let[t]of this.plugins)await this.stop(t);}getPlugin(t){return this.plugins.get(t)?.plugin}getAllPlugins(){return [...this.plugins.values()].map(t=>t.plugin)}getRunningPlugins(){return [...this.plugins.values()].filter(t=>t.started).map(t=>t.plugin)}isRunning(t){return this.plugins.get(t)?.started??false}async healthCheck(t){let e=this.plugins.get(t);if(!e)return {healthy:false,lastCheck:Date.now(),error:"Plugin not found"};if(!e.started)return {healthy:false,lastCheck:Date.now(),error:"Plugin not running"};try{let n=await Promise.race([e.plugin.healthCheck(),new Promise((s,i)=>setTimeout(()=>i(new Error("Health check timeout")),this.config.healthCheckTimeout))]);return e.lastHealthCheck=n,n}catch(n){let s={healthy:false,lastCheck:Date.now(),error:n instanceof Error?n.message:String(n)};return e.lastHealthCheck=s,s}}async healthCheckAll(){let t=new Map;for(let[e]of this.plugins)t.set(e,await this.healthCheck(e));return t}startHealthCheckTimer(){this.healthCheckTimer||(this.healthCheckTimer=setInterval(async()=>{for(let[t,e]of this.plugins){if(!e.started)continue;let n=await this.healthCheck(t);n.healthy||(this.log.warn("plugin health check failed",{id:t,error:n.error}),this.config.autoReconnect&&(e.started=false,this.scheduleReconnect(t)));}},this.config.healthCheckInterval),this.log.info("health check timer started",{interval:this.config.healthCheckInterval}));}stopHealthCheckTimer(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null,this.log.info("health check timer stopped"));}scheduleReconnect(t){if(!this.config.autoReconnect)return;let e=this.plugins.get(t);if(!e)return;if(e.reconnectAttempts>=this.config.maxReconnectAttempts){this.log.error("max reconnect attempts reached",{id:t,attempts:e.reconnectAttempts});return}let n=this.calculateBackoffDelay(e.reconnectAttempts);e.reconnectAttempts++,this.log.info("scheduling reconnect",{id:t,attempt:e.reconnectAttempts,delay:n}),e.reconnectTimer=setTimeout(async()=>{try{await this.start(t),this.log.info("reconnect successful",{id:t});}catch(s){this.log.warn("reconnect failed",{id:t,error:String(s)}),this.scheduleReconnect(t);}},n),e.reconnectTimer.unref?.();}cancelReconnect(t){let e=this.plugins.get(t);e&&e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0);}calculateBackoffDelay(t){let e=Math.min(this.backoffPolicy.initialMs*this.backoffPolicy.factor**t,this.backoffPolicy.maxMs),n=e*this.backoffPolicy.jitter*(Math.random()*2-1);return Math.floor(e+n)}};var A=class extends Error{constructor(e,n,s){super(e);a$2(this,"code",n);a$2(this,"configuredChannels",s);this.name="ChannelSelectionError";}},V=a.create({service:"gateway:channel-selection"});function G(c){if(!(!c||typeof c!="string"))return c.toLowerCase().trim()}async function Le(c){let{channel:t,sessionId:e,userId:n,defaultChannel:s,fallbackChannels:i,sessionManager:r,pluginLoader:l,contactStore:g}=c,u=G(t);if(u){let m=De(u,l);if(m){if(n&&g){let v=await en(u,n,g,l);if(v)return v}return m}if(e){let v=et(e,r);if(v)return V.debug("explicit channel unavailable, using session-bound channel as fallback",{explicitChannel:u,sessionChannel:v.channel}),v}throw new A(`Channel \u4E0D\u53EF\u7528\u6216\u672A\u914D\u7F6E: ${u}`,"CHANNEL_UNAVAILABLE",[])}if(e){let m=et(e,r);if(m)return m}if(n&&g){let m=await tn(n,g,l);if(m)return m}let C=Oe(l);if(C.length===0)throw new A("\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684 Channel\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F\u3002\u8BF7\u81F3\u5C11\u914D\u7F6E\u4E00\u4E2A Channel\u3002","NO_CHANNEL",[]);let w=G(s);if(w){let m=De(w,l);if(m)return V.debug("using default channel",{channel:w}),{...m,source:"default"};V.warn("default channel unavailable",{channel:w});}if(C.length===1){let m=C[0],v=l?.getPlugin(m);return {channel:m,source:"single-configured",channelInfo:{platform:v?.platform??"api",channelId:m}}}let L=(i??[]).map(G).filter(m=>m!==void 0);for(let m of L){let v=De(m,l);if(v)return V.debug("using fallback channel",{channel:m}),{...v,source:"fallback"};V.debug("fallback channel unavailable, trying next",{channel:m});}throw w?new A(`\u914D\u7F6E\u7684\u9ED8\u8BA4 Channel \u4E0D\u53EF\u7528: ${w}`,"CHANNEL_UNAVAILABLE",C):new A(`\u9700\u8981\u660E\u786E\u6307\u5B9A Channel\uFF08\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF09: ${C.join(", ")}\u3002\u8BF7\u901A\u8FC7 channel \u53C2\u6570\u6307\u5B9A\u8981\u4F7F\u7528\u7684 Channel\uFF0C\u6216\u5728 gateway.json \u4E2D\u914D\u7F6E defaults.channel\u3002`,"MULTIPLE_CHANNELS",C)}function De(c,t){if(!t)return null;let e=t.getPlugin(c);if(e&&t.isRunning(c))return {channel:c,source:"explicit",channelInfo:{platform:e.platform,channelId:c}};let n=G(c);if(!n)return null;let s=t.getAllPlugins();for(let i of s)if(t.isRunning(i.id)&&G(i.platform)===n)return {channel:i.id,source:"explicit",channelInfo:{platform:i.platform,channelId:i.id}};return null}function et(c,t){if(!t)return null;let e=t.get(c);return e?{channel:e.channel.channelId,source:"session-bound",channelInfo:e.channel}:null}async function en(c,t,e,n){let s=n?.getPlugin(c);if(!s)return null;let i=await e.findByPlatformId(s.platform,t);return i?{channel:c,source:"explicit",channelInfo:{platform:s.platform,channelId:c,userId:i.stableId,chatId:i.stableId}}:null}async function tn(c,t,e){let n=Oe(e);if(n.length===0)return null;for(let s of n){let i=e?.getPlugin(s);if(!i)continue;let r=await t.findByPlatformId(i.platform,c);if(r)return {channel:s,source:"single-configured",channelInfo:{platform:i.platform,channelId:s,userId:r.stableId,chatId:r.stableId}}}return null}function Oe(c){if(!c)return [];let t=[],e=c.getAllPlugins();for(let n of e)c.isRunning(n.id)&&t.push(n.id);return t}function Ue(c){switch(c.code){case "NO_CHANNEL":return "\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684 Channel\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F\u3002\u8BF7\u5728 gateway.json \u4E2D\u914D\u7F6E\u81F3\u5C11\u4E00\u4E2A Channel\u3002";case "MULTIPLE_CHANNELS":return `\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF0C\u9700\u8981\u660E\u786E\u6307\u5B9A: ${c.configuredChannels?.join(", ")||""}\u3002\u8BF7\u901A\u8FC7 channel \u53C2\u6570\u6307\u5B9A\u8981\u4F7F\u7528\u7684 Channel\uFF0C\u6216\u5728 gateway.json \u4E2D\u914D\u7F6E defaults.channel \u4F5C\u4E3A\u9ED8\u8BA4\u503C\u3002`;case "CHANNEL_UNAVAILABLE":return c.message;case "UNKNOWN_CHANNEL":return `\u672A\u77E5\u7684 Channel: ${c.message}\u3002\u8BF7\u68C0\u67E5 Channel ID \u662F\u5426\u6B63\u786E\u3002`;default:return c.message}}var d=a.create({service:"gateway:websocket-server"});function on(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ie(c,t){for(let[e,n]of t.entries())if(n===c)return e;return null}var N=class{constructor(t={}){a$2(this,"config");a$2(this,"server",null);a$2(this,"wss",null);a$2(this,"httpsServer",null);a$2(this,"httpRedirectServer",null);a$2(this,"connections",new Map);a$2(this,"subscriptions",new Map);a$2(this,"sessionSubscriptions",new Map);a$2(this,"sessionLastActivity",new Map);a$2(this,"cleanupInterval",null);a$2(this,"heartbeatInterval",null);a$2(this,"startTime",0);a$2(this,"running",false);a$2(this,"channelResolveParams",null);a$2(this,"messageSender",null);a$2(this,"pluginLoaderRef",null);this.config={...Ne,...t};}setChannelResolveDeps(t){this.channelResolveParams=t,d.debug("channel resolve deps set",{hasSessionManager:!!t.sessionManager,hasPluginLoader:!!t.pluginLoader,hasContactStore:!!t.contactStore});}setMessageSender(t){this.messageSender=t,d.debug("message sender set",{hasSender:!!t});}setPluginLoader(t){this.pluginLoaderRef=t;}getChannelResolveParams(){return this.channelResolveParams?this.channelResolveParams:{}}async start(){if(this.running){d.warn("WebSocket server is already running");return}d.debug("WebSocket server start: checking configuration",{port:this.config.port,hostname:this.config.hostname,path:this.config.path,https:this.config.https?.enabled??false}),this.startTime=Date.now();let t={onOpen:(s,i)=>{this.handleConnection(i);},onMessage:async(s,i)=>{try{let r=JSON.parse(s.data.toString());await this.handleMessage(i,r);}catch(r){d.error("Error processing WebSocket message",{error:r.message}),this.sendError(i,r.message);}},onClose:(s,i)=>{this.handleDisconnection(i);},onError:(s,i)=>{d.error("WebSocket error",{error:s.type});}},e=this.config.https?.enabled??false;d.debug("WebSocket server start: choosing server type",{https:e});try{e?(d.debug("WebSocket server start: starting HTTPS server"),await this.startHTTPSServer(t)):(d.debug("WebSocket server start: starting HTTP server"),await this.startHTTPServer(t)),d.debug("WebSocket server start: HTTP/HTTPS server started successfully");}catch(s){throw d.error("WebSocket server start: HTTP/HTTPS server failed",{error:s instanceof Error?s.message:String(s)}),s}d.debug("WebSocket server start: server initialization complete"),this.cleanupInterval=setInterval(()=>this.cleanupExpiredSessions(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let n=e?"wss":"ws";d.info("WebSocket server started",{url:`${n}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(t){d.debug("HTTP server start: creating server",{port:this.config.port,hostname:this.config.hostname}),this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true}),d.debug("HTTP server start: server created, checking raw server");let e=this.server.raw;e?(d.debug("HTTP server start: raw server available, setting up WebSocket upgrade"),this.setupWebSocketUpgrade(e,t),d.debug("HTTP server start: WebSocket upgrade configured")):d.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(t){let e=this.config.https,n=this.loadSSLCertificates(e);if(!n){d.error("Failed to load SSL certificates, falling back to HTTP"),await this.startHTTPServer(t);return}this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let s=this.server.raw;this.httpsServer=sn.createServer(n,s.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,t),await new Promise(i=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{d.info("HTTPS server started",{port:this.config.port,hostname:this.config.hostname}),i();});}),e.forceRedirect&&e.httpPort&&this.startHTTPRedirectServer(e.httpPort);}loadSSLCertificates(t){try{return t.cert&&t.key?{cert:t.cert,key:t.key}:t.certPath&&t.keyPath?{cert:R__default.readFileSync(t.certPath),key:R__default.readFileSync(t.keyPath)}:null}catch(e){return d.error("Failed to load SSL certificates",{error:e.message}),null}}setupWebSocketUpgrade(t,e){this.wss=new WebSocketServer({noServer:true}),t.on("upgrade",(n,s,i)=>{try{let l=new URL(n.url||"/",`http://${n.headers.host}`).pathname;(l===this.config.path||this.config.path==="/"&&(l==="/"||l===""))&&this.wss.handleUpgrade(n,s,i,g=>{e.onOpen?.({type:"open"},g),g.on("message",u=>{e.onMessage?.({data:u},g);}),g.on("close",(u,C)=>{e.onClose?.({code:u,reason:C},g);}),g.on("error",u=>{e.onError?.({type:"error",message:u.message},g);});});}catch{}});}startHTTPRedirectServer(t){this.httpRedirectServer=rn.createServer((e,n)=>{let i=`https://${e.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${e.url}`;d.debug("Redirecting HTTP to HTTPS",{from:e.url,to:i}),n.writeHead(301,{Location:i,"Content-Type":"text/plain"}),n.end(`Redirecting to ${i}`);}),this.httpRedirectServer.listen(t,this.config.hostname,()=>{d.info("HTTP redirect server started",{port:t,hostname:this.config.hostname});});}async stop(){if(!this.running){d.warn("WebSocket server is not running");return}d.info("Stopping WebSocket server"),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let[t,e]of this.connections.entries())try{e.close(1e3,"Server shutting down");}catch(n){d.debug("Error closing connection",{clientId:t,error:String(n)});}this.connections.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.sessionLastActivity.clear(),this.wss&&(this.wss.close(),this.wss=null),this.httpsServer&&(await new Promise(t=>{this.httpsServer.close(()=>t());}),this.httpsServer=null),this.httpRedirectServer&&(await new Promise(t=>{this.httpRedirectServer.close(()=>t());}),this.httpRedirectServer=null),this.server&&(await this.server.stop(),this.server=null),this.running=false,d.info("WebSocket server stopped");}broadcastToSession(t,e){this.touchSession(t);let n=this.sessionSubscriptions.get(t);if(!n||n.size===0){d.debug("No clients subscribed to session",{sessionId:t});return}let s=e?.properties?.sessionID;if(typeof s=="string"&&s&&s!==t)return;let i=JSON.stringify({type:"event",sessionId:t,payload:e});for(let r of n){let l=this.subscriptions.get(r);if(l&&l.ws.readyState===l.ws.OPEN&&l.subscribedSessions.has(t)){if(l.subscribedEventTypes.size>0&&!l.subscribedEventTypes.has(e.type)){d.debug("Event type not subscribed, skipping",{clientId:r,sessionId:t,eventType:e.type,subscribedTypes:Array.from(l.subscribedEventTypes)});continue}l.ws.send(i),d.debug("Event pushed to client",{clientId:r,sessionId:t,eventType:e.type});}}}getConnectionCount(){return this.connections.size}getSubscriptionCount(){return this.sessionSubscriptions.size}getConnectionInfos(){let t=[];for(let[e,n]of this.subscriptions.entries())t.push({clientId:e,state:n.ws.readyState===n.ws.OPEN?"connected":"disconnected",connectedAt:n.connectedAt,lastActivityAt:n.lastActivityAt,authInfo:n.authInfo});return t}isRunning(){return this.running}handleConnection(t){if(this.connections.size>=(this.config.maxConnections??B.maxConnections)){d.warn("Maximum connections reached, rejecting new connection"),t.close(1013,"Maximum connections reached");return}let e=on();this.connections.set(e,t),this.subscriptions.set(e,{clientId:e,ws:t,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()}),d.info("WebSocket client connected",{clientId:e,totalConnections:this.connections.size}),this.sendMessage(t,{type:"connected",clientId:e,payload:{version:"1.0.0",capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}handleDisconnection(t){let e=Ie(t,this.connections);if(!e)return;this.connections.delete(e);let n=this.subscriptions.get(e);if(n){for(let s of n.subscribedSessions){let i=this.sessionSubscriptions.get(s);i&&(i.delete(e),i.size===0&&this.sessionSubscriptions.delete(s));}this.subscriptions.delete(e);}d.info("WebSocket client disconnected",{clientId:e,totalConnections:this.connections.size});}async handleMessage(t,e){let n=Ie(t,this.connections);if(!n){this.sendError(t,"Client not found");return}let s=this.subscriptions.get(n);switch(s&&(s.lastActivityAt=Date.now()),e.type){case "ping":this.sendMessage(t,{type:"pong"});break;case "initialize":await this.handleInitialize(t,e);break;case "subscribe":await this.handleSubscribe(t,e);break;case "unsubscribe":await this.handleUnsubscribe(t,e);break;case "message":await this.handleMessageRequest(t,e);break;case "interrupt":await this.handleInterrupt(t,e);break;case "releaseSubscription":await this.handleReleaseSubscription(t,e);break;default:this.sendError(t,`Unknown message type: ${e.type}`);}}async handleInitialize(t,e){this.sendMessage(t,{type:"initialize_response",success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}async handleSubscribe(t,e){if(e.type!=="subscribe"||!e.sessionId){this.sendError(t,"Invalid subscribe request");return}let n=Ie(t,this.connections);if(!n){this.sendError(t,"Client not found");return}let s=this.subscriptions.get(n);if(!s){this.sendError(t,"Subscription not found");return}s.subscribedSessions.add(e.sessionId),this.sessionSubscriptions.has(e.sessionId)||this.sessionSubscriptions.set(e.sessionId,new Set),this.sessionSubscriptions.get(e.sessionId).add(n);let i=e;if(i.backendSessionId){let r=this.getChannelResolveParams();if(r.sessionManager)try{await r.sessionManager.bindBackendSession(i.sessionId,i.backendSessionId),d.info("backend session bound on subscribe",{gatewaySessionId:i.sessionId,backendSessionId:i.backendSessionId});}catch(l){d.warn("failed to bind backend session on subscribe",{sessionId:i.sessionId,backendSessionId:i.backendSessionId,error:String(l)});}}if(this.touchSession(e.sessionId),e.payload?.eventTypes)for(let r of e.payload.eventTypes)s.subscribedEventTypes.add(r);d.info("Client subscribed to session",{clientId:n,sessionId:e.sessionId,backendSessionId:i.backendSessionId}),this.sendMessage(t,{type:"subscribed",sessionId:e.sessionId});}async handleUnsubscribe(t,e){if(e.type!=="unsubscribe"||!e.sessionId){this.sendError(t,"Invalid unsubscribe request");return}let n=Ie(t,this.connections);if(!n)return;let s=this.subscriptions.get(n);if(!s)return;s.subscribedSessions.delete(e.sessionId);let i=this.sessionSubscriptions.get(e.sessionId);i&&(i.delete(n),i.size===0&&this.sessionSubscriptions.delete(e.sessionId)),d.info("Client unsubscribed from session",{clientId:n,sessionId:e.sessionId}),this.sendMessage(t,{type:"unsubscribed",sessionId:e.sessionId});}async handleMessageRequest(t,e){if(e.type!=="message"||!e.sessionId||!e.payload){this.sendError(t,"Invalid message request");return}d.debug("Message received",{sessionId:e.sessionId}),this.sendMessage(t,{type:"response",sessionId:e.sessionId,success:true,result:{received:true}});}async handleInterrupt(t,e){if(e.type!=="interrupt"||!e.sessionId){this.sendError(t,"Invalid interrupt request");return}d.info("Interrupt requested via WebSocket",{sessionId:e.sessionId}),this.sendMessage(t,{type:"interrupted",sessionId:e.sessionId,success:true});}async handleReleaseSubscription(t,e){if(e.type!=="releaseSubscription"||!e.sessionId){this.sendError(t,"Invalid releaseSubscription request");return}d.info("Release subscription requested via WebSocket",{sessionId:e.sessionId}),this.releaseSessionResources(e.sessionId),this.sendMessage(t,{type:"subscriptionReleased",sessionId:e.sessionId});}touchSession(t){this.sessionLastActivity.set(t,Date.now());}checkConnectionTimeout(){let t=Date.now(),e=this.config.connectionTimeout??B.connectionTimeout,n=[];for(let[s,i]of this.subscriptions.entries())t-i.lastActivityAt>e&&n.push(s);for(let s of n){let i=this.subscriptions.get(s);if(i){d.info("Closing inactive connection",{clientId:s,lastActivityAt:i.lastActivityAt,timeoutMs:e});try{i.ws.close(1001,"Connection timeout");}catch(r){d.debug("Error closing timed out connection",{clientId:s,error:String(r)});}}}n.length>0&&d.debug("Closed timed out connections",{count:n.length,remainingConnections:this.connections.size-n.length});}cleanupExpiredSessions(){let t=Date.now(),e=[],n=this.config.sessionExpireMs??B.sessionExpireMs;for(let[s,i]of this.sessionLastActivity.entries())t-i>n&&e.push(s);for(let s of e)d.info("Session expired due to inactivity, releasing resources",{sessionId:s,lastActivity:this.sessionLastActivity.get(s),expireMs:n}),this.releaseSessionResources(s),this.sessionLastActivity.delete(s);e.length>0&&d.debug("Cleaned up expired sessions",{count:e.length,remainingActive:this.sessionLastActivity.size});}releaseSessionResources(t){let e=this.sessionSubscriptions.get(t);if(e){for(let n of e){let s=this.subscriptions.get(n);s&&s.ws.readyState===s.ws.OPEN&&this.sendMessage(s.ws,{type:"session_closed",sessionId:t,payload:{reason:"Session resources released due to expiration or explicit release"}});}for(let n of e){let s=this.subscriptions.get(n);s&&s.subscribedSessions.delete(t);}this.sessionSubscriptions.delete(t),d.info("Session resources released",{sessionId:t,clientCount:e.size});}}sendMessage(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e));}sendError(t,e,n){this.sendMessage(t,{type:"error",message:e,code:n});}createRoutes(){return [{method:"get",path:"/health",handler:t=>{let e={status:"healthy",timestamp:Date.now(),version:"1.0.0"};return t.json(e)}},{method:"get",path:"/status",handler:t=>{let e={status:this.running?"running":"stopped",connections:this.connections.size,sessions:this.sessionSubscriptions.size,subscriptions:this.subscriptions.size,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0"};return t.json(e)}},{method:"get",path:"/channels",handler:async t=>{let e=this.channelResolveParams?.pluginLoader;if(!e)return t.json({error:"Plugin loader not available"},503);let s=e.getAllPlugins().map(i=>({id:i.id,platform:i.platform,name:i.name,version:i.version}));return t.json({channels:s,total:s.length})}},{method:"get",path:"/contacts",handler:async t=>{let e=t.req.query("platform"),n=parseInt(t.req.query("limit")||"100",10),s=parseInt(t.req.query("offset")||"0",10),i=this.channelResolveParams?.contactStore;if(!i)return t.json({error:"Contact store not available"},503);try{if(e){let r=await i.listByPlatform(e,n,s);return t.json({contacts:r.contacts.map(l=>({uid:l.uid,platform:l.platform,stableId:l.stableId,profile:l.profile,lastSeenAt:l.lastSeenAt,createdAt:l.createdAt})),total:r.total,hasMore:r.hasMore})}else {let r=await i.count();return t.json({total:r,message:"Specify platform query parameter to list contacts"})}}catch(r){return d.error("failed to list contacts",{error:String(r)}),t.json({error:String(r)},500)}}},{method:"get",path:"/contacts/:uid",handler:async t=>{let e=t.req.param("uid"),n=this.channelResolveParams?.contactStore;if(!n)return t.json({error:"Contact store not available"},503);try{let s=await n.findByUid(e);return s?t.json({uid:s.uid,platform:s.platform,stableId:s.stableId,profile:s.profile,aliases:s.aliases,lastSeenAt:s.lastSeenAt,createdAt:s.createdAt}):t.json({error:"Contact not found"},404)}catch(s){return d.error("failed to get contact",{uid:e,error:String(s)}),t.json({error:String(s)},500)}}},{method:"get",path:"/sessions",handler:async t=>{let e=parseInt(t.req.query("limit")||"100",10),n=parseInt(t.req.query("offset")||"0",10);t.req.query("platform");let i=[];for(let[r,l]of this.sessionSubscriptions)i.length>=n&&i.length<n+e&&i.push({id:r,state:"active",createdAt:this.sessionLastActivity.get(r)||Date.now(),lastActiveAt:this.sessionLastActivity.get(r)||Date.now()});return t.json({sessions:i,total:this.sessionSubscriptions.size,hasMore:n+e<this.sessionSubscriptions.size})}},{method:"get",path:"/sessions/:sessionId",handler:async t=>{let e=t.req.param("sessionId"),n=this.sessionSubscriptions.get(e);return n?t.json({id:e,state:"active",subscriberCount:n.size,lastActiveAt:this.sessionLastActivity.get(e)||Date.now()}):t.json({error:"Session not found"},404)}},{method:"post",path:"/initialize",handler:async t=>{let e=await t.req.json().catch(()=>({}));return d.debug("ACP initialize request received",{body:e}),t.json({success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"],version:"1.0.0"}})}},{method:"post",path:"/session",handler:async t=>{await t.req.json().catch(()=>({}));let s={id:`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,createdAt:Date.now()};return t.json(s)}},{method:"post",path:"/session/:sessionId/prompt",handler:async t=>{let e=t.req.param("sessionId"),n=await t.req.json().catch(()=>({}));if(!e)return t.json({error:"No sessionId provided"},400);try{let s=this.getChannelResolveParams(),i=await Le({...s,sessionId:e,channel:n.channel,userId:n.userId});d.debug("channel resolved for message",{sessionId:e,channel:i.channel,source:i.source});let r=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,l={id:r,sessionId:e,type:"output",content:typeof n.content=="string"?[{type:"text",text:n.content}]:n.content||[],metadata:{channel:i.channelInfo},timestamp:Date.now()};if(this.pluginLoaderRef)try{await this.pluginLoaderRef.send(i.channel,l),d.debug("message sent via pluginLoader",{messageId:r,channel:i.channel});}catch(u){return d.error("failed to send message",{sessionId:e,error:String(u)}),t.json({error:String(u)},500)}let g={messageId:r,sessionId:e,createdAt:Date.now(),metadata:{channel:i.channel,channelSource:i.source,channelInfo:i.channelInfo}};return t.status(202),t.json(g)}catch(s){return s instanceof A?(d.warn("channel selection failed",{sessionId:e,error:s.message}),t.json({error:Ue(s),code:s.code},400)):(d.error("send message error",{sessionId:e,error:String(s)}),t.json({error:String(s)},500))}}},{method:"get",path:"/subscriptions",handler:t=>{let e=Array.from(this.sessionSubscriptions.entries()).map(([s,i])=>({sessionId:s,subscriberCount:i.size,subscribers:Array.from(i)})),n={subscriptions:e,total:e.length};return t.json(n)}}]}};var y=class{constructor(){a$2(this,"version","1.0.0");a$2(this,"log");a$2(this,"config",null);a$2(this,"messageHandler",null);a$2(this,"_status","stopped");a$2(this,"lastActivity",0);a$2(this,"startPromise",null);a$2(this,"stopPromise",null);}initLog(){this.log=a.create({service:`channel:${this.platform}`});}async start(t,e){if(this.startPromise)return this.log.warn("plugin start already in progress"),this.startPromise;if(this._status==="running"){this.log.warn("plugin is already running");return}this.startPromise=this.doStartInternal(t,e);try{await this.startPromise;}finally{this.startPromise=null;}}async doStartInternal(t,e){this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=t,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(n){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(n)}),n}}async stop(){if(this.stopPromise)return this.log.warn("plugin stop already in progress"),this.stopPromise;if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}this.stopPromise=this.doStopInternal();try{await this.stopPromise;}finally{this.stopPromise=null;}}async doStopInternal(){this.log.info("stopping channel plugin",{id:this.id}),this._status="stopping";try{await this.doStop(),this._status="stopped",this.log.info("channel plugin stopped",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(t)}),t}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(t){return {healthy:false,lastCheck:Date.now(),error:t instanceof Error?t.message:String(t)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}extractText(t){return t.content.filter(e=>e.type==="text").map(e=>e.text??"").join(`
|
|
3
|
+
`)}buildSessionId(t,e,n){let s=[this.platform,t,e];return n&&s.push(n),s.join("_")}async handleMessage(t){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:t.id});return}this.updateActivity(),await this.messageHandler.onMessage(t);}async handleEvent(t,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:t});return}await this.messageHandler.onEvent({type:t,channelId:this.id,data:e,timestamp:Date.now()});}};var J=class extends y{constructor(e="telegram-main"){super();a$2(this,"id");a$2(this,"platform","telegram");a$2(this,"name","Telegram Bot");a$2(this,"botConfig",null);a$2(this,"baseUrl","");a$2(this,"abortController",null);a$2(this,"lastUpdateId",0);a$2(this,"typingTimers",new Map);a$2(this,"commandRouter",new Map);a$2(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});this.id=e,this.initLog();}async doStart(){if(!this.config)throw E(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw E(this.id,"CONFIG_MISSING_REQUIRED","Bot token is required");if(this.baseUrl=`https://api.telegram.org/bot${this.botConfig.botToken}`,this.botConfig.retry&&(this.retryState={attempts:0,maxAttempts:this.botConfig.retry.maxAttempts??3,initialDelay:this.botConfig.retry.initialDelay??1e3,maxDelay:this.botConfig.retry.maxDelay??3e4}),this.botConfig.commands)for(let n of this.botConfig.commands)this.commandRouter.set(`/${n.command}`,n);let e=await this.getMe();this.log.info("Telegram bot connected",{id:e.id,username:e.username,first_name:e.first_name}),this.botConfig.polling?.enabled!==false&&this.startPolling();}async doStop(){this.abortController?.abort(),this.abortController=null,this.clearAllTyping(),this.commandRouter.clear(),this.botConfig=null,this.log.info("Telegram plugin stopped");}async send(e){let n=e.metadata.channel.chatId;if(!n)throw E(this.id,"MESSAGE_SEND_FAILED","Chat ID is required");let s=this.detectParseMode(e),i=e.metadata.context?.replyTo;return this.sendApiMessage(n,this.extractText(e),{parseMode:s,replyTo:i?parseInt(i,10):void 0})}async sendTyping(e){await this.sendChatAction(e,"typing");}async sendChatAction(e,n){await this.request("sendChatAction",{chat_id:e,action:n}),this.scheduleTypingStop(e,5e3);}scheduleTypingStop(e,n){let s=this.typingTimers.get(e);s&&clearTimeout(s);let i=setTimeout(()=>{this.typingTimers.delete(e);},n);this.typingTimers.set(e,i);}clearAllTyping(){for(let e of this.typingTimers.values())clearTimeout(e);this.typingTimers.clear();}detectParseMode(e){let n=this.extractText(e);return n.includes("<")&&n.includes("</")?"HTML":n.includes("*")||n.includes("_")||n.includes("`")?"Markdown":"None"}startPolling(){this.abortController=new AbortController,this.pollLoop(),this.log.info("Polling started");}pollLoop(){(async()=>{try{await this.poll(),this.abortController?.signal.aborted||this.pollLoop();}catch(n){this.handlePollingError(n);}})();}async poll(){let e=this.botConfig?.polling?.timeout??0,n=await this.getUpdates(this.lastUpdateId+1,100,e);for(let s of n)this.lastUpdateId=Math.max(this.lastUpdateId,s.update_id),s.message&&await this.handleTelegramMessage(s.message),s.edited_message&&await this.handleTelegramMessage(s.edited_message);this.retryState.attempts=0;}handlePollingError(e){if(!this.abortController?.signal.aborted)if(this.log.error("Polling error",{error:String(e)}),this.retryState.attempts<this.retryState.maxAttempts){let n=Math.min(this.retryState.initialDelay*2**this.retryState.attempts,this.retryState.maxDelay);this.retryState.attempts++,this.log.info("Retrying polling",{attempt:this.retryState.attempts,delay:n}),this.sleep(n).then(()=>this.pollLoop());}else this.log.error("Polling failed after max attempts",{attempts:this.retryState.maxAttempts});}sleep(e){return new Promise(n=>setTimeout(n,e))}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot||e.text?.startsWith("/")&&await this.handleCommand(e))return;await this.sendTyping(e.chat.id.toString());let n=this.toGatewayMessage(e);await this.handleMessage(n);}async handleCommand(e){let n=(e.text??"").split(" "),s=n[0]?.toLowerCase()??"",i=n.slice(1),r=this.commandRouter.get(s);if(!r)return false;let l={chatId:e.chat.id.toString(),userId:e.from?.id.toString(),args:i,messageId:e.message_id,reply:async(g,u)=>this.sendApiMessage(e.chat.id.toString(),g,u)};try{return await r.handler(l),!0}catch(g){return this.log.error("Command handler error",{command:s,error:String(g)}),true}}toGatewayMessage(e){let n=this.processMessageAndGetSessionId(e);return b(n,"input",this.parseContent(e),{channel:{platform:"telegram",channelId:this.id,userId:e.from?.id.toString(),chatId:e.chat.id.toString(),username:e.from?.username,firstName:e.from?.first_name,lastName:e.from?.last_name,chatType:e.chat.type,chatTitle:e.chat.title},context:{replyTo:e.reply_to_message?.message_id.toString(),messageId:e.message_id.toString()}})}parseContent(e){let n=[],s=e.text??e.caption??"";if(e.photo&&e.photo.length>0){let i=e.photo[e.photo.length-1];i&&n.push({type:"image",image:i.file_id,mime:"image/jpeg"});}return e.document&&n.push({type:"file",data:e.document.file_id,mime:e.document.mime_type}),s&&n.push({type:"text",text:s}),n}buildSessionId(e,n,s){return s?`telegram_${e}_${n}_${s}`:`telegram_${e}_${n}`}processMessageAndGetSessionId(e){let n=e.chat.id.toString(),s=e.from?.id.toString();return e.chat.type==="private"?this.buildSessionId(this.id,n):this.buildSessionId(this.id,n,s)}async getMe(){return (await this.request("getMe")).result}async getUpdates(e,n,s){let i={offset:e,limit:n};return s>0&&(i.timeout=s),(await this.request("getUpdates",i)).result||[]}async sendApiMessage(e,n,s){let i={chat_id:e,text:n};return s?.parseMode&&s.parseMode!=="None"&&(i.parse_mode=s.parseMode),s?.replyTo&&(i.reply_to_message_id=s.replyTo),s?.replyMarkup&&(i.reply_markup=s.replyMarkup),(await this.request("sendMessage",i)).result.message_id.toString()}async request(e,n={}){let s=`${this.baseUrl}/${e}`,i;for(let r=0;r<=this.retryState.maxAttempts;r++)try{let l=await Fetch.post(s,n,{timeout:this.retryState.maxDelay,retries:0,headers:{"Content-Type":"application/json"},signal:this.abortController?.signal}),g=l.data;if(!g.ok){if(g.error_code===429){this.log.warn("Rate limited, retrying after",{retryAfter:l.headers.get("Retry-After")});let u=parseInt(l.headers.get("Retry-After")??"1",10)*1e3;await this.sleep(u);continue}throw E(this.id,"CHANNEL_CONNECTION_FAILED",`Telegram API error: ${g.description}`,g.error_code!==400&&g.error_code!==401)}return g}catch(l){if(l instanceof M||this.abortController?.signal.aborted)throw l;if(i=l instanceof Error?l:new Error(String(l)),this.log.warn("Request failed, retrying",{method:e,attempt:r+1,error:i.message}),r<this.retryState.maxAttempts){let g=Math.min(this.retryState.initialDelay*2**r,this.retryState.maxDelay);await this.sleep(g);}}throw E(this.id,"CHANNEL_CONNECTION_FAILED",`Failed after ${this.retryState.maxAttempts+1} attempts: ${i?.message}`,true)}};var Q=class extends y{constructor(e="discord-main"){super();a$2(this,"id");a$2(this,"platform","discord");a$2(this,"name","Discord Bot");a$2(this,"botConfig",null);a$2(this,"baseUrl","https://discord.com/api/v10");a$2(this,"gatewayWs",null);a$2(this,"heartbeatInterval",null);a$2(this,"sessionId",null);a$2(this,"sequenceNumber",null);a$2(this,"abortController",null);a$2(this,"reconnectAttempts",0);a$2(this,"maxReconnectAttempts",5);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");let e=await this.getCurrentUser();this.log.info("Discord bot connected",{id:e.id,username:e.username}),this.botConfig.gateway?.enabled!==false&&await this.startGateway();}async doStop(){this.abortController?.abort(),this.abortController=null,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.gatewayWs&&(this.gatewayWs.close(),this.gatewayWs=null),this.botConfig=null,this.reconnectAttempts=0,this.log.info("Discord plugin stopped");}async send(e){let n=e.metadata.channel.chatId;if(!n)throw new Error("Channel ID is required");let s=this.extractText(e);return (await this.createMessage(n,s,e.metadata.context?.replyTo)).id}async startGateway(){if(this.abortController?.signal.aborted)return;let n=`${(await this.getGatewayBot()).url}/?v=10&encoding=json`;this.gatewayWs=new WebSocket(n),this.gatewayWs.onmessage=s=>{this.handleGatewayMessage(JSON.parse(s.data.toString()));},this.gatewayWs.onclose=()=>{if(!this.abortController?.signal.aborted)if(this.log.info("Gateway disconnected"),this.reconnectAttempts<this.maxReconnectAttempts){let s=Math.min(1e3*2**this.reconnectAttempts,3e4);this.reconnectAttempts++,this.log.info("Attempting to reconnect",{attempt:this.reconnectAttempts,delay:s}),setTimeout(()=>this.startGateway(),s);}else this.log.error("Max reconnect attempts reached");},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,n){e==="MESSAGE_CREATE"&&this.handleDiscordMessage(n);}async handleDiscordMessage(e){if(e.author.bot)return;let n=this.toGatewayMessage(e);await this.handleMessage(n);}toGatewayMessage(e){let n=this.processMessageAndGetSessionId(e);return b(n,"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 n=[];e.content&&n.push({type:"text",text:e.content});for(let s of e.attachments)s.content_type?.startsWith("image/")?n.push({type:"image",image:s.url,mime:s.content_type}):n.push({type:"file",data:s.url,mime:s.content_type});return n}buildSessionId(e,n,s){return s?`discord_${e}_${n}_${s}`:`discord_${e}_${n}`}processMessageAndGetSessionId(e){let n=e.channel_id,s=e.author.id;return this.buildSessionId(this.id,n,s)}async getCurrentUser(){return this.request("GET","/users/@me")}async getGatewayBot(){return this.request("GET","/gateway/bot")}async createMessage(e,n,s){let i={content:n};return s&&(i.message_reference={message_id:s}),this.request("POST",`/channels/${e}/messages`,i)}async request(e,n,s){let i=`${this.baseUrl}${n}`,r;if(e==="GET"?r=await Fetch.get(i,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}):e==="POST"?r=await Fetch.post(i,s,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}):e==="DELETE"?r=await Fetch.del(i,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}):r=await Fetch.request(i,{method:e,body:s,headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}),!r.ok)throw new Error(`Discord API error: ${r.data}`);return r.data}};var Y=class extends y{constructor(e="slack-main"){super();a$2(this,"id");a$2(this,"platform","slack");a$2(this,"name","Slack Bot");a$2(this,"botConfig",null);a$2(this,"baseUrl","");a$2(this,"socketModeClient",null);a$2(this,"abortController",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");this.abortController=new AbortController,this.baseUrl="https://slack.com/api";let e=await this.authTest();this.log.info("Slack bot connected",{user:e.user,team:e.team,bot_id:e.bot_id}),this.botConfig.socketMode&&this.botConfig.appToken&&await this.startSocketMode();}async doStop(){this.abortController?.abort(),this.abortController=null,this.socketModeClient&&(this.socketModeClient.close(),this.socketModeClient=null),this.botConfig=null,this.log.info("Slack plugin stopped");}async send(e){let n=e.metadata.channel.chatId;if(!n)throw new Error("Channel ID is required");let s=this.extractText(e);return (await this.postMessage(n,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 n=>{try{let s=JSON.parse(n.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 n=e.payload.event;n.type==="message"&&!n.subtype&&await this.handleSlackMessage(n);}}async handleSlackMessage(e){this.updateActivity();let n=this.toGatewayMessage(e);await this.handleMessage(n);}toGatewayMessage(e){let n=this.processMessageAndGetSessionId(e);return b(n,"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 n=[];if(e.text&&n.push({type:"text",text:e.text}),e.files)for(let s of e.files)n.push({type:"file",data:s.url_private,mime:s.mimetype});return n}buildSessionId(e,n,s){return s?`slack_${e}_${n}_${s}`:`slack_${e}_${n}`}processMessageAndGetSessionId(e){let n=e.channel,s=e.user;return this.buildSessionId(this.id,n,s)}async authTest(){return await this.request("auth.test")}async postMessage(e,n,s){let i={channel:e,text:n};return s&&(i.thread_ts=s),await this.request("chat.postMessage",i)}async request(e,n={}){let s=`${this.baseUrl}/${e}`,i=await Fetch.post(s,n,{headers:{Authorization:`Bearer ${this.botConfig?.botToken}`,"Content-Type":"application/json; charset=utf-8"}});if(!i.data.ok)throw new Error(`Slack API error: ${i.data.error}`);return i.data}};var X=class extends y{constructor(e="feishu-main"){super();a$2(this,"id");a$2(this,"platform","feishu");a$2(this,"name","Feishu Bot");a$2(this,"botConfig",null);a$2(this,"baseUrl","https://open.feishu.cn/open-apis");a$2(this,"tenantAccessToken",null);a$2(this,"tokenExpireTime",0);a$2(this,"abortController",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw new Error("App ID and App Secret are required");this.abortController=new AbortController,await this.refreshTenantAccessToken(),this.log.info("Feishu bot connected",{app_id:this.botConfig.appId});}async doStop(){this.abortController?.abort(),this.abortController=null,this.botConfig=null,this.tenantAccessToken=null,this.log.info("Feishu plugin stopped");}async send(e){let n=e.metadata.channel.chatId;if(!n)throw new Error("Chat ID is required");await this.ensureTokenValid();let s=this.extractText(e);return (await this.sendMessage(n,s)).message_id}async handleWebhookEvent(e){if(this.updateActivity(),this.botConfig?.verificationToken,e.event?.message){let n=this.toGatewayMessage(e);await this.handleMessage(n);}}toGatewayMessage(e){let n=e.event.message,s=this.processMessageAndGetSessionId(e);return b(s,"input",this.parseContent(n),{channel:{platform:"feishu",channelId:this.id,userId:n.sender.sender_id.open_id,chatId:n.chat_id,messageId:n.message_id,rootId:n.root_id,parentId:n.parent_id,tenantKey:e.tenant_key},context:{threadId:n.root_id,conversationId:n.chat_id}})}parseContent(e){let n=[];try{let s=JSON.parse(e.content);switch(e.message_type){case "text":s.text&&n.push({type:"text",text:s.text});break;case "post":if(s.content){let i=this.extractPostContent(s.content);n.push({type:"text",text:i});}break;case "image":s.image_key&&n.push({type:"image",image:s.image_key,mime:"image/jpeg"});break;case "file":s.file_key&&n.push({type:"file",data:s.file_key,mime:s.file_type});break;default:n.push({type:"text",text:JSON.stringify(s)});}}catch{n.push({type:"text",text:e.content});}return n}extractPostContent(e){let n=[];for(let s of e)if(typeof s=="object"&&s!==null){let i=s;i.text&&n.push(String(i.text)),Array.isArray(i.children)&&n.push(this.extractPostContent(i.children));}return n.join(`
|
|
4
|
+
`)}buildSessionId(e,n,s){return s?`feishu_${e}_${n}_${s}`:`feishu_${e}_${n}`}processMessageAndGetSessionId(e){let n=e.event.message,s=n.chat_id,i=n.sender.sender_id.open_id;return this.buildSessionId(this.id,s,i)}async refreshTenantAccessToken(){let n=(await Fetch.post(`${this.baseUrl}/auth/v3/tenant_access_token/internal`,{app_id:this.botConfig?.appId,app_secret:this.botConfig?.appSecret},{headers:{"Content-Type":"application/json"}})).data;if(n.code!==0)throw new Error(`Feishu API error: ${n.msg}`);this.tenantAccessToken=n.tenant_access_token,this.tokenExpireTime=Date.now()+n.expire*1e3-6e4;}async ensureTokenValid(){(!this.tenantAccessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshTenantAccessToken();}async sendMessage(e,n){let i=(await Fetch.post(`${this.baseUrl}/im/v1/messages?receive_id_type=chat_id`,{receive_id:e,msg_type:"text",content:JSON.stringify({text:n})},{headers:{Authorization:`Bearer ${this.tenantAccessToken}`,"Content-Type":"application/json"}})).data;if(i.code!==0)throw new Error(`Feishu API error: ${i.msg}`);return i.data}};var Z=class extends y{constructor(e="wechat-main"){super();a$2(this,"id");a$2(this,"platform","wechat");a$2(this,"name","WeChat Bot");a$2(this,"botConfig",null);a$2(this,"accessToken",null);a$2(this,"tokenExpireTime",0);a$2(this,"abortController",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw new Error("App ID and App Secret are required");this.abortController=new AbortController,await this.refreshAccessToken(),this.log.info("WeChat bot connected",{app_id:this.botConfig.appId,mode:this.botConfig.mode});}async doStop(){this.abortController?.abort(),this.abortController=null,this.botConfig=null,this.accessToken=null,this.log.info("WeChat plugin stopped");}async send(e){let n=e.metadata.channel.userId;if(!n)throw new Error("User ID is required");await this.ensureTokenValid();let s=this.extractText(e);return this.botConfig?.mode==="wecom"?await this.sendWeComMessage(n,s):await this.sendOfficialMessage(n,s)}async handleWebhookMessage(e){this.updateActivity();let n=this.parseXmlMessage(e);if(n){let s=this.toGatewayMessage(n);await this.handleMessage(s);}}parseXmlMessage(e){let n=r=>e.match(new RegExp(`<${r}><!\\[CDATA\\[(.*?)\\]\\]></${r}>`))?.[1],s=r=>{let l=e.match(new RegExp(`<${r}>(\\d+)</${r}>`));return l?.[1]?parseInt(l[1],10):void 0},i=n("MsgType");return i?{ToUserName:n("ToUserName")??"",FromUserName:n("FromUserName")??"",CreateTime:s("CreateTime")??0,MsgType:i,Content:n("Content"),MsgId:s("MsgId"),PicUrl:n("PicUrl"),MediaId:n("MediaId")}:null}toGatewayMessage(e){let n=this.processMessageAndGetSessionId(e);return b(n,"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 n=[];switch(e.MsgType){case "text":e.Content&&n.push({type:"text",text:e.Content});break;case "image":(e.PicUrl||e.MediaId)&&n.push({type:"image",image:e.PicUrl??e.MediaId??"",mime:"image/jpeg"});break;case "voice":e.MediaId&&n.push({type:"file",data:e.MediaId,mime:"audio/amr"}),"Recognition"in e&&e.Recognition&&n.push({type:"text",text:e.Recognition});break;case "video":case "shortvideo":e.MediaId&&n.push({type:"file",data:e.MediaId,mime:"video/mp4"});break;default:e.Content&&n.push({type:"text",text:e.Content});}return n}buildSessionId(e,n,s){return s?`wechat_${e}_${n}_${s}`:`wechat_${e}_${n}`}processMessageAndGetSessionId(e){let n=e.FromUserName;return this.buildSessionId(this.id,n)}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 Fetch.get(e)).data;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,n){let i=(await Fetch.post(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{touser:e,msgtype:"text",text:{content:n}},{headers:{"Content-Type":"application/json"}})).data;if(i.errcode!==0)throw new Error(`WeChat API error: ${i.errmsg}`);return i.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,n){let i=(await Fetch.post(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${this.accessToken}`,{touser:e,msgtype:"text",agentid:this.botConfig?.agentId,text:{content:n}},{headers:{"Content-Type":"application/json"}})).data;if(i.errcode!==0)throw new Error(`WeCom API error: ${i.errmsg}`);return i.msgid??Date.now().toString()}};var ee=class extends y{constructor(e="webchat-main"){super();a$2(this,"id");a$2(this,"platform","webchat");a$2(this,"name","WebChat");a$2(this,"webChatConfig",null);a$2(this,"connections",new Map);a$2(this,"heartbeatInterval",null);a$2(this,"abortController",null);a$2(this,"wsServer",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");this.webChatConfig=this.config.platform,this.abortController=new AbortController,await this.startWebSocketServer(),this.startHeartbeat(),this.log.info("WebChat plugin started",{port:this.webChatConfig.port,hostname:this.webChatConfig.hostname,path:this.webChatConfig.path,maxConnections:this.webChatConfig.maxConnections});}async startWebSocketServer(){if(!this.webChatConfig)return;let e={port:this.webChatConfig.port,hostname:this.webChatConfig.hostname,path:this.webChatConfig.path,maxConnections:this.webChatConfig.maxConnections,connectionTimeout:this.webChatConfig.connectionTimeout,heartbeatInterval:this.webChatConfig.heartbeatInterval,sessionExpireMs:this.webChatConfig.sessionExpireMs,https:this.webChatConfig.https};this.wsServer=new N(e),await this.wsServer.start(),this.log.info("WebSocket server started",{url:`${this.webChatConfig.https?.enabled?"wss":"ws"}://${this.webChatConfig.hostname}:${this.webChatConfig.port}${this.webChatConfig.path}`});}async doStop(){this.abortController?.abort(),this.abortController=null,this.wsServer&&(await this.wsServer.stop(),this.wsServer=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let e of this.connections.values())e.ws.close();this.connections.clear(),this.webChatConfig=null,this.log.info("WebChat plugin stopped");}async send(e){let n=e.sessionId,s=e.metadata.channel.userId;if(this.wsServer&&n){let l={type:"message",sessionId:n,properties:{sessionID:n,content:e.content,timestamp:e.timestamp||Date.now()}};return this.wsServer.broadcastToSession(n,l),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 r={type:"message",sessionId:n,content:e.content,metadata:e.metadata};return i.ws.send(JSON.stringify(r)),i.lastActivity=Date.now(),e.id}pushEvent(e,n){this.wsServer&&this.wsServer.broadcastToSession(e,n);}getWebSocketServer(){return this.wsServer}async handleConnection(e,n){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:n,lastActivity:Date.now()};this.connections.set(s,i),e.onmessage=r=>{this.handleWebSocketMessage(i,r.data.toString());},e.onclose=()=>{this.connections.delete(s),this.log.debug("WebSocket closed",{connId:s,userId:n});},e.onerror=r=>{this.log.error("WebSocket error",{connId:s,userId:n,error:String(r)});},this.log.info("WebSocket connected",{connId:s,userId:n});}async handleWebSocketMessage(e,n){this.updateActivity(),e.lastActivity=Date.now();try{let s=JSON.parse(n);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,n){if(!n.content||!n.sessionId)return;let s=b(n.sessionId,"input",n.content,{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:n.sessionId,connectionId:e.id},context:{conversationId:n.sessionId},...n.metadata});await this.handleMessage(s);}startHeartbeat(){let e=this.webChatConfig?.heartbeatInterval??3e4;this.heartbeatInterval=setInterval(()=>{let n=Date.now(),s=this.webChatConfig?.connectionTimeout??6e4;for(let[i,r]of this.connections)n-r.lastActivity>s&&(this.log.info("Closing inactive connection",{connId:i}),r.ws.close(1001,"Connection timeout"),this.connections.delete(i));},e);}findConnectionByUser(e){for(let n of this.connections.values())if(n.userId===e)return n}generateConnectionId(){return `conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}getConnectionCount(){return this.connections.size}getWsServerConnectionCount(){return this.wsServer?.getConnectionCount()??0}};var te=class extends y{constructor(e="signal-main"){super();a$2(this,"id");a$2(this,"platform","signal");a$2(this,"name","Signal Bot");a$2(this,"botConfig",null);a$2(this,"abortController",null);a$2(this,"lastTimestamp",0);a$2(this,"pollingIntervalMs",5e3);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.phoneNumber)throw new Error("Phone number is required");this.abortController=new AbortController;let e=await this.getAccountInfo();this.log.info("Signal bot connected",{number:this.botConfig.phoneNumber,address:e.address}),this.startPolling();}async doStop(){this.abortController?.abort(),this.abortController=null,this.botConfig=null,this.lastTimestamp=0,this.log.info("Signal plugin stopped");}async send(e){let n=e.metadata.channel.userId;if(!n)throw new Error("Recipient is required");let s=this.extractText(e);return (await this.sendMessage(n,s)).timestamp.toString()}startPolling(){this.pollLoop(),this.log.info("Polling started",{interval:this.pollingIntervalMs});}pollLoop(){if(this.abortController?.signal.aborted)return;(async()=>{try{await this.poll();}catch(n){this.log.error("Polling error",{error:String(n)});}})().then(()=>{this.abortController?.signal.aborted||setTimeout(()=>this.pollLoop(),this.pollingIntervalMs);});}async poll(){let e=await this.receiveMessages(this.lastTimestamp);for(let n of e)this.lastTimestamp=n.envelope.timestamp,n.envelope.dataMessage&&await this.handleSignalMessage(n);}async handleSignalMessage(e){this.updateActivity();let n=this.toGatewayMessage(e);await this.handleMessage(n);}toGatewayMessage(e){let n=this.processMessageAndGetSessionId(e),s=e.envelope.dataMessage;return b(n,"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 n=[];if(!e)return n;if(e.message&&n.push({type:"text",text:e.message}),e.attachments)for(let s of e.attachments)s.contentType.startsWith("image/")?n.push({type:"image",image:s.id,mime:s.contentType}):n.push({type:"file",data:s.id,mime:s.contentType});return n}buildSessionId(e,n,s){return s?`signal_${e}_${n}_${s}`:`signal_${e}_${n}`}processMessageAndGetSessionId(e){let n=e.envelope.sourceNumber;return this.buildSessionId(this.id,n)}async getAccountInfo(){return await this.request("GET",`/v1/accounts/${this.botConfig?.phoneNumber}`)}async receiveMessages(e){let n=e>0?`?since=${e}`:"";return await this.request("GET",`/v1/receive/${this.botConfig?.phoneNumber}${n}`)||[]}async sendMessage(e,n){return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:n})}async request(e,n,s){let i=`${this.botConfig?.serviceUrl}${n}`,r={"Content-Type":"application/json"};this.botConfig?.password&&(r.Authorization=`Basic ${Buffer.from(`${this.botConfig.phoneNumber}:${this.botConfig.password}`).toString("base64")}`);let l;if(e==="GET"?l=await Fetch.get(i,{headers:r}):e==="POST"?l=await Fetch.post(i,s,{headers:r}):e==="DELETE"?l=await Fetch.del(i,{headers:r}):l=await Fetch.request(i,{method:e,body:s,headers:r}),!l.ok)throw new Error(`Signal API error: ${l.data}`);return l.data}};var ne=class extends y{constructor(e="nostr-main"){super();a$2(this,"id");a$2(this,"platform","nostr");a$2(this,"name","Nostr Bot");a$2(this,"botConfig",null);a$2(this,"relayConnections",new Map);a$2(this,"subscriptions",new Map);a$2(this,"eventHandlers",new Map);a$2(this,"abortController",null);a$2(this,"relayReconnectAttempts",new Map);a$2(this,"maxReconnectAttempts",5);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.relays||this.botConfig.relays.length===0)throw new Error("At least one relay is required");this.abortController=new AbortController;for(let e of this.botConfig.relays)await this.connectToRelay(e);this.log.info("Nostr bot connected",{relays:this.botConfig.relays,pubkey:this.botConfig.publicKey?.substring(0,16)+"..."});}async doStop(){this.abortController?.abort(),this.abortController=null;for(let[e,n]of this.relayConnections)n.close();this.relayConnections.clear(),this.subscriptions.clear(),this.eventHandlers.clear(),this.relayReconnectAttempts.clear(),this.botConfig=null,this.log.info("Nostr plugin stopped");}async send(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required for sending messages");let n=this.extractText(e),s=await this.createEvent(n,e.metadata.context?.replyTo);return await this.publishEvent(s),s.id}async connectToRelay(e){if(this.abortController?.signal.aborted)return;let n=new WebSocket(e);n.onopen=()=>{this.log.info("Connected to relay",{relay:e}),this.relayReconnectAttempts.set(e,0);for(let[s,i]of this.subscriptions)this.subscribeToRelay(n,s,i);},n.onmessage=s=>{this.handleRelayMessage(e,s.data.toString());},n.onclose=()=>{if(this.abortController?.signal.aborted)return;this.log.info("Disconnected from relay",{relay:e}),this.relayConnections.delete(e);let s=this.relayReconnectAttempts.get(e)??0;if(s<this.maxReconnectAttempts){let i=Math.min(1e3*2**s,3e4);this.relayReconnectAttempts.set(e,s+1),this.log.info("Attempting to reconnect to relay",{relay:e,attempt:s+1,delay:i}),setTimeout(()=>this.connectToRelay(e),i);}else this.log.error("Max reconnect attempts reached for relay",{relay:e});},n.onerror=s=>{this.log.error("Relay error",{relay:e,error:String(s)});},this.relayConnections.set(e,n);}handleRelayMessage(e,n){this.updateActivity();try{let s=JSON.parse(n);if(s[0]==="EVENT"&&s[2]){let i=s[2];this.handleNostrEvent(i);}if(s[0]==="OK"){let i=s[1],r=s[2];this.log.debug("Event published",{eventId:i,success:r});}}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 n=this.toGatewayMessage(e);await this.handleMessage(n);}toGatewayMessage(e){let n=this.processMessageAndGetSessionId(e);return b(n,"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 n=[];e.content&&n.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)&&n.push({type:"image",image:i});}return n}findReplyTo(e){for(let n of e)if(n[0]==="e"&&n[1])return n[1]}buildSessionId(e,n,s){return s?`nostr_${e}_${n}_${s}`:`nostr_${e}_${n}`}processMessageAndGetSessionId(e){return this.buildSessionId(this.id,e.pubkey)}subscribeToRelay(e,n,s){let i=["REQ",n,s];e.send(JSON.stringify(i));}async createEvent(e,n){let s=[];n&&s.push(["e",n]);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 n=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),i=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(r)).map(g=>g.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required");return "signature_placeholder"}async publishEvent(e){let n=["EVENT",e];for(let s of this.relayConnections.values())s.readyState===WebSocket.OPEN&&s.send(JSON.stringify(n));}};var We=class extends y{constructor(e){super();a$2(this,"id");a$2(this,"platform");a$2(this,"name");a$2(this,"version");a$2(this,"options");this.id=e.id,this.platform=e.platform||"custom",this.name=e.name,this.version=e.version||"1.0.0",this.options=e,this.initLog();}async doStart(){this.options.setup?.initialize&&await this.options.setup.initialize(),this.log.info("Channel plugin started",{id:this.id,platform:this.platform});}async doStop(){this.options.setup?.destroy&&await this.options.setup.destroy(),this.log.info("Channel plugin stopped",{id:this.id});}async send(e){let n=e;this.options.actions?.beforeSend&&(n=await this.options.actions.beforeSend(e));let s=await this.options.messaging.send(n);return this.options.actions?.afterSend&&await this.options.actions.afterSend(n,s),s}async healthCheck(){return this.options.status?.healthCheck?{healthy:await this.options.status.healthCheck(),lastCheck:Date.now()}:{healthy:true,lastCheck:Date.now()}}};function ln(c){return new We(c)}var Be={telegram:J,discord:Q,slack:Y,feishu:X,wechat:Z,webchat:ee,signal:te,nostr:ne};function so(){return Object.keys(Be)}function gn(c){let t={platform:c.channel?.platform??"api",channelId:c.channel?.channelId??"unknown",chatId:c.channel?.chatId,userId:c.channel?.userId};return {id:c.messageId??`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c.sessionId,type:c.type,content:Array.isArray(c.content)?c.content:[{type:"text",text:String(c.content??"")}],metadata:{channel:t,replyToMessageId:c.replyToMessageId},timestamp:c.timestamp??Date.now()}}var it=class{constructor(t){a$2(this,"log",a.create({service:"gateway:server"}));a$2(this,"config");a$2(this,"router");a$2(this,"sessionManager");a$2(this,"pluginLoader");a$2(this,"messageStore");a$2(this,"contactStore",null);a$2(this,"wsServer",null);a$2(this,"running",false);a$2(this,"connections",0);this.log.debug("GatewayServer.constructor: starting"),this.config=t,this.log.debug("GatewayServer.constructor: creating MessageRouter"),this.router=new we,this.log.debug("GatewayServer.constructor: creating GatewaySessionManager"),this.sessionManager=new q,this.log.debug("GatewayServer.constructor: creating ChannelPluginLoader"),this.pluginLoader=new K({healthCheckInterval:6e4}),this.log.debug("GatewayServer.constructor: pluginLoader created");let e=O(),n=k();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:n}),this.messageStore=new H({storagePath:`${e.Path.data}/gateway-messages`}),n&&(this.log.debug("GatewayServer.constructor: adapter exists, setting message storage"),T().setMessageStorage({store:async i=>{let r=gn(i);await this.messageStore.store(r);},updateStatus:async(i,r,l)=>{await this.messageStore.updateStatus(i,r,l);}})),this.pluginLoader.setMessageHandler({onMessage:s=>this.onMessage(s),onEvent:s=>this.onEvent(s)}),this.log.debug("GatewayServer.constructor: completed");}async loadChannelPlugins(){try{let{config:t}=await S(),e=t.channels;if(!e){this.log.debug("no channel config found, skipping plugin loading");return}for(let[n,s]of Object.entries(e)){if(!s?.enabled){this.log.debug("channel disabled or not configured",{platform:n});continue}let i=Be[n];if(!i){this.log.warn("no plugin class found for platform",{platform:n});continue}let r=`${n}-main`,l=new i(r),g={enabled:!0,platform:s,session:{autoCreate:!0,resetPolicy:"onNewConversation"},routing:{broadcast:!0,dispatchToSubAgent:!0}};try{await this.pluginLoader.register(l,g),this.log.info("channel plugin registered",{platform:n,id:r});}catch(u){this.log.error("failed to register channel plugin",{platform:n,error:String(u)});}}}catch(t){this.log.error("failed to load channel plugins",{error:String(t)});}}async start(){if(this.log.debug("GatewayServer.start: called"),this.running){this.log.warn("gateway server is already running");return}this.log.info("starting gateway server",{port:this.config.port,hostname:this.config.hostname}),this.log.debug("GatewayServer.start: initializing sessionManager"),await this.sessionManager.initialize(),this.log.debug("GatewayServer.start: sessionManager initialized"),this.log.debug("GatewayServer.start: initializing contactStore");let e=`${O().Path.data}/gateway`,n=new $({baseDir:e});this.contactStore=new j(n,{cacheSize:1e3}),this.contactStore.initialize&&await this.contactStore.initialize(),this.log.debug("GatewayServer.start: contactStore initialized"),this.log.debug("GatewayServer.start: creating WebSocket server"),this.wsServer=new N({port:this.config.port,hostname:this.config.hostname,path:String(this.config.path??"/")}),this.log.debug("GatewayServer.start: calling wsServer.start()"),await this.wsServer.start(),this.log.debug("GatewayServer.start: wsServer started"),await this.loadChannelPlugins(),this.log.debug("GatewayServer.start: starting plugins in background"),this.pluginLoader.startAll().catch(r=>{this.log.error("plugin startup error",{error:String(r)});}),this.log.debug("GatewayServer.start: plugins startup initiated"),this.log.debug("GatewayServer.start: starting health check timer"),this.pluginLoader.startHealthCheckTimer();let{config:s}=await S(),i=s.defaults;this.wsServer.setChannelResolveDeps({sessionManager:{get:r=>this.sessionManager.get(r),bindBackendSession:(r,l)=>this.sessionManager.bindBackendSession(r,l)},pluginLoader:{getPlugin:r=>this.pluginLoader.getPlugin(r),getAllPlugins:()=>this.pluginLoader.getAllPlugins(),isRunning:r=>this.pluginLoader.isRunning(r)},defaultChannel:i?.channel,fallbackChannels:i?.fallbackChannels,contactStore:this.contactStore?{findByPlatformId:(r,l)=>this.contactStore.findByPlatformId(r,l),findByUid:r=>this.contactStore.findByUid(r),listByPlatform:(r,l,g)=>this.contactStore.listByPlatform(r,l,g),count:r=>this.contactStore.count(r)}:void 0}),this.wsServer.setPluginLoader({send:(r,l)=>this.sendToChannel(r,l)}),this.running=true,this.log.debug("GatewayServer.start: completed"),this.log.info("gateway server started");}async stop(){if(!this.running){this.log.warn("gateway server is not running");return}this.log.info("stopping gateway server"),this.wsServer&&(this.log.debug("stopping WebSocket server"),await this.wsServer.stop(),this.wsServer=null,this.log.debug("WebSocket server stopped")),this.pluginLoader.stopHealthCheckTimer(),await this.pluginLoader.stopAll(),await this.router.shutdown(),await this.sessionManager.close(),this.running=false,this.log.info("gateway server stopped");}getStatus(){return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections}}async onMessage(t){if(this.log.debug("message received",{id:t.id,sessionId:t.sessionId,type:t.type}),this.messageStore.isProcessed(t.id)){this.log.warn("message already processed, skipping",{id:t.id});return}await this.storeMessage(t),t.type==="input"&&await this.saveContactFromMessage(t),await this.sessionManager.incrementMessageCountOrCreate(t.sessionId,t.metadata.channel),(await this.router.route(t)).broadcastCount===0&&t.type==="input"&&(this.log.debug("no subscribers, dispatching to local SubAgent",{id:t.id}),await this.dispatchToSubAgent(t));}async saveContactFromMessage(t){if(!this.contactStore)return;let{platform:e,channelId:n,userId:s,chatId:i}=t.metadata.channel;if(!e||e==="api")return;let r=s||i;if(r)try{let l=await this.contactStore.getOrCreate(e,r,{username:t.metadata.channel?.username,displayName:t.metadata.channel?.firstName});this.log.debug("contact saved",{uid:l.uid});}catch(l){this.log.warn("failed to save contact",{platform:e,stableId:r,error:String(l)});}}async dispatchToSubAgent(t){if(!k()){this.log.debug("no agent adapter, message remains pending",{id:t.id});return}try{let n=T().subAgentRunner;if(!n){this.log.debug("no SubAgentRunner available, message remains pending",{id:t.id});return}this.log.info("dispatching message to local SubAgent",{id:t.id,sessionId:t.sessionId});let s=this.sessionManager.get(t.sessionId),i=s?.backendSessionId||void 0;await this.triggerHook(HookEvent.GatewayMessageProcess,{messageId:t.id,sessionId:t.sessionId,backendSessionId:i,processorId:"subagent",processType:"subagent",agent:"default",timestamp:Date.now()});let r=t.metadata.channel,l=r?.platform||"unknown",g=r?.userId||r?.chatId||"unknown user",u=`${l}:${g}`,C=`## External Channel Message
|
|
5
|
+
- Platform: ${l}
|
|
6
|
+
- From: ${g} (contactUid: ${u})
|
|
7
|
+
- Channel: ${r?.channelId||"default"}
|
|
8
|
+
- Session: ${t.sessionId}
|
|
9
|
+
|
|
10
|
+
## Instructions
|
|
11
|
+
- Reply the message directly if it's a simple response.
|
|
12
|
+
- Use gateway_channel tool to proactively send messages: \`\`\`json
|
|
13
|
+
{"operation": "send", "contactUid": "${u}", "content": "Your message here"}
|
|
14
|
+
\`\`\``,w={source:t.sessionId,title:`[${l}] Message from ${g}`,agent:"gateway",sessionId:i,parts:t.content,system:C,channel:{platform:l,contactUid:u,channelId:r?.channelId,userId:g}},L=await n.run(w),m=L.metadata?.sessionId;if(m&&s&&s.backendSessionId!==m&&(await this.sessionManager.bindBackendSession(t.sessionId,m),this.log.info("backend session bound",{gatewaySessionId:t.sessionId,backendSessionId:m})),await this.triggerHook(HookEvent.GatewayMessageComplete,{messageId:t.id,sessionId:t.sessionId,backendSessionId:m||i,processorId:"subagent",status:"completed",timestamp:Date.now()}),L.output){let v=t.metadata.channel;v?.channelId&&await this.sendToChannel(v.channelId,{id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:t.sessionId,type:"output",content:[{type:"text",text:L.output}],metadata:{channel:v},timestamp:Date.now()});}this.log.info("SubAgent response sent",{id:t.id});}catch(e){this.log.error("SubAgent dispatch failed",{id:t.id,error:String(e)});}}async triggerHook(t,e){if(k())try{await T().hookRegistry.emit({name:t,data:e});}catch{this.log.debug("hook trigger skipped",{event:t});}}async storeMessage(t){let e={messageId:t.id,sessionId:t.sessionId,type:t.type,content:t.content,channel:t.metadata.channel,replyToMessageId:t.metadata.replyToMessageId,timestamp:t.timestamp||Date.now()};if(k())try{await T().hookRegistry.emit({name:HookEvent.GatewayMessageReceive,data:e}),this.log.debug("message stored via hook",{messageId:t.id});return}catch{this.log.debug("hook trigger skipped, using local storage");}await this.messageStore.store(t),this.log.debug("message stored locally",{messageId:t.id});}async processMessage(t,e,n,s={}){if(await this.messageStore.updateStatus(e,"processing",{processedBy:n}),k())try{await T().hookRegistry.emit({name:HookEvent.GatewayMessageProcess,data:{messageId:e,sessionId:t,processorId:n,processType:s.processType||"direct",agent:s.agent,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}}async completeMessage(t,e,n,s={}){let{success:i=true,error:r,responseMessageId:l,tokens:g,duration:u}=s;if(await this.messageStore.updateStatus(e,i?"completed":"failed",{processedBy:n,error:r}),k())try{await T().hookRegistry.emit({name:HookEvent.GatewayMessageComplete,data:{messageId:e,sessionId:t,processorId:n,status:i?"completed":"failed",error:r,responseMessageId:l,tokens:g,duration:u,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}await this.router.completeMessage(t,e,n,i?"completed":"failed");}async onEvent(t){switch(this.log.debug("channel event",{type:t.type,channelId:t.channelId}),t.type){case "connected":this.connections++;break;case "disconnected":this.connections--;break;case "error":this.log.error("channel error",{channelId:t.channelId,data:t.data});break}}async registerChannel(t,e){let n=e??{enabled:true,platform:{},session:{autoCreate:true,resetPolicy:"onNewConversation"},routing:{broadcast:true,dispatchToSubAgent:false}};await this.pluginLoader.register(t,n),this.running&&await this.pluginLoader.start(t.id);}async unregisterChannel(t){await this.pluginLoader.unregister(t);}async subscribe(t,e){await this.router.subscribe(t,e),await this.sessionManager.addSubscriber(t,e.id);}async unsubscribe(t){await this.router.unsubscribe(t);}async send(t){await this.onMessage(t);}async sendToChannel(t,e,n={}){let{proactive:s=false,replyToMessageId:i}=n;if(k())try{await T().hookRegistry.emit({name:HookEvent.GatewayMessageSend,data:{messageId:e.id,sessionId:e.sessionId,type:e.type,channel:e.metadata.channel,proactive:s,replyToMessageId:i,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}let r=this.pluginLoader.getPlugin(t);if(!r)throw new Error(`Plugin not found: ${t}`);return r.send(e)}async sendProactiveMessage(t,e,n,s){let i={id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:e,type:"output",content:n,metadata:{channel:s},timestamp:Date.now()};return this.sendToChannel(t,i,{proactive:true})}getSessionManager(){return this.sessionManager}getRouter(){return this.router}getPluginLoader(){return this.pluginLoader}getMessageStore(){return this.messageStore}getContactStore(){return this.contactStore}async getMessageHistory(t,e){return this.messageStore.getSessionHistory(t,e)}};export{Jt as $,Lt as A,Ot as B,Ut as C,Ft as D,Wt as E,Bt as F,Ht as G,zt as H,$t as I,jt as J,qt as K,Qe as L,Ln as M,On as N,k as O,T as P,Re as Q,se as R,ie as S,b as T,rt as U,Me as V,Ae as W,Te as X,Ne as Y,Kt as Z,Vt as _,ce as a,Qt as aa,le as b,we as ba,ge as c,H as ca,de as d,z as da,ue as e,q as ea,he as f,K as fa,pe as g,N as ga,He as h,y as ha,ze as i,J as ia,$e as j,Q as ja,je as k,Y as ka,qe as l,X as la,fe as m,Z as ma,me as n,ee as na,ye as o,te as oa,be as p,ne as pa,Ce as q,ln as qa,Se as r,Be as ra,ae as s,so as sa,Ee as t,it as ta,ut as u,Ke as v,Ve as w,Je as x,Gt as y,Dt as z};
|