@easbot/gateway 0.2.44 → 0.2.46

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,30 +0,0 @@
1
- import {b,a}from'./chunk-RGPJTZUB.mjs';import g,{z as z$1}from'zod';import*as ae from'path';import ae__default from'path';import*as X from'fs';import X__default,{existsSync}from'fs';import*as L from'fs/promises';import L__default from'fs/promises';import {Filesystem,TruncateContent,Fetch,PKG,createServer}from'@easbot/utils';import {WebSocketServer}from'ws';import Sn from'https';import Cn from'http';import wn from'crypto';import {pathToFileURL,fileURLToPath}from'url';import {HookEvent}from'@easbot/plugin';function M(d,t,e,s){return {id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:d,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 gs(d,t,e,s){return M(d,t,[{type:"text",text:e}],s)}function Le(d){let t={platform:d.channel?.platform??"api",channelId:d.channel?.channelId??"unknown",chatId:d.channel?.chatId,userId:d.channel?.userId,chatType:d.channel?.chatType,chatTitle:d.channel?.chatTitle};return {id:d.id,sessionId:d.sessionId,type:d.type,content:Array.isArray(d.content)?d.content:[{type:"text",text:String(d.content??"")}],metadata:{channel:t,replyToMessageId:d.replyToMessageId,processorId:d.processorId,agent:d.agent,proactive:d.proactive??!d.replyToMessageId},timestamp:d.timestamp??Date.now()}}function Fe(d){if(!d.platform)throw new Error("Invalid session: platform is required");if(!d.channelId)throw new Error("Invalid session: channelId is required");let t=d.chatId??"",e=d.userId??t;if(!t&&!d.userId)throw new Error(`Invalid session: chatId and userId cannot both be empty. platform=${d.platform}, channelId=${d.channelId}`);return [d.platform,d.channelId,t,e].join("_")}function Ue(){return {status:"active",messageCount:0,lastMessageAt:null}}function Oe(d,t){if(!d||!t)throw new Error("platform and stableId are required");return `${d}:${t}`}function Be(d){if(!d||typeof d!="string")return null;let t=d.indexOf(":");if(t<=0||t>=d.length-1)return null;let e=d.slice(0,t),s=d.slice(t+1);return !e||!s?null:{platform:e,stableId:s}}function ht(d){let{platform:t,stableId:e,profile:s={},aliases:n={},metadata:i}=d;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:Oe(t,e),platform:t,stableId:e,aliases:{...n},profile:{...s},createdAt:r,lastSeenAt:r,metadata:i}}function mt(d,t){return `sub_${d}_${t}`}var us=b.create({service:"gateway:config"});g.enum(["telegram","slack","feishu","wechat","webchat","signal","nostr","dingtalk"]);g.enum(["low","medium","high","critical"]);var He=g.object({enabled:g.boolean().default(true),botToken:g.string().describe("Telegram Bot Token"),webhookUrl:g.string().optional().describe("Webhook URL for receiving updates"),polling:g.object({enabled:g.boolean().default(true),interval:g.number().int().positive().optional().describe("Polling interval in ms"),timeout:g.number().int().positive().optional().default(30).describe("Long polling timeout in seconds")}).refine(d=>d===void 0||d.enabled,{message:"polling.enabled must be true when polling is configured"}).optional(),maxConnections:g.number().int().positive().optional().default(100),timeout:g.number().int().positive().optional().default(3e4)}),We=g.object({enabled:g.boolean().default(true),botToken:g.string().describe("Slack Bot Token (xoxb-*)"),appToken:g.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:g.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:g.number().int().positive().optional().default(100),timeout:g.number().int().positive().optional().default(3e4)}),ze=g.object({enabled:g.boolean().default(true),appId:g.string().describe("Feishu App ID"),appSecret:g.string().describe("Feishu App Secret"),encryptKey:g.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:g.string().optional().describe("Feishu Verification Token"),maxConnections:g.number().int().positive().optional().default(100),timeout:g.number().int().positive().optional().default(3e4)}),je=g.object({enabled:g.boolean().default(true),mode:g.enum(["official","wecom"]).default("official"),appId:g.string().describe("WeChat App ID"),appSecret:g.string().describe("WeChat App Secret"),token:g.string().optional().describe("WeChat Token for message verification"),encodingAESKey:g.string().optional().describe("WeChat Encoding AES Key"),agentId:g.string().optional().describe("WeCom Agent ID"),maxConnections:g.number().int().positive().optional().default(100),timeout:g.number().int().positive().optional().default(3e4)}),qe=g.object({enabled:g.boolean().default(true),path:g.string().optional().default("/"),heartbeatInterval:g.number().int().positive().optional().default(3e4),connectionTimeout:g.number().int().positive().optional().default(36e5),maxConnections:g.number().int().positive().optional().default(1e3),cors:g.boolean().optional().default(true)}),Ke=g.object({enabled:g.boolean().default(true),serviceUrl:g.string().optional().default("https://chat.signal.org"),phoneNumber:g.string().describe("Signal phone number"),password:g.string().optional().describe("Signal account password"),maxConnections:g.number().int().positive().optional().default(100),timeout:g.number().int().positive().optional().default(3e4)}),Ve=g.object({enabled:g.boolean().default(true),relays:g.array(g.string()).min(1).describe("Nostr relay URLs"),privateKey:g.string().optional().describe("Nostr private key (hex)"),publicKey:g.string().optional().describe("Nostr public key (hex)"),maxConnections:g.number().int().positive().optional().default(100),timeout:g.number().int().positive().optional().default(3e4)}),ps=g.object({enabled:g.boolean().default(true),appKey:g.string().describe("DingTalk AppKey"),appSecret:g.string().describe("DingTalk AppSecret"),token:g.string().optional().describe("DingTalk token for signature verification"),encryptKey:g.string().optional().describe("DingTalk encrypt key for message encryption"),webhook:g.object({enabled:g.boolean().default(true),path:g.string().optional().default("/dingtalk/webhook"),port:g.number().int().positive().optional().describe("Webhook server port")}).optional(),maxConnections:g.number().int().positive().optional().default(100),timeout:g.number().int().positive().optional().default(3e4)}),_t=g.object({telegram:He.optional(),slack:We.optional(),feishu:ze.optional(),wechat:je.optional(),webchat:qe.optional(),signal:Ke.optional(),nostr:Ve.optional(),dingtalk:ps.optional()}),Dt=g.object({enabled:g.boolean().default(false),cert:g.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:g.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:g.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:g.string().optional().describe("Path to SSL key file (alias of key)"),ca:g.string().optional().describe("Path to CA certificate file"),forceRedirect:g.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:g.number().int().positive().optional().default(80).describe("HTTP redirect port")}),hs=g.object({name:g.string().describe("Token name/description"),value:g.string().describe("Token value"),permissions:g.array(g.string()).default(["*"]).describe("Associated permissions"),expiresAt:g.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:g.string().optional().describe("Token description")}),ms=g.object({enabled:g.boolean().default(true),tokens:g.array(hs).default([]).describe("List of valid tokens"),onInvalid:g.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:g.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:g.array(g.string()).default([]).describe("Default permissions for anonymous users")}),fs=g.object({enabled:g.boolean().default(false),authorizationServer:g.string().describe("OAuth2 authorization server URL"),clientId:g.string().describe("OAuth2 client ID"),clientSecret:g.string().describe("OAuth2 client secret"),tokenValidationEndpoint:g.string().describe("OAuth2 token validation endpoint"),scope:g.array(g.string()).default([]).describe("OAuth2 scopes")}),Nt=g.object({type:g.enum(["token","oauth2"]).default("token"),token:ms.optional(),oauth2:fs.optional()}),Gt=g.object({mode:g.enum(["pull","push","both"]).default("both"),interval:g.number().int().positive().default(3e4),pushEvents:g.array(g.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:g.enum(["latest","local","remote"]).default("latest")}),ys=g.object({id:g.string().describe("Gateway node ID"),address:g.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:g.boolean().default(true),metadata:g.record(g.string(),g.any()).optional()}),Lt=g.object({nodeId:g.string().describe("Current gateway node ID"),nodes:g.array(ys).default([]).describe("Other gateway nodes in the cluster"),sync:Gt.optional()}),Je=g.object({maxConnectionsPerChannel:g.number().int().positive().default(100),idleTimeout:g.number().int().positive().default(3e5),reuseStrategy:g.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:g.number().int().positive().default(6e4),acquireTimeout:g.number().int().positive().default(5e3),warmupCount:g.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),Qe=g.object({maxLength:g.number().int().positive().default(1e4),concurrency:g.number().int().positive().default(100),batchSize:g.number().int().positive().default(10),batchTimeout:g.number().int().positive().default(100),priorityLevels:g.number().int().positive().default(4)}),Ye=g.object({failureThreshold:g.number().int().positive().default(5),successThreshold:g.number().int().positive().default(3),timeout:g.number().int().positive().default(3e4),halfOpenDuration:g.number().int().positive().default(15e3)}),Xe=g.object({heartbeatInterval:g.number().int().positive().default(6e4),heartbeatTimeout:g.number().int().positive().default(3e5),heartbeatCheckInterval:g.number().int().positive().default(3e5),autoDeregisterTimeout:g.number().int().positive().default(6e5),maxAgents:g.number().int().positive().default(100),persistenceFile:g.string().optional().describe("Path to persist agent registrations"),maxRegistrations:g.number().int().positive().default(1e3)}),Ze=g.object({sessionTimeout:g.number().int().positive().default(18e5),resumeGracePeriod:g.number().int().positive().default(3e5),maxSessions:g.number().int().positive().default(1e4),persistenceFile:g.string().optional().describe("Path to persist sessions")}),et=g.object({enabled:g.boolean().default(true),port:g.number().int().positive().default(8080),hostname:g.string().default("localhost"),path:g.string().optional().default("/"),maxConnections:g.number().int().positive().optional().default(1e3),connectionTimeout:g.number().int().positive().optional().default(36e5),heartbeatInterval:g.number().int().positive().optional().default(3e4),sessionExpireMs:g.number().int().positive().optional().default(36e5),https:Dt.optional(),auth:Nt.optional(),cors:g.boolean().default(true),corsOrigins:g.array(g.string()).optional(),mdns:g.boolean().default(false),mdnsDomain:g.string().optional().default("gateway.easbot.local")}),bs=g.object({channel:g.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:g.array(g.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),Ss=g.enum(["localAgent","subAgent","both"]),Cs=g.object({mode:Ss.default("localAgent").describe("Agent processing mode: localAgent, subAgent, or both"),localAgentPriority:g.number().int().min(1).max(10).default(1).describe("Priority for localAgent (lower = higher priority)"),subAgentPriority:g.number().int().min(1).max(10).default(2).describe("Priority for subAgent (lower = higher priority)"),timeout:g.number().int().positive().optional().default(3e5).describe("Timeout for agent execution in milliseconds"),retryOnFailure:g.boolean().default(true).describe("Retry with subAgent when localAgent fails")}),tt=g.object({autoRegister:g.boolean().default(true).describe("Whether to auto-register agent on startup"),heartbeatInterval:g.number().int().positive().default(3e4).describe("Heartbeat interval in milliseconds"),maxReconnectAttempts:g.number().int().min(0).default(5).describe("Maximum reconnect attempts"),reconnectDelay:g.number().int().positive().default(3e3).describe("Reconnect delay in milliseconds"),heartbeatTimeout:g.number().int().positive().default(9e4).describe("Heartbeat timeout in milliseconds")}),$e=g.object({server:et.optional(),channels:_t.optional(),cluster:Lt.optional(),connectionPool:Je.optional(),messageQueue:Qe.optional(),circuitBreaker:Ye.optional(),agentRegistry:Xe.optional(),session:Ze.optional(),defaults:bs.optional(),agentProcessing:Cs.optional(),client:tt.optional().describe("Gateway client config for agent registration"),defaultAgent:g.string().optional().describe("Default agent ID for routing"),logLevel:g.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(g.unknown());function ft(d){let t=$e.safeParse(d);return t.success||us.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:$e.parse({})}function ws(d){return $e.parse(d)}var T=b.create({service:"sdk-event-bus"}),st=(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))(st||{});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(),update:z$1.record(z$1.string(),z$1.any()),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 ue=class{constructor(){a(this,"subscriptions",new Map);a(this,"wildcardSubscriptions",new Set);a(this,"destroyed",false);}subscribe(t,e){if(this.destroyed)return T.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{};let s=this.subscriptions.get(t)??new Set;return s.add(e),this.subscriptions.set(t,s),T.debug("Subscribed to event",{eventType:t}),()=>{s.delete(e),s.size===0&&this.subscriptions.delete(t),T.debug("Unsubscribed from event",{eventType:t});}}subscribeAll(t){return this.destroyed?(T.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{}):(this.wildcardSubscriptions.add(t),T.debug("Subscribed to all events"),()=>{this.wildcardSubscriptions.delete(t),T.debug("Unsubscribed from all events");})}async publish(t){if(this.destroyed){T.warn("Cannot publish to destroyed SdkEventBus",{type:t.type});return}T.debug("Publishing event",{type:t.type});let e=[],s=this.subscriptions.get(t.type);if(s&&e.push(...s),e.push(...this.wildcardSubscriptions),e.length===0){T.debug("No subscribers for event",{type:t.type});return}let n=await Promise.allSettled(e.map(async a=>{try{await a(t);}catch(o){throw T.error("Event callback error",{type:t.type,error:o instanceof Error?o.message:String(o)}),o}})),i=n.filter(a=>a.status==="fulfilled").length,r=n.filter(a=>a.status==="rejected").length;r>0?T.warn("Event callbacks completed with errors",{type:t.type,fulfilled:i,rejected:r}):T.debug("Event callbacks completed",{type:t.type,count:i});}publishSync(t){if(this.destroyed)return;let e=[],s=this.subscriptions.get(t.type);s&&e.push(...s),e.push(...this.wildcardSubscriptions);for(let n of e)Promise.resolve().then(()=>n(t)).catch(i=>{T.error("Event callback error (sync)",{type:t.type,error:i instanceof Error?i.message:String(i)});});}subscriberCount(t){return t?this.subscriptions.get(t)?.size??0:this.wildcardSubscriptions.size}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(),T.debug("All subscriptions cleared");}destroy(){this.clear(),this.destroyed=true,T.info("SdkEventBus destroyed");}isDestroyed(){return this.destroyed}};var x=b.create({service:"sdk-event-bridge"}),vs={Info:z$1.object({id:z$1.string(),content:z$1.string(),status:z$1.enum(["in_progress","pending","completed","cancelled"]),priority:z$1.enum(["high","medium","low"])})},pe=class{constructor(t,e,s){a(this,"sdk");a(this,"sdkEventBus");a(this,"abortController",null);a(this,"started",false);a(this,"sessionFilter");this.sdk=t,this.sdkEventBus=e,this.sessionFilter=s;}async pushEvent(t,e){this.sessionFilter&&!this.sessionFilter(t)||await this.sdkEventBus?.publish({type:"sdk.session_update",properties:{sessionId:t,update:e,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,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)||(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.sdk.session.message({sessionId:e.sessionId,messageId:e.messageId},{throwOnError:true}).then(i=>i.data).catch(i=>{x.error("unexpected error when fetching message",{error:i});});!n||n.info.role!=="assistant"||(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=Is(n);switch(i.status){case "pending":{let a={sessionUpdate:"tool_call",toolCallId:s,title:n,kind:r,status:"pending",locations:[],rawInput:{}};await this.pushEvent(e,a);break}case "running":{let a={sessionUpdate:"tool_call_update",toolCallId:s,status:"in_progress",kind:r,title:n,locations:As(n,i.input),rawInput:i.input};await this.pushEvent(e,a);break}case "completed":{let a=[{type:"content",content:{type:"text",text:i.output}}];if(r==="edit"){let l=i.input,u=l.filePath??"",p=l.oldString??"",h=l.newString??l.content??"";a.push({type:"diff",path:u,oldText:p,newText:h});}if(n==="todo"){let l=Ps(i.output);if(l&&i.input.operation==="write"){let u={sessionUpdate:"plan",entries:l.map(p=>({priority:"medium",status:p.status==="cancelled"?"completed":p.status,content:p.content}))};await this.pushEvent(e,u);}}let o={sessionUpdate:"tool_call_update",toolCallId:s,status:"completed",kind:r,content:a,title:i.title??n,rawInput:i.input,rawOutput:{output:i.output,metadata:i.metadata}};await this.pushEvent(e,o);break}case "error":{let a={sessionUpdate:"tool_call_update",toolCallId:s,status:"failed",kind:r,title:n,rawInput:i.input,content:[{type:"content",content:{type:"text",text:i.error}}],rawOutput:{error:i.error}};await this.pushEvent(e,a);break}}}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;if(!n)return;let i={sessionUpdate:"agent_message_chunk",content:{type:"text",text:n},messageId:t.messageId,time:t.time};await this.pushEvent(t.sessionId,i);}async handleStepStartPart(t){let e={sessionUpdate:"step_start",messageId:t.messageId};await this.pushEvent(t.sessionId,e);}async handleStepFinishPart(t){let e={sessionUpdate:"step_finish",messageId:t.messageId};t.tokens&&(e.tokens=t.tokens),t.cost&&(e.cost=t.cost),await this.pushEvent(t.sessionId,e);}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;if(!n)return;let i={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n},messageId:t.messageId,time:t.time};await this.pushEvent(t.sessionId,i);}async handleSessionStatus(t){let{sessionId:e,status:s}=t,n={sessionUpdate:"status_update",status:s};await this.sdkEventBus?.publish({type:"sdk.session_update",properties:{sessionId:e,update:n,timestamp:Date.now()}}),x.debug("Session status update sent",{sessionId:e,status:s.type});}};function Is(d){switch(d.toLowerCase()){case "bash":return "execute";case "webfetch":return "fetch";case "edit":case "patch":case "write":return "edit";case "grep":case "glob":case "context7_resolve_library_id":case "context7_get_library_docs":return "search";case "list":case "read":return "read";default:return "other"}}function As(d,t){if(!t)return [];switch(d.toLowerCase()){case "read":case "edit":case "write":return t.filePath?[{path:t.filePath}]:[];case "glob":case "grep":return t.path?[{path:t.path}]:[];case "bash":return [];case "list":return t.path?[{path:t.path}]:[];default:return []}}function Ps(d){try{let t=JSON.parse(d),e=z$1.array(vs.Info).safeParse(t);return e.success?e.data:null}catch{return null}}var nt=b.create({service:"sdk-message-collector"}),Ft={includeThinking:false,includeToolDetails:false,includeToolOutput:false,includeSteps:false},Ms={includeThinking:true,includeToolDetails:true,includeToolOutput:true,includeSteps:true},he=class{constructor(t=Ft){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","");nt.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;e&&e.type==="text"&&e.time?.end&&(this.hasTextEnd=true,e.messageId&&(this.messageId=e.messageId));}if(t.type==="session.status"){let e=t.properties.status?.type;(e==="idle"||e==="busy"||e==="retry")&&(this.sessionStatus=e);}if(t.type==="session.error"&&(this.sessionStatus="error",t.properties.error?.data?.message&&(this.error=t.properties.error.data.message)),t.type==="part.updated"){let e=t.properties.part;e?.type==="step-finish"&&(this.hasStepFinish=true,e.messageId&&(this.messageId=e.messageId));}}checkComplete(){return this.isComplete=!!this.error||this.hasTextEnd&&this.hasStepFinish,this.isComplete&&nt.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=[];}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(o=>o.type==="part.updated"&&o.properties.part?.type==="reasoning"&&o.properties.part?.time?.end).map(o=>{let l=o.properties.part.text??"";return l=l.replace("[REDACTED]","").trim(),l}).filter(o=>o.length>0).join("");a&&(e=a);}let s;if(this.filterConfig.includeToolDetails){let a=this.events.filter(o=>o.type==="part.updated"&&o.properties.part?.type==="tool"&&(o.properties.part?.state?.status==="completed"||o.properties.part?.state?.status==="error"));a.length>0&&(s=a.map(o=>{let l=o.properties.part,u=l.state;return {name:l.tool,status:u.status,output:this.filterConfig.includeToolOutput?u.output:void 0,error:u.error}}));}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 nt.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="",nt.debug("MessageEventCollector.reset",{hasTextEnd:false,hasStepFinish:false});}};var N=class extends Error{constructor(e,s,n){super(e,{cause:n});a(this,"code",s);this.name="GatewayAgentError";}},me=class{constructor(t,e={}){a(this,"sdk",t);a(this,"log",b.create({service:"gateway:agent"}));a(this,"config");a(this,"filterConfig");a(this,"sessionId");a(this,"collector");a(this,"eventBus");a(this,"eventBridge");a(this,"bridgeStarted",false);a(this,"commandListCache",null);a(this,"commandListCacheTime",0);a(this,"COMMAND_LIST_CACHE_TTL",18e5);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.collector=new he(this.filterConfig),this.eventBus=new ue,this.eventBridge=new pe(t,this.eventBus);}async getCommandList(){let t=Date.now();if(this.commandListCache&&t-this.commandListCacheTime<this.COMMAND_LIST_CACHE_TTL)return this.commandListCache;try{let e=await this.sdk.command.list({});return this.commandListCache=e.data??[],this.commandListCacheTime=t,this.commandListCache}catch(e){return this.log.warn("Failed to get command list",{error:String(e)}),[]}}async getCommandPart(t){let e=t.parts?.find(i=>i.type==="command");if(!e)return;let n=(await this.getCommandList()).find(i=>i.name===e.command);return {...e,local:n?.commandType==="local"}}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):this.runPrompt(t)}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 N("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 N(s instanceof Error?s.message:String(s),"COMMAND_ERROR",s instanceof Error?s:void 0)}}async runPromptCommand(t,e){this.log.debug("GatewayAgent.runPromptCommand: starting",{command:e.command,arguments:e.arguments});try{let s=await this.ensureSession(t.source);if(!s)throw new N("Failed to create or get session","NO_SESSION");this.collector.reset(),this.collector.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=!0);let n=()=>{},i=new Promise(a=>{let o=null,l=()=>{o&&clearTimeout(o);};o=setTimeout(()=>{this.log.warn("runPromptCommand: event collection timeout, returning partial result"),n(),l(),a(this.collector.assembleMessage());},12e4),n=this.eventBus.subscribeAll(u=>{if(u.type==="sdk.session_update"){let p=u.properties;if(p.sessionId!==s)return;let h=this.convertUpdateToSessionEvent(p.update,s);h&&(this.collector.addEvent(h),this.collector.checkComplete()&&(l(),n(),a(this.collector.assembleMessage())));}});});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});let r=await i;return n(),this.log.debug("GatewayAgent.runPromptCommand: completed",{sessionId:s,command:e.command}),this.assembleResult(r,s,t)}catch(s){throw this.log.error("GatewayAgent.runPromptCommand: failed",{error:s instanceof Error?s.message:String(s)}),new N(s instanceof Error?s.message:String(s),"COMMAND_ERROR",s instanceof Error?s:void 0)}}async runPrompt(t){this.log.debug("GatewayAgent.runPrompt: starting",{source:t.source,agent:t.agent});try{let e=await this.ensureSession(t.source);if(!e)throw new N("Failed to create or get session","NO_SESSION");let s=await this.sendAndCollect(e,t);return this.log.debug("GatewayAgent.runPrompt: completed",{sessionId:e,outputLength:s.output.length}),s}catch(e){throw this.log.error("GatewayAgent.runPrompt: failed",{error:e instanceof Error?e.message:String(e)}),e instanceof N?e:new N(e instanceof Error?e.message:String(e),"EXECUTION_ERROR",e instanceof Error?e: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 N("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){let s=[];for(let a of e.parts??[])if(a.type==="text")s.push({type:"text",text:a.text??""});else if(a.type==="image"){let o="";typeof a.image=="string"?o=a.image:a.image instanceof URL?o=a.image.toString():a.image instanceof Uint8Array&&(o=`data:${a.mime??"image/png"};base64,${Buffer.from(a.image).toString("base64")}`),s.push({type:"file",url:o,mime:a.mime??"image/png"});}else if(a.type==="file"){let o="";typeof a.data=="string"?o=a.data:a.data instanceof URL?o=a.data.toString():a.data instanceof Uint8Array&&(o=`data:${a.mime??"application/octet-stream"};base64,${Buffer.from(a.data).toString("base64")}`),s.push({type:"file",url:o,mime:a.mime??"application/octet-stream"});}s.length===0&&s.push({type:"text",text:""}),this.collector.reset(),this.collector.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=true);let n=()=>{},i=new Promise(a=>{let o=null,l=()=>{o&&clearTimeout(o);};o=setTimeout(()=>{this.log.warn("Event collection timeout, returning partial result"),l(),n(),a(this.collector.assembleMessage());},12e4),n=this.eventBus.subscribeAll(u=>{if(u.type==="sdk.session_update"){let p=u.properties;if(p.sessionId!==t)return;let h=this.convertUpdateToSessionEvent(p.update,t);h&&(this.collector.addEvent(h),this.collector.checkComplete()&&(l(),n(),a(this.collector.assembleMessage())));}});});await this.sdk.session.prompt({sessionId:t,parts:s,system:e.system,agent:e.agent,model:e.model?{providerId:e.model.providerId,modelId:e.model.modelId}:void 0});let r=await i;return n(),this.assembleResult(r,t,e)}convertUpdateToSessionEvent(t,e){switch(t.sessionUpdate){case "agent_message_chunk":{let n=t.content,i=t.messageId,r=t.time;return !n||n.type!=="text"?null:{type:"part.updated",properties:{sessionId:e,part:{type:"text",text:n.text,messageId:i,time:r??{start:Date.now(),end:Date.now()}}}}}case "agent_thought_chunk":{let n=t.content,i=t.messageId,r=t.time;return !n||n.type!=="text"?null:{type:"part.updated",properties:{sessionId:e,part:{type:"reasoning",text:n.text,messageId:i,time:r??{start:Date.now(),end:Date.now()}}}}}case "step_start":{let n=t.messageId;return {type:"part.updated",properties:{sessionId:e,part:{type:"step-start",messageId:n}}}}case "step_finish":{let n=t.messageId,i=t.tokens;t.cost;return {type:"part.updated",properties:{sessionId:e,part:{type:"step-finish",messageId:n,tokens:i}}}}case "tool_call_update":{let n=t.toolCallId,i=t.status;t.kind;let a=t.title,o=t.content,l=t.rawInput;t.rawOutput;let p;return i==="completed"?p={status:"completed",output:o?.[0]?.content?.text??"",input:l??{}}:i==="failed"?p={status:"error",error:o?.[0]?.content?.text??"Unknown error",input:l??{}}:i==="in_progress"?p={status:"running",input:l??{}}:p={status:"pending",input:l??{}},{type:"part.updated",properties:{sessionId:e,part:{type:"tool",tool:a,callId:n,state:p,messageId:""}}}}case "status_update":{let n=t.status;return {type:"session.status",properties:{sessionId:e,status:n??{type:"idle"}}}}default:return null}}assembleResult(t,e,s){return {output:this.formatOutput(t),title:s.title??"Gateway Response",metadata:{sessionId:e,source:s.source,agent:s.agent,...t.metadata.tokens?{tokens:t.metadata.tokens}:{}}}}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(`
2
- [Tool: ${s.name}]
3
- ${String(s.output)}
4
- `),s.error&&e.push(`
5
- [Tool Error: ${s.name}]
6
- ${s.error}
7
- `);return e.join(`
8
- `).trim()}getSessionId(){return this.sessionId}resetSession(){this.sessionId=void 0,this.collector.resetForNextMessage();}};var Ut=b.create({service:"gateway:interfaces"}),G;function Mi(d){G=d,d?Ut.debug("Agent adapter registered",{hasSubAgentRunner:!!d.subAgentRunner}):Ut.debug("Agent adapter cleared");}function xi(){return G}function re(){return G!==void 0}function K(){if(!G)throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");return G}var xs={Path:{home:process.env.HOME||process.env.USERPROFILE||"",data:".easbot",cache:".easbot/cache",config:".easbot",state:".easbot/state",log:".easbot/log",bin:".easbot/bin"}},ks={directory:process.cwd(),worktree:process.cwd()};function E(){return G?G.global:xs}function bt(){return G?G.instance:ks}var yt=null;function Wt(d){yt=d;}async function it(){return yt?yt():null}function Ts(){if(!G?.sdk)throw new Error("SDK not available. Agent adapter is not set or has no SDK.");return G.sdk}function zt(d){let t=Ts();return new me(t,d)}var O=b.create({service:"gateway:config"}),at={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}},_s={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},Ds={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},Ns={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},Gs={heartbeatInterval:6e4,heartbeatTimeout:3e5,heartbeatCheckInterval:3e5,autoDeregisterTimeout:6e5,maxAgents:100,maxRegistrations:1e3},Ls={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e3},Fs={enabled:true,botToken:"",maxConnections:100,timeout:3e4,polling:{enabled:true,timeout:30}},Us={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Os={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},Bs={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},$s={enabled:true,path:"/ws",heartbeatInterval:6e4,connectionTimeout:36e5,maxConnections:1e3,cors:true},Hs={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},Ws={enabled:true,relays:[],maxConnections:100,timeout:3e4},fe,ye=null;async function jt(d){try{if(!existsSync(d))return null;let t=await L__default.readFile(d,"utf-8");t=t.replace(/\{env:([^}]+)\}/g,(r,a)=>{let o=process.env[a];return o===void 0?(O.debug("Environment variable not found",{varName:a,file:d}),""):o});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]!==`
9
- `&&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 O.debug("Failed to load config file",{file:d,error:String(t)}),null}}function rt(d,t){let e={...d,...t};return (d.server||t.server)&&(e.server={...d.server,...t.server}),(d.channels||t.channels)&&(e.channels={...d.channels,...t.channels}),e}async function zs(){let d=E(),t=bt(),e=[],s=ae__default.join(d.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{O.debug("Filesystem utils not available, using basic directories");}let n=process.env.EASBOT_CONFIG_DIR;return n&&(e.push(n),O.debug("Using EASBOT_CONFIG_DIR",{path:n})),[...new Set(e)]}async function js(d){let t=["gateway.json"],e={};for(let s of t){let n=ae__default.join(d,s),i=await jt(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=rt(e,{server:a,channels:r.channels}),O.debug("Loaded gateway config from file",{file:n});}else "gateway"in i||(e=rt(e,i),O.debug("Loaded gateway config from file (direct format)",{file:n}));}return e}async function qs(d){let t=["easbot.json"];for(let e of t){let s=ae__default.join(d,e),n=await jt(s);if(n?.gateway)return O.debug("Loaded gateway config from easbot.json",{file:s}),n.gateway}return {}}function Ks(){return fe||(fe=async()=>{let d=await zs(),t={};for(let s of d){let n=await js(s);t=rt(t,n);let i=await qs(s);t=rt(t,i);}let e=ft(t);return ye=e,O.info("Gateway config loaded",{directories:d.length,port:e.server?.port,logLevel:e.logLevel}),{config:e,directories:d}}),fe}async function k(){return Ks()()}async function Ot(d){return d&&(fe=void 0,ye=null),(await k()).config}function Bt(){return ye}function $t(){return ye!==null}function Vs(){fe=void 0,ye=null,O.debug("Config cache cleared");}function Js(){return bt().directory}async function Qs(){let{config:d}=await k();return et.parse({...at,...d.server})}async function Ys(d){let{config:t}=await k(),e=t.channels?.[d],n={telegram:He.parse(Fs),slack:We.parse(Us),feishu:ze.parse(Os),wechat:je.parse(Bs),webchat:qe.parse($s),signal:Ke.parse(Hs),nostr:Ve.parse(Ws)}[d];if(!n)throw new Error(`Unknown channel type: ${d}`);return {...n,...e}}async function Xs(){let{config:d}=await k();return Je.parse({..._s,...d.connectionPool})}async function Zs(){let{config:d}=await k();return Qe.parse({...Ds,...d.messageQueue})}async function en(){let{config:d}=await k();return Ye.parse({...Ns,...d.circuitBreaker})}async function tn(){let{config:d}=await k();return Xe.parse({...Gs,...d.agentRegistry})}async function sn(){let{config:d}=await k();return Ze.parse({...Ls,...d.session})}async function nn(){let{config:d}=await k();if(d.client)return tt.parse(d.client)}async function rn(){let{config:d}=await k();if(!(d.client?.autoRegister??true))return;let e=d.server,s=e?.hostname??"localhost",n=e?.port??8080,i=e?.path||"/acp";return `ws://${s}:${n}${i}`}async function an(){let{config:d}=await k();return d.server?.https}async function on(){let{config:d}=await k();return d.server?.auth}async function cn(){let{config:d}=await k();return d.cluster}async function ln(){let{config:d}=await k();return d.defaultAgent}async function Ht(){let{config:d}=await k();return d.logLevel??"INFO"}var Ct=at,be={maxConnections:1e3,connectionTimeout:36e5};var dn={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var ot={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 gn={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var B=class d 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,d);}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 d)return e.recoverable;let s=e.code;return ["ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH"].includes(s??"")}};function f(d,t,e,s=true){return new B(e,{code:t,recoverable:s,details:{channelId:d}})}var lt=class{constructor(t,e){a(this,"log",b.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=mt(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 Se=class{constructor(t={}){a(this,"log",b.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 L.readdir(this.storagePath,{withFileTypes:!0});for(let s of e){if(!s.isDirectory())continue;let n=ae.join(this.storagePath,s.name),i=await L.readdir(n);for(let r of i)if(r.endsWith(".json"))try{let a=ae.join(n,r),o=await L.readFile(a,"utf-8"),l=JSON.parse(o);l.status!=="completed"&&l.status!=="delivered"&&(this.messages.has(l.message.id)||(this.messages.set(l.message.id,l),this.addToSessionMessages(l.message.sessionId,l.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 L.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 ae.join(this.storagePath,`${this.sanitizeFileName(t)}.json`)}getSessionDir(t){return ae.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=ae.join(e,`${this.sanitizeFileName(t.message.id)}.json`);await L.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 Ce=class{constructor(t={}){a(this,"log",b.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 X.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(!X.existsSync(t)){this.log.debug("no saved sessions found");return}let e=await X.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 ae.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){X.existsSync(this.config.storagePath)||await X.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 un="./data/gateway",pn="contacts",hn="index.json",we=class{constructor(t={}){a(this,"log",b.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??un,this.contactDir=ae.join(this.baseDir,pn),this.indexPath=ae.join(this.contactDir,hn),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 L.mkdir(t,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async loadIndex(){try{let t=await L.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 L.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=Be(t);if(e){let s=this.getFilePath(e.platform,e.stableId);this.indexFileMap[t]=s;}}}getFilePath(t,e){let s=this.sanitizeFilename(e);return ae.join(this.contactDir,t,`${s}.json`)}sanitizeFilename(t){return t.replace(/[/\\:*?"<>|]/g,"_")}getPlatformDir(t){return ae.join(this.contactDir,t)}async save(t){let{platform:e,stableId:s,uid:n}=t,i=this.getFilePath(e,s);return await this.ensureDir(ae.dirname(i)),await L.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=ht(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=Be(t);return e?this.findByPlatformId(e.platform,e.stableId):null}async findByPlatformId(t,e){let s=Oe(t,e),n=this.index.byUid[s];if(n)try{let r=await L.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 L.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 L.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 o of r){let l=await this.findByUid(o);l&&a.push(l);}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 o=await this.listByPlatform(t.platform,t.limit,t.offset),l=o.contacts;if(t.username){let u=t.username.toLowerCase();l=l.filter(p=>p.profile.username?.toLowerCase().includes(u));}if(t.email){let u=t.email.toLowerCase();l=l.filter(p=>p.profile.email?.toLowerCase().includes(u));}if(t.phone){let u=t.phone.replace(/\s/g,"");l=l.filter(p=>p.profile.phone?.replace(/\s/g,"").includes(u));}return {contacts:l,total:o.total,hasMore:o.hasMore}}let e=[];for(let o of Object.keys(this.index.byPlatform)){let l=await this.listByPlatform(o,1e3,0);e.push(...l.contacts);}let s=e;if(t.username){let o=t.username.toLowerCase();s=s.filter(l=>l.profile.username?.toLowerCase().includes(o));}if(t.email){let o=t.email.toLowerCase();s=s.filter(l=>l.profile.email?.toLowerCase().includes(o));}if(t.phone){let o=t.phone.replace(/\s/g,"");s=s.filter(l=>l.profile.phone?.replace(/\s/g,"").includes(o));}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 wt=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}},ve=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 wt(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 U=b.create({service:"gateway:storage:agent-registry"}),Ie=class{constructor(t){a(this,"config");a(this,"filePath");a(this,"cache",new Map);a(this,"initialized",false);this.config=t,this.filePath=ae.join(t.dataDir,"agent-registry.json");}async initialize(){if(!this.initialized)try{await L.mkdir(this.config.dataDir,{recursive:!0}),this.initialized=!0,U.debug("Agent registry store initialized",{dataDir:this.config.dataDir});}catch(t){throw U.error("Failed to initialize agent registry store",{dataDir:this.config.dataDir,error:String(t)}),t}}async loadFromDisk(){await this.initialize();try{let t=await L.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 U.debug("Agent registry loaded from disk",{count:s.size}),s}catch(t){return t.code==="ENOENT"?(U.debug("Agent registry file not found, starting fresh"),new Map):(U.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 L.writeFile(this.filePath,JSON.stringify(t,null,2),"utf-8"),U.debug("Agent registry saved to disk",{count:this.cache.size});}catch(t){throw U.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(),U.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(),U.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(),U.debug("Agent registration deleted",{agentId:t}));}getFilePath(){return this.filePath}};var Ae=class{constructor(t={}){a(this,"log",b.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 Ce({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=Fe(t),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),n):(n={id:s,channel:t,backendSessionId:null,subscribers:new Set,state:Ue(),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=Fe(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:Ue(),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 Pe=class{constructor(t={}){a(this,"log",b.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 B(`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 B("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 z=class extends Error{constructor(e,s,n){super(e);a(this,"code",s);a(this,"configuredChannels",n);this.name="ChannelSelectionError";}},W=b.create({service:"gateway:channel-selection"});function ce(d){if(!(!d||typeof d!="string"))return d.toLowerCase().trim()}async function At(d){let{channel:t,sessionId:e,userId:s,defaultChannel:n,fallbackChannels:i,sessionManager:r,pluginLoader:a,contactStore:o}=d,l=ce(t);if(l){let m=vt(l,a);if(m){if(e){let w=It(e,r);if(w){if(w.channelInfo.chatId||w.channelInfo.userId)return W.debug("enriching explicit channel with session info",{sessionId:e,chatId:w.channelInfo.chatId,userId:w.channelInfo.userId}),{...m,channelInfo:{...m.channelInfo,chatId:w.channelInfo.chatId,userId:w.channelInfo.userId}}}else if(s&&r){W.debug("session not found, creating new session for private chat",{userId:s});let _=s,q={platform:m.channelInfo.platform,channelId:m.channel,chatId:_,userId:s};try{let Y=await r.getOrCreate(q);return W.debug("auto-created session for private chat",{sessionId:Y.id,chatId:_,userId:s}),{channel:m.channel,source:"session-bound",channelInfo:Y.channel}}catch(Y){W.warn("failed to auto-create session, using explicit channel info",{userId:s,error:String(Y)});}}}if(s&&o){let w=await mn(l,s,o,a);if(w)return w}return m}if(e){let w=It(e,r);if(w){if((!w.channelInfo.chatId||!w.channelInfo.userId)&&w.channelInfo.platform!=="api"){let q=yn(w.channelInfo.platform,r);if(q)return W.debug("session missing chatId/userId, using session with complete info",{originalSessionId:e,newSessionId:q.channelInfo.chatId}),q}return w}}throw new z(`Channel \u4E0D\u53EF\u7528\u6216\u672A\u914D\u7F6E: ${l}`,"CHANNEL_UNAVAILABLE",[])}if(e){let m=It(e,r);if(m)return m}if(s&&o){let m=await fn(s,o,a);if(m)return m}let u=Pt(a);if(u.length===0)throw new z("\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=ce(n);if(p){let m=vt(p,a);if(m)return W.debug("using default channel",{channel:p}),{...m,source:"default"};W.warn("default channel unavailable",{channel:p});}if(u.length===1){let m=u[0],w=a?.getPlugin(m);return {channel:m,source:"single-configured",channelInfo:{platform:w?.platform,channelId:m}}}let h=(i??[]).map(ce).filter(m=>m!==void 0);for(let m of h){let w=vt(m,a);if(w)return W.debug("using fallback channel",{channel:m}),{...w,source:"fallback"};W.debug("fallback channel unavailable, trying next",{channel:m});}throw p?new z(`\u914D\u7F6E\u7684\u9ED8\u8BA4 Channel \u4E0D\u53EF\u7528: ${p}`,"CHANNEL_UNAVAILABLE",u):new z(`\u9700\u8981\u660E\u786E\u6307\u5B9A Channel\uFF08\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF09: ${u.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",u)}function vt(d,t){if(!t)return null;let e=t.getPlugin(d);if(e&&t.isRunning(d))return {channel:d,source:"explicit",channelInfo:{platform:e.platform,channelId:d}};let s=ce(d);if(!s)return null;let n=t.getAllPlugins();for(let i of n)if(t.isRunning(i.id)&&ce(i.platform)===s)return {channel:i.id,source:"explicit",channelInfo:{platform:i.platform,channelId:i.id}};return null}function It(d,t){if(!t)return null;let e=t.get(d);return e?{channel:e.channel.channelId,source:"session-bound",channelInfo:e.channel}:null}async function mn(d,t,e,s){let n=s?.getPlugin(d);if(!n)return null;let i=await e.findByPlatformId(n.platform,t);return i?{channel:d,source:"explicit",channelInfo:{platform:n.platform,channelId:d,userId:i.stableId,chatId:i.stableId}}:null}async function fn(d,t,e){let s=Pt(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,d);if(r)return {channel:n,source:"single-configured",channelInfo:{platform:i.platform,channelId:n,userId:r.stableId,chatId:r.stableId}}}return null}function Pt(d){if(!d)return [];let t=[],e=d.getAllPlugins();for(let s of e)d.isRunning(s.id)&&t.push(s.id);return t}function Mt(d){switch(d.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: ${d.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 d.message;case "UNKNOWN_CHANNEL":return `\u672A\u77E5\u7684 Channel: ${d.message}\u3002\u8BF7\u68C0\u67E5 Channel ID \u662F\u5426\u6B63\u786E\u3002`;default:return d.message}}function yn(d,t){if(!t)return null;let e=t.getAll?.()??[];for(let s of e)if(s.channel.platform===d&&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===d&&s.channel.chatId)return {channel:s.channel.channelId,source:"session-bound",channelInfo:s.channel};return null}var y=b.create({service:"gateway:websocket-server"});function xt(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function R(d,t){for(let[e,s]of t.entries())if(s===d)return e;return null}var ee=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={...Ct,...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 wn.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){y.warn("WebSocket server is already running");return}y.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){y.error("Error processing WebSocket message",{error:r.message}),this.sendError(i,r.message);}},onClose:(n,i)=>{this.handleDisconnection(i);},onError:(n,i)=>{y.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 y.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";y.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):y.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(t){let e=this.config.https,s=this.loadSSLCertificates(e);if(!s){y.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=Sn.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,t),await new Promise(i=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{y.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:X__default.readFileSync(t.certPath),key:X__default.readFileSync(t.keyPath)}:null}catch(e){return y.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,o=this.config.path||"";(a===o||o===""&&(a==="/"||a===""))&&this.wss.handleUpgrade(s,n,i,l=>{e.onOpen?.({type:"open"},l),l.on("message",u=>{e.onMessage?.({data:u},l);}),l.on("close",(u,p)=>{e.onClose?.({code:u,reason:p},l);}),l.on("error",u=>{e.onError?.({type:"error",message:u.message},l);});});}catch{}});}startHTTPRedirectServer(t){this.httpRedirectServer=Cn.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,()=>{y.info("HTTP redirect server started",{port:t,hostname:this.config.hostname});});}async stop(){if(!this.running){y.warn("WebSocket server is not running");return}y.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,y.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??be.maxConnections)){y.warn("Maximum connections reached, rejecting new connection"),t.close(1013,"Maximum connections reached");return}let e=xt();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()}),y.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=R(t,this.connections);e&&(this.connections.delete(e),await this.cleanupClientResources(e),y.debug("WebSocket client disconnected",{clientId:e,totalConnections:this.connections.size}));}async cleanupClientResources(t){if(y.debug("Cleaning up client resources",{clientId:t}),this.routerRef){try{await this.routerRef.unsubscribeAll(t);}catch{}this.subscribers.delete(t),y.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=R(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=R(t,this.connections);r&&r!==n&&(await this.cleanupClientResources(r),this.connections.delete(r),y.info("Client reconnected with different clientId, cleaned up old resources",{oldClientId:r,newClientId:n})),this.connections.set(n,t);}else n=R(t,this.connections)??xt(),R(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(y.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",o={id:n,type:a,createdAt:Date.now(),lastActiveAt:Date.now(),connection:{send:async l=>{this.sendMessage(t,{type:"message",sessionId:l.sessionId,payload:{id:l.id,type:l.type,content:l.content,metadata:l.metadata,timestamp:l.timestamp}});},close:async()=>{t.close(1e3,"Subscriber closed");},isConnected:()=>t.readyState===t.OPEN}};this.subscribers.set(n,o),await this.routerRef.subscribe(e.sessionId,o),y.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=R(t,this.connections);if(s){if(y.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),y.debug("Subscriber unregistered from router",{clientId:s,sessionId:e.sessionId});}catch(r){y.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";y.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:""}]};y.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 R(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}y.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=R(t,this.connections);if(!s){this.sendError(t,"Client not found");return}if(y.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??be.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){y.debug("Closing inactive connection",{clientId:n,lastActivityAt:this.clientLastActivity.get(n),timeoutMs:e});try{i.close(1001,"Connection timeout");}catch(r){y.debug("Error closing timed out connection",{clientId:n,error:String(r)});}this.connections.delete(n);}}s.length>0&&y.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size});}async cleanupInactiveClients(){let t=Date.now(),e=[],s=this.config.connectionTimeout??be.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){y.debug("Client inactive, closing connection",{clientId:n,lastActivity:this.clientLastActivity.get(n),timeoutMs:s});try{i.close(1001,"Client inactive");}catch(r){y.debug("Error closing inactive client",{clientId:n,error:String(r)});}this.connections.delete(n);}}e.length>0&&y.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 it();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 y.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 y.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"),o=[],u=this.getChannelResolveParams().sessionManager?.getAll?.()??[];for(let h of u){let m=!n||h.channel.platform===n,w=!i||h.channel.channelId===i,_=!r||h.channel.userId===r,q=!a||h.channel.chatId===a;m&&w&&(!r&&!a||_&&q)&&o.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=o.slice(s,s+e);return t.json({sessions:p,total:o.length,hasMore:s+e<o.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&&(y.debug("found gateway session via backendSessionId",{backendSessionId:e,gatewaySessionId:a.id}),i=a.id);}}try{let r=await At({...n,sessionId:i,channel:s.channel,userId:s.userId??s.chatId});y.debug("channel resolved for message",{sessionId:e,channel:r.channel,source:r.source,channelInfo:r.channelInfo});let a=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,o={...r.channelInfo};if(!o.chatId){let p=s.chatId??r.channelInfo.userId;p&&(o.chatId=p,y.debug("filled channelInfo.chatId from request body or session",{chatId:o.chatId}));}if(!o.userId&&o.chatId&&(o.userId=s.userId??o.chatId,y.debug("filled channelInfo.userId from chatId",{userId:o.userId})),!o.chatId)return y.error("channelInfo missing chatId, cannot send message",{sessionId:i,channelInfo:o,body:{userId:s.userId,chatId:s.chatId}}),t.json({error:"channelInfo missing chatId"},400);let l={id:a,sessionId:i,type:"output",content:typeof s.content=="string"?[{type:"text",text:s.content}]:s.content||[],metadata:{channel:o,replyToMessageId:s.replyToMessageId,processorId:s.processorId??"gateway",agent:s.agent??"gateway"},timestamp:Date.now()};if(this.pluginLoaderRef)try{await this.pluginLoaderRef(r.channel,l,{}),y.debug("message sent via pluginLoader",{messageId:a,channel:r.channel});}catch(p){return y.error("failed to send message",{sessionId:i,error:String(p)}),t.json({error:String(p)},500)}else return y.error("no pluginLoader available for sending message",{sessionId:i}),t.json({error:"Plugin loader not available"},500);let u={messageId:a,sessionId:i,createdAt:Date.now(),metadata:{channel:r.channel,channelSource:r.source,channelInfo:r.channelInfo}};return t.status(202),t.json(u)}catch(r){return r instanceof z?(y.warn("channel selection failed",{sessionId:i,error:r.message}),t.json({error:Mt(r),code:r.code},400)):(y.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");y.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();y.debug("messageSubscriptions",{size:a.size,entries:Array.from(a.entries())});for(let[o,l]of a.entries()){if(e&&e!=="agent-list"&&o!==e)continue;let u=new Map;for(let p of l){let h=r.getSubscription(p);if(h){if(s&&h.subscriberId!==s)continue;u.set(h.subscriberId,{id:h.subscriberId,subscriptionId:p});}}u.size>0&&n.push({type:"message",sessionId:o,subscriberCount:u.size,subscribers:Array.from(u.values())});}}if(this.agentSyncRef&&!(e&&e!=="agent-list")){let r=this.agentSyncRef.getSubscribers();y.debug("agentSubscribers",{count:r.length,subscribers:r,filterSubscriberId:s});let a=s?r.filter(o=>o===s):r;y.debug("filteredAgents",{filteredAgents:a}),a.length>0&&n.push({type:"agent",sessionId:"agent-list",subscriberCount:a.length,subscribers:a.map(o=>({id:o,subscriptionId:`agent_sub_${o}`}))});}let i={subscriptions:n,total:n.length};return y.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=R(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=R(t,this.connections);i&&i!==n&&this.connections.delete(i),this.connections.set(n,t);}else n=R(t,this.connections)??xt(),R(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=R(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=R(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentDeregister(s,e.payload);}};var A=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=b.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
- `)}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=K(),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);default:return {handled:false}}}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 it();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)}`}}}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 u=i.status==="running"?"\u{1F7E2}":"\u26AA";if(r.push(`- **Status**: ${u} ${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 o=s.split("_"),l=o.length>=2?`${o[0]}_${o[1]}...`:s;return r.push(`- **Session ID**: \`${l}\``),r.push(`- **Backend Session**: ${n?`\`${n}\``:"\u274C Not Bound"}`),r.push(""),r.push("---"),r.push(`*Report generated: ${new Date().toLocaleString()}*`),r.join(`
11
- `)}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 Me=class extends A{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 f(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw f(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===true&&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 f(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(u=>u.type==="image"),o=e.content.find(u=>u.type==="file"),l;if(a){let u=a.image,p=n||void 0;l=await this.sendPhoto(s,u,p);}else if(o){let u=o.data,p=n||void 0;l=await this.sendDocument(s,u,p);}else try{l=await this.sendApiMessage(s,n,{parseMode:r,replyTo:i?parseInt(i,10):void 0});}catch(u){if(r!=="None"&&this.isParseError(u))this.log.debug("parse error, retrying with plain text",{parseMode:r,error:String(u)}),l=await this.sendApiMessage(s,n,{parseMode:"None",replyTo:i?parseInt(i,10):void 0});else throw u}return this.sentMessages.set(e.id,{chatId:s,messageId:parseInt(l,10),timestamp:Date.now()}),this.sessionIdMap.set(e.id,e.sessionId),l}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 l=await Fetch.post(`${this.baseUrl}/sendPhoto`,{chat_id:e,photo:s,caption:n});if(!l.data.ok)throw new Error(`sendPhoto failed: ${l.data.description||"unknown error"}`);return l.data.result.message_id.toString()}else if(s instanceof URL){let l=await Fetch.post(`${this.baseUrl}/sendPhoto`,{chat_id:e,photo:s.toString(),caption:n});if(!l.data.ok)throw new Error(`sendPhoto failed: ${l.data.description||"unknown error"}`);return l.data.result.message_id.toString()}else a=s;this.log.debug("sendPhoto: calling Fetch.postForm",{url:`${this.baseUrl}/sendPhoto?${i}`,filename:r});let o=await Fetch.postForm(`${this.baseUrl}/sendPhoto?${i}`,[{name:"photo",value:a,filename:r}],{timeout:3e5});if(this.log.debug("sendPhoto: response received",{ok:o.ok,status:o.status,data:o.data}),!o.ok)throw new Error(`sendPhoto failed: ${o.data.description||"unknown error"}`);return o.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 l=await Fetch.post(`${this.baseUrl}/sendDocument`,{chat_id:e,document:s,caption:n});if(!l.data.ok)throw new Error(`sendDocument failed: ${l.data.description||"unknown error"}`);return l.data.result.message_id.toString()}else if(s instanceof URL){let l=await Fetch.post(`${this.baseUrl}/sendDocument`,{chat_id:e,document:s.toString(),caption:n});if(!l.data.ok)throw new Error(`sendDocument failed: ${l.data.description||"unknown error"}`);return l.data.result.message_id.toString()}else a=s;this.log.debug("sendDocument: calling Fetch.postForm",{url:`${this.baseUrl}/sendDocument?${i}`,filename:r});let o=await Fetch.postForm(`${this.baseUrl}/sendDocument?${i}`,[{name:"document",value:a,filename:r}],{timeout:3e5});if(this.log.debug("sendDocument: response received",{ok:o.ok,status:o.status,data:o.data}),!o.ok)throw new Error(`sendDocument failed: ${o.data.description||"unknown error"}`);return o.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??0,s=await this.getUpdates(this.lastUpdateId+1,100,e);for(let n of s)if(this.lastUpdateId=Math.max(this.lastUpdateId,n.update_id),n.message&&await this.handleTelegramMessage(n.message),n.edited_message&&await this.handleTelegramMessage(n.edited_message),n.message_reaction&&await this.handleMessageReaction(n.message_reaction),n.message_reaction_count&&n.message_reaction_count.length>0)for(let i of n.message_reaction_count)await this.handleMessageReactionCount(i);this.retryState.attempts=0;}async handleMessageReaction(e){let s=this.findSentMessageEntry(e.message_id);if(!s)return;let n=s.gatewayMessageId,i=this.sessionIdMap.get(n),a=e.new_reaction.some(o=>o.type==="emoji"&&(o.emoji==="\u{1F441}"||o.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=(e.text??"").split(" "),n=s[0]?.toLowerCase()??"",i=s.slice(1),r=this.buildSessionId(this.id,e.chat.id.toString(),e.from?.id.toString()),a=await this.processLocalCommand(n,r,e.chat.id.toString());if(a.handled&&a.reply)return await this.sendApiMessage(e.chat.id.toString(),a.reply,{parseMode:"Markdown",replyTo:e.message_id}),true;let o=n.replace(/^\//,""),l=await this.getCommandList(),u=new Map;for(let m of l){let w=m.name.replace(/[-_]/g,"").toLowerCase();u.set(w,m.name);}let p=u.get(o)??o;if(l.some(m=>m.name===p)){await this.sendTyping(e.chat.id.toString());let m=M(this.buildSessionId(this.id,e.chat.id.toString(),e.from?.id.toString()),"input",[{type:"command",command:p,arguments:i.join(" ")}],{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()}});return await this.handleMessage(m),true}return false}async toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return M(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 o=Buffer.from(r.data);return await PKG.file(s).write(o),s}async parseContent(e){let s=[],n=e.text??e.caption??"",i=E()?.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 o=`photo_${a.file_unique_id}.jpg`,l=Filesystem.join(r,`${e.chat.id}_${a.file_unique_id}_${o}`);await this.downloadBinaryFile(a.file_id,l),this.log.debug("photo downloaded",{filePath:l,fileId:a.file_id}),s.push({type:"image",image:pathToFileURL(l).href,mime:"image/jpeg"});}catch(o){this.log.warn("failed to download photo, storing as file",{platform:"telegram",fileId:a.file_id,error:String(o)}),s.push({type:"image",image:a.file_id,mime:"image/jpeg"});}}if(e.document){let a=e.document.mime_type||"application/octet-stream",o=e.document.file_name||"file",l=e.document.file_id;if(a.startsWith("text/"))try{this.log.debug("downloading text file",{fileId:l,fileName:o,mimeType:a});let u=await this.parseFileContent(l),p=await TruncateContent.truncate(u,{maxChars:5e3,label:`file: ${o}`});s.push({type:"text",text:`\u{1F4CE} File: ${o}
12
-
13
- ${p.content}`});}catch(u){this.log.warn("failed to download text file, storing as file",{platform:"telegram",fileId:l,error:String(u)}),s.push({type:"file",data:l,mime:a});}else try{let u=o.includes(".")?o.split(".").pop():Filesystem.mimeTypeToExt(a)||"bin",p=`${e.document.file_unique_id||l}.${u}`,h=Filesystem.join(r,`${e.chat.id}_${l}_${p}`);this.log.debug("downloading binary file",{filePath:h,fileId:l,fileName:o,mimeType:a}),await this.downloadBinaryFile(l,h),s.push({type:"file",data:pathToFileURL(h).href,mime:a});}catch(u){this.log.warn("failed to download file, storing as file",{platform:"telegram",fileId:l,error:String(u)}),s.push({type:"file",data:l,mime:a});}}return n&&s.push({type:"text",text:n}),s}buildSessionId(e,s,n){return `telegram_${e}_${s}_${n??s}`}processMessageAndGetSessionId(e){let s=e.chat.id.toString(),n=e.from?.id.toString();return this.buildSessionId(this.id,s,n)}async getMe(){return (await this.request("getMe")).result}async getUpdates(e,s,n){let i={offset:e,limit:s};n>0&&(i.timeout=n);let r=["message","edited_message","channel_post","edited_channel_post","callback_query","message_reaction","message_reaction_count"];return i.allowed_updates=JSON.stringify(r),(await this.request("getUpdates",i)).result||[]}async sendApiMessage(e,s,n){let r=this.getCapabilities().maxMessageLength-500,a=s;if(s.length>r){let u=await TruncateContent.truncate(s,{maxChars:r,label:"telegram message"});a=u.content,this.log.debug("sendApiMessage: message truncated",{originalLength:s.length,maxLength:r,outputPath:u.truncated?u.outputPath:void 0});}let o={chat_id:e,text:a};return n?.parseMode&&n.parseMode!=="None"&&(o.parse_mode=n.parseMode),n?.replyTo&&(o.reply_to_message_id=n.replyTo),n?.replyMarkup&&(o.reply_markup=n.replyMarkup),(await this.request("sendMessage",o)).result.message_id.toString()}async request(e,s={}){let n=`${this.baseUrl}/${e}`,i;for(let r=0;r<=this.retryState.maxAttempts;r++)try{let a=await Fetch.post(n,s,{timeout:this.retryState.maxDelay,retries:0,headers:{"Content-Type":"application/json"},signal:this.abortController?.signal}),o=a.data;if(!o.ok){if(o.error_code===429){this.log.warn("Rate limited, retrying after",{retryAfter:a.headers.get("Retry-After")});let l=parseInt(a.headers.get("Retry-After")??"1",10)*1e3;await this.sleep(l);continue}throw f(this.id,"CHANNEL_CONNECTION_FAILED",`Telegram API error: ${o.description}`,o.error_code!==400&&o.error_code!==401)}return o}catch(a){if(a instanceof B||this.abortController?.signal.aborted)throw a;if(i=a instanceof Error?a:new Error(String(a)),this.log.warn("Request failed, retrying",{method:e,attempt:r+1,error:i.message}),r<this.retryState.maxAttempts){let o=Math.min(this.retryState.initialDelay*2**r,this.retryState.maxDelay);await this.sleep(o);}}throw f(this.id,"CHANNEL_CONNECTION_FAILED",`Failed after ${this.retryState.maxAttempts+1} attempts: ${i?.message}`,true)}async syncBotCommands(){try{let e=[{command:"new",description:"Reset session and start a new conversation"},{command:"status",description:"Show gateway and channel status"}],n=(await this.getCommandList()).filter(o=>o.hidden!==!0);if(this.log.debug("syncBotCommands: commands fetched",{count:n.length,commands:n}),n.length===0&&e.length===0){this.log.debug("no commands available");return}let i=new Map,r=n.map(o=>{let l=o.name.replace(/[-_]/g,"").toLowerCase();return i.set(l,o.name),{command:l,description:o.description||l}}).filter(o=>{let l=/^[a-zA-Z0-9_]{1,32}$/.test(o.command);return l||this.log.debug("syncBotCommands: filtered invalid telegram name",{telegramName:o.command,originalName:i.get(o.command)}),l}).map(o=>{let l=o.description||o.command;return l=l.replace(/<[^>]*>/g,"").replace(/./g,u=>u.charCodeAt(0)<=31||u.charCodeAt(0)===127?"":u).trim(),l.length>250&&(this.log.debug("syncBotCommands: truncating description",{command:o.command,originalLength:l.length}),l=l.substring(0,250)+"..."),{...o,description:l}}),a=[...e,...r];if(a.length===0){this.log.debug("syncBotCommands: no valid commands after filtering");return}this.log.debug("syncBotCommands: setting telegram commands",{allCommands:a}),await this.request("setMyCommands",{commands:a}),this.log.debug("bot commands synced",{count:a.length});}catch(e){this.log.warn("failed to sync bot commands",{error:String(e)});}}};var xe=class extends A{constructor(e="discord-main"){super();a(this,"id");a(this,"platform","discord");a(this,"name","Discord Bot");a(this,"botConfig",null);a(this,"baseUrl","https://discord.com/api/v10");a(this,"gatewayWs",null);a(this,"heartbeatInterval",null);a(this,"sessionId",null);a(this,"sequenceNumber",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,"reconnectAttempts",0);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 f(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw f(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.botConfig.commands)for(let s of this.botConfig.commands)this.commandRouter.set(s.name,s);this.abortController=new AbortController;let e=await this.getCurrentUser();this.log.info("Discord bot connected",{id:e.id,username:e.username}),await this.syncCommands(),this.botConfig.gateway?.enabled!==false&&await this.startGateway();}async doStop(){this.abortController?.abort(),this.abortController=null,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.gatewayWs&&(this.gatewayWs.close(),this.gatewayWs=null),this.processedMessageIds.clear(),this.sentMessages.clear(),this.sessionIdMap.clear(),this.commandRouter.clear(),this.botConfig=null,this.reconnectAttempts=0,this.retryState.attempts=0,this.sessionId=null,this.sequenceNumber=null,this.log.debug("Discord plugin stopped");}async doHealthCheck(){if(this._status!=="running"||this.abortController?.signal.aborted)return false;try{return await this.getCurrentUser(),!0}catch{return false}}async send(e){let s=e.metadata.channel.chatId;if(!s)throw f(this.id,"MESSAGE_SEND_FAILED","Channel ID is required");let n=this.extractText(e),i=e.content.find(l=>l.type==="image"),r=e.content.find(l=>l.type==="file"),a=e.metadata.context?.replyTo,o;return i?o=await this.createMessage(s,n,a):r?o=await this.createMessage(s,n,a):o=await this.createMessage(s,n,a),this.sentMessages.set(e.id,{channelId:s,messageId:o.id,timestamp:Date.now()}),this.sessionIdMap.set(e.id,e.sessionId),o.id}async createMessage(e,s,n){let r=this.getCapabilities().maxMessageLength-500,a=s;if(s.length>r){let l=await TruncateContent.truncate(s,{maxChars:r,label:"discord message"});a=l.content,this.log.debug("createMessage: message truncated",{originalLength:s.length,maxLength:r,outputPath:l.truncated?l.outputPath:void 0});}let o={content:a};return n&&(o.message_reference={message_id:n}),this.request("POST",`/channels/${e}/messages`,o)}async syncCommands(){if(this.commandRouter.size!==0)try{let e=Array.from(this.commandRouter.values()).map(s=>({name:s.name,description:s.description,options:s.options}));await this.request("POST",`/applications/${this.botConfig?.applicationId}/commands`,e),this.log.debug("Bot commands synced",{count:e.length});}catch(e){this.log.warn("Failed to sync bot commands",{error:String(e)});}}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:true,supportsEdit:true,supportsDelete:true,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:true,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:2e3,maxMediaCount:10}}async startGateway(){if(!this.abortController?.signal.aborted)try{let s=`${(await this.getGatewayBot()).url}/?v=10&encoding=json`;this.gatewayWs=new WebSocket(s),this.gatewayWs.onmessage=n=>{this.handleGatewayMessage(JSON.parse(n.data.toString()));},this.gatewayWs.onclose=()=>{if(!this.abortController?.signal.aborted)if(this.log.info("Gateway disconnected"),this.reconnectAttempts<this.maxReconnectAttempts){let n=Math.min(1e3*2**this.reconnectAttempts,3e4);this.reconnectAttempts++,this.log.info("Attempting to reconnect",{attempt:this.reconnectAttempts,delay:n}),setTimeout(()=>this.startGateway(),n);}else this.log.error("Max reconnect attempts reached");},this.gatewayWs.onerror=n=>{this.log.error("Gateway error",{error:String(n)});};}catch(e){throw this.log.error("Failed to start Gateway",{error:String(e)}),e}}handleGatewayMessage(e){switch(this.updateActivity(),e.op){case 10:this.handleHello(e.d);break;case 11:this.log.debug("Heartbeat ACK");break;case 0:e.s&&(this.sequenceNumber=e.s),this.handleDispatch(e.t,e.d);break;case 9:this.log.warn("Invalid session, reconnecting"),this.gatewayWs?.close();break}return Promise.resolve()}handleHello(e){this.heartbeatInterval=setInterval(()=>{this.gatewayWs?.send(JSON.stringify({op:1,d:this.sequenceNumber}));},e.heartbeat_interval),this.gatewayWs?.send(JSON.stringify({op:2,d:{token:this.botConfig?.botToken,intents:this.botConfig?.gateway?.intents??513,properties:{os:"linux",browser:"easbot",device:"easbot"}}}));}handleDispatch(e,s){switch(e){case "MESSAGE_CREATE":this.handleDiscordMessage(s);break;case "MESSAGE_REACTION_ADD":this.handleReactionEvent(s);break}}async handleReactionEvent(e){if(e.emoji.name!=="\u2705"&&e.emoji.name!=="\u{1F440}")return;let s=this.findSentMessageEntry(e.message_id);if(!s)return;let n=s.gatewayMessageId,i=this.sessionIdMap.get(n),a=e.emoji.name==="\u2705"?"message_read":"message_delivered";this.log.debug("message reaction received",{messageId:n,discordMessageId:e.message_id,sessionId:i,eventType:a}),this.messageHandler&&await this.messageHandler.onEvent({type:a,channelId:this.id,data:{id:n,sessionId:i,platform:"discord",channelId:this.id,emoji:e.emoji.name,discordMessageId:e.message_id,userId:e.user_id},timestamp:Date.now()});}findSentMessageEntry(e){for(let[s,n]of this.sentMessages.entries())if(n.messageId===e)return {gatewayMessageId:s,...n}}async handleDiscordMessage(e){if(e.author.bot||this.processedMessageIds.has(e.id))return;if(this.processedMessageIds.add(e.id),this.processedMessageIds.size>1e4){let n=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(n.slice(-5e3));}let s=await this.toGatewayMessage(e);await this.handleMessage(s);}async toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return M(s,"input",await this.parseContent(e),{channel:{platform:"discord",channelId:this.id,userId:e.author.id,chatId:e.channel_id,messageId:e.id,guildId:e.guild_id,username:e.author.username,discriminator:e.author.discriminator},context:{threadId:e.message_reference?.message_id,conversationId:e.channel_id}})}async parseContent(e){let s=[],n=E()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=Filesystem.join(n,"gateway","downloads");e.content&&s.push({type:"text",text:e.content});for(let r of e.attachments)if(r.content_type?.startsWith("image/"))try{let a=r.filename||"image",o=a.includes(".")?a.split(".").pop()??"":"png",l=Filesystem.join(i,`discord_${e.channel_id}_${r.id}.${o}`);await this.downloadFile(r.url,l),s.push({type:"image",image:pathToFileURL(l).href,mime:r.content_type});}catch(a){this.log.warn("failed to download image, storing as URL",{attachmentId:r.id,error:String(a)}),s.push({type:"image",image:r.url,mime:r.content_type});}else try{let a=r.filename||"file",o=a.includes(".")?a.split(".").pop()??"":Filesystem.mimeTypeToExt(r.content_type||"")||"bin",l=Filesystem.join(i,`discord_${e.channel_id}_${r.id}.${o}`);if(r.content_type?.startsWith("text/")){let u=await this.downloadTextFile(r.url),p=await TruncateContent.truncate(u,{maxChars:5e3,label:`file: ${a}`});s.push({type:"text",text:`\u{1F4CE} File: ${a}
14
-
15
- ${p.content}`});}else await this.downloadFile(r.url,l),s.push({type:"file",data:pathToFileURL(l).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 f(this.id,"MESSAGE_SEND_FAILED",`Discord API error: ${JSON.stringify(r.data)}`);return r.data}};var ke=class extends A{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 f(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw f(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 f(this.id,"MESSAGE_SEND_FAILED","Channel ID is required");let n=this.extractText(e),i=e.content.find(l=>l.type==="image"),r=e.content.find(l=>l.type==="file"),a=e.metadata.context?.threadId,o;return i?o=await this.postImage(s,i.image,n,a):r?o=await this.postFile(s,r.data,r.mime,n,a):o=await this.postMessage(s,n,a),this.sentMessages.set(e.id,{channelId:s,ts:o.ts,timestamp:Date.now()}),this.sessionIdMap.set(e.id,e.sessionId),o.ts}async postMessage(e,s,n){let r=this.getCapabilities().maxMessageLength-500,a=s;if(s.length>r){let l=await TruncateContent.truncate(s,{maxChars:r,label:"slack message"});a=l.content,this.log.debug("postMessage: message truncated",{originalLength:s.length,maxLength:r,outputPath:l.truncated?l.outputPath:void 0});}let o={channel:e,text:a};return n&&(o.thread_ts=n),this.request("chat.postMessage",o)}async postImage(e,s,n,i){let r;if(typeof s=="string")if(s.startsWith("http")){let o=await Fetch.get(s,{responseType:"arrayBuffer"}),l=s.split("/").pop()||"image.jpg";r=await this.uploadFile(new Uint8Array(o.data),l);}else if(s.startsWith("file://")){let o=await PKG.file(fileURLToPath(s)).bytes(),l=s.split("/").pop()||"image.jpg";r=await this.uploadFile(o,l);}else r=s;else if(s instanceof URL){let o=await Fetch.get(s.toString(),{responseType:"arrayBuffer"}),l=s.pathname.split("/").pop()||"image.jpg";r=await this.uploadFile(new Uint8Array(o.data),l);}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,o="file";if(typeof s=="string")if(s.startsWith("http")){let p=await Fetch.get(s,{responseType:"arrayBuffer"});a=new Uint8Array(p.data),o=s.split("/").pop()||"file";}else s.startsWith("file://")?(a=await PKG.file(fileURLToPath(s)).bytes(),o=s.split("/").pop()||"file"):(a=await PKG.file(s).bytes(),o=s.split("/").pop()||"file");else if(s instanceof URL){let p=await Fetch.get(s.toString(),{responseType:"arrayBuffer"});a=new Uint8Array(p.data),o=s.pathname.split("/").pop()||"file";}else a=s;await this.uploadFile(a,o);let u={channel:e,text:i||`File: ${o}`,attachments:[{fallback:o,text:i||o,fields:[{title:"File",value:o,short:true}]}]};return r&&(u.thread_ts=r),this.request("chat.postMessage",u)}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 f(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 h={channelId:e.channel,userId:e.user,args:i,ts:e.ts,reply:async m=>(await this.postMessage(e.channel,m,e.thread_ts)).ts};try{return await r.handler(h),!0}catch(m){return this.log.error("Command handler error",{command:n,error:String(m)}),true}}let a=await this.getCommandList(),o=n.replace(/^\//,""),l=new Map;for(let h of a){let m=h.name.replace(/[-_]/g,"").toLowerCase();l.set(m,h.name);}let u=l.get(o)??o;if(a.some(h=>h.name===u)){let h=M(this.buildSessionId(this.id,e.channel,e.user),"input",[{type:"command",command:u,arguments:i.join(" ")}],{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}});return await this.handleMessage(h),true}return false}async getCommandList(){try{return (await this.request("commands.list",{})).map(s=>({name:s.name,description:s.description}))}catch{return []}}async syncBotCommands(){try{if((await this.getCommandList()).filter(r=>r.hidden!==!0).length===0)return;let i=[...Array.from(this.commandRouter.values()).map(r=>({command:r.command.replace(/^\//,""),description:r.description}))];if(i.length===0)return;await this.request("commands.set",{commands:i}),this.log.debug("Bot commands synced",{count:i.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 M(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=E()?.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`,o=a.includes(".")?a.split(".").pop():"jpg",l=Filesystem.join(i,`slack_${e.channel}_${r.id}.${o}`);await this.downloadFile(r.url_private_download||r.url_private,l),s.push({type:"image",image:pathToFileURL(l).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}`,o=a.includes(".")?a.split(".").pop():Filesystem.mimeTypeToExt(r.mimetype)||"bin",l=Filesystem.join(i,`slack_${e.channel}_${r.id}.${o}`);if(r.mimetype.startsWith("text/")){let u=await this.downloadTextFile(r.url_private),p=await TruncateContent.truncate(u,{maxChars:5e3,label:`file: ${a}`});s.push({type:"text",text:`\u{1F4CE} File: ${a}
16
-
17
- ${p.content}`});}else await this.downloadFile(r.url_private_download||r.url_private,l),s.push({type:"file",data:pathToFileURL(l).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 f(this.id,"MESSAGE_SEND_FAILED",`Slack API error: ${i.data.error}`);return i.data}};var Te=class extends A{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 f(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw f(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 f(this.id,"MESSAGE_SEND_FAILED","Chat ID is required");await this.ensureTokenValid();let n=this.extractText(e),i=e.content.find(o=>o.type==="image"),r=e.content.find(o=>o.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:false,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=await this.toGatewayMessage(e);await this.handleMessage(n);}}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 f(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 l=await TruncateContent.truncate(s,{maxChars:i,label:"feishu message"});r=l.content,this.log.debug("sendMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:l.truncated?l.outputPath:void 0});}let o=(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(o.code!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`Feishu API error: ${o.msg}`);return o.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 o=await Fetch.get(s,{responseType:"arrayBuffer"});i=await this.uploadFile(new Uint8Array(o.data),"file");}else i=s;else if(s instanceof URL){let o=await Fetch.get(s.toString(),{responseType:"arrayBuffer"});i=await this.uploadFile(new Uint8Array(o.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 f(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 f(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 M(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=E()?.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}`,o=a.includes(".")?a.split(".").pop():Filesystem.mimeTypeToExt(r.file_type)||"bin",l=Filesystem.join(i,`feishu_${e.chat_id}_${r.file_key}.${o}`);await this.downloadFile(r.file_key,l),s.push({type:"file",data:pathToFileURL(l).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(`
18
- `)}buildSessionId(e,s,n){let i=["feishu",e,s];return n&&i.push(n),i.join("_")}};var Ee=class extends A{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 f(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw f(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 f(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 f(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 l=await TruncateContent.truncate(s,{maxChars:i,label:"wechat message"});r=l.content,this.log.debug("sendOfficialMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:l.truncated?l.outputPath:void 0});}let o=(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(o.errcode!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`WeChat API error: ${o.errmsg}`);return o.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,s){let i=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let l=await TruncateContent.truncate(s,{maxChars:i,label:"wecom message"});r=l.content,this.log.debug("sendWeComMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:l.truncated?l.outputPath:void 0});}let o=(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(o.errcode!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`WeCom API error: ${o.errmsg}`);return o.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 f(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 f(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 f(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 l=await Fetch.get(e,{responseType:"arrayBuffer"});i=new Uint8Array(l.data);}catch{throw f(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}`,o=await Fetch.postForm(a,[{name:"media",value:i,filename:"image.jpg"}],{timeout:3e5,headers:{Authorization:`Bearer ${this.accessToken}`}});if(o.data.errcode!==0||!o.data.media_id)throw f(this.id,"MESSAGE_SEND_FAILED",`Image upload failed: ${o.data.errmsg}`);return o.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 M(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 Re=class extends A{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 f(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 f(this.id,"MESSAGE_SEND_FAILED","User ID is required");let i=this.findConnectionByUser(n);if(!i)throw f(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 ee(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 i=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(i.slice(-5e3));}let n=M(s.sessionId,"input",s.content,{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},context:{conversationId:s.sessionId},...s.metadata});await this.handleMessage(n);}startHeartbeat(){let e=this.webChatConfig?.heartbeatInterval??3e4;this.heartbeatInterval=setInterval(()=>{let s=Date.now(),n=this.webChatConfig?.connectionTimeout??6e4;for(let[i,r]of this.connections)s-r.lastActivity>n&&(this.log.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 _e=class extends A{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 f(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.phoneNumber)throw f(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 f(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:false,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=await this.toGatewayMessage(e);await this.handleMessage(s);}async toGatewayMessage(e){let s=this.buildSessionId(this.id,e.envelope.sourceNumber),n=e.envelope.dataMessage;return M(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=E()?.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",o=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 o=await TruncateContent.truncate(s,{maxChars:i,label:"signal message"});r=o.content,this.log.debug("sendMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:o.truncated?o.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 f(this.id,"MESSAGE_SEND_FAILED",`Signal API error: ${JSON.stringify(a.data)}`);return a.data}};var De=class extends A{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 f(this.id,"CHANNEL_INIT_FAILED","Config not set");if(this.botConfig=this.config.platform,!this.botConfig.relays||this.botConfig.relays.length===0)throw f(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 f(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:false,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;let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.buildSessionId(this.id,e.pubkey);return M(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(o=>o.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw f(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 Tt=class extends A{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 Pn(d){return new Tt(d)}var Et={telegram:Me,discord:xe,slack:ke,feishu:Te,wechat:Ee,webchat:Re,signal:_e,nostr:De};function Cc(){return Object.keys(Et)}var I=b.create({service:"gateway:net:registry"});function cs(d){let t=d.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 Mn(d,t){try{let e=await Fetch.post(d,{jsonrpc:"2.0",id:1,method:"agent.initialize",params:{protocolVersion:"2024-11-05"}},{timeout:t});if(!e.ok)return !1;let s=e.data;return !(!s||s.error)}catch{return false}}async function xn(d,t){return new Promise(e=>{let s=null,n=false,i=setTimeout(()=>{n||(n=true,s?.close(),e(false));},t);try{s=new WebSocket(d),s.onopen=()=>{let r={jsonrpc:"2.0",id:1,method:"agent.initialize",params:{protocolVersion:"2024-11-05"}};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 kn(d,t){try{let e=await Fetch.post(d,{jsonrpc:"2.0",id:1,method:"agent.initialize",params:{protocolVersion:"2024-11-05"}},{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 Ne=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={...ot,...s},e&&(this.store=new Ie({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}=cs(t.address);if(i!=="http"&&i!=="websocket")throw new Error(`Unsupported protocol: ${t.address}. Only http/https/ws/wss are supported`);let r=await kn(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(o=>a.capabilities.includes(o)))),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,o]of this.agents.entries()){let l=t-o.lastHeartbeat;if(l>s){n.push(a);continue}(l>e||o.status==="unhealthy")&&r.push((async()=>{let{url:u,protocol:p}=cs(o.address),h=this.config.heartbeatTimeout/2;I.debug("Checking agent connectivity",{agentId:a,url:u,protocol:p});let m=false;try{p==="http"?m=await Mn(u,h):m=await xn(u,h);}catch(_){I.debug("Agent connectivity check error",{agentId:a,error:String(_)}),m=false;}let w=o.status;m?(o.lastHeartbeat=t,o.status!=="healthy"&&(o.status="healthy",I.debug("Agent recovered, marked as healthy",{agentId:a,name:o.name,previousStatus:w}),this.store&&this.store.save(o).catch(_=>{I.error("Failed to save agent to store",{agentId:a,error:String(_)});}),this.emitEvent({type:"status_change",agent:o,oldStatus:w}))):o.status==="healthy"&&(o.status="unhealthy",i++,I.warn("Agent marked as unhealthy due to connectivity check failed",{agentId:a,name:o.name,url:u,protocol:p,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:l,timeout:e}),this.store&&this.store.save(o).catch(_=>{I.error("Failed to save agent to store",{agentId:a,error:String(_)});}),this.emitEvent({type:"status_change",agent:o,oldStatus:w}));})());}await Promise.all(r);for(let a of n){let o=this.agents.get(a);o&&(I.debug("Auto-deregistering agent due to timeout",{agentId:a,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:s}),this.agents.delete(a),this.store&&await this.store.delete(a),this.emitEvent({type:"deregister",agent:o}));}(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 P=b.create({service:"gateway:net:sync-manager"}),Ge=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){P.warn("Agent sync manager is already running");return}P.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,P.info("Agent sync manager started");}async stop(){if(!this.running){P.warn("Agent sync manager is not running");return}P.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,P.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=>{P.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 o of a)o.sourceGatewayId=t,this.remoteAgents.set(o.id,{agent:o,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,P.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){P.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}`);P.debug("Pushed event to node",{nodeId:t,eventType:e.type});}catch(n){P.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:P.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(),P.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&&P.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){P.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,P.debug("Node health check passed",{nodeId:t})):(e.info.status="offline",P.warn("Node health check failed",{nodeId:t,status:i.status}));}catch(n){e.info.status="offline",P.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){P.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}),P.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);P.debug("Remote node removed",{nodeId:t});}};var F=b.create({service:"gateway:ws-agent-sync"}),pt=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){F.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){F.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){F.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){F.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(!this.getClientWs(t)){F.warn("Client not found for agent register",{clientId:t});return}let n={id:e.agentId,name:e.name,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),F.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}),F.debug("Agent registered from client",{clientId:t,agentId:n.id,name:n.name}),this.broadcastAgentUpdate("add",n);}catch(i){F.warn("Failed to register agent from client",{clientId:t,agentId:e.agentId,error:String(i)});}}async handleAgentDeregister(t,e){if(!this.getClientWs(t)){F.warn("Client not found for agent deregister",{clientId:t});return}try{await this.syncManager.registry.deregister(e.agentId),F.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){F.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 se=class se{constructor(t){a(this,"log",b.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);this.log.debug("GatewayServer.constructor: starting"),this.config=t,this.log.debug("GatewayServer.constructor: creating MessageRouter");let e=re()?K().hookRegistry:void 0;this.router=new lt(e),this.log.debug("GatewayServer.constructor: creating GatewaySessionManager");let s=E();this.sessionManager=new Ae({storagePath:`${s.Path.data}/gateway/sessions`,enablePersistence:true}),this.pluginLoader=new Pe({healthCheckInterval:6e4});let n=re();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:n}),this.messageStore=new Se({storagePath:`${s.Path.data}/gateway/messages`}),this.agentRegistry=new Ne({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 k(),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=Et[s];if(!i){this.log.warn("no plugin class found for platform",{platform:s});continue}let r=`${s}-main`,a=new i(r),o={enabled:!0,platform:n,session:{autoCreate:!0,resetPolicy:"onNewConversation"},routing:{broadcast:!0,dispatchToSubAgent:!0}};try{await this.pluginLoader.register(a,o),this.log.info("channel plugin registered",{platform:s,id:r});}catch(l){this.log.error("failed to register channel plugin",{platform:s,error:String(l)});}}}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=`${E().Path.data}/gateway`,s=new we({baseDir:e});this.contactStore=new ve(s,{cacheSize:1e3}),this.contactStore.initialize&&await this.contactStore.initialize(),this.log.debug("GatewayServer.start: contactStore initialized"),this.wsServer=new ee({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(u=>{this.log.error("plugin startup error",{error:String(u)});}),this.log.debug("GatewayServer.start: plugins startup initiated"),this.pluginLoader.startHealthCheckTimer();let{config:n}=await k(),i=n.defaults;this.wsServer.setChannelResolveDeps({sessionManager:{get:u=>this.sessionManager.get(u),getOrCreate:(u,p)=>this.sessionManager.getOrCreate(u,p),bindBackendSession:(u,p)=>this.sessionManager.bindBackendSession(u,p),findByBackendSessionId:u=>this.sessionManager.findByBackendSessionId(u),getAll:()=>this.sessionManager.getAllSessions()},pluginLoader:{getPlugin:u=>this.pluginLoader.getPlugin(u),getAllPlugins:()=>this.pluginLoader.getAllPlugins(),isRunning:u=>this.pluginLoader.isRunning(u)},defaultChannel:i?.channel,fallbackChannels:i?.fallbackChannels,contactStore:this.contactStore?{findByPlatformId:(u,p)=>this.contactStore.findByPlatformId(u,p),findByUid:u=>this.contactStore.findByUid(u),listByPlatform:(u,p,h)=>this.contactStore.listByPlatform(u,p,h),count:u=>this.contactStore.count(u)}:void 0}),this.wsServer.setPluginLoader((u,p,h)=>this.sendToChannel(u,p,h)),this.wsServer.setRouter(this.router),this.router.setSessionManager({get:u=>this.sessionManager.get(u),bindBackendSession:(u,p)=>this.sessionManager.bindBackendSession(u,p)}),this.pluginLoader.setMessageHandler({onMessage:u=>this.onMessage(u),onEvent:u=>this.onEvent(u),session:{getSession:u=>{let p=this.sessionManager.get(u);return p?{backendSessionId:p.backendSessionId}:void 0},unbindBackendSession:u=>this.sessionManager.unbindBackendSession(u)}}),this.agentSyncManager=new Ge({registry:this.agentRegistry,localNodeId:"gateway",localNodeName:"gateway"}),this.wsAgentSync=new pt({wsServer:this.wsServer,syncManager:this.agentSyncManager,getClientWs:u=>this.wsServer.getClientWs(u)}),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"),Wt(async()=>{let u=this.sessionManager.getAllSessions(),p=this.router.getStats?.()??{subscribers:0},h=this.agentRegistry.getStats?.()??{totalAgents:0,healthyAgents:0,unhealthyAgents:0},m=this.wsAgentSync?.getSubscriberCount?.()??0,w=this.wsServer?.getStartTime?.()??0,Y=this.pluginLoader.getAllPlugins().filter(ne=>this.pluginLoader.isRunning(ne.id)).map(ne=>({id:ne.id,platform:ne.platform,name:ne.name,version:ne.version}));return {status:this.running?"running":"stopped",connections:this.wsServer?.getConnectionCount?.()??0,sessions:u.length,messageSubscriptions:p.subscribers??0,agentSubscriptions:m,uptime:this.running&&w?Date.now()-w:0,version:"1.0.0",agents:{total:h.totalAgents,healthy:h.healthyAgents,unhealthy:h.unhealthyAgents},channels:Y}});let r=await this.messageStore.loadFromDisk();this.log.debug("loaded messages from disk",{count:r});let a=Date.now(),o=6e4,l=()=>{let u=Date.now()-a,p=this.pluginLoader.getAllPlugins(),h=p.filter(m=>this.pluginLoader.isRunning(m.id));h.length===p.length&&p.length>0?(this.log.debug("all plugins ready, proceeding with message retry"),this.retryPendingMessages().catch(m=>{this.log.error("failed to retry pending messages",{error:String(m)});})):u>o?(this.log.warn("plugin startup timeout, proceeding with message retry anyway",{elapsed:u}),this.retryPendingMessages().catch(m=>{this.log.error("failed to retry pending messages",{error:String(m)});})):(this.log.debug("waiting for plugins to be ready",{elapsed:u,ready:h.length,total:p.length}),setTimeout(l,100));};l(),this.running=true,this.log.debug("GatewayServer.start: completed"),this.log.info("gateway server started");}async stop(){if(!this.running){this.log.warn("gateway server is not running");return}this.log.info("stopping gateway server"),this.wsServer&&(await this.wsServer.stop(),this.wsServer=null,this.log.debug("WebSocket server stopped")),this.pluginLoader.stopHealthCheckTimer(),await this.pluginLoader.stopAll(),await this.router.shutdown(),await this.sessionManager.close(),await this.messageStore.close(),this.contactStore?.close&&await this.contactStore.close(),this.running=false,this.log.info("gateway server stopped");}getStatus(){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>se.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:o}=await k(),l=o.agentProcessing??{mode:"localAgent",localAgentPriority:1,subAgentPriority:2,timeout:3e5,retryOnFailure:!0};this.log.debug("no subscribers, dispatching to agent",{id:t.id,mode:l.mode}),this.dispatchToAgent(i,l).catch(u=>{this.log.error("agent dispatch failed",{id:t.id,error:String(u)}),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(!re()){this.log.debug("no agent adapter, message remains pending",{id:t.id});return}let s=K(),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(!K().sdk)return null;this.gatewayAgent=zt({});}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()}),i?n.sdk.session.get({sessionId:i}).then(a=>{a.data?this.executeGatewayAgent(t,e,r,i,s):n.sdk.session.create({title:`Gateway-${e?.platform||"unknown"}`}).then(o=>{let l=o.data?.id;this.executeGatewayAgent(t,e,r,l,s);});}):n.sdk.session.create({title:`Gateway-${e?.platform||"unknown"}`}).then(a=>{let o=a.data?.id;this.executeGatewayAgent(t,e,r,o,s);});}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
19
- - Platform: ${s}
20
- - Chat Type: ${r} (e.g., private, group)
21
- - From: ${n} (contactUid: ${i})
22
- - Channel: ${e?.channelId||"default"}
23
- - Session: ${t.sessionId}
24
-
25
- ## Instructions
26
- - Reply the message directly if it's a simple response.
27
- - Use gateway tool to proactively send messages (works for both private and group chats):
28
- \`\`\`json
29
- {"operation": "send", "sessionId": "${t.sessionId}", "content": "Your message here"}
30
- \`\`\``}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};s.run(r).then(a=>{this.handleAgentResult(t,e,a,"gatewayAgent",n);},a=>{this.handleAgentError(t,e,a,"gatewayAgent",n);});}handleAgentResult(t,e,s,n,i){let r=s.metadata.sessionId;r&&this.sessionManager.get(t.sessionId)&&i!==r&&(this.sessionManager.bindBackendSession(t.sessionId,r),this.log.debug("backend session bound",{gatewaySessionId:t.sessionId,backendSessionId:r})),this.triggerHook(HookEvent.GatewayMessageComplete,{id:t.id,sessionId:t.sessionId,backendSessionId:r||i,processorId:n,status:"completed",timestamp:Date.now()}),s.output&&e?.channelId&&(this.log.debug("sending response to channel",{id:t.id,channelId:e.channelId,outputLength:s.output.length}),this.sendToChannel(e.channelId,{id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,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 o=`\u26A0\uFE0F \u5904\u7406\u5931\u8D25: ${s instanceof Error?s.message:String(s)}`;this.sendToChannel(r,{id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:t.sessionId,type:"output",content:[{type:"text",text:o}],metadata:{channel:e,processorId:n,proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}).catch(l=>{this.log.error("failed to send error response",{error:String(l)});});}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",o=e?.userId||e?.chatId||"unknown user",l=`${a}:${o}`,u={source:t.sessionId,title:`[${a}] Message from ${o}`,agent:"gateway",sessionId:i,parts:t.content,system:s,channel:{platform:a,contactUid:l,channelId:e?.channelId,userId:o}};r.run(u).then(p=>{this.handleAgentResult(t,e,p,"subAgent",i);},p=>{this.handleAgentError(t,e,p,"subAgent",i);});}async triggerHook(t,e){if(re())try{await K().hookRegistry.triggerEvent(t,e,{messageStore:{store:async(n,i)=>{let r=Le(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()-se.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>se.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(l=>{this.log.error("failed to re-dispatch stuck message",{messageId:r.id,error:String(l)});});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(l=>{this.log.error("failed to retry message",{messageId:r.id,error:String(l)});});}}}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(re())try{await K().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(u,p)=>{let h=Le(u);await this.messageStore.store(h,p);},updateStatus:async(u,p,h)=>{await this.messageStore.updateStatus(u,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 o;try{o=await a.send(e),this.log.debug("sendToChannel: plugin.send completed",{pluginId:t,messageId:e.id,result:o});}catch(l){throw this.log.error("sendToChannel: plugin.send failed",{pluginId:t,messageId:e.id,error:String(l)}),await this.messageStore.incrementRetry(e.id),await this.messageStore.updateStatus(e.id,"failed",{error:String(l)}),l}return o}async sendProactiveMessage(t,e,s,n,i={}){let r={id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:e,type:"output",content:s,metadata:{channel:n,processorId:i.processorId,agent:i.agent,proactive:true},timestamp:Date.now()};return this.sendToChannel(t,r,{})}getSessionManager(){return this.sessionManager}getRouter(){return this.router}getPluginLoader(){return this.pluginLoader}getMessageStore(){return this.messageStore}getContactStore(){return this.contactStore}async getMessageHistory(t,e){return this.messageStore.getSessionHistory(t,e)}};a(se,"MAX_RETRY_COUNT",3),a(se,"SEVEN_DAYS_MS",10080*60*1e3);var ds=se;export{M as $,Js as A,Et as Aa,Qs as B,Cc as Ba,Ys as C,Ne as Ca,Xs as D,Ge as Da,Zs as E,ds as Ea,en as F,tn as G,sn as H,nn as I,rn as J,an as K,on as L,cn as M,ln as N,Ht as O,st as P,ue as Q,pe as R,Ft as S,Ms as T,he as U,Mi as V,xi as W,re as X,K as Y,E as Z,bt as _,He as a,gs as aa,We as b,Le as ba,ze as c,Fe as ca,je as d,Ue as da,qe as e,mt as ea,Ke as f,Ct as fa,Ve as g,dn as ga,_t as h,ot as ha,Dt as i,ct as ia,Nt as j,gn as ja,Gt as k,lt as ka,Lt as l,Se as la,Je as m,Ce as ma,Qe as n,Ae as na,Ye as o,Pe as oa,Xe as p,ee as pa,Ze as q,A as qa,et as r,Me as ra,tt as s,xe as sa,$e as t,ke as ta,ft as u,Te as ua,ws as v,Ee as va,Ot as w,Re as wa,Bt as x,_e as xa,$t as y,De as ya,Vs as z,Pn as za};