@easbot/gateway 0.3.19 → 0.3.20

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.
@@ -1,4 +1,4 @@
1
- import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Identifier,Filesystem,TruncateContent,Fetch,PKG,createServer}from'@easbot/utils';import u,{z as z$1}from'zod';import*as pe from'path';import pe__default,{join,extname,basename}from'path';import*as se from'fs';import se__default,{existsSync,readFileSync,writeFileSync,mkdirSync,chmodSync,unlinkSync}from'fs';import*as W from'fs/promises';import W__default,{readFile}from'fs/promises';import {WebSocketServer}from'ws';import Wi from'https';import Hi from'http';import zi,{randomUUID,createHash,randomBytes,createCipheriv,createDecipheriv}from'crypto';import {pathToFileURL,fileURLToPath}from'url';import {homedir,tmpdir}from'os';import {HookEvent}from'@easbot/plugin';function A(o,t,e,s){return {id:Identifier.ascending("message"),sessionId:o,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 wn(o,t,e,s){return A(o,t,[{type:"text",text:e}],s)}function Ve(o){let t={platform:o.channel?.platform??"api",channelId:o.channel?.channelId??"unknown",chatId:o.channel?.chatId,userId:o.channel?.userId,chatType:o.channel?.chatType,chatTitle:o.channel?.chatTitle};return {id:o.id,sessionId:o.sessionId,type:o.type,content:Array.isArray(o.content)?o.content:[{type:"text",text:String(o.content??"")}],metadata:{channel:t,replyToMessageId:o.replyToMessageId,processorId:o.processorId,agent:o.agent,proactive:o.proactive??!o.replyToMessageId},timestamp:o.timestamp??Date.now()}}function Je(o){if(!o.platform)throw new Error("Invalid session: platform is required");if(!o.channelId)throw new Error("Invalid session: channelId is required");let t=o.chatId??"",e=o.userId??t;if(!t&&!o.userId)throw new Error(`Invalid session: chatId and userId cannot both be empty. platform=${o.platform}, channelId=${o.channelId}`);return [o.platform,o.channelId,t,e].join("_")}function Qe(){return {status:"active",messageCount:0,lastMessageAt:null}}function Xe(o,t){if(!o||!t)throw new Error("platform and stableId are required");return `${o}:${t}`}function Ye(o){if(!o||typeof o!="string")return null;let t=o.indexOf(":");if(t<=0||t>=o.length-1)return null;let e=o.slice(0,t),s=o.slice(t+1);return !e||!s?null:{platform:e,stableId:s}}function _t(o){let{platform:t,stableId:e,profile:s={},aliases:n={},metadata:i}=o;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:Xe(t,e),platform:t,stableId:e,aliases:{...n},profile:{...s},createdAt:r,lastSeenAt:r,metadata:i}}function Et(o,t){return `sub_${o}_${t}`}var In=Log.create({service:"gateway:config"});u.enum(["telegram","slack","feishu","wechat","weixin","webchat","signal","nostr","dingtalk"]);u.enum(["low","medium","high","critical"]);var et=u.object({enabled:u.boolean().default(true),botToken:u.string().describe("Telegram Bot Token"),webhookUrl:u.string().optional().describe("Webhook URL for receiving updates"),polling:u.object({enabled:u.boolean().default(true),interval:u.number().int().positive().optional().describe("Polling interval in ms"),timeout:u.number().int().positive().optional().default(30).describe("Long polling timeout in seconds")}).refine(o=>o===void 0||o.enabled,{message:"polling.enabled must be true when polling is configured"}).optional(),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),tt=u.object({enabled:u.boolean().default(true),botToken:u.string().describe("Slack Bot Token (xoxb-*)"),appToken:u.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:u.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),st=u.object({enabled:u.boolean().default(true),appId:u.string().describe("Feishu App ID"),appSecret:u.string().describe("Feishu App Secret"),encryptKey:u.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:u.string().optional().describe("Feishu Verification Token"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),nt=u.object({enabled:u.boolean().default(true),mode:u.enum(["official","wecom"]).default("official"),appId:u.string().describe("WeChat App ID"),appSecret:u.string().describe("WeChat App Secret"),token:u.string().optional().describe("WeChat Token for message verification"),encodingAESKey:u.string().optional().describe("WeChat Encoding AES Key"),agentId:u.string().optional().describe("WeCom Agent ID"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),An=u.object({enabled:u.boolean().default(true),stateDir:u.string().optional().describe("Override the default account persistence directory (default: ~/.easbot/channels/weixin)"),baseUrl:u.string().optional().describe("Override the iLink API baseUrl (default: https://ilinkai.weixin.qq.com)"),cdnBaseUrl:u.string().optional().describe("Override the CDN baseUrl (default: https://novac2c.cdn.weixin.qq.com/c2c)"),maxMessageLength:u.number().int().positive().optional().default(4e3),timeout:u.number().int().positive().optional().default(3e4)}),it=u.object({enabled:u.boolean().default(true),path:u.string().optional().default("/"),heartbeatInterval:u.number().int().positive().optional().default(3e4),connectionTimeout:u.number().int().positive().optional().default(36e5),maxConnections:u.number().int().positive().optional().default(1e3),cors:u.boolean().optional().default(true)}),rt=u.object({enabled:u.boolean().default(true),serviceUrl:u.string().optional().default("https://chat.signal.org"),phoneNumber:u.string().describe("Signal phone number"),password:u.string().optional().describe("Signal account password"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),at=u.object({enabled:u.boolean().default(true),relays:u.array(u.string()).min(1).describe("Nostr relay URLs"),privateKey:u.string().optional().describe("Nostr private key (hex)"),publicKey:u.string().optional().describe("Nostr public key (hex)"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),Pn=u.object({enabled:u.boolean().default(true),appKey:u.string().describe("DingTalk AppKey"),appSecret:u.string().describe("DingTalk AppSecret"),token:u.string().optional().describe("DingTalk token for signature verification"),encryptKey:u.string().optional().describe("DingTalk encrypt key for message encryption"),webhook:u.object({enabled:u.boolean().default(true),path:u.string().optional().default("/dingtalk/webhook"),port:u.number().int().positive().optional().describe("Webhook server port")}).optional(),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),ns=u.object({telegram:et.optional(),slack:tt.optional(),feishu:st.optional(),wechat:nt.optional(),weixin:An.optional(),webchat:it.optional(),signal:rt.optional(),nostr:at.optional(),dingtalk:Pn.optional()}),is=u.object({enabled:u.boolean().default(false),cert:u.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:u.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:u.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:u.string().optional().describe("Path to SSL key file (alias of key)"),ca:u.string().optional().describe("Path to CA certificate file"),forceRedirect:u.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:u.number().int().positive().optional().default(80).describe("HTTP redirect port")}),xn=u.object({name:u.string().describe("Token name/description"),value:u.string().describe("Token value"),permissions:u.array(u.string()).default(["*"]).describe("Associated permissions"),expiresAt:u.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:u.string().optional().describe("Token description")}),Mn=u.object({enabled:u.boolean().default(true),tokens:u.array(xn).default([]).describe("List of valid tokens"),onInvalid:u.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:u.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:u.array(u.string()).default([]).describe("Default permissions for anonymous users")}),kn=u.object({enabled:u.boolean().default(false),authorizationServer:u.string().describe("OAuth2 authorization server URL"),clientId:u.string().describe("OAuth2 client ID"),clientSecret:u.string().describe("OAuth2 client secret"),tokenValidationEndpoint:u.string().describe("OAuth2 token validation endpoint"),scope:u.array(u.string()).default([]).describe("OAuth2 scopes")}),rs=u.object({type:u.enum(["token","oauth2"]).default("token"),token:Mn.optional(),oauth2:kn.optional()}),as=u.object({mode:u.enum(["pull","push","both"]).default("both"),interval:u.number().int().positive().default(3e4),pushEvents:u.array(u.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:u.enum(["latest","local","remote"]).default("latest")}),Tn=u.object({id:u.string().describe("Gateway node ID"),address:u.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:u.boolean().default(true),metadata:u.record(u.string(),u.any()).optional()}),os=u.object({nodeId:u.string().describe("Current gateway node ID"),nodes:u.array(Tn).default([]).describe("Other gateway nodes in the cluster"),sync:as.optional()}),ot=u.object({maxConnectionsPerChannel:u.number().int().positive().default(100),idleTimeout:u.number().int().positive().default(3e5),reuseStrategy:u.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:u.number().int().positive().default(6e4),acquireTimeout:u.number().int().positive().default(5e3),warmupCount:u.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),ct=u.object({maxLength:u.number().int().positive().default(1e4),concurrency:u.number().int().positive().default(100),batchSize:u.number().int().positive().default(10),batchTimeout:u.number().int().positive().default(100),priorityLevels:u.number().int().positive().default(4)}),lt=u.object({failureThreshold:u.number().int().positive().default(5),successThreshold:u.number().int().positive().default(3),timeout:u.number().int().positive().default(3e4),halfOpenDuration:u.number().int().positive().default(15e3)}),dt=u.object({heartbeatInterval:u.number().int().positive().default(6e4),heartbeatTimeout:u.number().int().positive().default(3e5),heartbeatCheckInterval:u.number().int().positive().default(3e5),autoDeregisterTimeout:u.number().int().positive().default(6e5),maxAgents:u.number().int().positive().default(100),persistenceFile:u.string().optional().describe("Path to persist agent registrations"),maxRegistrations:u.number().int().positive().default(1e3)}),gt=u.object({sessionTimeout:u.number().int().positive().default(18e5),resumeGracePeriod:u.number().int().positive().default(3e5),maxSessions:u.number().int().positive().default(1e4),persistenceFile:u.string().optional().describe("Path to persist sessions")}),ut=u.object({enabled:u.boolean().default(true),port:u.number().int().positive().default(8080),hostname:u.string().default("localhost"),path:u.string().optional().default("/"),maxConnections:u.number().int().positive().optional().default(1e3),connectionTimeout:u.number().int().positive().optional().default(36e5),heartbeatInterval:u.number().int().positive().optional().default(3e4),sessionExpireMs:u.number().int().positive().optional().default(36e5),https:is.optional(),auth:rs.optional(),cors:u.boolean().default(true),corsOrigins:u.array(u.string()).optional(),mdns:u.boolean().default(false),mdnsDomain:u.string().optional().default("gateway.easbot.local")}),_n=u.object({channel:u.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:u.array(u.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),En=u.enum(["localAgent","subAgent","both"]),Rn=u.object({mode:En.default("localAgent").describe("Agent processing mode: localAgent, subAgent, or both"),localAgentPriority:u.number().int().min(1).max(10).default(1).describe("Priority for localAgent (lower = higher priority)"),subAgentPriority:u.number().int().min(1).max(10).default(2).describe("Priority for subAgent (lower = higher priority)"),timeout:u.number().int().positive().optional().default(3e5).describe("Timeout for agent execution in milliseconds"),retryOnFailure:u.boolean().default(true).describe("Retry with subAgent when localAgent fails")}),pt=u.object({autoRegister:u.boolean().default(true).describe("Whether to auto-register agent on startup"),heartbeatInterval:u.number().int().positive().default(3e4).describe("Heartbeat interval in milliseconds"),maxReconnectAttempts:u.number().int().min(0).default(5).describe("Maximum reconnect attempts"),reconnectDelay:u.number().int().positive().default(3e3).describe("Reconnect delay in milliseconds"),heartbeatTimeout:u.number().int().positive().default(9e4).describe("Heartbeat timeout in milliseconds")}),Ze=u.object({server:ut.optional(),channels:ns.optional(),cluster:os.optional(),connectionPool:ot.optional(),messageQueue:ct.optional(),circuitBreaker:lt.optional(),agentRegistry:dt.optional(),session:gt.optional(),defaults:_n.optional(),agentProcessing:Rn.optional(),client:pt.optional().describe("Gateway client config for agent registration"),defaultAgent:u.string().optional().describe("Default agent ID for routing"),logLevel:u.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(u.unknown());function Rt(o){let t=Ze.safeParse(o);return t.success||In.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:Ze.parse({})}function Dn(o){return Ze.parse(o)}var N=Log.create({service:"sdk-event-bus"}),ht=(i=>(i.SDK_SESSION_STATUS="agent.status",i.SDK_ERROR="sdk.error",i.SDK_SESSION_UPDATE="sdk.session_update",i.SDK_PERMISSION_REQUEST="sdk.permission_request",i.SDK_SESSION_DELETED="sdk.session_deleted",i))(ht||{});z$1.object({sessionId:z$1.string(),status:z$1.enum(["idle","busy","retry"]),timestamp:z$1.number()});z$1.object({error:z$1.string(),context:z$1.record(z$1.string(),z$1.any()).optional(),timestamp:z$1.number()});z$1.object({sessionId:z$1.string(),sessionEvent:z$1.unknown(),timestamp:z$1.number()});z$1.object({requestId:z$1.string(),sessionId:z$1.string(),permission:z$1.string(),tool:z$1.object({callId:z$1.string().optional()}).optional(),metadata:z$1.record(z$1.string(),z$1.any()).optional(),timestamp:z$1.number()});z$1.object({sessionId:z$1.string(),timestamp:z$1.number()});var ve=class{constructor(){a(this,"subscriptions",new Map);a(this,"wildcardSubscriptions",new Set);a(this,"destroyed",false);}subscribe(t,e){if(this.destroyed)return N.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{};let s=this.subscriptions.get(t)??new Set;return s.add(e),this.subscriptions.set(t,s),N.debug("Subscribed to event",{eventType:t}),()=>{s.delete(e),s.size===0&&this.subscriptions.delete(t),N.debug("Unsubscribed from event",{eventType:t});}}subscribeAll(t){return this.destroyed?(N.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{}):(this.wildcardSubscriptions.add(t),N.debug("Subscribed to all events"),()=>{this.wildcardSubscriptions.delete(t),N.debug("Unsubscribed from all events");})}async publish(t){if(this.destroyed){N.warn("Cannot publish to destroyed SdkEventBus",{type:t.type});return}N.debug("Publishing event",{type:t.type});let e=this.collectCallbacks(t);if(e.length===0){N.debug("No subscribers for event",{type:t.type});return}let s=await Promise.allSettled(e.map(async r=>{try{await r(t);}catch(a){throw N.error("Event callback error",{type:t.type,error:a instanceof Error?a.message:String(a)}),a}})),n=s.filter(r=>r.status==="fulfilled").length,i=s.filter(r=>r.status==="rejected").length;i>0?N.warn("Event callbacks completed with errors",{type:t.type,fulfilled:n,rejected:i}):N.debug("Event callbacks completed",{type:t.type,count:n});}publishSync(t){if(this.destroyed)return;let e=this.collectCallbacks(t);for(let s of e)Promise.resolve().then(()=>s(t)).catch(n=>{N.error("Event callback error (sync)",{type:t.type,error:n instanceof Error?n.message:String(n)});});}collectCallbacks(t){let e=[],s=this.subscriptions.get(t.type);return s&&e.push(...s),e.push(...this.wildcardSubscriptions),e}subscriberCount(t){return t?this.subscriptions.get(t)?.size??0:this.totalSubscribers()}totalSubscribers(){let t=this.wildcardSubscriptions.size;for(let e of this.subscriptions.values())t+=e.size;return t}hasSubscribers(t){return t?(this.subscriptions.get(t)?.size??0)>0||this.wildcardSubscriptions.size>0:this.totalSubscribers()>0}clear(){this.subscriptions.clear(),this.wildcardSubscriptions.clear(),N.debug("All subscriptions cleared");}destroy(){this.clear(),this.destroyed=true,N.info("SdkEventBus destroyed");}isDestroyed(){return this.destroyed}};var x=Log.create({service:"sdk-event-bridge"}),Ie=class{constructor(t,e,s){a(this,"sdk");a(this,"sdkEventBus");a(this,"abortController",null);a(this,"started",false);a(this,"sessionFilter");a(this,"_cachedPrimaryAgents",null);a(this,"_messageMetaCache",new Map);this.sdk=t,this.sdkEventBus=e,this.sessionFilter=s;}async getMessageMeta(t,e){let s=`${t}:${e}`,n=this._messageMetaCache.get(s);if(n)return n;let i=await this.sdk.session.message({sessionId:t,messageId:e},{throwOnError:true}).then(a=>a.data).catch(a=>{x.error("unexpected error when fetching message",{error:a,sessionId:t,messageId:e});});if(!i)return;let r={role:i.info.role,agent:i.info.agent};return this._messageMetaCache.set(s,r),r}clearMessageMetaCache(t){let e=`${t}:`;for(let s of this._messageMetaCache.keys())s.startsWith(e)&&this._messageMetaCache.delete(s);}async pushSessionEvent(t){let e=t.properties.sessionId??"";if(!e){x.debug("Dropping session event without sessionId",{type:t.type});return}await this.sdkEventBus?.publish({type:"sdk.session_update",properties:{sessionId:e,sessionEvent:t,timestamp:Date.now()}});}async start(){if(this.started){x.warn("SdkEventBridge already started");return}this.started=true,this.abortController=new AbortController,x.info("Starting SDK event bridge"),this.runEventLoop().catch(t=>{if(this.abortController?.signal.aborted){x.debug("Event loop stopped due to abort");return}x.error("Event loop failed",{error:t instanceof Error?t.message:String(t)}),this.sdkEventBus?.publish({type:"sdk.error",properties:{error:t instanceof Error?t.message:String(t),context:{source:"event_loop"},timestamp:Date.now()}});});}async stop(){this.started&&(x.info("Stopping SDK event bridge"),this.started=false,this.abortController?.abort(),this.abortController=null,this._messageMetaCache.clear(),this._cachedPrimaryAgents=null,x.info("SDK event bridge stopped"));}isStarted(){return this.started}async runEventLoop(){for(;;){if(this.abortController?.signal.aborted){x.debug("Event loop aborted");return}try{let t=this.abortController?.signal;if(!t)return;if(t.aborted){x.debug("Event loop aborted before event call");return}let e=await this.sdk.global.event({signal:t});for await(let s of e.stream){if(this.abortController?.signal.aborted){x.debug("Event loop aborted during iteration");return}let n=s?.payload;n&&await this.handleEvent(n).catch(i=>{x.error("Failed to handle event",{error:i instanceof Error?i.message:String(i),type:n.type});});}}catch(t){if(this.abortController?.signal.aborted){x.debug("Event loop aborted, not reconnecting");return}x.error("Event stream error, reconnecting...",{error:t instanceof Error?t.message:String(t)}),await new Promise(e=>setTimeout(e,1e3));}}}async handleEvent(t){switch(x.debug("Handling event",{type:t.type}),t.type){case "permission.asked":await this.handlePermissionAsked(t.properties);break;case "message.part.updated":await this.handleMessagePartUpdated(t.properties);break;case "session.status":await this.handleSessionStatus(t.properties);break;case "session.deleted":await this.handleSessionDeleted(t.properties);break;default:x.debug("Unknown event type, ignoring",{type:t.type});}}async handleSessionDeleted(t){let{sessionId:e}=t;this.sessionFilter&&!this.sessionFilter(e)||(this.clearMessageMetaCache(e),x.debug("Publishing session deleted event to SdkEventBus",{sessionId:e}),await this.sdkEventBus?.publish({type:"sdk.session_deleted",properties:{sessionId:e,timestamp:Date.now()}}));}async handlePermissionAsked(t){let{id:e,sessionId:s,permission:n,tool:i,metadata:r}=t;this.sessionFilter&&!this.sessionFilter(s)||(x.debug("Publishing permission request to SdkEventBus",{id:e,sessionId:s,permission:n}),await this.sdkEventBus?.publish({type:"sdk.permission_request",properties:{requestId:e,sessionId:s,permission:n,tool:i,metadata:r,timestamp:Date.now()}}));}async handleMessagePartUpdated(t){let{part:e,delta:s}=t;if(this.sessionFilter&&!this.sessionFilter(e.sessionId))return;x.debug("Handling message part update",{type:e.type,sessionId:e.sessionId,messageId:e.messageId});let n=await this.getMessageMeta(e.sessionId,e.messageId);n?.role==="assistant"&&(n.agent&&await this.shouldFilterAgent(n.agent)||(e.type==="tool"?await this.handleToolPart(e):e.type==="text"?await this.handleTextPart(e,s):e.type==="reasoning"?await this.handleReasoningPart(e,s):e.type==="step-start"?await this.handleStepStartPart(e):e.type==="step-finish"&&await this.handleStepFinishPart(e)));}async handleToolPart(t){let{sessionId:e,callId:s,tool:n,state:i}=t,r;switch(i.status){case "pending":r={status:"pending"};break;case "running":r={status:"running",input:i.input};break;case "completed":r={status:"completed",input:i.input,output:i.output,title:i.title,metadata:i.metadata};break;case "error":r={status:"error",input:i.input,error:i.error};break;default:x.warn("Unknown tool state, falling back to pending",{tool:n,callId:s,status:i.status}),r={status:"pending"};break}await this.pushSessionEvent({type:"part.updated",properties:{sessionId:e,part:{type:"tool",tool:n,callId:s,state:r}}});}async handleTextPart(t,e){if(t.ignored===true||!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"text",text:n,messageId:t.messageId,time:t.time}}});}async handleStepStartPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-start",messageId:t.messageId}}});}async handleStepFinishPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-finish",messageId:t.messageId,tokens:t.tokens}}});}async handleReasoningPart(t,e){if(!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"reasoning",text:n,messageId:t.messageId,time:t.time}}});}async handleSessionStatus(t){let{sessionId:e,status:s}=t;await this.pushSessionEvent({type:"session.status",properties:{sessionId:e,status:s}}),s.type==="idle"&&this.clearMessageMetaCache(e),x.debug("Session status update sent",{sessionId:e,status:s.type});}async shouldFilterAgent(t){if(!this._cachedPrimaryAgents)try{let s=(await this.sdk.app.agents({})).data||[];this._cachedPrimaryAgents=new Set(s.filter(n=>n.mode==="primary"&&n.hidden!==!0).map(n=>n.name));}catch{this._cachedPrimaryAgents=new Set;}return !this._cachedPrimaryAgents.has(t)}};var mt=Log.create({service:"sdk-message-collector"}),cs={includeThinking:false,includeToolDetails:false,includeToolOutput:false,includeSteps:false},Un={includeThinking:true,includeToolDetails:true,includeToolOutput:true,includeSteps:true},ge=class{constructor(t=cs){a(this,"filterConfig",t);a(this,"events",[]);a(this,"isComplete",false);a(this,"hasTextEnd",false);a(this,"hasStepFinish",false);a(this,"error","");a(this,"sessionStatus","idle");a(this,"sessionId","");a(this,"messageId","");mt.debug("MessageEventCollector created",{filterConfig:t});}addEvent(t){if(!this.shouldIncludeEvent(t)){this.checkCompletion(t);return}this.events.push(t),this.checkCompletion(t);}shouldIncludeEvent(t){if(t.type!=="part.updated")return true;let e=t.properties.part;return e?!(e.type==="reasoning"&&!this.filterConfig.includeThinking||e.type==="tool"&&e.state?.status==="running"&&!this.filterConfig.includeToolDetails||(e.type==="step-start"||e.type==="step-finish")&&!this.filterConfig.includeSteps):true}checkCompletion(t){if(t.properties.sessionId&&(this.sessionId=t.properties.sessionId),t.properties.info?.id&&(this.sessionId=t.properties.info.id),t.type==="part.updated"){let e=t.properties.part;if(!e)return;e.type==="text"&&e.time?.end?(this.hasTextEnd=true,e.messageId&&(this.messageId=e.messageId)):e.type==="step-finish"&&(this.hasStepFinish=true,e.messageId&&(this.messageId=e.messageId));return}if(t.type==="session.status"){let e=t.properties.status?.type;(e==="idle"||e==="busy"||e==="retry")&&(this.sessionStatus=e);return}t.type==="session.error"&&(this.sessionStatus="error",t.properties.error?.data?.message&&(this.error=t.properties.error.data.message));}checkComplete(){return this.isComplete=!!this.error||this.hasTextEnd&&this.hasStepFinish,this.isComplete&&mt.debug("MessageEventCollector.checkComplete",{isComplete:this.isComplete,hasError:!!this.error,hasTextEnd:this.hasTextEnd,hasStepFinish:this.hasStepFinish}),this.isComplete}hasTextEndReady(){return this.hasTextEnd}isTextOnlyComplete(){return this.hasTextEnd&&!this.hasStepFinish&&!this.error}resetForNextMessage(){this.hasTextEnd=false,this.hasStepFinish=false,this.error="",this.isComplete=false,this.events=[];}getSessionStatus(){return this.sessionStatus}getCurrentMessageId(){return this.messageId}assembleMessage(){let t=this.events.filter(a=>a.type==="part.updated"&&a.properties.part?.type==="text"&&a.properties.part?.time?.end).map(a=>a.properties.part.text??"").join(""),e;if(this.filterConfig.includeThinking){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="reasoning"&&c.properties.part?.time?.end).map(c=>{let d=c.properties.part.text??"";return d=d.replace("[REDACTED]","").trim(),d}).filter(c=>c.length>0).join("");a&&(e=a);}let s;if(this.filterConfig.includeToolDetails){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="tool"&&(c.properties.part?.state?.status==="completed"||c.properties.part?.state?.status==="error"));a.length>0&&(s=a.map(c=>{let d=c.properties.part,g=d.state;return {name:d.tool,callId:d.callId,title:g.title,status:g.status,output:this.filterConfig.includeToolOutput?g.output:void 0,error:g.error,input:g.input}}));}let i=this.events.find(a=>a.type==="part.updated"&&a.properties.part?.type==="step-finish")?.properties.part?.tokens,r={role:"assistant",text:t,thinking:e,tools:s,metadata:{sessionId:this.sessionId,sessionStatus:this.sessionStatus,messageId:this.messageId,timestamp:Date.now(),tokens:i?{input:i.input,output:i.output,total:i.input+i.output+i.reasoning}:void 0,error:this.error||void 0}};return mt.debug("Message assembled",{textLength:t.length,thinkingLength:e?.length??0,toolsCount:s?.length??0,isComplete:this.isComplete,includeThinking:this.filterConfig.includeThinking,includeToolDetails:this.filterConfig.includeToolDetails,includeToolOutput:this.filterConfig.includeToolOutput}),r}reset(){this.events=[],this.isComplete=false,this.hasTextEnd=false,this.hasStepFinish=false,this.error="",this.sessionStatus="idle",this.sessionId="",this.messageId="",mt.debug("MessageEventCollector.reset",{hasTextEnd:false,hasStepFinish:false});}};var O=class extends Error{constructor(e,s,n){super(e,{cause:n});a(this,"code",s);this.name="GatewayAgentError";}},Ae=class{constructor(t,e={}){a(this,"sdk",t);a(this,"log",Log.create({service:"gateway:agent"}));a(this,"config");a(this,"filterConfig");a(this,"sessionId");a(this,"eventBus");a(this,"eventBridge");a(this,"bridgeStarted",false);this.config=e,this.filterConfig={includeThinking:e.filterConfig?.includeThinking??false,includeToolDetails:e.filterConfig?.includeToolDetails??false,includeToolOutput:e.filterConfig?.includeToolOutput??true,includeSteps:e.filterConfig?.includeSteps??false},this.eventBus=new ve,this.eventBridge=new Ie(t,this.eventBus);}async getCommandPart(t){let e=t.parts?.find(n=>n.type==="command");if(!e)return;let s=false;try{s=(await this.sdk.command.get({name:e.command})).data?.commandType==="local";}catch(n){this.log.warn("Failed to get command",{command:e.command,error:String(n)});}return {...e,local:s}}async run(t,e){this.log.debug("GatewayAgent.run: starting",{source:t.source,agent:t.agent,partsCount:t.parts?.length??0});let s=await this.getCommandPart(t);return s?s.local?this.runLocalCommand(t,s):this.runPromptCommand(t,s,e):this.runPrompt(t,e)}async runLocalCommand(t,e){this.log.debug("GatewayAgent.runLocalCommand: starting",{command:e.command,arguments:e.arguments});try{let s=await this.ensureSession(t.source);if(!s)throw new O("Failed to create or get session","NO_SESSION");let i=(await this.sdk.session.command({sessionId:s,command:e.command,arguments:e.arguments??"",agent:t.agent,model:t.model?`${t.model.providerId}/${t.model.modelId}`:void 0})).data;return this.log.debug("GatewayAgent.runLocalCommand: completed",{sessionId:s,success:i?.success}),{output:i?.output??"",title:t.title??`Command: ${e.command}`,metadata:{sessionId:s,source:t.source,agent:t.agent,success:i?.success,error:i?.error}}}catch(s){throw this.log.error("GatewayAgent.runLocalCommand: failed",{error:s instanceof Error?s.message:String(s)}),new O(s instanceof Error?s.message:String(s),"COMMAND_ERROR",s instanceof Error?s:void 0)}}async runPromptCommand(t,e,s){this.log.debug("GatewayAgent.runPromptCommand: starting",{command:e.command,arguments:e.arguments});try{let n=await this.ensureSession(t.source);if(!n)throw new O("Failed to create or get session","NO_SESSION");let i=new ge(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=!0);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,S=null,C=()=>{S&&clearTimeout(S);},_=E=>{C();try{a();}catch{}g({messages:p,finishReason:E});};S=setTimeout(()=>{this.log.warn("runPromptCommand: event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),_("timeout");},12e4),a=this.eventBus.subscribeAll(E=>{if(E.type==="sdk.session_update"){let F=E.properties;if(F.sessionId!==n)return;if(i.addEvent(F.sessionEvent),i.checkComplete()){let R=i.assembleMessage();if(p.push(R),i.resetForNextMessage(),!R.text||R.text.trim().length===0){this.log.debug("runPromptCommand: skipping onMessage for empty-text message",{messageId:R.metadata.messageId,hasThinking:!!R.thinking,hasTools:(R.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(R)).catch(te=>{this.log.error("runPromptCommand: onMessage callback error",{error:te instanceof Error?te.message:String(te)});});}}let k=i.getSessionStatus();if(h==="busy"&&k==="idle"&&p.length>0){this.log.debug("runPromptCommand: turn complete (busy -> idle)",{messageCount:p.length}),_("idle");return}(k==="idle"||k==="busy"||k==="retry")&&(h=k);});});await this.sdk.session.command({sessionId:n,command:e.command,arguments:e.arguments??"",agent:t.agent,model:t.model?`${t.model.providerId}/${t.model.modelId}`:void 0});let d=await c;try{a();}catch{}return this.log.debug("GatewayAgent.runPromptCommand: completed",{sessionId:n,command:e.command,messageCount:d.messages.length,finishReason:d.finishReason}),this.assembleResult(d.messages,n,t,d.finishReason)}catch(n){throw this.log.error("GatewayAgent.runPromptCommand: failed",{error:n instanceof Error?n.message:String(n)}),new O(n instanceof Error?n.message:String(n),"COMMAND_ERROR",n instanceof Error?n:void 0)}}async runPrompt(t,e){this.log.debug("GatewayAgent.runPrompt: starting",{source:t.source,agent:t.agent});try{let s=await this.ensureSession(t.source);if(!s)throw new O("Failed to create or get session","NO_SESSION");let n=await this.sendAndCollect(s,t,e);return this.log.debug("GatewayAgent.runPrompt: completed",{sessionId:s,outputLength:n.output.length,messageCount:Array.isArray(n.metadata.messages)?n.metadata.messages.length:void 0}),n}catch(s){throw this.log.error("GatewayAgent.runPrompt: failed",{error:s instanceof Error?s.message:String(s)}),s instanceof O?s:new O(s instanceof Error?s.message:String(s),"EXECUTION_ERROR",s instanceof Error?s:void 0)}}async ensureSession(t){if(t)try{if((await this.sdk.session.get({sessionId:t})).data)return this.sessionId=t,this.log.debug("Using existing session",{sessionId:t}),t}catch{this.log.debug("Session not found, will create new",{sessionId:t});}let e=await this.sdk.session.create({title:"Gateway Session"});if(!e.data?.id)throw new O("Failed to create session","CREATE_SESSION_FAILED");return this.sessionId=e.data.id,this.log.debug("Created new session",{sessionId:this.sessionId}),this.sessionId}async sendAndCollect(t,e,s){let n=[];for(let g of e.parts??[])if(g.type==="text")n.push({type:"text",text:g.text??""});else if(g.type==="image"){let p="";typeof g.image=="string"?p=g.image:g.image instanceof URL?p=g.image.toString():g.image instanceof Uint8Array&&(p=`data:${g.mime??"image/png"};base64,${Buffer.from(g.image).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"image/png"});}else if(g.type==="file"){let p="";typeof g.data=="string"?p=g.data:g.data instanceof URL?p=g.data.toString():g.data instanceof Uint8Array&&(p=`data:${g.mime??"application/octet-stream"};base64,${Buffer.from(g.data).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"application/octet-stream"});}n.length===0&&n.push({type:"text",text:""});let i=new ge(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=true);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,S=null,C=()=>{S&&clearTimeout(S);},_=E=>{C();try{a();}catch{}g({messages:p,finishReason:E});};S=setTimeout(()=>{this.log.warn("Event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),_("timeout");},12e4),a=this.eventBus.subscribeAll(E=>{if(E.type==="sdk.session_update"){let F=E.properties;if(F.sessionId!==t)return;if(i.addEvent(F.sessionEvent),i.checkComplete()){let R=i.assembleMessage();if(p.push(R),i.resetForNextMessage(),this.log.debug("sendAndCollect: message complete",{messageId:R.metadata.messageId,messageCount:p.length,textLength:R.text?.length??0}),!R.text||R.text.trim().length===0){this.log.debug("sendAndCollect: skipping onMessage for empty-text message",{messageId:R.metadata.messageId,hasThinking:!!R.thinking,hasTools:(R.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(R)).catch(te=>{this.log.error("sendAndCollect: onMessage callback error",{error:te instanceof Error?te.message:String(te)});});}}let k=i.getSessionStatus();if(h==="busy"&&k==="idle"&&p.length>0){this.log.debug("sendAndCollect: turn complete (busy -> idle)",{messageCount:p.length}),_("idle");return}(k==="idle"||k==="busy"||k==="retry")&&(h=k);});});await this.sdk.session.prompt({sessionId:t,parts:n,system:e.system,agent:e.agent,model:e.model?{providerId:e.model.providerId,modelId:e.model.modelId}:void 0});let d=await c;try{a();}catch{}return this.assembleResult(d.messages,t,e,d.finishReason)}assembleResult(t,e,s,n="idle"){let i=t.map(c=>this.formatOutput(c)).filter(c=>c.length>0).join(`
1
+ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Identifier,Filesystem,TruncateContent,Fetch,PKG,createServer}from'@easbot/utils';import u,{z as z$1}from'zod';import*as pe from'path';import pe__default,{join,extname,basename}from'path';import*as se from'fs';import se__default,{existsSync,watch,readFileSync,writeFileSync,mkdirSync,chmodSync,unlinkSync}from'fs';import*as W from'fs/promises';import W__default,{readFile}from'fs/promises';import {WebSocketServer}from'ws';import Wi from'https';import Hi from'http';import zi,{randomUUID,createHash,randomBytes,createCipheriv,createDecipheriv}from'crypto';import {pathToFileURL,fileURLToPath}from'url';import {homedir,tmpdir}from'os';import {HookEvent}from'@easbot/plugin';function A(o,t,e,s){return {id:Identifier.ascending("message"),sessionId:o,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 wn(o,t,e,s){return A(o,t,[{type:"text",text:e}],s)}function Ve(o){let t={platform:o.channel?.platform??"api",channelId:o.channel?.channelId??"unknown",chatId:o.channel?.chatId,userId:o.channel?.userId,chatType:o.channel?.chatType,chatTitle:o.channel?.chatTitle};return {id:o.id,sessionId:o.sessionId,type:o.type,content:Array.isArray(o.content)?o.content:[{type:"text",text:String(o.content??"")}],metadata:{channel:t,replyToMessageId:o.replyToMessageId,processorId:o.processorId,agent:o.agent,proactive:o.proactive??!o.replyToMessageId},timestamp:o.timestamp??Date.now()}}function Je(o){if(!o.platform)throw new Error("Invalid session: platform is required");if(!o.channelId)throw new Error("Invalid session: channelId is required");let t=o.chatId??"",e=o.userId??t;if(!t&&!o.userId)throw new Error(`Invalid session: chatId and userId cannot both be empty. platform=${o.platform}, channelId=${o.channelId}`);return [o.platform,o.channelId,t,e].join("_")}function Qe(){return {status:"active",messageCount:0,lastMessageAt:null}}function Xe(o,t){if(!o||!t)throw new Error("platform and stableId are required");return `${o}:${t}`}function Ye(o){if(!o||typeof o!="string")return null;let t=o.indexOf(":");if(t<=0||t>=o.length-1)return null;let e=o.slice(0,t),s=o.slice(t+1);return !e||!s?null:{platform:e,stableId:s}}function Et(o){let{platform:t,stableId:e,profile:s={},aliases:n={},metadata:i}=o;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:Xe(t,e),platform:t,stableId:e,aliases:{...n},profile:{...s},createdAt:r,lastSeenAt:r,metadata:i}}function Rt(o,t){return `sub_${o}_${t}`}var In=Log.create({service:"gateway:config"});u.enum(["telegram","slack","feishu","wechat","weixin","webchat","signal","nostr","dingtalk"]);u.enum(["low","medium","high","critical"]);var et=u.object({enabled:u.boolean().default(true),botToken:u.string().describe("Telegram Bot Token"),webhookUrl:u.string().optional().describe("Webhook URL for receiving updates"),polling:u.object({enabled:u.boolean().default(true),interval:u.number().int().positive().optional().describe("Polling interval in ms"),timeout:u.number().int().positive().optional().default(30).describe("Long polling timeout in seconds")}).refine(o=>o===void 0||o.enabled,{message:"polling.enabled must be true when polling is configured"}).optional(),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),tt=u.object({enabled:u.boolean().default(true),botToken:u.string().describe("Slack Bot Token (xoxb-*)"),appToken:u.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:u.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),st=u.object({enabled:u.boolean().default(true),appId:u.string().describe("Feishu App ID"),appSecret:u.string().describe("Feishu App Secret"),encryptKey:u.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:u.string().optional().describe("Feishu Verification Token"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),nt=u.object({enabled:u.boolean().default(true),mode:u.enum(["official","wecom"]).default("official"),appId:u.string().describe("WeChat App ID"),appSecret:u.string().describe("WeChat App Secret"),token:u.string().optional().describe("WeChat Token for message verification"),encodingAESKey:u.string().optional().describe("WeChat Encoding AES Key"),agentId:u.string().optional().describe("WeCom Agent ID"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),An=u.object({enabled:u.boolean().default(true),stateDir:u.string().optional().describe("Override the default account persistence directory (default: ~/.easbot/channels/weixin)"),baseUrl:u.string().optional().describe("Override the iLink API baseUrl (default: https://ilinkai.weixin.qq.com)"),cdnBaseUrl:u.string().optional().describe("Override the CDN baseUrl (default: https://novac2c.cdn.weixin.qq.com/c2c)"),maxMessageLength:u.number().int().positive().optional().default(4e3),timeout:u.number().int().positive().optional().default(3e4)}),it=u.object({enabled:u.boolean().default(true),path:u.string().optional().default("/"),heartbeatInterval:u.number().int().positive().optional().default(3e4),connectionTimeout:u.number().int().positive().optional().default(36e5),maxConnections:u.number().int().positive().optional().default(1e3),cors:u.boolean().optional().default(true)}),rt=u.object({enabled:u.boolean().default(true),serviceUrl:u.string().optional().default("https://chat.signal.org"),phoneNumber:u.string().describe("Signal phone number"),password:u.string().optional().describe("Signal account password"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),at=u.object({enabled:u.boolean().default(true),relays:u.array(u.string()).min(1).describe("Nostr relay URLs"),privateKey:u.string().optional().describe("Nostr private key (hex)"),publicKey:u.string().optional().describe("Nostr public key (hex)"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),Pn=u.object({enabled:u.boolean().default(true),appKey:u.string().describe("DingTalk AppKey"),appSecret:u.string().describe("DingTalk AppSecret"),token:u.string().optional().describe("DingTalk token for signature verification"),encryptKey:u.string().optional().describe("DingTalk encrypt key for message encryption"),webhook:u.object({enabled:u.boolean().default(true),path:u.string().optional().default("/dingtalk/webhook"),port:u.number().int().positive().optional().describe("Webhook server port")}).optional(),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),is=u.object({telegram:et.optional(),slack:tt.optional(),feishu:st.optional(),wechat:nt.optional(),weixin:An.optional(),webchat:it.optional(),signal:rt.optional(),nostr:at.optional(),dingtalk:Pn.optional()}),rs=u.object({enabled:u.boolean().default(false),cert:u.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:u.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:u.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:u.string().optional().describe("Path to SSL key file (alias of key)"),ca:u.string().optional().describe("Path to CA certificate file"),forceRedirect:u.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:u.number().int().positive().optional().default(80).describe("HTTP redirect port")}),xn=u.object({name:u.string().describe("Token name/description"),value:u.string().describe("Token value"),permissions:u.array(u.string()).default(["*"]).describe("Associated permissions"),expiresAt:u.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:u.string().optional().describe("Token description")}),Mn=u.object({enabled:u.boolean().default(true),tokens:u.array(xn).default([]).describe("List of valid tokens"),onInvalid:u.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:u.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:u.array(u.string()).default([]).describe("Default permissions for anonymous users")}),kn=u.object({enabled:u.boolean().default(false),authorizationServer:u.string().describe("OAuth2 authorization server URL"),clientId:u.string().describe("OAuth2 client ID"),clientSecret:u.string().describe("OAuth2 client secret"),tokenValidationEndpoint:u.string().describe("OAuth2 token validation endpoint"),scope:u.array(u.string()).default([]).describe("OAuth2 scopes")}),as=u.object({type:u.enum(["token","oauth2"]).default("token"),token:Mn.optional(),oauth2:kn.optional()}),os=u.object({mode:u.enum(["pull","push","both"]).default("both"),interval:u.number().int().positive().default(3e4),pushEvents:u.array(u.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:u.enum(["latest","local","remote"]).default("latest")}),Tn=u.object({id:u.string().describe("Gateway node ID"),address:u.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:u.boolean().default(true),metadata:u.record(u.string(),u.any()).optional()}),cs=u.object({nodeId:u.string().describe("Current gateway node ID"),nodes:u.array(Tn).default([]).describe("Other gateway nodes in the cluster"),sync:os.optional()}),ot=u.object({maxConnectionsPerChannel:u.number().int().positive().default(100),idleTimeout:u.number().int().positive().default(3e5),reuseStrategy:u.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:u.number().int().positive().default(6e4),acquireTimeout:u.number().int().positive().default(5e3),warmupCount:u.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),ct=u.object({maxLength:u.number().int().positive().default(1e4),concurrency:u.number().int().positive().default(100),batchSize:u.number().int().positive().default(10),batchTimeout:u.number().int().positive().default(100),priorityLevels:u.number().int().positive().default(4)}),lt=u.object({failureThreshold:u.number().int().positive().default(5),successThreshold:u.number().int().positive().default(3),timeout:u.number().int().positive().default(3e4),halfOpenDuration:u.number().int().positive().default(15e3)}),dt=u.object({heartbeatInterval:u.number().int().positive().default(6e4),heartbeatTimeout:u.number().int().positive().default(3e5),heartbeatCheckInterval:u.number().int().positive().default(3e5),autoDeregisterTimeout:u.number().int().positive().default(6e5),maxAgents:u.number().int().positive().default(100),persistenceFile:u.string().optional().describe("Path to persist agent registrations"),maxRegistrations:u.number().int().positive().default(1e3)}),gt=u.object({sessionTimeout:u.number().int().positive().default(18e5),resumeGracePeriod:u.number().int().positive().default(3e5),maxSessions:u.number().int().positive().default(1e4),persistenceFile:u.string().optional().describe("Path to persist sessions")}),ut=u.object({enabled:u.boolean().default(true),port:u.number().int().positive().default(8080),hostname:u.string().default("localhost"),path:u.string().optional().default("/"),maxConnections:u.number().int().positive().optional().default(1e3),connectionTimeout:u.number().int().positive().optional().default(36e5),heartbeatInterval:u.number().int().positive().optional().default(3e4),sessionExpireMs:u.number().int().positive().optional().default(36e5),https:rs.optional(),auth:as.optional(),cors:u.boolean().default(true),corsOrigins:u.array(u.string()).optional(),mdns:u.boolean().default(false),mdnsDomain:u.string().optional().default("gateway.easbot.local")}),_n=u.object({channel:u.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:u.array(u.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),En=u.enum(["localAgent","subAgent","both"]),Rn=u.object({mode:En.default("localAgent").describe("Agent processing mode: localAgent, subAgent, or both"),localAgentPriority:u.number().int().min(1).max(10).default(1).describe("Priority for localAgent (lower = higher priority)"),subAgentPriority:u.number().int().min(1).max(10).default(2).describe("Priority for subAgent (lower = higher priority)"),timeout:u.number().int().positive().optional().default(3e5).describe("Timeout for agent execution in milliseconds"),retryOnFailure:u.boolean().default(true).describe("Retry with subAgent when localAgent fails")}),pt=u.object({autoRegister:u.boolean().default(true).describe("Whether to auto-register agent on startup"),heartbeatInterval:u.number().int().positive().default(3e4).describe("Heartbeat interval in milliseconds"),maxReconnectAttempts:u.number().int().min(0).default(5).describe("Maximum reconnect attempts"),reconnectDelay:u.number().int().positive().default(3e3).describe("Reconnect delay in milliseconds"),heartbeatTimeout:u.number().int().positive().default(9e4).describe("Heartbeat timeout in milliseconds")}),Ze=u.object({server:ut.optional(),channels:is.optional(),cluster:cs.optional(),connectionPool:ot.optional(),messageQueue:ct.optional(),circuitBreaker:lt.optional(),agentRegistry:dt.optional(),session:gt.optional(),defaults:_n.optional(),agentProcessing:Rn.optional(),client:pt.optional().describe("Gateway client config for agent registration"),defaultAgent:u.string().optional().describe("Default agent ID for routing"),logLevel:u.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(u.unknown());function Dt(o){let t=Ze.safeParse(o);return t.success||In.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:Ze.parse({})}function Dn(o){return Ze.parse(o)}var N=Log.create({service:"sdk-event-bus"}),ht=(i=>(i.SDK_SESSION_STATUS="agent.status",i.SDK_ERROR="sdk.error",i.SDK_SESSION_UPDATE="sdk.session_update",i.SDK_PERMISSION_REQUEST="sdk.permission_request",i.SDK_SESSION_DELETED="sdk.session_deleted",i))(ht||{});z$1.object({sessionId:z$1.string(),status:z$1.enum(["idle","busy","retry"]),timestamp:z$1.number()});z$1.object({error:z$1.string(),context:z$1.record(z$1.string(),z$1.any()).optional(),timestamp:z$1.number()});z$1.object({sessionId:z$1.string(),sessionEvent:z$1.unknown(),timestamp:z$1.number()});z$1.object({requestId:z$1.string(),sessionId:z$1.string(),permission:z$1.string(),tool:z$1.object({callId:z$1.string().optional()}).optional(),metadata:z$1.record(z$1.string(),z$1.any()).optional(),timestamp:z$1.number()});z$1.object({sessionId:z$1.string(),timestamp:z$1.number()});var ve=class{constructor(){a(this,"subscriptions",new Map);a(this,"wildcardSubscriptions",new Set);a(this,"destroyed",false);}subscribe(t,e){if(this.destroyed)return N.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{};let s=this.subscriptions.get(t)??new Set;return s.add(e),this.subscriptions.set(t,s),N.debug("Subscribed to event",{eventType:t}),()=>{s.delete(e),s.size===0&&this.subscriptions.delete(t),N.debug("Unsubscribed from event",{eventType:t});}}subscribeAll(t){return this.destroyed?(N.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{}):(this.wildcardSubscriptions.add(t),N.debug("Subscribed to all events"),()=>{this.wildcardSubscriptions.delete(t),N.debug("Unsubscribed from all events");})}async publish(t){if(this.destroyed){N.warn("Cannot publish to destroyed SdkEventBus",{type:t.type});return}N.debug("Publishing event",{type:t.type});let e=this.collectCallbacks(t);if(e.length===0){N.debug("No subscribers for event",{type:t.type});return}let s=await Promise.allSettled(e.map(async r=>{try{await r(t);}catch(a){throw N.error("Event callback error",{type:t.type,error:a instanceof Error?a.message:String(a)}),a}})),n=s.filter(r=>r.status==="fulfilled").length,i=s.filter(r=>r.status==="rejected").length;i>0?N.warn("Event callbacks completed with errors",{type:t.type,fulfilled:n,rejected:i}):N.debug("Event callbacks completed",{type:t.type,count:n});}publishSync(t){if(this.destroyed)return;let e=this.collectCallbacks(t);for(let s of e)Promise.resolve().then(()=>s(t)).catch(n=>{N.error("Event callback error (sync)",{type:t.type,error:n instanceof Error?n.message:String(n)});});}collectCallbacks(t){let e=[],s=this.subscriptions.get(t.type);return s&&e.push(...s),e.push(...this.wildcardSubscriptions),e}subscriberCount(t){return t?this.subscriptions.get(t)?.size??0:this.totalSubscribers()}totalSubscribers(){let t=this.wildcardSubscriptions.size;for(let e of this.subscriptions.values())t+=e.size;return t}hasSubscribers(t){return t?(this.subscriptions.get(t)?.size??0)>0||this.wildcardSubscriptions.size>0:this.totalSubscribers()>0}clear(){this.subscriptions.clear(),this.wildcardSubscriptions.clear(),N.debug("All subscriptions cleared");}destroy(){this.clear(),this.destroyed=true,N.info("SdkEventBus destroyed");}isDestroyed(){return this.destroyed}};var x=Log.create({service:"sdk-event-bridge"}),Ie=class{constructor(t,e,s){a(this,"sdk");a(this,"sdkEventBus");a(this,"abortController",null);a(this,"started",false);a(this,"sessionFilter");a(this,"_cachedPrimaryAgents",null);a(this,"_messageMetaCache",new Map);this.sdk=t,this.sdkEventBus=e,this.sessionFilter=s;}async getMessageMeta(t,e){let s=`${t}:${e}`,n=this._messageMetaCache.get(s);if(n)return n;let i=await this.sdk.session.message({sessionId:t,messageId:e},{throwOnError:true}).then(a=>a.data).catch(a=>{x.error("unexpected error when fetching message",{error:a,sessionId:t,messageId:e});});if(!i)return;let r={role:i.info.role,agent:i.info.agent};return this._messageMetaCache.set(s,r),r}clearMessageMetaCache(t){let e=`${t}:`;for(let s of this._messageMetaCache.keys())s.startsWith(e)&&this._messageMetaCache.delete(s);}async pushSessionEvent(t){let e=t.properties.sessionId??"";if(!e){x.debug("Dropping session event without sessionId",{type:t.type});return}await this.sdkEventBus?.publish({type:"sdk.session_update",properties:{sessionId:e,sessionEvent:t,timestamp:Date.now()}});}async start(){if(this.started){x.warn("SdkEventBridge already started");return}this.started=true,this.abortController=new AbortController,x.info("Starting SDK event bridge"),this.runEventLoop().catch(t=>{if(this.abortController?.signal.aborted){x.debug("Event loop stopped due to abort");return}x.error("Event loop failed",{error:t instanceof Error?t.message:String(t)}),this.sdkEventBus?.publish({type:"sdk.error",properties:{error:t instanceof Error?t.message:String(t),context:{source:"event_loop"},timestamp:Date.now()}});});}async stop(){this.started&&(x.info("Stopping SDK event bridge"),this.started=false,this.abortController?.abort(),this.abortController=null,this._messageMetaCache.clear(),this._cachedPrimaryAgents=null,x.info("SDK event bridge stopped"));}isStarted(){return this.started}async runEventLoop(){for(;;){if(this.abortController?.signal.aborted){x.debug("Event loop aborted");return}try{let t=this.abortController?.signal;if(!t)return;if(t.aborted){x.debug("Event loop aborted before event call");return}let e=await this.sdk.global.event({signal:t});for await(let s of e.stream){if(this.abortController?.signal.aborted){x.debug("Event loop aborted during iteration");return}let n=s?.payload;n&&await this.handleEvent(n).catch(i=>{x.error("Failed to handle event",{error:i instanceof Error?i.message:String(i),type:n.type});});}}catch(t){if(this.abortController?.signal.aborted){x.debug("Event loop aborted, not reconnecting");return}x.error("Event stream error, reconnecting...",{error:t instanceof Error?t.message:String(t)}),await new Promise(e=>setTimeout(e,1e3));}}}async handleEvent(t){switch(x.debug("Handling event",{type:t.type}),t.type){case "permission.asked":await this.handlePermissionAsked(t.properties);break;case "message.part.updated":await this.handleMessagePartUpdated(t.properties);break;case "session.status":await this.handleSessionStatus(t.properties);break;case "session.deleted":await this.handleSessionDeleted(t.properties);break;default:x.debug("Unknown event type, ignoring",{type:t.type});}}async handleSessionDeleted(t){let{sessionId:e}=t;this.sessionFilter&&!this.sessionFilter(e)||(this.clearMessageMetaCache(e),x.debug("Publishing session deleted event to SdkEventBus",{sessionId:e}),await this.sdkEventBus?.publish({type:"sdk.session_deleted",properties:{sessionId:e,timestamp:Date.now()}}));}async handlePermissionAsked(t){let{id:e,sessionId:s,permission:n,tool:i,metadata:r}=t;this.sessionFilter&&!this.sessionFilter(s)||(x.debug("Publishing permission request to SdkEventBus",{id:e,sessionId:s,permission:n}),await this.sdkEventBus?.publish({type:"sdk.permission_request",properties:{requestId:e,sessionId:s,permission:n,tool:i,metadata:r,timestamp:Date.now()}}));}async handleMessagePartUpdated(t){let{part:e,delta:s}=t;if(this.sessionFilter&&!this.sessionFilter(e.sessionId))return;x.debug("Handling message part update",{type:e.type,sessionId:e.sessionId,messageId:e.messageId});let n=await this.getMessageMeta(e.sessionId,e.messageId);n?.role==="assistant"&&(n.agent&&await this.shouldFilterAgent(n.agent)||(e.type==="tool"?await this.handleToolPart(e):e.type==="text"?await this.handleTextPart(e,s):e.type==="reasoning"?await this.handleReasoningPart(e,s):e.type==="step-start"?await this.handleStepStartPart(e):e.type==="step-finish"&&await this.handleStepFinishPart(e)));}async handleToolPart(t){let{sessionId:e,callId:s,tool:n,state:i}=t,r;switch(i.status){case "pending":r={status:"pending"};break;case "running":r={status:"running",input:i.input};break;case "completed":r={status:"completed",input:i.input,output:i.output,title:i.title,metadata:i.metadata};break;case "error":r={status:"error",input:i.input,error:i.error};break;default:x.warn("Unknown tool state, falling back to pending",{tool:n,callId:s,status:i.status}),r={status:"pending"};break}await this.pushSessionEvent({type:"part.updated",properties:{sessionId:e,part:{type:"tool",tool:n,callId:s,state:r}}});}async handleTextPart(t,e){if(t.ignored===true||!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"text",text:n,messageId:t.messageId,time:t.time}}});}async handleStepStartPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-start",messageId:t.messageId}}});}async handleStepFinishPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-finish",messageId:t.messageId,tokens:t.tokens}}});}async handleReasoningPart(t,e){if(!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"reasoning",text:n,messageId:t.messageId,time:t.time}}});}async handleSessionStatus(t){let{sessionId:e,status:s}=t;await this.pushSessionEvent({type:"session.status",properties:{sessionId:e,status:s}}),s.type==="idle"&&this.clearMessageMetaCache(e),x.debug("Session status update sent",{sessionId:e,status:s.type});}async shouldFilterAgent(t){if(!this._cachedPrimaryAgents)try{let s=(await this.sdk.app.agents({})).data||[];this._cachedPrimaryAgents=new Set(s.filter(n=>n.mode==="primary"&&n.hidden!==!0).map(n=>n.name));}catch{this._cachedPrimaryAgents=new Set;}return !this._cachedPrimaryAgents.has(t)}};var mt=Log.create({service:"sdk-message-collector"}),ls={includeThinking:false,includeToolDetails:false,includeToolOutput:false,includeSteps:false},Un={includeThinking:true,includeToolDetails:true,includeToolOutput:true,includeSteps:true},ge=class{constructor(t=ls){a(this,"filterConfig",t);a(this,"events",[]);a(this,"isComplete",false);a(this,"hasTextEnd",false);a(this,"hasStepFinish",false);a(this,"error","");a(this,"sessionStatus","idle");a(this,"sessionId","");a(this,"messageId","");mt.debug("MessageEventCollector created",{filterConfig:t});}addEvent(t){if(!this.shouldIncludeEvent(t)){this.checkCompletion(t);return}this.events.push(t),this.checkCompletion(t);}shouldIncludeEvent(t){if(t.type!=="part.updated")return true;let e=t.properties.part;return e?!(e.type==="reasoning"&&!this.filterConfig.includeThinking||e.type==="tool"&&e.state?.status==="running"&&!this.filterConfig.includeToolDetails||(e.type==="step-start"||e.type==="step-finish")&&!this.filterConfig.includeSteps):true}checkCompletion(t){if(t.properties.sessionId&&(this.sessionId=t.properties.sessionId),t.properties.info?.id&&(this.sessionId=t.properties.info.id),t.type==="part.updated"){let e=t.properties.part;if(!e)return;e.type==="text"&&e.time?.end?(this.hasTextEnd=true,e.messageId&&(this.messageId=e.messageId)):e.type==="step-finish"&&(this.hasStepFinish=true,e.messageId&&(this.messageId=e.messageId));return}if(t.type==="session.status"){let e=t.properties.status?.type;(e==="idle"||e==="busy"||e==="retry")&&(this.sessionStatus=e);return}t.type==="session.error"&&(this.sessionStatus="error",t.properties.error?.data?.message&&(this.error=t.properties.error.data.message));}checkComplete(){return this.isComplete=!!this.error||this.hasTextEnd&&this.hasStepFinish,this.isComplete&&mt.debug("MessageEventCollector.checkComplete",{isComplete:this.isComplete,hasError:!!this.error,hasTextEnd:this.hasTextEnd,hasStepFinish:this.hasStepFinish}),this.isComplete}hasTextEndReady(){return this.hasTextEnd}isTextOnlyComplete(){return this.hasTextEnd&&!this.hasStepFinish&&!this.error}resetForNextMessage(){this.hasTextEnd=false,this.hasStepFinish=false,this.error="",this.isComplete=false,this.events=[];}getSessionStatus(){return this.sessionStatus}getCurrentMessageId(){return this.messageId}assembleMessage(){let t=this.events.filter(a=>a.type==="part.updated"&&a.properties.part?.type==="text"&&a.properties.part?.time?.end).map(a=>a.properties.part.text??"").join(""),e;if(this.filterConfig.includeThinking){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="reasoning"&&c.properties.part?.time?.end).map(c=>{let d=c.properties.part.text??"";return d=d.replace("[REDACTED]","").trim(),d}).filter(c=>c.length>0).join("");a&&(e=a);}let s;if(this.filterConfig.includeToolDetails){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="tool"&&(c.properties.part?.state?.status==="completed"||c.properties.part?.state?.status==="error"));a.length>0&&(s=a.map(c=>{let d=c.properties.part,g=d.state;return {name:d.tool,callId:d.callId,title:g.title,status:g.status,output:this.filterConfig.includeToolOutput?g.output:void 0,error:g.error,input:g.input}}));}let i=this.events.find(a=>a.type==="part.updated"&&a.properties.part?.type==="step-finish")?.properties.part?.tokens,r={role:"assistant",text:t,thinking:e,tools:s,metadata:{sessionId:this.sessionId,sessionStatus:this.sessionStatus,messageId:this.messageId,timestamp:Date.now(),tokens:i?{input:i.input,output:i.output,total:i.input+i.output+i.reasoning}:void 0,error:this.error||void 0}};return mt.debug("Message assembled",{textLength:t.length,thinkingLength:e?.length??0,toolsCount:s?.length??0,isComplete:this.isComplete,includeThinking:this.filterConfig.includeThinking,includeToolDetails:this.filterConfig.includeToolDetails,includeToolOutput:this.filterConfig.includeToolOutput}),r}reset(){this.events=[],this.isComplete=false,this.hasTextEnd=false,this.hasStepFinish=false,this.error="",this.sessionStatus="idle",this.sessionId="",this.messageId="",mt.debug("MessageEventCollector.reset",{hasTextEnd:false,hasStepFinish:false});}};var O=class extends Error{constructor(e,s,n){super(e,{cause:n});a(this,"code",s);this.name="GatewayAgentError";}},Ae=class{constructor(t,e={}){a(this,"sdk",t);a(this,"log",Log.create({service:"gateway:agent"}));a(this,"config");a(this,"filterConfig");a(this,"sessionId");a(this,"eventBus");a(this,"eventBridge");a(this,"bridgeStarted",false);this.config=e,this.filterConfig={includeThinking:e.filterConfig?.includeThinking??false,includeToolDetails:e.filterConfig?.includeToolDetails??false,includeToolOutput:e.filterConfig?.includeToolOutput??true,includeSteps:e.filterConfig?.includeSteps??false},this.eventBus=new ve,this.eventBridge=new Ie(t,this.eventBus);}async getCommandPart(t){let e=t.parts?.find(n=>n.type==="command");if(!e)return;let s=false;try{s=(await this.sdk.command.get({name:e.command})).data?.commandType==="local";}catch(n){this.log.warn("Failed to get command",{command:e.command,error:String(n)});}return {...e,local:s}}async run(t,e){this.log.debug("GatewayAgent.run: starting",{source:t.source,agent:t.agent,partsCount:t.parts?.length??0});let s=await this.getCommandPart(t);return s?s.local?this.runLocalCommand(t,s):this.runPromptCommand(t,s,e):this.runPrompt(t,e)}async runLocalCommand(t,e){this.log.debug("GatewayAgent.runLocalCommand: starting",{command:e.command,arguments:e.arguments});try{let s=await this.ensureSession(t.source);if(!s)throw new O("Failed to create or get session","NO_SESSION");let i=(await this.sdk.session.command({sessionId:s,command:e.command,arguments:e.arguments??"",agent:t.agent,model:t.model?`${t.model.providerId}/${t.model.modelId}`:void 0})).data;return this.log.debug("GatewayAgent.runLocalCommand: completed",{sessionId:s,success:i?.success}),{output:i?.output??"",title:t.title??`Command: ${e.command}`,metadata:{sessionId:s,source:t.source,agent:t.agent,success:i?.success,error:i?.error}}}catch(s){throw this.log.error("GatewayAgent.runLocalCommand: failed",{error:s instanceof Error?s.message:String(s)}),new O(s instanceof Error?s.message:String(s),"COMMAND_ERROR",s instanceof Error?s:void 0)}}async runPromptCommand(t,e,s){this.log.debug("GatewayAgent.runPromptCommand: starting",{command:e.command,arguments:e.arguments});try{let n=await this.ensureSession(t.source);if(!n)throw new O("Failed to create or get session","NO_SESSION");let i=new ge(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=!0);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,S=null,C=()=>{S&&clearTimeout(S);},_=E=>{C();try{a();}catch{}g({messages:p,finishReason:E});};S=setTimeout(()=>{this.log.warn("runPromptCommand: event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),_("timeout");},12e4),a=this.eventBus.subscribeAll(E=>{if(E.type==="sdk.session_update"){let F=E.properties;if(F.sessionId!==n)return;if(i.addEvent(F.sessionEvent),i.checkComplete()){let R=i.assembleMessage();if(p.push(R),i.resetForNextMessage(),!R.text||R.text.trim().length===0){this.log.debug("runPromptCommand: skipping onMessage for empty-text message",{messageId:R.metadata.messageId,hasThinking:!!R.thinking,hasTools:(R.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(R)).catch(te=>{this.log.error("runPromptCommand: onMessage callback error",{error:te instanceof Error?te.message:String(te)});});}}let k=i.getSessionStatus();if(h==="busy"&&k==="idle"&&p.length>0){this.log.debug("runPromptCommand: turn complete (busy -> idle)",{messageCount:p.length}),_("idle");return}(k==="idle"||k==="busy"||k==="retry")&&(h=k);});});await this.sdk.session.command({sessionId:n,command:e.command,arguments:e.arguments??"",agent:t.agent,model:t.model?`${t.model.providerId}/${t.model.modelId}`:void 0});let d=await c;try{a();}catch{}return this.log.debug("GatewayAgent.runPromptCommand: completed",{sessionId:n,command:e.command,messageCount:d.messages.length,finishReason:d.finishReason}),this.assembleResult(d.messages,n,t,d.finishReason)}catch(n){throw this.log.error("GatewayAgent.runPromptCommand: failed",{error:n instanceof Error?n.message:String(n)}),new O(n instanceof Error?n.message:String(n),"COMMAND_ERROR",n instanceof Error?n:void 0)}}async runPrompt(t,e){this.log.debug("GatewayAgent.runPrompt: starting",{source:t.source,agent:t.agent});try{let s=await this.ensureSession(t.source);if(!s)throw new O("Failed to create or get session","NO_SESSION");let n=await this.sendAndCollect(s,t,e);return this.log.debug("GatewayAgent.runPrompt: completed",{sessionId:s,outputLength:n.output.length,messageCount:Array.isArray(n.metadata.messages)?n.metadata.messages.length:void 0}),n}catch(s){throw this.log.error("GatewayAgent.runPrompt: failed",{error:s instanceof Error?s.message:String(s)}),s instanceof O?s:new O(s instanceof Error?s.message:String(s),"EXECUTION_ERROR",s instanceof Error?s:void 0)}}async ensureSession(t){if(t)try{if((await this.sdk.session.get({sessionId:t})).data)return this.sessionId=t,this.log.debug("Using existing session",{sessionId:t}),t}catch{this.log.debug("Session not found, will create new",{sessionId:t});}let e=await this.sdk.session.create({title:"Gateway Session"});if(!e.data?.id)throw new O("Failed to create session","CREATE_SESSION_FAILED");return this.sessionId=e.data.id,this.log.debug("Created new session",{sessionId:this.sessionId}),this.sessionId}async sendAndCollect(t,e,s){let n=[];for(let g of e.parts??[])if(g.type==="text")n.push({type:"text",text:g.text??""});else if(g.type==="image"){let p="";typeof g.image=="string"?p=g.image:g.image instanceof URL?p=g.image.toString():g.image instanceof Uint8Array&&(p=`data:${g.mime??"image/png"};base64,${Buffer.from(g.image).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"image/png"});}else if(g.type==="file"){let p="";typeof g.data=="string"?p=g.data:g.data instanceof URL?p=g.data.toString():g.data instanceof Uint8Array&&(p=`data:${g.mime??"application/octet-stream"};base64,${Buffer.from(g.data).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"application/octet-stream"});}n.length===0&&n.push({type:"text",text:""});let i=new ge(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=true);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,S=null,C=()=>{S&&clearTimeout(S);},_=E=>{C();try{a();}catch{}g({messages:p,finishReason:E});};S=setTimeout(()=>{this.log.warn("Event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),_("timeout");},12e4),a=this.eventBus.subscribeAll(E=>{if(E.type==="sdk.session_update"){let F=E.properties;if(F.sessionId!==t)return;if(i.addEvent(F.sessionEvent),i.checkComplete()){let R=i.assembleMessage();if(p.push(R),i.resetForNextMessage(),this.log.debug("sendAndCollect: message complete",{messageId:R.metadata.messageId,messageCount:p.length,textLength:R.text?.length??0}),!R.text||R.text.trim().length===0){this.log.debug("sendAndCollect: skipping onMessage for empty-text message",{messageId:R.metadata.messageId,hasThinking:!!R.thinking,hasTools:(R.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(R)).catch(te=>{this.log.error("sendAndCollect: onMessage callback error",{error:te instanceof Error?te.message:String(te)});});}}let k=i.getSessionStatus();if(h==="busy"&&k==="idle"&&p.length>0){this.log.debug("sendAndCollect: turn complete (busy -> idle)",{messageCount:p.length}),_("idle");return}(k==="idle"||k==="busy"||k==="retry")&&(h=k);});});await this.sdk.session.prompt({sessionId:t,parts:n,system:e.system,agent:e.agent,model:e.model?{providerId:e.model.providerId,modelId:e.model.modelId}:void 0});let d=await c;try{a();}catch{}return this.assembleResult(d.messages,t,e,d.finishReason)}assembleResult(t,e,s,n="idle"){let i=t.map(c=>this.formatOutput(c)).filter(c=>c.length>0).join(`
2
2
 
3
3
  `),a=t[t.length-1]?.metadata.tokens;return {output:i,title:s.title??"Gateway Response",metadata:{sessionId:e,source:s.source,agent:s.agent,messageCount:t.length,finishReason:n,messages:t,...a?{tokens:a}:{}}}}formatOutput(t){let e=[];if(t.text&&e.push(t.text),t.tools&&this.filterConfig.includeToolOutput)for(let s of t.tools)s.output&&e.push(`
4
4
  [Tool: ${s.name}]
@@ -7,8 +7,8 @@ ${String(s.output)}
7
7
  [Tool Error: ${s.name}]
8
8
  ${s.error}
9
9
  `);return e.join(`
10
- `).trim()}getSessionId(){return this.sessionId}resetSession(){this.sessionId=void 0;}async stop(){this.bridgeStarted&&(await this.eventBridge.stop(),this.bridgeStarted=false,this.sessionId=void 0);}};var ls=Log.create({service:"gateway:interfaces"}),$;function eo(o){$=o,o?ls.debug("Agent adapter registered",{hasSubAgentRunner:!!o.subAgentRunner}):ls.debug("Agent adapter cleared");}function to(){return $}function ue(){return $!==void 0}function X(){if(!$)throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");return $}var On={Path:{home:process.env.HOME||process.env.USERPROFILE||"",data:".easbot",cache:".easbot/cache",config:".easbot",state:".easbot/state",log:".easbot/log",bin:".easbot/bin"}},$n={directory:process.cwd(),worktree:process.cwd()};function v(){return $?$.global:On}function Nt(){return $?$.instance:$n}var Dt=null;function hs(o){Dt=o;}async function ft(){return Dt?Dt():null}function Wn(){if(!$?.sdk)throw new Error("SDK not available. Agent adapter is not set or has no SDK.");return $.sdk}function ms(o){let t=Wn();return new Ae(t,o)}var j=Log.create({service:"gateway:config"}),bt={enabled:true,port:8080,hostname:"localhost",path:"",maxConnections:1e3,connectionTimeout:36e5,heartbeatInterval:3e4,sessionExpireMs:36e5,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}},qn={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},Kn={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},Vn={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},Jn={heartbeatInterval:6e4,heartbeatTimeout:3e5,heartbeatCheckInterval:3e5,autoDeregisterTimeout:6e5,maxAgents:100,maxRegistrations:1e3},Qn={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e3},Xn={enabled:true,botToken:"",maxConnections:100,timeout:3e4,polling:{enabled:true,timeout:30}},Yn={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Zn={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},ei={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},ti={enabled:true,path:"/ws",heartbeatInterval:6e4,connectionTimeout:36e5,maxConnections:1e3,cors:true},si={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},ni={enabled:true,relays:[],maxConnections:100,timeout:3e4},Pe,xe=null;async function fs(o){try{if(!existsSync(o))return null;let t=await W__default.readFile(o,"utf-8");t=t.replace(/\{env:([^}]+)\}/g,(r,a)=>{let c=process.env[a];return c===void 0?(j.debug("Environment variable not found",{varName:a,file:o}),""):c});let e=t,s=!1,n=!1,i=[];for(let r=0;r<t.length;r++){let a=t[r];if(n){i.push(a),n=!1;continue}if(a==="\\"){i.push(a),n=!0;continue}if(a==='"'){s=!s,i.push(a);continue}if(!s&&a==="/"&&t[r+1]==="/"){for(;r<t.length&&t[r]!==`
11
- `&&t[r]!=="\r";)r++;continue}if(!s&&a==="/"&&t[r+1]==="*"){for(r+=2;r<t.length-1;){if(t[r]==="*"&&t[r+1]==="/"){r+=2;break}r++;}continue}i.push(a);}return e=i.join("").trim(),e?JSON.parse(e):null}catch(t){return j.debug("Failed to load config file",{file:o,error:String(t)}),null}}function yt(o,t){let e={...o,...t};return (o.server||t.server)&&(e.server={...o.server,...t.server}),(o.channels||t.channels)&&(e.channels={...o.channels,...t.channels}),e}async function ii(){let o=v(),t=Nt(),e=[],s=pe__default.join(o.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{j.debug("Filesystem utils not available, using basic directories");}let n=process.env.EASBOT_CONFIG_DIR;return n&&(e.push(n),j.debug("Using EASBOT_CONFIG_DIR",{path:n})),[...new Set(e)]}async function ri(o){let t=["gateway.json"],e={};for(let s of t){let n=pe__default.join(o,s),i=await fs(n);if(i)if("gateway"in i&&i.gateway){let r=i.gateway,a={};"enabled"in r&&(a.enabled=r.enabled),"port"in r&&(a.port=r.port),"hostname"in r&&(a.hostname=r.hostname),"path"in r&&(a.path=r.path),"https"in r&&(a.https=r.https),e=yt(e,{server:a,channels:r.channels}),j.debug("Loaded gateway config from file",{file:n});}else "gateway"in i||(e=yt(e,i),j.debug("Loaded gateway config from file (direct format)",{file:n}));}return e}async function ai(o){let t=["easbot.json"];for(let e of t){let s=pe__default.join(o,e),n=await fs(s);if(n?.gateway)return j.debug("Loaded gateway config from easbot.json",{file:s}),n.gateway}return {}}function oi(){return Pe||(Pe=async()=>{let o=await ii(),t={};for(let s of o){let n=await ri(s);t=yt(t,n);let i=await ai(s);t=yt(t,i);}let e=Rt(t);return xe=e,j.info("Gateway config loaded",{directories:o.length,port:e.server?.port,logLevel:e.logLevel}),{config:e,directories:o}}),Pe}async function T(){return oi()()}async function ds(o){return o&&(Pe=void 0,xe=null),(await T()).config}function gs(){return xe}function us(){return xe!==null}function ci(){Pe=void 0,xe=null,j.debug("Config cache cleared");}function li(){return Nt().directory}async function di(){let{config:o}=await T();return ut.parse({...bt,...o.server})}async function gi(o){let{config:t}=await T(),e=t.channels?.[o],n={telegram:et.parse(Xn),slack:tt.parse(Yn),feishu:st.parse(Zn),wechat:nt.parse(ei),webchat:it.parse(ti),signal:rt.parse(si),nostr:at.parse(ni)}[o];if(!n)throw new Error(`Unknown channel type: ${o}`);return {...n,...e}}async function ui(){let{config:o}=await T();return ot.parse({...qn,...o.connectionPool})}async function pi(){let{config:o}=await T();return ct.parse({...Kn,...o.messageQueue})}async function hi(){let{config:o}=await T();return lt.parse({...Vn,...o.circuitBreaker})}async function mi(){let{config:o}=await T();return dt.parse({...Jn,...o.agentRegistry})}async function fi(){let{config:o}=await T();return gt.parse({...Qn,...o.session})}async function yi(){let{config:o}=await T();if(o.client)return pt.parse(o.client)}async function bi(){let{config:o}=await T();if(!(o.client?.autoRegister??true))return;let e=o.server,s=e?.hostname??"localhost",n=e?.port??8080,i=e?.path||"/acp";return `ws://${s}:${n}${i}`}async function Si(){let{config:o}=await T();return o.server?.https}async function Ci(){let{config:o}=await T();return o.server?.auth}async function wi(){let{config:o}=await T();return o.cluster}async function vi(){let{config:o}=await T();return o.defaultAgent}async function ps(){let{config:o}=await T();return o.logLevel??"INFO"}var Gt=bt,Me={maxConnections:1e3,connectionTimeout:36e5};var Ii={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var St={heartbeatInterval:6e4,heartbeatTimeout:3e5,heartbeatCheckInterval:3e5,autoDeregisterTimeout:6e5,maxAgents:100,maxRegistrations:1e3};var Ct={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};var Ai={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var q=class o extends Error{constructor(e,s){super(e);a(this,"code");a(this,"recoverable");a(this,"details");a(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,o);}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 o)return e.recoverable;let s=e.code;return ["ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH"].includes(s??"")}};function y(o,t,e,s=true){return new q(e,{code:t,recoverable:s,details:{channelId:o}})}var wt=class{constructor(t,e){a(this,"log",Log.create({service:"gateway:router"}));a(this,"subscribers",new Map);a(this,"subscriptions",new Map);a(this,"messageSubscriptions",new Map);a(this,"channelPlugins",new Map);a(this,"cancelHandlers",new Set);a(this,"processingMessages",new Map);a(this,"hookRegistry",null);a(this,"sessionManager",null);this.hookRegistry=t??null,this.sessionManager=e??null;}setSessionManager(t){this.sessionManager=t;}async triggerHook(t,e,s){if(this.hookRegistry)try{await this.hookRegistry.triggerEvent(t,e,s);}catch{}}async triggerBeforeSend(t,e,s){if(this.sessionManager)try{await this.sessionManager.bindBackendSession(t.sessionId,s.sessionId);}catch{}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)});}}selectSubscriber(t){let e=this.messageSubscriptions.get(t.sessionId);if(!e||e.size===0){if(this.sessionManager){let r=this.sessionManager.get(t.sessionId);r?.backendSessionId&&(e=this.messageSubscriptions.get(r.backendSessionId));}if(!e||e.size===0){for(let[,r]of this.messageSubscriptions)if(r.size>0){e=r;break}}}if(!e||e.size===0)return null;let s=e.values().next().value;if(!s)return null;let n=this.subscriptions.get(s);if(!n)return null;let i=this.subscribers.get(n.subscriberId);return i?{subscription:n,subscriber:i}:null}async route(t){let e=this.selectSubscriber(t);if(!e)return {success:true,dispatched:false,dispatchedToSubAgent:false};let{subscription:s,subscriber:n}=e;if(t.type==="input"){let i=this.processingMessages.get(t.id);if(i&&i!==n.id)return {success:true,dispatched:false,dispatchedToSubAgent:false};this.processingMessages.set(t.id,n.id);}try{return await this.triggerBeforeSend(t,n.id,{sessionId:s.sessionId,subscriberId:s.subscriberId}),await n.connection.send(t),n.lastActiveAt=Date.now(),{success:!0,dispatched:!0,dispatchedToSubAgent:!1}}catch(i){return this.log.warn("failed to send message to subscriber",{subscriberId:n.id,error:String(i)}),t.type==="input"&&this.processingMessages.delete(t.id),{success:false,dispatched:false,dispatchedToSubAgent:false,error:i instanceof Error?i.message:String(i)}}}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()});}async subscribe(t,e){let s=Et(e.id,t);if(this.subscriptions.has(s))return this.subscriptions.get(s);for(let[i,r]of this.subscriptions.entries())r.subscriberId===e.id&&r.sessionId===t&&i!==s&&await this.unsubscribe(i);let n={id:s,subscriberId:e.id,sessionId:t,createdAt:Date.now()};return this.subscribers.set(e.id,e),this.subscriptions.set(s,n),this.messageSubscriptions.has(t)||this.messageSubscriptions.set(t,new Set),this.messageSubscriptions.get(t).add(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.messageSubscriptions.get(e.sessionId);s&&(s.delete(t),s.size===0&&this.messageSubscriptions.delete(e.sessionId));}async unsubscribeAll(t){for(let[e,s]of this.subscriptions.entries())s.subscriberId===t&&await this.unsubscribe(e);this.subscribers.delete(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)}getMessageSubscriptions(){return this.messageSubscriptions}getSubscriberCount(t){return this.messageSubscriptions.get(t)?.size??0}getStats(){return {subscribers:this.subscribers.size,subscriptions:this.subscriptions.size,sessions:this.messageSubscriptions.size}}async shutdown(){this.processingMessages.clear(),this.subscribers.clear(),this.subscriptions.clear(),this.messageSubscriptions.clear(),this.channelPlugins.clear(),this.cancelHandlers.clear(),this.log.info("router shutdown");}};var ke=class{constructor(t={}){a(this,"log",Log.create({service:"gateway:message-store"}));a(this,"config");a(this,"messages",new Map);a(this,"sessionMessages",new Map);a(this,"cleanupTimer",null);a(this,"accessOrder",[]);a(this,"storagePath");a(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 loadFromDisk(){let t=0;try{let e=await W.readdir(this.storagePath,{withFileTypes:!0});for(let s of e){if(!s.isDirectory())continue;let n=pe.join(this.storagePath,s.name),i=await W.readdir(n);for(let r of i)if(r.endsWith(".json"))try{let a=pe.join(n,r),c=await W.readFile(a,"utf-8"),d=JSON.parse(c);d.status!=="completed"&&d.status!=="delivered"&&(this.messages.has(d.message.id)||(this.messages.set(d.message.id,d),this.addToSessionMessages(d.message.sessionId,d.message.id),t++));}catch(a){this.log.debug("failed to load message file",{file:r,error:String(a)});}}t>0&&this.log.debug("loaded messages from disk",{count:t});}catch(e){this.log.warn("failed to load messages from disk",{error:String(e)});}return t}addToSessionMessages(t,e){this.sessionMessages.has(t)||this.sessionMessages.set(t,new Set),this.sessionMessages.get(t).add(e);}async ensureDir(t){try{await W.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 pe.join(this.storagePath,`${this.sanitizeFileName(t)}.json`)}getSessionDir(t){return pe.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.addToSessionMessages(t.sessionId,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=pe.join(e,`${this.sanitizeFileName(t.message.id)}.json`);await W.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()),"error"in s&&(n.error=s.error??null),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)=>r.createdAt-i.createdAt),n.slice(0,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.debug("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 ne=class{constructor(t={}){a(this,"log",Log.create({service:"gateway:session-store"}));a(this,"config");a(this,"sessions",new Map);a(this,"channelSessions",new Map);a(this,"autoSaveTimer",null);a(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 se.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(!se.existsSync(t)){this.log.debug("no saved sessions found");return}let e=await se.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 a={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(a.id,a),this.channelSessions.has(a.channel.channelId)||this.channelSessions.set(a.channel.channelId,new Set),this.channelSessions.get(a.channel.channelId).add(a.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 pe.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){se.existsSync(this.config.storagePath)||await se.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 Ti="./data/gateway",_i="contacts",Ei="index.json",re=class{constructor(t={}){a(this,"log",Log.create({service:"gateway:contact-store"}));a(this,"baseDir");a(this,"contactDir");a(this,"indexPath");a(this,"index");a(this,"indexFileMap");a(this,"dirty",false);a(this,"saveTimer",null);a(this,"SAVE_DEBOUNCE_MS",1e3);this.baseDir=t.baseDir??Ti,this.contactDir=pe.join(this.baseDir,_i),this.indexPath=pe.join(this.contactDir,Ei),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 W.mkdir(t,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async loadIndex(){try{let t=await W.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 W.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=Ye(t);if(e){let s=this.getFilePath(e.platform,e.stableId);this.indexFileMap[t]=s;}}}getFilePath(t,e){let s=this.sanitizeFilename(e);return pe.join(this.contactDir,t,`${s}.json`)}sanitizeFilename(t){return t.replace(/[/\\:*?"<>|]/g,"_")}getPlatformDir(t){return pe.join(this.contactDir,t)}async save(t){let{platform:e,stableId:s,uid:n}=t,i=this.getFilePath(e,s);return await this.ensureDir(pe.dirname(i)),await W.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=_t(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=Ye(t);return e?this.findByPlatformId(e.platform,e.stableId):null}async findByPlatformId(t,e){let s=Xe(t,e),n=this.index.byUid[s];if(n)try{let r=await W.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 W.readFile(i,"utf-8"),a=JSON.parse(r);return this.index.byUid[s]=i,this.indexFileMap[s]=i,this.dirty=!0,await this.saveIndex(),a}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 W.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),a=[];for(let c of r){let d=await this.findByUid(c);d&&a.push(d);}return {contacts:a,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 c=await this.listByPlatform(t.platform,t.limit,t.offset),d=c.contacts;if(t.username){let g=t.username.toLowerCase();d=d.filter(p=>p.profile.username?.toLowerCase().includes(g));}if(t.email){let g=t.email.toLowerCase();d=d.filter(p=>p.profile.email?.toLowerCase().includes(g));}if(t.phone){let g=t.phone.replace(/\s/g,"");d=d.filter(p=>p.profile.phone?.replace(/\s/g,"").includes(g));}return {contacts:d,total:c.total,hasMore:c.hasMore}}let e=[];for(let c of Object.keys(this.index.byPlatform)){let d=await this.listByPlatform(c,1e3,0);e.push(...d.contacts);}let s=e;if(t.username){let c=t.username.toLowerCase();s=s.filter(d=>d.profile.username?.toLowerCase().includes(c));}if(t.email){let c=t.email.toLowerCase();s=s.filter(d=>d.profile.email?.toLowerCase().includes(c));}if(t.phone){let c=t.phone.replace(/\s/g,"");s=s.filter(d=>d.profile.phone?.replace(/\s/g,"").includes(c));}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 Ut=class{constructor(t){a(this,"cache",new Map);a(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}},Te=class{constructor(t,e={}){a(this,"store",t);a(this,"cache");a(this,"usernameIndex");a(this,"emailIndex");a(this,"phoneIndex");a(this,"platformIndex");a(this,"initialized",false);this.cache=new Ut(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 z=Log.create({service:"gateway:storage:agent-registry"}),_e=class{constructor(t){a(this,"config");a(this,"filePath");a(this,"cache",new Map);a(this,"initialized",false);this.config=t,this.filePath=pe.join(t.dataDir,"agent-registry.json");}async initialize(){if(!this.initialized)try{await W.mkdir(this.config.dataDir,{recursive:!0}),this.initialized=!0,z.debug("Agent registry store initialized",{dataDir:this.config.dataDir});}catch(t){throw z.error("Failed to initialize agent registry store",{dataDir:this.config.dataDir,error:String(t)}),t}}async loadFromDisk(){await this.initialize();try{let t=await W.readFile(this.filePath,"utf-8"),e=JSON.parse(t),s=new Map;for(let n of e)n.agent?.id&&s.set(n.agent.id,n);return z.debug("Agent registry loaded from disk",{count:s.size}),s}catch(t){return t.code==="ENOENT"?(z.debug("Agent registry file not found, starting fresh"),new Map):(z.error("Failed to load agent registry from disk",{error:String(t)}),new Map)}}async saveToDisk(){await this.initialize();try{let t=Array.from(this.cache.values());await W.writeFile(this.filePath,JSON.stringify(t,null,2),"utf-8"),z.debug("Agent registry saved to disk",{count:this.cache.size});}catch(t){throw z.error("Failed to save agent registry to disk",{error:String(t)}),t}}async loadAll(){let t=await this.loadFromDisk();return this.cache=t,Array.from(this.cache.values()).map(e=>e.agent)}async save(t){await this.initialize();let e={agent:t,storedAt:Date.now()};this.cache.set(t.id,e),await this.saveToDisk(),z.debug("Agent registration saved",{agentId:t.id});}async saveAll(t){await this.initialize();for(let e of t){let s={agent:e,storedAt:Date.now()};this.cache.set(e.id,s);}await this.saveToDisk(),z.debug("All agent registrations saved",{count:t.length});}async delete(t){await this.initialize(),this.cache.has(t)&&(this.cache.delete(t),await this.saveToDisk(),z.debug("Agent registration deleted",{agentId:t}));}getFilePath(){return this.filePath}};var Ee=class{constructor(t={}){a(this,"log",Log.create({service:"gateway:session"}));a(this,"sessionStore");a(this,"config");a(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 ne({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=Je(t),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),n):(n={id:s,channel:t,backendSessionId:null,subscribers:new Set,state:Qe(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(n),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);}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);}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);}findByBackendSessionId(t){for(let e of this.sessionStore.getAll())if(e.backendSessionId===t)return e}getState(t){return this.sessionStore.get(t)?.state}async incrementMessageCountOrCreate(t,e){let s=this.sessionStore.get(t);if(!s){if(!e)throw new Error(`Cannot create session: channelInfo is required when session "${t}" does not exist`);let n=Je(e);n!==t&&this.log.warn("sessionId mismatch, using correct sessionId from channelInfo",{providedSessionId:t,correctSessionId:n}),s={id:n,channel:e,backendSessionId:null,subscribers:new Set,state:Qe(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(s),this.log.debug("session auto-created from message",{sessionId:n,platform:e.platform,channelId:e.channelId,chatId:e.chatId,userId:e.userId});}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);}async removeSubscriber(t,e){let s=this.sessionStore.get(t);s&&(s.subscribers.delete(e),await this.sessionStore.set(s));}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}async save(){}getStats(){return this.sessionStore.getStats()}};var Re=class{constructor(t={}){a(this,"log",Log.create({service:"gateway:plugin-loader"}));a(this,"plugins",new Map);a(this,"messageHandler",null);a(this,"healthCheckTimer",null);a(this,"config");a(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;}updateSessionHandler(t){this.messageHandler&&(this.messageHandler.session=t,this.log.debug("session handler updated"));}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 q(`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 q("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 J=class extends Error{constructor(e,s,n){super(e);a(this,"code",s);a(this,"configuredChannels",n);this.name="ChannelSelectionError";}},V=Log.create({service:"gateway:channel-selection"});function me(o){if(!(!o||typeof o!="string"))return o.toLowerCase().trim()}async function Ot(o){let{channel:t,sessionId:e,userId:s,defaultChannel:n,fallbackChannels:i,sessionManager:r,pluginLoader:a,contactStore:c}=o,d=me(t);if(d){let S=Ft(d,a);if(S){if(e){let C=Bt(e,r);if(C){if(C.channelInfo.chatId||C.channelInfo.userId)return V.debug("enriching explicit channel with session info",{sessionId:e,chatId:C.channelInfo.chatId,userId:C.channelInfo.userId}),{...S,channelInfo:{...S.channelInfo,chatId:C.channelInfo.chatId,userId:C.channelInfo.userId}}}else if(s&&r){V.debug("session not found, creating new session for private chat",{userId:s});let _=s,E={platform:S.channelInfo.platform,channelId:S.channel,chatId:_,userId:s};try{let k=await r.getOrCreate(E);return V.debug("auto-created session for private chat",{sessionId:k.id,chatId:_,userId:s}),{channel:S.channel,source:"session-bound",channelInfo:k.channel}}catch(k){V.warn("failed to auto-create session, using explicit channel info",{userId:s,error:String(k)});}}}if(s&&c){let C=await Gi(d,s,c,a);if(C)return C}return S}if(e){let C=Bt(e,r);if(C){if((!C.channelInfo.chatId||!C.channelInfo.userId)&&C.channelInfo.platform!=="api"){let E=Fi(C.channelInfo.platform,r);if(E)return V.debug("session missing chatId/userId, using session with complete info",{originalSessionId:e,newSessionId:E.channelInfo.chatId}),E}return C}}throw new J(`Channel \u4E0D\u53EF\u7528\u6216\u672A\u914D\u7F6E: ${d}`,"CHANNEL_UNAVAILABLE",[])}if(e){let S=Bt(e,r);if(S)return S}if(s&&c){let S=await Ui(s,c,a);if(S)return S}let g=$t(a);if(g.length===0)throw new J("\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 p=me(n);if(p){let S=Ft(p,a);if(S)return V.debug("using default channel",{channel:p}),{...S,source:"default"};V.warn("default channel unavailable",{channel:p});}if(g.length===1){let S=g[0],C=a?.getPlugin(S);return {channel:S,source:"single-configured",channelInfo:{platform:C?.platform,channelId:S}}}let h=(i??[]).map(me).filter(S=>S!==void 0);for(let S of h){let C=Ft(S,a);if(C)return V.debug("using fallback channel",{channel:S}),{...C,source:"fallback"};V.debug("fallback channel unavailable, trying next",{channel:S});}throw p?new J(`\u914D\u7F6E\u7684\u9ED8\u8BA4 Channel \u4E0D\u53EF\u7528: ${p}`,"CHANNEL_UNAVAILABLE",g):new J(`\u9700\u8981\u660E\u786E\u6307\u5B9A Channel\uFF08\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF09: ${g.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",g)}function Ft(o,t){if(!t)return null;let e=t.getPlugin(o);if(e&&t.isRunning(o))return {channel:o,source:"explicit",channelInfo:{platform:e.platform,channelId:o}};let s=me(o);if(!s)return null;let n=t.getAllPlugins();for(let i of n)if(t.isRunning(i.id)&&me(i.platform)===s)return {channel:i.id,source:"explicit",channelInfo:{platform:i.platform,channelId:i.id}};return null}function Bt(o,t){if(!t)return null;let e=t.get(o);return e?{channel:e.channel.channelId,source:"session-bound",channelInfo:e.channel}:null}async function Gi(o,t,e,s){let n=s?.getPlugin(o);if(!n)return null;let i=await e.findByPlatformId(n.platform,t);return i?{channel:o,source:"explicit",channelInfo:{platform:n.platform,channelId:o,userId:i.stableId,chatId:i.stableId}}:null}async function Ui(o,t,e){let s=$t(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,o);if(r)return {channel:n,source:"single-configured",channelInfo:{platform:i.platform,channelId:n,userId:r.stableId,chatId:r.stableId}}}return null}function $t(o){if(!o)return [];let t=[],e=o.getAllPlugins();for(let s of e)o.isRunning(s.id)&&t.push(s.id);return t}function Wt(o){switch(o.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: ${o.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 o.message;case "UNKNOWN_CHANNEL":return `\u672A\u77E5\u7684 Channel: ${o.message}\u3002\u8BF7\u68C0\u67E5 Channel ID \u662F\u5426\u6B63\u786E\u3002`;default:return o.message}}function Fi(o,t){if(!t)return null;let e=t.getAll?.()??[];for(let s of e)if(s.channel.platform===o&&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===o&&s.channel.chatId)return {channel:s.channel.channelId,source:"session-bound",channelInfo:s.channel};return null}var b=Log.create({service:"gateway:websocket-server"});function Ht(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function L(o,t){for(let[e,s]of t.entries())if(s===o)return e;return null}var ae=class{constructor(t={}){a(this,"config");a(this,"server",null);a(this,"wss",null);a(this,"httpsServer",null);a(this,"httpRedirectServer",null);a(this,"connections",new Map);a(this,"subscriptions",new Map);a(this,"clientLastActivity",new Map);a(this,"cleanupInterval",null);a(this,"heartbeatInterval",null);a(this,"startTime",0);a(this,"running",false);a(this,"channelResolveParams",null);a(this,"pluginLoaderRef",null);a(this,"agentSyncRef",null);a(this,"agentRegistryRef",null);a(this,"routerRef",null);a(this,"subscribers",new Map);this.config={...Gt,...t};}setChannelResolveDeps(t){this.channelResolveParams=t;}setPluginLoader(t){this.pluginLoaderRef=t;}getGatewayId(){let t=this.config.https?.enabled?"https":"http",e=this.config.hostname||"localhost",s=this.config.port||8080,n=`${t}://${e}:${s}`;return zi.createHash("sha256").update(n).digest("hex").substring(0,16)}setAgentSync(t){this.agentSyncRef=t;}setAgentRegistry(t){this.agentRegistryRef=t;}setRouter(t){this.routerRef=t;}getChannelResolveParams(){return this.channelResolveParams?this.channelResolveParams:{}}async start(){if(this.running){b.warn("WebSocket server is already running");return}b.debug("WebSocket server starting",{port:this.config.port,hostname:this.config.hostname,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){b.error("Error processing WebSocket message",{error:r.message}),this.sendError(i,r.message);}},onClose:(n,i)=>{this.handleDisconnection(i);},onError:(n,i)=>{b.error("WebSocket error",{error:n.type});}},e=this.config.https?.enabled??false;try{e?await this.startHTTPSServer(t):await this.startHTTPServer(t);}catch(n){throw b.error("WebSocket server start: HTTP/HTTPS server failed",{error:n instanceof Error?n.message:String(n)}),n}this.cleanupInterval=setInterval(()=>this.cleanupInactiveClients(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let s=e?"wss":"ws";b.info("WebSocket server started",{url:`${s}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(t){this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let e=this.server.raw;e?this.setupWebSocketUpgrade(e,t):b.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(t){let e=this.config.https,s=this.loadSSLCertificates(e);if(!s){b.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=Wi.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,t),await new Promise(i=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{b.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:se__default.readFileSync(t.certPath),key:se__default.readFileSync(t.keyPath)}:null}catch(e){return b.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 a=new URL(s.url||"/",`http://${s.headers.host}`).pathname,c=this.config.path||"";(a===c||c===""&&(a==="/"||a===""))&&this.wss.handleUpgrade(s,n,i,d=>{e.onOpen?.({type:"open"},d),d.on("message",g=>{e.onMessage?.({data:g},d);}),d.on("close",(g,p)=>{e.onClose?.({code:g,reason:p},d);}),d.on("error",g=>{e.onError?.({type:"error",message:g.message},d);});});}catch{}});}startHTTPRedirectServer(t){this.httpRedirectServer=Hi.createServer((e,s)=>{let i=`https://${e.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${e.url}`;s.writeHead(301,{Location:i,"Content-Type":"text/plain"}),s.end(`Redirecting to ${i}`);}),this.httpRedirectServer.listen(t,this.config.hostname,()=>{b.info("HTTP redirect server started",{port:t,hostname:this.config.hostname});});}async stop(){if(!this.running){b.warn("WebSocket server is not running");return}b.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{}this.connections.clear(),this.subscriptions.clear(),this.subscribers.clear(),this.clientLastActivity.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,b.info("WebSocket server stopped");}touchClient(t){this.clientLastActivity.set(t,Date.now());let e=this.subscriptions.get(t);e&&(e.lastActivityAt=Date.now());}getConnectionCount(){return this.connections.size}getStartTime(){return this.startTime}getSubscriptionCount(){return this.subscribers.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??Me.maxConnections)){b.warn("Maximum connections reached, rejecting new connection"),t.close(1013,"Maximum connections reached");return}let e=Ht();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()}),b.debug("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"]}});}async handleDisconnection(t){let e=L(t,this.connections);e&&(this.connections.delete(e),await this.cleanupClientResources(e),b.debug("WebSocket client disconnected",{clientId:e,totalConnections:this.connections.size}));}async cleanupClientResources(t){if(b.debug("Cleaning up client resources",{clientId:t}),this.routerRef){try{await this.routerRef.unsubscribeAll(t);}catch{}this.subscribers.delete(t),b.debug("Subscriber cleaned up from router",{clientId:t});}if(this.agentSyncRef)try{await this.agentSyncRef.cleanupClient(t);}catch{}this.subscriptions.delete(t),this.clientLastActivity.delete(t);}async handleMessage(t,e){let s=L(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 "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;case "agent_list_request":await this.handleAgentListRequest(t,e);break;case "agent_subscribe":await this.handleAgentSubscribe(t,e);break;case "agent_register":await this.handleAgentRegister(t,e);break;case "agent_deregister":await this.handleAgentDeregister(t,e);break;default:this.sendError(t,`Unknown message type: ${e.type}`);}}async handleSubscribe(t,e){if(e.type!=="subscribe"||!e.sessionId){this.sendError(t,"Invalid subscribe request");return}let s=e.clientId,n;if(s){n=s;let r=L(t,this.connections);r&&r!==n&&(await this.cleanupClientResources(r),this.connections.delete(r),b.info("Client reconnected with different clientId, cleaned up old resources",{oldClientId:r,newClientId:n})),this.connections.set(n,t);}else n=L(t,this.connections)??Ht(),L(t,this.connections)||this.connections.set(n,t);let i=this.subscriptions.get(n);if(i?(i.ws=t,i.lastActivityAt=Date.now()):(i={clientId:n,ws:t,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()},this.subscriptions.set(n,i)),e.payload?.eventTypes)for(let r of e.payload.eventTypes)i.subscribedEventTypes.add(r);if(b.debug("Client subscribed to session",{clientId:n,sessionId:e.sessionId}),this.routerRef){if(this.subscribers.get(n))try{await this.routerRef.unsubscribeAll(n);}catch{}let a=e.payload?.clientType||"tui",c={id:n,type:a,createdAt:Date.now(),lastActiveAt:Date.now(),connection:{send:async d=>{this.sendMessage(t,{type:"message",sessionId:d.sessionId,payload:{id:d.id,type:d.type,content:d.content,metadata:d.metadata,timestamp:d.timestamp}});},close:async()=>{t.close(1e3,"Subscriber closed");},isConnected:()=>t.readyState===t.OPEN}};this.subscribers.set(n,c),await this.routerRef.subscribe(e.sessionId,c),b.debug("Subscriber registered to router",{clientId:n,sessionId:e.sessionId});}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=L(t,this.connections);if(s){if(b.debug("Client unsubscribed from session",{clientId:s,sessionId:e.sessionId}),this.routerRef){let n=this.subscribers.get(s);if(n){let i=`sub_${n.id}_${e.sessionId}`;try{await this.routerRef.unsubscribe(i),b.debug("Subscriber unregistered from router",{clientId:s,sessionId:e.sessionId});}catch(r){b.debug("Failed to unsubscribe from router (subscription may not exist)",{clientId:s,sessionId:e.sessionId,error:String(r)});}this.subscribers.delete(s);}}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}let s=this.getClientIdByWs(t)||"unknown";b.debug("Message received from WebSocket client",{clientId:s,sessionId:e.sessionId});let n=e.payload,i=n.message?{...n.message}:{id:`ws_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:e.sessionId,content:n.content||[{type:"text",text:""}]};b.debug("Message received from WebSocket client (use HTTP API to send)",{messageId:i.id,sessionId:e.sessionId}),this.sendMessage(t,{type:"response",sessionId:e.sessionId,success:true,result:{received:true}});}getClientIdByWs(t){return L(t,this.connections)}getClientWs(t){return this.connections.get(t)}async handleInterrupt(t,e){if(e.type!=="interrupt"||!e.sessionId){this.sendError(t,"Invalid interrupt request");return}b.debug("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}let s=L(t,this.connections);if(!s){this.sendError(t,"Client not found");return}if(b.debug("Release subscription requested via WebSocket",{clientId:s,sessionId:e.sessionId}),this.routerRef){let i=`sub_${s}_${e.sessionId}`;try{await this.routerRef.unsubscribe(i);}catch{}}let n=this.subscriptions.get(s);n&&n.subscribedSessions.delete(e.sessionId),this.sendMessage(t,{type:"subscriptionReleased",sessionId:e.sessionId});}async checkConnectionTimeout(){let t=Date.now(),e=this.config.connectionTimeout??Me.connectionTimeout,s=[];for(let[n,i]of this.subscriptions.entries())t-i.lastActivityAt>e&&s.push(n);for(let n of s){await this.cleanupClientResources(n);let i=this.connections.get(n);if(i){b.debug("Closing inactive connection",{clientId:n,lastActivityAt:this.clientLastActivity.get(n),timeoutMs:e});try{i.close(1001,"Connection timeout");}catch(r){b.debug("Error closing timed out connection",{clientId:n,error:String(r)});}this.connections.delete(n);}}s.length>0&&b.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size});}async cleanupInactiveClients(){let t=Date.now(),e=[],s=this.config.connectionTimeout??Me.connectionTimeout;for(let[n,i]of this.clientLastActivity.entries())t-i>s&&e.push(n);for(let n of e){await this.cleanupClientResources(n);let i=this.connections.get(n);if(i){b.debug("Client inactive, closing connection",{clientId:n,lastActivity:this.clientLastActivity.get(n),timeoutMs:s});try{i.close(1001,"Client inactive");}catch(r){b.debug("Error closing inactive client",{clientId:n,error:String(r)});}this.connections.delete(n);}}e.length>0&&b.debug("Cleaned up inactive clients",{count:e.length,remainingActive:this.clientLastActivity.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:async t=>{let e=await ft();if(e)return t.json(e);let s={status:this.running?"running":"stopped",connections:this.connections.size,sessions:0,messageSubscriptions:0,agentSubscriptions:0,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0",channels:[]};return t.json(s)}},{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(a=>({uid:a.uid,platform:a.platform,stableId:a.stableId,profile:a.profile,lastSeenAt:a.lastSeenAt,createdAt:a.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 b.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 b.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"),a=t.req.query("chatId"),c=[],g=this.getChannelResolveParams().sessionManager?.getAll?.()??[];for(let h of g){let S=!n||h.channel.platform===n,C=!i||h.channel.channelId===i,_=!r||h.channel.userId===r,E=!a||h.channel.chatId===a;S&&C&&(!r&&!a||_&&E)&&c.push({id:h.id,platform:h.channel.platform,channelId:h.channel.channelId,userId:h.channel.userId,chatId:h.channel.chatId,chatType:h.channel.chatType,chatTitle:h.channel.chatTitle,state:h.state.status,createdAt:h.createdAt,lastActiveAt:h.lastActiveAt});}let p=c.slice(s,s+e);return t.json({sessions:p,total:c.length,hasMore:s+e<c.length})}},{method:"get",path:"/sessions/:sessionId",handler:async t=>{let e=t.req.param("sessionId"),n=this.channelResolveParams?.sessionManager?.get(e);if(!n)return t.json({error:"Session not found"},404);let i=0;return n.backendSessionId&&this.routerRef&&(i=this.routerRef.getMessageSubscriptions().get(n.backendSessionId)?.size??0),t.json({id:n.id,platform:n.channel.platform,channelId:n.channel.channelId,userId:n.channel.userId,chatId:n.channel.chatId,state:n.state.status,backendSessionId:n.backendSessionId,subscriberCount:i,createdAt:n.createdAt,lastActiveAt:n.lastActiveAt})}},{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),a={id:r.id,createdAt:r.createdAt};return t.json(a)}},{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);let n=this.getChannelResolveParams(),i=e;if(n.sessionManager){let r=n.sessionManager.get(e);if(r)i=r.id;else {let a=n.sessionManager.findByBackendSessionId(e);a&&(b.debug("found gateway session via backendSessionId",{backendSessionId:e,gatewaySessionId:a.id}),i=a.id);}}try{let r=await Ot({...n,sessionId:i,channel:s.channel,userId:s.userId??s.chatId});b.debug("channel resolved for message",{sessionId:e,channel:r.channel,source:r.source,channelInfo:r.channelInfo});let a=Identifier.ascending("message"),c={...r.channelInfo};if(!c.chatId){let p=s.chatId??r.channelInfo.userId;p&&(c.chatId=p,b.debug("filled channelInfo.chatId from request body or session",{chatId:c.chatId}));}if(!c.userId&&c.chatId&&(c.userId=s.userId??c.chatId,b.debug("filled channelInfo.userId from chatId",{userId:c.userId})),!c.chatId)return b.error("channelInfo missing chatId, cannot send message",{sessionId:i,channelInfo:c,body:{userId:s.userId,chatId:s.chatId}}),t.json({error:"channelInfo missing chatId"},400);let d={id:a,sessionId:i,type:"output",content:typeof s.content=="string"?[{type:"text",text:s.content}]:s.content||[],metadata:{channel:c,replyToMessageId:s.replyToMessageId,processorId:s.processorId??"gateway",agent:s.agent??"gateway"},timestamp:Date.now()};if(this.pluginLoaderRef)try{await this.pluginLoaderRef(r.channel,d,{}),b.debug("message sent via pluginLoader",{messageId:a,channel:r.channel});}catch(p){return b.error("failed to send message",{sessionId:i,error:String(p)}),t.json({error:String(p)},500)}else return b.error("no pluginLoader available for sending message",{sessionId:i}),t.json({error:"Plugin loader not available"},500);let g={messageId:a,sessionId:i,createdAt:Date.now(),metadata:{channel:r.channel,channelSource:r.source,channelInfo:r.channelInfo}};return t.status(202),t.json(g)}catch(r){return r instanceof J?(b.warn("channel selection failed",{sessionId:i,error:r.message}),t.json({error:Wt(r),code:r.code},400)):(b.error("send message error",{sessionId:i,error:String(r)}),t.json({error:String(r)},500))}}},{method:"get",path:"/subscriptions",handler:t=>{let e=t.req.query("sessionId"),s=t.req.query("subscriberId");b.debug("subscriptions endpoint called",{routerRefExists:!!this.routerRef,agentSyncRefExists:!!this.agentSyncRef,filterSessionId:e,filterSubscriberId:s});let n=[];if(this.routerRef){let r=this.routerRef,a=r.getMessageSubscriptions();b.debug("messageSubscriptions",{size:a.size,entries:Array.from(a.entries())});for(let[c,d]of a.entries()){if(e&&e!=="agent-list"&&c!==e)continue;let g=new Map;for(let p of d){let h=r.getSubscription(p);if(h){if(s&&h.subscriberId!==s)continue;g.set(h.subscriberId,{id:h.subscriberId,subscriptionId:p});}}g.size>0&&n.push({type:"message",sessionId:c,subscriberCount:g.size,subscribers:Array.from(g.values())});}}if(this.agentSyncRef&&!(e&&e!=="agent-list")){let r=this.agentSyncRef.getSubscribers();b.debug("agentSubscribers",{count:r.length,subscribers:r,filterSubscriberId:s});let a=s?r.filter(c=>c===s):r;b.debug("filteredAgents",{filteredAgents:a}),a.length>0&&n.push({type:"agent",sessionId:"agent-list",subscriberCount:a.length,subscribers:a.map(c=>({id:c,subscriptionId:`agent_sub_${c}`}))});}let i={subscriptions:n,total:n.length};return b.debug("subscriptions response",{subscriptionsCount:n.length,subscriptions:n.map(r=>({type:r.type,sessionId:r.sessionId,subscriberCount:r.subscriberCount}))}),t.json(i)}}]}async handleAgentListRequest(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_list_request"){this.sendError(t,"Invalid agent list request");return}let s=L(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentListRequest(s,e.requestId);}async handleAgentSubscribe(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_subscribe"){this.sendError(t,"Invalid agent subscribe request");return}let s=e.clientId,n;if(s){n=s;let i=L(t,this.connections);i&&i!==n&&this.connections.delete(i),this.connections.set(n,t);}else n=L(t,this.connections)??Ht(),L(t,this.connections)||this.connections.set(n,t);await this.agentSyncRef.handleAgentSubscribe(n,e.subscribe);}async handleAgentRegister(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_register"||!e.payload){this.sendError(t,"Invalid agent register request");return}let s=L(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentRegister(s,e.payload);}async handleAgentDeregister(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_deregister"||!e.payload){this.sendError(t,"Invalid agent deregister request");return}let s=L(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentDeregister(s,e.payload);}};function qi(o){return o.toLowerCase().replace(/^\//,"").replace(/@[^\s]+$/,"")}function Ki(o){return o.replace(/[-_]/g,"").toLowerCase()}var oe=[{command:"new",description:"Reset session and start a new conversation"},{command:"status",description:"Show gateway and channel status"},{command:"commands",description:"Show available commands"}],P=class{constructor(){a(this,"version","1.0.0");a(this,"log");a(this,"config",null);a(this,"messageHandler",null);a(this,"_status","stopped");a(this,"lastActivity",0);a(this,"startPromise",null);a(this,"stopPromise",null);}initLog(){this.log=Log.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,supportsSlashCommands:false,supportsNativeCommands:false,commandPrefix:"/",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(`
10
+ `).trim()}getSessionId(){return this.sessionId}resetSession(){this.sessionId=void 0;}async stop(){this.bridgeStarted&&(await this.eventBridge.stop(),this.bridgeStarted=false,this.sessionId=void 0);}};var ds=Log.create({service:"gateway:interfaces"}),$;function no(o){$=o,o?ds.debug("Agent adapter registered",{hasSubAgentRunner:!!o.subAgentRunner}):ds.debug("Agent adapter cleared");}function io(){return $}function ue(){return $!==void 0}function X(){if(!$)throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");return $}var On={Path:{home:process.env.HOME||process.env.USERPROFILE||"",data:".easbot",cache:".easbot/cache",config:".easbot",state:".easbot/state",log:".easbot/log",bin:".easbot/bin"}},$n={directory:process.cwd(),worktree:process.cwd()};function v(){return $?$.global:On}function Lt(){return $?$.instance:$n}var Nt=null;function ms(o){Nt=o;}async function ft(){return Nt?Nt():null}function Wn(){if(!$?.sdk)throw new Error("SDK not available. Agent adapter is not set or has no SDK.");return $.sdk}function fs(o){let t=Wn();return new Ae(t,o)}var j=Log.create({service:"gateway:config"}),bt={enabled:true,port:8080,hostname:"localhost",path:"",maxConnections:1e3,connectionTimeout:36e5,heartbeatInterval:3e4,sessionExpireMs:36e5,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}},qn={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},Kn={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},Vn={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},Jn={heartbeatInterval:6e4,heartbeatTimeout:3e5,heartbeatCheckInterval:3e5,autoDeregisterTimeout:6e5,maxAgents:100,maxRegistrations:1e3},Qn={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e3},Xn={enabled:true,botToken:"",maxConnections:100,timeout:3e4,polling:{enabled:true,timeout:30}},Yn={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Zn={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},ei={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},ti={enabled:true,path:"/ws",heartbeatInterval:6e4,connectionTimeout:36e5,maxConnections:1e3,cors:true},si={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},ni={enabled:true,relays:[],maxConnections:100,timeout:3e4},Pe,xe=null;async function ys(o){try{if(!existsSync(o))return null;let t=await W__default.readFile(o,"utf-8");t=t.replace(/\{env:([^}]+)\}/g,(r,a)=>{let c=process.env[a];return c===void 0?(j.debug("Environment variable not found",{varName:a,file:o}),""):c});let e=t,s=!1,n=!1,i=[];for(let r=0;r<t.length;r++){let a=t[r];if(n){i.push(a),n=!1;continue}if(a==="\\"){i.push(a),n=!0;continue}if(a==='"'){s=!s,i.push(a);continue}if(!s&&a==="/"&&t[r+1]==="/"){for(;r<t.length&&t[r]!==`
11
+ `&&t[r]!=="\r";)r++;continue}if(!s&&a==="/"&&t[r+1]==="*"){for(r+=2;r<t.length-1;){if(t[r]==="*"&&t[r+1]==="/"){r+=2;break}r++;}continue}i.push(a);}return e=i.join("").trim(),e?JSON.parse(e):null}catch(t){return j.debug("Failed to load config file",{file:o,error:String(t)}),null}}function yt(o,t){let e={...o,...t};return (o.server||t.server)&&(e.server={...o.server,...t.server}),(o.channels||t.channels)&&(e.channels={...o.channels,...t.channels}),e}async function ii(){let o=v(),t=Lt(),e=[],s=pe__default.join(o.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{j.debug("Filesystem utils not available, using basic directories");}let n=process.env.EASBOT_CONFIG_DIR;return n&&(e.push(n),j.debug("Using EASBOT_CONFIG_DIR",{path:n})),[...new Set(e)]}async function ri(o){let t=["gateway.json"],e={};for(let s of t){let n=pe__default.join(o,s),i=await ys(n);if(i)if("gateway"in i&&i.gateway){let r=i.gateway,a={};"enabled"in r&&(a.enabled=r.enabled),"port"in r&&(a.port=r.port),"hostname"in r&&(a.hostname=r.hostname),"path"in r&&(a.path=r.path),"https"in r&&(a.https=r.https),e=yt(e,{server:a,channels:r.channels}),j.debug("Loaded gateway config from file",{file:n});}else "gateway"in i||(e=yt(e,i),j.debug("Loaded gateway config from file (direct format)",{file:n}));}return e}async function ai(o){let t=["easbot.json"];for(let e of t){let s=pe__default.join(o,e),n=await ys(s);if(n?.gateway)return j.debug("Loaded gateway config from easbot.json",{file:s}),n.gateway}return {}}function oi(){return Pe||(Pe=async()=>{let o=await ii(),t={};for(let s of o){let n=await ri(s);t=yt(t,n);let i=await ai(s);t=yt(t,i);}let e=Dt(t);return xe=e,j.info("Gateway config loaded",{directories:o.length,port:e.server?.port,logLevel:e.logLevel}),{config:e,directories:o}}),Pe}async function T(){return oi()()}async function gs(o){return o&&(Pe=void 0,xe=null),(await T()).config}function us(){return xe}function ps(){return xe!==null}function ci(){Pe=void 0,xe=null,j.debug("Config cache cleared");}function li(){return Lt().directory}async function di(){let{config:o}=await T();return ut.parse({...bt,...o.server})}async function gi(o){let{config:t}=await T(),e=t.channels?.[o],n={telegram:et.parse(Xn),slack:tt.parse(Yn),feishu:st.parse(Zn),wechat:nt.parse(ei),webchat:it.parse(ti),signal:rt.parse(si),nostr:at.parse(ni)}[o];if(!n)throw new Error(`Unknown channel type: ${o}`);return {...n,...e}}async function ui(){let{config:o}=await T();return ot.parse({...qn,...o.connectionPool})}async function pi(){let{config:o}=await T();return ct.parse({...Kn,...o.messageQueue})}async function hi(){let{config:o}=await T();return lt.parse({...Vn,...o.circuitBreaker})}async function mi(){let{config:o}=await T();return dt.parse({...Jn,...o.agentRegistry})}async function fi(){let{config:o}=await T();return gt.parse({...Qn,...o.session})}async function yi(){let{config:o}=await T();if(o.client)return pt.parse(o.client)}async function bi(){let{config:o}=await T();if(!(o.client?.autoRegister??true))return;let e=o.server,s=e?.hostname??"localhost",n=e?.port??8080,i=e?.path||"/acp";return `ws://${s}:${n}${i}`}async function Si(){let{config:o}=await T();return o.server?.https}async function Ci(){let{config:o}=await T();return o.server?.auth}async function wi(){let{config:o}=await T();return o.cluster}async function vi(){let{config:o}=await T();return o.defaultAgent}async function hs(){let{config:o}=await T();return o.logLevel??"INFO"}var Ut=bt,Me={maxConnections:1e3,connectionTimeout:36e5};var Ii={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var St={heartbeatInterval:6e4,heartbeatTimeout:3e5,heartbeatCheckInterval:3e5,autoDeregisterTimeout:6e5,maxAgents:100,maxRegistrations:1e3};var Ct={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};var Ai={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var q=class o extends Error{constructor(e,s){super(e);a(this,"code");a(this,"recoverable");a(this,"details");a(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,o);}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 o)return e.recoverable;let s=e.code;return ["ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH"].includes(s??"")}};function y(o,t,e,s=true){return new q(e,{code:t,recoverable:s,details:{channelId:o}})}var wt=class{constructor(t,e){a(this,"log",Log.create({service:"gateway:router"}));a(this,"subscribers",new Map);a(this,"subscriptions",new Map);a(this,"messageSubscriptions",new Map);a(this,"channelPlugins",new Map);a(this,"cancelHandlers",new Set);a(this,"processingMessages",new Map);a(this,"hookRegistry",null);a(this,"sessionManager",null);this.hookRegistry=t??null,this.sessionManager=e??null;}setSessionManager(t){this.sessionManager=t;}async triggerHook(t,e,s){if(this.hookRegistry)try{await this.hookRegistry.triggerEvent(t,e,s);}catch{}}async triggerBeforeSend(t,e,s){if(this.sessionManager)try{await this.sessionManager.bindBackendSession(t.sessionId,s.sessionId);}catch{}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)});}}selectSubscriber(t){let e=this.messageSubscriptions.get(t.sessionId);if(!e||e.size===0){if(this.sessionManager){let r=this.sessionManager.get(t.sessionId);r?.backendSessionId&&(e=this.messageSubscriptions.get(r.backendSessionId));}if(!e||e.size===0){for(let[,r]of this.messageSubscriptions)if(r.size>0){e=r;break}}}if(!e||e.size===0)return null;let s=e.values().next().value;if(!s)return null;let n=this.subscriptions.get(s);if(!n)return null;let i=this.subscribers.get(n.subscriberId);return i?{subscription:n,subscriber:i}:null}async route(t){let e=this.selectSubscriber(t);if(!e)return {success:true,dispatched:false,dispatchedToSubAgent:false};let{subscription:s,subscriber:n}=e;if(t.type==="input"){let i=this.processingMessages.get(t.id);if(i&&i!==n.id)return {success:true,dispatched:false,dispatchedToSubAgent:false};this.processingMessages.set(t.id,n.id);}try{return await this.triggerBeforeSend(t,n.id,{sessionId:s.sessionId,subscriberId:s.subscriberId}),await n.connection.send(t),n.lastActiveAt=Date.now(),{success:!0,dispatched:!0,dispatchedToSubAgent:!1}}catch(i){return this.log.warn("failed to send message to subscriber",{subscriberId:n.id,error:String(i)}),t.type==="input"&&this.processingMessages.delete(t.id),{success:false,dispatched:false,dispatchedToSubAgent:false,error:i instanceof Error?i.message:String(i)}}}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()});}async subscribe(t,e){let s=Rt(e.id,t);if(this.subscriptions.has(s))return this.subscriptions.get(s);for(let[i,r]of this.subscriptions.entries())r.subscriberId===e.id&&r.sessionId===t&&i!==s&&await this.unsubscribe(i);let n={id:s,subscriberId:e.id,sessionId:t,createdAt:Date.now()};return this.subscribers.set(e.id,e),this.subscriptions.set(s,n),this.messageSubscriptions.has(t)||this.messageSubscriptions.set(t,new Set),this.messageSubscriptions.get(t).add(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.messageSubscriptions.get(e.sessionId);s&&(s.delete(t),s.size===0&&this.messageSubscriptions.delete(e.sessionId));}async unsubscribeAll(t){for(let[e,s]of this.subscriptions.entries())s.subscriberId===t&&await this.unsubscribe(e);this.subscribers.delete(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)}getMessageSubscriptions(){return this.messageSubscriptions}getSubscriberCount(t){return this.messageSubscriptions.get(t)?.size??0}getStats(){return {subscribers:this.subscribers.size,subscriptions:this.subscriptions.size,sessions:this.messageSubscriptions.size}}async shutdown(){this.processingMessages.clear(),this.subscribers.clear(),this.subscriptions.clear(),this.messageSubscriptions.clear(),this.channelPlugins.clear(),this.cancelHandlers.clear(),this.log.info("router shutdown");}};var ke=class{constructor(t={}){a(this,"log",Log.create({service:"gateway:message-store"}));a(this,"config");a(this,"messages",new Map);a(this,"sessionMessages",new Map);a(this,"cleanupTimer",null);a(this,"accessOrder",[]);a(this,"storagePath");a(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 loadFromDisk(){let t=0;try{let e=await W.readdir(this.storagePath,{withFileTypes:!0});for(let s of e){if(!s.isDirectory())continue;let n=pe.join(this.storagePath,s.name),i=await W.readdir(n);for(let r of i)if(r.endsWith(".json"))try{let a=pe.join(n,r),c=await W.readFile(a,"utf-8"),d=JSON.parse(c);d.status!=="completed"&&d.status!=="delivered"&&(this.messages.has(d.message.id)||(this.messages.set(d.message.id,d),this.addToSessionMessages(d.message.sessionId,d.message.id),t++));}catch(a){this.log.debug("failed to load message file",{file:r,error:String(a)});}}t>0&&this.log.debug("loaded messages from disk",{count:t});}catch(e){this.log.warn("failed to load messages from disk",{error:String(e)});}return t}addToSessionMessages(t,e){this.sessionMessages.has(t)||this.sessionMessages.set(t,new Set),this.sessionMessages.get(t).add(e);}async ensureDir(t){try{await W.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 pe.join(this.storagePath,`${this.sanitizeFileName(t)}.json`)}getSessionDir(t){return pe.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.addToSessionMessages(t.sessionId,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=pe.join(e,`${this.sanitizeFileName(t.message.id)}.json`);await W.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()),"error"in s&&(n.error=s.error??null),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)=>r.createdAt-i.createdAt),n.slice(0,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.debug("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 ne=class{constructor(t={}){a(this,"log",Log.create({service:"gateway:session-store"}));a(this,"config");a(this,"sessions",new Map);a(this,"channelSessions",new Map);a(this,"autoSaveTimer",null);a(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 se.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(!se.existsSync(t)){this.log.debug("no saved sessions found");return}let e=await se.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 a={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(a.id,a),this.channelSessions.has(a.channel.channelId)||this.channelSessions.set(a.channel.channelId,new Set),this.channelSessions.get(a.channel.channelId).add(a.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 pe.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){se.existsSync(this.config.storagePath)||await se.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 Ti="./data/gateway",_i="contacts",Ei="index.json",re=class{constructor(t={}){a(this,"log",Log.create({service:"gateway:contact-store"}));a(this,"baseDir");a(this,"contactDir");a(this,"indexPath");a(this,"index");a(this,"indexFileMap");a(this,"dirty",false);a(this,"saveTimer",null);a(this,"SAVE_DEBOUNCE_MS",1e3);this.baseDir=t.baseDir??Ti,this.contactDir=pe.join(this.baseDir,_i),this.indexPath=pe.join(this.contactDir,Ei),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 W.mkdir(t,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async loadIndex(){try{let t=await W.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 W.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=Ye(t);if(e){let s=this.getFilePath(e.platform,e.stableId);this.indexFileMap[t]=s;}}}getFilePath(t,e){let s=this.sanitizeFilename(e);return pe.join(this.contactDir,t,`${s}.json`)}sanitizeFilename(t){return t.replace(/[/\\:*?"<>|]/g,"_")}getPlatformDir(t){return pe.join(this.contactDir,t)}async save(t){let{platform:e,stableId:s,uid:n}=t,i=this.getFilePath(e,s);return await this.ensureDir(pe.dirname(i)),await W.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=Et(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=Ye(t);return e?this.findByPlatformId(e.platform,e.stableId):null}async findByPlatformId(t,e){let s=Xe(t,e),n=this.index.byUid[s];if(n)try{let r=await W.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 W.readFile(i,"utf-8"),a=JSON.parse(r);return this.index.byUid[s]=i,this.indexFileMap[s]=i,this.dirty=!0,await this.saveIndex(),a}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 W.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),a=[];for(let c of r){let d=await this.findByUid(c);d&&a.push(d);}return {contacts:a,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 c=await this.listByPlatform(t.platform,t.limit,t.offset),d=c.contacts;if(t.username){let g=t.username.toLowerCase();d=d.filter(p=>p.profile.username?.toLowerCase().includes(g));}if(t.email){let g=t.email.toLowerCase();d=d.filter(p=>p.profile.email?.toLowerCase().includes(g));}if(t.phone){let g=t.phone.replace(/\s/g,"");d=d.filter(p=>p.profile.phone?.replace(/\s/g,"").includes(g));}return {contacts:d,total:c.total,hasMore:c.hasMore}}let e=[];for(let c of Object.keys(this.index.byPlatform)){let d=await this.listByPlatform(c,1e3,0);e.push(...d.contacts);}let s=e;if(t.username){let c=t.username.toLowerCase();s=s.filter(d=>d.profile.username?.toLowerCase().includes(c));}if(t.email){let c=t.email.toLowerCase();s=s.filter(d=>d.profile.email?.toLowerCase().includes(c));}if(t.phone){let c=t.phone.replace(/\s/g,"");s=s.filter(d=>d.profile.phone?.replace(/\s/g,"").includes(c));}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 Ft=class{constructor(t){a(this,"cache",new Map);a(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}},Te=class{constructor(t,e={}){a(this,"store",t);a(this,"cache");a(this,"usernameIndex");a(this,"emailIndex");a(this,"phoneIndex");a(this,"platformIndex");a(this,"initialized",false);this.cache=new Ft(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 z=Log.create({service:"gateway:storage:agent-registry"}),_e=class{constructor(t){a(this,"config");a(this,"filePath");a(this,"cache",new Map);a(this,"initialized",false);this.config=t,this.filePath=pe.join(t.dataDir,"agent-registry.json");}async initialize(){if(!this.initialized)try{await W.mkdir(this.config.dataDir,{recursive:!0}),this.initialized=!0,z.debug("Agent registry store initialized",{dataDir:this.config.dataDir});}catch(t){throw z.error("Failed to initialize agent registry store",{dataDir:this.config.dataDir,error:String(t)}),t}}async loadFromDisk(){await this.initialize();try{let t=await W.readFile(this.filePath,"utf-8"),e=JSON.parse(t),s=new Map;for(let n of e)n.agent?.id&&s.set(n.agent.id,n);return z.debug("Agent registry loaded from disk",{count:s.size}),s}catch(t){return t.code==="ENOENT"?(z.debug("Agent registry file not found, starting fresh"),new Map):(z.error("Failed to load agent registry from disk",{error:String(t)}),new Map)}}async saveToDisk(){await this.initialize();try{let t=Array.from(this.cache.values());await W.writeFile(this.filePath,JSON.stringify(t,null,2),"utf-8"),z.debug("Agent registry saved to disk",{count:this.cache.size});}catch(t){throw z.error("Failed to save agent registry to disk",{error:String(t)}),t}}async loadAll(){let t=await this.loadFromDisk();return this.cache=t,Array.from(this.cache.values()).map(e=>e.agent)}async save(t){await this.initialize();let e={agent:t,storedAt:Date.now()};this.cache.set(t.id,e),await this.saveToDisk(),z.debug("Agent registration saved",{agentId:t.id});}async saveAll(t){await this.initialize();for(let e of t){let s={agent:e,storedAt:Date.now()};this.cache.set(e.id,s);}await this.saveToDisk(),z.debug("All agent registrations saved",{count:t.length});}async delete(t){await this.initialize(),this.cache.has(t)&&(this.cache.delete(t),await this.saveToDisk(),z.debug("Agent registration deleted",{agentId:t}));}getFilePath(){return this.filePath}};var Ee=class{constructor(t={}){a(this,"log",Log.create({service:"gateway:session"}));a(this,"sessionStore");a(this,"config");a(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 ne({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=Je(t),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),n):(n={id:s,channel:t,backendSessionId:null,subscribers:new Set,state:Qe(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(n),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);}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);}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);}findByBackendSessionId(t){for(let e of this.sessionStore.getAll())if(e.backendSessionId===t)return e}getState(t){return this.sessionStore.get(t)?.state}async incrementMessageCountOrCreate(t,e){let s=this.sessionStore.get(t);if(!s){if(!e)throw new Error(`Cannot create session: channelInfo is required when session "${t}" does not exist`);let n=Je(e);n!==t&&this.log.warn("sessionId mismatch, using correct sessionId from channelInfo",{providedSessionId:t,correctSessionId:n}),s={id:n,channel:e,backendSessionId:null,subscribers:new Set,state:Qe(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(s),this.log.debug("session auto-created from message",{sessionId:n,platform:e.platform,channelId:e.channelId,chatId:e.chatId,userId:e.userId});}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);}async removeSubscriber(t,e){let s=this.sessionStore.get(t);s&&(s.subscribers.delete(e),await this.sessionStore.set(s));}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}async save(){}getStats(){return this.sessionStore.getStats()}};var Re=class{constructor(t={}){a(this,"log",Log.create({service:"gateway:plugin-loader"}));a(this,"plugins",new Map);a(this,"messageHandler",null);a(this,"healthCheckTimer",null);a(this,"config");a(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;}updateSessionHandler(t){this.messageHandler&&(this.messageHandler.session=t,this.log.debug("session handler updated"));}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 q(`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 q("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 J=class extends Error{constructor(e,s,n){super(e);a(this,"code",s);a(this,"configuredChannels",n);this.name="ChannelSelectionError";}},V=Log.create({service:"gateway:channel-selection"});function me(o){if(!(!o||typeof o!="string"))return o.toLowerCase().trim()}async function $t(o){let{channel:t,sessionId:e,userId:s,defaultChannel:n,fallbackChannels:i,sessionManager:r,pluginLoader:a,contactStore:c}=o,d=me(t);if(d){let S=Bt(d,a);if(S){if(e){let C=Ot(e,r);if(C){if(C.channelInfo.chatId||C.channelInfo.userId)return V.debug("enriching explicit channel with session info",{sessionId:e,chatId:C.channelInfo.chatId,userId:C.channelInfo.userId}),{...S,channelInfo:{...S.channelInfo,chatId:C.channelInfo.chatId,userId:C.channelInfo.userId}}}else if(s&&r){V.debug("session not found, creating new session for private chat",{userId:s});let _=s,E={platform:S.channelInfo.platform,channelId:S.channel,chatId:_,userId:s};try{let k=await r.getOrCreate(E);return V.debug("auto-created session for private chat",{sessionId:k.id,chatId:_,userId:s}),{channel:S.channel,source:"session-bound",channelInfo:k.channel}}catch(k){V.warn("failed to auto-create session, using explicit channel info",{userId:s,error:String(k)});}}}if(s&&c){let C=await Gi(d,s,c,a);if(C)return C}return S}if(e){let C=Ot(e,r);if(C){if((!C.channelInfo.chatId||!C.channelInfo.userId)&&C.channelInfo.platform!=="api"){let E=Fi(C.channelInfo.platform,r);if(E)return V.debug("session missing chatId/userId, using session with complete info",{originalSessionId:e,newSessionId:E.channelInfo.chatId}),E}return C}}throw new J(`Channel \u4E0D\u53EF\u7528\u6216\u672A\u914D\u7F6E: ${d}`,"CHANNEL_UNAVAILABLE",[])}if(e){let S=Ot(e,r);if(S)return S}if(s&&c){let S=await Ui(s,c,a);if(S)return S}let g=Wt(a);if(g.length===0)throw new J("\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 p=me(n);if(p){let S=Bt(p,a);if(S)return V.debug("using default channel",{channel:p}),{...S,source:"default"};V.warn("default channel unavailable",{channel:p});}if(g.length===1){let S=g[0],C=a?.getPlugin(S);return {channel:S,source:"single-configured",channelInfo:{platform:C?.platform,channelId:S}}}let h=(i??[]).map(me).filter(S=>S!==void 0);for(let S of h){let C=Bt(S,a);if(C)return V.debug("using fallback channel",{channel:S}),{...C,source:"fallback"};V.debug("fallback channel unavailable, trying next",{channel:S});}throw p?new J(`\u914D\u7F6E\u7684\u9ED8\u8BA4 Channel \u4E0D\u53EF\u7528: ${p}`,"CHANNEL_UNAVAILABLE",g):new J(`\u9700\u8981\u660E\u786E\u6307\u5B9A Channel\uFF08\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF09: ${g.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",g)}function Bt(o,t){if(!t)return null;let e=t.getPlugin(o);if(e&&t.isRunning(o))return {channel:o,source:"explicit",channelInfo:{platform:e.platform,channelId:o}};let s=me(o);if(!s)return null;let n=t.getAllPlugins();for(let i of n)if(t.isRunning(i.id)&&me(i.platform)===s)return {channel:i.id,source:"explicit",channelInfo:{platform:i.platform,channelId:i.id}};return null}function Ot(o,t){if(!t)return null;let e=t.get(o);return e?{channel:e.channel.channelId,source:"session-bound",channelInfo:e.channel}:null}async function Gi(o,t,e,s){let n=s?.getPlugin(o);if(!n)return null;let i=await e.findByPlatformId(n.platform,t);return i?{channel:o,source:"explicit",channelInfo:{platform:n.platform,channelId:o,userId:i.stableId,chatId:i.stableId}}:null}async function Ui(o,t,e){let s=Wt(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,o);if(r)return {channel:n,source:"single-configured",channelInfo:{platform:i.platform,channelId:n,userId:r.stableId,chatId:r.stableId}}}return null}function Wt(o){if(!o)return [];let t=[],e=o.getAllPlugins();for(let s of e)o.isRunning(s.id)&&t.push(s.id);return t}function Ht(o){switch(o.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: ${o.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 o.message;case "UNKNOWN_CHANNEL":return `\u672A\u77E5\u7684 Channel: ${o.message}\u3002\u8BF7\u68C0\u67E5 Channel ID \u662F\u5426\u6B63\u786E\u3002`;default:return o.message}}function Fi(o,t){if(!t)return null;let e=t.getAll?.()??[];for(let s of e)if(s.channel.platform===o&&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===o&&s.channel.chatId)return {channel:s.channel.channelId,source:"session-bound",channelInfo:s.channel};return null}var b=Log.create({service:"gateway:websocket-server"});function zt(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function L(o,t){for(let[e,s]of t.entries())if(s===o)return e;return null}var ae=class{constructor(t={}){a(this,"config");a(this,"server",null);a(this,"wss",null);a(this,"httpsServer",null);a(this,"httpRedirectServer",null);a(this,"connections",new Map);a(this,"subscriptions",new Map);a(this,"clientLastActivity",new Map);a(this,"cleanupInterval",null);a(this,"heartbeatInterval",null);a(this,"startTime",0);a(this,"running",false);a(this,"channelResolveParams",null);a(this,"pluginLoaderRef",null);a(this,"agentSyncRef",null);a(this,"agentRegistryRef",null);a(this,"routerRef",null);a(this,"subscribers",new Map);this.config={...Ut,...t};}setChannelResolveDeps(t){this.channelResolveParams=t;}setPluginLoader(t){this.pluginLoaderRef=t;}getGatewayId(){let t=this.config.https?.enabled?"https":"http",e=this.config.hostname||"localhost",s=this.config.port||8080,n=`${t}://${e}:${s}`;return zi.createHash("sha256").update(n).digest("hex").substring(0,16)}setAgentSync(t){this.agentSyncRef=t;}setAgentRegistry(t){this.agentRegistryRef=t;}setRouter(t){this.routerRef=t;}getChannelResolveParams(){return this.channelResolveParams?this.channelResolveParams:{}}async start(){if(this.running){b.warn("WebSocket server is already running");return}b.debug("WebSocket server starting",{port:this.config.port,hostname:this.config.hostname,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){b.error("Error processing WebSocket message",{error:r.message}),this.sendError(i,r.message);}},onClose:(n,i)=>{this.handleDisconnection(i);},onError:(n,i)=>{b.error("WebSocket error",{error:n.type});}},e=this.config.https?.enabled??false;try{e?await this.startHTTPSServer(t):await this.startHTTPServer(t);}catch(n){throw b.error("WebSocket server start: HTTP/HTTPS server failed",{error:n instanceof Error?n.message:String(n)}),n}this.cleanupInterval=setInterval(()=>this.cleanupInactiveClients(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let s=e?"wss":"ws";b.info("WebSocket server started",{url:`${s}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(t){this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let e=this.server.raw;e?this.setupWebSocketUpgrade(e,t):b.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(t){let e=this.config.https,s=this.loadSSLCertificates(e);if(!s){b.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=Wi.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,t),await new Promise(i=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{b.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:se__default.readFileSync(t.certPath),key:se__default.readFileSync(t.keyPath)}:null}catch(e){return b.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 a=new URL(s.url||"/",`http://${s.headers.host}`).pathname,c=this.config.path||"";(a===c||c===""&&(a==="/"||a===""))&&this.wss.handleUpgrade(s,n,i,d=>{e.onOpen?.({type:"open"},d),d.on("message",g=>{e.onMessage?.({data:g},d);}),d.on("close",(g,p)=>{e.onClose?.({code:g,reason:p},d);}),d.on("error",g=>{e.onError?.({type:"error",message:g.message},d);});});}catch{}});}startHTTPRedirectServer(t){this.httpRedirectServer=Hi.createServer((e,s)=>{let i=`https://${e.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${e.url}`;s.writeHead(301,{Location:i,"Content-Type":"text/plain"}),s.end(`Redirecting to ${i}`);}),this.httpRedirectServer.listen(t,this.config.hostname,()=>{b.info("HTTP redirect server started",{port:t,hostname:this.config.hostname});});}async stop(){if(!this.running){b.warn("WebSocket server is not running");return}b.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{}this.connections.clear(),this.subscriptions.clear(),this.subscribers.clear(),this.clientLastActivity.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,b.info("WebSocket server stopped");}touchClient(t){this.clientLastActivity.set(t,Date.now());let e=this.subscriptions.get(t);e&&(e.lastActivityAt=Date.now());}getConnectionCount(){return this.connections.size}getStartTime(){return this.startTime}getSubscriptionCount(){return this.subscribers.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??Me.maxConnections)){b.warn("Maximum connections reached, rejecting new connection"),t.close(1013,"Maximum connections reached");return}let e=zt();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()}),b.debug("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"]}});}async handleDisconnection(t){let e=L(t,this.connections);e&&(this.connections.delete(e),await this.cleanupClientResources(e),b.debug("WebSocket client disconnected",{clientId:e,totalConnections:this.connections.size}));}async cleanupClientResources(t){if(b.debug("Cleaning up client resources",{clientId:t}),this.routerRef){try{await this.routerRef.unsubscribeAll(t);}catch{}this.subscribers.delete(t),b.debug("Subscriber cleaned up from router",{clientId:t});}if(this.agentSyncRef)try{await this.agentSyncRef.cleanupClient(t);}catch{}this.subscriptions.delete(t),this.clientLastActivity.delete(t);}async handleMessage(t,e){let s=L(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 "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;case "agent_list_request":await this.handleAgentListRequest(t,e);break;case "agent_subscribe":await this.handleAgentSubscribe(t,e);break;case "agent_register":await this.handleAgentRegister(t,e);break;case "agent_deregister":await this.handleAgentDeregister(t,e);break;default:this.sendError(t,`Unknown message type: ${e.type}`);}}async handleSubscribe(t,e){if(e.type!=="subscribe"||!e.sessionId){this.sendError(t,"Invalid subscribe request");return}let s=e.clientId,n;if(s){n=s;let r=L(t,this.connections);r&&r!==n&&(await this.cleanupClientResources(r),this.connections.delete(r),b.info("Client reconnected with different clientId, cleaned up old resources",{oldClientId:r,newClientId:n})),this.connections.set(n,t);}else n=L(t,this.connections)??zt(),L(t,this.connections)||this.connections.set(n,t);let i=this.subscriptions.get(n);if(i?(i.ws=t,i.lastActivityAt=Date.now()):(i={clientId:n,ws:t,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()},this.subscriptions.set(n,i)),e.payload?.eventTypes)for(let r of e.payload.eventTypes)i.subscribedEventTypes.add(r);if(b.debug("Client subscribed to session",{clientId:n,sessionId:e.sessionId}),this.routerRef){if(this.subscribers.get(n))try{await this.routerRef.unsubscribeAll(n);}catch{}let a=e.payload?.clientType||"tui",c={id:n,type:a,createdAt:Date.now(),lastActiveAt:Date.now(),connection:{send:async d=>{this.sendMessage(t,{type:"message",sessionId:d.sessionId,payload:{id:d.id,type:d.type,content:d.content,metadata:d.metadata,timestamp:d.timestamp}});},close:async()=>{t.close(1e3,"Subscriber closed");},isConnected:()=>t.readyState===t.OPEN}};this.subscribers.set(n,c),await this.routerRef.subscribe(e.sessionId,c),b.debug("Subscriber registered to router",{clientId:n,sessionId:e.sessionId});}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=L(t,this.connections);if(s){if(b.debug("Client unsubscribed from session",{clientId:s,sessionId:e.sessionId}),this.routerRef){let n=this.subscribers.get(s);if(n){let i=`sub_${n.id}_${e.sessionId}`;try{await this.routerRef.unsubscribe(i),b.debug("Subscriber unregistered from router",{clientId:s,sessionId:e.sessionId});}catch(r){b.debug("Failed to unsubscribe from router (subscription may not exist)",{clientId:s,sessionId:e.sessionId,error:String(r)});}this.subscribers.delete(s);}}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}let s=this.getClientIdByWs(t)||"unknown";b.debug("Message received from WebSocket client",{clientId:s,sessionId:e.sessionId});let n=e.payload,i=n.message?{...n.message}:{id:`ws_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:e.sessionId,content:n.content||[{type:"text",text:""}]};b.debug("Message received from WebSocket client (use HTTP API to send)",{messageId:i.id,sessionId:e.sessionId}),this.sendMessage(t,{type:"response",sessionId:e.sessionId,success:true,result:{received:true}});}getClientIdByWs(t){return L(t,this.connections)}getClientWs(t){return this.connections.get(t)}async handleInterrupt(t,e){if(e.type!=="interrupt"||!e.sessionId){this.sendError(t,"Invalid interrupt request");return}b.debug("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}let s=L(t,this.connections);if(!s){this.sendError(t,"Client not found");return}if(b.debug("Release subscription requested via WebSocket",{clientId:s,sessionId:e.sessionId}),this.routerRef){let i=`sub_${s}_${e.sessionId}`;try{await this.routerRef.unsubscribe(i);}catch{}}let n=this.subscriptions.get(s);n&&n.subscribedSessions.delete(e.sessionId),this.sendMessage(t,{type:"subscriptionReleased",sessionId:e.sessionId});}async checkConnectionTimeout(){let t=Date.now(),e=this.config.connectionTimeout??Me.connectionTimeout,s=[];for(let[n,i]of this.subscriptions.entries())t-i.lastActivityAt>e&&s.push(n);for(let n of s){await this.cleanupClientResources(n);let i=this.connections.get(n);if(i){b.debug("Closing inactive connection",{clientId:n,lastActivityAt:this.clientLastActivity.get(n),timeoutMs:e});try{i.close(1001,"Connection timeout");}catch(r){b.debug("Error closing timed out connection",{clientId:n,error:String(r)});}this.connections.delete(n);}}s.length>0&&b.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size});}async cleanupInactiveClients(){let t=Date.now(),e=[],s=this.config.connectionTimeout??Me.connectionTimeout;for(let[n,i]of this.clientLastActivity.entries())t-i>s&&e.push(n);for(let n of e){await this.cleanupClientResources(n);let i=this.connections.get(n);if(i){b.debug("Client inactive, closing connection",{clientId:n,lastActivity:this.clientLastActivity.get(n),timeoutMs:s});try{i.close(1001,"Client inactive");}catch(r){b.debug("Error closing inactive client",{clientId:n,error:String(r)});}this.connections.delete(n);}}e.length>0&&b.debug("Cleaned up inactive clients",{count:e.length,remainingActive:this.clientLastActivity.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:async t=>{let e=await ft();if(e)return t.json(e);let s={status:this.running?"running":"stopped",connections:this.connections.size,sessions:0,messageSubscriptions:0,agentSubscriptions:0,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0",channels:[]};return t.json(s)}},{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(a=>({uid:a.uid,platform:a.platform,stableId:a.stableId,profile:a.profile,lastSeenAt:a.lastSeenAt,createdAt:a.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 b.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 b.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"),a=t.req.query("chatId"),c=[],g=this.getChannelResolveParams().sessionManager?.getAll?.()??[];for(let h of g){let S=!n||h.channel.platform===n,C=!i||h.channel.channelId===i,_=!r||h.channel.userId===r,E=!a||h.channel.chatId===a;S&&C&&(!r&&!a||_&&E)&&c.push({id:h.id,platform:h.channel.platform,channelId:h.channel.channelId,userId:h.channel.userId,chatId:h.channel.chatId,chatType:h.channel.chatType,chatTitle:h.channel.chatTitle,state:h.state.status,createdAt:h.createdAt,lastActiveAt:h.lastActiveAt});}let p=c.slice(s,s+e);return t.json({sessions:p,total:c.length,hasMore:s+e<c.length})}},{method:"get",path:"/sessions/:sessionId",handler:async t=>{let e=t.req.param("sessionId"),n=this.channelResolveParams?.sessionManager?.get(e);if(!n)return t.json({error:"Session not found"},404);let i=0;return n.backendSessionId&&this.routerRef&&(i=this.routerRef.getMessageSubscriptions().get(n.backendSessionId)?.size??0),t.json({id:n.id,platform:n.channel.platform,channelId:n.channel.channelId,userId:n.channel.userId,chatId:n.channel.chatId,state:n.state.status,backendSessionId:n.backendSessionId,subscriberCount:i,createdAt:n.createdAt,lastActiveAt:n.lastActiveAt})}},{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),a={id:r.id,createdAt:r.createdAt};return t.json(a)}},{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);let n=this.getChannelResolveParams(),i=e;if(n.sessionManager){let r=n.sessionManager.get(e);if(r)i=r.id;else {let a=n.sessionManager.findByBackendSessionId(e);a&&(b.debug("found gateway session via backendSessionId",{backendSessionId:e,gatewaySessionId:a.id}),i=a.id);}}try{let r=await $t({...n,sessionId:i,channel:s.channel,userId:s.userId??s.chatId});b.debug("channel resolved for message",{sessionId:e,channel:r.channel,source:r.source,channelInfo:r.channelInfo});let a=Identifier.ascending("message"),c={...r.channelInfo};if(!c.chatId){let p=s.chatId??r.channelInfo.userId;p&&(c.chatId=p,b.debug("filled channelInfo.chatId from request body or session",{chatId:c.chatId}));}if(!c.userId&&c.chatId&&(c.userId=s.userId??c.chatId,b.debug("filled channelInfo.userId from chatId",{userId:c.userId})),!c.chatId)return b.error("channelInfo missing chatId, cannot send message",{sessionId:i,channelInfo:c,body:{userId:s.userId,chatId:s.chatId}}),t.json({error:"channelInfo missing chatId"},400);let d={id:a,sessionId:i,type:"output",content:typeof s.content=="string"?[{type:"text",text:s.content}]:s.content||[],metadata:{channel:c,replyToMessageId:s.replyToMessageId,processorId:s.processorId??"gateway",agent:s.agent??"gateway"},timestamp:Date.now()};if(this.pluginLoaderRef)try{await this.pluginLoaderRef(r.channel,d,{}),b.debug("message sent via pluginLoader",{messageId:a,channel:r.channel});}catch(p){return b.error("failed to send message",{sessionId:i,error:String(p)}),t.json({error:String(p)},500)}else return b.error("no pluginLoader available for sending message",{sessionId:i}),t.json({error:"Plugin loader not available"},500);let g={messageId:a,sessionId:i,createdAt:Date.now(),metadata:{channel:r.channel,channelSource:r.source,channelInfo:r.channelInfo}};return t.status(202),t.json(g)}catch(r){return r instanceof J?(b.warn("channel selection failed",{sessionId:i,error:r.message}),t.json({error:Ht(r),code:r.code},400)):(b.error("send message error",{sessionId:i,error:String(r)}),t.json({error:String(r)},500))}}},{method:"get",path:"/subscriptions",handler:t=>{let e=t.req.query("sessionId"),s=t.req.query("subscriberId");b.debug("subscriptions endpoint called",{routerRefExists:!!this.routerRef,agentSyncRefExists:!!this.agentSyncRef,filterSessionId:e,filterSubscriberId:s});let n=[];if(this.routerRef){let r=this.routerRef,a=r.getMessageSubscriptions();b.debug("messageSubscriptions",{size:a.size,entries:Array.from(a.entries())});for(let[c,d]of a.entries()){if(e&&e!=="agent-list"&&c!==e)continue;let g=new Map;for(let p of d){let h=r.getSubscription(p);if(h){if(s&&h.subscriberId!==s)continue;g.set(h.subscriberId,{id:h.subscriberId,subscriptionId:p});}}g.size>0&&n.push({type:"message",sessionId:c,subscriberCount:g.size,subscribers:Array.from(g.values())});}}if(this.agentSyncRef&&!(e&&e!=="agent-list")){let r=this.agentSyncRef.getSubscribers();b.debug("agentSubscribers",{count:r.length,subscribers:r,filterSubscriberId:s});let a=s?r.filter(c=>c===s):r;b.debug("filteredAgents",{filteredAgents:a}),a.length>0&&n.push({type:"agent",sessionId:"agent-list",subscriberCount:a.length,subscribers:a.map(c=>({id:c,subscriptionId:`agent_sub_${c}`}))});}let i={subscriptions:n,total:n.length};return b.debug("subscriptions response",{subscriptionsCount:n.length,subscriptions:n.map(r=>({type:r.type,sessionId:r.sessionId,subscriberCount:r.subscriberCount}))}),t.json(i)}}]}async handleAgentListRequest(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_list_request"){this.sendError(t,"Invalid agent list request");return}let s=L(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentListRequest(s,e.requestId);}async handleAgentSubscribe(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_subscribe"){this.sendError(t,"Invalid agent subscribe request");return}let s=e.clientId,n;if(s){n=s;let i=L(t,this.connections);i&&i!==n&&this.connections.delete(i),this.connections.set(n,t);}else n=L(t,this.connections)??zt(),L(t,this.connections)||this.connections.set(n,t);await this.agentSyncRef.handleAgentSubscribe(n,e.subscribe);}async handleAgentRegister(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_register"||!e.payload){this.sendError(t,"Invalid agent register request");return}let s=L(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentRegister(s,e.payload);}async handleAgentDeregister(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_deregister"||!e.payload){this.sendError(t,"Invalid agent deregister request");return}let s=L(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentDeregister(s,e.payload);}};function qi(o){return o.toLowerCase().replace(/^\//,"").replace(/@[^\s]+$/,"")}function Ki(o){return o.replace(/[-_]/g,"").toLowerCase()}var oe=[{command:"new",description:"Reset session and start a new conversation"},{command:"status",description:"Show gateway and channel status"},{command:"commands",description:"Show available commands"}],P=class{constructor(){a(this,"version","1.0.0");a(this,"log");a(this,"config",null);a(this,"messageHandler",null);a(this,"_status","stopped");a(this,"lastActivity",0);a(this,"startPromise",null);a(this,"stopPromise",null);}initLog(){this.log=Log.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,supportsSlashCommands:false,supportsNativeCommands:false,commandPrefix:"/",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(`
12
12
  `)}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()});}async getCommandList(){try{let t=X(),s=(await t.sdk.config.get().then(i=>i.data).catch(()=>{}))?.context?.mode??"general";return (await t.sdk.command.list({contextMode:s},{throwOnError:!0})).data??[]}catch(t){return this.log.warn("failed to get command list",{error:String(t)}),[]}}async processLocalCommand(t,e,s){switch(t.toLowerCase().replace(/^\//,"").replace(/@[^\s]+$/,"")){case "new":return this.handleNewCommand(e);case "status":return this.handleStatusCommand(e);case "commands":return this.handleCommandsCommand();default:return {handled:false}}}async handleCommandsCommand(){try{let e=(await this.getCommandList()).filter(n=>n.hidden!==!0),s=[];s.push("\u{1F4D6} **Available Commands**"),s.push(""),s.push("**Local**");for(let n of oe)s.push(`\`/${n.command}\` - ${n.description}`);if(s.push(""),s.push("**EASBot**"),e.length===0)s.push("_No commands available_");else for(let n of e){let i=n.description?.trim()||n.name;s.push(`\`/${n.name}\` - ${i}`);}return {handled:!0,reply:s.join(`
13
13
  `)}}catch(t){return this.log.error("failed to process /commands command",{error:String(t)}),{handled:true,reply:`\u274C Failed to list commands: ${String(t)}`}}}async handleNewCommand(t){try{return this.messageHandler?.session?this.messageHandler.session.getSession(t)?(await this.messageHandler.session.unbindBackendSession(t),this.log.debug("session backendSessionId cleared",{sessionId:t}),{handled:!0,reply:"\u2705 Session reset. Next message will create a new session."}):{handled:!0,reply:"\u274C Session not found"}:{handled:!0,reply:"\u274C Session management interface unavailable"}}catch(e){return this.log.error("failed to process /new command",{error:String(e)}),{handled:true,reply:`\u274C Operation failed: ${String(e)}`}}}async handleStatusCommand(t){try{let e=this.getStatus(),s=await this.healthCheck(),n;this.messageHandler?.session&&(n=this.messageHandler.session.getSession(t)?.backendSessionId),this.log.debug("handleStatusCommand: getting gateway status via global function");let i=await ft();return this.log.debug("handleStatusCommand: gateway status retrieved",{hasGatewayStatus:!!i}),{handled:!0,reply:this.formatStatusReport(e,s,t,n,i)}}catch(e){return this.log.error("failed to process /status command",{error:String(e)}),{handled:true,reply:`\u274C Failed to get status: ${String(e)}`}}}async processCommand(t){let e=t.text.trim();if(!e.startsWith("/"))return {handled:false};let s=e.split(/\s+/),n=s[0]??"",i=s.slice(1),r=qi(n),a=await this.processLocalCommand(n,t.sessionId,t.chatId);if(a.handled)return {handled:true,reply:a.reply};let d=(await this.getCommandList()).find(g=>Ki(g.name)===r);if(d){let g={};return t.messageId&&(g.messageId=t.messageId),t.replyToMessageId&&(g.replyToMessageId=t.replyToMessageId),{handled:true,gatewayMessage:A(t.sessionId,"input",[{type:"command",command:d.name,arguments:i.join(" ")}],{channel:t.channelInfo,...Object.keys(g).length>0?{context:g}:{}})}}return {handled:false}}formatStatusReport(t,e,s,n,i){let r=[];if(r.push("\u{1F4CA} **Gateway Status Report**"),r.push(""),r.push("---"),r.push(""),r.push("### Gateway"),i){let g=i.status==="running"?"\u{1F7E2}":"\u26AA";if(r.push(`- **Status**: ${g} ${i.status}`),r.push(`- **Version**: ${i.version??"unknown"}`),r.push(`- **Uptime**: ${this.formatUptime(i.uptime)}`),r.push(`- **Connections**: ${i.connections}`),r.push(`- **Sessions**: ${i.sessions}`),r.push(`- **Message Subscriptions**: ${i.messageSubscriptions}`),r.push(`- **Agent Subscriptions**: ${i.agentSubscriptions}`),i.agents&&r.push(`- **Agents**: ${i.agents.total} (healthy: ${i.agents.healthy}, unhealthy: ${i.agents.unhealthy})`),i.channels&&i.channels.length>0){let p=i.channels.map(h=>h.platform).join(", ");r.push(`- **Channels**: ${p}`);}}else r.push("- **Status**: N/A");r.push(""),r.push("### Channel");let a=t.status==="running"?"\u{1F7E2}":t.status==="error"?"\u{1F534}":"\u26AA";r.push(`- **Platform**: ${this.platform}`),r.push(`- **Plugin ID**: ${this.id}`),r.push(`- **Name**: ${this.name}`),r.push(`- **Status**: ${a} ${t.status}`),r.push(`- **Health**: ${e.healthy?"\u2705 OK":"\u274C Error"}`),e.error&&r.push(`- **Error**: ${e.error}`),this.version&&r.push(`- **Version**: ${this.version}`),r.push(`- **Last Activity**: ${new Date(t.lastActivity??Date.now()).toLocaleString()}`),r.push(""),r.push("### Session");let c=s.split("_"),d=c.length>=2?`${c[0]}_${c[1]}...`:s;return r.push(`- **Session ID**: \`${d}\``),r.push(`- **Backend Session**: ${n?`\`${n}\``:"\u274C Not Bound"}`),r.push(""),r.push("---"),r.push(`*Report generated: ${new Date().toLocaleString()}*`),r.join(`
14
14
  `)}formatUptime(t){if(t<=0)return "0s";let e=Math.floor(t/1e3),s=Math.floor(e/60),n=Math.floor(s/60),i=Math.floor(n/24),r=[];return i>0&&r.push(`${i}d`),n%24>0&&r.push(`${n%24}h`),s%60>0&&r.push(`${s%60}m`),(e%60>0||r.length===0)&&r.push(`${e%60}s`),r.slice(0,2).join(" ")}};var De=class extends P{constructor(e="telegram-main"){super();a(this,"id");a(this,"platform","telegram");a(this,"name","Telegram Bot");a(this,"botConfig",null);a(this,"baseUrl","");a(this,"abortController",null);a(this,"lastUpdateId",0);a(this,"typingTimers",new Map);a(this,"sentMessages",new Map);a(this,"sessionIdMap",new Map);a(this,"commandRouter",new Map);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});a(this,"pollingStopped",false);this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw y(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.debug("Telegram bot connected",{id:e.id,username:e.username,first_name:e.first_name}),this.log.debug("syncBotCommands: calling syncBotCommands"),await this.syncBotCommands(),this.botConfig.polling?.enabled!==false&&this.startPolling();}async doStop(){this.abortController?.abort(),this.abortController=null,this.pollingStopped=false,this.retryState.attempts=0,this.clearAllTyping(),this.commandRouter.clear(),this.botConfig=null,this.log.debug("Telegram plugin stopped");}async doHealthCheck(){return this._status!=="running"?false:this.pollingStopped?(this.log.warn("Polling was stopped, attempting restart"),this.restartPolling(),true):this.abortController!=null&&!this.abortController.signal.aborted}async send(e){let s=e.metadata.channel.chatId;if(!s)throw y(this.id,"MESSAGE_SEND_FAILED","Chat ID is required");let n=this.extractText(e),i=e.metadata.context?.replyTo,r=this.detectParseMode(e),a=e.content.find(g=>g.type==="image"),c=e.content.find(g=>g.type==="file"),d;if(a){let g=a.image,p=n||void 0;d=await this.sendPhoto(s,g,p);}else if(c){let g=c.data,p=n||void 0;d=await this.sendDocument(s,g,p);}else try{d=await this.sendApiMessage(s,n,{parseMode:r,replyTo:i?parseInt(i,10):void 0});}catch(g){if(r!=="None"&&this.isParseError(g))this.log.debug("parse error, retrying with plain text",{parseMode:r,error:String(g)}),d=await this.sendApiMessage(s,n,{parseMode:"None",replyTo:i?parseInt(i,10):void 0});else throw g}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",a;if(typeof s=="string")if(s.startsWith("file://"))a=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 a=s;this.log.debug("sendPhoto: calling Fetch.postForm",{url:`${this.baseUrl}/sendPhoto?${i}`,filename:r});let c=await Fetch.postForm(`${this.baseUrl}/sendPhoto?${i}`,[{name:"photo",value:a,filename:r}],{timeout:3e5});if(this.log.debug("sendPhoto: response received",{ok:c.ok,status:c.status,data:c.data}),!c.ok)throw new Error(`sendPhoto failed: ${c.data.description||"unknown error"}`);return c.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",a;if(typeof s=="string")if(s.startsWith("file://"))a=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 a=s;this.log.debug("sendDocument: calling Fetch.postForm",{url:`${this.baseUrl}/sendDocument?${i}`,filename:r});let c=await Fetch.postForm(`${this.baseUrl}/sendDocument?${i}`,[{name:"document",value:a,filename:r}],{timeout:3e5});if(this.log.debug("sendDocument: response received",{ok:c.ok,status:c.status,data:c.data}),!c.ok)throw new Error(`sendDocument failed: ${c.data.description||"unknown error"}`);return c.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,supportsSlashCommands:true,supportsNativeCommands:true,commandPrefix:"/",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.debug("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??30,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),a=e.new_reaction.some(c=>c.type==="emoji"&&(c.emoji==="\u{1F441}"||c.emoji==="\u2705"))?"message_read":"message_delivered";this.log.debug("message reaction received",{messageId:n,telegramMessageId:e.message_id,sessionId:i,eventType:a,reactions:e.new_reaction}),this.messageHandler&&await this.messageHandler.onEvent({type:a,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.debug("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.debug("Retrying polling",{attempt:this.retryState.attempts,delay:s}),this.sleep(s).then(()=>this.pollLoop());}else this.log.error("Polling failed after max attempts, needs restart",{attempts:this.retryState.maxAttempts}),this.pollingStopped=true;}restartPolling(){this.retryState.attempts=0,this.pollingStopped=false,this.abortController=new AbortController,this.pollLoop(),this.log.debug("Polling restarted");}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=this.buildSessionId(this.id,e.chat.id.toString(),e.from?.id.toString()),n=await this.processCommand({text:e.text??"",sessionId:s,chatId:e.chat.id.toString(),channelInfo:{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},messageId:e.message_id.toString(),replyToMessageId:e.reply_to_message?.message_id.toString()});return n.handled?(n.reply?await this.sendApiMessage(e.chat.id.toString(),n.reply,{parseMode:"Markdown",replyTo:e.message_id}):n.gatewayMessage&&(await this.sendTyping(e.chat.id.toString()),await this.handleMessage(n.gatewayMessage)),true):false}async toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return A(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}`);let a=Filesystem.dirname(s);await Filesystem.mkdir(a,{recursive:true});let c=Buffer.from(r.data);return await PKG.file(s).write(c),s}async parseContent(e){let s=[],n=e.text??e.caption??"",i=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",r=Filesystem.join(i,"gateway","downloads");if(this.log.debug("download directory resolved",{globalDataPath:i,downloadDir:r}),e.photo&&e.photo.length>0){let a=e.photo[e.photo.length-1];if(a)try{let c=`photo_${a.file_unique_id}.jpg`,d=Filesystem.join(r,`${e.chat.id}_${a.file_unique_id}_${c}`);await this.downloadBinaryFile(a.file_id,d),this.log.debug("photo downloaded",{filePath:d,fileId:a.file_id}),s.push({type:"image",image:pathToFileURL(d).href,mime:"image/jpeg"});}catch(c){this.log.warn("failed to download photo, storing as file",{platform:"telegram",fileId:a.file_id,error:String(c)}),s.push({type:"image",image:a.file_id,mime:"image/jpeg"});}}if(e.document){let a=e.document.mime_type||"application/octet-stream",c=e.document.file_name||"file",d=e.document.file_id;if(a.startsWith("text/"))try{this.log.debug("downloading text file",{fileId:d,fileName:c,mimeType:a});let g=await this.parseFileContent(d),p=await TruncateContent.truncate(g,{maxChars:5e3,label:`file: ${c}`});s.push({type:"text",text:`\u{1F4CE} File: ${c}
@@ -18,18 +18,18 @@ ${p.content}`});}catch(g){this.log.warn("failed to download text file, storing a
18
18
  ${p.content}`});}else await this.downloadFile(r.url,d),s.push({type:"file",data:pathToFileURL(d).href,mime:r.content_type});}catch(a){this.log.warn("failed to download file, storing as URL",{attachmentId:r.id,error:String(a)}),s.push({type:"file",data:r.url,mime:r.content_type});}return s}async downloadFile(e,s){let n=await Fetch.get(e,{responseType:"arrayBuffer",headers:{Authorization:`Bot ${this.botConfig?.botToken}`}});if(!n.ok)throw new Error(`Failed to download file: ${n.status}`);let i=Filesystem.dirname(s);await Filesystem.mkdir(i,{recursive:true});let r=Buffer.from(n.data);return await PKG.file(s).write(r),s}async downloadTextFile(e){let s=await Fetch.get(e,{responseType:"text",headers:{Authorization:`Bot ${this.botConfig?.botToken}`}});if(!s.ok)throw new Error(`Failed to download text file: ${s.status}`);return s.data}buildSessionId(e,s,n){let i=["discord",e,s];return n&&i.push(n),i.join("_")}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 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"}}):r=await Fetch.post(i,n,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}),!r.ok)throw y(this.id,"MESSAGE_SEND_FAILED",`Discord API error: ${JSON.stringify(r.data)}`);return r.data}};var Le=class extends P{constructor(e="slack-main"){super();a(this,"id");a(this,"platform","slack");a(this,"name","Slack Bot");a(this,"botConfig",null);a(this,"baseUrl","https://slack.com/api");a(this,"socketModeClient",null);a(this,"abortController",null);a(this,"processedMessageIds",new Set);a(this,"sentMessages",new Map);a(this,"sessionIdMap",new Map);a(this,"commandRouter",new Map);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});a(this,"socketReconnectAttempts",0);a(this,"maxSocketReconnectAttempts",5);this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw y(this.id,"CONFIG_MISSING_REQUIRED","Bot token is required");if(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.abortController=new AbortController,this.botConfig.commands)for(let s of this.botConfig.commands)this.commandRouter.set(`/${s.command}`,s);let e=await this.authTest();this.log.info("Slack bot connected",{user:e.user,team:e.team,bot_id:e.bot_id}),await this.syncBotCommands(),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.processedMessageIds.clear(),this.sentMessages.clear(),this.sessionIdMap.clear(),this.commandRouter.clear(),this.socketReconnectAttempts=0,this.botConfig=null,this.retryState.attempts=0,this.log.debug("Slack plugin stopped");}async doHealthCheck(){if(this._status!=="running"||this.abortController?.signal.aborted)return false;try{return await this.authTest(),!0}catch{return false}}async send(e){let s=e.metadata.channel.chatId;if(!s)throw y(this.id,"MESSAGE_SEND_FAILED","Channel ID is required");let n=this.extractText(e),i=e.content.find(d=>d.type==="image"),r=e.content.find(d=>d.type==="file"),a=e.metadata.context?.threadId,c;return i?c=await this.postImage(s,i.image,n,a):r?c=await this.postFile(s,r.data,r.mime,n,a):c=await this.postMessage(s,n,a),this.sentMessages.set(e.id,{channelId:s,ts:c.ts,timestamp:Date.now()}),this.sessionIdMap.set(e.id,e.sessionId),c.ts}async postMessage(e,s,n){let r=this.getCapabilities().maxMessageLength-500,a=s;if(s.length>r){let d=await TruncateContent.truncate(s,{maxChars:r,label:"slack message"});a=d.content,this.log.debug("postMessage: message truncated",{originalLength:s.length,maxLength:r,outputPath:d.truncated?d.outputPath:void 0});}let c={channel:e,text:a};return n&&(c.thread_ts=n),this.request("chat.postMessage",c)}async postImage(e,s,n,i){let r;if(typeof s=="string")if(s.startsWith("http")){let c=await Fetch.get(s,{responseType:"arrayBuffer"}),d=s.split("/").pop()||"image.jpg";r=await this.uploadFile(new Uint8Array(c.data),d);}else if(s.startsWith("file://")){let c=await PKG.file(fileURLToPath(s)).bytes(),d=s.split("/").pop()||"image.jpg";r=await this.uploadFile(c,d);}else r=s;else if(s instanceof URL){let c=await Fetch.get(s.toString(),{responseType:"arrayBuffer"}),d=s.pathname.split("/").pop()||"image.jpg";r=await this.uploadFile(new Uint8Array(c.data),d);}else r=await this.uploadFile(s,"image.jpg");let a={channel:e,text:n||"",attachments:[{image_url:r}]};return i&&(a.thread_ts=i),this.request("chat.postMessage",a)}async postFile(e,s,n,i,r){let a,c="file";if(typeof s=="string")if(s.startsWith("http")){let p=await Fetch.get(s,{responseType:"arrayBuffer"});a=new Uint8Array(p.data),c=s.split("/").pop()||"file";}else s.startsWith("file://")?(a=await PKG.file(fileURLToPath(s)).bytes(),c=s.split("/").pop()||"file"):(a=await PKG.file(s).bytes(),c=s.split("/").pop()||"file");else if(s instanceof URL){let p=await Fetch.get(s.toString(),{responseType:"arrayBuffer"});a=new Uint8Array(p.data),c=s.pathname.split("/").pop()||"file";}else a=s;await this.uploadFile(a,c);let g={channel:e,text:i||`File: ${c}`,attachments:[{fallback:c,text:i||c,fields:[{title:"File",value:c,short:true}]}]};return r&&(g.thread_ts=r),this.request("chat.postMessage",g)}async uploadFile(e,s){let n=await Fetch.postForm(`${this.baseUrl}/files.upload`,[{name:"file",value:e,filename:s}],{timeout:3e5,headers:{Authorization:`Bearer ${this.botConfig?.botToken}`}});if(!n.data.ok||!n.data.file)throw y(this.id,"MESSAGE_SEND_FAILED",`File upload failed: ${n.data.error}`);return n.data.file.url_private}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,supportsSlashCommands:true,supportsNativeCommands:true,commandPrefix:"/",maxMessageLength:3e4,maxMediaCount:10}}async startSocketMode(){if(!this.botConfig?.appToken||this.abortController?.signal.aborted)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.socketModeClient.onerror=s=>{this.log.error("Socket mode error",{error:String(s)});},this.socketModeClient.onclose=()=>{if(!this.abortController?.signal.aborted)if(this.log.info("Socket mode disconnected"),this.socketReconnectAttempts<this.maxSocketReconnectAttempts){let s=Math.min(1e3*2**this.socketReconnectAttempts,3e4);this.socketReconnectAttempts++,this.log.info("Attempting to reconnect to Socket mode",{attempt:this.socketReconnectAttempts,delay:s}),setTimeout(()=>this.startSocketMode(),s);}else this.log.error("Max Socket reconnect attempts reached");},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(e.payload.event),s.type==="reaction_added"&&await this.handleReactionEvent(e.payload.event);}}async handleReactionEvent(e){if(e.reaction!=="white_check_mark"&&e.reaction!=="eyes")return;let s=this.findSentMessageEntry(e.item.ts);if(!s)return;let n=s.gatewayMessageId,i=this.sessionIdMap.get(n),a=e.reaction==="white_check_mark"?"message_read":"message_delivered";this.log.debug("message reaction received",{messageId:n,slackTs:e.item.ts,sessionId:i,eventType:a}),this.messageHandler&&await this.messageHandler.onEvent({type:a,channelId:this.id,data:{id:n,sessionId:i,platform:"slack",channelId:this.id,reaction:e.reaction,slackTs:e.item.ts},timestamp:Date.now()});}findSentMessageEntry(e){for(let[s,n]of this.sentMessages.entries())if(n.ts===e)return {gatewayMessageId:s,...n}}async handleSlackMessage(e){if(this.updateActivity(),e.user==="USLACKBOT"||this.processedMessageIds.has(e.ts))return;if(this.processedMessageIds.add(e.ts),this.processedMessageIds.size>1e4){let n=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(n.slice(-5e3));}if(e.text?.startsWith("/")&&await this.handleCommand(e))return;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){let d={channelId:e.channel,userId:e.user,args:i,ts:e.ts,reply:async g=>(await this.postMessage(e.channel,g,e.thread_ts)).ts};try{return await r.handler(d),!0}catch(g){return this.log.error("Command handler error",{command:n,error:String(g)}),true}}let a=this.buildSessionId(this.id,e.channel,e.user),c=await this.processCommand({text:e.text??"",sessionId:a,chatId:e.channel,channelInfo:{platform:"slack",channelId:this.id,userId:e.user,chatId:e.channel,ts:e.ts,threadTs:e.thread_ts},messageId:e.ts,replyToMessageId:e.thread_ts});return c.handled?(c.reply?await this.postMessage(e.channel,c.reply,e.thread_ts):c.gatewayMessage&&await this.handleMessage(c.gatewayMessage),true):false}async getCommandList(){try{return (await this.request("commands.list",{})).map(s=>({name:s.name,description:s.description}))}catch{return []}}async syncBotCommands(){try{let e=oe.map(i=>({command:i.command,description:i.description})),s=Array.from(this.commandRouter.values()).map(i=>({command:i.command.replace(/^\//,""),description:i.description})),n=[...e,...s];if(n.length===0)return;await this.request("commands.set",{commands:n}),this.log.debug("Bot commands synced",{count:n.length});}catch(e){this.log.warn("Failed to sync bot commands",{error:String(e)});}}async toGatewayMessage(e){let s=this.buildSessionId(this.id,e.channel,e.user);return A(s,"input",await 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}})}async parseContent(e){let s=[],n=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");if(e.text&&s.push({type:"text",text:e.text}),e.files)for(let r of e.files)if(r.mimetype?.startsWith("image/"))try{let a=r.name||`image_${r.id}.jpg`,c=a.includes(".")?a.split(".").pop():"jpg",d=Filesystem.join(i,`slack_${e.channel}_${r.id}.${c}`);await this.downloadFile(r.url_private_download||r.url_private,d),s.push({type:"image",image:pathToFileURL(d).href,mime:r.mimetype});}catch(a){this.log.warn("failed to download image, storing as URL",{fileId:r.id,error:String(a)}),s.push({type:"image",image:r.url_private,mime:r.mimetype});}else try{let a=r.name||`file_${r.id}`,c=a.includes(".")?a.split(".").pop():Filesystem.mimeTypeToExt(r.mimetype)||"bin",d=Filesystem.join(i,`slack_${e.channel}_${r.id}.${c}`);if(r.mimetype.startsWith("text/")){let g=await this.downloadTextFile(r.url_private),p=await TruncateContent.truncate(g,{maxChars:5e3,label:`file: ${a}`});s.push({type:"text",text:`\u{1F4CE} File: ${a}
19
19
 
20
20
  ${p.content}`});}else await this.downloadFile(r.url_private_download||r.url_private,d),s.push({type:"file",data:pathToFileURL(d).href,mime:r.mimetype});}catch(a){this.log.warn("failed to download file, storing as URL",{fileId:r.id,error:String(a)}),s.push({type:"file",data:r.url_private,mime:r.mimetype});}return s}async downloadFile(e,s){let n=await Fetch.get(e,{responseType:"arrayBuffer",headers:{Authorization:`Bearer ${this.botConfig?.botToken}`}});if(!n.ok)throw new Error(`Failed to download file: ${n.status}`);let i=Filesystem.dirname(s);await Filesystem.mkdir(i,{recursive:true});let r=Buffer.from(n.data);return await PKG.file(s).write(r),s}async downloadTextFile(e){let s=await Fetch.get(e,{responseType:"text",headers:{Authorization:`Bearer ${this.botConfig?.botToken}`}});if(!s.ok)throw new Error(`Failed to download text file: ${s.status}`);return s.data}buildSessionId(e,s,n){let i=["slack",e,s];return n&&i.push(n),i.join("_")}async authTest(){return await this.request("auth.test",{})}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 y(this.id,"MESSAGE_SEND_FAILED",`Slack API error: ${i.data.error}`);return i.data}};var Ge=class extends P{constructor(e="feishu-main"){super();a(this,"id");a(this,"platform","feishu");a(this,"name","Feishu Bot");a(this,"botConfig",null);a(this,"baseUrl","https://open.feishu.cn/open-apis");a(this,"tenantAccessToken",null);a(this,"tokenExpireTime",0);a(this,"abortController",null);a(this,"processedMessageIds",new Set);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw y(this.id,"CONFIG_MISSING_REQUIRED","App ID and App Secret are required");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.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.processedMessageIds.clear(),this.botConfig=null,this.tenantAccessToken=null,this.tokenExpireTime=0,this.retryState.attempts=0,this.log.debug("Feishu plugin stopped");}async doHealthCheck(){if(this._status!=="running"||this.abortController?.signal.aborted)return false;try{return await this.ensureTokenValid(),!0}catch{return false}}async send(e){let s=e.metadata.channel.chatId;if(!s)throw y(this.id,"MESSAGE_SEND_FAILED","Chat ID is required");await this.ensureTokenValid();let n=this.extractText(e),i=e.content.find(c=>c.type==="image"),r=e.content.find(c=>c.type==="file"),a;return i?a=await this.sendImage(s,i.image,n):r?a=await this.sendFile(s,r.data,n):a=await this.sendMessage(s,n),a}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,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:4e3,maxMediaCount:10}}async handleWebhookEvent(e){this.updateActivity();let s=e.event?.message?.message_id;if(s&&this.processedMessageIds.has(s)){this.log.debug("Duplicate message ignored",{messageId:s});return}if(s&&(this.processedMessageIds.add(s),this.processedMessageIds.size>1e4)){let n=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(n.slice(-5e3));}if(e.event?.message){let n=e.event.message,i;if(n.message_type==="text")try{let a=JSON.parse(n.content);a.text?.trim().startsWith("/")&&(i=a.text);}catch{}if(i!==void 0){let a=this.buildSessionId(this.id,n.chat_id,n.sender.sender_id.open_id),c=await this.processCommand({text:i,sessionId:a,chatId:n.chat_id,channelInfo:{platform:"feishu",channelId:this.id,userId:n.sender.sender_id.open_id,chatId:n.chat_id,messageId:n.message_id,rootId:n.root_id,parentId:n.parent_id,tenantKey:e.tenant_key},messageId:n.message_id,replyToMessageId:n.parent_id??n.root_id});if(c.handled){c.reply?await this.sendMessage(n.chat_id,c.reply):c.gatewayMessage&&await this.handleMessage(c.gatewayMessage);return}}let r=await this.toGatewayMessage(e);await this.handleMessage(r);}}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 y(this.id,"CHANNEL_INIT_FAILED",`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=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let d=await TruncateContent.truncate(s,{maxChars:i,label:"feishu message"});r=d.content,this.log.debug("sendMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:d.truncated?d.outputPath:void 0});}let c=(await Fetch.post(`${this.baseUrl}/im/v1/messages?receive_id_type=chat_id`,{receive_id:e,msg_type:"text",content:JSON.stringify({text:r})},{headers:{Authorization:`Bearer ${this.tenantAccessToken}`,"Content-Type":"application/json"}})).data;if(c.code!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`Feishu API error: ${c.msg}`);return c.data.message_id}async sendImage(e,s,n){let i;if(typeof s=="string")if(s.startsWith("http")){let a=await Fetch.get(s,{responseType:"arrayBuffer"});i=await this.uploadImage(new Uint8Array(a.data),"image.jpg");}else i=s;else if(s instanceof URL){let a=await Fetch.get(s.toString(),{responseType:"arrayBuffer"});i=await this.uploadImage(new Uint8Array(a.data),"image.jpg");}else i=await this.uploadImage(s,"image.jpg");let r=await Fetch.post(`${this.baseUrl}/im/v1/messages?receive_id_type=chat_id`,{receive_id:e,msg_type:"image",content:JSON.stringify({image_key:i})},{headers:{Authorization:`Bearer ${this.tenantAccessToken}`,"Content-Type":"application/json"}});return r.data.code!==0?(this.log.debug("Image send failed, falling back to text",{error:r.data.msg}),await this.sendMessage(e,n??"[Image]")):r.data.data.message_id}async sendFile(e,s,n){let i;if(typeof s=="string")if(s.startsWith("http")){let c=await Fetch.get(s,{responseType:"arrayBuffer"});i=await this.uploadFile(new Uint8Array(c.data),"file");}else i=s;else if(s instanceof URL){let c=await Fetch.get(s.toString(),{responseType:"arrayBuffer"});i=await this.uploadFile(new Uint8Array(c.data),"file");}else i=await this.uploadFile(s,"file");let a=await Fetch.post(`${this.baseUrl}/im/v1/messages?receive_id_type=chat_id`,{receive_id:e,msg_type:"file",content:JSON.stringify({file_key:i})},{headers:{Authorization:`Bearer ${this.tenantAccessToken}`,"Content-Type":"application/json"}});return a.data.code!==0?(this.log.debug("File send failed, falling back to text",{error:a.data.msg}),await this.sendMessage(e,n??"[File]")):a.data.data.message_id}async uploadImage(e,s){let n=await Fetch.postForm(`${this.baseUrl}/im/v1/images`,[{name:"image",value:e,filename:s}],{headers:{Authorization:`Bearer ${this.tenantAccessToken}`}});if(n.data.code!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`Image upload failed: ${n.data.msg}`);return n.data.data.image_key}async uploadFile(e,s){let n=await Fetch.postForm(`${this.baseUrl}/im/v1/files`,[{name:"file",value:e,filename:s}],{timeout:3e5,headers:{Authorization:`Bearer ${this.tenantAccessToken}`}});if(n.data.code!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`File upload failed: ${n.data.msg}`);return n.data.data.file_key}async toGatewayMessage(e){let s=e.event.message,n=this.buildSessionId(this.id,s.chat_id,s.sender.sender_id.open_id);return A(n,"input",await 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}})}async parseContent(e){let s=[],n=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");try{let r=JSON.parse(e.content);switch(e.message_type){case "text":r.text&&s.push({type:"text",text:r.text});break;case "post":if(r.content){let a=this.extractPostContent(r.content);s.push({type:"text",text:a});}break;case "image":if(r.image_key)try{let a=Filesystem.join(i,`feishu_${e.chat_id}_${r.image_key}.jpg`);await this.downloadImage(r.image_key,a),s.push({type:"image",image:pathToFileURL(a).href,mime:"image/jpeg"});}catch(a){this.log.warn("failed to download image, storing as key",{imageKey:r.image_key,error:String(a)}),s.push({type:"image",image:r.image_key,mime:"image/jpeg"});}break;case "file":if(r.file_key)try{let a=r.file_name||`file_${r.file_key}`,c=a.includes(".")?a.split(".").pop():Filesystem.mimeTypeToExt(r.file_type)||"bin",d=Filesystem.join(i,`feishu_${e.chat_id}_${r.file_key}.${c}`);await this.downloadFile(r.file_key,d),s.push({type:"file",data:pathToFileURL(d).href,mime:r.file_type??"application/octet-stream"});}catch(a){this.log.warn("failed to download file, storing as key",{fileKey:r.file_key,error:String(a)}),s.push({type:"file",data:r.file_key,mime:r.file_type??"application/octet-stream"});}break;default:s.push({type:"text",text:JSON.stringify(r)});}}catch{s.push({type:"text",text:e.content});}return s}async downloadImage(e,s){await this.ensureTokenValid();let n=await Fetch.get(`${this.baseUrl}/im/v1/images/${e}`,{responseType:"arrayBuffer",headers:{Authorization:`Bearer ${this.tenantAccessToken}`}});if(!n.ok)throw new Error(`Failed to download image: ${n.status}`);let i=Filesystem.dirname(s);await Filesystem.mkdir(i,{recursive:true});let r=Buffer.from(n.data);return await PKG.file(s).write(r),s}async downloadFile(e,s){await this.ensureTokenValid();let n=await Fetch.get(`${this.baseUrl}/im/v1/files/${e}`,{responseType:"arrayBuffer",headers:{Authorization:`Bearer ${this.tenantAccessToken}`}});if(!n.ok)throw new Error(`Failed to download file: ${n.status}`);let i=Filesystem.dirname(s);await Filesystem.mkdir(i,{recursive:true});let r=Buffer.from(n.data);return await PKG.file(s).write(r),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(`
21
- `)}buildSessionId(e,s,n){let i=["feishu",e,s];return n&&i.push(n),i.join("_")}};var Ue=class extends P{constructor(e="wechat-main"){super();a(this,"id");a(this,"platform","wechat");a(this,"name","WeChat Bot");a(this,"botConfig",null);a(this,"accessToken",null);a(this,"tokenExpireTime",0);a(this,"abortController",null);a(this,"processedMessageIds",new Set);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw y(this.id,"CONFIG_MISSING_REQUIRED","App ID and App Secret are required");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.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.processedMessageIds.clear(),this.botConfig=null,this.accessToken=null,this.tokenExpireTime=0,this.retryState.attempts=0,this.log.debug("WeChat plugin stopped");}async doHealthCheck(){if(this._status!=="running"||this.abortController?.signal.aborted)return false;try{return await this.ensureTokenValid(),!0}catch{return false}}async send(e){let s=e.metadata.channel.userId;if(!s)throw y(this.id,"MESSAGE_SEND_FAILED","User ID is required");await this.ensureTokenValid();let n=this.extractText(e),i=e.content.find(a=>a.type==="image"),r;return i?r=await this.sendImage(s,i.image):this.botConfig?.mode==="wecom"?r=await this.sendWeComMessage(s,n):r=await this.sendOfficialMessage(s,n),r}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,supportsSlashCommands:false,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:2048,maxMediaCount:1}}async handleWebhookMessage(e){this.updateActivity();let s=this.parseXmlMessage(e);if(s){let n=s.MsgId?.toString();if(n&&this.processedMessageIds.has(n)){this.log.debug("Duplicate message ignored",{msgId:n});return}if(n&&(this.processedMessageIds.add(n),this.processedMessageIds.size>1e4)){let r=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(r.slice(-5e3));}let i=this.toGatewayMessage(s);await this.handleMessage(i);}}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 y(this.id,"CHANNEL_INIT_FAILED",`WeChat API error: ${n.errmsg}`);this.accessToken=n.access_token,this.tokenExpireTime=Date.now()+n.expires_in*1e3-12e4;}async ensureTokenValid(){(!this.accessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshAccessToken();}async sendOfficialMessage(e,s){let i=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let d=await TruncateContent.truncate(s,{maxChars:i,label:"wechat message"});r=d.content,this.log.debug("sendOfficialMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:d.truncated?d.outputPath:void 0});}let c=(await Fetch.post(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{touser:e,msgtype:"text",text:{content:r}},{headers:{"Content-Type":"application/json"}})).data;if(c.errcode!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`WeChat API error: ${c.errmsg}`);return c.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,s){let i=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let d=await TruncateContent.truncate(s,{maxChars:i,label:"wecom message"});r=d.content,this.log.debug("sendWeComMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:d.truncated?d.outputPath:void 0});}let c=(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:r}},{headers:{"Content-Type":"application/json"}})).data;if(c.errcode!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`WeCom API error: ${c.errmsg}`);return c.msgid??Date.now().toString()}async sendImage(e,s){let n;if(typeof s=="string")s.startsWith("http")?n=await this.uploadImage(s):n=s;else if(s instanceof URL)n=await this.uploadImage(s.toString());else throw y(this.id,"MESSAGE_SEND_FAILED","Binary image upload not supported");if(this.botConfig?.mode==="wecom"){let i=await Fetch.post(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${this.accessToken}`,{touser:e,msgtype:"image",agentid:this.botConfig?.agentId,image:{media_id:n}},{headers:{"Content-Type":"application/json"}});if(i.data.errcode!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`WeCom API error: ${i.data.errmsg}`);return i.data.msgid??Date.now().toString()}else {let i=await Fetch.post(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{touser:e,msgtype:"image",image:{media_id:n}},{headers:{"Content-Type":"application/json"}});if(i.data.errcode!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`WeChat API error: ${i.data.errmsg}`);return i.data.msg_id?.toString()??Date.now().toString()}}async uploadImage(e){let s=(this.botConfig?.mode==="wecom","media/upload"),n=(this.botConfig?.mode==="wecom","?type=image"),i;try{let d=await Fetch.get(e,{responseType:"arrayBuffer"});i=new Uint8Array(d.data);}catch{throw y(this.id,"MESSAGE_SEND_FAILED","Failed to download image for upload")}let a=`${this.botConfig?.mode==="wecom"?"https://qyapi.weixin.qq.com":"https://api.weixin.qq.com"}/cgi-bin/${s}${n}&access_token=${this.accessToken}`,c=await Fetch.postForm(a,[{name:"media",value:i,filename:"image.jpg"}],{timeout:3e5,headers:{Authorization:`Bearer ${this.accessToken}`}});if(c.data.errcode!==0||!c.data.media_id)throw y(this.id,"MESSAGE_SEND_FAILED",`Image upload failed: ${c.data.errmsg}`);return c.data.media_id}parseXmlMessage(e){let s=r=>e.match(new RegExp(`<${r}><!\\[CDATA\\[(.*?)\\]\\]></${r}>`))?.[1],n=r=>{let a=e.match(new RegExp(`<${r}>(\\d+)</${r}>`));return a?.[1]?parseInt(a[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.buildSessionId(this.id,e.FromUserName,e.FromUserName);return A(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){let i=["wechat",e,s];return n&&i.push(n),i.join("_")}};var Ce="weixin";function jt(){let o=process.env.EASBOT_DATA_PATH;if(o)return Filesystem.normalize(o);let t=v()?.Path?.data;return t?Filesystem.normalize(t):Filesystem.normalize(join(homedir(),".easbot"))}function Rs(){return Filesystem.join(jt(),"gateway","channels","weixin")}function Yi(){return Filesystem.join(jt(),"gateway")}function Zi(){return Filesystem.join(jt(),"gateway","sessions")}function Ds(o,t){return `${Ce}_${o}_${t}_${t}`}function er(){return {status:"idle",messageCount:0,lastMessageAt:null}}function tr(o){let t={};return o.displayName&&(t.displayName=o.displayName),o.username&&(t.username=o.username),t}async function qt(){let o=new re({baseDir:Yi()});return await o.initialize(),o}async function Ns(){let o=new ne({storagePath:Zi()});return await o.initialize(),o}async function sr(o){let t=await qt();{let e=tr(o),s=await t.findByPlatformId(Ce,o.userId);if(s){let r=Date.now(),a={...s,profile:{...s.profile,...e},aliases:o.aliases?{...s.aliases,...o.aliases}:s.aliases,metadata:o.metadata?{...s.metadata??{},...o.metadata}:s.metadata,lastSeenAt:r};return {contact:await t.save(a),created:false}}return {contact:await t.create({platform:Ce,stableId:o.userId,profile:e,aliases:o.aliases,metadata:o.metadata}),created:true}}}async function nr(o){let t=await Ns();{let e=o.channelId??"weixin-main",s=Ds(e,o.userId),n=t.get(s);if(n)return n.lastActiveAt=Date.now(),await t.set(n),{session:{id:n.id,channel:n.channel,backendSessionId:n.backendSessionId,subscribers:[...n.subscribers],state:n.state,createdAt:n.createdAt,lastActiveAt:n.lastActiveAt},created:false};let i=Date.now(),r={platform:Ce,channelId:e,userId:o.userId,chatId:o.userId},a={id:s,channel:r,backendSessionId:null,subscribers:new Set,state:er(),createdAt:i,lastActiveAt:i};return await t.set(a),{session:{id:a.id,channel:a.channel,backendSessionId:a.backendSessionId,subscribers:[...a.subscribers],state:a.state,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt},created:true}}}async function bd(o){let t=await sr(o),e=await nr(o);return {contact:t.contact,session:e.session,created:{contact:t.created,session:e.created}}}async function Sd(o,t="weixin-main"){let e=false,s=false;try{let n=await qt(),i=`${Ce}:${o}`;e=await n.delete(i);}catch{}try{let n=await Ns(),i=Ds(t,o);n.get(i)&&(await n.delete(i),s=!0);}catch{}return {removed:{contact:e,session:s}}}async function Cd(){return (await(await qt()).listByPlatform(Ce,1e4,0)).contacts}var Gs="https://ilinkai.weixin.qq.com",Vt="https://novac2c.cdn.weixin.qq.com/c2c",Us=null;function Fs(o){Us=o;}function we(){let o=Us||process.env.WEIXIN_STATE_DIR||Rs()||join(homedir(),".easbot","channels","weixin");return existsSync(o)||mkdirSync(o,{recursive:true}),o}function Jt(){return join(we(),"account.json")}function Qt(){let o=Jt();if(!existsSync(o))return null;try{return JSON.parse(readFileSync(o,"utf-8"))}catch{return null}}function Md(o){let t=Jt();writeFileSync(t,JSON.stringify(o,null,2),"utf-8"),chmodSync(t,384);}function kd(){let o=Jt();existsSync(o)&&unlinkSync(o);}var ur="0.1.0";function Fe(){return {channel_version:ur}}function pr(){return randomBytes(4).toString("base64")}function hr(o){let t={"X-WECHAT-UIN":pr()};return o&&(t.AuthorizationType="ilink_bot_token",t.Authorization=`Bearer ${o}`),t}async function Be(o,t,e,s,n=4e4,i){let r=await Fetch.post(`${o}${t}`,e,{timeout:n,headers:hr(s),signal:i});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);return r.data}async function Bs(o,t,e,s){let n={get_updates_buf:e,base_info:Fe()};try{return await Be(o,"/ilink/bot/getupdates",n,t,4e4,s)}catch(i){if(i instanceof Error&&i.name==="AbortError")return {ret:0,msgs:[],get_updates_buf:e};throw i}}async function Xt(o,t,e){let s={msg:e,base_info:Fe()};await Be(o,"/ilink/bot/sendmessage",s,t);}async function Os(o,t,e){return Be(o,"/ilink/bot/getuploadurl",{...e,base_info:Fe()},t)}async function $s(o,t,e,s){return Be(o,"/ilink/bot/getconfig",{ilink_user_id:e,context_token:s,base_info:Fe()},t)}async function Ws(o,t,e){return Be(o,"/ilink/bot/sendtyping",{...e,base_info:Fe()},t)}var Oe={USER:1,BOT:2},D={TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},Yt={FINISH:2},At={IMAGE:1,VIDEO:2,FILE:3},Hs={TYPING:1,CANCEL:2};function wr(o,t){let e=createCipheriv("aes-128-ecb",t,null);return Buffer.concat([e.update(o),e.final()])}function vr(o,t){let e=createDecipheriv("aes-128-ecb",t,null);return Buffer.concat([e.update(o),e.final()])}function Ir(o,t){return `${t}/download?encrypted_query_param=${encodeURIComponent(o)}`}function Ar(o,t,e){return `${o}/upload?encrypted_query_param=${encodeURIComponent(t)}&filekey=${encodeURIComponent(e)}`}function Pr(o){let t=Buffer.from(o,"base64");if(t.length===16)return t;if(t.length===32&&/^[0-9a-fA-F]{32}$/.test(t.toString("ascii")))return Buffer.from(t.toString("ascii"),"hex");throw new Error(`Invalid aes_key: expected 16 raw bytes or 32 hex chars, got ${t.length} bytes`)}async function qs(o){let t=Ir(o.encryptQueryParam,o.cdnBaseUrl),e=await Fetch.get(t,{responseType:"arrayBuffer",timeout:6e4});if(!e.ok)throw new Error(`CDN download failed: HTTP ${e.status}`);return vr(Buffer.from(e.data),Pr(o.aesKey))}async function Ks(o){let t=readFileSync(o.filePath),e=t.length,s=createHash("md5").update(t).digest("hex"),n=randomBytes(16),i=randomBytes(16).toString("hex"),r=wr(t,n),a=r.length,c=await Os(o.apiBaseUrl,o.token,{filekey:i,media_type:o.mediaType,to_user_id:o.toUserId,rawsize:e,rawfilemd5:s,filesize:a,no_need_thumb:true,aeskey:n.toString("hex")});if(!c.upload_param)throw new Error("No upload_param in response");let d=Ar(o.cdnBaseUrl,c.upload_param,i),g=new Uint8Array(r),p=await Fetch.request(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Blob([g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength)]),timeout:12e4,responseType:"json"});if(!p.ok)throw new Error(`CDN upload failed: HTTP ${p.status}`);return {encryptQueryParam:p.headers.get("x-encrypted-param")||"",aesKey:Buffer.from(n.toString("hex")).toString("base64"),fileSize:a,rawSize:e,fileName:basename(o.filePath)}}function Vs(o){let t=extname(o).toLowerCase(),e=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".heic"],s=[".mp4",".mov",".avi",".mkv",".webm"];return e.includes(t)?At.IMAGE:s.includes(t)?At.VIDEO:At.FILE}function Zs(){return join(we(),"access.json")}function en(){return join(we(),"pending-pairings.json")}function tn(){let o=en();if(!existsSync(o))return {};try{return JSON.parse(readFileSync(o,"utf-8"))}catch{return {}}}function Pt(o){writeFileSync(en(),JSON.stringify(o,null,2),"utf-8");}function sn(){let o=Zs();if(!existsSync(o))return {policy:"pairing",allowFrom:[]};try{return JSON.parse(readFileSync(o,"utf-8"))}catch{return {policy:"pairing",allowFrom:[]}}}function xr(o){writeFileSync(Zs(),JSON.stringify(o,null,2),"utf-8");}function nn(o){let t=sn();return t.policy==="disabled"?true:t.allowFrom.includes(o)}function rn(o){let t=tn(),e=Date.now();for(let n of Object.keys(t))t[n].expiresAt<e&&delete t[n];for(let[n,i]of Object.entries(t))if(i.userId===o)return Pt(t),n;let s=String(Math.floor(1e5+Math.random()*9e5));return t[s]={userId:o,expiresAt:e+600*1e3},Pt(t),s}function eg(o){let t=tn(),e=t[o];if(!e||e.expiresAt<Date.now())return delete t[o],Pt(t),null;delete t[o],Pt(t);let s=sn();return s.allowFrom.includes(e.userId)||(s.allowFrom.push(e.userId),xr(s)),e.userId}function Mr(o){let t="",e=0;for(;e<o.length;)if(o.startsWith("```",e)){let s=e+3;for(;s<o.length&&o[s]!==`
21
+ `)}buildSessionId(e,s,n){let i=["feishu",e,s];return n&&i.push(n),i.join("_")}};var Ue=class extends P{constructor(e="wechat-main"){super();a(this,"id");a(this,"platform","wechat");a(this,"name","WeChat Bot");a(this,"botConfig",null);a(this,"accessToken",null);a(this,"tokenExpireTime",0);a(this,"abortController",null);a(this,"processedMessageIds",new Set);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw y(this.id,"CONFIG_MISSING_REQUIRED","App ID and App Secret are required");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.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.processedMessageIds.clear(),this.botConfig=null,this.accessToken=null,this.tokenExpireTime=0,this.retryState.attempts=0,this.log.debug("WeChat plugin stopped");}async doHealthCheck(){if(this._status!=="running"||this.abortController?.signal.aborted)return false;try{return await this.ensureTokenValid(),!0}catch{return false}}async send(e){let s=e.metadata.channel.userId;if(!s)throw y(this.id,"MESSAGE_SEND_FAILED","User ID is required");await this.ensureTokenValid();let n=this.extractText(e),i=e.content.find(a=>a.type==="image"),r;return i?r=await this.sendImage(s,i.image):this.botConfig?.mode==="wecom"?r=await this.sendWeComMessage(s,n):r=await this.sendOfficialMessage(s,n),r}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,supportsSlashCommands:false,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:2048,maxMediaCount:1}}async handleWebhookMessage(e){this.updateActivity();let s=this.parseXmlMessage(e);if(s){let n=s.MsgId?.toString();if(n&&this.processedMessageIds.has(n)){this.log.debug("Duplicate message ignored",{msgId:n});return}if(n&&(this.processedMessageIds.add(n),this.processedMessageIds.size>1e4)){let r=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(r.slice(-5e3));}let i=this.toGatewayMessage(s);await this.handleMessage(i);}}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 y(this.id,"CHANNEL_INIT_FAILED",`WeChat API error: ${n.errmsg}`);this.accessToken=n.access_token,this.tokenExpireTime=Date.now()+n.expires_in*1e3-12e4;}async ensureTokenValid(){(!this.accessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshAccessToken();}async sendOfficialMessage(e,s){let i=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let d=await TruncateContent.truncate(s,{maxChars:i,label:"wechat message"});r=d.content,this.log.debug("sendOfficialMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:d.truncated?d.outputPath:void 0});}let c=(await Fetch.post(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{touser:e,msgtype:"text",text:{content:r}},{headers:{"Content-Type":"application/json"}})).data;if(c.errcode!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`WeChat API error: ${c.errmsg}`);return c.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,s){let i=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let d=await TruncateContent.truncate(s,{maxChars:i,label:"wecom message"});r=d.content,this.log.debug("sendWeComMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:d.truncated?d.outputPath:void 0});}let c=(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:r}},{headers:{"Content-Type":"application/json"}})).data;if(c.errcode!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`WeCom API error: ${c.errmsg}`);return c.msgid??Date.now().toString()}async sendImage(e,s){let n;if(typeof s=="string")s.startsWith("http")?n=await this.uploadImage(s):n=s;else if(s instanceof URL)n=await this.uploadImage(s.toString());else throw y(this.id,"MESSAGE_SEND_FAILED","Binary image upload not supported");if(this.botConfig?.mode==="wecom"){let i=await Fetch.post(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${this.accessToken}`,{touser:e,msgtype:"image",agentid:this.botConfig?.agentId,image:{media_id:n}},{headers:{"Content-Type":"application/json"}});if(i.data.errcode!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`WeCom API error: ${i.data.errmsg}`);return i.data.msgid??Date.now().toString()}else {let i=await Fetch.post(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{touser:e,msgtype:"image",image:{media_id:n}},{headers:{"Content-Type":"application/json"}});if(i.data.errcode!==0)throw y(this.id,"MESSAGE_SEND_FAILED",`WeChat API error: ${i.data.errmsg}`);return i.data.msg_id?.toString()??Date.now().toString()}}async uploadImage(e){let s=(this.botConfig?.mode==="wecom","media/upload"),n=(this.botConfig?.mode==="wecom","?type=image"),i;try{let d=await Fetch.get(e,{responseType:"arrayBuffer"});i=new Uint8Array(d.data);}catch{throw y(this.id,"MESSAGE_SEND_FAILED","Failed to download image for upload")}let a=`${this.botConfig?.mode==="wecom"?"https://qyapi.weixin.qq.com":"https://api.weixin.qq.com"}/cgi-bin/${s}${n}&access_token=${this.accessToken}`,c=await Fetch.postForm(a,[{name:"media",value:i,filename:"image.jpg"}],{timeout:3e5,headers:{Authorization:`Bearer ${this.accessToken}`}});if(c.data.errcode!==0||!c.data.media_id)throw y(this.id,"MESSAGE_SEND_FAILED",`Image upload failed: ${c.data.errmsg}`);return c.data.media_id}parseXmlMessage(e){let s=r=>e.match(new RegExp(`<${r}><!\\[CDATA\\[(.*?)\\]\\]></${r}>`))?.[1],n=r=>{let a=e.match(new RegExp(`<${r}>(\\d+)</${r}>`));return a?.[1]?parseInt(a[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.buildSessionId(this.id,e.FromUserName,e.FromUserName);return A(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){let i=["wechat",e,s];return n&&i.push(n),i.join("_")}};var Ce="weixin";function qt(){let o=process.env.EASBOT_DATA_PATH;if(o)return Filesystem.normalize(o);let t=v()?.Path?.data;return t?Filesystem.normalize(t):Filesystem.normalize(join(homedir(),".easbot"))}function Ds(){return Filesystem.join(qt(),"gateway","channels","weixin")}function Yi(){return Filesystem.join(qt(),"gateway")}function Zi(){return Filesystem.join(qt(),"gateway","sessions")}function Ns(o,t){return `${Ce}_${o}_${t}_${t}`}function er(){return {status:"idle",messageCount:0,lastMessageAt:null}}function tr(o){let t={};return o.displayName&&(t.displayName=o.displayName),o.username&&(t.username=o.username),t}async function Kt(){let o=new re({baseDir:Yi()});return await o.initialize(),o}async function Ls(){let o=new ne({storagePath:Zi()});return await o.initialize(),o}async function sr(o){let t=await Kt();{let e=tr(o),s=await t.findByPlatformId(Ce,o.userId);if(s){let r=Date.now(),a={...s,profile:{...s.profile,...e},aliases:o.aliases?{...s.aliases,...o.aliases}:s.aliases,metadata:o.metadata?{...s.metadata??{},...o.metadata}:s.metadata,lastSeenAt:r};return {contact:await t.save(a),created:false}}return {contact:await t.create({platform:Ce,stableId:o.userId,profile:e,aliases:o.aliases,metadata:o.metadata}),created:true}}}async function nr(o){let t=await Ls();{let e=o.channelId??"weixin-main",s=Ns(e,o.userId),n=t.get(s);if(n)return n.lastActiveAt=Date.now(),await t.set(n),{session:{id:n.id,channel:n.channel,backendSessionId:n.backendSessionId,subscribers:[...n.subscribers],state:n.state,createdAt:n.createdAt,lastActiveAt:n.lastActiveAt},created:false};let i=Date.now(),r={platform:Ce,channelId:e,userId:o.userId,chatId:o.userId},a={id:s,channel:r,backendSessionId:null,subscribers:new Set,state:er(),createdAt:i,lastActiveAt:i};return await t.set(a),{session:{id:a.id,channel:a.channel,backendSessionId:a.backendSessionId,subscribers:[...a.subscribers],state:a.state,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt},created:true}}}async function wd(o){let t=await sr(o),e=await nr(o);return {contact:t.contact,session:e.session,created:{contact:t.created,session:e.created}}}async function vd(o,t="weixin-main"){let e=false,s=false;try{let n=await Kt(),i=`${Ce}:${o}`;e=await n.delete(i);}catch{}try{let n=await Ls(),i=Ns(t,o);n.get(i)&&(await n.delete(i),s=!0);}catch{}return {removed:{contact:e,session:s}}}async function Id(){return (await(await Kt()).listByPlatform(Ce,1e4,0)).contacts}var Jt="https://ilinkai.weixin.qq.com",Qt="https://novac2c.cdn.weixin.qq.com/c2c",Us=null;function Fs(o){Us=o;}function we(){let o=Us||process.env.WEIXIN_STATE_DIR||Ds()||join(homedir(),".easbot","channels","weixin");return existsSync(o)||mkdirSync(o,{recursive:true}),o}function Xt(){return join(we(),"account.json")}function At(){let o=Xt();if(!existsSync(o))return null;try{return JSON.parse(readFileSync(o,"utf-8"))}catch{return null}}function _d(o){let t=Xt();writeFileSync(t,JSON.stringify(o,null,2),"utf-8"),chmodSync(t,384);}function Ed(){let o=Xt();existsSync(o)&&unlinkSync(o);}var ur="0.1.0";function Fe(){return {channel_version:ur}}function pr(){return randomBytes(4).toString("base64")}function hr(o){let t={"X-WECHAT-UIN":pr()};return o&&(t.AuthorizationType="ilink_bot_token",t.Authorization=`Bearer ${o}`),t}async function Be(o,t,e,s,n=4e4,i){let r=await Fetch.post(`${o}${t}`,e,{timeout:n,headers:hr(s),signal:i});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);return r.data}async function Bs(o,t,e,s){let n={get_updates_buf:e,base_info:Fe()};try{return await Be(o,"/ilink/bot/getupdates",n,t,4e4,s)}catch(i){if(i instanceof Error&&i.name==="AbortError")return {ret:0,msgs:[],get_updates_buf:e};throw i}}async function Yt(o,t,e){let s={msg:e,base_info:Fe()};await Be(o,"/ilink/bot/sendmessage",s,t);}async function Os(o,t,e){return Be(o,"/ilink/bot/getuploadurl",{...e,base_info:Fe()},t)}async function $s(o,t,e,s){return Be(o,"/ilink/bot/getconfig",{ilink_user_id:e,context_token:s,base_info:Fe()},t)}async function Ws(o,t,e){return Be(o,"/ilink/bot/sendtyping",{...e,base_info:Fe()},t)}var Oe={USER:1,BOT:2},D={TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},Zt={FINISH:2},Pt={IMAGE:1,VIDEO:2,FILE:3},Hs={TYPING:1,CANCEL:2};function wr(o,t){let e=createCipheriv("aes-128-ecb",t,null);return Buffer.concat([e.update(o),e.final()])}function vr(o,t){let e=createDecipheriv("aes-128-ecb",t,null);return Buffer.concat([e.update(o),e.final()])}function Ir(o,t){return `${t}/download?encrypted_query_param=${encodeURIComponent(o)}`}function Ar(o,t,e){return `${o}/upload?encrypted_query_param=${encodeURIComponent(t)}&filekey=${encodeURIComponent(e)}`}function Pr(o){let t=Buffer.from(o,"base64");if(t.length===16)return t;if(t.length===32&&/^[0-9a-fA-F]{32}$/.test(t.toString("ascii")))return Buffer.from(t.toString("ascii"),"hex");throw new Error(`Invalid aes_key: expected 16 raw bytes or 32 hex chars, got ${t.length} bytes`)}async function qs(o){let t=Ir(o.encryptQueryParam,o.cdnBaseUrl),e=await Fetch.get(t,{responseType:"arrayBuffer",timeout:6e4});if(!e.ok)throw new Error(`CDN download failed: HTTP ${e.status}`);return vr(Buffer.from(e.data),Pr(o.aesKey))}async function Ks(o){let t=readFileSync(o.filePath),e=t.length,s=createHash("md5").update(t).digest("hex"),n=randomBytes(16),i=randomBytes(16).toString("hex"),r=wr(t,n),a=r.length,c=await Os(o.apiBaseUrl,o.token,{filekey:i,media_type:o.mediaType,to_user_id:o.toUserId,rawsize:e,rawfilemd5:s,filesize:a,no_need_thumb:true,aeskey:n.toString("hex")});if(!c.upload_param)throw new Error("No upload_param in response");let d=Ar(o.cdnBaseUrl,c.upload_param,i),g=new Uint8Array(r),p=await Fetch.request(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Blob([g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength)]),timeout:12e4,responseType:"json"});if(!p.ok)throw new Error(`CDN upload failed: HTTP ${p.status}`);return {encryptQueryParam:p.headers.get("x-encrypted-param")||"",aesKey:Buffer.from(n.toString("hex")).toString("base64"),fileSize:a,rawSize:e,fileName:basename(o.filePath)}}function Vs(o){let t=extname(o).toLowerCase(),e=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".heic"],s=[".mp4",".mov",".avi",".mkv",".webm"];return e.includes(t)?Pt.IMAGE:s.includes(t)?Pt.VIDEO:Pt.FILE}function Zs(){return join(we(),"access.json")}function en(){return join(we(),"pending-pairings.json")}function tn(){let o=en();if(!existsSync(o))return {};try{return JSON.parse(readFileSync(o,"utf-8"))}catch{return {}}}function xt(o){writeFileSync(en(),JSON.stringify(o,null,2),"utf-8");}function sn(){let o=Zs();if(!existsSync(o))return {policy:"pairing",allowFrom:[]};try{return JSON.parse(readFileSync(o,"utf-8"))}catch{return {policy:"pairing",allowFrom:[]}}}function xr(o){writeFileSync(Zs(),JSON.stringify(o,null,2),"utf-8");}function nn(o){let t=sn();return t.policy==="disabled"?true:t.allowFrom.includes(o)}function rn(o){let t=tn(),e=Date.now();for(let n of Object.keys(t))t[n].expiresAt<e&&delete t[n];for(let[n,i]of Object.entries(t))if(i.userId===o)return xt(t),n;let s=String(Math.floor(1e5+Math.random()*9e5));return t[s]={userId:o,expiresAt:e+600*1e3},xt(t),s}function ng(o){let t=tn(),e=t[o];if(!e||e.expiresAt<Date.now())return delete t[o],xt(t),null;delete t[o],xt(t);let s=sn();return s.allowFrom.includes(e.userId)||(s.allowFrom.push(e.userId),xr(s)),e.userId}function Mr(o){let t="",e=0;for(;e<o.length;)if(o.startsWith("```",e)){let s=e+3;for(;s<o.length&&o[s]!==`
22
22
  `;)s++;s<o.length&&s++;let n=s;for(;s<o.length;){if(o.startsWith("```",s)){for(t+=o.slice(n,s),s+=3;s<o.length&&o[s]!==`
23
23
  `;)s++;s<o.length&&s++;break}s++;}s>=o.length&&!o.startsWith("```",s-3)&&(t+=o.slice(e)),e=s;}else t+=o[e],e++;return t}function on(o){return Mr(o).replace(/`([^`]+)`/g,"$1").replace(/\*\*\*(.+?)\*\*\*/g,"$1").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/___(.+?)___/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1 ($2)").replace(/!\[([^\]]*)\]\([^)]+\)/g,"[$1]").replace(/^>\s+/gm,"").replace(/^[-*_]{3,}$/gm,"---").replace(/^[\s]*[-*+]\s+/gm,"- ").replace(/^[\s]*(\d+)\.\s+/gm,"$1. ").replace(/\n{3,}/g,`
24
24
 
25
- `).trim()}async function $e(o){let t=randomUUID();return await Xt(o.baseUrl,o.token,{to_user_id:o.to,from_user_id:"",client_id:t,message_type:Oe.BOT,message_state:Yt.FINISH,context_token:o.contextToken,item_list:[{type:D.TEXT,text_item:{text:on(o.text)}}]}),{messageId:t}}async function kr(o){let t="";for(let e of o.items)t=randomUUID(),await Xt(o.baseUrl,o.token,{to_user_id:o.to,from_user_id:"",client_id:t,message_type:Oe.BOT,message_state:Yt.FINISH,context_token:o.contextToken,item_list:[e]});return t}async function cn(o){let t=Vs(o.filePath),e=await Ks({filePath:o.filePath,toUserId:o.to,mediaType:t,apiBaseUrl:o.baseUrl,token:o.token,cdnBaseUrl:o.cdnBaseUrl}),s={encrypt_query_param:e.encryptQueryParam,aes_key:e.aesKey,encrypt_type:1},n=[];switch(o.text&&n.push({type:D.TEXT,text_item:{text:on(o.text)}}),t){case 1:n.push({type:D.IMAGE,image_item:{media:s,mid_size:e.fileSize}});break;case 2:n.push({type:D.VIDEO,video_item:{media:s,video_size:e.fileSize}});break;default:n.push({type:D.FILE,file_item:{media:s,file_name:e.fileName,len:String(e.rawSize)}});break}return {messageId:await kr({items:n,to:o.to,baseUrl:o.baseUrl,token:o.token,contextToken:o.contextToken})}}var Lr=/^\s*(y|yes|n|no)\s+([a-km-z]{5})\s*$/i,le=Log.create({service:"weixin-sdk"}),gn=new Map;function xt(o){return gn.get(o)}function un(){return join(we(),"cursor.txt")}function Gr(){let o=un();return existsSync(o)?readFileSync(o,"utf-8").trim():""}function Ur(o){writeFileSync(un(),o,"utf-8");}function Fr(o){if(o)return o;let t=v()?.Path?.data||process.env.EASBOT_DATA_PATH;return t?Filesystem.join(t,"gateway","downloads"):join(tmpdir(),"weixin-media")}async function Br(o,t,e){let s,n,i="",r="";switch(o.type){case D.IMAGE:s=o.image_item?.media?.encrypt_query_param,n=o.image_item?.aeskey?Buffer.from(o.image_item.aeskey,"hex").toString("base64"):o.image_item?.media?.aes_key,i=".jpg",r="image";break;case D.VOICE:s=o.voice_item?.media?.encrypt_query_param,n=o.voice_item?.media?.aes_key,i=".silk",r="voice";break;case D.FILE:s=o.file_item?.media?.encrypt_query_param,n=o.file_item?.media?.aes_key,i=o.file_item?.file_name?`.${o.file_item.file_name.split(".").pop()}`:"",r="file";break;case D.VIDEO:s=o.video_item?.media?.encrypt_query_param,n=o.video_item?.media?.aes_key,i=".mp4",r="video";break;default:return null}if(!s||!n)return null;try{let a=await qs({encryptQueryParam:s,aesKey:n,cdnBaseUrl:t}),c=Fr(e);existsSync(c)||mkdirSync(c,{recursive:!0});let d=o.file_item?.file_name||`${Date.now()}${i}`,g=basename(d),p=join(c,g);return writeFileSync(p,a),{path:p,type:r}}catch(a){return le.error("failed to download media",{error:String(a)}),null}}function Or(o){let t=o.match(Lr);if(!t)return null;let e=t[1]?.toLowerCase().startsWith("y")?"allow":"deny",s=t[2]?.toLowerCase();return s?{requestId:s,behavior:e}:null}async function pn(o){let{baseUrl:t,cdnBaseUrl:e,token:s,onMessage:n,onPermissionResponse:i,abortSignal:r,downloadDir:a}=o,c=Gr(),d=0;for(le.info("starting message poll loop");!r.aborted;)try{let g=await Bs(t,s,c,r);if(g.errcode===-14){le.warn("session expired (errcode -14), pausing 30s"),await new Promise(p=>setTimeout(p,3e4));continue}if(g.ret!==0&&g.ret!==void 0)throw new Error(`getUpdates error: ret=${g.ret} errcode=${g.errcode} ${g.errmsg}`);if(d=0,g.get_updates_buf&&(c=g.get_updates_buf,Ur(c)),g.msgs&&g.msgs.length>0)for(let p of g.msgs)await $r(p,{baseUrl:t,cdnBaseUrl:e,token:s,onMessage:n,onPermissionResponse:i,downloadDir:a});}catch(g){if(r.aborted)break;d+=1,le.error("poll error",{consecutiveErrors:d,error:g instanceof Error?g.message:String(g)}),d>=3?(le.warn("too many consecutive errors, backing off 30s"),await new Promise(p=>setTimeout(p,3e4)),d=0):await new Promise(p=>setTimeout(p,2e3));}le.info("poll loop stopped");}async function $r(o,t){if(o.message_type!==Oe.USER)return;let e=o.from_user_id;if(!e)return;if(o.context_token&&gn.set(e,o.context_token),!nn(e)){let r=rn(e);try{await $e({to:e,text:`Your pairing code is: ${r}
25
+ `).trim()}async function $e(o){let t=randomUUID();return await Yt(o.baseUrl,o.token,{to_user_id:o.to,from_user_id:"",client_id:t,message_type:Oe.BOT,message_state:Zt.FINISH,context_token:o.contextToken,item_list:[{type:D.TEXT,text_item:{text:on(o.text)}}]}),{messageId:t}}async function kr(o){let t="";for(let e of o.items)t=randomUUID(),await Yt(o.baseUrl,o.token,{to_user_id:o.to,from_user_id:"",client_id:t,message_type:Oe.BOT,message_state:Zt.FINISH,context_token:o.contextToken,item_list:[e]});return t}async function cn(o){let t=Vs(o.filePath),e=await Ks({filePath:o.filePath,toUserId:o.to,mediaType:t,apiBaseUrl:o.baseUrl,token:o.token,cdnBaseUrl:o.cdnBaseUrl}),s={encrypt_query_param:e.encryptQueryParam,aes_key:e.aesKey,encrypt_type:1},n=[];switch(o.text&&n.push({type:D.TEXT,text_item:{text:on(o.text)}}),t){case 1:n.push({type:D.IMAGE,image_item:{media:s,mid_size:e.fileSize}});break;case 2:n.push({type:D.VIDEO,video_item:{media:s,video_size:e.fileSize}});break;default:n.push({type:D.FILE,file_item:{media:s,file_name:e.fileName,len:String(e.rawSize)}});break}return {messageId:await kr({items:n,to:o.to,baseUrl:o.baseUrl,token:o.token,contextToken:o.contextToken})}}var Lr=/^\s*(y|yes|n|no)\s+([a-km-z]{5})\s*$/i,le=Log.create({service:"weixin-sdk"}),gn=new Map;function Mt(o){return gn.get(o)}function un(){return join(we(),"cursor.txt")}function Gr(){let o=un();return existsSync(o)?readFileSync(o,"utf-8").trim():""}function Ur(o){writeFileSync(un(),o,"utf-8");}function Fr(o){if(o)return o;let t=v()?.Path?.data||process.env.EASBOT_DATA_PATH;return t?Filesystem.join(t,"gateway","downloads"):join(tmpdir(),"weixin-media")}async function Br(o,t,e){let s,n,i="",r="";switch(o.type){case D.IMAGE:s=o.image_item?.media?.encrypt_query_param,n=o.image_item?.aeskey?Buffer.from(o.image_item.aeskey,"hex").toString("base64"):o.image_item?.media?.aes_key,i=".jpg",r="image";break;case D.VOICE:s=o.voice_item?.media?.encrypt_query_param,n=o.voice_item?.media?.aes_key,i=".silk",r="voice";break;case D.FILE:s=o.file_item?.media?.encrypt_query_param,n=o.file_item?.media?.aes_key,i=o.file_item?.file_name?`.${o.file_item.file_name.split(".").pop()}`:"",r="file";break;case D.VIDEO:s=o.video_item?.media?.encrypt_query_param,n=o.video_item?.media?.aes_key,i=".mp4",r="video";break;default:return null}if(!s||!n)return null;try{let a=await qs({encryptQueryParam:s,aesKey:n,cdnBaseUrl:t}),c=Fr(e);existsSync(c)||mkdirSync(c,{recursive:!0});let d=o.file_item?.file_name||`${Date.now()}${i}`,g=basename(d),p=join(c,g);return writeFileSync(p,a),{path:p,type:r}}catch(a){return le.error("failed to download media",{error:String(a)}),null}}function Or(o){let t=o.match(Lr);if(!t)return null;let e=t[1]?.toLowerCase().startsWith("y")?"allow":"deny",s=t[2]?.toLowerCase();return s?{requestId:s,behavior:e}:null}async function pn(o){let{baseUrl:t,cdnBaseUrl:e,token:s,onMessage:n,onPermissionResponse:i,abortSignal:r,downloadDir:a}=o,c=Gr(),d=0;for(le.info("starting message poll loop");!r.aborted;)try{let g=await Bs(t,s,c,r);if(g.errcode===-14){le.warn("session expired (errcode -14), pausing 30s"),await new Promise(p=>setTimeout(p,3e4));continue}if(g.ret!==0&&g.ret!==void 0)throw new Error(`getUpdates error: ret=${g.ret} errcode=${g.errcode} ${g.errmsg}`);if(d=0,g.get_updates_buf&&(c=g.get_updates_buf,Ur(c)),g.msgs&&g.msgs.length>0)for(let p of g.msgs)await $r(p,{baseUrl:t,cdnBaseUrl:e,token:s,onMessage:n,onPermissionResponse:i,downloadDir:a});}catch(g){if(r.aborted)break;d+=1,le.error("poll error",{consecutiveErrors:d,error:g instanceof Error?g.message:String(g)}),d>=3?(le.warn("too many consecutive errors, backing off 30s"),await new Promise(p=>setTimeout(p,3e4)),d=0):await new Promise(p=>setTimeout(p,2e3));}le.info("poll loop stopped");}async function $r(o,t){if(o.message_type!==Oe.USER)return;let e=o.from_user_id;if(!e)return;if(o.context_token&&gn.set(e,o.context_token),!nn(e)){let r=rn(e);try{await $e({to:e,text:`Your pairing code is: ${r}
26
26
 
27
27
  Ask the operator to confirm:
28
28
  easbot weixin access pair ${r}`,baseUrl:t.baseUrl,token:t.token,contextToken:o.context_token||""});}catch(a){le.error("failed to send pairing code",{fromUserId:e,error:String(a)});}return}let s="",n,i;if(o.item_list){for(let r of o.item_list)if(r.type===D.TEXT&&r.text_item?.text)s+=`${s?`
29
29
  `:""}${r.text_item.text}`;else if(r.type===D.IMAGE||r.type===D.VOICE||r.type===D.FILE||r.type===D.VIDEO){let a=await Br(r,t.cdnBaseUrl,t.downloadDir);a&&(n=a.path,i=a.type),r.type===D.VOICE&&r.voice_item?.text&&(s+=`${s?`
30
- `:""}[Voice transcription]: ${r.voice_item.text}`);}}if(!(!s&&!n)){if(s&&t.onPermissionResponse){let r=Or(s);if(r){let{consumePendingPermission:a}=await import('./permissions-VGMKDEK7.mjs'),c=a(r.requestId,e);if(c){await t.onPermissionResponse({requestId:c.request_id,behavior:r.behavior,fromUserId:e});return}}}await t.onMessage({fromUserId:e,messageId:String(o.message_id||""),text:s||"(media attachment)",attachmentPath:n,attachmentType:i});}}var We=class extends P{constructor(e="weixin-main"){super();a(this,"id");a(this,"platform","weixin");a(this,"name","WeChat iLink");a(this,"botConfig",null);a(this,"account",null);a(this,"abortController",null);a(this,"processedMessageIds",new Set);a(this,"sentMessages",new Map);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});a(this,"pollingStopped",false);this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");this.botConfig=this.config.platform,Fs(this.resolveStateDir());let e=Qt();if(!e?.token)throw y(this.id,"CONFIG_MISSING_REQUIRED","WeChat account not connected. Run `easbot weixin login` to bind a personal WeChat account.");this.account={token:e.token,baseUrl:e.baseUrl||this.botConfig.baseUrl||Gs,userId:e.userId,savedAt:e.savedAt},this.abortController=new AbortController,this.runPollLoop().catch(s=>{this.log.error("poll loop crashed",{error:String(s)});}),this.log.info("Weixin plugin started",{userId:this.account.userId,baseUrl:this.account.baseUrl,stateDir:this.resolveStateDir()});}resolveStateDir(){let e=this.botConfig?.stateDir;if(e)return e;let s=v()?.Path?.data;return s?Filesystem.join(s,"gateway","channels","weixin"):join(homedir(),".easbot","channels","weixin")}async doStop(){this.abortController?.abort(),this.abortController=null,this.processedMessageIds.clear(),this.sentMessages.clear(),this.pollingStopped=false,this.retryState.attempts=0,this.botConfig=null,this.account=null,this.log.debug("Weixin plugin stopped");}async doHealthCheck(){if(this._status!=="running")return false;if(this.pollingStopped)return this.log.warn("weixin poll loop was stopped, attempting restart"),this.restartPollLoop(),true;if(this.abortController?.signal.aborted)return false;let e=Qt();return !!e&&!!e.token}async send(e){if(!this.account)throw y(this.id,"MESSAGE_SEND_FAILED","Weixin plugin not started");let s=e.metadata.channel.userId;if(!s)throw y(this.id,"MESSAGE_SEND_FAILED","User ID is required");let n=this.extractText(e),i=this.botConfig?.cdnBaseUrl||Vt,r=xt(s)||"",a=this.botConfig?.maxMessageLength??4e3,c=n;if(n.length>a){let h=await TruncateContent.truncate(n,{maxChars:a,label:"weixin message"});c=h.content,this.log.debug("send: message truncated",{originalLength:n.length,maxLength:a,outputPath:h.truncated?h.outputPath:void 0});}let d=e.content.find(h=>h.type==="image"),g=e.content.find(h=>h.type==="file"),p;if(d||g){let h=d??g,S="image"in h?h.image:h.data,C=await this.resolveAttachmentToPath(S,this.id);p=await cn({filePath:C,to:s,text:c,baseUrl:this.account.baseUrl,token:this.account.token,contextToken:r,cdnBaseUrl:i});}else p=await $e({to:s,text:c,baseUrl:this.account.baseUrl,token:this.account.token,contextToken:r});return this.sentMessages.set(e.id,{userId:s,clientId:p.messageId,timestamp:Date.now()}),p.messageId}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:false,supportsThread:false,supportsEdit:false,supportsDelete:false,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:false,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:this.botConfig?.maxMessageLength??4e3,maxMediaCount:1}}resolveDownloadDir(){let e=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot";return Filesystem.join(e,"gateway","downloads")}async runPollLoop(){if(!this.account||!this.abortController)return;let e=this.botConfig?.cdnBaseUrl||Vt,s=this.resolveDownloadDir();await Filesystem.mkdir(s,{recursive:true});try{await pn({baseUrl:this.account.baseUrl,cdnBaseUrl:e,token:this.account.token,onMessage:async n=>this.handleWeixinMessage(n),abortSignal:this.abortController.signal,downloadDir:s});}catch(n){this.log.error("poll loop crashed",{error:String(n)}),this.pollingStopped=true;}}restartPollLoop(){this.account&&(this.retryState.attempts=0,this.pollingStopped=false,this.abortController=new AbortController,this.runPollLoop(),this.log.debug("weixin poll loop restarted"));}async handleWeixinMessage(e){this.updateActivity();let s=e.messageId||`${e.fromUserId}:${e.text}`;if(this.processedMessageIds.has(s)){this.log.debug("duplicate weixin message ignored",{messageKey:s});return}if(this.processedMessageIds.add(s),this.processedMessageIds.size>1e4){let a=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(a.slice(-5e3));}let n=this.buildSessionId(this.id,e.fromUserId,e.fromUserId),i={platform:this.platform,channelId:this.id,userId:e.fromUserId,chatId:e.fromUserId,chatType:"private"};if(e.text.trim().startsWith("/")){let a=await this.processCommand({text:e.text,sessionId:n,chatId:e.fromUserId,channelInfo:i,messageId:e.messageId});if(a.handled){a.reply?await this.sendCommandReply(e.fromUserId,a.reply):a.gatewayMessage&&await this.handleMessage(a.gatewayMessage);return}}let r=A(n,"input",await this.parseContent(e),{channel:i,context:{messageId:e.messageId,source:"ilink"}});await this.handleMessage(r);}async sendCommandReply(e,s){if(!this.account)return;let n=xt(e)??"";try{await $e({to:e,text:s,baseUrl:this.account.baseUrl,token:this.account.token,contextToken:n}),this.log.debug("weixin command reply sent",{toUserId:e,length:s.length});}catch(i){this.log.error("weixin command reply failed",{toUserId:e,error:String(i)});}}async parseContent(e){let s=[],n=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");if(e.attachmentPath){let r=pathToFileURL(e.attachmentPath).href,a=Filesystem.mimeType(e.attachmentPath),c=e.attachmentPath.split(/[\\/]/).pop()||e.attachmentPath;if(e.attachmentType==="image"){let d=a.startsWith("image/")?a:"image/jpeg";s.push({type:"image",image:r,mime:d});}else if(e.attachmentType==="voice")this.log.debug("weixin voice: skip raw attachment, transcription in text",{attachmentPath:e.attachmentPath});else if(Filesystem.isTextMime(a))try{let d=await readFile(e.attachmentPath,"utf-8"),g=await TruncateContent.truncate(d,{maxChars:5e3,label:`file: ${c}`});s.push({type:"text",text:`\u{1F4CE} File: ${c}
30
+ `:""}[Voice transcription]: ${r.voice_item.text}`);}}if(!(!s&&!n)){if(s&&t.onPermissionResponse){let r=Or(s);if(r){let{consumePendingPermission:a}=await import('./permissions-VGMKDEK7.mjs'),c=a(r.requestId,e);if(c){await t.onPermissionResponse({requestId:c.request_id,behavior:r.behavior,fromUserId:e});return}}}await t.onMessage({fromUserId:e,messageId:String(o.message_id||""),text:s||"(media attachment)",attachmentPath:n,attachmentType:i});}}function Qr(o,t){return o===t?true:!o||!t?false:o.token===t.token&&o.userId===t.userId&&o.baseUrl===t.baseUrl&&o.savedAt===t.savedAt}var We=class extends P{constructor(e="weixin-main"){super();a(this,"id");a(this,"platform","weixin");a(this,"name","WeChat iLink");a(this,"botConfig",null);a(this,"account",null);a(this,"abortController",null);a(this,"processedMessageIds",new Set);a(this,"sentMessages",new Map);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});a(this,"pollingStopped",false);a(this,"accountWatcher",null);a(this,"reloadDebounceTimer",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");this.botConfig=this.config.platform,Fs(this.resolveStateDir());let e=At();if(!e?.token)throw y(this.id,"CONFIG_MISSING_REQUIRED","WeChat account not connected. Run `easbot weixin login` to bind a personal WeChat account.");this.account={token:e.token,baseUrl:e.baseUrl||this.botConfig.baseUrl||Jt,userId:e.userId,savedAt:e.savedAt},this.abortController=new AbortController,this.startStateFileWatchers(),this.runPollLoop().catch(s=>{this.log.error("poll loop crashed",{error:String(s)});}),this.log.info("Weixin plugin started",{userId:this.account.userId,baseUrl:this.account.baseUrl,stateDir:this.resolveStateDir()});}resolveStateDir(){let e=this.botConfig?.stateDir;if(e)return e;let s=v()?.Path?.data;return s?Filesystem.join(s,"gateway","channels","weixin"):join(homedir(),".easbot","channels","weixin")}async doStop(){this.stopStateFileWatchers(),this.abortController?.abort(),this.abortController=null,this.processedMessageIds.clear(),this.sentMessages.clear(),this.pollingStopped=false,this.retryState.attempts=0,this.botConfig=null,this.account=null,this.log.debug("Weixin plugin stopped");}async doHealthCheck(){if(this._status!=="running")return false;if(this.pollingStopped)return this.log.warn("weixin poll loop was stopped, attempting restart"),this.restartPollLoop(),true;if(this.abortController?.signal.aborted)return false;let e=At();return !!e&&!!e.token}startStateFileWatchers(){let e=this.resolveStateDir();if(!existsSync(e)){this.log.warn("weixin state dir missing, skip watcher",{stateDir:e});return}try{this.accountWatcher=watch(e,{persistent:!1},(s,n)=>{(n==="account.json"||n==="access.json")&&this.scheduleReloadAccount();}),this.accountWatcher.on("error",s=>{this.log.error("state file watcher error",{error:String(s)});}),this.log.debug("weixin state file watcher started",{stateDir:e});}catch(s){this.log.error("failed to start state file watcher",{error:String(s)});}}stopStateFileWatchers(){this.reloadDebounceTimer&&(clearTimeout(this.reloadDebounceTimer),this.reloadDebounceTimer=null),this.accountWatcher&&(this.accountWatcher.close(),this.accountWatcher=null);}scheduleReloadAccount(){this.reloadDebounceTimer&&clearTimeout(this.reloadDebounceTimer),this.reloadDebounceTimer=setTimeout(()=>{this.reloadDebounceTimer=null,this.reloadAccountIfChanged();},200);}reloadAccountIfChanged(){let e=At();if(!e){this.log.warn("account.json deleted or unreadable, leaving plugin running");return}let s=this.account,n=e.baseUrl||this.botConfig?.baseUrl||Jt,i={token:e.token,baseUrl:n,userId:e.userId,savedAt:e.savedAt};Qr(s,i)||(this.log.info("weixin account changed, reloading",{oldUserId:s?.userId,newUserId:e.userId}),this.account=i,this._status==="running"&&this.restartPollLoop());}async send(e){if(!this.account)throw y(this.id,"MESSAGE_SEND_FAILED","Weixin plugin not started");let s=e.metadata.channel.userId;if(!s)throw y(this.id,"MESSAGE_SEND_FAILED","User ID is required");let n=this.extractText(e),i=this.botConfig?.cdnBaseUrl||Qt,r=Mt(s)||"",a=this.botConfig?.maxMessageLength??4e3,c=n;if(n.length>a){let h=await TruncateContent.truncate(n,{maxChars:a,label:"weixin message"});c=h.content,this.log.debug("send: message truncated",{originalLength:n.length,maxLength:a,outputPath:h.truncated?h.outputPath:void 0});}let d=e.content.find(h=>h.type==="image"),g=e.content.find(h=>h.type==="file"),p;if(d||g){let h=d??g,S="image"in h?h.image:h.data,C=await this.resolveAttachmentToPath(S,this.id);p=await cn({filePath:C,to:s,text:c,baseUrl:this.account.baseUrl,token:this.account.token,contextToken:r,cdnBaseUrl:i});}else p=await $e({to:s,text:c,baseUrl:this.account.baseUrl,token:this.account.token,contextToken:r});return this.sentMessages.set(e.id,{userId:s,clientId:p.messageId,timestamp:Date.now()}),p.messageId}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:false,supportsThread:false,supportsEdit:false,supportsDelete:false,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:false,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:this.botConfig?.maxMessageLength??4e3,maxMediaCount:1}}resolveDownloadDir(){let e=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot";return Filesystem.join(e,"gateway","downloads")}async runPollLoop(){if(!this.account||!this.abortController)return;let e=this.botConfig?.cdnBaseUrl||Qt,s=this.resolveDownloadDir();await Filesystem.mkdir(s,{recursive:true});try{await pn({baseUrl:this.account.baseUrl,cdnBaseUrl:e,token:this.account.token,onMessage:async n=>this.handleWeixinMessage(n),abortSignal:this.abortController.signal,downloadDir:s});}catch(n){this.log.error("poll loop crashed",{error:String(n)}),this.pollingStopped=true;}}restartPollLoop(){this.account&&(this.retryState.attempts=0,this.pollingStopped=false,this.abortController=new AbortController,this.runPollLoop(),this.log.debug("weixin poll loop restarted"));}async handleWeixinMessage(e){this.updateActivity();let s=e.messageId||`${e.fromUserId}:${e.text}`;if(this.processedMessageIds.has(s)){this.log.debug("duplicate weixin message ignored",{messageKey:s});return}if(this.processedMessageIds.add(s),this.processedMessageIds.size>1e4){let a=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(a.slice(-5e3));}let n=this.buildSessionId(this.id,e.fromUserId,e.fromUserId),i={platform:this.platform,channelId:this.id,userId:e.fromUserId,chatId:e.fromUserId,chatType:"private"};if(e.text.trim().startsWith("/")){let a=await this.processCommand({text:e.text,sessionId:n,chatId:e.fromUserId,channelInfo:i,messageId:e.messageId});if(a.handled){a.reply?await this.sendCommandReply(e.fromUserId,a.reply):a.gatewayMessage&&await this.handleMessage(a.gatewayMessage);return}}let r=A(n,"input",await this.parseContent(e),{channel:i,context:{messageId:e.messageId,source:"ilink"}});await this.handleMessage(r);}async sendCommandReply(e,s){if(!this.account)return;let n=Mt(e)??"";try{await $e({to:e,text:s,baseUrl:this.account.baseUrl,token:this.account.token,contextToken:n}),this.log.debug("weixin command reply sent",{toUserId:e,length:s.length});}catch(i){this.log.error("weixin command reply failed",{toUserId:e,error:String(i)});}}async parseContent(e){let s=[],n=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");if(e.attachmentPath){let r=pathToFileURL(e.attachmentPath).href,a=Filesystem.mimeType(e.attachmentPath),c=e.attachmentPath.split(/[\\/]/).pop()||e.attachmentPath;if(e.attachmentType==="image"){let d=a.startsWith("image/")?a:"image/jpeg";s.push({type:"image",image:r,mime:d});}else if(e.attachmentType==="voice")this.log.debug("weixin voice: skip raw attachment, transcription in text",{attachmentPath:e.attachmentPath});else if(Filesystem.isTextMime(a))try{let d=await readFile(e.attachmentPath,"utf-8"),g=await TruncateContent.truncate(d,{maxChars:5e3,label:`file: ${c}`});s.push({type:"text",text:`\u{1F4CE} File: ${c}
31
31
 
32
- ${g.content}`}),this.log.debug("weixin text file inlined",{fileName:c,mime:a,length:d.length});}catch(d){this.log.warn("weixin text file read failed, fallback to file part",{fileName:c,error:String(d)}),s.push({type:"file",data:r,mime:a});}else s.push({type:"file",data:r,mime:a});this.log.debug("weixin attachment resolved",{downloadDir:i,source:e.attachmentPath});}return e.text&&s.push({type:"text",text:e.text}),s}async resolveAttachmentToPath(e,s){if(typeof e=="string")return /^https?:\/\//i.test(e)?this.downloadUrlToLocal(e,s):e.startsWith("file://")?fileURLToPath(e):e;if(e instanceof URL)return /^https?:$/i.test(e.protocol)?this.downloadUrlToLocal(e.toString(),s):this.resolveAttachmentToPath(e.toString(),s);let n=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");await Filesystem.mkdir(i,{recursive:true});let r=Filesystem.join(i,`${s}_${Date.now()}.bin`);return await Filesystem.write(r,Buffer.from(e)),r}async downloadUrlToLocal(e,s){let n=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");await Filesystem.mkdir(i,{recursive:true});let r=new URL(e).pathname.split("/").pop()||`weixin_${Date.now()}`,a=Filesystem.join(i,`${s}_${r}`);this.log.debug("weixin download remote attachment",{url:e,dest:a});let c=await Fetch.get(e,{responseType:"arrayBuffer",timeout:12e4});if(!c.ok)throw new Error(`Failed to download attachment from ${e}: HTTP ${c.status}`);return await Filesystem.write(a,Buffer.from(c.data)),this.log.debug("weixin remote attachment downloaded",{url:e,dest:a,bytes:c.data.byteLength}),a}async sendTyping(e){if(!this.account)return;let s=xt(e);if(!s){this.log.debug("sendTyping skipped: no context token",{userId:e});return}try{let n=await $s(this.account.baseUrl,this.account.token,e,s);n.typing_ticket&&await Ws(this.account.baseUrl,this.account.token,{ilink_user_id:e,typing_ticket:n.typing_ticket,status:Hs.TYPING});}catch(n){this.log.debug("sendTyping failed",{userId:e,error:String(n)});}}buildSessionId(e,s,n){let i=n??s;return `${this.platform}_${e}_${s}_${i}`}};var He=class extends P{constructor(e="webchat-main"){super();a(this,"id");a(this,"platform","webchat");a(this,"name","WebChat");a(this,"webChatConfig",null);a(this,"connections",new Map);a(this,"heartbeatInterval",null);a(this,"abortController",null);a(this,"processedMessageIds",new Set);a(this,"sentMessages",new Map);a(this,"wsServer",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","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 doStop(){this.abortController?.abort(),this.abortController=null,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.wsServer&&(await this.wsServer.stop(),this.wsServer=null);for(let e of this.connections.values())e.ws.close();this.connections.clear(),this.processedMessageIds.clear(),this.sentMessages.clear(),this.webChatConfig=null,this.log.info("WebChat plugin stopped");}async doHealthCheck(){return !(this._status!=="running"||this.abortController?.signal.aborted||!this.wsServer)}async send(e){let s=e.sessionId,n=e.metadata.channel.userId;if(!n)throw y(this.id,"MESSAGE_SEND_FAILED","User ID is required");let i=this.findConnectionByUser(n);if(!i)throw y(this.id,"MESSAGE_SEND_FAILED","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(),this.sentMessages.set(e.id,{sessionId:s,messageId:e.id,timestamp: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,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:1e5,maxMediaCount:20}}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.debug("WebSocket connected",{connId:n,userId:s});}getConnectionCount(){return this.connections.size}getWsServerConnectionCount(){return this.wsServer?.getConnectionCount()??0}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 ae(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 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.debug("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||this.processedMessageIds.has(s.messageId??""))return;if(s.messageId&&(this.processedMessageIds.add(s.messageId),this.processedMessageIds.size>1e4)){let r=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(r.slice(-5e3));}let n=s.content.find(r=>r.type==="text");if(n?.text.trim().startsWith("/")){let r=this.buildSessionId(this.id,s.sessionId,e.userId),a=await this.processCommand({text:n.text,sessionId:r,chatId:s.sessionId,channelInfo:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},messageId:s.messageId});if(a.handled){if(a.reply){let c=A(s.sessionId,"output",[{type:"text",text:a.reply}],{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},context:{conversationId:s.sessionId},...s.metadata});await this.send(c);}else a.gatewayMessage&&await this.handleMessage(a.gatewayMessage);return}}let i=A(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(i);}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.debug("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)}`}};var ze=class extends P{constructor(e="signal-main"){super();a(this,"id");a(this,"platform","signal");a(this,"name","Signal Bot");a(this,"botConfig",null);a(this,"abortController",null);a(this,"lastTimestamp",0);a(this,"pollingIntervalMs",5e3);a(this,"processedMessageIds",new Set);a(this,"sentMessages",new Map);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.phoneNumber)throw y(this.id,"CONFIG_MISSING_REQUIRED","Phone number is required");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.polling&&(this.pollingIntervalMs=this.botConfig.polling.interval??5e3),this.abortController=new AbortController;let e=await this.getAccountInfo();this.log.info("Signal bot connected",{number:this.botConfig.phoneNumber,address:e.address}),this.botConfig.polling?.enabled!==false&&this.startPolling();}async doStop(){this.abortController?.abort(),this.abortController=null,this.processedMessageIds.clear(),this.sentMessages.clear(),this.lastTimestamp=0,this.botConfig=null,this.retryState.attempts=0,this.log.info("Signal plugin stopped");}async doHealthCheck(){if(this._status!=="running"||this.abortController?.signal.aborted)return false;try{return await this.getAccountInfo(),!0}catch{return false}}async send(e){let s=e.metadata.channel.userId;if(!s)throw y(this.id,"MESSAGE_SEND_FAILED","Recipient is required");let n=this.extractText(e),i=await this.sendMessage(s,n);return this.sentMessages.set(e.id,{timestamp:i.timestamp}),i.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,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",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){let n=`${s.envelope.sourceNumber}_${s.envelope.timestamp}`;if(!this.processedMessageIds.has(n)){if(this.processedMessageIds.add(n),this.processedMessageIds.size>1e4){let i=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(i.slice(-5e3));}this.lastTimestamp=s.envelope.timestamp,s.envelope.dataMessage&&await this.handleSignalMessage(s);}}}async handleSignalMessage(e){this.updateActivity();let s=e.envelope.dataMessage?.message;if(s?.trim().startsWith("/")){let i=this.buildSessionId(this.id,e.envelope.sourceNumber),r=await this.processCommand({text:s,sessionId:i,chatId:e.envelope.sourceNumber,channelInfo:{platform:"signal",channelId:this.id,userId:e.envelope.sourceNumber,chatId:e.envelope.sourceNumber,timestamp:e.envelope.dataMessage?.timestamp},messageId:e.envelope.dataMessage?.timestamp?.toString()});if(r.handled){r.reply?await this.sendMessage(e.envelope.sourceNumber,r.reply):r.gatewayMessage&&await this.handleMessage(r.gatewayMessage);return}}let n=await this.toGatewayMessage(e);await this.handleMessage(n);}async toGatewayMessage(e){let s=this.buildSessionId(this.id,e.envelope.sourceNumber),n=e.envelope.dataMessage;return A(s,"input",await 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}})}async parseContent(e){let s=[],n=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");if(!e)return s;if(e.message&&s.push({type:"text",text:e.message}),e.attachments)for(let r of e.attachments)try{let a=r.contentType.split("/").pop()||"bin",c=Filesystem.join(i,`signal_${r.id}.${a}`);s.push({type:r.contentType.startsWith("image/")?"image":"file",image:r.id,data:r.id,mime:r.contentType});}catch(a){this.log.warn("failed to handle attachment",{attachmentId:r.id,error:String(a)}),s.push({type:r.contentType.startsWith("image/")?"image":"file",image:r.id,data:r.id,mime:r.contentType});}return s}buildSessionId(e,s,n){let i=["signal",e,s];return n&&i.push(n),i.join("_")}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){let i=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let c=await TruncateContent.truncate(s,{maxChars:i,label:"signal message"});r=c.content,this.log.debug("sendMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:c.truncated?c.outputPath:void 0});}return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:r})}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 a;if(e==="GET"?a=await Fetch.get(i,{headers:r}):e==="POST"?a=await Fetch.post(i,n,{headers:r}):e==="DELETE"?a=await Fetch.del(i,{headers:r}):a=await Fetch.request(i,{method:e,body:n,headers:r}),!a.ok)throw y(this.id,"MESSAGE_SEND_FAILED",`Signal API error: ${JSON.stringify(a.data)}`);return a.data}};var je=class extends P{constructor(e="nostr-main"){super();a(this,"id");a(this,"platform","nostr");a(this,"name","Nostr Bot");a(this,"botConfig",null);a(this,"relayConnections",new Map);a(this,"subscriptions",new Map);a(this,"abortController",null);a(this,"processedEventIds",new Set);a(this,"sentMessages",new Map);a(this,"relayReconnectAttempts",new Map);a(this,"maxReconnectAttempts",5);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.relays||this.botConfig.relays.length===0)throw y(this.id,"CONFIG_MISSING_REQUIRED","At least one relay is required");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.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.processedEventIds.clear(),this.sentMessages.clear(),this.relayReconnectAttempts.clear(),this.botConfig=null,this.log.info("Nostr plugin stopped");}async doHealthCheck(){if(this._status!=="running"||this.abortController?.signal.aborted)return false;for(let e of this.relayConnections.values())if(e.readyState===WebSocket.OPEN)return true;return false}async send(e){if(!this.botConfig?.privateKey)throw y(this.id,"CONFIG_MISSING_REQUIRED","Private key is required for sending messages");let s=this.extractText(e),n=e.metadata.context?.replyTo,i=await this.createEvent(s,n);return await this.publishEvent(i),this.sentMessages.set(e.id,{eventId:i.id,timestamp:Date.now()}),i.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,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",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||this.processedEventIds.has(e.id))return;if(this.processedEventIds.add(e.id),this.processedEventIds.size>1e4){let n=Array.from(this.processedEventIds);this.processedEventIds=new Set(n.slice(-5e3));}if(e.pubkey===this.botConfig?.publicKey)return;if(e.content?.trim().startsWith("/")){let n=this.buildSessionId(this.id,e.pubkey),i=await this.processCommand({text:e.content,sessionId:n,chatId:e.pubkey,channelInfo:{platform:"nostr",channelId:this.id,userId:e.pubkey,chatId:e.pubkey,eventId:e.id,createdAt:e.created_at},messageId:e.id});if(i.handled){i.reply?await this.createEvent(i.reply):i.gatewayMessage&&await this.handleMessage(i.gatewayMessage);return}}let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.buildSessionId(this.id,e.pubkey);return A(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){let i=["nostr",e,s];return n&&i.push(n),i.join("_")}subscribeToRelay(e,s,n){let i=["REQ",s,n];e.send(JSON.stringify(i));}unsubscribeFromRelay(e,s){let n=["CLOSE",s];e.send(JSON.stringify(n));}async createEvent(e,s){let n=[];s&&n.push(["e",s,"","reply"]);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(c=>c.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw y(this.id,"CONFIG_MISSING_REQUIRED","Private key is required");return this.log.warn("Event signing not implemented, using placeholder signature"),"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 es=class extends P{constructor(e){super();a(this,"id");a(this,"platform");a(this,"name");a(this,"version");a(this,"options");this.id=e.id,this.platform=e.platform||"custom",this.name=e.name,this.version=e.version||"1.0.0",this.options=e,this.initLog();}async doStart(){this.options.setup?.initialize&&await this.options.setup.initialize(),this.log.info("Channel plugin started",{id:this.id,platform:this.platform});}async doStop(){this.options.setup?.destroy&&await this.options.setup.destroy(),this.log.info("Channel plugin stopped",{id:this.id});}async send(e){let 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 Jr(o){return new es(o)}var ts={telegram:De,discord:Ne,slack:Le,feishu:Ge,wechat:Ue,weixin:We,webchat:He,signal:ze,nostr:je};function Au(){return Object.keys(ts)}var I=Log.create({service:"gateway:net:registry"});function fn(o){if(!o)return {url:"",protocol:"unsupported"};let t=o.trim();return t.startsWith("ws://")||t.startsWith("wss://")||t.startsWith("acp-ws://")?(t.startsWith("acp-ws://")&&(t=t.replace("acp-ws://","ws://")),t.includes("/acp")||(t=t.replace(/\/$/,"")+"/acp"),{url:t,protocol:"websocket"}):t.startsWith("http://")||t.startsWith("https://")?(t.includes("/acp")||(t=t.replace(/\/$/,"")+"/acp"),{url:t,protocol:"http"}):{url:t,protocol:"unsupported"}}async function Xr(o,t){try{let e=await Fetch.post(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}},{timeout:t});if(!e.ok)return !1;let s=e.data;return !(!s||s.error)}catch{return false}}async function Yr(o,t){return new Promise(e=>{let s=null,n=false,i=setTimeout(()=>{n||(n=true,s?.close(),e(false));},t);try{s=new WebSocket(o),s.onopen=()=>{let r={jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}};s.send(JSON.stringify(r));},s.onmessage=r=>{try{let a=JSON.parse(r.data);a.id===1&&!a.error?n||(n=!0,clearTimeout(i),s?.close(),e(!0)):a.error&&(n||(n=!0,clearTimeout(i),s?.close(),e(!1)));}catch{}},s.onerror=()=>{n||(n=!0,clearTimeout(i),e(!1));},s.onclose=()=>{n||(n=!0,clearTimeout(i),e(!1));};}catch{n||(n=true,clearTimeout(i),e(false));}})}async function Zr(o,t){try{let e=await Fetch.post(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}},{timeout:t});if(!e.ok||!e.data?.result?.agentCapabilities)return [];let s=e.data.result.agentCapabilities,n=[];return s.mcpCapabilities&&(s.mcpCapabilities.http&&n.push("mcp:http"),s.mcpCapabilities.sse&&n.push("mcp:sse")),s.promptCapabilities&&(s.promptCapabilities.image&&n.push("prompt:image"),s.promptCapabilities.embeddedContext&&n.push("prompt:context")),s.sessionCapabilities&&(s.sessionCapabilities.fork&&n.push("session:fork"),s.sessionCapabilities.resume&&n.push("session:resume")),n}catch{return []}}var qe=class{constructor(t={}){a(this,"config");a(this,"agents",new Map);a(this,"heartbeatTimer",null);a(this,"roundRobinIndex",0);a(this,"store",null);a(this,"eventCallbacks",new Set);let{dataDir:e,...s}=t;this.config={...St,...s},e&&(this.store=new _e({dataDir:e}));}async load(){if(this.store)try{let t=await this.store.loadAll(),e=Date.now();for(let s of t)e-s.lastHeartbeat>this.config.heartbeatTimeout&&(s.status="unhealthy"),this.agents.set(s.id,s);I.info("Agent registry loaded from storage",{count:t.length});}catch(t){I.error("Failed to load agent registry from storage",{error:String(t)});}}async register(t){if(this.agents.has(t.id))throw new Error(`Agent with ID "${t.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),s={...t,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(t.id,s);let{url:n,protocol:i}=fn(t.address);if(i!=="http"&&i!=="websocket")throw new Error(`Unsupported protocol: ${t.address}. Only http/https/ws/wss are supported`);let r=await Zr(n,3e4).catch(()=>[]);r.length>0&&(s.capabilities=r),this.store&&await this.store.save(s),I.info("Agent registered",{agentId:t.id,name:t.name,capabilities:s.capabilities,address:t.address,totalAgents:this.agents.size}),this.emitEvent({type:"register",agent:s});}async deregister(t){let e=this.agents.get(t);if(!e){I.warn("Attempted to deregister unknown agent",{agentId:t});return}this.agents.delete(t),this.store&&await this.store.delete(t),I.info("Agent deregistered",{agentId:t,name:e.name,totalAgents:this.agents.size}),this.emitEvent({type:"deregister",agent:e});}async heartbeat(t,e){let s=this.agents.get(t);if(!s)throw I.warn("Heartbeat received from unknown agent",{agentId:t}),new Error(`Agent "${t}" is not registered`);let n=s.status;s.lastHeartbeat=Date.now(),s.status="healthy",e&&(s.metadata={...s.metadata,...e});let i=6e4,r=Date.now();this.store&&(n!=="healthy"||r-s.lastHeartbeat>=i)&&this.store.save(s).catch(a=>{I.error("Failed to save agent to store",{agentId:t,error:String(a)});}),n!=="healthy"&&this.emitEvent({type:"status_change",agent:s,oldStatus:n});}setStatus(t,e){let s=this.agents.get(t);if(!s){I.warn("Attempted to set status for unknown agent",{agentId:t});return}let n=s.status;n!==e&&(s.status=e,this.store&&this.store.save(s).catch(i=>{I.error("Failed to save agent status to store",{agentId:t,error:String(i)});}),this.emitEvent({type:"status_change",agent:s,oldStatus:n}));}getAgent(t){return this.agents.get(t)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(t=>t.status==="healthy")}selectAgent(t){let{strategy:e,capabilities:s,healthyOnly:n=true}=t,i=n?this.getHealthyAgents():this.getAllAgents();if(s&&s.length>0&&(i=i.filter(a=>s.every(c=>a.capabilities.includes(c)))),i.length===0){I.warn("No agents available for selection",{strategy:e,capabilities:s,healthyOnly:n,totalAgents:this.agents.size});return}let r;switch(e){case "random":r=this.selectRandom(i);break;case "round-robin":r=this.selectRoundRobin(i);break;case "least-connections":r=this.selectLeastConnections(i);break;default:r=this.selectRandom(i);}return I.debug("Agent selected",{agentId:r.id,strategy:e,connectionCount:r.connectionCount}),r}incrementConnection(t){let e=this.agents.get(t);e&&(e.connectionCount++,I.debug("Agent connection incremented",{agentId:t,connectionCount:e.connectionCount}));}decrementConnection(t){let e=this.agents.get(t);e&&e.connectionCount>0&&(e.connectionCount--,I.debug("Agent connection decremented",{agentId:t,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){I.warn("Heartbeat check is already running");return}I.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,I.info("Heartbeat check stopped"));}async checkHeartbeats(){let t=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:s}=this.config,n=[],i=0,r=[];for(let[a,c]of this.agents.entries()){let d=t-c.lastHeartbeat;if(d>s){n.push(a);continue}(d>e||c.status==="unhealthy")&&r.push((async()=>{let{url:g,protocol:p}=fn(c.address),h=this.config.heartbeatTimeout/2;I.debug("Checking agent connectivity",{agentId:a,url:g,protocol:p});let S=false;try{p==="http"?S=await Xr(g,h):S=await Yr(g,h);}catch(_){I.debug("Agent connectivity check error",{agentId:a,error:String(_)}),S=false;}let C=c.status;S?(c.lastHeartbeat=t,c.status!=="healthy"&&(c.status="healthy",I.debug("Agent recovered, marked as healthy",{agentId:a,name:c.name,previousStatus:C}),this.store&&this.store.save(c).catch(_=>{I.error("Failed to save agent to store",{agentId:a,error:String(_)});}),this.emitEvent({type:"status_change",agent:c,oldStatus:C}))):c.status==="healthy"&&(c.status="unhealthy",i++,I.warn("Agent marked as unhealthy due to connectivity check failed",{agentId:a,name:c.name,url:g,protocol:p,lastHeartbeat:c.lastHeartbeat,timeSinceLastHeartbeat:d,timeout:e}),this.store&&this.store.save(c).catch(_=>{I.error("Failed to save agent to store",{agentId:a,error:String(_)});}),this.emitEvent({type:"status_change",agent:c,oldStatus:C}));})());}await Promise.all(r);for(let a of n){let c=this.agents.get(a);c&&(I.debug("Auto-deregistering agent due to timeout",{agentId:a,name:c.name,lastHeartbeat:c.lastHeartbeat,timeout:s}),this.agents.delete(a),this.store&&await this.store.delete(a),this.emitEvent({type:"deregister",agent:c}));}(i>0||n.length>0)&&I.debug("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:n.length,totalAgents:this.agents.size});}onEvent(t){this.eventCallbacks.add(t);}offEvent(t){this.eventCallbacks.delete(t);}emitEvent(t){for(let e of this.eventCallbacks)try{e(t);}catch(s){I.error("Agent event callback error",{eventType:t.type,agentId:t.agent.id,error:String(s)});}}selectRandom(t){let e=Math.floor(Math.random()*t.length);return t[e]}selectRoundRobin(t){if(t.length===0)throw new Error("No candidates available for round-robin selection");this.roundRobinIndex>=t.length&&(this.roundRobinIndex=0);let e=t[this.roundRobinIndex];return this.roundRobinIndex=(this.roundRobinIndex+1)%t.length,e}selectLeastConnections(t){return t.reduce((e,s)=>s.connectionCount<e.connectionCount?s:e)}getStats(){let t=this.getAllAgents();return {totalAgents:t.length,healthyAgents:t.filter(e=>e.status==="healthy").length,unhealthyAgents:t.filter(e=>e.status==="unhealthy").length,offlineAgents:t.filter(e=>e.status==="offline").length,totalConnections:t.reduce((e,s)=>e+s.connectionCount,0)}}setAgentStatus(t,e){this.setStatus(t,e);}setLastHeartbeat(t,e){let s=this.agents.get(t);s&&(s.lastHeartbeat=e);}};var M=Log.create({service:"gateway:net:sync-manager"}),Ke=class{constructor(t){a(this,"config");a(this,"internalConfig");a(this,"registry");a(this,"localNodeId");a(this,"localNodeName");a(this,"remoteNodes",new Map);a(this,"remoteAgents",new Map);a(this,"syncTimer",null);a(this,"cleanupTimer",null);a(this,"reconnectTimer",null);a(this,"heartbeatTimer",null);a(this,"running",false);a(this,"agentListChangeCallbacks",new Set);this.registry=t.registry,this.localNodeId=t.localNodeId,this.localNodeName=t.localNodeName,this.config={...Ct,...t.config},this.internalConfig={maxConcurrentSync:3,remoteAgentTtl:300*1e3,cleanupInterval:180*1e3,maxRetryCount:5,baseRetryDelay:15e3};}async start(){if(this.running){M.warn("Agent sync manager is already running");return}M.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let t of this.config.remoteNodes)this.remoteNodes.set(t.id,{info:{id:t.id,name:t.id,address:t.address,port:t.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced",retryCount:0,nextRetryAt:0});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.cleanupTimer=setInterval(()=>this.cleanupStaleAgents(),this.internalConfig.cleanupInterval),this.reconnectTimer=setInterval(()=>this.reconnectFailedNodes(),this.internalConfig.baseRetryDelay),this.heartbeatTimer=setInterval(()=>this.checkNodeHealth(),6e4),this.registry.onEvent(t=>this.handleLocalAgentEvent(t)),this.running=true,M.info("Agent sync manager started");}async stop(){if(!this.running){M.warn("Agent sync manager is not running");return}M.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,M.info("Agent sync manager stopped");}async pullFromAllNodes(){let t=Array.from(this.remoteNodes.keys()),e=this.internalConfig.maxConcurrentSync;for(let s=0;s<t.length;s+=e){let i=t.slice(s,s+e).map(r=>this.pullFromNode(r).catch(a=>{M.error("Failed to pull from node",{nodeId:r,error:a.message});}));await Promise.all(i);}}async pullFromNode(t){let e=this.remoteNodes.get(t);if(!e)throw new Error(`Unknown remote node: ${t}`);e.status="syncing";let s=this.config.remoteNodes.find(i=>i.id===t);if(!s)throw new Error(`Remote node not found in config: ${t}`);let n=Date.now();try{let i=`http://${s.address}:${s.port}/sync/agents`,r=await Fetch.get(i,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);let a=r.data.agents||[];for(let c of a)c.sourceGatewayId=t,this.remoteAgents.set(c.id,{agent:c,cachedAt:n});return e.lastSyncAt=n,e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",e.retryCount=0,delete e.error,a}catch(i){e.status="error",e.error=i.message,e.info.status="offline";let r=this.calculateRetryDelay(e.retryCount);throw e.retryCount++,e.nextRetryAt=n+r,M.error("Failed to pull from node",{nodeId:t,error:i.message,retryCount:e.retryCount,nextRetryAt:e.nextRetryAt}),i}}calculateRetryDelay(t){let{baseRetryDelay:e,maxRetryCount:s}=this.internalConfig;return Math.min(e*2**t,e*2**s)}async pushEvent(t){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[s]of this.remoteNodes.entries())e.push(this.pushToNode(s,t));await Promise.allSettled(e);}async pushToNode(t,e){let s=this.config.remoteNodes.find(n=>n.id===t);if(!s){M.warn("Unknown remote node for push",{nodeId:t});return}try{let n=`http://${s.address}:${s.port}/sync/events`,i=await Fetch.post(n,e,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}`);M.debug("Pushed event to node",{nodeId:t,eventType:e.type});}catch(n){M.error("Failed to push to node",{nodeId:t,eventType:e.type,error:n.message});}}async handleSyncMessage(t){switch(t.type){case "agent_list_request":await this.handleAgentListRequest(t);break;case "agent_list_response":await this.handleAgentListResponse(t);break;case "agent_register":await this.handleAgentRegister(t);break;case "agent_deregister":await this.handleAgentDeregister(t);break;case "agent_heartbeat":await this.handleAgentHeartbeat(t);break;case "agent_status_change":await this.handleAgentStatusChange(t);break;default:M.warn("Unknown sync message type",{type:t.type});}}async handleAgentListRequest(t){let e=this.getLocalAgentsForSync(),s={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:t.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(t.sourceNodeId,s);}async handleAgentListResponse(t){for(let e of t.agents)this.remoteAgents.set(e.id,{agent:e,cachedAt:Date.now()});this.notifyAgentListChange(t.agents,"add");}async handleAgentRegister(t){let{agent:e}=t,s=this.remoteAgents.get(e.id);if(s){let n=this.resolveConflict(s.agent,e);this.remoteAgents.set(e.id,{agent:n,cachedAt:Date.now()});}else this.remoteAgents.set(e.id,{agent:e,cachedAt:Date.now()});this.notifyAgentListChange([e],"add");}async handleAgentDeregister(t){let{agentId:e}=t,s=this.remoteAgents.get(e);this.remoteAgents.delete(e),s&&this.notifyAgentListChange([s.agent],"remove");}async handleAgentHeartbeat(t){let{agentId:e,heartbeatAt:s,status:n}=t,i=this.remoteAgents.get(e);i&&(i.agent.updatedAt=s,i.agent.status=n,i.cachedAt=Date.now());}async handleAgentStatusChange(t){let{agentId:e,newStatus:s,changedAt:n}=t,i=this.remoteAgents.get(e);if(i){({...i.agent});i.agent.status=s,i.agent.updatedAt=n,i.cachedAt=Date.now(),M.debug("Remote agent status changed",{agentId:e,newStatus:s,sourceNodeId:t.sourceNodeId}),this.notifyAgentListChange([i.agent],"update");}}cleanupStaleAgents(){if(!this.running)return;let t=Date.now(),e=this.internalConfig.remoteAgentTtl,s=0;for(let[n,i]of this.remoteAgents.entries())t-i.cachedAt>e&&(this.remoteAgents.delete(n),s++);s>0&&M.debug("Cleaned up stale remote agents",{cleanedCount:s,remainingCount:this.remoteAgents.size});}async reconnectFailedNodes(){if(!this.running)return;let t=Date.now(),e=[];for(let[s,n]of this.remoteNodes.entries())n.status==="error"&&n.nextRetryAt>0&&t>=n.nextRetryAt&&e.push(s);if(e.length>0){M.debug("Retrying failed nodes",{nodeCount:e.length});for(let s of e)try{await this.pullFromNode(s);}catch{}}}async checkNodeHealth(){if(this.running)for(let[t,e]of this.remoteNodes.entries()){let s=this.config.remoteNodes.find(n=>n.id===t);if(s)try{let n=`http://${s.address}:${s.port}/status`,i=await Fetch.get(n,{timeout:5e3});i.ok?(e.info.status="online",e.retryCount=0,M.debug("Node health check passed",{nodeId:t})):(e.info.status="offline",M.warn("Node health check failed",{nodeId:t,status:i.status}));}catch(n){e.info.status="offline",M.warn("Node health check error",{nodeId:t,error:n.message});}}}async handleLocalAgentEvent(t){if(!this.config.pushEvents.includes(t.type))return;let e=this.agentToSyncInfo(t.agent),s=Date.now();switch(t.type){case "register":await this.pushEvent({type:"agent_register",sourceNodeId:this.localNodeId,timestamp:s,agent:e});break;case "deregister":await this.pushEvent({type:"agent_deregister",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id});break;case "heartbeat":await this.pushEvent({type:"agent_heartbeat",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id,heartbeatAt:t.agent.lastHeartbeat,status:t.agent.status});break;case "status_change":await this.pushEvent({type:"agent_status_change",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id,oldStatus:t.oldStatus??"healthy",newStatus:t.agent.status,changedAt:s});break}}agentToSyncInfo(t){return {id:t.id,name:t.name,sourceGatewayId:this.localNodeId,address:t.address,capabilities:t.capabilities,status:t.status,updatedAt:t.lastHeartbeat,metadata:t.metadata}}resolveConflict(t,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>t.updatedAt?e:e.updatedAt<t.updatedAt?t:e.id>t.id?e:t;case "local":return t;case "remote":return e;default:return e.updatedAt>t.updatedAt?e:e.updatedAt<t.updatedAt?t:e.id>t.id?e:t}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(t=>this.agentToSyncInfo(t))}notifyAgentListChange(t,e){for(let s of this.agentListChangeCallbacks)try{for(let n of t)s(t,e,n);}catch(n){M.error("Agent list change callback error",{error:String(n)});}}onAgentListChange(t){this.agentListChangeCallbacks.add(t);}offAgentListChange(t){this.agentListChangeCallbacks.delete(t);}getMergedAgentList(){let t=new Map;for(let e of this.getLocalAgentsForSync())t.set(e.id,e);for(let[e,s]of this.remoteAgents.entries())t.has(e)||t.set(e,s.agent);return Array.from(t.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values()).map(t=>t.agent)}getStats(){let t=this.registry.getAllAgents(),e=0,s=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:s++;let n=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(n||0)&&(n=i.lastSyncAt);return {localAgentCount:t.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:t.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:s,lastSyncAt:n}}isRunning(){return this.running}addRemoteNode(t){this.remoteNodes.set(t.id,{info:{id:t.id,name:t.id,address:t.address,port:t.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced",retryCount:0,nextRetryAt:0}),M.debug("Remote node added",{nodeId:t.id,address:t.address});}removeRemoteNode(t){this.remoteNodes.delete(t);for(let[e,s]of this.remoteAgents.entries())s.agent.sourceGatewayId===t&&this.remoteAgents.delete(e);M.debug("Remote node removed",{nodeId:t});}};var U=Log.create({service:"gateway:ws-agent-sync"}),kt=class{constructor(t){a(this,"wsServer");a(this,"syncManager");a(this,"gatewayId");a(this,"subscribers",new Map);a(this,"getClientWs");this.wsServer=t.wsServer,this.syncManager=t.syncManager,this.getClientWs=t.getClientWs,this.gatewayId=t.wsServer.getGatewayId();}async handleAgentListRequest(t,e){let s=this.getClientWs(t);if(!s){U.warn("Client not found for agent list request",{clientId:t,requestId:e});return}let n=this.syncManager.getMergedAgentList();this.sendMessage(s,{type:"agent_list_response",requestId:e,agents:n});}async handleAgentSubscribe(t,e){let s=this.getClientWs(t);if(!s){U.warn("Client not found for agent subscribe",{clientId:t});return}if(e){this.subscribers.delete(t),this.subscribers.set(t,{clientId:t,ws:s,subscribedAt:Date.now()});let n=this.syncManager.getMergedAgentList();this.sendMessage(s,{type:"agent_list_response",agents:n});}else this.subscribers.delete(t);}broadcastAgentUpdate(t,e){if(this.subscribers.size===0)return;let s={type:"agent_update",action:t,agent:e};for(let[n,i]of this.subscribers.entries())try{i.ws.readyState===i.ws.OPEN&&this.sendMessage(i.ws,s);}catch(r){U.error("Failed to send agent update to client",{clientId:n,error:r.message});}}broadcastAgentList(){if(this.subscribers.size===0)return;let t=this.syncManager.getMergedAgentList();for(let[e,s]of this.subscribers.entries())try{s.ws.readyState===s.ws.OPEN&&this.sendMessage(s.ws,{type:"agent_list_response",requestId:`broadcast_${Date.now()}`,agents:t});}catch(n){U.error("Failed to send agent list to client",{clientId:e,error:n.message});}}cleanupClientSubscription(t){this.subscribers.delete(t);}getSubscriberCount(){return this.subscribers.size}getSubscribers(){return Array.from(this.subscribers.keys())}sendMessage(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e));}async handleAgentRegister(t,e){if(!e.agentId){U.warn("Agent register payload missing agentId",{clientId:t});return}if(!this.getClientWs(t)){U.warn("Client not found for agent register",{clientId:t});return}let n={id:e.agentId,name:e.name??e.agentId,sourceGatewayId:this.gatewayId,address:e.address??"",capabilities:e.capabilities??[],status:"healthy",updatedAt:Date.now(),metadata:e.metadata};try{let i=this.syncManager.registry;if(i.agents.has(n.id)){await i.heartbeat(n.id,n.metadata),U.debug("Agent heartbeat from client",{clientId:t,agentId:n.id});return}let r={...n.metadata,sourceGatewayId:this.gatewayId};await i.register({id:n.id,name:n.name,address:n.address,capabilities:n.capabilities,metadata:r}),U.debug("Agent registered from client",{clientId:t,agentId:n.id,name:n.name}),this.broadcastAgentUpdate("add",n);}catch(i){U.warn("Failed to register agent from client",{clientId:t,agentId:e.agentId,error:String(i)});}}async handleAgentDeregister(t,e){if(!e.agentId){U.warn("Agent deregister payload missing agentId",{clientId:t});return}if(!this.getClientWs(t)){U.warn("Client not found for agent deregister",{clientId:t});return}try{await this.syncManager.registry.deregister(e.agentId),U.debug("Agent deregistered from client",{clientId:t,agentId:e.agentId});let n={id:e.agentId,name:"unknown",sourceGatewayId:this.gatewayId,address:"",capabilities:[],status:"offline",updatedAt:Date.now()};this.broadcastAgentUpdate("remove",n);}catch(n){U.warn("Failed to deregister agent from client",{clientId:t,agentId:e.agentId,error:String(n)});}}async cleanupClient(t){this.subscribers.delete(t);let e=this.syncManager.registry.getAllAgents().filter(s=>s.metadata?.sourceGatewayId===this.gatewayId);for(let s of e)try{await this.syncManager.registry.deregister(s.id);let n={id:s.id,name:s.name,sourceGatewayId:this.gatewayId,address:s.address,capabilities:s.capabilities,status:"offline",updatedAt:Date.now()};this.broadcastAgentUpdate("remove",n);}catch{}}};var de=class de{constructor(t){a(this,"log",Log.create({service:"gateway:server"}));a(this,"config");a(this,"router");a(this,"sessionManager");a(this,"pluginLoader");a(this,"messageStore");a(this,"contactStore",null);a(this,"wsServer",null);a(this,"agentRegistry");a(this,"agentSyncManager",null);a(this,"wsAgentSync",null);a(this,"running",false);a(this,"connections",0);a(this,"gatewayAgent",null);a(this,"bindingLocks",new Map);this.log.debug("GatewayServer.constructor: starting"),this.config=t,this.log.debug("GatewayServer.constructor: creating MessageRouter");let e=ue()?X().hookRegistry:void 0;this.router=new wt(e),this.log.debug("GatewayServer.constructor: creating GatewaySessionManager");let s=v();this.sessionManager=new Ee({storagePath:`${s.Path.data}/gateway/sessions`,enablePersistence:true}),this.pluginLoader=new Re({healthCheckInterval:6e4});let n=ue();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:n}),this.messageStore=new ke({storagePath:`${s.Path.data}/gateway/messages`}),this.agentRegistry=new qe({dataDir:`${s.Path.data}/gateway/net`});let i={getSession:r=>{let a=this.sessionManager.get(r);return a?{backendSessionId:a.backendSessionId}:void 0},unbindBackendSession:r=>this.sessionManager.unbindBackendSession(r)};this.pluginLoader.setMessageHandler({onMessage:r=>this.onMessage(r),onEvent:r=>this.onEvent(r),session:i}),this.log.debug("GatewayServer.constructor: completed");}async loadChannelPlugins(){try{let{config:t}=await T(),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=ts[s];if(!i){this.log.warn("no plugin class found for platform",{platform:s});continue}let r=`${s}-main`,a=new i(r),c={enabled:!0,platform:n,session:{autoCreate:!0,resetPolicy:"onNewConversation"},routing:{broadcast:!0,dispatchToSubAgent:!0}};try{await this.pluginLoader.register(a,c),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}),await this.sessionManager.initialize(),this.log.debug("GatewayServer.start: sessionManager initialized"),await this.agentRegistry.load(),this.log.debug("GatewayServer.start: agentRegistry initialized");let e=`${v().Path.data}/gateway`,s=new re({baseDir:e});this.contactStore=new Te(s,{cacheSize:1e3}),this.contactStore.initialize&&await this.contactStore.initialize(),this.log.debug("GatewayServer.start: contactStore initialized"),this.wsServer=new ae({port:this.config.port,hostname:this.config.hostname,path:String(this.config.path??"/")}),await this.wsServer.start(),this.log.debug("GatewayServer.start: wsServer started"),await this.loadChannelPlugins(),this.pluginLoader.startAll().catch(g=>{this.log.error("plugin startup error",{error:String(g)});}),this.log.debug("GatewayServer.start: plugins startup initiated"),this.pluginLoader.startHealthCheckTimer();let{config:n}=await T(),i=n.defaults;this.wsServer.setChannelResolveDeps({sessionManager:{get:g=>this.sessionManager.get(g),getOrCreate:(g,p)=>this.sessionManager.getOrCreate(g,p),bindBackendSession:(g,p)=>this.sessionManager.bindBackendSession(g,p),findByBackendSessionId:g=>this.sessionManager.findByBackendSessionId(g),getAll:()=>this.sessionManager.getAllSessions()},pluginLoader:{getPlugin:g=>this.pluginLoader.getPlugin(g),getAllPlugins:()=>this.pluginLoader.getAllPlugins(),isRunning:g=>this.pluginLoader.isRunning(g)},defaultChannel:i?.channel,fallbackChannels:i?.fallbackChannels,contactStore:this.contactStore?{findByPlatformId:(g,p)=>this.contactStore.findByPlatformId(g,p),findByUid:g=>this.contactStore.findByUid(g),listByPlatform:(g,p,h)=>this.contactStore.listByPlatform(g,p,h),count:g=>this.contactStore.count(g)}:void 0}),this.wsServer.setPluginLoader((g,p,h)=>this.sendToChannel(g,p,h)),this.wsServer.setRouter(this.router),this.router.setSessionManager({get:g=>this.sessionManager.get(g),bindBackendSession:(g,p)=>this.sessionManager.bindBackendSession(g,p)}),this.pluginLoader.setMessageHandler({onMessage:g=>this.onMessage(g),onEvent:g=>this.onEvent(g),session:{getSession:g=>{let p=this.sessionManager.get(g);return p?{backendSessionId:p.backendSessionId}:void 0},unbindBackendSession:g=>this.sessionManager.unbindBackendSession(g)}}),this.agentSyncManager=new Ke({registry:this.agentRegistry,localNodeId:"gateway",localNodeName:"gateway"}),this.wsAgentSync=new kt({wsServer:this.wsServer,syncManager:this.agentSyncManager,getClientWs:g=>this.wsServer.getClientWs(g)}),this.wsServer.setAgentSync(this.wsAgentSync),this.wsServer.setAgentRegistry(this.agentRegistry),this.log.debug("GatewayServer.start: agent sync initialized"),this.log.debug("GatewayServer.start: registering gateway status provider"),hs(async()=>{let g=this.sessionManager.getAllSessions(),p=this.router.getStats?.()??{subscribers:0},h=this.agentRegistry.getStats?.()??{totalAgents:0,healthyAgents:0,unhealthyAgents:0},S=this.wsAgentSync?.getSubscriberCount?.()??0,C=this.wsServer?.getStartTime?.()??0,k=this.pluginLoader.getAllPlugins().filter(F=>this.pluginLoader.isRunning(F.id)).map(F=>({id:F.id,platform:F.platform,name:F.name,version:F.version}));return {status:this.running?"running":"stopped",connections:this.wsServer?.getConnectionCount?.()??0,sessions:g.length,messageSubscriptions:p.subscribers??0,agentSubscriptions:S,uptime:this.running&&C?Date.now()-C:0,version:"1.0.0",agents:{total:h.totalAgents,healthy:h.healthyAgents,unhealthy:h.unhealthyAgents},channels:k}});let r=await this.messageStore.loadFromDisk();this.log.debug("loaded messages from disk",{count:r});let a=Date.now(),c=6e4,d=()=>{let g=Date.now()-a,p=this.pluginLoader.getAllPlugins(),h=p.filter(S=>this.pluginLoader.isRunning(S.id));h.length===p.length&&p.length>0?(this.log.debug("all plugins ready, proceeding with message retry"),this.retryPendingMessages().catch(S=>{this.log.error("failed to retry pending messages",{error:String(S)});})):g>c?(this.log.warn("plugin startup timeout, proceeding with message retry anyway",{elapsed:g}),this.retryPendingMessages().catch(S=>{this.log.error("failed to retry pending messages",{error:String(S)});})):(this.log.debug("waiting for plugins to be ready",{elapsed:g,ready:h.length,total:p.length}),setTimeout(d,100));};d(),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}if(this.log.info("stopping gateway server"),this.wsServer&&(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.gatewayAgent){try{await this.gatewayAgent.stop();}catch(t){this.log.warn("Failed to stop gatewayAgent during server shutdown",{error:String(t)});}this.gatewayAgent=null;}this.running=false,this.log.info("gateway server stopped");}getStatus(){let t=this.agentRegistry.getStats();return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections,agents:{total:t.totalAgents,healthy:t.healthyAgents,unhealthy:t.unhealthyAgents}}}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>de.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=t.metadata.channel,n=this.buildChannelContext(t,s),i={...t,metadata:{...t.metadata,system:n}},r=true;try{let a=await this.router.route(i);if(r=a.success,!a.dispatched&&t.type==="input"){let{config:c}=await T(),d=c.agentProcessing??{mode:"localAgent",localAgentPriority:1,subAgentPriority:2,timeout:3e5,retryOnFailure:!0};this.log.debug("no subscribers, dispatching to agent",{id:t.id,mode:d.mode}),this.dispatchToAgent(i,d).catch(g=>{this.log.error("agent dispatch failed",{id:t.id,error:String(g)}),r=!1;});}}catch(a){r=false,this.log.error("route failed",{messageId:t.id,error:String(a)});}t.type==="input"&&!r&&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 a=await this.contactStore.getOrCreate(e,r,{username:t.metadata.channel?.username,displayName:t.metadata.channel?.firstName});this.log.debug("contact saved",{uid:a.uid});}catch(a){this.log.warn("failed to save contact",{platform:e,stableId:r,error:String(a)});}}async dispatchToAgent(t,e){if(!ue()){this.log.debug("no agent adapter, message remains pending",{id:t.id});return}let s=X(),n=t.metadata.channel,r=this.sessionManager.get(t.sessionId)?.backendSessionId||void 0,a=t.metadata.system;switch(e.mode){case "localAgent":{this.dispatchToGatewayAgent(t,n,a,s,r);break}case "subAgent":{this.dispatchToSubAgent(t,n,a,s,r);break}default:{this.dispatchToGatewayAgent(t,n,a,s,r);break}}}getGatewayAgent(){if(!this.gatewayAgent){if(!X().sdk)return null;this.gatewayAgent=ms({});}return this.gatewayAgent}dispatchToGatewayAgent(t,e,s,n,i){let r=this.getGatewayAgent();if(!r){this.log.debug("no GatewayAgent available, message remains pending",{id:t.id});return}this.log.debug("dispatching message to GatewayAgent",{id:t.id,sessionId:t.sessionId,backendSessionId:i}),this.triggerHook(HookEvent.GatewayMessageProcess,{id:t.id,sessionId:t.sessionId,backendSessionId:i,processorId:"gatewayAgent",processType:"gatewayAgent",agent:t?.metadata?.agent??"gateway",timestamp:Date.now()});let a=t.sessionId,d=(this.bindingLocks.get(a)??Promise.resolve()).catch(()=>{}).then(()=>this.resolveAndBindBackendSession(t,e,n,i)).then(g=>{g!==void 0&&this.executeGatewayAgent(t,e,r,g,s);}).catch(g=>{this.log.error("dispatchToGatewayAgent: binding pipeline failed",{id:t.id,sessionId:t.sessionId,error:String(g)}),this.handleAgentError(t,e,g,"gatewayAgent",i);}).finally(()=>{this.bindingLocks.get(a)===d&&this.bindingLocks.delete(a);});this.bindingLocks.set(a,d);}async resolveAndBindBackendSession(t,e,s,n){let r=`Gateway-${e?.platform||"unknown"}`;if(n){try{if((await s.sdk.session.get({sessionId:n})).data)return n}catch(p){this.log.warn("dispatchToGatewayAgent: session.get failed, will re-create",{sessionId:n,error:String(p)});}let g=(await s.sdk.session.create({title:r})).data?.id;if(g)return await this.sessionManager.bindBackendSession(t.sessionId,g),this.log.debug("backend session re-bound (previous session expired)",{gatewaySessionId:t.sessionId,backendSessionId:g}),g;this.log.warn("dispatchToGatewayAgent: session.create returned no id (re-bind)",{messageId:t.id});return}let c=(await s.sdk.session.create({title:r})).data?.id;if(c)return await this.sessionManager.bindBackendSession(t.sessionId,c),this.log.debug("backend session bound (first message)",{gatewaySessionId:t.sessionId,backendSessionId:c}),c;this.log.warn("dispatchToGatewayAgent: session.create returned no id (first bind)",{messageId:t.id});}buildChannelContext(t,e){let s=e?.platform||"unknown",n=e?.userId||e?.chatId||"unknown user",i=`${s}:${n}`,r=e?.chatType||"unknown";return `## External Channel Message
32
+ ${g.content}`}),this.log.debug("weixin text file inlined",{fileName:c,mime:a,length:d.length});}catch(d){this.log.warn("weixin text file read failed, fallback to file part",{fileName:c,error:String(d)}),s.push({type:"file",data:r,mime:a});}else s.push({type:"file",data:r,mime:a});this.log.debug("weixin attachment resolved",{downloadDir:i,source:e.attachmentPath});}return e.text&&s.push({type:"text",text:e.text}),s}async resolveAttachmentToPath(e,s){if(typeof e=="string")return /^https?:\/\//i.test(e)?this.downloadUrlToLocal(e,s):e.startsWith("file://")?fileURLToPath(e):e;if(e instanceof URL)return /^https?:$/i.test(e.protocol)?this.downloadUrlToLocal(e.toString(),s):this.resolveAttachmentToPath(e.toString(),s);let n=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");await Filesystem.mkdir(i,{recursive:true});let r=Filesystem.join(i,`${s}_${Date.now()}.bin`);return await Filesystem.write(r,Buffer.from(e)),r}async downloadUrlToLocal(e,s){let n=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");await Filesystem.mkdir(i,{recursive:true});let r=new URL(e).pathname.split("/").pop()||`weixin_${Date.now()}`,a=Filesystem.join(i,`${s}_${r}`);this.log.debug("weixin download remote attachment",{url:e,dest:a});let c=await Fetch.get(e,{responseType:"arrayBuffer",timeout:12e4});if(!c.ok)throw new Error(`Failed to download attachment from ${e}: HTTP ${c.status}`);return await Filesystem.write(a,Buffer.from(c.data)),this.log.debug("weixin remote attachment downloaded",{url:e,dest:a,bytes:c.data.byteLength}),a}async sendTyping(e){if(!this.account)return;let s=Mt(e);if(!s){this.log.debug("sendTyping skipped: no context token",{userId:e});return}try{let n=await $s(this.account.baseUrl,this.account.token,e,s);n.typing_ticket&&await Ws(this.account.baseUrl,this.account.token,{ilink_user_id:e,typing_ticket:n.typing_ticket,status:Hs.TYPING});}catch(n){this.log.debug("sendTyping failed",{userId:e,error:String(n)});}}buildSessionId(e,s,n){let i=n??s;return `${this.platform}_${e}_${s}_${i}`}};var He=class extends P{constructor(e="webchat-main"){super();a(this,"id");a(this,"platform","webchat");a(this,"name","WebChat");a(this,"webChatConfig",null);a(this,"connections",new Map);a(this,"heartbeatInterval",null);a(this,"abortController",null);a(this,"processedMessageIds",new Set);a(this,"sentMessages",new Map);a(this,"wsServer",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","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 doStop(){this.abortController?.abort(),this.abortController=null,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.wsServer&&(await this.wsServer.stop(),this.wsServer=null);for(let e of this.connections.values())e.ws.close();this.connections.clear(),this.processedMessageIds.clear(),this.sentMessages.clear(),this.webChatConfig=null,this.log.info("WebChat plugin stopped");}async doHealthCheck(){return !(this._status!=="running"||this.abortController?.signal.aborted||!this.wsServer)}async send(e){let s=e.sessionId,n=e.metadata.channel.userId;if(!n)throw y(this.id,"MESSAGE_SEND_FAILED","User ID is required");let i=this.findConnectionByUser(n);if(!i)throw y(this.id,"MESSAGE_SEND_FAILED","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(),this.sentMessages.set(e.id,{sessionId:s,messageId:e.id,timestamp: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,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:1e5,maxMediaCount:20}}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.debug("WebSocket connected",{connId:n,userId:s});}getConnectionCount(){return this.connections.size}getWsServerConnectionCount(){return this.wsServer?.getConnectionCount()??0}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 ae(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 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.debug("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||this.processedMessageIds.has(s.messageId??""))return;if(s.messageId&&(this.processedMessageIds.add(s.messageId),this.processedMessageIds.size>1e4)){let r=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(r.slice(-5e3));}let n=s.content.find(r=>r.type==="text");if(n?.text.trim().startsWith("/")){let r=this.buildSessionId(this.id,s.sessionId,e.userId),a=await this.processCommand({text:n.text,sessionId:r,chatId:s.sessionId,channelInfo:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},messageId:s.messageId});if(a.handled){if(a.reply){let c=A(s.sessionId,"output",[{type:"text",text:a.reply}],{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},context:{conversationId:s.sessionId},...s.metadata});await this.send(c);}else a.gatewayMessage&&await this.handleMessage(a.gatewayMessage);return}}let i=A(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(i);}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.debug("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)}`}};var ze=class extends P{constructor(e="signal-main"){super();a(this,"id");a(this,"platform","signal");a(this,"name","Signal Bot");a(this,"botConfig",null);a(this,"abortController",null);a(this,"lastTimestamp",0);a(this,"pollingIntervalMs",5e3);a(this,"processedMessageIds",new Set);a(this,"sentMessages",new Map);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.phoneNumber)throw y(this.id,"CONFIG_MISSING_REQUIRED","Phone number is required");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.polling&&(this.pollingIntervalMs=this.botConfig.polling.interval??5e3),this.abortController=new AbortController;let e=await this.getAccountInfo();this.log.info("Signal bot connected",{number:this.botConfig.phoneNumber,address:e.address}),this.botConfig.polling?.enabled!==false&&this.startPolling();}async doStop(){this.abortController?.abort(),this.abortController=null,this.processedMessageIds.clear(),this.sentMessages.clear(),this.lastTimestamp=0,this.botConfig=null,this.retryState.attempts=0,this.log.info("Signal plugin stopped");}async doHealthCheck(){if(this._status!=="running"||this.abortController?.signal.aborted)return false;try{return await this.getAccountInfo(),!0}catch{return false}}async send(e){let s=e.metadata.channel.userId;if(!s)throw y(this.id,"MESSAGE_SEND_FAILED","Recipient is required");let n=this.extractText(e),i=await this.sendMessage(s,n);return this.sentMessages.set(e.id,{timestamp:i.timestamp}),i.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,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",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){let n=`${s.envelope.sourceNumber}_${s.envelope.timestamp}`;if(!this.processedMessageIds.has(n)){if(this.processedMessageIds.add(n),this.processedMessageIds.size>1e4){let i=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(i.slice(-5e3));}this.lastTimestamp=s.envelope.timestamp,s.envelope.dataMessage&&await this.handleSignalMessage(s);}}}async handleSignalMessage(e){this.updateActivity();let s=e.envelope.dataMessage?.message;if(s?.trim().startsWith("/")){let i=this.buildSessionId(this.id,e.envelope.sourceNumber),r=await this.processCommand({text:s,sessionId:i,chatId:e.envelope.sourceNumber,channelInfo:{platform:"signal",channelId:this.id,userId:e.envelope.sourceNumber,chatId:e.envelope.sourceNumber,timestamp:e.envelope.dataMessage?.timestamp},messageId:e.envelope.dataMessage?.timestamp?.toString()});if(r.handled){r.reply?await this.sendMessage(e.envelope.sourceNumber,r.reply):r.gatewayMessage&&await this.handleMessage(r.gatewayMessage);return}}let n=await this.toGatewayMessage(e);await this.handleMessage(n);}async toGatewayMessage(e){let s=this.buildSessionId(this.id,e.envelope.sourceNumber),n=e.envelope.dataMessage;return A(s,"input",await 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}})}async parseContent(e){let s=[],n=v()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");if(!e)return s;if(e.message&&s.push({type:"text",text:e.message}),e.attachments)for(let r of e.attachments)try{let a=r.contentType.split("/").pop()||"bin",c=Filesystem.join(i,`signal_${r.id}.${a}`);s.push({type:r.contentType.startsWith("image/")?"image":"file",image:r.id,data:r.id,mime:r.contentType});}catch(a){this.log.warn("failed to handle attachment",{attachmentId:r.id,error:String(a)}),s.push({type:r.contentType.startsWith("image/")?"image":"file",image:r.id,data:r.id,mime:r.contentType});}return s}buildSessionId(e,s,n){let i=["signal",e,s];return n&&i.push(n),i.join("_")}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){let i=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let c=await TruncateContent.truncate(s,{maxChars:i,label:"signal message"});r=c.content,this.log.debug("sendMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:c.truncated?c.outputPath:void 0});}return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:r})}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 a;if(e==="GET"?a=await Fetch.get(i,{headers:r}):e==="POST"?a=await Fetch.post(i,n,{headers:r}):e==="DELETE"?a=await Fetch.del(i,{headers:r}):a=await Fetch.request(i,{method:e,body:n,headers:r}),!a.ok)throw y(this.id,"MESSAGE_SEND_FAILED",`Signal API error: ${JSON.stringify(a.data)}`);return a.data}};var je=class extends P{constructor(e="nostr-main"){super();a(this,"id");a(this,"platform","nostr");a(this,"name","Nostr Bot");a(this,"botConfig",null);a(this,"relayConnections",new Map);a(this,"subscriptions",new Map);a(this,"abortController",null);a(this,"processedEventIds",new Set);a(this,"sentMessages",new Map);a(this,"relayReconnectAttempts",new Map);a(this,"maxReconnectAttempts",5);a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});this.id=e,this.initLog();}async doStart(){if(!this.config)throw y(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.relays||this.botConfig.relays.length===0)throw y(this.id,"CONFIG_MISSING_REQUIRED","At least one relay is required");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.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.processedEventIds.clear(),this.sentMessages.clear(),this.relayReconnectAttempts.clear(),this.botConfig=null,this.log.info("Nostr plugin stopped");}async doHealthCheck(){if(this._status!=="running"||this.abortController?.signal.aborted)return false;for(let e of this.relayConnections.values())if(e.readyState===WebSocket.OPEN)return true;return false}async send(e){if(!this.botConfig?.privateKey)throw y(this.id,"CONFIG_MISSING_REQUIRED","Private key is required for sending messages");let s=this.extractText(e),n=e.metadata.context?.replyTo,i=await this.createEvent(s,n);return await this.publishEvent(i),this.sentMessages.set(e.id,{eventId:i.id,timestamp:Date.now()}),i.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,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",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||this.processedEventIds.has(e.id))return;if(this.processedEventIds.add(e.id),this.processedEventIds.size>1e4){let n=Array.from(this.processedEventIds);this.processedEventIds=new Set(n.slice(-5e3));}if(e.pubkey===this.botConfig?.publicKey)return;if(e.content?.trim().startsWith("/")){let n=this.buildSessionId(this.id,e.pubkey),i=await this.processCommand({text:e.content,sessionId:n,chatId:e.pubkey,channelInfo:{platform:"nostr",channelId:this.id,userId:e.pubkey,chatId:e.pubkey,eventId:e.id,createdAt:e.created_at},messageId:e.id});if(i.handled){i.reply?await this.createEvent(i.reply):i.gatewayMessage&&await this.handleMessage(i.gatewayMessage);return}}let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.buildSessionId(this.id,e.pubkey);return A(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){let i=["nostr",e,s];return n&&i.push(n),i.join("_")}subscribeToRelay(e,s,n){let i=["REQ",s,n];e.send(JSON.stringify(i));}unsubscribeFromRelay(e,s){let n=["CLOSE",s];e.send(JSON.stringify(n));}async createEvent(e,s){let n=[];s&&n.push(["e",s,"","reply"]);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(c=>c.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw y(this.id,"CONFIG_MISSING_REQUIRED","Private key is required");return this.log.warn("Event signing not implemented, using placeholder signature"),"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 ts=class extends P{constructor(e){super();a(this,"id");a(this,"platform");a(this,"name");a(this,"version");a(this,"options");this.id=e.id,this.platform=e.platform||"custom",this.name=e.name,this.version=e.version||"1.0.0",this.options=e,this.initLog();}async doStart(){this.options.setup?.initialize&&await this.options.setup.initialize(),this.log.info("Channel plugin started",{id:this.id,platform:this.platform});}async doStop(){this.options.setup?.destroy&&await this.options.setup.destroy(),this.log.info("Channel plugin stopped",{id:this.id});}async send(e){let 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 Yr(o){return new ts(o)}var ss={telegram:De,discord:Ne,slack:Le,feishu:Ge,wechat:Ue,weixin:We,webchat:He,signal:ze,nostr:je};function ku(){return Object.keys(ss)}var I=Log.create({service:"gateway:net:registry"});function fn(o){if(!o)return {url:"",protocol:"unsupported"};let t=o.trim();return t.startsWith("ws://")||t.startsWith("wss://")||t.startsWith("acp-ws://")?(t.startsWith("acp-ws://")&&(t=t.replace("acp-ws://","ws://")),t.includes("/acp")||(t=t.replace(/\/$/,"")+"/acp"),{url:t,protocol:"websocket"}):t.startsWith("http://")||t.startsWith("https://")?(t.includes("/acp")||(t=t.replace(/\/$/,"")+"/acp"),{url:t,protocol:"http"}):{url:t,protocol:"unsupported"}}async function ea(o,t){try{let e=await Fetch.post(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}},{timeout:t});if(!e.ok)return !1;let s=e.data;return !(!s||s.error)}catch{return false}}async function ta(o,t){return new Promise(e=>{let s=null,n=false,i=setTimeout(()=>{n||(n=true,s?.close(),e(false));},t);try{s=new WebSocket(o),s.onopen=()=>{let r={jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}};s.send(JSON.stringify(r));},s.onmessage=r=>{try{let a=JSON.parse(r.data);a.id===1&&!a.error?n||(n=!0,clearTimeout(i),s?.close(),e(!0)):a.error&&(n||(n=!0,clearTimeout(i),s?.close(),e(!1)));}catch{}},s.onerror=()=>{n||(n=!0,clearTimeout(i),e(!1));},s.onclose=()=>{n||(n=!0,clearTimeout(i),e(!1));};}catch{n||(n=true,clearTimeout(i),e(false));}})}async function sa(o,t){try{let e=await Fetch.post(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}},{timeout:t});if(!e.ok||!e.data?.result?.agentCapabilities)return [];let s=e.data.result.agentCapabilities,n=[];return s.mcpCapabilities&&(s.mcpCapabilities.http&&n.push("mcp:http"),s.mcpCapabilities.sse&&n.push("mcp:sse")),s.promptCapabilities&&(s.promptCapabilities.image&&n.push("prompt:image"),s.promptCapabilities.embeddedContext&&n.push("prompt:context")),s.sessionCapabilities&&(s.sessionCapabilities.fork&&n.push("session:fork"),s.sessionCapabilities.resume&&n.push("session:resume")),n}catch{return []}}var qe=class{constructor(t={}){a(this,"config");a(this,"agents",new Map);a(this,"heartbeatTimer",null);a(this,"roundRobinIndex",0);a(this,"store",null);a(this,"eventCallbacks",new Set);let{dataDir:e,...s}=t;this.config={...St,...s},e&&(this.store=new _e({dataDir:e}));}async load(){if(this.store)try{let t=await this.store.loadAll(),e=Date.now();for(let s of t)e-s.lastHeartbeat>this.config.heartbeatTimeout&&(s.status="unhealthy"),this.agents.set(s.id,s);I.info("Agent registry loaded from storage",{count:t.length});}catch(t){I.error("Failed to load agent registry from storage",{error:String(t)});}}async register(t){if(this.agents.has(t.id))throw new Error(`Agent with ID "${t.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),s={...t,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(t.id,s);let{url:n,protocol:i}=fn(t.address);if(i!=="http"&&i!=="websocket")throw new Error(`Unsupported protocol: ${t.address}. Only http/https/ws/wss are supported`);let r=await sa(n,3e4).catch(()=>[]);r.length>0&&(s.capabilities=r),this.store&&await this.store.save(s),I.info("Agent registered",{agentId:t.id,name:t.name,capabilities:s.capabilities,address:t.address,totalAgents:this.agents.size}),this.emitEvent({type:"register",agent:s});}async deregister(t){let e=this.agents.get(t);if(!e){I.warn("Attempted to deregister unknown agent",{agentId:t});return}this.agents.delete(t),this.store&&await this.store.delete(t),I.info("Agent deregistered",{agentId:t,name:e.name,totalAgents:this.agents.size}),this.emitEvent({type:"deregister",agent:e});}async heartbeat(t,e){let s=this.agents.get(t);if(!s)throw I.warn("Heartbeat received from unknown agent",{agentId:t}),new Error(`Agent "${t}" is not registered`);let n=s.status;s.lastHeartbeat=Date.now(),s.status="healthy",e&&(s.metadata={...s.metadata,...e});let i=6e4,r=Date.now();this.store&&(n!=="healthy"||r-s.lastHeartbeat>=i)&&this.store.save(s).catch(a=>{I.error("Failed to save agent to store",{agentId:t,error:String(a)});}),n!=="healthy"&&this.emitEvent({type:"status_change",agent:s,oldStatus:n});}setStatus(t,e){let s=this.agents.get(t);if(!s){I.warn("Attempted to set status for unknown agent",{agentId:t});return}let n=s.status;n!==e&&(s.status=e,this.store&&this.store.save(s).catch(i=>{I.error("Failed to save agent status to store",{agentId:t,error:String(i)});}),this.emitEvent({type:"status_change",agent:s,oldStatus:n}));}getAgent(t){return this.agents.get(t)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(t=>t.status==="healthy")}selectAgent(t){let{strategy:e,capabilities:s,healthyOnly:n=true}=t,i=n?this.getHealthyAgents():this.getAllAgents();if(s&&s.length>0&&(i=i.filter(a=>s.every(c=>a.capabilities.includes(c)))),i.length===0){I.warn("No agents available for selection",{strategy:e,capabilities:s,healthyOnly:n,totalAgents:this.agents.size});return}let r;switch(e){case "random":r=this.selectRandom(i);break;case "round-robin":r=this.selectRoundRobin(i);break;case "least-connections":r=this.selectLeastConnections(i);break;default:r=this.selectRandom(i);}return I.debug("Agent selected",{agentId:r.id,strategy:e,connectionCount:r.connectionCount}),r}incrementConnection(t){let e=this.agents.get(t);e&&(e.connectionCount++,I.debug("Agent connection incremented",{agentId:t,connectionCount:e.connectionCount}));}decrementConnection(t){let e=this.agents.get(t);e&&e.connectionCount>0&&(e.connectionCount--,I.debug("Agent connection decremented",{agentId:t,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){I.warn("Heartbeat check is already running");return}I.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,I.info("Heartbeat check stopped"));}async checkHeartbeats(){let t=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:s}=this.config,n=[],i=0,r=[];for(let[a,c]of this.agents.entries()){let d=t-c.lastHeartbeat;if(d>s){n.push(a);continue}(d>e||c.status==="unhealthy")&&r.push((async()=>{let{url:g,protocol:p}=fn(c.address),h=this.config.heartbeatTimeout/2;I.debug("Checking agent connectivity",{agentId:a,url:g,protocol:p});let S=false;try{p==="http"?S=await ea(g,h):S=await ta(g,h);}catch(_){I.debug("Agent connectivity check error",{agentId:a,error:String(_)}),S=false;}let C=c.status;S?(c.lastHeartbeat=t,c.status!=="healthy"&&(c.status="healthy",I.debug("Agent recovered, marked as healthy",{agentId:a,name:c.name,previousStatus:C}),this.store&&this.store.save(c).catch(_=>{I.error("Failed to save agent to store",{agentId:a,error:String(_)});}),this.emitEvent({type:"status_change",agent:c,oldStatus:C}))):c.status==="healthy"&&(c.status="unhealthy",i++,I.warn("Agent marked as unhealthy due to connectivity check failed",{agentId:a,name:c.name,url:g,protocol:p,lastHeartbeat:c.lastHeartbeat,timeSinceLastHeartbeat:d,timeout:e}),this.store&&this.store.save(c).catch(_=>{I.error("Failed to save agent to store",{agentId:a,error:String(_)});}),this.emitEvent({type:"status_change",agent:c,oldStatus:C}));})());}await Promise.all(r);for(let a of n){let c=this.agents.get(a);c&&(I.debug("Auto-deregistering agent due to timeout",{agentId:a,name:c.name,lastHeartbeat:c.lastHeartbeat,timeout:s}),this.agents.delete(a),this.store&&await this.store.delete(a),this.emitEvent({type:"deregister",agent:c}));}(i>0||n.length>0)&&I.debug("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:n.length,totalAgents:this.agents.size});}onEvent(t){this.eventCallbacks.add(t);}offEvent(t){this.eventCallbacks.delete(t);}emitEvent(t){for(let e of this.eventCallbacks)try{e(t);}catch(s){I.error("Agent event callback error",{eventType:t.type,agentId:t.agent.id,error:String(s)});}}selectRandom(t){let e=Math.floor(Math.random()*t.length);return t[e]}selectRoundRobin(t){if(t.length===0)throw new Error("No candidates available for round-robin selection");this.roundRobinIndex>=t.length&&(this.roundRobinIndex=0);let e=t[this.roundRobinIndex];return this.roundRobinIndex=(this.roundRobinIndex+1)%t.length,e}selectLeastConnections(t){return t.reduce((e,s)=>s.connectionCount<e.connectionCount?s:e)}getStats(){let t=this.getAllAgents();return {totalAgents:t.length,healthyAgents:t.filter(e=>e.status==="healthy").length,unhealthyAgents:t.filter(e=>e.status==="unhealthy").length,offlineAgents:t.filter(e=>e.status==="offline").length,totalConnections:t.reduce((e,s)=>e+s.connectionCount,0)}}setAgentStatus(t,e){this.setStatus(t,e);}setLastHeartbeat(t,e){let s=this.agents.get(t);s&&(s.lastHeartbeat=e);}};var M=Log.create({service:"gateway:net:sync-manager"}),Ke=class{constructor(t){a(this,"config");a(this,"internalConfig");a(this,"registry");a(this,"localNodeId");a(this,"localNodeName");a(this,"remoteNodes",new Map);a(this,"remoteAgents",new Map);a(this,"syncTimer",null);a(this,"cleanupTimer",null);a(this,"reconnectTimer",null);a(this,"heartbeatTimer",null);a(this,"running",false);a(this,"agentListChangeCallbacks",new Set);this.registry=t.registry,this.localNodeId=t.localNodeId,this.localNodeName=t.localNodeName,this.config={...Ct,...t.config},this.internalConfig={maxConcurrentSync:3,remoteAgentTtl:300*1e3,cleanupInterval:180*1e3,maxRetryCount:5,baseRetryDelay:15e3};}async start(){if(this.running){M.warn("Agent sync manager is already running");return}M.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let t of this.config.remoteNodes)this.remoteNodes.set(t.id,{info:{id:t.id,name:t.id,address:t.address,port:t.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced",retryCount:0,nextRetryAt:0});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.cleanupTimer=setInterval(()=>this.cleanupStaleAgents(),this.internalConfig.cleanupInterval),this.reconnectTimer=setInterval(()=>this.reconnectFailedNodes(),this.internalConfig.baseRetryDelay),this.heartbeatTimer=setInterval(()=>this.checkNodeHealth(),6e4),this.registry.onEvent(t=>this.handleLocalAgentEvent(t)),this.running=true,M.info("Agent sync manager started");}async stop(){if(!this.running){M.warn("Agent sync manager is not running");return}M.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,M.info("Agent sync manager stopped");}async pullFromAllNodes(){let t=Array.from(this.remoteNodes.keys()),e=this.internalConfig.maxConcurrentSync;for(let s=0;s<t.length;s+=e){let i=t.slice(s,s+e).map(r=>this.pullFromNode(r).catch(a=>{M.error("Failed to pull from node",{nodeId:r,error:a.message});}));await Promise.all(i);}}async pullFromNode(t){let e=this.remoteNodes.get(t);if(!e)throw new Error(`Unknown remote node: ${t}`);e.status="syncing";let s=this.config.remoteNodes.find(i=>i.id===t);if(!s)throw new Error(`Remote node not found in config: ${t}`);let n=Date.now();try{let i=`http://${s.address}:${s.port}/sync/agents`,r=await Fetch.get(i,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);let a=r.data.agents||[];for(let c of a)c.sourceGatewayId=t,this.remoteAgents.set(c.id,{agent:c,cachedAt:n});return e.lastSyncAt=n,e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",e.retryCount=0,delete e.error,a}catch(i){e.status="error",e.error=i.message,e.info.status="offline";let r=this.calculateRetryDelay(e.retryCount);throw e.retryCount++,e.nextRetryAt=n+r,M.error("Failed to pull from node",{nodeId:t,error:i.message,retryCount:e.retryCount,nextRetryAt:e.nextRetryAt}),i}}calculateRetryDelay(t){let{baseRetryDelay:e,maxRetryCount:s}=this.internalConfig;return Math.min(e*2**t,e*2**s)}async pushEvent(t){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[s]of this.remoteNodes.entries())e.push(this.pushToNode(s,t));await Promise.allSettled(e);}async pushToNode(t,e){let s=this.config.remoteNodes.find(n=>n.id===t);if(!s){M.warn("Unknown remote node for push",{nodeId:t});return}try{let n=`http://${s.address}:${s.port}/sync/events`,i=await Fetch.post(n,e,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}`);M.debug("Pushed event to node",{nodeId:t,eventType:e.type});}catch(n){M.error("Failed to push to node",{nodeId:t,eventType:e.type,error:n.message});}}async handleSyncMessage(t){switch(t.type){case "agent_list_request":await this.handleAgentListRequest(t);break;case "agent_list_response":await this.handleAgentListResponse(t);break;case "agent_register":await this.handleAgentRegister(t);break;case "agent_deregister":await this.handleAgentDeregister(t);break;case "agent_heartbeat":await this.handleAgentHeartbeat(t);break;case "agent_status_change":await this.handleAgentStatusChange(t);break;default:M.warn("Unknown sync message type",{type:t.type});}}async handleAgentListRequest(t){let e=this.getLocalAgentsForSync(),s={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:t.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(t.sourceNodeId,s);}async handleAgentListResponse(t){for(let e of t.agents)this.remoteAgents.set(e.id,{agent:e,cachedAt:Date.now()});this.notifyAgentListChange(t.agents,"add");}async handleAgentRegister(t){let{agent:e}=t,s=this.remoteAgents.get(e.id);if(s){let n=this.resolveConflict(s.agent,e);this.remoteAgents.set(e.id,{agent:n,cachedAt:Date.now()});}else this.remoteAgents.set(e.id,{agent:e,cachedAt:Date.now()});this.notifyAgentListChange([e],"add");}async handleAgentDeregister(t){let{agentId:e}=t,s=this.remoteAgents.get(e);this.remoteAgents.delete(e),s&&this.notifyAgentListChange([s.agent],"remove");}async handleAgentHeartbeat(t){let{agentId:e,heartbeatAt:s,status:n}=t,i=this.remoteAgents.get(e);i&&(i.agent.updatedAt=s,i.agent.status=n,i.cachedAt=Date.now());}async handleAgentStatusChange(t){let{agentId:e,newStatus:s,changedAt:n}=t,i=this.remoteAgents.get(e);if(i){({...i.agent});i.agent.status=s,i.agent.updatedAt=n,i.cachedAt=Date.now(),M.debug("Remote agent status changed",{agentId:e,newStatus:s,sourceNodeId:t.sourceNodeId}),this.notifyAgentListChange([i.agent],"update");}}cleanupStaleAgents(){if(!this.running)return;let t=Date.now(),e=this.internalConfig.remoteAgentTtl,s=0;for(let[n,i]of this.remoteAgents.entries())t-i.cachedAt>e&&(this.remoteAgents.delete(n),s++);s>0&&M.debug("Cleaned up stale remote agents",{cleanedCount:s,remainingCount:this.remoteAgents.size});}async reconnectFailedNodes(){if(!this.running)return;let t=Date.now(),e=[];for(let[s,n]of this.remoteNodes.entries())n.status==="error"&&n.nextRetryAt>0&&t>=n.nextRetryAt&&e.push(s);if(e.length>0){M.debug("Retrying failed nodes",{nodeCount:e.length});for(let s of e)try{await this.pullFromNode(s);}catch{}}}async checkNodeHealth(){if(this.running)for(let[t,e]of this.remoteNodes.entries()){let s=this.config.remoteNodes.find(n=>n.id===t);if(s)try{let n=`http://${s.address}:${s.port}/status`,i=await Fetch.get(n,{timeout:5e3});i.ok?(e.info.status="online",e.retryCount=0,M.debug("Node health check passed",{nodeId:t})):(e.info.status="offline",M.warn("Node health check failed",{nodeId:t,status:i.status}));}catch(n){e.info.status="offline",M.warn("Node health check error",{nodeId:t,error:n.message});}}}async handleLocalAgentEvent(t){if(!this.config.pushEvents.includes(t.type))return;let e=this.agentToSyncInfo(t.agent),s=Date.now();switch(t.type){case "register":await this.pushEvent({type:"agent_register",sourceNodeId:this.localNodeId,timestamp:s,agent:e});break;case "deregister":await this.pushEvent({type:"agent_deregister",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id});break;case "heartbeat":await this.pushEvent({type:"agent_heartbeat",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id,heartbeatAt:t.agent.lastHeartbeat,status:t.agent.status});break;case "status_change":await this.pushEvent({type:"agent_status_change",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id,oldStatus:t.oldStatus??"healthy",newStatus:t.agent.status,changedAt:s});break}}agentToSyncInfo(t){return {id:t.id,name:t.name,sourceGatewayId:this.localNodeId,address:t.address,capabilities:t.capabilities,status:t.status,updatedAt:t.lastHeartbeat,metadata:t.metadata}}resolveConflict(t,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>t.updatedAt?e:e.updatedAt<t.updatedAt?t:e.id>t.id?e:t;case "local":return t;case "remote":return e;default:return e.updatedAt>t.updatedAt?e:e.updatedAt<t.updatedAt?t:e.id>t.id?e:t}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(t=>this.agentToSyncInfo(t))}notifyAgentListChange(t,e){for(let s of this.agentListChangeCallbacks)try{for(let n of t)s(t,e,n);}catch(n){M.error("Agent list change callback error",{error:String(n)});}}onAgentListChange(t){this.agentListChangeCallbacks.add(t);}offAgentListChange(t){this.agentListChangeCallbacks.delete(t);}getMergedAgentList(){let t=new Map;for(let e of this.getLocalAgentsForSync())t.set(e.id,e);for(let[e,s]of this.remoteAgents.entries())t.has(e)||t.set(e,s.agent);return Array.from(t.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values()).map(t=>t.agent)}getStats(){let t=this.registry.getAllAgents(),e=0,s=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:s++;let n=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(n||0)&&(n=i.lastSyncAt);return {localAgentCount:t.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:t.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:s,lastSyncAt:n}}isRunning(){return this.running}addRemoteNode(t){this.remoteNodes.set(t.id,{info:{id:t.id,name:t.id,address:t.address,port:t.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced",retryCount:0,nextRetryAt:0}),M.debug("Remote node added",{nodeId:t.id,address:t.address});}removeRemoteNode(t){this.remoteNodes.delete(t);for(let[e,s]of this.remoteAgents.entries())s.agent.sourceGatewayId===t&&this.remoteAgents.delete(e);M.debug("Remote node removed",{nodeId:t});}};var U=Log.create({service:"gateway:ws-agent-sync"}),Tt=class{constructor(t){a(this,"wsServer");a(this,"syncManager");a(this,"gatewayId");a(this,"subscribers",new Map);a(this,"getClientWs");this.wsServer=t.wsServer,this.syncManager=t.syncManager,this.getClientWs=t.getClientWs,this.gatewayId=t.wsServer.getGatewayId();}async handleAgentListRequest(t,e){let s=this.getClientWs(t);if(!s){U.warn("Client not found for agent list request",{clientId:t,requestId:e});return}let n=this.syncManager.getMergedAgentList();this.sendMessage(s,{type:"agent_list_response",requestId:e,agents:n});}async handleAgentSubscribe(t,e){let s=this.getClientWs(t);if(!s){U.warn("Client not found for agent subscribe",{clientId:t});return}if(e){this.subscribers.delete(t),this.subscribers.set(t,{clientId:t,ws:s,subscribedAt:Date.now()});let n=this.syncManager.getMergedAgentList();this.sendMessage(s,{type:"agent_list_response",agents:n});}else this.subscribers.delete(t);}broadcastAgentUpdate(t,e){if(this.subscribers.size===0)return;let s={type:"agent_update",action:t,agent:e};for(let[n,i]of this.subscribers.entries())try{i.ws.readyState===i.ws.OPEN&&this.sendMessage(i.ws,s);}catch(r){U.error("Failed to send agent update to client",{clientId:n,error:r.message});}}broadcastAgentList(){if(this.subscribers.size===0)return;let t=this.syncManager.getMergedAgentList();for(let[e,s]of this.subscribers.entries())try{s.ws.readyState===s.ws.OPEN&&this.sendMessage(s.ws,{type:"agent_list_response",requestId:`broadcast_${Date.now()}`,agents:t});}catch(n){U.error("Failed to send agent list to client",{clientId:e,error:n.message});}}cleanupClientSubscription(t){this.subscribers.delete(t);}getSubscriberCount(){return this.subscribers.size}getSubscribers(){return Array.from(this.subscribers.keys())}sendMessage(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e));}async handleAgentRegister(t,e){if(!e.agentId){U.warn("Agent register payload missing agentId",{clientId:t});return}if(!this.getClientWs(t)){U.warn("Client not found for agent register",{clientId:t});return}let n={id:e.agentId,name:e.name??e.agentId,sourceGatewayId:this.gatewayId,address:e.address??"",capabilities:e.capabilities??[],status:"healthy",updatedAt:Date.now(),metadata:e.metadata};try{let i=this.syncManager.registry;if(i.agents.has(n.id)){await i.heartbeat(n.id,n.metadata),U.debug("Agent heartbeat from client",{clientId:t,agentId:n.id});return}let r={...n.metadata,sourceGatewayId:this.gatewayId};await i.register({id:n.id,name:n.name,address:n.address,capabilities:n.capabilities,metadata:r}),U.debug("Agent registered from client",{clientId:t,agentId:n.id,name:n.name}),this.broadcastAgentUpdate("add",n);}catch(i){U.warn("Failed to register agent from client",{clientId:t,agentId:e.agentId,error:String(i)});}}async handleAgentDeregister(t,e){if(!e.agentId){U.warn("Agent deregister payload missing agentId",{clientId:t});return}if(!this.getClientWs(t)){U.warn("Client not found for agent deregister",{clientId:t});return}try{await this.syncManager.registry.deregister(e.agentId),U.debug("Agent deregistered from client",{clientId:t,agentId:e.agentId});let n={id:e.agentId,name:"unknown",sourceGatewayId:this.gatewayId,address:"",capabilities:[],status:"offline",updatedAt:Date.now()};this.broadcastAgentUpdate("remove",n);}catch(n){U.warn("Failed to deregister agent from client",{clientId:t,agentId:e.agentId,error:String(n)});}}async cleanupClient(t){this.subscribers.delete(t);let e=this.syncManager.registry.getAllAgents().filter(s=>s.metadata?.sourceGatewayId===this.gatewayId);for(let s of e)try{await this.syncManager.registry.deregister(s.id);let n={id:s.id,name:s.name,sourceGatewayId:this.gatewayId,address:s.address,capabilities:s.capabilities,status:"offline",updatedAt:Date.now()};this.broadcastAgentUpdate("remove",n);}catch{}}};var de=class de{constructor(t){a(this,"log",Log.create({service:"gateway:server"}));a(this,"config");a(this,"router");a(this,"sessionManager");a(this,"pluginLoader");a(this,"messageStore");a(this,"contactStore",null);a(this,"wsServer",null);a(this,"agentRegistry");a(this,"agentSyncManager",null);a(this,"wsAgentSync",null);a(this,"running",false);a(this,"connections",0);a(this,"gatewayAgent",null);a(this,"bindingLocks",new Map);this.log.debug("GatewayServer.constructor: starting"),this.config=t,this.log.debug("GatewayServer.constructor: creating MessageRouter");let e=ue()?X().hookRegistry:void 0;this.router=new wt(e),this.log.debug("GatewayServer.constructor: creating GatewaySessionManager");let s=v();this.sessionManager=new Ee({storagePath:`${s.Path.data}/gateway/sessions`,enablePersistence:true}),this.pluginLoader=new Re({healthCheckInterval:6e4});let n=ue();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:n}),this.messageStore=new ke({storagePath:`${s.Path.data}/gateway/messages`}),this.agentRegistry=new qe({dataDir:`${s.Path.data}/gateway/net`});let i={getSession:r=>{let a=this.sessionManager.get(r);return a?{backendSessionId:a.backendSessionId}:void 0},unbindBackendSession:r=>this.sessionManager.unbindBackendSession(r)};this.pluginLoader.setMessageHandler({onMessage:r=>this.onMessage(r),onEvent:r=>this.onEvent(r),session:i}),this.log.debug("GatewayServer.constructor: completed");}async loadChannelPlugins(){try{let{config:t}=await T(),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=ss[s];if(!i){this.log.warn("no plugin class found for platform",{platform:s});continue}let r=`${s}-main`,a=new i(r),c={enabled:!0,platform:n,session:{autoCreate:!0,resetPolicy:"onNewConversation"},routing:{broadcast:!0,dispatchToSubAgent:!0}};try{await this.pluginLoader.register(a,c),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}),await this.sessionManager.initialize(),this.log.debug("GatewayServer.start: sessionManager initialized"),await this.agentRegistry.load(),this.log.debug("GatewayServer.start: agentRegistry initialized");let e=`${v().Path.data}/gateway`,s=new re({baseDir:e});this.contactStore=new Te(s,{cacheSize:1e3}),this.contactStore.initialize&&await this.contactStore.initialize(),this.log.debug("GatewayServer.start: contactStore initialized"),this.wsServer=new ae({port:this.config.port,hostname:this.config.hostname,path:String(this.config.path??"/")}),await this.wsServer.start(),this.log.debug("GatewayServer.start: wsServer started"),await this.loadChannelPlugins(),this.pluginLoader.startAll().catch(g=>{this.log.error("plugin startup error",{error:String(g)});}),this.log.debug("GatewayServer.start: plugins startup initiated"),this.pluginLoader.startHealthCheckTimer();let{config:n}=await T(),i=n.defaults;this.wsServer.setChannelResolveDeps({sessionManager:{get:g=>this.sessionManager.get(g),getOrCreate:(g,p)=>this.sessionManager.getOrCreate(g,p),bindBackendSession:(g,p)=>this.sessionManager.bindBackendSession(g,p),findByBackendSessionId:g=>this.sessionManager.findByBackendSessionId(g),getAll:()=>this.sessionManager.getAllSessions()},pluginLoader:{getPlugin:g=>this.pluginLoader.getPlugin(g),getAllPlugins:()=>this.pluginLoader.getAllPlugins(),isRunning:g=>this.pluginLoader.isRunning(g)},defaultChannel:i?.channel,fallbackChannels:i?.fallbackChannels,contactStore:this.contactStore?{findByPlatformId:(g,p)=>this.contactStore.findByPlatformId(g,p),findByUid:g=>this.contactStore.findByUid(g),listByPlatform:(g,p,h)=>this.contactStore.listByPlatform(g,p,h),count:g=>this.contactStore.count(g)}:void 0}),this.wsServer.setPluginLoader((g,p,h)=>this.sendToChannel(g,p,h)),this.wsServer.setRouter(this.router),this.router.setSessionManager({get:g=>this.sessionManager.get(g),bindBackendSession:(g,p)=>this.sessionManager.bindBackendSession(g,p)}),this.pluginLoader.setMessageHandler({onMessage:g=>this.onMessage(g),onEvent:g=>this.onEvent(g),session:{getSession:g=>{let p=this.sessionManager.get(g);return p?{backendSessionId:p.backendSessionId}:void 0},unbindBackendSession:g=>this.sessionManager.unbindBackendSession(g)}}),this.agentSyncManager=new Ke({registry:this.agentRegistry,localNodeId:"gateway",localNodeName:"gateway"}),this.wsAgentSync=new Tt({wsServer:this.wsServer,syncManager:this.agentSyncManager,getClientWs:g=>this.wsServer.getClientWs(g)}),this.wsServer.setAgentSync(this.wsAgentSync),this.wsServer.setAgentRegistry(this.agentRegistry),this.log.debug("GatewayServer.start: agent sync initialized"),this.log.debug("GatewayServer.start: registering gateway status provider"),ms(async()=>{let g=this.sessionManager.getAllSessions(),p=this.router.getStats?.()??{subscribers:0},h=this.agentRegistry.getStats?.()??{totalAgents:0,healthyAgents:0,unhealthyAgents:0},S=this.wsAgentSync?.getSubscriberCount?.()??0,C=this.wsServer?.getStartTime?.()??0,k=this.pluginLoader.getAllPlugins().filter(F=>this.pluginLoader.isRunning(F.id)).map(F=>({id:F.id,platform:F.platform,name:F.name,version:F.version}));return {status:this.running?"running":"stopped",connections:this.wsServer?.getConnectionCount?.()??0,sessions:g.length,messageSubscriptions:p.subscribers??0,agentSubscriptions:S,uptime:this.running&&C?Date.now()-C:0,version:"1.0.0",agents:{total:h.totalAgents,healthy:h.healthyAgents,unhealthy:h.unhealthyAgents},channels:k}});let r=await this.messageStore.loadFromDisk();this.log.debug("loaded messages from disk",{count:r});let a=Date.now(),c=6e4,d=()=>{let g=Date.now()-a,p=this.pluginLoader.getAllPlugins(),h=p.filter(S=>this.pluginLoader.isRunning(S.id));h.length===p.length&&p.length>0?(this.log.debug("all plugins ready, proceeding with message retry"),this.retryPendingMessages().catch(S=>{this.log.error("failed to retry pending messages",{error:String(S)});})):g>c?(this.log.warn("plugin startup timeout, proceeding with message retry anyway",{elapsed:g}),this.retryPendingMessages().catch(S=>{this.log.error("failed to retry pending messages",{error:String(S)});})):(this.log.debug("waiting for plugins to be ready",{elapsed:g,ready:h.length,total:p.length}),setTimeout(d,100));};d(),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}if(this.log.info("stopping gateway server"),this.wsServer&&(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.gatewayAgent){try{await this.gatewayAgent.stop();}catch(t){this.log.warn("Failed to stop gatewayAgent during server shutdown",{error:String(t)});}this.gatewayAgent=null;}this.running=false,this.log.info("gateway server stopped");}getStatus(){let t=this.agentRegistry.getStats();return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections,agents:{total:t.totalAgents,healthy:t.healthyAgents,unhealthy:t.unhealthyAgents}}}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>de.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=t.metadata.channel,n=this.buildChannelContext(t,s),i={...t,metadata:{...t.metadata,system:n}},r=true;try{let a=await this.router.route(i);if(r=a.success,!a.dispatched&&t.type==="input"){let{config:c}=await T(),d=c.agentProcessing??{mode:"localAgent",localAgentPriority:1,subAgentPriority:2,timeout:3e5,retryOnFailure:!0};this.log.debug("no subscribers, dispatching to agent",{id:t.id,mode:d.mode}),this.dispatchToAgent(i,d).catch(g=>{this.log.error("agent dispatch failed",{id:t.id,error:String(g)}),r=!1;});}}catch(a){r=false,this.log.error("route failed",{messageId:t.id,error:String(a)});}t.type==="input"&&!r&&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 a=await this.contactStore.getOrCreate(e,r,{username:t.metadata.channel?.username,displayName:t.metadata.channel?.firstName});this.log.debug("contact saved",{uid:a.uid});}catch(a){this.log.warn("failed to save contact",{platform:e,stableId:r,error:String(a)});}}async dispatchToAgent(t,e){if(!ue()){this.log.debug("no agent adapter, message remains pending",{id:t.id});return}let s=X(),n=t.metadata.channel,r=this.sessionManager.get(t.sessionId)?.backendSessionId||void 0,a=t.metadata.system;switch(e.mode){case "localAgent":{this.dispatchToGatewayAgent(t,n,a,s,r);break}case "subAgent":{this.dispatchToSubAgent(t,n,a,s,r);break}default:{this.dispatchToGatewayAgent(t,n,a,s,r);break}}}getGatewayAgent(){if(!this.gatewayAgent){if(!X().sdk)return null;this.gatewayAgent=fs({});}return this.gatewayAgent}dispatchToGatewayAgent(t,e,s,n,i){let r=this.getGatewayAgent();if(!r){this.log.debug("no GatewayAgent available, message remains pending",{id:t.id});return}this.log.debug("dispatching message to GatewayAgent",{id:t.id,sessionId:t.sessionId,backendSessionId:i}),this.triggerHook(HookEvent.GatewayMessageProcess,{id:t.id,sessionId:t.sessionId,backendSessionId:i,processorId:"gatewayAgent",processType:"gatewayAgent",agent:t?.metadata?.agent??"gateway",timestamp:Date.now()});let a=t.sessionId,d=(this.bindingLocks.get(a)??Promise.resolve()).catch(()=>{}).then(()=>this.resolveAndBindBackendSession(t,e,n,i)).then(g=>{g!==void 0&&this.executeGatewayAgent(t,e,r,g,s);}).catch(g=>{this.log.error("dispatchToGatewayAgent: binding pipeline failed",{id:t.id,sessionId:t.sessionId,error:String(g)}),this.handleAgentError(t,e,g,"gatewayAgent",i);}).finally(()=>{this.bindingLocks.get(a)===d&&this.bindingLocks.delete(a);});this.bindingLocks.set(a,d);}async resolveAndBindBackendSession(t,e,s,n){let r=`Gateway-${e?.platform||"unknown"}`;if(n){try{if((await s.sdk.session.get({sessionId:n})).data)return n}catch(p){this.log.warn("dispatchToGatewayAgent: session.get failed, will re-create",{sessionId:n,error:String(p)});}let g=(await s.sdk.session.create({title:r})).data?.id;if(g)return await this.sessionManager.bindBackendSession(t.sessionId,g),this.log.debug("backend session re-bound (previous session expired)",{gatewaySessionId:t.sessionId,backendSessionId:g}),g;this.log.warn("dispatchToGatewayAgent: session.create returned no id (re-bind)",{messageId:t.id});return}let c=(await s.sdk.session.create({title:r})).data?.id;if(c)return await this.sessionManager.bindBackendSession(t.sessionId,c),this.log.debug("backend session bound (first message)",{gatewaySessionId:t.sessionId,backendSessionId:c}),c;this.log.warn("dispatchToGatewayAgent: session.create returned no id (first bind)",{messageId:t.id});}buildChannelContext(t,e){let s=e?.platform||"unknown",n=e?.userId||e?.chatId||"unknown user",i=`${s}:${n}`,r=e?.chatType||"unknown";return `## External Channel Message
33
33
  - Platform: ${s}
34
34
  - Chat Type: ${r} (e.g., private, group)
35
35
  - From: ${n} (contactUid: ${i})
@@ -41,4 +41,4 @@ ${g.content}`}),this.log.debug("weixin text file inlined",{fileName:c,mime:a,len
41
41
  - Use gateway tool to proactively send messages (works for both private and group chats):
42
42
  \`\`\`json
43
43
  {"operation": "send", "sessionId": "${t.sessionId}", "content": "Your message here"}
44
- \`\`\``}executeGatewayAgent(t,e,s,n,i){let r={source:n??"",title:`[${e?.platform||"unknown"}] Message from ${e?.userId||e?.chatId||"unknown"}]`,agent:t?.metadata?.agent,parts:t.content,system:i},a=false;s.run(r,{onMessage:c=>{let d=c.text??"";!d||d.trim().length===0||e?.channelId&&(a=true,this.sendToChannel(e.channelId,{id:Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:d}],metadata:{channel:e,processorId:"gatewayAgent",proactive:false,replyToMessageId:t.id,streaming:true,messageId:c.metadata.messageId},timestamp:Date.now()},{}).catch(g=>{this.log.error("executeGatewayAgent: sendToChannel failed in onMessage",{id:t.id,error:String(g)});}));}}).then(c=>{this.handleAgentResult(t,e,c,"gatewayAgent",n,a);},c=>{this.handleAgentError(t,e,c,"gatewayAgent",n);});}handleAgentResult(t,e,s,n,i,r=false){let a=s.metadata.sessionId;a&&this.sessionManager.get(t.sessionId)&&i!==a&&(this.sessionManager.bindBackendSession(t.sessionId,a),this.log.debug("backend session re-bound (session changed during execution)",{gatewaySessionId:t.sessionId,previousBackendSessionId:i,newBackendSessionId:a})),this.triggerHook(HookEvent.GatewayMessageComplete,{id:t.id,sessionId:t.sessionId,backendSessionId:a||i,processorId:n,status:"completed",timestamp:Date.now()}),s.output&&!r&&e?.channelId&&(this.log.debug("sending response to channel",{id:t.id,channelId:e.channelId,outputLength:s.output.length}),this.sendToChannel(e.channelId,{id:Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:s.output}],metadata:{channel:e,processorId:n,proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}),this.log.debug("agent response sent to channel",{id:t.id,channelId:e.channelId})),this.sessionManager.incrementMessageCount(t.sessionId);}handleAgentError(t,e,s,n,i){this.log.error(`${n} dispatch failed`,{id:t.id,error:String(s)});let r=e?.channelId;if(r){let c=`\u26A0\uFE0F \u5904\u7406\u5931\u8D25: ${s instanceof Error?s.message:String(s)}`;this.sendToChannel(r,{id:Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:c}],metadata:{channel:e,processorId:n,proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}).catch(d=>{this.log.error("failed to send error response",{error:String(d)});});}this.triggerHook(HookEvent.GatewayMessageComplete,{id:t.id,sessionId:t.sessionId,backendSessionId:i,processorId:n,status:"failed",error:String(s),timestamp:Date.now()});}dispatchToSubAgent(t,e,s,n,i){let r=n.subAgentRunner;if(!r){this.log.debug("no SubAgentRunner available, message remains pending",{id:t.id});return}this.log.debug("dispatching message to SubAgent",{id:t.id,sessionId:t.sessionId}),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 a=e?.platform||"unknown",c=e?.userId||e?.chatId||"unknown user",d=`${a}:${c}`,g={source:t.sessionId,title:`[${a}] Message from ${c}`,agent:"gateway",sessionId:i,parts:t.content,system:s,channel:{platform:a,contactUid:d,channelId:e?.channelId,userId:c}};r.run(g).then(p=>{this.handleAgentResult(t,e,p,"subAgent",i);},p=>{this.handleAgentError(t,e,p,"subAgent",i);});}async triggerHook(t,e){if(ue())try{await X().hookRegistry.triggerEvent(t,e,{messageStore:{store:async(n,i)=>{let r=Ve(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()-de.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)continue;let r=i.message;if(i.retryCount>de.MAX_RETRY_COUNT){this.log.debug("message retry count exceeded, skipping",{messageId:r.id,retryCount:i.retryCount});continue}let a=r.metadata.channel?.channelId;if(!a){this.log.debug("message has no pluginId, skipping",{messageId:r.id});continue}if(!this.pluginLoader.getPlugin(a)||!this.pluginLoader.isRunning(a)){this.log.debug("plugin not available, skipping",{messageId:r.id,pluginId:a});continue}if(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)});});else if(r.type==="output"){if(i.status!=="pending"&&i.status!=="failed"){this.log.debug("output message not in retryable state, skipping",{messageId:r.id,status:i.status});continue}this.log.debug("retrying output message",{messageId:r.id,pluginId:a,status:i.status}),this.sendToChannel(a,r,{isRetry:true}).then(()=>{e++;}).catch(d=>{this.log.error("failed to retry message",{messageId:r.id,error:String(d)});});}}}this.log.debug("retryPendingMessages completed",{totalProcessed: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(!s.isRetry&&this.messageStore.isProcessed(e.id))return this.log.debug("message already processed, skipping send",{id:e.id}),e.id;if(ue())try{await X().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(g,p)=>{let h=Ve(g);await this.messageStore.store(h,p);},updateStatus:async(g,p,h)=>{await this.messageStore.updateStatus(g,p,h);}}});}catch{this.log.debug("hook trigger skipped (no context)");}let a=this.pluginLoader.getPlugin(t);if(!a)throw new Error(`Plugin not found: ${t}`);this.log.debug("sendToChannel: calling plugin.send",{pluginId:t,messageId:e.id});let c;try{c=await a.send(e),this.log.debug("sendToChannel: plugin.send completed",{pluginId:t,messageId:e.id,result:c});}catch(d){throw this.log.error("sendToChannel: plugin.send failed",{pluginId:t,messageId:e.id,error:String(d)}),await this.messageStore.incrementRetry(e.id),await this.messageStore.updateStatus(e.id,"failed",{error:String(d)}),d}return c}async sendProactiveMessage(t,e,s,n,i={}){let r={id:Identifier.ascending("message"),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(de,"MAX_RETRY_COUNT",3),a(de,"SEVEN_DAYS_MS",10080*60*1e3);var bn=de;export{A as $,bn as $a,li as A,nr as Aa,di as B,bd as Ba,gi as C,Sd as Ca,ui as D,Cd as Da,pi as E,Gs as Ea,hi as F,Vt as Fa,mi as G,Fs as Ga,fi as H,Qt as Ha,yi as I,Md as Ia,bi as J,kd as Ja,Si as K,$s as Ka,Ci as L,Ws as La,wi as M,Hs as Ma,vi as N,eg as Na,ps as O,$e as Oa,ht as P,cn as Pa,ve as Q,xt as Qa,Ie as R,pn as Ra,cs as S,We as Sa,Un as T,He as Ta,ge as U,ze as Ua,eo as V,je as Va,to as W,Jr as Wa,ue as X,ts as Xa,X as Y,Au as Ya,v as Z,qe as Za,Nt as _,Ke as _a,et as a,wn as aa,tt as b,Ve as ba,st as c,Je as ca,nt as d,Qe as da,it as e,Et as ea,rt as f,Gt as fa,at as g,Ii as ga,ns as h,St as ha,is as i,Ct as ia,rs as j,Ai as ja,as as k,wt as ka,os as l,ke as la,ot as m,ne as ma,ct as n,Ee as na,lt as o,Re as oa,dt as p,ae as pa,gt as q,P as qa,ut as r,De as ra,pt as s,Ne as sa,Ze as t,Le as ta,Rt as u,Ge as ua,Dn as v,Ue as va,ds as w,Ce as wa,gs as x,Yi as xa,us as y,Zi as ya,ci as z,sr as za};
44
+ \`\`\``}executeGatewayAgent(t,e,s,n,i){let r={source:n??"",title:`[${e?.platform||"unknown"}] Message from ${e?.userId||e?.chatId||"unknown"}]`,agent:t?.metadata?.agent,parts:t.content,system:i},a=false;s.run(r,{onMessage:c=>{let d=c.text??"";!d||d.trim().length===0||e?.channelId&&(a=true,this.sendToChannel(e.channelId,{id:Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:d}],metadata:{channel:e,processorId:"gatewayAgent",proactive:false,replyToMessageId:t.id,streaming:true,messageId:c.metadata.messageId},timestamp:Date.now()},{}).catch(g=>{this.log.error("executeGatewayAgent: sendToChannel failed in onMessage",{id:t.id,error:String(g)});}));}}).then(c=>{this.handleAgentResult(t,e,c,"gatewayAgent",n,a);},c=>{this.handleAgentError(t,e,c,"gatewayAgent",n);});}handleAgentResult(t,e,s,n,i,r=false){let a=s.metadata.sessionId;a&&this.sessionManager.get(t.sessionId)&&i!==a&&(this.sessionManager.bindBackendSession(t.sessionId,a),this.log.debug("backend session re-bound (session changed during execution)",{gatewaySessionId:t.sessionId,previousBackendSessionId:i,newBackendSessionId:a})),this.triggerHook(HookEvent.GatewayMessageComplete,{id:t.id,sessionId:t.sessionId,backendSessionId:a||i,processorId:n,status:"completed",timestamp:Date.now()}),s.output&&!r&&e?.channelId&&(this.log.debug("sending response to channel",{id:t.id,channelId:e.channelId,outputLength:s.output.length}),this.sendToChannel(e.channelId,{id:Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:s.output}],metadata:{channel:e,processorId:n,proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}),this.log.debug("agent response sent to channel",{id:t.id,channelId:e.channelId})),this.sessionManager.incrementMessageCount(t.sessionId);}handleAgentError(t,e,s,n,i){this.log.error(`${n} dispatch failed`,{id:t.id,error:String(s)});let r=e?.channelId;if(r){let c=`\u26A0\uFE0F \u5904\u7406\u5931\u8D25: ${s instanceof Error?s.message:String(s)}`;this.sendToChannel(r,{id:Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:c}],metadata:{channel:e,processorId:n,proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}).catch(d=>{this.log.error("failed to send error response",{error:String(d)});});}this.triggerHook(HookEvent.GatewayMessageComplete,{id:t.id,sessionId:t.sessionId,backendSessionId:i,processorId:n,status:"failed",error:String(s),timestamp:Date.now()});}dispatchToSubAgent(t,e,s,n,i){let r=n.subAgentRunner;if(!r){this.log.debug("no SubAgentRunner available, message remains pending",{id:t.id});return}this.log.debug("dispatching message to SubAgent",{id:t.id,sessionId:t.sessionId}),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 a=e?.platform||"unknown",c=e?.userId||e?.chatId||"unknown user",d=`${a}:${c}`,g={source:t.sessionId,title:`[${a}] Message from ${c}`,agent:"gateway",sessionId:i,parts:t.content,system:s,channel:{platform:a,contactUid:d,channelId:e?.channelId,userId:c}};r.run(g).then(p=>{this.handleAgentResult(t,e,p,"subAgent",i);},p=>{this.handleAgentError(t,e,p,"subAgent",i);});}async triggerHook(t,e){if(ue())try{await X().hookRegistry.triggerEvent(t,e,{messageStore:{store:async(n,i)=>{let r=Ve(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()-de.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)continue;let r=i.message;if(i.retryCount>de.MAX_RETRY_COUNT){this.log.debug("message retry count exceeded, skipping",{messageId:r.id,retryCount:i.retryCount});continue}let a=r.metadata.channel?.channelId;if(!a){this.log.debug("message has no pluginId, skipping",{messageId:r.id});continue}if(!this.pluginLoader.getPlugin(a)||!this.pluginLoader.isRunning(a)){this.log.debug("plugin not available, skipping",{messageId:r.id,pluginId:a});continue}if(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)});});else if(r.type==="output"){if(i.status!=="pending"&&i.status!=="failed"){this.log.debug("output message not in retryable state, skipping",{messageId:r.id,status:i.status});continue}this.log.debug("retrying output message",{messageId:r.id,pluginId:a,status:i.status}),this.sendToChannel(a,r,{isRetry:true}).then(()=>{e++;}).catch(d=>{this.log.error("failed to retry message",{messageId:r.id,error:String(d)});});}}}this.log.debug("retryPendingMessages completed",{totalProcessed: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(!s.isRetry&&this.messageStore.isProcessed(e.id))return this.log.debug("message already processed, skipping send",{id:e.id}),e.id;if(ue())try{await X().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(g,p)=>{let h=Ve(g);await this.messageStore.store(h,p);},updateStatus:async(g,p,h)=>{await this.messageStore.updateStatus(g,p,h);}}});}catch{this.log.debug("hook trigger skipped (no context)");}let a=this.pluginLoader.getPlugin(t);if(!a)throw new Error(`Plugin not found: ${t}`);this.log.debug("sendToChannel: calling plugin.send",{pluginId:t,messageId:e.id});let c;try{c=await a.send(e),this.log.debug("sendToChannel: plugin.send completed",{pluginId:t,messageId:e.id,result:c});}catch(d){throw this.log.error("sendToChannel: plugin.send failed",{pluginId:t,messageId:e.id,error:String(d)}),await this.messageStore.incrementRetry(e.id),await this.messageStore.updateStatus(e.id,"failed",{error:String(d)}),d}return c}async sendProactiveMessage(t,e,s,n,i={}){let r={id:Identifier.ascending("message"),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(de,"MAX_RETRY_COUNT",3),a(de,"SEVEN_DAYS_MS",10080*60*1e3);var bn=de;export{A as $,bn as $a,li as A,nr as Aa,di as B,wd as Ba,gi as C,vd as Ca,ui as D,Id as Da,pi as E,Jt as Ea,hi as F,Qt as Fa,mi as G,Fs as Ga,fi as H,At as Ha,yi as I,_d as Ia,bi as J,Ed as Ja,Si as K,$s as Ka,Ci as L,Ws as La,wi as M,Hs as Ma,vi as N,ng as Na,hs as O,$e as Oa,ht as P,cn as Pa,ve as Q,Mt as Qa,Ie as R,pn as Ra,ls as S,We as Sa,Un as T,He as Ta,ge as U,ze as Ua,no as V,je as Va,io as W,Yr as Wa,ue as X,ss as Xa,X as Y,ku as Ya,v as Z,qe as Za,Lt as _,Ke as _a,et as a,wn as aa,tt as b,Ve as ba,st as c,Je as ca,nt as d,Qe as da,it as e,Rt as ea,rt as f,Ut as fa,at as g,Ii as ga,is as h,St as ha,rs as i,Ct as ia,as as j,Ai as ja,os as k,wt as ka,cs as l,ke as la,ot as m,ne as ma,ct as n,Ee as na,lt as o,Re as oa,dt as p,ae as pa,gt as q,P as qa,ut as r,De as ra,pt as s,Ne as sa,Ze as t,Le as ta,Dt as u,Ge as ua,Dn as v,Ue as va,gs as w,Ce as wa,us as x,Yi as xa,ps as y,Zi as ya,ci as z,sr as za};