@easbot/gateway 0.2.27 → 0.2.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ import {a}from'./chunk-7OFQ65NG.mjs';import {a as a$1}from'./chunk-HAMGVOQD.mjs';import l from'zod';import*as L from'path';import L__default from'path';import*as D from'fs';import D__default,{existsSync}from'fs';import*as M from'fs/promises';import M__default from'fs/promises';import {Fetch,PKG,TruncateContent,Filesystem,createServer}from'@easbot/utils';import {WebSocketServer}from'ws';import us from'https';import ps from'http';import {fileURLToPath}from'url';import {HookEvent}from'@easbot/plugin';function w(c,t,e,s){return {id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c,type:t,content:e,metadata:{channel:{platform:s?.channel?.platform??"api",channelId:s?.channel?.channelId??"default",userId:s?.channel?.userId,chatId:s?.channel?.chatId,...Object.fromEntries(Object.entries(s?.channel??{}).filter(([n])=>!["platform","channelId","userId","chatId"].includes(n)))},context:s?.context,agent:s?.agent},timestamp:Date.now()}}function pt(c,t,e,s){return w(c,t,[{type:"text",text:e}],s)}function ce(c){let t={platform:c.channel?.platform??"api",channelId:c.channel?.channelId??"unknown",chatId:c.channel?.chatId,userId:c.channel?.userId,chatType:c.channel?.chatType,chatTitle:c.channel?.chatTitle};return {id:c.id,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,processorId:c.processorId,agent:c.agent,proactive:c.proactive??!c.replyToMessageId},timestamp:c.timestamp??Date.now()}}function Ee(c){let t=[c.platform,c.channelId,c.chatId??""],e=c.userId??c.chatId??"";return t.push(e),t.join("_")}function Ne(){return {status:"active",messageCount:0,lastMessageAt:null}}function le(c,t){if(!c||!t)throw new Error("platform and stableId are required");return `${c}:${t}`}function ge(c){if(!c||typeof c!="string")return null;let t=c.indexOf(":");if(t<=0||t>=c.length-1)return null;let e=c.slice(0,t),s=c.slice(t+1);return !e||!s?null:{platform:e,stableId:s}}function Ge(c){let{platform:t,stableId:e,profile:s={},aliases:n={},metadata:i}=c;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:le(t,e),platform:t,stableId:e,aliases:{...n},profile:{...s},createdAt:r,lastSeenAt:r,metadata:i}}function De(c,t){return `sub_${c}_${t}`}var ht=a.create({service:"gateway:config"});l.enum(["telegram","slack","feishu","wechat","webchat","signal","nostr"]);l.enum(["low","medium","high","critical"]);var ue=l.object({enabled:l.boolean().default(true),botToken:l.string().describe("Telegram Bot Token"),webhookUrl:l.string().optional().describe("Webhook URL for receiving updates"),polling:l.object({enabled:l.boolean(),interval:l.number().int().positive().optional().describe("Polling interval in ms"),timeout:l.number().int().positive().optional().describe("Long polling timeout in seconds")}).refine(c=>c===void 0||c.enabled===true,{message:"polling.enabled must be true when polling is configured"}).optional(),maxConnections:l.number().int().positive().optional().default(100),timeout:l.number().int().positive().optional().default(3e4)}),pe=l.object({enabled:l.boolean().default(true),botToken:l.string().describe("Slack Bot Token (xoxb-*)"),appToken:l.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:l.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:l.number().int().positive().optional().default(100),timeout:l.number().int().positive().optional().default(3e4)}),he=l.object({enabled:l.boolean().default(true),appId:l.string().describe("Feishu App ID"),appSecret:l.string().describe("Feishu App Secret"),encryptKey:l.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:l.string().optional().describe("Feishu Verification Token"),maxConnections:l.number().int().positive().optional().default(100),timeout:l.number().int().positive().optional().default(3e4)}),fe=l.object({enabled:l.boolean().default(true),mode:l.enum(["official","wecom"]).default("official"),appId:l.string().describe("WeChat App ID"),appSecret:l.string().describe("WeChat App Secret"),token:l.string().optional().describe("WeChat Token for message verification"),encodingAESKey:l.string().optional().describe("WeChat Encoding AES Key"),agentId:l.string().optional().describe("WeCom Agent ID"),maxConnections:l.number().int().positive().optional().default(100),timeout:l.number().int().positive().optional().default(3e4)}),me=l.object({enabled:l.boolean().default(true),path:l.string().optional().default("/"),heartbeatInterval:l.number().int().positive().optional().default(3e4),connectionTimeout:l.number().int().positive().optional().default(6e4),maxConnections:l.number().int().positive().optional().default(1e3),cors:l.boolean().optional().default(true)}),ye=l.object({enabled:l.boolean().default(true),serviceUrl:l.string().optional().default("https://chat.signal.org"),phoneNumber:l.string().describe("Signal phone number"),password:l.string().optional().describe("Signal account password"),maxConnections:l.number().int().positive().optional().default(100),timeout:l.number().int().positive().optional().default(3e4)}),be=l.object({enabled:l.boolean().default(true),relays:l.array(l.string()).min(1).describe("Nostr relay URLs"),privateKey:l.string().optional().describe("Nostr private key (hex)"),publicKey:l.string().optional().describe("Nostr public key (hex)"),maxConnections:l.number().int().positive().optional().default(100),timeout:l.number().int().positive().optional().default(3e4)}),Qe=l.object({telegram:ue.optional(),slack:pe.optional(),feishu:he.optional(),wechat:fe.optional(),webchat:me.optional(),signal:ye.optional(),nostr:be.optional()}),Ye=l.object({enabled:l.boolean().default(false),cert:l.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:l.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:l.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:l.string().optional().describe("Path to SSL key file (alias of key)"),ca:l.string().optional().describe("Path to CA certificate file"),forceRedirect:l.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:l.number().int().positive().optional().default(80).describe("HTTP redirect port")}),ft=l.object({name:l.string().describe("Token name/description"),value:l.string().describe("Token value"),permissions:l.array(l.string()).default(["*"]).describe("Associated permissions"),expiresAt:l.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:l.string().optional().describe("Token description")}),mt=l.object({enabled:l.boolean().default(true),tokens:l.array(ft).default([]).describe("List of valid tokens"),onInvalid:l.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:l.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:l.array(l.string()).default([]).describe("Default permissions for anonymous users")}),yt=l.object({enabled:l.boolean().default(false),authorizationServer:l.string().describe("OAuth2 authorization server URL"),clientId:l.string().describe("OAuth2 client ID"),clientSecret:l.string().describe("OAuth2 client secret"),tokenValidationEndpoint:l.string().describe("OAuth2 token validation endpoint"),scope:l.array(l.string()).default([]).describe("OAuth2 scopes")}),Xe=l.object({type:l.enum(["token","oauth2"]).default("token"),token:mt.optional(),oauth2:yt.optional()}),Ze=l.object({mode:l.enum(["pull","push","both"]).default("both"),interval:l.number().int().positive().default(3e4),pushEvents:l.array(l.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:l.enum(["latest","local","remote"]).default("latest")}),bt=l.object({id:l.string().describe("Gateway node ID"),address:l.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:l.boolean().default(true),metadata:l.record(l.string(),l.any()).optional()}),et=l.object({nodeId:l.string().describe("Current gateway node ID"),nodes:l.array(bt).default([]).describe("Other gateway nodes in the cluster"),sync:Ze.optional()}),Ce=l.object({maxConnectionsPerChannel:l.number().int().positive().default(100),idleTimeout:l.number().int().positive().default(3e5),reuseStrategy:l.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:l.number().int().positive().default(6e4),acquireTimeout:l.number().int().positive().default(5e3),warmupCount:l.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),Se=l.object({maxLength:l.number().int().positive().default(1e4),concurrency:l.number().int().positive().default(100),batchSize:l.number().int().positive().default(10),batchTimeout:l.number().int().positive().default(100),priorityLevels:l.number().int().positive().default(4)}),ve=l.object({failureThreshold:l.number().int().positive().default(5),successThreshold:l.number().int().positive().default(3),timeout:l.number().int().positive().default(3e4),halfOpenDuration:l.number().int().positive().default(15e3)}),we=l.object({heartbeatInterval:l.number().int().positive().default(3e4),heartbeatTimeout:l.number().int().positive().default(9e4),heartbeatCheckInterval:l.number().int().positive().default(1e4),autoDeregisterTimeout:l.number().int().positive().default(3e5),maxAgents:l.number().int().positive().default(100),persistenceFile:l.string().optional().describe("Path to persist agent registrations"),maxRegistrations:l.number().int().positive().default(1e3)}),Ie=l.object({sessionTimeout:l.number().int().positive().default(18e5),resumeGracePeriod:l.number().int().positive().default(3e5),maxSessions:l.number().int().positive().default(1e4),persistenceFile:l.string().optional().describe("Path to persist sessions")}),Pe=l.object({enabled:l.boolean().default(true),port:l.number().int().positive().default(8080),hostname:l.string().default("localhost"),path:l.string().optional().default("/"),maxConnections:l.number().int().positive().optional().default(1e3),connectionTimeout:l.number().int().positive().optional().default(6e4),heartbeatInterval:l.number().int().positive().optional().default(3e4),sessionExpireMs:l.number().int().positive().optional().default(3e5),https:Ye.optional(),auth:Xe.optional(),cors:l.boolean().default(true),corsOrigins:l.array(l.string()).optional(),mdns:l.boolean().default(false),mdnsDomain:l.string().optional().default("gateway.easbot.local")}),Ct=l.object({channel:l.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:l.array(l.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),de=l.object({server:Pe.optional(),channels:Qe.optional(),cluster:et.optional(),connectionPool:Ce.optional(),messageQueue:Se.optional(),circuitBreaker:ve.optional(),agentRegistry:we.optional(),session:Ie.optional(),defaults:Ct.optional(),defaultAgent:l.string().optional().describe("Default agent ID for routing"),logLevel:l.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(l.unknown());function Le(c){let t=de.safeParse(c);return t.success||ht.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:de.parse({})}function St(c){return de.parse(c)}var vt=a.create({service:"gateway:interfaces"}),x;function Ls(c){x=c,vt.debug("Agent adapter registered",{hasSubAgentRunner:!!c.subAgentRunner});}function Os(){return x}function F(){return x!==void 0}function $(){if(!x)throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");return x}var wt={Path:{home:process.env.HOME||process.env.USERPROFILE||"",data:".easbot",cache:".easbot/cache",config:".easbot",state:".easbot/state",log:".easbot/log",bin:".easbot/bin"}},It={directory:process.cwd(),worktree:process.cwd()};function N(){return x?x.global:wt}function Oe(){return x?x.instance:It}var A=a.create({service:"gateway:config"}),Me={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}},xt={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},At={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},Tt={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},kt={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3},Rt={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e4},_t={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Et={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Nt={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},Gt={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},Dt={enabled:true,path:"/ws",heartbeatInterval:3e4,connectionTimeout:6e4,maxConnections:1e3,cors:true},Lt={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},Ot={enabled:true,relays:[],maxConnections:100,timeout:3e4},z,q=null;async function rt(c){try{if(!existsSync(c))return null;let t=await M__default.readFile(c,"utf-8");t=t.replace(/\{env:([^}]+)\}/g,(r,o)=>{let g=process.env[o];return g===void 0?(A.debug("Environment variable not found",{varName:o,file:c}),""):g});let e=t,s=!1,n=!1,i=[];for(let r=0;r<t.length;r++){let o=t[r];if(n){i.push(o),n=!1;continue}if(o==="\\"){i.push(o),n=!0;continue}if(o==='"'){s=!s,i.push(o);continue}if(!s&&o==="/"&&t[r+1]==="/"){for(;r<t.length&&t[r]!==`
2
+ `&&t[r]!=="\r";)r++;continue}if(!s&&o==="/"&&t[r+1]==="*"){for(r+=2;r<t.length-1;){if(t[r]==="*"&&t[r+1]==="/"){r+=2;break}r++;}continue}i.push(o);}return e=i.join("").trim(),e?JSON.parse(e):null}catch(t){return A.debug("Failed to load config file",{file:c,error:String(t)}),null}}function j(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 Ut(){let c=N(),t=Oe(),e=[],s=L__default.join(c.Path.config);e.push(s),e.push(t.directory);try{let{Filesystem:i}=await import('@easbot/utils'),r=await Array.fromAsync(i.up({targets:[".easbot"],start:t.directory,stop:t.worktree}));e.push(...r);}catch{A.debug("Filesystem utils not available, using basic directories");}let n=process.env.EASBOT_CONFIG_DIR;return n&&(e.push(n),A.debug("Using EASBOT_CONFIG_DIR",{path:n})),[...new Set(e)]}async function Ft(c){let t=["gateway.json"],e={};for(let s of t){let n=L__default.join(c,s),i=await rt(n);if(i)if("gateway"in i&&i.gateway){let r=i.gateway;"server"in r||"channels"in r||"cluster"in r?e=j(e,r):e=j(e,{server:r}),A.debug("Loaded gateway config from file (nested format)",{file:n});}else "gateway"in i||(e=j(e,i),A.debug("Loaded gateway config from file (direct format)",{file:n}));}return e}async function Bt(c){let t=["easbot.json"];for(let e of t){let s=L__default.join(c,e),n=await rt(s);if(n?.gateway)return A.debug("Loaded gateway config from easbot.json",{file:s}),n.gateway}return {}}function Wt(){return z||(z=async()=>{let c=await Ut(),t={};for(let s of c){let n=await Ft(s);t=j(t,n);let i=await Bt(s);t=j(t,i);}let e=Le(t);return q=e,A.info("Gateway config loaded",{directories:c.length,port:e.server?.port,logLevel:e.logLevel}),{config:e,directories:c}}),z}async function I(){return Wt()()}async function tt(c){return c&&(z=void 0,q=null),(await I()).config}function st(){return q}function nt(){return q!==null}function Ht(){z=void 0,q=null,A.debug("Config cache cleared");}function $t(){return Oe().directory}async function zt(){let{config:c}=await I();return Pe.parse({...Me,...c.server})}async function jt(c){let{config:t}=await I(),e=t.channels?.[c],n={telegram:ue.parse(_t),slack:pe.parse(Et),feishu:he.parse(Nt),wechat:fe.parse(Gt),webchat:me.parse(Dt),signal:ye.parse(Lt),nostr:be.parse(Ot)}[c];if(!n)throw new Error(`Unknown channel type: ${c}`);return {...n,...e}}async function qt(){let{config:c}=await I();return Ce.parse({...xt,...c.connectionPool})}async function Kt(){let{config:c}=await I();return Se.parse({...At,...c.messageQueue})}async function Vt(){let{config:c}=await I();return ve.parse({...Tt,...c.circuitBreaker})}async function Jt(){let{config:c}=await I();return we.parse({...kt,...c.agentRegistry})}async function Qt(){let{config:c}=await I();return Ie.parse({...Rt,...c.session})}async function Yt(){let{config:c}=await I();return c.server?.https}async function Xt(){let{config:c}=await I();return c.server?.auth}async function Zt(){let{config:c}=await I();return c.cluster}async function es(){let{config:c}=await I();return c.defaultAgent}async function it(){let{config:c}=await I();return c.logLevel??"INFO"}var Fe=Me,K={maxConnections:1e3,connectionTimeout:6e4,sessionExpireMs:3e5};var ts={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var ss={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3};var ns={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};var is={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var T=class c extends Error{constructor(e,s){super(e);a$1(this,"code");a$1(this,"recoverable");a$1(this,"details");a$1(this,"cause");this.name="GatewayError",this.code=s.code,this.recoverable=s.recoverable,this.details=s.details,this.cause=s.cause,Error.captureStackTrace&&Error.captureStackTrace(this,c);}toJSON(){return {name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,details:this.details,cause:this.cause?.message,stack:this.stack}}static isRecoverable(e){if(e instanceof c)return e.recoverable;let s=e.code;return ["ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH"].includes(s??"")}};function G(c,t,e,s=true){return new T(e,{code:t,recoverable:s,details:{channelId:c}})}var xe=class{constructor(t){a$1(this,"log",a.create({service:"gateway:router"}));a$1(this,"subscribers",new Map);a$1(this,"subscriptions",new Map);a$1(this,"sessionSubscriptions",new Map);a$1(this,"channelPlugins",new Map);a$1(this,"cancelHandlers",new Set);a$1(this,"processingMessages",new Map);a$1(this,"hookRegistry",null);this.hookRegistry=t??null;}async triggerHook(t,e,s){if(this.hookRegistry)try{await this.hookRegistry.triggerEvent(t,e,s);}catch{this.log.debug("hook trigger skipped",{event:t});}}async triggerBeforeSend(t,e){await this.triggerHook("gateway.message.process",{messageId:t.id,sessionId:t.sessionId,processorId:e,processType:"subscription",agent:e,timestamp:Date.now()});}onCancel(t){this.cancelHandlers.add(t);}offCancel(t){this.cancelHandlers.delete(t);}async emitCancel(t){for(let e of this.cancelHandlers)try{await e(t);}catch(s){this.log.error("cancel handler error",{error:String(s)});}}async route(t){this.log.debug("routing message",{id:t.id,sessionId:t.sessionId,type:t.type});let e=this.sessionSubscriptions.get(t.sessionId);if(!e||e.size===0)return this.log.debug("no subscribers for session",{sessionId:t.sessionId}),{success:true,dispatched:false,dispatchedToSubAgent:false};let s=false,n=null,i=[];for(let r of e){let o=this.subscriptions.get(r);if(!o)continue;let g=this.subscribers.get(o.subscriberId);if(g){if(t.type==="input"){let d=this.processingMessages.get(t.id);if(d&&d!==g.id){this.log.debug("skipping subscriber, message already being processed",{subscriberId:g.id,processor:d});continue}n=g.id,this.processingMessages.set(t.id,g.id);}try{await this.triggerBeforeSend(t,g.id),await g.connection.send(t),s=!0,g.lastActiveAt=Date.now();}catch(d){this.log.warn("failed to send message to subscriber",{subscriberId:g.id,error:String(d)}),i.push(d instanceof Error?d:new Error(String(d))),n===g.id&&(this.processingMessages.delete(t.id),n=null);}}}return this.log.debug("message routed",{id:t.id,dispatched:s,errorCount:i.length,processedBy:n}),{success:i.length===0,dispatched:s,dispatchedToSubAgent:false,error:i.length>0?i.map(r=>r.message).join("; "):void 0}}async completeMessage(t,e,s,n="completed"){this.processingMessages.delete(e),await this.emitCancel({sessionId:t,messageId:e,processedBy:s,reason:n,timestamp:Date.now()}),this.log.info("message completed",{sessionId:t,messageId:e,subscriberId:s,reason:n});}async subscribe(t,e){let s=De(e.id,t);if(this.subscriptions.has(s))return this.log.debug("already subscribed",{subscriberId:e.id,sessionId:t}),this.subscriptions.get(s);let n={id:s,subscriberId:e.id,sessionId:t,createdAt:Date.now()};return this.subscribers.has(e.id)||this.subscribers.set(e.id,e),this.subscriptions.set(s,n),this.sessionSubscriptions.has(t)||this.sessionSubscriptions.set(t,new Set),this.sessionSubscriptions.get(t).add(s),e.sessions.add(t),this.log.info("subscribed to session",{subscriberId:e.id,sessionId:t,subscriptionId:s}),n}async unsubscribe(t){let e=this.subscriptions.get(t);if(!e){this.log.warn("subscription not found",{subscriptionId:t});return}this.subscriptions.delete(t);let s=this.sessionSubscriptions.get(e.sessionId);s&&(s.delete(t),s.size===0&&this.sessionSubscriptions.delete(e.sessionId));let n=this.subscribers.get(e.subscriberId);n&&n.sessions.delete(e.sessionId),this.log.info("unsubscribed from session",{subscriberId:e.subscriberId,sessionId:e.sessionId,subscriptionId:t});}async unsubscribeAll(t){let e=this.subscribers.get(t);if(!e)return;let s=[...e.sessions];for(let n of s){let i=this.sessionSubscriptions.get(n);if(i)for(let r of i)this.subscriptions.get(r)?.subscriberId===t&&await this.unsubscribe(r);}this.subscribers.delete(t),this.log.info("all subscriptions removed for subscriber",{subscriberId:t});}registerChannel(t){this.channelPlugins.set(t.id,t),this.log.info("channel plugin registered",{id:t.id,platform:t.platform});}unregisterChannel(t){this.channelPlugins.delete(t),this.log.info("channel plugin unregistered",{id:t});}getSubscriber(t){return this.subscribers.get(t)}getSubscription(t){return this.subscriptions.get(t)}getSubscriberCount(t){return this.sessionSubscriptions.get(t)?.size??0}getStats(){return {subscribers:this.subscribers.size,subscriptions:this.subscriptions.size,sessions:this.sessionSubscriptions.size}}async shutdown(){this.processingMessages.clear(),this.subscribers.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.channelPlugins.clear(),this.cancelHandlers.clear(),this.log.info("router shutdown");}};var V=class{constructor(t={}){a$1(this,"log",a.create({service:"gateway:message-store"}));a$1(this,"config");a$1(this,"messages",new Map);a$1(this,"sessionMessages",new Map);a$1(this,"cleanupTimer",null);a$1(this,"accessOrder",[]);a$1(this,"storagePath");a$1(this,"dirty",false);this.config={storagePath:t.storagePath??"./data/gateway-messages",maxRetentionDays:t.maxRetentionDays??7,maxRecords:t.maxRecords??5e4,cleanupIntervalMs:t.cleanupIntervalMs??36e5,cleanupBatchSize:t.cleanupBatchSize??1e3,lruEnabled:t.lruEnabled??true,lruMaxMemory:t.lruMaxMemory??0},this.storagePath=this.config.storagePath,this.ensureDir(this.storagePath),this.startCleanupTimer();}async ensureDir(t){try{await M.mkdir(t,{recursive:!0});}catch(e){e.code!=="EEXIST"&&this.log.warn("failed to create storage directory",{dirPath:t,error:String(e)});}}getMessageFilePath(t){return L.join(this.storagePath,`${this.sanitizeFileName(t)}.json`)}getSessionDir(t){return L.join(this.storagePath,this.sanitizeFileName(t))}sanitizeFileName(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}startCleanupTimer(){this.cleanupTimer||(this.cleanupTimer=setInterval(()=>{this.performCleanup().catch(t=>{this.log.error("Cleanup error",{error:String(t)});});},this.config.cleanupIntervalMs),this.cleanupTimer.unref?.(),this.log.info("Cleanup timer started",{intervalMs:this.config.cleanupIntervalMs}));}performCleanup(){return new Promise(t=>{let e=this.cleanup();this.log.info("Periodic cleanup completed",{deleted:e}),t();})}async store(t,e="pending"){this.messages.size>=this.config.maxRecords&&this.evictLRU(1e3),this.config.lruEnabled&&this.updateAccessOrder(t.id);let s={message:t,status:e,processedBy:e==="completed"?"gateway":null,processedAt:e==="completed"?Date.now():null,retryCount:0,error:null,createdAt:Date.now(),updatedAt:Date.now(),deliveredAt:null,readAt:null};return this.messages.set(t.id,s),this.sessionMessages.has(t.sessionId)||this.sessionMessages.set(t.sessionId,new Set),this.sessionMessages.get(t.sessionId).add(t.id),this.dirty=true,await this.saveMessageToFile(s),this.log.debug("message stored",{id:t.id,sessionId:t.sessionId,type:t.type,total:this.messages.size}),s}async saveMessageToFile(t){try{let e=this.getSessionDir(t.message.sessionId);await this.ensureDir(e);let s=L.join(e,`${this.sanitizeFileName(t.message.id)}.json`);await M.writeFile(s,JSON.stringify(t,null,2),"utf-8");}catch(e){this.log.warn("failed to save message to file",{messageId:t.message.id,error:String(e)});}}get(t){let e=this.messages.get(t);return e&&this.config.lruEnabled&&this.updateAccessOrder(t),e}async updateStatus(t,e,s={}){let n=this.messages.get(t);if(!n){this.log.warn("message not found for status update",{messageId:t});return}n.status=e,n.updatedAt=Date.now(),s.processedBy&&(n.processedBy=s.processedBy),(e==="completed"||e==="failed")&&(n.processedAt=Date.now()),s.error&&(n.error=s.error),s.deliveredAt&&(n.deliveredAt=s.deliveredAt),s.readAt&&(n.readAt=s.readAt),this.dirty=true,await this.saveMessageToFile(n),this.log.debug("message status updated",{id:t,status:e,processedBy:s.processedBy});}async incrementRetry(t){let e=this.messages.get(t);return e?(e.retryCount++,e.updatedAt=Date.now(),this.dirty=true,await this.saveMessageToFile(e),e.retryCount):0}isProcessed(t){let e=this.messages.get(t);return e?e.status==="completed"||e.status==="processing":false}getSessionHistory(t,e=100){let s=this.sessionMessages.get(t);if(!s)return [];let n=[];for(let i of s){let r=this.messages.get(i);r&&n.push(r);}return n.sort((i,r)=>i.createdAt-r.createdAt),n.slice(-e)}getPendingMessages(t,e){let s=[];for(let n of this.messages.values())if(n.status==="pending"){if(e&&n.message.type!==e)continue;(!t||n.message.sessionId===t)&&s.push(n);}return s}getFailedMessages(t=3,e){let s=[];for(let n of this.messages.values())if(n.status==="failed"&&n.retryCount<t){if(e&&n.message.type!==e)continue;s.push(n);}return s}cleanup(){let t=Date.now(),e=this.config.maxRetentionDays*24*60*60*1e3,s=[];for(let[n,i]of this.messages)if((t-i.createdAt>e||i.status==="completed")&&(s.push(n),s.length>=this.config.cleanupBatchSize))break;for(let n of s)this.deleteMessage(n);return s.length>0&&this.log.info("cleanup completed",{deleted:s.length,remaining:this.messages.size}),s.length}evictLRU(t){if(!this.config.lruEnabled||this.accessOrder.length===0)return;let e=0;for(;e<t&&this.accessOrder.length>0;){let s=this.accessOrder.shift();s&&(this.deleteMessage(s),e++);}this.log.info("LRU eviction completed",{evicted:e,remaining:this.messages.size});}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e>-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t);}deleteMessage(t){let e=this.messages.get(t);if(e){let s=this.sessionMessages.get(e.message.sessionId);s&&(s.delete(t),s.size===0&&this.sessionMessages.delete(e.message.sessionId)),this.messages.delete(t);let n=this.accessOrder.indexOf(t);n>-1&&this.accessOrder.splice(n,1);}}getStats(){let t={total:this.messages.size,pending:0,processing:0,completed:0,failed:0,cancelled:0,delivered:0,read:0,sessions:this.sessionMessages.size};for(let e of this.messages.values()){let s=e.status;s in t&&s!=="total"&&s!=="sessions"&&t[s]++;}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 J=class{constructor(t={}){a$1(this,"log",a.create({service:"gateway:session-store"}));a$1(this,"config");a$1(this,"sessions",new Map);a$1(this,"channelSessions",new Map);a$1(this,"autoSaveTimer",null);a$1(this,"isDirty",false);this.config={storagePath:t.storagePath??"./data/gateway-sessions",autoSaveInterval:t.autoSaveInterval??6e4,maxRetentionDays:t.maxRetentionDays??7,enablePersistence:t.enablePersistence??true};}async initialize(){if(!this.config.enablePersistence){this.log.info("session persistence disabled");return}await this.ensureStorageDir(),await this.load(),this.startAutoSave(),this.log.info("session store initialized",{sessionCount:this.sessions.size,storagePath:this.config.storagePath});}async close(){this.stopAutoSave(),this.isDirty&&await this.save(),this.log.info("session store closed");}async set(t){this.sessions.set(t.id,t),this.channelSessions.has(t.channel.channelId)||this.channelSessions.set(t.channel.channelId,new Set),this.channelSessions.get(t.channel.channelId).add(t.id),this.markDirty(),await this.save();}get(t){return this.sessions.get(t)}async delete(t){let e=this.sessions.get(t);if(!e)return;this.sessions.delete(t);let s=this.channelSessions.get(e.channel.channelId);s&&(s.delete(t),s.size===0&&this.channelSessions.delete(e.channel.channelId)),this.markDirty(),await this.save();}getAll(){return [...this.sessions.values()]}getByChannel(t){let e=this.channelSessions.get(t);return e?[...e].map(s=>this.sessions.get(s)).filter(s=>s!==void 0):[]}size(){return this.sessions.size}markDirty(){this.isDirty=true;}async save(){if(!this.config.enablePersistence)return;let t=this.getSessionFilePath(),e=this.serializeAll();try{await this.ensureStorageDir(),await D.promises.writeFile(t,JSON.stringify(e,null,2),"utf-8"),this.isDirty=!1,this.log.debug("sessions saved",{count:e.length});}catch(s){throw this.log.error("failed to save sessions",{error:s}),s}}async load(){if(!this.config.enablePersistence)return;let t=this.getSessionFilePath();try{if(!D.existsSync(t)){this.log.debug("no saved sessions found");return}let e=await D.promises.readFile(t,"utf-8"),s=JSON.parse(e);this.sessions.clear(),this.channelSessions.clear();let n=Date.now(),i=this.config.maxRetentionDays*24*60*60*1e3;for(let r of s){if(n-r.lastActiveAt>i)continue;let o={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(o.id,o),this.channelSessions.has(o.channel.channelId)||this.channelSessions.set(o.channel.channelId,new Set),this.channelSessions.get(o.channel.channelId).add(o.id);}this.log.info("sessions loaded",{loaded:this.sessions.size,skipped:s.length-this.sessions.size});}catch(e){this.log.error("failed to load sessions",{error:e});}}serializeAll(){let t=[];for(let e of this.sessions.values())t.push(this.serialize(e));return t}serialize(t){return {id:t.id,channel:t.channel,backendSessionId:t.backendSessionId,subscribers:[...t.subscribers],state:t.state,createdAt:t.createdAt,lastActiveAt:t.lastActiveAt}}getSessionFilePath(){return L.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){D.existsSync(this.config.storagePath)||await D.promises.mkdir(this.config.storagePath,{recursive:true});}startAutoSave(){this.autoSaveTimer||(this.autoSaveTimer=setInterval(async()=>{this.isDirty&&await this.save();},this.config.autoSaveInterval));}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null);}async cleanup(){let t=Date.now(),e=this.config.maxRetentionDays*24*60*60*1e3,s=[];for(let n of this.sessions.values())t-n.lastActiveAt>e&&s.push(n.id);for(let n of s)await this.delete(n);return s.length>0&&(this.log.info("cleaned up expired sessions",{count:s.length}),await this.save()),s.length}getStats(){let t={total:this.sessions.size,byStatus:{active:0,idle:0,closed:0},byPlatform:{}};for(let e of this.sessions.values()){t.byStatus[e.state.status]++;let s=e.channel.platform;t.byPlatform[s]=(t.byPlatform[s]||0)+1;}return t}};var rs="./data/gateway",as="contacts",os="index.json",Q=class{constructor(t={}){a$1(this,"log",a.create({service:"gateway:contact-store"}));a$1(this,"baseDir");a$1(this,"contactDir");a$1(this,"indexPath");a$1(this,"index");a$1(this,"indexFileMap");a$1(this,"dirty",false);a$1(this,"saveTimer",null);a$1(this,"SAVE_DEBOUNCE_MS",1e3);this.baseDir=t.baseDir??rs,this.contactDir=L.join(this.baseDir,as),this.indexPath=L.join(this.contactDir,os),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 M.mkdir(t,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async loadIndex(){try{let t=await M.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 M.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=ge(t);if(e){let s=this.getFilePath(e.platform,e.stableId);this.indexFileMap[t]=s;}}}getFilePath(t,e){let s=this.sanitizeFilename(e);return L.join(this.contactDir,t,`${s}.json`)}sanitizeFilename(t){return t.replace(/[/\\:*?"<>|]/g,"_")}getPlatformDir(t){return L.join(this.contactDir,t)}async save(t){let{platform:e,stableId:s,uid:n}=t,i=this.getFilePath(e,s);return await this.ensureDir(L.dirname(i)),await M.writeFile(i,JSON.stringify(t,null,2),"utf-8"),this.index.byUid[n]=i,this.indexFileMap[n]=i,this.index.byPlatform[e]||(this.index.byPlatform[e]=[]),this.index.byPlatform[e].includes(n)||this.index.byPlatform[e].push(n),this.updateSearchIndices(t),this.dirty=true,await this.saveIndex(),this.log.debug("contact saved",{uid:n,platform:e,stableId:s}),t}async create(t){let e=Ge(t);return this.save(e)}async getOrCreate(t,e,s){let n=await this.findByPlatformId(t,e);return n||this.create({platform:t,stableId:e,profile:s})}async findByUid(t){let e=ge(t);return e?this.findByPlatformId(e.platform,e.stableId):null}async findByPlatformId(t,e){let s=le(t,e),n=this.index.byUid[s];if(n)try{let r=await M.readFile(n,"utf-8");return JSON.parse(r)}catch(r){r.code!=="ENOENT"&&this.log.warn("failed to read contact file",{uid:s,filePath:n,error:String(r)}),delete this.index.byUid[s],this.dirty=true;}let i=this.getFilePath(t,e);try{let r=await M.readFile(i,"utf-8"),o=JSON.parse(r);return this.index.byUid[s]=i,this.indexFileMap[s]=i,this.dirty=!0,await this.saveIndex(),o}catch{return null}}async update(t,e){let s=await this.findByUid(t);if(!s)return null;let n={...s,profile:e.profile?{...s.profile,...e.profile}:s.profile,aliases:e.aliases?{...s.aliases,...e.aliases}:s.aliases,metadata:e.metadata?{...s.metadata,...e.metadata}:s.metadata,lastSeenAt:Date.now()};return this.save(n)}async touch(t){let e=await this.findByUid(t);e&&(e.lastSeenAt=Date.now(),await this.save(e));}async delete(t){let e=await this.findByUid(t);if(!e)return false;let{platform:s,stableId:n}=e,i=this.index.byUid[t]||this.getFilePath(s,n);try{await M.unlink(i);}catch(r){r.code!=="ENOENT"&&this.log.warn("failed to delete contact file",{uid:t,filePath:i,error:String(r)});}return delete this.index.byUid[t],delete this.indexFileMap[t],this.index.byPlatform[s]&&(this.index.byPlatform[s]=this.index.byPlatform[s].filter(r=>r!==t)),this.removeFromSearchIndices(e),this.dirty=true,await this.saveIndex(),this.log.debug("contact deleted",{uid:t}),true}async listByPlatform(t,e=100,s=0){let n=this.index.byPlatform[t]||[],i=n.length,r=n.slice(s,s+e),o=[];for(let g of r){let d=await this.findByUid(g);d&&o.push(d);}return {contacts:o,total:i,hasMore:s+e<i}}async findByUsername(t){let e=t.toLowerCase(),s=this.index.byUsername[e];return s?this.findByUid(s):null}async findByEmail(t){let e=t.toLowerCase(),s=this.index.byEmail[e];return s?this.findByUid(s):null}async findByPhone(t){let e=t.replace(/\s/g,""),s=this.index.byPhone[e];return s?this.findByUid(s):null}async search(t){if(t.platform){let g=await this.listByPlatform(t.platform,t.limit,t.offset),d=g.contacts;if(t.username){let p=t.username.toLowerCase();d=d.filter(y=>y.profile.username?.toLowerCase().includes(p));}if(t.email){let p=t.email.toLowerCase();d=d.filter(y=>y.profile.email?.toLowerCase().includes(p));}if(t.phone){let p=t.phone.replace(/\s/g,"");d=d.filter(y=>y.profile.phone?.replace(/\s/g,"").includes(p));}return {contacts:d,total:g.total,hasMore:g.hasMore}}let e=[];for(let g of Object.keys(this.index.byPlatform)){let d=await this.listByPlatform(g,1e3,0);e.push(...d.contacts);}let s=e;if(t.username){let g=t.username.toLowerCase();s=s.filter(d=>d.profile.username?.toLowerCase().includes(g));}if(t.email){let g=t.email.toLowerCase();s=s.filter(d=>d.profile.email?.toLowerCase().includes(g));}if(t.phone){let g=t.phone.replace(/\s/g,"");s=s.filter(d=>d.profile.phone?.replace(/\s/g,"").includes(g));}let n=s.length,i=t.limit??100,r=t.offset??0;return {contacts:s.slice(r,r+i),total:n,hasMore:r+i<n}}async count(t){return t?(this.index.byPlatform[t]||[]).length:Object.keys(this.index.byUid).length}async exists(t){return await this.findByUid(t)!==null}async addAlias(t,e,s){let n=await this.findByUid(t);if(!n)return null;let i={...n,aliases:{...n.aliases,[e]:{...n.aliases[e],...s}},lastSeenAt:Date.now()};return this.save(i)}async close(){this.saveTimer&&clearTimeout(this.saveTimer),this.dirty&&await this.doSaveIndex(),this.log.info("contact store closed");}updateSearchIndices(t){let{uid:e,profile:s}=t;s.username&&(this.index.byUsername[s.username.toLowerCase()]=e),s.email&&(this.index.byEmail[s.email.toLowerCase()]=e),s.phone&&(this.index.byPhone[s.phone.replace(/\s/g,"")]=e);}removeFromSearchIndices(t){let{uid:e,profile:s}=t;if(s.username){let n=s.username.toLowerCase();this.index.byUsername[n]===e&&delete this.index.byUsername[n];}if(s.email){let n=s.email.toLowerCase();this.index.byEmail[n]===e&&delete this.index.byEmail[n];}if(s.phone){let n=s.phone.replace(/\s/g,"");this.index.byPhone[n]===e&&delete this.index.byPhone[n];}}};var Be=class{constructor(t){a$1(this,"cache",new Map);a$1(this,"maxSize");this.maxSize=t;}get(t){let e=this.cache.get(t);return e!==void 0&&(this.cache.delete(t),this.cache.set(t,e)),e}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s);}this.cache.set(t,e);}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear();}get size(){return this.cache.size}},Y=class{constructor(t,e={}){a$1(this,"store",t);a$1(this,"cache");a$1(this,"usernameIndex");a$1(this,"emailIndex");a$1(this,"phoneIndex");a$1(this,"platformIndex");a$1(this,"initialized",false);this.cache=new Be(e.cacheSize??1e3),this.usernameIndex=new Map,this.emailIndex=new Map,this.phoneIndex=new Map,this.platformIndex=new Map;}async initialize(){this.initialized||("initialize"in this.store&&typeof this.store.initialize=="function"&&await this.store.initialize(),await this.warmCache(),this.initialized=true);}async warmCache(){try{let t=["telegram","discord","slack","feishu","wechat","webchat","signal","nostr"];for(let e of t)try{let s=await this.store.listByPlatform(e,1e3,0);for(let n of s.contacts)this.cacheContact(n);}catch{}}catch{}}cacheContact(t){let{uid:e,profile:s}=t;this.cache.set(e,t),s.username&&this.usernameIndex.set(s.username.toLowerCase(),e),s.email&&this.emailIndex.set(s.email.toLowerCase(),e),s.phone&&this.phoneIndex.set(s.phone.replace(/\s/g,""),e),this.platformIndex.has(t.platform)||this.platformIndex.set(t.platform,new Set),this.platformIndex.get(t.platform).add(e);}invalidateContact(t){let{uid:e,profile:s}=t;if(this.cache.delete(e),s.username){let i=s.username.toLowerCase();this.usernameIndex.get(i)===e&&this.usernameIndex.delete(i);}if(s.email){let i=s.email.toLowerCase();this.emailIndex.get(i)===e&&this.emailIndex.delete(i);}if(s.phone){let i=s.phone.replace(/\s/g,"");this.phoneIndex.get(i)===e&&this.phoneIndex.delete(i);}let n=this.platformIndex.get(t.platform);n&&n.delete(e);}async save(t){this.invalidateContact(t);let e=await this.store.save(t);return this.cacheContact(e),e}async create(t){let e=await this.store.create(t);return this.cacheContact(e),e}async getOrCreate(t,e,s){let n=this.cache.get(`${t}:${e}`);if(n)return n;let i=await this.store.getOrCreate(t,e,s);return this.cacheContact(i),i}async findByUid(t){let e=this.cache.get(t);if(e)return e;let s=await this.store.findByUid(t);return s&&this.cacheContact(s),s}async findByPlatformId(t,e){return this.findByUid(`${t}:${e}`)}async update(t,e){let s=await this.cache.get(t);s&&this.invalidateContact(s);let n=await this.store.update(t,e);return n&&this.cacheContact(n),n}async touch(t){await this.store.touch(t);}async delete(t){let e=await this.cache.get(t);return e&&this.invalidateContact(e),this.store.delete(t)}async listByPlatform(t,e=100,s=0){return this.store.listByPlatform(t,e,s)}async findByUsername(t){let e=t.toLowerCase(),s=this.usernameIndex.get(e);return s?this.findByUid(s):this.store.findByUsername(t)}async findByEmail(t){let e=t.toLowerCase(),s=this.emailIndex.get(e);return s?this.findByUid(s):this.store.findByEmail(t)}async findByPhone(t){let e=t.replace(/\s/g,""),s=this.phoneIndex.get(e);return s?this.findByUid(s):this.store.findByPhone(t)}async search(t){return this.store.search(t)}async count(t){return t?this.platformIndex.get(t)?.size??0:this.cache.size}async exists(t){return this.cache.has(t)?true:this.store.exists(t)}async addAlias(t,e,s){let n=await this.store.addAlias(t,e,s);return n&&(this.invalidateContact(n),this.cacheContact(n)),n}async close(){this.cache.clear(),this.usernameIndex.clear(),this.emailIndex.clear(),this.phoneIndex.clear(),this.platformIndex.clear(),"close"in this.store&&typeof this.store.close=="function"&&await this.store.close();}};var X=class{constructor(t={}){a$1(this,"log",a.create({service:"gateway:session"}));a$1(this,"sessionStore");a$1(this,"config");a$1(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 J({storagePath:this.config.storagePath,autoSaveInterval:this.config.autoSaveInterval,maxRetentionDays:this.config.maxRetentionDays,enablePersistence:this.config.enablePersistence});}async initialize(){this.initialized||(await this.sessionStore.initialize(),this.initialized=true,this.log.info("session manager initialized",{sessionCount:this.sessionStore.size(),persistenceEnabled:this.config.enablePersistence}));}async close(){await this.sessionStore.close(),this.log.info("session manager closed");}async getOrCreate(t,e={}){let s=Ee(t),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),this.log.debug("session found",{sessionId:s}),n):(n={id:s,channel:t,backendSessionId:null,subscribers:new Set,state:Ne(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(n),this.log.info("session created",{sessionId:s,platform:t.platform,channelId:t.channelId,chatId:t.chatId,userId:t.userId}),n)}get(t){return this.sessionStore.get(t)}async closeSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.state.status="closed",await this.sessionStore.delete(t),this.log.info("session closed",{sessionId:t});}async closeById(t){return this.closeSession(t)}async bindBackendSession(t,e){let s=this.sessionStore.get(t);if(!s)throw new Error(`Session not found: ${t}`);s.backendSessionId=e,await this.sessionStore.set(s),this.log.info("backend session bound",{gatewaySessionId:t,backendSessionId:e});}async unbindBackendSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.backendSessionId=null,await this.sessionStore.set(e),this.log.info("backend session unbound",{gatewaySessionId:t});}getState(t){return this.sessionStore.get(t)?.state}async incrementMessageCountOrCreate(t,e){let s=this.sessionStore.get(t);if(!s){let n=e??{platform:"api",channelId:"default"};s=await this.getOrCreate(n);}return s.state.messageCount++,s.state.lastMessageAt=Date.now(),s.lastActiveAt=Date.now(),await this.sessionStore.set(s),s}async incrementMessageCount(t){let e=this.sessionStore.get(t);e&&(e.state.messageCount++,e.state.lastMessageAt=Date.now(),e.lastActiveAt=Date.now(),await this.sessionStore.set(e));}async addSubscriber(t,e){let s=this.sessionStore.get(t);if(!s){this.log.warn("session not found",{sessionId:t});return}s.subscribers.add(e),await this.sessionStore.set(s),this.log.debug("subscriber added to session",{sessionId:t,subscriberId:e});}async removeSubscriber(t,e){let s=this.sessionStore.get(t);s&&(s.subscribers.delete(e),await this.sessionStore.set(s),this.log.debug("subscriber removed from session",{sessionId:t,subscriberId:e}));}query(t){let e=this.sessionStore.getAll();return t.platform&&(e=e.filter(s=>s.channel.platform===t.platform)),t.channelId&&(e=e.filter(s=>s.channel.channelId===t.channelId)),t.userId&&(e=e.filter(s=>s.channel.userId===t.userId)),t.status&&(e=e.filter(s=>s.state.status===t.status)),e}getSessionsByChannel(t){return this.sessionStore.getByChannel(t)}getAllSessions(){return this.sessionStore.getAll()}getSessionCount(){return this.sessionStore.size()}async cleanupIdleSessions(t){let e=Date.now(),s=[];for(let n of this.sessionStore.getAll())n.state.status==="idle"&&e-n.lastActiveAt>t&&s.push(n.id);for(let n of s)await this.closeSession(n);return s.length>0&&this.log.info("cleaned up idle sessions",{count:s.length}),s.length}async save(){this.log.debug("session save triggered");}getStats(){return this.sessionStore.getStats()}};var Z=class{constructor(t={}){a$1(this,"log",a.create({service:"gateway:plugin-loader"}));a$1(this,"plugins",new Map);a$1(this,"messageHandler",null);a$1(this,"healthCheckTimer",null);a$1(this,"config");a$1(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 T(`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 T("Message handler not set",{code:"PLUGIN_ERROR",recoverable:false});if(!e.config.enabled){this.log.warn("plugin is disabled",{id:t});return}this.log.info("starting plugin",{id:t});try{await e.plugin.start(e.config,this.messageHandler),e.started=!0,e.reconnectAttempts=0,this.log.info("plugin started",{id:t});}catch(s){throw this.log.error("failed to start plugin",{id:t,error:String(s)}),this.scheduleReconnect(t),s}}async stop(t){let e=this.plugins.get(t);if(!e){this.log.warn("plugin not found",{id:t});return}if(!e.started){this.log.warn("plugin not started",{id:t});return}this.cancelReconnect(t),this.log.info("stopping plugin",{id:t});try{await e.plugin.stop(),e.started=!1,this.log.info("plugin stopped",{id:t});}catch(s){e.started=false,this.log.error("failed to stop plugin",{id:t,error:String(s)});}}async startAll(){let t=[];for(let[e,s]of this.plugins){if(!s.config.enabled){this.log.debug("skipping disabled plugin",{id:e});continue}try{await this.start(e);}catch(n){t.push({id:e,error:n instanceof Error?n:new Error(String(n))});}}t.length>0&&this.log.warn("some plugins failed to start",{count:t.length,errors:t.map(e=>({id:e.id,error:e.error.message}))});}async stopAll(){this.stopHealthCheckTimer();for(let[t]of this.plugins)await this.stop(t);}getPlugin(t){return this.plugins.get(t)?.plugin}getAllPlugins(){return [...this.plugins.values()].map(t=>t.plugin)}getRunningPlugins(){return [...this.plugins.values()].filter(t=>t.started).map(t=>t.plugin)}isRunning(t){return this.plugins.get(t)?.started??false}async healthCheck(t){let e=this.plugins.get(t);if(!e)return {healthy:false,lastCheck:Date.now(),error:"Plugin not found"};if(!e.started)return {healthy:false,lastCheck:Date.now(),error:"Plugin not running"};try{let s=await Promise.race([e.plugin.healthCheck(),new Promise((n,i)=>setTimeout(()=>i(new Error("Health check timeout")),this.config.healthCheckTimeout))]);return e.lastHealthCheck=s,s}catch(s){let n={healthy:false,lastCheck:Date.now(),error:s instanceof Error?s.message:String(s)};return e.lastHealthCheck=n,n}}async healthCheckAll(){let t=new Map;for(let[e]of this.plugins)t.set(e,await this.healthCheck(e));return t}startHealthCheckTimer(){this.healthCheckTimer||(this.healthCheckTimer=setInterval(async()=>{for(let[t,e]of this.plugins){if(!e.started)continue;let s=await this.healthCheck(t);s.healthy||(this.log.warn("plugin health check failed",{id:t,error:s.error}),this.config.autoReconnect&&(e.started=false,this.scheduleReconnect(t)));}},this.config.healthCheckInterval),this.log.info("health check timer started",{interval:this.config.healthCheckInterval}));}stopHealthCheckTimer(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null,this.log.info("health check timer stopped"));}scheduleReconnect(t){if(!this.config.autoReconnect)return;let e=this.plugins.get(t);if(!e)return;if(e.reconnectAttempts>=this.config.maxReconnectAttempts){this.log.error("max reconnect attempts reached",{id:t,attempts:e.reconnectAttempts});return}let s=this.calculateBackoffDelay(e.reconnectAttempts);e.reconnectAttempts++,this.log.info("scheduling reconnect",{id:t,attempt:e.reconnectAttempts,delay:s}),e.reconnectTimer=setTimeout(async()=>{try{await this.start(t),this.log.info("reconnect successful",{id:t});}catch(n){this.log.warn("reconnect failed",{id:t,error:String(n)}),this.scheduleReconnect(t);}},s),e.reconnectTimer.unref?.();}cancelReconnect(t){let e=this.plugins.get(t);e&&e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0);}calculateBackoffDelay(t){let e=Math.min(this.backoffPolicy.initialMs*this.backoffPolicy.factor**t,this.backoffPolicy.maxMs),s=e*this.backoffPolicy.jitter*(Math.random()*2-1);return Math.floor(e+s)}};var R=class extends Error{constructor(e,s,n){super(e);a$1(this,"code",s);a$1(this,"configuredChannels",n);this.name="ChannelSelectionError";}},k=a.create({service:"gateway:channel-selection"});function B(c){if(!(!c||typeof c!="string"))return c.toLowerCase().trim()}async function $e(c){let{channel:t,sessionId:e,userId:s,defaultChannel:n,fallbackChannels:i,sessionManager:r,pluginLoader:o,contactStore:g}=c,d=B(t);if(d){let m=We(d,o);if(m){if(e){let b=He(e,r);if(b){if(b.channelInfo.chatId||b.channelInfo.userId)return k.debug("enriching explicit channel with session info",{sessionId:e,chatId:b.channelInfo.chatId,userId:b.channelInfo.userId}),{...m,channelInfo:{...m.channelInfo,chatId:b.channelInfo.chatId,userId:b.channelInfo.userId}}}else if(s&&r){k.debug("session not found, creating new session for private chat",{userId:s});let P=s,E={platform:m.channelInfo.platform,channelId:m.channel,chatId:P,userId:s};try{let H=await r.getOrCreate(E);return k.info("auto-created session for private chat",{sessionId:H.id,chatId:P,userId:s}),{channel:m.channel,source:"session-bound",channelInfo:H.channel}}catch(H){k.warn("failed to auto-create session, using explicit channel info",{userId:s,error:String(H)});}}}if(s&&g){let b=await cs(d,s,g,o);if(b)return b}return m}if(e){let b=He(e,r);if(b){if((!b.channelInfo.chatId||!b.channelInfo.userId)&&b.channelInfo.platform!=="api"){let E=gs(b.channelInfo.platform,r);if(E)return k.debug("session missing chatId/userId, using session with complete info",{originalSessionId:e,newSessionId:E.channelInfo.chatId}),E}return b}}throw new R(`Channel \u4E0D\u53EF\u7528\u6216\u672A\u914D\u7F6E: ${d}`,"CHANNEL_UNAVAILABLE",[])}if(e){let m=He(e,r);if(m)return m}if(s&&g){let m=await ls(s,g,o);if(m)return m}let p=ze(o);if(p.length===0)throw new R("\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 y=B(n);if(y){let m=We(y,o);if(m)return k.debug("using default channel",{channel:y}),{...m,source:"default"};k.warn("default channel unavailable",{channel:y});}if(p.length===1){let m=p[0],b=o?.getPlugin(m);return {channel:m,source:"single-configured",channelInfo:{platform:b?.platform,channelId:m}}}let S=(i??[]).map(B).filter(m=>m!==void 0);for(let m of S){let b=We(m,o);if(b)return k.debug("using fallback channel",{channel:m}),{...b,source:"fallback"};k.debug("fallback channel unavailable, trying next",{channel:m});}throw y?new R(`\u914D\u7F6E\u7684\u9ED8\u8BA4 Channel \u4E0D\u53EF\u7528: ${y}`,"CHANNEL_UNAVAILABLE",p):new R(`\u9700\u8981\u660E\u786E\u6307\u5B9A Channel\uFF08\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF09: ${p.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",p)}function We(c,t){if(!t)return null;let e=t.getPlugin(c);if(e&&t.isRunning(c))return {channel:c,source:"explicit",channelInfo:{platform:e.platform,channelId:c}};let s=B(c);if(!s)return null;let n=t.getAllPlugins();for(let i of n)if(t.isRunning(i.id)&&B(i.platform)===s)return {channel:i.id,source:"explicit",channelInfo:{platform:i.platform,channelId:i.id}};return null}function He(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 cs(c,t,e,s){let n=s?.getPlugin(c);if(!n)return null;let i=await e.findByPlatformId(n.platform,t);return i?{channel:c,source:"explicit",channelInfo:{platform:n.platform,channelId:c,userId:i.stableId,chatId:i.stableId}}:null}async function ls(c,t,e){let s=ze(e);if(s.length===0)return null;for(let n of s){let i=e?.getPlugin(n);if(!i)continue;let r=await t.findByPlatformId(i.platform,c);if(r)return {channel:n,source:"single-configured",channelInfo:{platform:i.platform,channelId:n,userId:r.stableId,chatId:r.stableId}}}return null}function ze(c){if(!c)return [];let t=[],e=c.getAllPlugins();for(let s of e)c.isRunning(s.id)&&t.push(s.id);return t}function je(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}}function gs(c,t){if(!t)return null;let e=t.getAll?.()??[];for(let s of e)if(s.channel.platform===c&&s.channel.chatId&&s.channel.userId)return {channel:s.channel.channelId,source:"session-bound",channelInfo:s.channel};for(let s of e)if(s.channel.platform===c&&s.channel.chatId)return {channel:s.channel.channelId,source:"session-bound",channelInfo:s.channel};return null}var u=a.create({service:"gateway:websocket-server"});function hs(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ke(c,t){for(let[e,s]of t.entries())if(s===c)return e;return null}var O=class{constructor(t={}){a$1(this,"config");a$1(this,"server",null);a$1(this,"wss",null);a$1(this,"httpsServer",null);a$1(this,"httpRedirectServer",null);a$1(this,"connections",new Map);a$1(this,"subscriptions",new Map);a$1(this,"sessionSubscriptions",new Map);a$1(this,"sessionLastActivity",new Map);a$1(this,"cleanupInterval",null);a$1(this,"heartbeatInterval",null);a$1(this,"startTime",0);a$1(this,"running",false);a$1(this,"channelResolveParams",null);a$1(this,"pluginLoaderRef",null);this.config={...Fe,...t};}setChannelResolveDeps(t){this.channelResolveParams=t,u.debug("channel resolve deps set",{hasSessionManager:!!t.sessionManager,hasPluginLoader:!!t.pluginLoader,hasContactStore:!!t.contactStore});}setPluginLoader(t){this.pluginLoaderRef=t;}getChannelResolveParams(){return this.channelResolveParams?this.channelResolveParams:{}}async start(){if(this.running){u.warn("WebSocket server is already running");return}u.debug("WebSocket server start: checking configuration",{port:this.config.port,hostname:this.config.hostname,path:this.config.path,https:this.config.https?.enabled??false}),this.startTime=Date.now();let t={onOpen:(n,i)=>{this.handleConnection(i);},onMessage:async(n,i)=>{try{let r=JSON.parse(n.data.toString());await this.handleMessage(i,r);}catch(r){u.error("Error processing WebSocket message",{error:r.message}),this.sendError(i,r.message);}},onClose:(n,i)=>{this.handleDisconnection(i);},onError:(n,i)=>{u.error("WebSocket error",{error:n.type});}},e=this.config.https?.enabled??false;u.debug("WebSocket server start: choosing server type",{https:e});try{e?(u.debug("WebSocket server start: starting HTTPS server"),await this.startHTTPSServer(t)):(u.debug("WebSocket server start: starting HTTP server"),await this.startHTTPServer(t)),u.debug("WebSocket server start: HTTP/HTTPS server started successfully");}catch(n){throw u.error("WebSocket server start: HTTP/HTTPS server failed",{error:n instanceof Error?n.message:String(n)}),n}u.debug("WebSocket server start: server initialization complete"),this.cleanupInterval=setInterval(()=>this.cleanupExpiredSessions(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let s=e?"wss":"ws";u.info("WebSocket server started",{url:`${s}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(t){u.debug("HTTP server start: creating server",{port:this.config.port,hostname:this.config.hostname}),this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true}),u.debug("HTTP server start: server created, checking raw server");let e=this.server.raw;e?(u.debug("HTTP server start: raw server available, setting up WebSocket upgrade"),this.setupWebSocketUpgrade(e,t),u.debug("HTTP server start: WebSocket upgrade configured")):u.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(t){let e=this.config.https,s=this.loadSSLCertificates(e);if(!s){u.error("Failed to load SSL certificates, falling back to HTTP"),await this.startHTTPServer(t);return}this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let n=this.server.raw;this.httpsServer=us.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,t),await new Promise(i=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{u.info("HTTPS server started",{port:this.config.port,hostname:this.config.hostname}),i();});}),e.forceRedirect&&e.httpPort&&this.startHTTPRedirectServer(e.httpPort);}loadSSLCertificates(t){try{return t.cert&&t.key?{cert:t.cert,key:t.key}:t.certPath&&t.keyPath?{cert:D__default.readFileSync(t.certPath),key:D__default.readFileSync(t.keyPath)}:null}catch(e){return u.error("Failed to load SSL certificates",{error:e.message}),null}}setupWebSocketUpgrade(t,e){this.wss=new WebSocketServer({noServer:true}),t.on("upgrade",(s,n,i)=>{try{let o=new URL(s.url||"/",`http://${s.headers.host}`).pathname,g=this.config.path||"";(o===g||g===""&&(o==="/"||o===""))&&this.wss.handleUpgrade(s,n,i,d=>{e.onOpen?.({type:"open"},d),d.on("message",p=>{e.onMessage?.({data:p},d);}),d.on("close",(p,y)=>{e.onClose?.({code:p,reason:y},d);}),d.on("error",p=>{e.onError?.({type:"error",message:p.message},d);});});}catch{}});}startHTTPRedirectServer(t){this.httpRedirectServer=ps.createServer((e,s)=>{let i=`https://${e.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${e.url}`;u.debug("Redirecting HTTP to HTTPS",{from:e.url,to:i}),s.writeHead(301,{Location:i,"Content-Type":"text/plain"}),s.end(`Redirecting to ${i}`);}),this.httpRedirectServer.listen(t,this.config.hostname,()=>{u.info("HTTP redirect server started",{port:t,hostname:this.config.hostname});});}async stop(){if(!this.running){u.warn("WebSocket server is not running");return}u.info("Stopping WebSocket server"),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let[t,e]of this.connections.entries())try{e.close(1e3,"Server shutting down");}catch(s){u.debug("Error closing connection",{clientId:t,error:String(s)});}this.connections.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.sessionLastActivity.clear(),this.wss&&(this.wss.close(),this.wss=null),this.httpsServer&&(await new Promise(t=>{this.httpsServer.close(()=>t());}),this.httpsServer=null),this.httpRedirectServer&&(await new Promise(t=>{this.httpRedirectServer.close(()=>t());}),this.httpRedirectServer=null),this.server&&(await this.server.stop(),this.server=null),this.running=false,u.info("WebSocket server stopped");}broadcastToSession(t,e){this.touchSession(t);let s=this.sessionSubscriptions.get(t);if(!s||s.size===0){u.debug("No clients subscribed to session",{sessionId:t});return}let n=e?.properties?.sessionID;if(typeof n=="string"&&n&&n!==t)return;let i=JSON.stringify({type:"event",sessionId:t,payload:e});for(let r of s){let o=this.subscriptions.get(r);if(o&&o.ws.readyState===o.ws.OPEN&&o.subscribedSessions.has(t)){if(o.subscribedEventTypes.size>0&&!o.subscribedEventTypes.has(e.type)){u.debug("Event type not subscribed, skipping",{clientId:r,sessionId:t,eventType:e.type,subscribedTypes:Array.from(o.subscribedEventTypes)});continue}o.ws.send(i),u.debug("Event pushed to client",{clientId:r,sessionId:t,eventType:e.type});}}}getConnectionCount(){return this.connections.size}getSubscriptionCount(){return this.sessionSubscriptions.size}getConnectionInfos(){let t=[];for(let[e,s]of this.subscriptions.entries())t.push({clientId:e,state:s.ws.readyState===s.ws.OPEN?"connected":"disconnected",connectedAt:s.connectedAt,lastActivityAt:s.lastActivityAt,authInfo:s.authInfo});return t}isRunning(){return this.running}handleConnection(t){if(this.connections.size>=(this.config.maxConnections??K.maxConnections)){u.warn("Maximum connections reached, rejecting new connection"),t.close(1013,"Maximum connections reached");return}let e=hs();this.connections.set(e,t),this.subscriptions.set(e,{clientId:e,ws:t,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()}),u.info("WebSocket client connected",{clientId:e,totalConnections:this.connections.size}),this.sendMessage(t,{type:"connected",clientId:e,payload:{version:"1.0.0",capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}handleDisconnection(t){let e=ke(t,this.connections);if(!e)return;this.connections.delete(e);let s=this.subscriptions.get(e);if(s){for(let n of s.subscribedSessions){let i=this.sessionSubscriptions.get(n);i&&(i.delete(e),i.size===0&&this.sessionSubscriptions.delete(n));}this.subscriptions.delete(e);}u.info("WebSocket client disconnected",{clientId:e,totalConnections:this.connections.size});}async handleMessage(t,e){let s=ke(t,this.connections);if(!s){this.sendError(t,"Client not found");return}let n=this.subscriptions.get(s);switch(n&&(n.lastActivityAt=Date.now()),e.type){case "ping":this.sendMessage(t,{type:"pong"});break;case "initialize":await this.handleInitialize(t,e);break;case "subscribe":await this.handleSubscribe(t,e);break;case "unsubscribe":await this.handleUnsubscribe(t,e);break;case "message":await this.handleMessageRequest(t,e);break;case "interrupt":await this.handleInterrupt(t,e);break;case "releaseSubscription":await this.handleReleaseSubscription(t,e);break;default:this.sendError(t,`Unknown message type: ${e.type}`);}}async handleInitialize(t,e){this.sendMessage(t,{type:"initialize_response",success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}async handleSubscribe(t,e){if(e.type!=="subscribe"||!e.sessionId){this.sendError(t,"Invalid subscribe request");return}let s=ke(t,this.connections);if(!s){this.sendError(t,"Client not found");return}let n=this.subscriptions.get(s);if(!n){this.sendError(t,"Subscription not found");return}n.subscribedSessions.add(e.sessionId),this.sessionSubscriptions.has(e.sessionId)||this.sessionSubscriptions.set(e.sessionId,new Set),this.sessionSubscriptions.get(e.sessionId).add(s);let i=e;if(i.backendSessionId){let r=this.getChannelResolveParams();if(r.sessionManager)try{await r.sessionManager.bindBackendSession(i.sessionId,i.backendSessionId),u.info("backend session bound on subscribe",{gatewaySessionId:i.sessionId,backendSessionId:i.backendSessionId});}catch(o){u.warn("failed to bind backend session on subscribe",{sessionId:i.sessionId,backendSessionId:i.backendSessionId,error:String(o)});}}if(this.touchSession(e.sessionId),e.payload?.eventTypes)for(let r of e.payload.eventTypes)n.subscribedEventTypes.add(r);u.info("Client subscribed to session",{clientId:s,sessionId:e.sessionId,backendSessionId:i.backendSessionId}),this.sendMessage(t,{type:"subscribed",sessionId:e.sessionId});}async handleUnsubscribe(t,e){if(e.type!=="unsubscribe"||!e.sessionId){this.sendError(t,"Invalid unsubscribe request");return}let s=ke(t,this.connections);if(!s)return;let n=this.subscriptions.get(s);if(!n)return;n.subscribedSessions.delete(e.sessionId);let i=this.sessionSubscriptions.get(e.sessionId);i&&(i.delete(s),i.size===0&&this.sessionSubscriptions.delete(e.sessionId)),u.info("Client unsubscribed from session",{clientId:s,sessionId:e.sessionId}),this.sendMessage(t,{type:"unsubscribed",sessionId:e.sessionId});}async handleMessageRequest(t,e){if(e.type!=="message"||!e.sessionId||!e.payload){this.sendError(t,"Invalid message request");return}u.debug("Message received",{sessionId:e.sessionId}),this.sendMessage(t,{type:"response",sessionId:e.sessionId,success:true,result:{received:true}});}async handleInterrupt(t,e){if(e.type!=="interrupt"||!e.sessionId){this.sendError(t,"Invalid interrupt request");return}u.info("Interrupt requested via WebSocket",{sessionId:e.sessionId}),this.sendMessage(t,{type:"interrupted",sessionId:e.sessionId,success:true});}async handleReleaseSubscription(t,e){if(e.type!=="releaseSubscription"||!e.sessionId){this.sendError(t,"Invalid releaseSubscription request");return}u.info("Release subscription requested via WebSocket",{sessionId:e.sessionId}),this.releaseSessionResources(e.sessionId),this.sendMessage(t,{type:"subscriptionReleased",sessionId:e.sessionId});}touchSession(t){this.sessionLastActivity.set(t,Date.now());}checkConnectionTimeout(){let t=Date.now(),e=this.config.connectionTimeout??K.connectionTimeout,s=[];for(let[n,i]of this.subscriptions.entries())t-i.lastActivityAt>e&&s.push(n);for(let n of s){let i=this.subscriptions.get(n);if(i){u.info("Closing inactive connection",{clientId:n,lastActivityAt:i.lastActivityAt,timeoutMs:e});try{i.ws.close(1001,"Connection timeout");}catch(r){u.debug("Error closing timed out connection",{clientId:n,error:String(r)});}}}s.length>0&&u.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size-s.length});}cleanupExpiredSessions(){let t=Date.now(),e=[],s=this.config.sessionExpireMs??K.sessionExpireMs;for(let[n,i]of this.sessionLastActivity.entries())t-i>s&&e.push(n);for(let n of e)u.info("Session expired due to inactivity, releasing resources",{sessionId:n,lastActivity:this.sessionLastActivity.get(n),expireMs:s}),this.releaseSessionResources(n),this.sessionLastActivity.delete(n);e.length>0&&u.debug("Cleaned up expired sessions",{count:e.length,remainingActive:this.sessionLastActivity.size});}releaseSessionResources(t){let e=this.sessionSubscriptions.get(t);if(e){for(let s of e){let n=this.subscriptions.get(s);n&&n.ws.readyState===n.ws.OPEN&&this.sendMessage(n.ws,{type:"session_closed",sessionId:t,payload:{reason:"Session resources released due to expiration or explicit release"}});}for(let s of e){let n=this.subscriptions.get(s);n&&n.subscribedSessions.delete(t);}this.sessionSubscriptions.delete(t),u.info("Session resources released",{sessionId:t,clientCount:e.size});}}sendMessage(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e));}sendError(t,e,s){this.sendMessage(t,{type:"error",message:e,code:s});}createRoutes(){return [{method:"get",path:"/health",handler:t=>{let e={status:"healthy",timestamp:Date.now(),version:"1.0.0"};return t.json(e)}},{method:"get",path:"/status",handler:t=>{let e={status:this.running?"running":"stopped",connections:this.connections.size,sessions:this.sessionSubscriptions.size,subscriptions:this.subscriptions.size,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0"};return t.json(e)}},{method:"get",path:"/channels",handler:async t=>{let e=this.channelResolveParams?.pluginLoader;if(!e)return t.json({error:"Plugin loader not available"},503);let n=e.getAllPlugins().map(i=>({id:i.id,platform:i.platform,name:i.name,version:i.version}));return t.json({channels:n,total:n.length})}},{method:"get",path:"/contacts",handler:async t=>{let e=t.req.query("platform"),s=parseInt(t.req.query("limit")||"100",10),n=parseInt(t.req.query("offset")||"0",10),i=this.channelResolveParams?.contactStore;if(!i)return t.json({error:"Contact store not available"},503);try{if(e){let r=await i.listByPlatform(e,s,n);return t.json({contacts:r.contacts.map(o=>({uid:o.uid,platform:o.platform,stableId:o.stableId,profile:o.profile,lastSeenAt:o.lastSeenAt,createdAt:o.createdAt})),total:r.total,hasMore:r.hasMore})}else {let r=await i.count();return t.json({total:r,message:"Specify platform query parameter to list contacts"})}}catch(r){return u.error("failed to list contacts",{error:String(r)}),t.json({error:String(r)},500)}}},{method:"get",path:"/contacts/:uid",handler:async t=>{let e=t.req.param("uid"),s=this.channelResolveParams?.contactStore;if(!s)return t.json({error:"Contact store not available"},503);try{let n=await s.findByUid(e);return n?t.json({uid:n.uid,platform:n.platform,stableId:n.stableId,profile:n.profile,aliases:n.aliases,lastSeenAt:n.lastSeenAt,createdAt:n.createdAt}):t.json({error:"Contact not found"},404)}catch(n){return u.error("failed to get contact",{uid:e,error:String(n)}),t.json({error:String(n)},500)}}},{method:"get",path:"/sessions",handler:async t=>{let e=parseInt(t.req.query("limit")||"100",10),s=parseInt(t.req.query("offset")||"0",10),n=t.req.query("platform"),i=t.req.query("channelId"),r=t.req.query("userId"),o=t.req.query("chatId"),g=[],p=this.getChannelResolveParams().sessionManager?.getAll?.()??[];for(let S of p){let m=!n||S.channel.platform===n,b=!i||S.channel.channelId===i,P=!r||S.channel.userId===r,E=!o||S.channel.chatId===o;m&&b&&(!r&&!o||P&&E)&&g.push({id:S.id,platform:S.channel.platform,channelId:S.channel.channelId,userId:S.channel.userId,chatId:S.channel.chatId,chatType:S.channel.chatType,chatTitle:S.channel.chatTitle,state:S.state.status,createdAt:S.createdAt,lastActiveAt:S.lastActiveAt});}let y=g.slice(s,s+e);return t.json({sessions:y,total:g.length,hasMore:s+e<g.length})}},{method:"get",path:"/sessions/:sessionId",handler:async t=>{let e=t.req.param("sessionId"),s=this.sessionSubscriptions.get(e);return s?t.json({id:e,state:"active",subscriberCount:s.size,lastActiveAt:this.sessionLastActivity.get(e)||Date.now()}):t.json({error:"Session not found"},404)}},{method:"post",path:"/initialize",handler:async t=>{let e=await t.req.json().catch(()=>({}));return u.debug("ACP initialize request received",{body:e}),t.json({success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"],version:"1.0.0"}})}},{method:"post",path:"/session",handler:async t=>{let e=await t.req.json().catch(()=>({}));if(!this.channelResolveParams?.sessionManager)return t.json({error:"Session manager not available"},500);let s=e.channel?.platform,n=e.channel?.channelId;if(!s||!n)return t.json({error:"platform and channelId are required"},400);let i={platform:s,channelId:n,userId:e.channel?.userId,chatId:e.channel?.chatId},r=await this.channelResolveParams.sessionManager.getOrCreate(i),o={id:r.id,createdAt:r.createdAt};return t.json(o)}},{method:"post",path:"/session/:sessionId/prompt",handler:async t=>{let e=t.req.param("sessionId"),s=await t.req.json().catch(()=>({}));if(!e)return t.json({error:"No sessionId provided"},400);try{let n=this.getChannelResolveParams(),i=await $e({...n,sessionId:e,channel:s.channel,userId:s.userId??s.chatId});u.debug("channel resolved for message",{sessionId:e,channel:i.channel,source:i.source,channelInfo:i.channelInfo});let r=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,o={...i.channelInfo};if(!o.chatId){let p=s.chatId??i.channelInfo.userId;p&&(o.chatId=p,u.debug("filled channelInfo.chatId from request body or session",{chatId:o.chatId}));}if(!o.userId&&o.chatId&&(o.userId=s.userId??o.chatId,u.debug("filled channelInfo.userId from chatId",{userId:o.userId})),!o.chatId)return u.error("channelInfo missing chatId, cannot send message",{sessionId:e,channelInfo:o,body:{userId:s.userId,chatId:s.chatId}}),t.json({error:"channelInfo missing chatId"},400);let g={id:r,sessionId:e,type:"output",content:typeof s.content=="string"?[{type:"text",text:s.content}]:s.content||[],metadata:{channel:o,replyToMessageId:s.replyToMessageId,processorId:s.processorId??"gateway",agent:s.agent??"gateway"},timestamp:Date.now()};if(this.pluginLoaderRef)try{await this.pluginLoaderRef(i.channel,g,{}),u.debug("message sent via pluginLoader",{messageId:r,channel:i.channel});}catch(p){return u.error("failed to send message",{sessionId:e,error:String(p)}),t.json({error:String(p)},500)}else return u.error("no pluginLoader available for sending message",{sessionId:e}),t.json({error:"Plugin loader not available"},500);let d={messageId:r,sessionId:e,createdAt:Date.now(),metadata:{channel:i.channel,channelSource:i.source,channelInfo:i.channelInfo}};return t.status(202),t.json(d)}catch(n){return n instanceof R?(u.warn("channel selection failed",{sessionId:e,error:n.message}),t.json({error:je(n),code:n.code},400)):(u.error("send message error",{sessionId:e,error:String(n)}),t.json({error:String(n)},500))}}},{method:"get",path:"/subscriptions",handler:t=>{let e=Array.from(this.sessionSubscriptions.entries()).map(([n,i])=>({sessionId:n,subscriberCount:i.size,subscribers:Array.from(i)})),s={subscriptions:e,total:e.length};return t.json(s)}}]}};var v=class{constructor(){a$1(this,"version","1.0.0");a$1(this,"log");a$1(this,"config",null);a$1(this,"messageHandler",null);a$1(this,"_status","stopped");a$1(this,"lastActivity",0);a$1(this,"startPromise",null);a$1(this,"stopPromise",null);}initLog(){this.log=a.create({service:`channel:${this.platform}`});}async start(t,e){if(this.startPromise)return this.log.warn("plugin start already in progress"),this.startPromise;if(this._status==="running"){this.log.warn("plugin is already running");return}this.startPromise=this.doStartInternal(t,e);try{await this.startPromise;}finally{this.startPromise=null;}}async doStartInternal(t,e){this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=t,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(s){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(s)}),s}}async stop(){if(this.stopPromise)return this.log.warn("plugin stop already in progress"),this.stopPromise;if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}this.stopPromise=this.doStopInternal();try{await this.stopPromise;}finally{this.stopPromise=null;}}async doStopInternal(){this.log.info("stopping channel plugin",{id:this.id}),this._status="stopping";try{await this.doStop(),this._status="stopped",this.log.info("channel plugin stopped",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(t)}),t}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(t){return {healthy:false,lastCheck:Date.now(),error:t instanceof Error?t.message:String(t)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}getCapabilities(){return {supportsText:true,supportsMedia:false,supportsReply:false,supportsThread:false,supportsEdit:false,supportsDelete:false,supportsTyping:false,supportsBatchSend:false,supportsMarkdown:false,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,maxMessageLength:4096,maxMediaCount:1}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}extractText(t){return t.content.filter(e=>e.type==="text").map(e=>e.text??"").join(`
3
+ `)}buildSessionId(t,e,s){let n=[this.platform,t,e];return s&&n.push(s),n.join("_")}async handleMessage(t){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:t.id});return}this.updateActivity(),await this.messageHandler.onMessage(t);}async handleEvent(t,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:t});return}await this.messageHandler.onEvent({type:t,channelId:this.id,data:e,timestamp:Date.now()});}};var ee=class extends v{constructor(e="telegram-main"){super();a$1(this,"id");a$1(this,"platform","telegram");a$1(this,"name","Telegram Bot");a$1(this,"botConfig",null);a$1(this,"baseUrl","");a$1(this,"abortController",null);a$1(this,"lastUpdateId",0);a$1(this,"typingTimers",new Map);a$1(this,"sentMessages",new Map);a$1(this,"sessionIdMap",new Map);a$1(this,"commandRouter",new Map);a$1(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});this.id=e,this.initLog();}async doStart(){if(!this.config)throw G(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw G(this.id,"CONFIG_MISSING_REQUIRED","Bot token is required");if(this.baseUrl=`https://api.telegram.org/bot${this.botConfig.botToken}`,this.botConfig.retry&&(this.retryState={attempts:0,maxAttempts:this.botConfig.retry.maxAttempts??3,initialDelay:this.botConfig.retry.initialDelay??1e3,maxDelay:this.botConfig.retry.maxDelay??3e4}),this.botConfig.commands)for(let s of this.botConfig.commands)this.commandRouter.set(`/${s.command}`,s);let e=await this.getMe();this.log.info("Telegram bot connected",{id:e.id,username:e.username,first_name:e.first_name}),this.botConfig.polling?.enabled===true&&this.startPolling();}async doStop(){this.abortController?.abort(),this.abortController=null,this.clearAllTyping(),this.commandRouter.clear(),this.botConfig=null,this.log.info("Telegram plugin stopped");}async send(e){let s=e.metadata.channel.chatId;if(!s)throw G(this.id,"MESSAGE_SEND_FAILED","Chat ID is required");let n=this.extractText(e),i=e.metadata.context?.replyTo,r=this.detectParseMode(e),o=e.content.find(p=>p.type==="image"),g=e.content.find(p=>p.type==="file"),d;if(o){let p=o.image,y=n||void 0;d=await this.sendPhoto(s,p,y);}else if(g){let p=g.data,y=n||void 0;d=await this.sendDocument(s,p,y);}else try{d=await this.sendApiMessage(s,n,{parseMode:r,replyTo:i?parseInt(i,10):void 0});}catch(p){if(r!=="None"&&this.isParseError(p))this.log.debug("parse error, retrying with plain text",{parseMode:r,error:String(p)}),d=await this.sendApiMessage(s,n,{parseMode:"None",replyTo:i?parseInt(i,10):void 0});else throw p}return this.sentMessages.set(e.id,{chatId:s,messageId:parseInt(d,10),timestamp:Date.now()}),this.sessionIdMap.set(e.id,e.sessionId),d}async sendPhoto(e,s,n){this.log.debug("sendPhoto called",{chatId:e,image:s,imageType:typeof s,caption:n});let i=new URLSearchParams({chat_id:e});n&&i.set("caption",n);let r="photo.jpg",o;if(typeof s=="string")if(s.startsWith("file://"))o=await PKG.file(fileURLToPath(s)).bytes(),r=s.split("/").pop()||r;else {let d=await Fetch.post(`${this.baseUrl}/sendPhoto`,{chat_id:e,photo:s,caption:n});if(!d.data.ok)throw new Error(`sendPhoto failed: ${d.data.description||"unknown error"}`);return d.data.result.message_id.toString()}else if(s instanceof URL){let d=await Fetch.post(`${this.baseUrl}/sendPhoto`,{chat_id:e,photo:s.toString(),caption:n});if(!d.data.ok)throw new Error(`sendPhoto failed: ${d.data.description||"unknown error"}`);return d.data.result.message_id.toString()}else o=s;this.log.debug("sendPhoto: calling Fetch.postForm",{url:`${this.baseUrl}/sendPhoto?${i}`,filename:r});let g=await Fetch.postForm(`${this.baseUrl}/sendPhoto?${i}`,[{name:"photo",value:o,filename:r}]);if(this.log.debug("sendPhoto: response received",{ok:g.ok,status:g.status,data:g.data}),!g.ok)throw new Error(`sendPhoto failed: ${g.data.description||"unknown error"}`);return g.data.result.message_id.toString()}async sendDocument(e,s,n){this.log.debug("sendDocument called",{chatId:e,file:s,fileType:typeof s,caption:n});let i=new URLSearchParams({chat_id:e});n&&i.set("caption",n);let r="document",o;if(typeof s=="string")if(s.startsWith("file://"))o=await PKG.file(fileURLToPath(s)).bytes(),r=s.split("/").pop()||r;else {let d=await Fetch.post(`${this.baseUrl}/sendDocument`,{chat_id:e,document:s,caption:n});if(!d.data.ok)throw new Error(`sendDocument failed: ${d.data.description||"unknown error"}`);return d.data.result.message_id.toString()}else if(s instanceof URL){let d=await Fetch.post(`${this.baseUrl}/sendDocument`,{chat_id:e,document:s.toString(),caption:n});if(!d.data.ok)throw new Error(`sendDocument failed: ${d.data.description||"unknown error"}`);return d.data.result.message_id.toString()}else o=s;this.log.debug("sendDocument: calling Fetch.postForm",{url:`${this.baseUrl}/sendDocument?${i}`,filename:r});let g=await Fetch.postForm(`${this.baseUrl}/sendDocument?${i}`,[{name:"document",value:o,filename:r}]);if(this.log.debug("sendDocument: response received",{ok:g.ok,status:g.status,data:g.data}),!g.ok)throw new Error(`sendDocument failed: ${g.data.description||"unknown error"}`);return g.data.result.message_id.toString()}isParseError(e){let s=String(e);return s.includes("can't parse entities")||s.includes("parse")}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:false,supportsEdit:true,supportsDelete:true,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:true,supportsHtml:true,supportsDeliveryReceipt:true,supportsReadReceipt:true,maxMessageLength:4096,maxMediaCount:10}}async sendTyping(e){await this.sendChatAction(e,"typing");}async sendChatAction(e,s){await this.request("sendChatAction",{chat_id:e,action:s}),this.scheduleTypingStop(e,5e3);}scheduleTypingStop(e,s){let n=this.typingTimers.get(e);n&&clearTimeout(n);let i=setTimeout(()=>{this.typingTimers.delete(e);},s);this.typingTimers.set(e,i);}clearAllTyping(){for(let e of this.typingTimers.values())clearTimeout(e);this.typingTimers.clear();}detectParseMode(e){let s=this.extractText(e);return s.includes("<")&&s.includes("</")?"HTML":s.includes("*")||s.includes("_")||s.includes("`")?"Markdown":"None"}startPolling(){this.abortController=new AbortController,this.pollLoop(),this.log.info("Polling started");}pollLoop(){(async()=>{try{await this.poll(),this.abortController?.signal.aborted||this.pollLoop();}catch(s){this.handlePollingError(s);}})();}async poll(){let e=this.botConfig?.polling?.timeout??0,s=await this.getUpdates(this.lastUpdateId+1,100,e);for(let n of s)if(this.lastUpdateId=Math.max(this.lastUpdateId,n.update_id),n.message&&await this.handleTelegramMessage(n.message),n.edited_message&&await this.handleTelegramMessage(n.edited_message),n.message_reaction&&await this.handleMessageReaction(n.message_reaction),n.message_reaction_count&&n.message_reaction_count.length>0)for(let i of n.message_reaction_count)await this.handleMessageReactionCount(i);this.retryState.attempts=0;}async handleMessageReaction(e){let s=this.findSentMessageEntry(e.message_id);if(!s)return;let n=s.gatewayMessageId,i=this.sessionIdMap.get(n),o=e.new_reaction.some(g=>g.type==="emoji"&&(g.emoji==="\u{1F441}"||g.emoji==="\u2705"))?"message_read":"message_delivered";this.log.info("message reaction received",{messageId:n,telegramMessageId:e.message_id,sessionId:i,eventType:o,reactions:e.new_reaction}),this.messageHandler&&await this.messageHandler.onEvent({type:o,channelId:this.id,data:{id:n,sessionId:i,platform:"telegram",channelId:this.id,reactions:e.new_reaction,telegramMessageId:e.message_id,timestamp:e.date*1e3},timestamp:Date.now()});}async handleMessageReactionCount(e){let s=this.findSentMessageEntry(e.message_id);if(!s)return;let n=s.gatewayMessageId,i=this.sessionIdMap.get(n),r=this.sentMessages.get(n);r&&Date.now()-r.timestamp>3e4&&(this.log.info("message reaction count received (delivery confirmation)",{messageId:n,telegramMessageId:e.message_id,sessionId:i,reactions:e.reactions}),this.messageHandler&&await this.messageHandler.onEvent({type:"message_delivered",channelId:this.id,data:{id:n,sessionId:i,platform:"telegram",channelId:this.id,reactions:e.reactions,telegramMessageId:e.message_id,timestamp:e.date*1e3},timestamp:Date.now()}));}findSentMessageEntry(e){for(let[s,n]of this.sentMessages.entries())if(n.messageId===e)return {gatewayMessageId:s,...n}}handlePollingError(e){if(!this.abortController?.signal.aborted)if(this.log.error("Polling error",{error:String(e)}),this.retryState.attempts<this.retryState.maxAttempts){let s=Math.min(this.retryState.initialDelay*2**this.retryState.attempts,this.retryState.maxDelay);this.retryState.attempts++,this.log.info("Retrying polling",{attempt:this.retryState.attempts,delay:s}),this.sleep(s).then(()=>this.pollLoop());}else this.log.error("Polling failed after max attempts",{attempts:this.retryState.maxAttempts});}sleep(e){return new Promise(s=>setTimeout(s,e))}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot||e.text?.startsWith("/")&&await this.handleCommand(e))return;await this.sendTyping(e.chat.id.toString());let s=await this.toGatewayMessage(e);await this.handleMessage(s);}async handleCommand(e){let s=(e.text??"").split(" "),n=s[0]?.toLowerCase()??"",i=s.slice(1),r=this.commandRouter.get(n);if(!r)return false;let o={chatId:e.chat.id.toString(),userId:e.from?.id.toString(),args:i,messageId:e.message_id,reply:async(g,d)=>this.sendApiMessage(e.chat.id.toString(),g,d)};try{return await r.handler(o),!0}catch(g){return this.log.error("Command handler error",{command:n,error:String(g)}),true}}async toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return w(s,"input",await 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()}})}async parseFileContent(e){let s=await this.request("getFile",{file_id:e});if(!s.result?.file_path)throw new Error("No file path returned");let n=`https://api.telegram.org/file/bot${this.botConfig?.botToken}/${s.result.file_path}`,i=await Fetch.get(n,{responseType:"text"});if(!i.ok)throw new Error(`Failed to download file: ${i.status}`);return i.data}async downloadBinaryFile(e,s){let n=await this.request("getFile",{file_id:e});if(!n.result?.file_path)throw new Error("No file path returned");let i=`https://api.telegram.org/file/bot${this.botConfig?.botToken}/${n.result.file_path}`,r=await Fetch.get(i,{responseType:"arrayBuffer"});if(!r.ok)throw new Error(`Failed to download file: ${r.status}`);return await PKG.file(s).write(r.data),s}async parseContent(e){let s=[],n=e.text??e.caption??"",r=`${N()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot"}/gateway/downloads`;if(e.photo&&e.photo.length>0){let o=e.photo[e.photo.length-1];if(o)try{let g=`photo_${o.file_unique_id}.jpg`,d=`${r}/${e.chat.id}_${o.file_unique_id}_${g}`;await this.downloadBinaryFile(o.file_id,d),s.push({type:"image",image:`file://${d}`,mime:"image/jpeg"});}catch(g){this.log.warn("failed to download photo, storing as file",{platform:"telegram",fileId:o.file_id,error:String(g)}),s.push({type:"image",image:o.file_id,mime:"image/jpeg"});}}if(e.document){let o=e.document.mime_type||"application/octet-stream",g=e.document.file_name||"file",d=e.document.file_id;if(o.startsWith("text/"))try{let p=await this.parseFileContent(d),y=TruncateContent.truncate(p,{maxChars:5e3,label:`file: ${g}`});s.push({type:"text",text:`\u{1F4CE} File: ${g}
4
+
5
+ ${y.content}`});}catch(p){this.log.warn("failed to download text file, storing as file",{platform:"telegram",fileId:d,error:String(p)}),s.push({type:"file",data:d,mime:o});}else try{let p=g.includes(".")?g.split(".").pop():Filesystem.mimeTypeToExt(o)||"bin",y=`${e.document.file_unique_id||d}.${p}`,S=`${r}/${e.chat.id}_${d}_${y}`;await this.downloadBinaryFile(d,S),s.push({type:"file",data:`file://${S}`,mime:o});}catch(p){this.log.warn("failed to download file, storing as file",{platform:"telegram",fileId:d,error:String(p)}),s.push({type:"file",data:d,mime:o});}}return n&&s.push({type:"text",text:n}),s}buildSessionId(e,s,n){return `telegram_${e}_${s}_${n??s}`}processMessageAndGetSessionId(e){let s=e.chat.id.toString(),n=e.from?.id.toString();return this.buildSessionId(this.id,s,n)}async getMe(){return (await this.request("getMe")).result}async getUpdates(e,s,n){let i={offset:e,limit:s};n>0&&(i.timeout=n);let r=["message","edited_message","channel_post","edited_channel_post","callback_query","message_reaction","message_reaction_count"];return i.allowed_updates=JSON.stringify(r),(await this.request("getUpdates",i)).result||[]}async sendApiMessage(e,s,n){let i={chat_id:e,text:s};return n?.parseMode&&n.parseMode!=="None"&&(i.parse_mode=n.parseMode),n?.replyTo&&(i.reply_to_message_id=n.replyTo),n?.replyMarkup&&(i.reply_markup=n.replyMarkup),(await this.request("sendMessage",i)).result.message_id.toString()}async request(e,s={}){let n=`${this.baseUrl}/${e}`,i;for(let r=0;r<=this.retryState.maxAttempts;r++)try{let o=await Fetch.post(n,s,{timeout:this.retryState.maxDelay,retries:0,headers:{"Content-Type":"application/json"},signal:this.abortController?.signal}),g=o.data;if(!g.ok){if(g.error_code===429){this.log.warn("Rate limited, retrying after",{retryAfter:o.headers.get("Retry-After")});let d=parseInt(o.headers.get("Retry-After")??"1",10)*1e3;await this.sleep(d);continue}throw G(this.id,"CHANNEL_CONNECTION_FAILED",`Telegram API error: ${g.description}`,g.error_code!==400&&g.error_code!==401)}return g}catch(o){if(o instanceof T||this.abortController?.signal.aborted)throw o;if(i=o instanceof Error?o:new Error(String(o)),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 G(this.id,"CHANNEL_CONNECTION_FAILED",`Failed after ${this.retryState.maxAttempts+1} attempts: ${i?.message}`,true)}};var te=class extends v{constructor(e="discord-main"){super();a$1(this,"id");a$1(this,"platform","discord");a$1(this,"name","Discord Bot");a$1(this,"botConfig",null);a$1(this,"baseUrl","https://discord.com/api/v10");a$1(this,"gatewayWs",null);a$1(this,"heartbeatInterval",null);a$1(this,"sessionId",null);a$1(this,"sequenceNumber",null);a$1(this,"abortController",null);a$1(this,"reconnectAttempts",0);a$1(this,"maxReconnectAttempts",5);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");let e=await this.getCurrentUser();this.log.info("Discord bot connected",{id:e.id,username:e.username}),this.botConfig.gateway?.enabled!==false&&await this.startGateway();}async doStop(){this.abortController?.abort(),this.abortController=null,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.gatewayWs&&(this.gatewayWs.close(),this.gatewayWs=null),this.botConfig=null,this.reconnectAttempts=0,this.log.info("Discord plugin stopped");}async send(e){let s=e.metadata.channel.chatId;if(!s)throw new Error("Channel ID is required");let n=this.extractText(e);return (await this.createMessage(s,n,e.metadata.context?.replyTo)).id}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:true,supportsEdit:true,supportsDelete:true,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:true,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,maxMessageLength:2e3,maxMediaCount:10}}async startGateway(){if(this.abortController?.signal.aborted)return;let s=`${(await this.getGatewayBot()).url}/?v=10&encoding=json`;this.gatewayWs=new WebSocket(s),this.gatewayWs.onmessage=n=>{this.handleGatewayMessage(JSON.parse(n.data.toString()));},this.gatewayWs.onclose=()=>{if(!this.abortController?.signal.aborted)if(this.log.info("Gateway disconnected"),this.reconnectAttempts<this.maxReconnectAttempts){let n=Math.min(1e3*2**this.reconnectAttempts,3e4);this.reconnectAttempts++,this.log.info("Attempting to reconnect",{attempt:this.reconnectAttempts,delay:n}),setTimeout(()=>this.startGateway(),n);}else this.log.error("Max reconnect attempts reached");},this.gatewayWs.onerror=n=>{this.log.error("Gateway error",{error:String(n)});};}handleGatewayMessage(e){switch(this.updateActivity(),e.op){case 10:this.handleHello(e.d);break;case 11:this.log.debug("Heartbeat ACK");break;case 0:e.s&&(this.sequenceNumber=e.s),this.handleDispatch(e.t,e.d);break;case 9:this.log.warn("Invalid session, reconnecting"),this.gatewayWs?.close();break}return Promise.resolve()}handleHello(e){this.heartbeatInterval=setInterval(()=>{this.gatewayWs?.send(JSON.stringify({op:1,d:this.sequenceNumber}));},e.heartbeat_interval),this.gatewayWs?.send(JSON.stringify({op:2,d:{token:this.botConfig?.botToken,intents:this.botConfig?.gateway?.intents??513,properties:{os:"linux",browser:"easbot",device:"easbot"}}}));}handleDispatch(e,s){e==="MESSAGE_CREATE"&&this.handleDiscordMessage(s);}async handleDiscordMessage(e){if(e.author.bot)return;let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return w(s,"input",this.parseContent(e),{channel:{platform:"discord",channelId:this.id,userId:e.author.id,chatId:e.channel_id,messageId:e.id,guildId:e.guild_id,username:e.author.username,discriminator:e.author.discriminator},context:{threadId:e.message_reference?.message_id,conversationId:e.channel_id}})}parseContent(e){let s=[];e.content&&s.push({type:"text",text:e.content});for(let n of e.attachments)n.content_type?.startsWith("image/")?s.push({type:"image",image:n.url,mime:n.content_type}):s.push({type:"file",data:n.url,mime:n.content_type});return s}buildSessionId(e,s,n){return n?`discord_${e}_${s}_${n}`:`discord_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.channel_id,n=e.author.id;return this.buildSessionId(this.id,s,n)}async getCurrentUser(){return this.request("GET","/users/@me")}async getGatewayBot(){return this.request("GET","/gateway/bot")}async createMessage(e,s,n){let i={content:s};return n&&(i.message_reference={message_id:n}),this.request("POST",`/channels/${e}/messages`,i)}async request(e,s,n){let i=`${this.baseUrl}${s}`,r;if(e==="GET"?r=await Fetch.get(i,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}):e==="POST"?r=await Fetch.post(i,n,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}):e==="DELETE"?r=await Fetch.del(i,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}):r=await Fetch.request(i,{method:e,body:n,headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}),!r.ok)throw new Error(`Discord API error: ${r.data}`);return r.data}};var se=class extends v{constructor(e="slack-main"){super();a$1(this,"id");a$1(this,"platform","slack");a$1(this,"name","Slack Bot");a$1(this,"botConfig",null);a$1(this,"baseUrl","");a$1(this,"socketModeClient",null);a$1(this,"abortController",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");this.abortController=new AbortController,this.baseUrl="https://slack.com/api";let e=await this.authTest();this.log.info("Slack bot connected",{user:e.user,team:e.team,bot_id:e.bot_id}),this.botConfig.socketMode&&this.botConfig.appToken&&await this.startSocketMode();}async doStop(){this.abortController?.abort(),this.abortController=null,this.socketModeClient&&(this.socketModeClient.close(),this.socketModeClient=null),this.botConfig=null,this.log.info("Slack plugin stopped");}async send(e){let s=e.metadata.channel.chatId;if(!s)throw new Error("Channel ID is required");let n=this.extractText(e);return (await this.postMessage(s,n,e.metadata.context?.threadId)).ts}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:true,supportsEdit:false,supportsDelete:false,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:true,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,maxMessageLength:3e4,maxMediaCount:10}}async startSocketMode(){if(!this.botConfig?.appToken)return;let e="wss://wss-primary.slack.com/socket";this.socketModeClient=new WebSocket(e),this.socketModeClient.onmessage=async s=>{try{let n=JSON.parse(s.data.toString());await this.handleSocketModeEvent(n);}catch(n){this.log.error("Socket mode event error",{error:String(n)});}},this.log.info("Socket mode started");}async handleSocketModeEvent(e){if(e.envelope_id&&this.socketModeClient?.send(JSON.stringify({envelope_id:e.envelope_id})),e.type==="events_api"&&e.payload?.event){let s=e.payload.event;s.type==="message"&&!s.subtype&&await this.handleSlackMessage(s);}}async handleSlackMessage(e){this.updateActivity();let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return w(s,"input",this.parseContent(e),{channel:{platform:"slack",channelId:this.id,userId:e.user,chatId:e.channel,ts:e.ts,threadTs:e.thread_ts},context:{threadId:e.thread_ts,conversationId:e.channel}})}parseContent(e){let s=[];if(e.text&&s.push({type:"text",text:e.text}),e.files)for(let n of e.files)s.push({type:"file",data:n.url_private,mime:n.mimetype});return s}buildSessionId(e,s,n){return n?`slack_${e}_${s}_${n}`:`slack_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.channel,n=e.user;return this.buildSessionId(this.id,s,n)}async authTest(){return await this.request("auth.test")}async postMessage(e,s,n){let i={channel:e,text:s};return n&&(i.thread_ts=n),await this.request("chat.postMessage",i)}async request(e,s={}){let n=`${this.baseUrl}/${e}`,i=await Fetch.post(n,s,{headers:{Authorization:`Bearer ${this.botConfig?.botToken}`,"Content-Type":"application/json; charset=utf-8"}});if(!i.data.ok)throw new Error(`Slack API error: ${i.data.error}`);return i.data}};var ne=class extends v{constructor(e="feishu-main"){super();a$1(this,"id");a$1(this,"platform","feishu");a$1(this,"name","Feishu Bot");a$1(this,"botConfig",null);a$1(this,"baseUrl","https://open.feishu.cn/open-apis");a$1(this,"tenantAccessToken",null);a$1(this,"tokenExpireTime",0);a$1(this,"abortController",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw new Error("App ID and App Secret are required");this.abortController=new AbortController,await this.refreshTenantAccessToken(),this.log.info("Feishu bot connected",{app_id:this.botConfig.appId});}async doStop(){this.abortController?.abort(),this.abortController=null,this.botConfig=null,this.tenantAccessToken=null,this.log.info("Feishu plugin stopped");}async send(e){let s=e.metadata.channel.chatId;if(!s)throw new Error("Chat ID is required");await this.ensureTokenValid();let n=this.extractText(e);return (await this.sendMessage(s,n)).message_id}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:false,supportsEdit:false,supportsDelete:false,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:true,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,maxMessageLength:4e3,maxMediaCount:10}}async handleWebhookEvent(e){if(this.updateActivity(),this.botConfig?.verificationToken,e.event?.message){let s=this.toGatewayMessage(e);await this.handleMessage(s);}}toGatewayMessage(e){let s=e.event.message,n=this.processMessageAndGetSessionId(e);return w(n,"input",this.parseContent(s),{channel:{platform:"feishu",channelId:this.id,userId:s.sender.sender_id.open_id,chatId:s.chat_id,messageId:s.message_id,rootId:s.root_id,parentId:s.parent_id,tenantKey:e.tenant_key},context:{threadId:s.root_id,conversationId:s.chat_id}})}parseContent(e){let s=[];try{let n=JSON.parse(e.content);switch(e.message_type){case "text":n.text&&s.push({type:"text",text:n.text});break;case "post":if(n.content){let i=this.extractPostContent(n.content);s.push({type:"text",text:i});}break;case "image":n.image_key&&s.push({type:"image",image:n.image_key,mime:"image/jpeg"});break;case "file":n.file_key&&s.push({type:"file",data:n.file_key,mime:n.file_type});break;default:s.push({type:"text",text:JSON.stringify(n)});}}catch{s.push({type:"text",text:e.content});}return s}extractPostContent(e){let s=[];for(let n of e)if(typeof n=="object"&&n!==null){let i=n;i.text&&s.push(String(i.text)),Array.isArray(i.children)&&s.push(this.extractPostContent(i.children));}return s.join(`
6
+ `)}buildSessionId(e,s,n){return n?`feishu_${e}_${s}_${n}`:`feishu_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.event.message,n=s.chat_id,i=s.sender.sender_id.open_id;return this.buildSessionId(this.id,n,i)}async refreshTenantAccessToken(){let s=(await Fetch.post(`${this.baseUrl}/auth/v3/tenant_access_token/internal`,{app_id:this.botConfig?.appId,app_secret:this.botConfig?.appSecret},{headers:{"Content-Type":"application/json"}})).data;if(s.code!==0)throw new Error(`Feishu API error: ${s.msg}`);this.tenantAccessToken=s.tenant_access_token,this.tokenExpireTime=Date.now()+s.expire*1e3-6e4;}async ensureTokenValid(){(!this.tenantAccessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshTenantAccessToken();}async sendMessage(e,s){let i=(await Fetch.post(`${this.baseUrl}/im/v1/messages?receive_id_type=chat_id`,{receive_id:e,msg_type:"text",content:JSON.stringify({text:s})},{headers:{Authorization:`Bearer ${this.tenantAccessToken}`,"Content-Type":"application/json"}})).data;if(i.code!==0)throw new Error(`Feishu API error: ${i.msg}`);return i.data}};var ie=class extends v{constructor(e="wechat-main"){super();a$1(this,"id");a$1(this,"platform","wechat");a$1(this,"name","WeChat Bot");a$1(this,"botConfig",null);a$1(this,"accessToken",null);a$1(this,"tokenExpireTime",0);a$1(this,"abortController",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw new Error("App ID and App Secret are required");this.abortController=new AbortController,await this.refreshAccessToken(),this.log.info("WeChat bot connected",{app_id:this.botConfig.appId,mode:this.botConfig.mode});}async doStop(){this.abortController?.abort(),this.abortController=null,this.botConfig=null,this.accessToken=null,this.log.info("WeChat plugin stopped");}async send(e){let s=e.metadata.channel.userId;if(!s)throw new Error("User ID is required");await this.ensureTokenValid();let n=this.extractText(e);return this.botConfig?.mode==="wecom"?await this.sendWeComMessage(s,n):await this.sendOfficialMessage(s,n)}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:false,supportsEdit:false,supportsDelete:false,supportsTyping:false,supportsBatchSend:false,supportsMarkdown:false,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,maxMessageLength:2048,maxMediaCount:1}}async handleWebhookMessage(e){this.updateActivity();let s=this.parseXmlMessage(e);if(s){let n=this.toGatewayMessage(s);await this.handleMessage(n);}}parseXmlMessage(e){let s=r=>e.match(new RegExp(`<${r}><!\\[CDATA\\[(.*?)\\]\\]></${r}>`))?.[1],n=r=>{let o=e.match(new RegExp(`<${r}>(\\d+)</${r}>`));return o?.[1]?parseInt(o[1],10):void 0},i=s("MsgType");return i?{ToUserName:s("ToUserName")??"",FromUserName:s("FromUserName")??"",CreateTime:n("CreateTime")??0,MsgType:i,Content:s("Content"),MsgId:n("MsgId"),PicUrl:s("PicUrl"),MediaId:s("MediaId")}:null}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return w(s,"input",this.parseContent(e),{channel:{platform:"wechat",channelId:this.id,userId:e.FromUserName,chatId:e.FromUserName,toUser:e.ToUserName,msgId:e.MsgId?.toString(),mode:this.botConfig?.mode},context:{conversationId:e.FromUserName}})}parseContent(e){let s=[];switch(e.MsgType){case "text":e.Content&&s.push({type:"text",text:e.Content});break;case "image":(e.PicUrl||e.MediaId)&&s.push({type:"image",image:e.PicUrl??e.MediaId??"",mime:"image/jpeg"});break;case "voice":e.MediaId&&s.push({type:"file",data:e.MediaId,mime:"audio/amr"}),"Recognition"in e&&e.Recognition&&s.push({type:"text",text:e.Recognition});break;case "video":case "shortvideo":e.MediaId&&s.push({type:"file",data:e.MediaId,mime:"video/mp4"});break;default:e.Content&&s.push({type:"text",text:e.Content});}return s}buildSessionId(e,s,n){return n?`wechat_${e}_${s}_${n}`:`wechat_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.FromUserName;return this.buildSessionId(this.id,s)}async refreshAccessToken(){let e;this.botConfig?.mode==="wecom"?e=`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${this.botConfig.appId}&corpsecret=${this.botConfig.appSecret}`:e=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.botConfig?.appId}&secret=${this.botConfig?.appSecret}`;let n=(await Fetch.get(e)).data;if(n.errcode&&n.errcode!==0)throw new Error(`WeChat API error: ${n.errmsg}`);this.accessToken=n.access_token,this.tokenExpireTime=Date.now()+n.expires_in*1e3-6e4;}async ensureTokenValid(){(!this.accessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshAccessToken();}async sendOfficialMessage(e,s){let i=(await Fetch.post(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{touser:e,msgtype:"text",text:{content:s}},{headers:{"Content-Type":"application/json"}})).data;if(i.errcode!==0)throw new Error(`WeChat API error: ${i.errmsg}`);return i.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,s){let i=(await Fetch.post(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${this.accessToken}`,{touser:e,msgtype:"text",agentid:this.botConfig?.agentId,text:{content:s}},{headers:{"Content-Type":"application/json"}})).data;if(i.errcode!==0)throw new Error(`WeCom API error: ${i.errmsg}`);return i.msgid??Date.now().toString()}};var re=class extends v{constructor(e="webchat-main"){super();a$1(this,"id");a$1(this,"platform","webchat");a$1(this,"name","WebChat");a$1(this,"webChatConfig",null);a$1(this,"connections",new Map);a$1(this,"heartbeatInterval",null);a$1(this,"abortController",null);a$1(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 O(e),await this.wsServer.start(),this.log.info("WebSocket server started",{url:`${this.webChatConfig.https?.enabled?"wss":"ws"}://${this.webChatConfig.hostname}:${this.webChatConfig.port}${this.webChatConfig.path}`});}async doStop(){this.abortController?.abort(),this.abortController=null,this.wsServer&&(await this.wsServer.stop(),this.wsServer=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let e of this.connections.values())e.ws.close();this.connections.clear(),this.webChatConfig=null,this.log.info("WebChat plugin stopped");}async send(e){let s=e.sessionId,n=e.metadata.channel.userId;if(this.wsServer&&s){let o={type:"message",sessionId:s,properties:{sessionID:s,content:e.content,timestamp:e.timestamp||Date.now()}};return this.wsServer.broadcastToSession(s,o),e.id}if(!n)throw new Error("User ID is required");let i=this.findConnectionByUser(n);if(!i)throw new Error("User not connected");let r={type:"message",sessionId:s,content:e.content,metadata:e.metadata};return i.ws.send(JSON.stringify(r)),i.lastActivity=Date.now(),e.id}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:true,supportsEdit:true,supportsDelete:true,supportsTyping:true,supportsBatchSend:true,supportsMarkdown:true,supportsHtml:true,supportsDeliveryReceipt:true,supportsReadReceipt:true,maxMessageLength:1e5,maxMediaCount:20}}pushEvent(e,s){this.wsServer&&this.wsServer.broadcastToSession(e,s);}getWebSocketServer(){return this.wsServer}async handleConnection(e,s){let n=this.generateConnectionId();if(this.connections.size>=(this.webChatConfig?.maxConnections??1e3)){e.close(1013,"Maximum connections reached");return}let i={id:n,ws:e,userId:s,lastActivity:Date.now()};this.connections.set(n,i),e.onmessage=r=>{this.handleWebSocketMessage(i,r.data.toString());},e.onclose=()=>{this.connections.delete(n),this.log.debug("WebSocket closed",{connId:n,userId:s});},e.onerror=r=>{this.log.error("WebSocket error",{connId:n,userId:s,error:String(r)});},this.log.info("WebSocket connected",{connId:n,userId:s});}async handleWebSocketMessage(e,s){this.updateActivity(),e.lastActivity=Date.now();try{let n=JSON.parse(s);switch(n.type){case "message":await this.handleChatMessage(e,n);break;case "ping":e.ws.send(JSON.stringify({type:"pong"}));break;case "subscribe":n.sessionId&&(e.sessionId=n.sessionId);break;case "unsubscribe":e.sessionId=void 0;break;case "message_delivered":await this.handleMessageAcknowledgment(e,n,"message_delivered");break;case "message_read":await this.handleMessageAcknowledgment(e,n,"message_read");break}}catch(n){this.log.error("Failed to handle WebSocket message",{error:String(n)});}}async handleMessageAcknowledgment(e,s,n){s.messageId&&(this.log.info("message acknowledgment received",{type:n,messageId:s.messageId,userId:e.userId}),this.messageHandler&&await this.messageHandler.onEvent({type:n,channelId:this.id,data:{messageId:s.messageId,sessionId:e.sessionId,platform:"webchat",channelId:this.id,userId:e.userId},timestamp:Date.now()}));}async handleChatMessage(e,s){if(!s.content||!s.sessionId)return;let n=w(s.sessionId,"input",s.content,{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},context:{conversationId:s.sessionId},...s.metadata});await this.handleMessage(n);}startHeartbeat(){let e=this.webChatConfig?.heartbeatInterval??3e4;this.heartbeatInterval=setInterval(()=>{let s=Date.now(),n=this.webChatConfig?.connectionTimeout??6e4;for(let[i,r]of this.connections)s-r.lastActivity>n&&(this.log.info("Closing inactive connection",{connId:i}),r.ws.close(1001,"Connection timeout"),this.connections.delete(i));},e);}findConnectionByUser(e){for(let s of this.connections.values())if(s.userId===e)return s}generateConnectionId(){return `conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}getConnectionCount(){return this.connections.size}getWsServerConnectionCount(){return this.wsServer?.getConnectionCount()??0}};var ae=class extends v{constructor(e="signal-main"){super();a$1(this,"id");a$1(this,"platform","signal");a$1(this,"name","Signal Bot");a$1(this,"botConfig",null);a$1(this,"abortController",null);a$1(this,"lastTimestamp",0);a$1(this,"pollingIntervalMs",5e3);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.phoneNumber)throw new Error("Phone number is required");this.abortController=new AbortController;let e=await this.getAccountInfo();this.log.info("Signal bot connected",{number:this.botConfig.phoneNumber,address:e.address}),this.startPolling();}async doStop(){this.abortController?.abort(),this.abortController=null,this.botConfig=null,this.lastTimestamp=0,this.log.info("Signal plugin stopped");}async send(e){let s=e.metadata.channel.userId;if(!s)throw new Error("Recipient is required");let n=this.extractText(e);return (await this.sendMessage(s,n)).timestamp.toString()}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:false,supportsThread:false,supportsEdit:false,supportsDelete:false,supportsTyping:false,supportsBatchSend:false,supportsMarkdown:false,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,maxMessageLength:65536,maxMediaCount:10}}startPolling(){this.pollLoop(),this.log.info("Polling started",{interval:this.pollingIntervalMs});}pollLoop(){if(this.abortController?.signal.aborted)return;(async()=>{try{await this.poll();}catch(s){this.log.error("Polling error",{error:String(s)});}})().then(()=>{this.abortController?.signal.aborted||setTimeout(()=>this.pollLoop(),this.pollingIntervalMs);});}async poll(){let e=await this.receiveMessages(this.lastTimestamp);for(let s of e)this.lastTimestamp=s.envelope.timestamp,s.envelope.dataMessage&&await this.handleSignalMessage(s);}async handleSignalMessage(e){this.updateActivity();let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e),n=e.envelope.dataMessage;return w(s,"input",this.parseContent(n),{channel:{platform:"signal",channelId:this.id,userId:e.envelope.sourceNumber,chatId:e.envelope.sourceNumber,sourceUuid:e.envelope.sourceUuid,timestamp:e.envelope.timestamp},context:{conversationId:e.envelope.sourceNumber}})}parseContent(e){let s=[];if(!e)return s;if(e.message&&s.push({type:"text",text:e.message}),e.attachments)for(let n of e.attachments)n.contentType.startsWith("image/")?s.push({type:"image",image:n.id,mime:n.contentType}):s.push({type:"file",data:n.id,mime:n.contentType});return s}buildSessionId(e,s,n){return n?`signal_${e}_${s}_${n}`:`signal_${e}_${s}`}processMessageAndGetSessionId(e){let s=e.envelope.sourceNumber;return this.buildSessionId(this.id,s)}async getAccountInfo(){return await this.request("GET",`/v1/accounts/${this.botConfig?.phoneNumber}`)}async receiveMessages(e){let s=e>0?`?since=${e}`:"";return await this.request("GET",`/v1/receive/${this.botConfig?.phoneNumber}${s}`)||[]}async sendMessage(e,s){return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:s})}async request(e,s,n){let i=`${this.botConfig?.serviceUrl}${s}`,r={"Content-Type":"application/json"};this.botConfig?.password&&(r.Authorization=`Basic ${Buffer.from(`${this.botConfig.phoneNumber}:${this.botConfig.password}`).toString("base64")}`);let o;if(e==="GET"?o=await Fetch.get(i,{headers:r}):e==="POST"?o=await Fetch.post(i,n,{headers:r}):e==="DELETE"?o=await Fetch.del(i,{headers:r}):o=await Fetch.request(i,{method:e,body:n,headers:r}),!o.ok)throw new Error(`Signal API error: ${o.data}`);return o.data}};var oe=class extends v{constructor(e="nostr-main"){super();a$1(this,"id");a$1(this,"platform","nostr");a$1(this,"name","Nostr Bot");a$1(this,"botConfig",null);a$1(this,"relayConnections",new Map);a$1(this,"subscriptions",new Map);a$1(this,"eventHandlers",new Map);a$1(this,"abortController",null);a$1(this,"relayReconnectAttempts",new Map);a$1(this,"maxReconnectAttempts",5);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.relays||this.botConfig.relays.length===0)throw new Error("At least one relay is required");this.abortController=new AbortController;for(let e of this.botConfig.relays)await this.connectToRelay(e);this.log.info("Nostr bot connected",{relays:this.botConfig.relays,pubkey:this.botConfig.publicKey?.substring(0,16)+"..."});}async doStop(){this.abortController?.abort(),this.abortController=null;for(let[e,s]of this.relayConnections)s.close();this.relayConnections.clear(),this.subscriptions.clear(),this.eventHandlers.clear(),this.relayReconnectAttempts.clear(),this.botConfig=null,this.log.info("Nostr plugin stopped");}async send(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required for sending messages");let s=this.extractText(e),n=await this.createEvent(s,e.metadata.context?.replyTo);return await this.publishEvent(n),n.id}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:true,supportsEdit:false,supportsDelete:false,supportsTyping:false,supportsBatchSend:false,supportsMarkdown:true,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,maxMessageLength:65536,maxMediaCount:1}}async connectToRelay(e){if(this.abortController?.signal.aborted)return;let s=new WebSocket(e);s.onopen=()=>{this.log.info("Connected to relay",{relay:e}),this.relayReconnectAttempts.set(e,0);for(let[n,i]of this.subscriptions)this.subscribeToRelay(s,n,i);},s.onmessage=n=>{this.handleRelayMessage(e,n.data.toString());},s.onclose=()=>{if(this.abortController?.signal.aborted)return;this.log.info("Disconnected from relay",{relay:e}),this.relayConnections.delete(e);let n=this.relayReconnectAttempts.get(e)??0;if(n<this.maxReconnectAttempts){let i=Math.min(1e3*2**n,3e4);this.relayReconnectAttempts.set(e,n+1),this.log.info("Attempting to reconnect to relay",{relay:e,attempt:n+1,delay:i}),setTimeout(()=>this.connectToRelay(e),i);}else this.log.error("Max reconnect attempts reached for relay",{relay:e});},s.onerror=n=>{this.log.error("Relay error",{relay:e,error:String(n)});},this.relayConnections.set(e,s);}handleRelayMessage(e,s){this.updateActivity();try{let n=JSON.parse(s);if(n[0]==="EVENT"&&n[2]){let i=n[2];this.handleNostrEvent(i);}if(n[0]==="OK"){let i=n[1],r=n[2];this.log.debug("Event published",{eventId:i,success:r});}}catch(n){this.log.error("Failed to handle relay message",{error:String(n)});}return Promise.resolve()}async handleNostrEvent(e){if(e.kind!==1||e.pubkey===this.botConfig?.publicKey)return;let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return w(s,"input",this.parseContent(e),{channel:{platform:"nostr",channelId:this.id,userId:e.pubkey,chatId:e.pubkey,eventId:e.id,createdAt:e.created_at,tags:e.tags},context:{replyTo:this.findReplyTo(e.tags),conversationId:e.pubkey}})}parseContent(e){let s=[];e.content&&s.push({type:"text",text:e.content});for(let n of e.tags)if(n[0]==="url"&&n[1]){let i=n[1];i.match(/\.(jpg|jpeg|png|gif|webp)$/i)&&s.push({type:"image",image:i});}return s}findReplyTo(e){for(let s of e)if(s[0]==="e"&&s[1])return s[1]}buildSessionId(e,s,n){return n?`nostr_${e}_${s}_${n}`:`nostr_${e}_${s}`}processMessageAndGetSessionId(e){return this.buildSessionId(this.id,e.pubkey)}subscribeToRelay(e,s,n){let i=["REQ",s,n];e.send(JSON.stringify(i));}async createEvent(e,s){let n=[];s&&n.push(["e",s]);let i={id:"",pubkey:this.botConfig?.publicKey??"",created_at:Math.floor(Date.now()/1e3),kind:1,tags:n,content:e,sig:""};return i.id=await this.computeEventId(i),i.sig=await this.signEvent(i),i}async computeEventId(e){let s=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),i=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(r)).map(g=>g.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required");return "signature_placeholder"}async publishEvent(e){let s=["EVENT",e];for(let n of this.relayConnections.values())n.readyState===WebSocket.OPEN&&n.send(JSON.stringify(s));}};var Ve=class extends v{constructor(e){super();a$1(this,"id");a$1(this,"platform");a$1(this,"name");a$1(this,"version");a$1(this,"options");this.id=e.id,this.platform=e.platform||"custom",this.name=e.name,this.version=e.version||"1.0.0",this.options=e,this.initLog();}async doStart(){this.options.setup?.initialize&&await this.options.setup.initialize(),this.log.info("Channel plugin started",{id:this.id,platform:this.platform});}async doStop(){this.options.setup?.destroy&&await this.options.setup.destroy(),this.log.info("Channel plugin stopped",{id:this.id});}async send(e){let s=e;this.options.actions?.beforeSend&&(s=await this.options.actions.beforeSend(e));let n=await this.options.messaging.send(s);return this.options.actions?.afterSend&&await this.options.actions.afterSend(s,n),n}async healthCheck(){return this.options.status?.healthCheck?{healthy:await this.options.status.healthCheck(),lastCheck:Date.now()}:{healthy:true,lastCheck:Date.now()}}};function bs(c){return new Ve(c)}var Je={telegram:ee,discord:te,slack:se,feishu:ne,wechat:ie,webchat:re,signal:ae,nostr:oe};function ia(){return Object.keys(Je)}var U=class U{constructor(t){a$1(this,"log",a.create({service:"gateway:server"}));a$1(this,"config");a$1(this,"router");a$1(this,"sessionManager");a$1(this,"pluginLoader");a$1(this,"messageStore");a$1(this,"contactStore",null);a$1(this,"wsServer",null);a$1(this,"running",false);a$1(this,"connections",0);this.log.debug("GatewayServer.constructor: starting"),this.config=t,this.log.debug("GatewayServer.constructor: creating MessageRouter");let e=F()?$().hookRegistry:void 0;this.router=new xe(e),this.log.debug("GatewayServer.constructor: creating GatewaySessionManager");let s=N();this.sessionManager=new X({storagePath:`${s.Path.data}/gateway/sessions`,enablePersistence:true}),this.log.debug("GatewayServer.constructor: creating ChannelPluginLoader"),this.pluginLoader=new Z({healthCheckInterval:6e4}),this.log.debug("GatewayServer.constructor: pluginLoader created");let n=F();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:n}),this.messageStore=new V({storagePath:`${s.Path.data}/gateway/messages`}),this.pluginLoader.setMessageHandler({onMessage:i=>this.onMessage(i),onEvent:i=>this.onEvent(i)}),this.log.debug("GatewayServer.constructor: completed");}async loadChannelPlugins(){try{let{config:t}=await I(),e=t.channels;if(!e){this.log.debug("no channel config found, skipping plugin loading");return}for(let[s,n]of Object.entries(e)){if(!n?.enabled){this.log.debug("channel disabled or not configured",{platform:s});continue}let i=Je[s];if(!i){this.log.warn("no plugin class found for platform",{platform:s});continue}let r=`${s}-main`,o=new i(r),g={enabled:!0,platform:n,session:{autoCreate:!0,resetPolicy:"onNewConversation"},routing:{broadcast:!0,dispatchToSubAgent:!0}};try{await this.pluginLoader.register(o,g),this.log.info("channel plugin registered",{platform:s,id:r});}catch(d){this.log.error("failed to register channel plugin",{platform:s,error:String(d)});}}}catch(t){this.log.error("failed to load channel plugins",{error:String(t)});}}async start(){if(this.log.debug("GatewayServer.start: called"),this.running){this.log.warn("gateway server is already running");return}this.log.info("starting gateway server",{port:this.config.port,hostname:this.config.hostname}),this.log.debug("GatewayServer.start: initializing sessionManager"),await this.sessionManager.initialize(),this.log.debug("GatewayServer.start: sessionManager initialized"),this.log.debug("GatewayServer.start: initializing contactStore");let e=`${N().Path.data}/gateway`,s=new Q({baseDir:e});this.contactStore=new Y(s,{cacheSize:1e3}),this.contactStore.initialize&&await this.contactStore.initialize(),this.log.debug("GatewayServer.start: contactStore initialized"),this.log.debug("GatewayServer.start: creating WebSocket server"),this.wsServer=new O({port:this.config.port,hostname:this.config.hostname,path:String(this.config.path??"/")}),this.log.debug("GatewayServer.start: calling wsServer.start()"),await this.wsServer.start(),this.log.debug("GatewayServer.start: wsServer started"),await this.loadChannelPlugins(),this.log.debug("GatewayServer.start: starting plugins in background"),this.pluginLoader.startAll().catch(r=>{this.log.error("plugin startup error",{error:String(r)});}),this.log.debug("GatewayServer.start: plugins startup initiated"),this.log.debug("GatewayServer.start: starting health check timer"),this.pluginLoader.startHealthCheckTimer();let{config:n}=await I(),i=n.defaults;this.wsServer.setChannelResolveDeps({sessionManager:{get:r=>this.sessionManager.get(r),getOrCreate:(r,o)=>this.sessionManager.getOrCreate(r,o),bindBackendSession:(r,o)=>this.sessionManager.bindBackendSession(r,o),getAll:()=>this.sessionManager.getAllSessions()},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,o)=>this.contactStore.findByPlatformId(r,o),findByUid:r=>this.contactStore.findByUid(r),listByPlatform:(r,o,g)=>this.contactStore.listByPlatform(r,o,g),count:r=>this.contactStore.count(r)}:void 0}),this.wsServer.setPluginLoader((r,o,g)=>this.sendToChannel(r,o,g)),this.retryPendingMessages().catch(r=>{this.log.error("failed to retry pending messages",{error:String(r)});}),this.running=true,this.log.debug("GatewayServer.start: completed"),this.log.info("gateway server started");}async stop(){if(!this.running){this.log.warn("gateway server is not running");return}this.log.info("stopping gateway server"),this.wsServer&&(this.log.debug("stopping WebSocket server"),await this.wsServer.stop(),this.wsServer=null,this.log.debug("WebSocket server stopped")),this.pluginLoader.stopHealthCheckTimer(),await this.pluginLoader.stopAll(),await this.router.shutdown(),await this.sessionManager.close(),await this.messageStore.close(),this.contactStore?.close&&await this.contactStore.close(),this.running=false,this.log.info("gateway server stopped");}getStatus(){return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections}}async onMessage(t){this.log.debug("message received",{id:t.id,sessionId:t.sessionId,type:t.type});let e=this.messageStore.get(t.id);if(e&&e.retryCount>U.MAX_RETRY_COUNT){this.log.warn("message retry count exceeded, skipping",{id:t.id,retryCount:e.retryCount});return}if(this.messageStore.isProcessed(t.id)){this.log.warn("message already processed, skipping",{id:t.id});return}await this.triggerHook(HookEvent.GatewayMessageReceive,{...t,channel:t.metadata.channel,processorId:t.metadata.processorId,agent:t.metadata.agent}),t.type==="input"&&await this.saveContactFromMessage(t),await this.sessionManager.incrementMessageCountOrCreate(t.sessionId,t.metadata.channel);let s=true;try{let n=await this.router.route(t);if(s=n.success,!n.dispatched&&t.type==="input"){this.log.debug("no subscribers, dispatching to local SubAgent",{id:t.id});try{await this.dispatchToSubAgent(t);}catch{s=!1;}}}catch(n){s=false,this.log.error("route failed",{messageId:t.id,error:String(n)});}t.type==="input"&&!s&&await this.messageStore.incrementRetry(t.id);}async saveContactFromMessage(t){if(!this.contactStore)return;let{platform:e,channelId:s,userId:n,chatId:i}=t.metadata.channel;if(!e||e==="api")return;let r=n||i;if(r)try{let o=await this.contactStore.getOrCreate(e,r,{username:t.metadata.channel?.username,displayName:t.metadata.channel?.firstName});this.log.debug("contact saved",{uid:o.uid});}catch(o){this.log.warn("failed to save contact",{platform:e,stableId:r,error:String(o)});}}async dispatchToSubAgent(t){if(!F()){this.log.debug("no agent adapter, message remains pending",{id:t.id});return}try{let s=$().subAgentRunner;if(!s){this.log.debug("no SubAgentRunner available, message remains pending",{id:t.id});return}this.log.info("dispatching message to local SubAgent",{id:t.id,sessionId:t.sessionId});let n=this.sessionManager.get(t.sessionId),i=n?.backendSessionId||void 0;await this.triggerHook(HookEvent.GatewayMessageProcess,{id:t.id,sessionId:t.sessionId,backendSessionId:i,processorId:"subagent",processType:"subagent",agent:t?.metadata?.agent??"gateway",timestamp:Date.now()});let r=t.metadata.channel,o=r?.platform||"unknown",g=r?.userId||r?.chatId||"unknown user",d=`${o}:${g}`,p=r?.chatType||"unknown",y=`## External Channel Message
7
+ - Platform: ${o}
8
+ - Chat Type: ${p} (e.g., private, group)
9
+ - From: ${g} (contactUid: ${d})
10
+ - Channel: ${r?.channelId||"default"}
11
+ - Session: ${t.sessionId}
12
+
13
+ ## Instructions
14
+ - Reply the message directly if it's a simple response.
15
+ - Use gateway tool to proactively send messages (works for both private and group chats):
16
+ \`\`\`json
17
+ {"operation": "send", "sessionId": "${t.sessionId}", "content": "Your message here"}
18
+ \`\`\``,S={source:t.sessionId,title:`[${o}] Message from ${g}`,agent:"gateway",sessionId:i,parts:t.content,system:y,channel:{platform:o,contactUid:d,channelId:r?.channelId,userId:g}},m=await s.run(S),b=m.metadata?.sessionId;if(b&&n&&n.backendSessionId!==b&&(await this.sessionManager.bindBackendSession(t.sessionId,b),this.log.info("backend session bound",{gatewaySessionId:t.sessionId,backendSessionId:b})),await this.triggerHook(HookEvent.GatewayMessageComplete,{id:t.id,sessionId:t.sessionId,backendSessionId:b||i,processorId:"subagent",status:"completed",timestamp:Date.now()}),m.output){let P=t.metadata.channel;P?.channelId&&(this.log.debug("dispatchToSubAgent: sending response to channel",{id:t.id,channelId:P.channelId,outputLength:m.output.length,outputPreview:m.output.substring(0,100)}),await this.sendToChannel(P.channelId,{id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:t.sessionId,type:"output",content:[{type:"text",text:m.output}],metadata:{channel:P,processorId:"subagent",agent:"subagent",proactive:!1,replyToMessageId:t.id},timestamp:Date.now()},{}),this.log.info("dispatchToSubAgent: response sent to channel",{id:t.id,channelId:P.channelId}),await this.sessionManager.incrementMessageCount(t.sessionId));}this.log.info("SubAgent response sent",{id:t.id});}catch(e){this.log.error("SubAgent dispatch failed",{id:t.id,error:String(e)});let s=t.metadata.channel;if(s?.channelId){let i=`\u26A0\uFE0F \u5904\u7406\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`;await this.sendToChannel(s.channelId,{id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:t.sessionId,type:"output",content:[{type:"text",text:i}],metadata:{channel:s,processorId:"subagent",agent:"subagent",proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}).catch(r=>{this.log.error("failed to send error response",{error:String(r)});});}}}async triggerHook(t,e){if(F())try{await $().hookRegistry.triggerEvent(t,e,{messageStore:{store:async(n,i)=>{let r=ce(n);await this.messageStore.store(r,i);},updateStatus:async(n,i,r)=>{await this.messageStore.updateStatus(n,i,r);}}});}catch{this.log.debug("hook trigger skipped",{event:t});}}async retryPendingMessages(){let t=Date.now()-U.SEVEN_DAYS_MS,e=0;for(let s of this.sessionManager.getAllSessions()){let n=this.messageStore.getSessionHistory(s.id,1e3);for(let i of n)if(!(i.createdAt<t)&&(i.status==="pending"||i.status==="failed"||i.status==="processing")){let r=i.message;if(i.retryCount>U.MAX_RETRY_COUNT){await this.messageStore.updateStatus(r.id,"failed",{error:"retry count exceeded"});continue}let o=r.metadata.channel?.channelId;if(!o){i.status==="processing"&&(this.log.warn("cannot process stuck message: no pluginId",{messageId:r.id}),await this.messageStore.updateStatus(r.id,"failed",{error:"no pluginId"}));continue}if(!this.pluginLoader.getPlugin(o)||!this.pluginLoader.isRunning(o)){i.status==="processing"&&(this.log.warn("cannot process stuck message: plugin unavailable",{messageId:r.id,pluginId:o}),await this.messageStore.updateStatus(r.id,"failed",{error:"plugin not available"}));continue}r.type==="input"?i.status==="processing"&&(this.log.debug("found stuck processing input message, re-dispatching via onMessage",{messageId:r.id,sessionId:s.id}),await this.messageStore.updateStatus(r.id,"pending"),this.onMessage(r).then(()=>{e++;}).catch(d=>{this.log.error("failed to re-dispatch stuck message",{messageId:r.id,error:String(d)});})):r.type==="output"&&(i.status!=="processing"&&await this.messageStore.updateStatus(r.id,"processing"),this.log.debug("retrying output message",{messageId:r.id,pluginId:o,status:i.status}),this.sendToChannel(o,r,{}).then(()=>{e++;}).catch(d=>{this.log.error("failed to retry message",{messageId:r.id,error:String(d)});}));}}this.log.info("retryPendingMessages completed",{totalProcessed:e});}async storeMessage(t){try{await this.messageStore.store(t),this.log.debug("message stored",{messageId:t.id});}catch(e){this.log.warn("failed to store message",{messageId:t.id,error:String(e)});}}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;case "message_delivered":this.log.debug("message delivered event received",{id:t.data?.id,sessionId:t.data?.sessionId,channelId:t.channelId}),await this.triggerHook(HookEvent.GatewayMessageDelivered,{id:t.data?.id,sessionId:t.data?.sessionId,timestamp:t.timestamp});break;case "message_read":this.log.debug("message read event received",{id:t.data?.id,sessionId:t.data?.sessionId,channelId:t.channelId}),await this.triggerHook(HookEvent.GatewayMessageRead,{id:t.data?.id,sessionId:t.data?.sessionId,timestamp:t.timestamp});break}}async registerChannel(t,e){let s=e??{enabled:true,platform:{},session:{autoCreate:true,resetPolicy:"onNewConversation"},routing:{broadcast:true,dispatchToSubAgent:false}};await this.pluginLoader.register(t,s),this.running&&await this.pluginLoader.start(t.id);}async unregisterChannel(t){await this.pluginLoader.unregister(t);}async subscribe(t,e){await this.router.subscribe(t,e),await this.sessionManager.addSubscriber(t,e.id);}async unsubscribe(t){await this.router.unsubscribe(t);}async sendToChannel(t,e,s={}){let n=e.metadata.proactive??!s.replyToMessageId,i=s.replyToMessageId??e.metadata.replyToMessageId;if(this.messageStore.isProcessed(e.id))return this.log.debug("message already processed, skipping send",{id:e.id}),e.id;if(F())try{await $().hookRegistry.triggerEvent(HookEvent.GatewayMessageSend,{id:e.id,sessionId:e.sessionId,type:e.type,content:e.content,channel:e.metadata.channel,proactive:n,replyToMessageId:i,timestamp:Date.now(),processorId:e.metadata.processorId??"gateway",agent:e.metadata.agent??"gateway"},{messageStore:{store:async(d,p)=>{let y=ce(d);await this.messageStore.store(y,p);},updateStatus:async(d,p,y)=>{await this.messageStore.updateStatus(d,p,y);}}});}catch{this.log.debug("hook trigger skipped (no context)");}let r=this.pluginLoader.getPlugin(t);if(!r)throw new Error(`Plugin not found: ${t}`);this.log.debug("sendToChannel: calling plugin.send",{pluginId:t,messageId:e.id});let o;try{o=await r.send(e),this.log.debug("sendToChannel: plugin.send completed",{pluginId:t,messageId:e.id,result:o});}catch(g){throw this.log.error("sendToChannel: plugin.send failed",{pluginId:t,messageId:e.id,error:String(g)}),await this.messageStore.incrementRetry(e.id),await this.messageStore.updateStatus(e.id,"failed",{error:String(g)}),g}return o}async sendProactiveMessage(t,e,s,n,i={}){let r={id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:e,type:"output",content:s,metadata:{channel:n,processorId:i.processorId,agent:i.agent,proactive:true},timestamp:Date.now()};return this.sendToChannel(t,r,{})}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)}};a$1(U,"MAX_RETRY_COUNT",3),a$1(U,"SEVEN_DAYS_MS",10080*60*1e3);var ut=U;export{is as $,zt as A,jt as B,qt as C,Kt as D,Vt as E,Jt as F,Qt as G,Yt as H,Xt as I,Zt as J,es as K,it as L,Ls as M,Os as N,F as O,$ as P,Oe as Q,w as R,pt as S,ce as T,Ee as U,Ne as V,De as W,Fe as X,ts as Y,ss as Z,ns as _,ue as a,xe as aa,pe as b,V as ba,he as c,J as ca,fe as d,X as da,me as e,Z as ea,ye as f,O as fa,be as g,v as ga,Qe as h,ee as ha,Ye as i,te as ia,Xe as j,se as ja,Ze as k,ne as ka,et as l,ie as la,Ce as m,re as ma,Se as n,ae as na,ve as o,oe as oa,we as p,bs as pa,Ie as q,Je as qa,Pe as r,ia as ra,de as s,ut as sa,Le as t,St as u,tt as v,st as w,nt as x,Ht as y,$t as z};