@easbot/gateway 0.2.40 → 0.2.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,30 @@
1
+ 'use strict';var chunk3SBZTZXS_cjs=require('./chunk-3SBZTZXS.cjs'),d=require('zod'),Y=require('path'),z=require('fs'),_=require('fs/promises'),utils=require('@easbot/utils'),ws$1=require('ws'),Js=require('https'),Qs=require('http'),url=require('url'),plugin=require('@easbot/plugin');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var d__default=/*#__PURE__*/_interopDefault(d);var Y__namespace=/*#__PURE__*/_interopNamespace(Y);var z__namespace=/*#__PURE__*/_interopNamespace(z);var ___namespace=/*#__PURE__*/_interopNamespace(_);var Js__default=/*#__PURE__*/_interopDefault(Js);var Qs__default=/*#__PURE__*/_interopDefault(Qs);function v(g,t,e,s){return {id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:g,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 Bt(g,t,e,s){return v(g,t,[{type:"text",text:e}],s)}function Ie(g){let t={platform:g.channel?.platform??"api",channelId:g.channel?.channelId??"unknown",chatId:g.channel?.chatId,userId:g.channel?.userId,chatType:g.channel?.chatType,chatTitle:g.channel?.chatTitle};return {id:g.id,sessionId:g.sessionId,type:g.type,content:Array.isArray(g.content)?g.content:[{type:"text",text:String(g.content??"")}],metadata:{channel:t,replyToMessageId:g.replyToMessageId,processorId:g.processorId,agent:g.agent,proactive:g.proactive??!g.replyToMessageId},timestamp:g.timestamp??Date.now()}}function Qe(g){let t=[g.platform,g.channelId,g.chatId??""],e=g.userId??g.chatId??"";return t.push(e),t.join("_")}function Ye(){return {status:"active",messageCount:0,lastMessageAt:null}}function Pe(g,t){if(!g||!t)throw new Error("platform and stableId are required");return `${g}:${t}`}function Ae(g){if(!g||typeof g!="string")return null;let t=g.indexOf(":");if(t<=0||t>=g.length-1)return null;let e=g.slice(0,t),s=g.slice(t+1);return !e||!s?null:{platform:e,stableId:s}}function Xe(g){let{platform:t,stableId:e,profile:s={},aliases:n={},metadata:i}=g;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:Pe(t,e),platform:t,stableId:e,aliases:{...n},profile:{...s},createdAt:r,lastSeenAt:r,metadata:i}}function Ze(g,t){return `sub_${g}_${t}`}var Wt=chunk3SBZTZXS_cjs.b.create({service:"gateway:config"});d__default.default.enum(["telegram","slack","feishu","wechat","webchat","signal","nostr","dingtalk"]);d__default.default.enum(["low","medium","high","critical"]);var xe=d__default.default.object({enabled:d__default.default.boolean().default(true),botToken:d__default.default.string().describe("Telegram Bot Token"),webhookUrl:d__default.default.string().optional().describe("Webhook URL for receiving updates"),polling:d__default.default.object({enabled:d__default.default.boolean().default(true),interval:d__default.default.number().int().positive().optional().describe("Polling interval in ms"),timeout:d__default.default.number().int().positive().optional().default(30).describe("Long polling timeout in seconds")}).refine(g=>g===void 0||g.enabled===true,{message:"polling.enabled must be true when polling is configured"}).optional(),maxConnections:d__default.default.number().int().positive().optional().default(100),timeout:d__default.default.number().int().positive().optional().default(3e4)}),ke=d__default.default.object({enabled:d__default.default.boolean().default(true),botToken:d__default.default.string().describe("Slack Bot Token (xoxb-*)"),appToken:d__default.default.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:d__default.default.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:d__default.default.number().int().positive().optional().default(100),timeout:d__default.default.number().int().positive().optional().default(3e4)}),Te=d__default.default.object({enabled:d__default.default.boolean().default(true),appId:d__default.default.string().describe("Feishu App ID"),appSecret:d__default.default.string().describe("Feishu App Secret"),encryptKey:d__default.default.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:d__default.default.string().optional().describe("Feishu Verification Token"),maxConnections:d__default.default.number().int().positive().optional().default(100),timeout:d__default.default.number().int().positive().optional().default(3e4)}),Ee=d__default.default.object({enabled:d__default.default.boolean().default(true),mode:d__default.default.enum(["official","wecom"]).default("official"),appId:d__default.default.string().describe("WeChat App ID"),appSecret:d__default.default.string().describe("WeChat App Secret"),token:d__default.default.string().optional().describe("WeChat Token for message verification"),encodingAESKey:d__default.default.string().optional().describe("WeChat Encoding AES Key"),agentId:d__default.default.string().optional().describe("WeCom Agent ID"),maxConnections:d__default.default.number().int().positive().optional().default(100),timeout:d__default.default.number().int().positive().optional().default(3e4)}),_e=d__default.default.object({enabled:d__default.default.boolean().default(true),path:d__default.default.string().optional().default("/"),heartbeatInterval:d__default.default.number().int().positive().optional().default(3e4),connectionTimeout:d__default.default.number().int().positive().optional().default(6e4),maxConnections:d__default.default.number().int().positive().optional().default(1e3),cors:d__default.default.boolean().optional().default(true)}),Re=d__default.default.object({enabled:d__default.default.boolean().default(true),serviceUrl:d__default.default.string().optional().default("https://chat.signal.org"),phoneNumber:d__default.default.string().describe("Signal phone number"),password:d__default.default.string().optional().describe("Signal account password"),maxConnections:d__default.default.number().int().positive().optional().default(100),timeout:d__default.default.number().int().positive().optional().default(3e4)}),De=d__default.default.object({enabled:d__default.default.boolean().default(true),relays:d__default.default.array(d__default.default.string()).min(1).describe("Nostr relay URLs"),privateKey:d__default.default.string().optional().describe("Nostr private key (hex)"),publicKey:d__default.default.string().optional().describe("Nostr public key (hex)"),maxConnections:d__default.default.number().int().positive().optional().default(100),timeout:d__default.default.number().int().positive().optional().default(3e4)}),Ht=d__default.default.object({enabled:d__default.default.boolean().default(true),appKey:d__default.default.string().describe("DingTalk AppKey"),appSecret:d__default.default.string().describe("DingTalk AppSecret"),token:d__default.default.string().optional().describe("DingTalk token for signature verification"),encryptKey:d__default.default.string().optional().describe("DingTalk encrypt key for message encryption"),webhook:d__default.default.object({enabled:d__default.default.boolean().default(true),path:d__default.default.string().optional().default("/dingtalk/webhook"),port:d__default.default.number().int().positive().optional().describe("Webhook server port")}).optional(),maxConnections:d__default.default.number().int().positive().optional().default(100),timeout:d__default.default.number().int().positive().optional().default(3e4)}),ut=d__default.default.object({telegram:xe.optional(),slack:ke.optional(),feishu:Te.optional(),wechat:Ee.optional(),webchat:_e.optional(),signal:Re.optional(),nostr:De.optional(),dingtalk:Ht.optional()}),ht=d__default.default.object({enabled:d__default.default.boolean().default(false),cert:d__default.default.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:d__default.default.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:d__default.default.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:d__default.default.string().optional().describe("Path to SSL key file (alias of key)"),ca:d__default.default.string().optional().describe("Path to CA certificate file"),forceRedirect:d__default.default.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:d__default.default.number().int().positive().optional().default(80).describe("HTTP redirect port")}),$t=d__default.default.object({name:d__default.default.string().describe("Token name/description"),value:d__default.default.string().describe("Token value"),permissions:d__default.default.array(d__default.default.string()).default(["*"]).describe("Associated permissions"),expiresAt:d__default.default.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:d__default.default.string().optional().describe("Token description")}),zt=d__default.default.object({enabled:d__default.default.boolean().default(true),tokens:d__default.default.array($t).default([]).describe("List of valid tokens"),onInvalid:d__default.default.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:d__default.default.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:d__default.default.array(d__default.default.string()).default([]).describe("Default permissions for anonymous users")}),jt=d__default.default.object({enabled:d__default.default.boolean().default(false),authorizationServer:d__default.default.string().describe("OAuth2 authorization server URL"),clientId:d__default.default.string().describe("OAuth2 client ID"),clientSecret:d__default.default.string().describe("OAuth2 client secret"),tokenValidationEndpoint:d__default.default.string().describe("OAuth2 token validation endpoint"),scope:d__default.default.array(d__default.default.string()).default([]).describe("OAuth2 scopes")}),mt=d__default.default.object({type:d__default.default.enum(["token","oauth2"]).default("token"),token:zt.optional(),oauth2:jt.optional()}),ft=d__default.default.object({mode:d__default.default.enum(["pull","push","both"]).default("both"),interval:d__default.default.number().int().positive().default(3e4),pushEvents:d__default.default.array(d__default.default.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:d__default.default.enum(["latest","local","remote"]).default("latest")}),qt=d__default.default.object({id:d__default.default.string().describe("Gateway node ID"),address:d__default.default.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:d__default.default.boolean().default(true),metadata:d__default.default.record(d__default.default.string(),d__default.default.any()).optional()}),yt=d__default.default.object({nodeId:d__default.default.string().describe("Current gateway node ID"),nodes:d__default.default.array(qt).default([]).describe("Other gateway nodes in the cluster"),sync:ft.optional()}),Ne=d__default.default.object({maxConnectionsPerChannel:d__default.default.number().int().positive().default(100),idleTimeout:d__default.default.number().int().positive().default(3e5),reuseStrategy:d__default.default.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:d__default.default.number().int().positive().default(6e4),acquireTimeout:d__default.default.number().int().positive().default(5e3),warmupCount:d__default.default.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),Ge=d__default.default.object({maxLength:d__default.default.number().int().positive().default(1e4),concurrency:d__default.default.number().int().positive().default(100),batchSize:d__default.default.number().int().positive().default(10),batchTimeout:d__default.default.number().int().positive().default(100),priorityLevels:d__default.default.number().int().positive().default(4)}),Le=d__default.default.object({failureThreshold:d__default.default.number().int().positive().default(5),successThreshold:d__default.default.number().int().positive().default(3),timeout:d__default.default.number().int().positive().default(3e4),halfOpenDuration:d__default.default.number().int().positive().default(15e3)}),Ue=d__default.default.object({heartbeatInterval:d__default.default.number().int().positive().default(3e4),heartbeatTimeout:d__default.default.number().int().positive().default(9e4),heartbeatCheckInterval:d__default.default.number().int().positive().default(1e4),autoDeregisterTimeout:d__default.default.number().int().positive().default(3e5),maxAgents:d__default.default.number().int().positive().default(100),persistenceFile:d__default.default.string().optional().describe("Path to persist agent registrations"),maxRegistrations:d__default.default.number().int().positive().default(1e3)}),Fe=d__default.default.object({sessionTimeout:d__default.default.number().int().positive().default(18e5),resumeGracePeriod:d__default.default.number().int().positive().default(3e5),maxSessions:d__default.default.number().int().positive().default(1e4),persistenceFile:d__default.default.string().optional().describe("Path to persist sessions")}),Oe=d__default.default.object({enabled:d__default.default.boolean().default(true),port:d__default.default.number().int().positive().default(8080),hostname:d__default.default.string().default("localhost"),path:d__default.default.string().optional().default("/"),maxConnections:d__default.default.number().int().positive().optional().default(1e3),connectionTimeout:d__default.default.number().int().positive().optional().default(6e4),heartbeatInterval:d__default.default.number().int().positive().optional().default(3e4),sessionExpireMs:d__default.default.number().int().positive().optional().default(3e5),https:ht.optional(),auth:mt.optional(),cors:d__default.default.boolean().default(true),corsOrigins:d__default.default.array(d__default.default.string()).optional(),mdns:d__default.default.boolean().default(false),mdnsDomain:d__default.default.string().optional().default("gateway.easbot.local")}),Kt=d__default.default.object({channel:d__default.default.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:d__default.default.array(d__default.default.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),Vt=d__default.default.enum(["localAgent","subAgent","both"]),Jt=d__default.default.object({mode:Vt.default("localAgent").describe("Agent processing mode: localAgent, subAgent, or both"),localAgentPriority:d__default.default.number().int().min(1).max(10).default(1).describe("Priority for localAgent (lower = higher priority)"),subAgentPriority:d__default.default.number().int().min(1).max(10).default(2).describe("Priority for subAgent (lower = higher priority)"),timeout:d__default.default.number().int().positive().optional().default(3e5).describe("Timeout for agent execution in milliseconds"),retryOnFailure:d__default.default.boolean().default(true).describe("Retry with subAgent when localAgent fails")}),Me=d__default.default.object({server:Oe.optional(),channels:ut.optional(),cluster:yt.optional(),connectionPool:Ne.optional(),messageQueue:Ge.optional(),circuitBreaker:Le.optional(),agentRegistry:Ue.optional(),session:Fe.optional(),defaults:Kt.optional(),agentProcessing:Jt.optional(),defaultAgent:d__default.default.string().optional().describe("Default agent ID for routing"),logLevel:d__default.default.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(d__default.default.unknown());function et(g){let t=Me.safeParse(g);return t.success||Wt.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:Me.parse({})}function Qt(g){return Me.parse(g)}var Be=chunk3SBZTZXS_cjs.b.create({service:"sdk-message-collector"}),Yt={includeThinking:false,includeToolDetails:false,includeToolOutput:false,includeSteps:false};var We=class{constructor(t=Yt){chunk3SBZTZXS_cjs.a(this,"filterConfig",t);chunk3SBZTZXS_cjs.a(this,"events",[]);chunk3SBZTZXS_cjs.a(this,"isComplete",false);chunk3SBZTZXS_cjs.a(this,"hasTextEnd",false);chunk3SBZTZXS_cjs.a(this,"hasStepFinish",false);chunk3SBZTZXS_cjs.a(this,"error","");chunk3SBZTZXS_cjs.a(this,"sessionStatus","idle");chunk3SBZTZXS_cjs.a(this,"sessionId","");chunk3SBZTZXS_cjs.a(this,"messageId","");Be.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&&Be.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(l=>l.type==="part.updated"&&l.properties.part?.type==="reasoning"&&l.properties.part?.time?.end).map(l=>{let c=l.properties.part.text??"";return c=c.replace("[REDACTED]","").trim(),c}).filter(l=>l.length>0).join("");a&&(e=a);}let s;if(this.filterConfig.includeToolDetails){let a=this.events.filter(l=>l.type==="part.updated"&&l.properties.part?.type==="tool"&&(l.properties.part?.state?.status==="completed"||l.properties.part?.state?.status==="error"));a.length>0&&(s=a.map(l=>{let c=l.properties.part,p=c.state;return {name:c.tool,status:p.status,output:this.filterConfig.includeToolOutput?p.output:void 0,error:p.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 Be.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="",Be.debug("MessageEventCollector.reset",{hasTextEnd:false,hasStepFinish:false});}};var A=chunk3SBZTZXS_cjs.b.create({service:"sdk-event-bus"});d.z.object({sessionId:d.z.string(),status:d.z.enum(["idle","busy","retry"]),timestamp:d.z.number()});d.z.object({error:d.z.string(),context:d.z.record(d.z.string(),d.z.any()).optional(),timestamp:d.z.number()});d.z.object({sessionId:d.z.string(),update:d.z.record(d.z.string(),d.z.any()),timestamp:d.z.number()});d.z.object({requestId:d.z.string(),sessionId:d.z.string(),permission:d.z.string(),tool:d.z.object({callId:d.z.string().optional()}).optional(),metadata:d.z.record(d.z.string(),d.z.any()).optional(),timestamp:d.z.number()});d.z.object({sessionId:d.z.string(),timestamp:d.z.number()});var He=class{constructor(){chunk3SBZTZXS_cjs.a(this,"subscriptions",new Map);chunk3SBZTZXS_cjs.a(this,"wildcardSubscriptions",new Set);chunk3SBZTZXS_cjs.a(this,"destroyed",false);}subscribe(t,e){if(this.destroyed)return A.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{};let s=this.subscriptions.get(t)??new Set;return s.add(e),this.subscriptions.set(t,s),A.debug("Subscribed to event",{eventType:t}),()=>{s.delete(e),s.size===0&&this.subscriptions.delete(t),A.debug("Unsubscribed from event",{eventType:t});}}subscribeAll(t){return this.destroyed?(A.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{}):(this.wildcardSubscriptions.add(t),A.debug("Subscribed to all events"),()=>{this.wildcardSubscriptions.delete(t),A.debug("Unsubscribed from all events");})}async publish(t){if(this.destroyed){A.warn("Cannot publish to destroyed SdkEventBus",{type:t.type});return}A.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){A.debug("No subscribers for event",{type:t.type});return}let n=await Promise.allSettled(e.map(async a=>{try{await a(t);}catch(l){throw A.error("Event callback error",{type:t.type,error:l instanceof Error?l.message:String(l)}),l}})),i=n.filter(a=>a.status==="fulfilled").length,r=n.filter(a=>a.status==="rejected").length;r>0?A.warn("Event callbacks completed with errors",{type:t.type,fulfilled:i,rejected:r}):A.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=>{A.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(),A.debug("All subscriptions cleared");}destroy(){this.clear(),this.destroyed=true,A.info("SdkEventBus destroyed");}isDestroyed(){return this.destroyed}};var M=chunk3SBZTZXS_cjs.b.create({service:"sdk-event-bridge"}),Zt={Info:d.z.object({id:d.z.string(),content:d.z.string(),status:d.z.enum(["in_progress","pending","completed","cancelled"]),priority:d.z.enum(["high","medium","low"])})},$e=class{constructor(t,e,s){chunk3SBZTZXS_cjs.a(this,"sdk");chunk3SBZTZXS_cjs.a(this,"sdkEventBus");chunk3SBZTZXS_cjs.a(this,"abortController",null);chunk3SBZTZXS_cjs.a(this,"started",false);chunk3SBZTZXS_cjs.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){M.warn("SdkEventBridge already started");return}this.started=true,this.abortController=new AbortController,M.info("Starting SDK event bridge"),this.runEventLoop().catch(t=>{this.abortController?.signal.aborted||(M.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&&(M.info("Stopping SDK event bridge"),this.started=false,this.abortController?.abort(),this.abortController=null,M.info("SDK event bridge stopped"));}isStarted(){return this.started}async runEventLoop(){for(;;){if(this.abortController?.signal.aborted){M.debug("Event loop aborted");return}try{let t=this.abortController?.signal;if(!t)return;let e=await this.sdk.global.event({signal:t});for await(let s of e.stream){if(this.abortController?.signal.aborted)return;let n=s?.payload;n&&await this.handleEvent(n).catch(i=>{M.error("Failed to handle event",{error:i instanceof Error?i.message:String(i),type:n.type});});}}catch(t){if(this.abortController?.signal.aborted)return;M.error("Event stream error, reconnecting...",{error:t instanceof Error?t.message:String(t)}),await new Promise(e=>setTimeout(e,1e3));}}}async handleEvent(t){switch(M.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:M.debug("Unknown event type, ignoring",{type:t.type});}}async handleSessionDeleted(t){let{sessionId:e}=t;this.sessionFilter&&!this.sessionFilter(e)||(M.info("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)||(M.info("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;M.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=>{M.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=es(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:ts(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 c=i.input,p=c.filePath??"",u=c.oldString??"",h=c.newString??c.content??"";a.push({type:"diff",path:p,oldText:u,newText:h});}if(n==="todo"){let c=ss(i.output);if(c&&i.input.operation==="write"){let p={sessionUpdate:"plan",entries:c.map(u=>({priority:"medium",status:u.status==="cancelled"?"completed":u.status,content:u.content}))};await this.pushEvent(e,p);}}let l={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,l);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()}}),M.debug("Session status update sent",{sessionId:e,status:s.type});}};function es(g){switch(g.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 ts(g,t){if(!t)return [];switch(g.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 ss(g){try{let t=JSON.parse(g),e=d.z.array(Zt.Info).safeParse(t);return e.success?e.data:null}catch{return null}}var T=class extends Error{constructor(e,s,n){super(e,{cause:n});chunk3SBZTZXS_cjs.a(this,"code",s);this.name="GatewayAgentError";}},ie=class{constructor(t,e={}){chunk3SBZTZXS_cjs.a(this,"sdk",t);chunk3SBZTZXS_cjs.a(this,"log",chunk3SBZTZXS_cjs.b.create({service:"gateway:agent"}));chunk3SBZTZXS_cjs.a(this,"config");chunk3SBZTZXS_cjs.a(this,"filterConfig");chunk3SBZTZXS_cjs.a(this,"sessionId");chunk3SBZTZXS_cjs.a(this,"collector");chunk3SBZTZXS_cjs.a(this,"eventBus");chunk3SBZTZXS_cjs.a(this,"eventBridge");chunk3SBZTZXS_cjs.a(this,"bridgeStarted",false);chunk3SBZTZXS_cjs.a(this,"commandListCache",null);chunk3SBZTZXS_cjs.a(this,"commandListCacheTime",0);chunk3SBZTZXS_cjs.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 We(this.filterConfig),this.eventBus=new He,this.eventBridge=new $e(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 T("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 T(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 T("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 l=null,c=()=>{l&&clearTimeout(l);};l=setTimeout(()=>{this.log.warn("runPromptCommand: event collection timeout, returning partial result"),n(),c(),a(this.collector.assembleMessage());},12e4),n=this.eventBus.subscribeAll(p=>{if(p.type==="sdk.session_update"){let u=p.properties;if(u.sessionId!==s)return;let h=this.convertUpdateToSessionEvent(u.update,s);h&&(this.collector.addEvent(h),this.collector.checkComplete()&&(c(),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 T(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 T("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 T?e:new T(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 T("Failed to create session","CREATE_SESSION_FAILED");return this.sessionId=e.data.id,this.log.info("Created new session",{sessionId:this.sessionId}),this.sessionId}async sendAndCollect(t,e){let s=[],n=(e.parts??[]).filter(c=>c.type==="text");if(n.length>0){let c=n.map(p=>p.text??"").join(`
2
+ `);c&&s.push({type:"text",text:c});}let i=(e.parts??[]).filter(c=>c.type==="file"||c.type==="image");for(let c of i)if(c.type==="image"){let p=c,u=p.image||p.url||"";u&&s.push({type:"file",url:u,mime:"image/png"});}else if(c.type==="file"){let p=c,u=typeof p.data=="string"?p.data:p.url??"",h=p.mime??"application/octet-stream";u&&s.push({type:"file",url:u,mime:h});}s.length===0&&s.push({type:"text",text:""}),this.collector.reset(),this.collector.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=true);let r=()=>{},a=new Promise(c=>{let p=null,u=()=>{p&&clearTimeout(p);};p=setTimeout(()=>{this.log.warn("Event collection timeout, returning partial result"),u(),r(),c(this.collector.assembleMessage());},12e4),r=this.eventBus.subscribeAll(h=>{if(h.type==="sdk.session_update"){let y=h.properties;if(y.sessionId!==t)return;let S=this.convertUpdateToSessionEvent(y.update,t);S&&(this.collector.addEvent(S),this.collector.checkComplete()&&(u(),r(),c(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 l=await a;return r(),this.assembleResult(l,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,l=t.content,c=t.rawInput;t.rawOutput;let u;return i==="completed"?u={status:"completed",output:l?.[0]?.content?.text??"",input:c??{}}:i==="failed"?u={status:"error",error:l?.[0]?.content?.text??"Unknown error",input:c??{}}:i==="in_progress"?u={status:"running",input:c??{}}:u={status:"pending",input:c??{}},{type:"part.updated",properties:{sessionId:e,part:{type:"tool",tool:a,callId:n,state:u,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(`
3
+ [Tool: ${s.name}]
4
+ ${String(s.output)}
5
+ `),s.error&&e.push(`
6
+ [Tool Error: ${s.name}]
7
+ ${s.error}
8
+ `);return e.join(`
9
+ `).trim()}getSessionId(){return this.sessionId}resetSession(){this.sessionId=void 0,this.collector.resetForNextMessage();}};var ns=chunk3SBZTZXS_cjs.b.create({service:"gateway:interfaces"}),E;function Vn(g){E=g,ns.debug("Agent adapter registered",{hasSubAgentRunner:!!g.subAgentRunner});}function Jn(){return E}function Q(){return E!==void 0}function O(){if(!E)throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");return E}var is={Path:{home:process.env.HOME||process.env.USERPROFILE||"",data:".easbot",cache:".easbot/cache",config:".easbot",state:".easbot/state",log:".easbot/log",bin:".easbot/bin"}},rs={directory:process.cwd(),worktree:process.cwd()};function x(){return E?E.global:is}function tt(){return E?E.instance:rs}function as(){if(!E?.sdk)throw new Error("SDK not available. Agent adapter is not set or has no SDK.");return E.sdk}function vt(g){let t=as();return new ie(t,g)}var R=chunk3SBZTZXS_cjs.b.create({service:"gateway:config"}),ze={enabled:true,port:8080,hostname:"localhost",path:"",maxConnections:1e3,connectionTimeout:6e4,heartbeatInterval:3e4,sessionExpireMs:3e5,cors:true,mdns:false,mdnsDomain:"gateway.easbot.local",https:{enabled:false,cert:"",key:"",certPath:void 0,keyPath:void 0,ca:void 0,forceRedirect:false,httpPort:80}},cs={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},ds={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},gs={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},ps={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3},us={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e4},hs={enabled:true,botToken:"",maxConnections:100,timeout:3e4,polling:{enabled:true,timeout:30}},ms={enabled:true,botToken:"",maxConnections:100,timeout:3e4},fs={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},ys={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},bs={enabled:true,path:"/ws",heartbeatInterval:3e4,connectionTimeout:6e4,maxConnections:1e3,cors:true},Cs={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},Ss={enabled:true,relays:[],maxConnections:100,timeout:3e4},re,oe=null;async function It(g){try{if(!z.existsSync(g))return null;let t=await ___namespace.default.readFile(g,"utf-8");t=t.replace(/\{env:([^}]+)\}/g,(r,a)=>{let l=process.env[a];return l===void 0?(R.debug("Environment variable not found",{varName:a,file:g}),""):l});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]!==`
10
+ `&&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 R.debug("Failed to load config file",{file:g,error:String(t)}),null}}function ae(g,t){let e={...g,...t};return (g.server||t.server)&&(e.server={...g.server,...t.server}),(g.channels||t.channels)&&(e.channels={...g.channels,...t.channels}),e}async function ws(){let g=x(),t=tt(),e=[],s=Y__namespace.default.join(g.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{R.debug("Filesystem utils not available, using basic directories");}let n=process.env.EASBOT_CONFIG_DIR;return n&&(e.push(n),R.debug("Using EASBOT_CONFIG_DIR",{path:n})),[...new Set(e)]}async function vs(g){let t=["gateway.json"],e={};for(let s of t){let n=Y__namespace.default.join(g,s),i=await It(n);if(i)if("gateway"in i&&i.gateway){let r=i.gateway;"server"in r||"channels"in r||"cluster"in r?e=ae(e,r):e=ae(e,{server:r}),R.debug("Loaded gateway config from file (nested format)",{file:n});}else "gateway"in i||(e=ae(e,i),R.debug("Loaded gateway config from file (direct format)",{file:n}));}return e}async function Is(g){let t=["easbot.json"];for(let e of t){let s=Y__namespace.default.join(g,e),n=await It(s);if(n?.gateway)return R.debug("Loaded gateway config from easbot.json",{file:s}),n.gateway}return {}}function Ps(){return re||(re=async()=>{let g=await ws(),t={};for(let s of g){let n=await vs(s);t=ae(t,n);let i=await Is(s);t=ae(t,i);}let e=et(t);return oe=e,R.info("Gateway config loaded",{directories:g.length,port:e.server?.port,logLevel:e.logLevel}),{config:e,directories:g}}),re}async function P(){return Ps()()}async function bt(g){return g&&(re=void 0,oe=null),(await P()).config}function Ct(){return oe}function St(){return oe!==null}function As(){re=void 0,oe=null,R.debug("Config cache cleared");}function Ms(){return tt().directory}async function xs(){let{config:g}=await P();return Oe.parse({...ze,...g.server})}async function ks(g){let{config:t}=await P(),e=t.channels?.[g],n={telegram:xe.parse(hs),slack:ke.parse(ms),feishu:Te.parse(fs),wechat:Ee.parse(ys),webchat:_e.parse(bs),signal:Re.parse(Cs),nostr:De.parse(Ss)}[g];if(!n)throw new Error(`Unknown channel type: ${g}`);return {...n,...e}}async function Ts(){let{config:g}=await P();return Ne.parse({...cs,...g.connectionPool})}async function Es(){let{config:g}=await P();return Ge.parse({...ds,...g.messageQueue})}async function _s(){let{config:g}=await P();return Le.parse({...gs,...g.circuitBreaker})}async function Rs(){let{config:g}=await P();return Ue.parse({...ps,...g.agentRegistry})}async function Ds(){let{config:g}=await P();return Fe.parse({...us,...g.session})}async function Ns(){let{config:g}=await P();return g.server?.https}async function Gs(){let{config:g}=await P();return g.server?.auth}async function Ls(){let{config:g}=await P();return g.cluster}async function Us(){let{config:g}=await P();return g.defaultAgent}async function wt(){let{config:g}=await P();return g.logLevel??"INFO"}var nt=ze,le={maxConnections:1e3,connectionTimeout:6e4,sessionExpireMs:3e5};var Fs={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var Os={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3};var Bs={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};var Ws={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var D=class g extends Error{constructor(e,s){super(e);chunk3SBZTZXS_cjs.a(this,"code");chunk3SBZTZXS_cjs.a(this,"recoverable");chunk3SBZTZXS_cjs.a(this,"details");chunk3SBZTZXS_cjs.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,g);}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 g)return e.recoverable;let s=e.code;return ["ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH"].includes(s??"")}};function f(g,t,e,s=true){return new D(e,{code:t,recoverable:s,details:{channelId:g}})}var je=class{constructor(t){chunk3SBZTZXS_cjs.a(this,"log",chunk3SBZTZXS_cjs.b.create({service:"gateway:router"}));chunk3SBZTZXS_cjs.a(this,"subscribers",new Map);chunk3SBZTZXS_cjs.a(this,"subscriptions",new Map);chunk3SBZTZXS_cjs.a(this,"sessionSubscriptions",new Map);chunk3SBZTZXS_cjs.a(this,"channelPlugins",new Map);chunk3SBZTZXS_cjs.a(this,"cancelHandlers",new Set);chunk3SBZTZXS_cjs.a(this,"processingMessages",new Map);chunk3SBZTZXS_cjs.a(this,"hookRegistry",null);this.hookRegistry=t??null;}async triggerHook(t,e,s){if(this.hookRegistry)try{await this.hookRegistry.triggerEvent(t,e,s);}catch{this.log.debug("hook trigger skipped",{event:t});}}async triggerBeforeSend(t,e){await this.triggerHook("gateway.message.process",{messageId:t.id,sessionId:t.sessionId,processorId:e,processType:"subscription",agent:e,timestamp:Date.now()});}onCancel(t){this.cancelHandlers.add(t);}offCancel(t){this.cancelHandlers.delete(t);}async emitCancel(t){for(let e of this.cancelHandlers)try{await e(t);}catch(s){this.log.error("cancel handler error",{error:String(s)});}}async route(t){this.log.debug("routing message",{id:t.id,sessionId:t.sessionId,type:t.type});let e=this.sessionSubscriptions.get(t.sessionId);if(!e||e.size===0)return this.log.debug("no subscribers for session",{sessionId:t.sessionId}),{success:true,dispatched:false,dispatchedToSubAgent:false};let s=false,n=null,i=[];for(let r of e){let a=this.subscriptions.get(r);if(!a)continue;let l=this.subscribers.get(a.subscriberId);if(l){if(t.type==="input"){let c=this.processingMessages.get(t.id);if(c&&c!==l.id){this.log.debug("skipping subscriber, message already being processed",{subscriberId:l.id,processor:c});continue}n=l.id,this.processingMessages.set(t.id,l.id);}try{await this.triggerBeforeSend(t,l.id),await l.connection.send(t),s=!0,l.lastActiveAt=Date.now();}catch(c){this.log.warn("failed to send message to subscriber",{subscriberId:l.id,error:String(c)}),i.push(c instanceof Error?c:new Error(String(c))),n===l.id&&(this.processingMessages.delete(t.id),n=null);}}}return this.log.debug("message routed",{id:t.id,dispatched:s,errorCount:i.length,processedBy:n}),{success:i.length===0,dispatched:s,dispatchedToSubAgent:false,error:i.length>0?i.map(r=>r.message).join("; "):void 0}}async completeMessage(t,e,s,n="completed"){this.processingMessages.delete(e),await this.emitCancel({sessionId:t,messageId:e,processedBy:s,reason:n,timestamp:Date.now()}),this.log.info("message completed",{sessionId:t,messageId:e,subscriberId:s,reason:n});}async subscribe(t,e){let s=Ze(e.id,t);if(this.subscriptions.has(s))return this.log.debug("already subscribed",{subscriberId:e.id,sessionId:t}),this.subscriptions.get(s);let n={id:s,subscriberId:e.id,sessionId:t,createdAt:Date.now()};return this.subscribers.has(e.id)||this.subscribers.set(e.id,e),this.subscriptions.set(s,n),this.sessionSubscriptions.has(t)||this.sessionSubscriptions.set(t,new Set),this.sessionSubscriptions.get(t).add(s),e.sessions.add(t),this.log.info("subscribed to session",{subscriberId:e.id,sessionId:t,subscriptionId:s}),n}async unsubscribe(t){let e=this.subscriptions.get(t);if(!e){this.log.warn("subscription not found",{subscriptionId:t});return}this.subscriptions.delete(t);let s=this.sessionSubscriptions.get(e.sessionId);s&&(s.delete(t),s.size===0&&this.sessionSubscriptions.delete(e.sessionId));let n=this.subscribers.get(e.subscriberId);n&&n.sessions.delete(e.sessionId),this.log.info("unsubscribed from session",{subscriberId:e.subscriberId,sessionId:e.sessionId,subscriptionId:t});}async unsubscribeAll(t){let e=this.subscribers.get(t);if(!e)return;let s=[...e.sessions];for(let n of s){let i=this.sessionSubscriptions.get(n);if(i)for(let r of i)this.subscriptions.get(r)?.subscriberId===t&&await this.unsubscribe(r);}this.subscribers.delete(t),this.log.info("all subscriptions removed for subscriber",{subscriberId:t});}registerChannel(t){this.channelPlugins.set(t.id,t),this.log.info("channel plugin registered",{id:t.id,platform:t.platform});}unregisterChannel(t){this.channelPlugins.delete(t),this.log.info("channel plugin unregistered",{id:t});}getSubscriber(t){return this.subscribers.get(t)}getSubscription(t){return this.subscriptions.get(t)}getSubscriberCount(t){return this.sessionSubscriptions.get(t)?.size??0}getStats(){return {subscribers:this.subscribers.size,subscriptions:this.subscriptions.size,sessions:this.sessionSubscriptions.size}}async shutdown(){this.processingMessages.clear(),this.subscribers.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.channelPlugins.clear(),this.cancelHandlers.clear(),this.log.info("router shutdown");}};var ce=class{constructor(t={}){chunk3SBZTZXS_cjs.a(this,"log",chunk3SBZTZXS_cjs.b.create({service:"gateway:message-store"}));chunk3SBZTZXS_cjs.a(this,"config");chunk3SBZTZXS_cjs.a(this,"messages",new Map);chunk3SBZTZXS_cjs.a(this,"sessionMessages",new Map);chunk3SBZTZXS_cjs.a(this,"cleanupTimer",null);chunk3SBZTZXS_cjs.a(this,"accessOrder",[]);chunk3SBZTZXS_cjs.a(this,"storagePath");chunk3SBZTZXS_cjs.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 ___namespace.readdir(this.storagePath,{withFileTypes:!0});for(let s of e){if(!s.isDirectory())continue;let n=Y__namespace.join(this.storagePath,s.name),i=await ___namespace.readdir(n);for(let r of i)if(r.endsWith(".json"))try{let a=Y__namespace.join(n,r),l=await ___namespace.readFile(a,"utf-8"),c=JSON.parse(l);c.status!=="completed"&&c.status!=="delivered"&&(this.messages.has(c.message.id)||(this.messages.set(c.message.id,c),this.addToSessionMessages(c.message.sessionId,c.message.id),t++));}catch(a){this.log.debug("failed to load message file",{file:r,error:String(a)});}}t>0&&this.log.info("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 ___namespace.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 Y__namespace.join(this.storagePath,`${this.sanitizeFileName(t)}.json`)}getSessionDir(t){return Y__namespace.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=Y__namespace.join(e,`${this.sanitizeFileName(t.message.id)}.json`);await ___namespace.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.info("LRU eviction completed",{evicted:e,remaining:this.messages.size});}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e>-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t);}deleteMessage(t){let e=this.messages.get(t);if(e){let s=this.sessionMessages.get(e.message.sessionId);s&&(s.delete(t),s.size===0&&this.sessionMessages.delete(e.message.sessionId)),this.messages.delete(t);let n=this.accessOrder.indexOf(t);n>-1&&this.accessOrder.splice(n,1);}}getStats(){let t={total:this.messages.size,pending:0,processing:0,completed:0,failed:0,cancelled:0,delivered:0,read:0,sessions:this.sessionMessages.size};for(let e of this.messages.values()){let s=e.status;s in t&&s!=="total"&&s!=="sessions"&&t[s]++;}return t}async close(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.messages.clear(),this.sessionMessages.clear(),this.accessOrder=[],this.log.info("MessageStore closed");}};var de=class{constructor(t={}){chunk3SBZTZXS_cjs.a(this,"log",chunk3SBZTZXS_cjs.b.create({service:"gateway:session-store"}));chunk3SBZTZXS_cjs.a(this,"config");chunk3SBZTZXS_cjs.a(this,"sessions",new Map);chunk3SBZTZXS_cjs.a(this,"channelSessions",new Map);chunk3SBZTZXS_cjs.a(this,"autoSaveTimer",null);chunk3SBZTZXS_cjs.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 z__namespace.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(!z__namespace.existsSync(t)){this.log.debug("no saved sessions found");return}let e=await z__namespace.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 Y__namespace.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){z__namespace.existsSync(this.config.storagePath)||await z__namespace.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 Hs="./data/gateway",$s="contacts",zs="index.json",ge=class{constructor(t={}){chunk3SBZTZXS_cjs.a(this,"log",chunk3SBZTZXS_cjs.b.create({service:"gateway:contact-store"}));chunk3SBZTZXS_cjs.a(this,"baseDir");chunk3SBZTZXS_cjs.a(this,"contactDir");chunk3SBZTZXS_cjs.a(this,"indexPath");chunk3SBZTZXS_cjs.a(this,"index");chunk3SBZTZXS_cjs.a(this,"indexFileMap");chunk3SBZTZXS_cjs.a(this,"dirty",false);chunk3SBZTZXS_cjs.a(this,"saveTimer",null);chunk3SBZTZXS_cjs.a(this,"SAVE_DEBOUNCE_MS",1e3);this.baseDir=t.baseDir??Hs,this.contactDir=Y__namespace.join(this.baseDir,$s),this.indexPath=Y__namespace.join(this.contactDir,zs),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 ___namespace.mkdir(t,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async loadIndex(){try{let t=await ___namespace.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 ___namespace.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=Ae(t);if(e){let s=this.getFilePath(e.platform,e.stableId);this.indexFileMap[t]=s;}}}getFilePath(t,e){let s=this.sanitizeFilename(e);return Y__namespace.join(this.contactDir,t,`${s}.json`)}sanitizeFilename(t){return t.replace(/[/\\:*?"<>|]/g,"_")}getPlatformDir(t){return Y__namespace.join(this.contactDir,t)}async save(t){let{platform:e,stableId:s,uid:n}=t,i=this.getFilePath(e,s);return await this.ensureDir(Y__namespace.dirname(i)),await ___namespace.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=Xe(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=Ae(t);return e?this.findByPlatformId(e.platform,e.stableId):null}async findByPlatformId(t,e){let s=Pe(t,e),n=this.index.byUid[s];if(n)try{let r=await ___namespace.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 ___namespace.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 ___namespace.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 l of r){let c=await this.findByUid(l);c&&a.push(c);}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 l=await this.listByPlatform(t.platform,t.limit,t.offset),c=l.contacts;if(t.username){let p=t.username.toLowerCase();c=c.filter(u=>u.profile.username?.toLowerCase().includes(p));}if(t.email){let p=t.email.toLowerCase();c=c.filter(u=>u.profile.email?.toLowerCase().includes(p));}if(t.phone){let p=t.phone.replace(/\s/g,"");c=c.filter(u=>u.profile.phone?.replace(/\s/g,"").includes(p));}return {contacts:c,total:l.total,hasMore:l.hasMore}}let e=[];for(let l of Object.keys(this.index.byPlatform)){let c=await this.listByPlatform(l,1e3,0);e.push(...c.contacts);}let s=e;if(t.username){let l=t.username.toLowerCase();s=s.filter(c=>c.profile.username?.toLowerCase().includes(l));}if(t.email){let l=t.email.toLowerCase();s=s.filter(c=>c.profile.email?.toLowerCase().includes(l));}if(t.phone){let l=t.phone.replace(/\s/g,"");s=s.filter(c=>c.profile.phone?.replace(/\s/g,"").includes(l));}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 it=class{constructor(t){chunk3SBZTZXS_cjs.a(this,"cache",new Map);chunk3SBZTZXS_cjs.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}},pe=class{constructor(t,e={}){chunk3SBZTZXS_cjs.a(this,"store",t);chunk3SBZTZXS_cjs.a(this,"cache");chunk3SBZTZXS_cjs.a(this,"usernameIndex");chunk3SBZTZXS_cjs.a(this,"emailIndex");chunk3SBZTZXS_cjs.a(this,"phoneIndex");chunk3SBZTZXS_cjs.a(this,"platformIndex");chunk3SBZTZXS_cjs.a(this,"initialized",false);this.cache=new it(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 ue=class{constructor(t={}){chunk3SBZTZXS_cjs.a(this,"log",chunk3SBZTZXS_cjs.b.create({service:"gateway:session"}));chunk3SBZTZXS_cjs.a(this,"sessionStore");chunk3SBZTZXS_cjs.a(this,"config");chunk3SBZTZXS_cjs.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 de({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=Qe(t),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),this.log.debug("session found",{sessionId:s}),n):(n={id:s,channel:t,backendSessionId:null,subscribers:new Set,state:Ye(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(n),this.log.info("session created",{sessionId:s,platform:t.platform,channelId:t.channelId,chatId:t.chatId,userId:t.userId}),n)}get(t){return this.sessionStore.get(t)}async closeSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.state.status="closed",await this.sessionStore.delete(t),this.log.info("session closed",{sessionId:t});}async closeById(t){return this.closeSession(t)}async bindBackendSession(t,e){let s=this.sessionStore.get(t);if(!s)throw new Error(`Session not found: ${t}`);s.backendSessionId=e,await this.sessionStore.set(s),this.log.info("backend session bound",{gatewaySessionId:t,backendSessionId:e});}async unbindBackendSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.backendSessionId=null,await this.sessionStore.set(e),this.log.info("backend session unbound",{gatewaySessionId:t});}getState(t){return this.sessionStore.get(t)?.state}async incrementMessageCountOrCreate(t,e){let s=this.sessionStore.get(t);if(!s){let n=e??{platform:"api",channelId:"default"};s=await this.getOrCreate(n);}return s.state.messageCount++,s.state.lastMessageAt=Date.now(),s.lastActiveAt=Date.now(),await this.sessionStore.set(s),s}async incrementMessageCount(t){let e=this.sessionStore.get(t);e&&(e.state.messageCount++,e.state.lastMessageAt=Date.now(),e.lastActiveAt=Date.now(),await this.sessionStore.set(e));}async addSubscriber(t,e){let s=this.sessionStore.get(t);if(!s){this.log.warn("session not found",{sessionId:t});return}s.subscribers.add(e),await this.sessionStore.set(s),this.log.debug("subscriber added to session",{sessionId:t,subscriberId:e});}async removeSubscriber(t,e){let s=this.sessionStore.get(t);s&&(s.subscribers.delete(e),await this.sessionStore.set(s),this.log.debug("subscriber removed from session",{sessionId:t,subscriberId:e}));}query(t){let e=this.sessionStore.getAll();return t.platform&&(e=e.filter(s=>s.channel.platform===t.platform)),t.channelId&&(e=e.filter(s=>s.channel.channelId===t.channelId)),t.userId&&(e=e.filter(s=>s.channel.userId===t.userId)),t.status&&(e=e.filter(s=>s.state.status===t.status)),e}getSessionsByChannel(t){return this.sessionStore.getByChannel(t)}getAllSessions(){return this.sessionStore.getAll()}getSessionCount(){return this.sessionStore.size()}async cleanupIdleSessions(t){let e=Date.now(),s=[];for(let n of this.sessionStore.getAll())n.state.status==="idle"&&e-n.lastActiveAt>t&&s.push(n.id);for(let n of s)await this.closeSession(n);return s.length>0&&this.log.info("cleaned up idle sessions",{count:s.length}),s.length}async save(){this.log.debug("session save triggered");}getStats(){return this.sessionStore.getStats()}};var he=class{constructor(t={}){chunk3SBZTZXS_cjs.a(this,"log",chunk3SBZTZXS_cjs.b.create({service:"gateway:plugin-loader"}));chunk3SBZTZXS_cjs.a(this,"plugins",new Map);chunk3SBZTZXS_cjs.a(this,"messageHandler",null);chunk3SBZTZXS_cjs.a(this,"healthCheckTimer",null);chunk3SBZTZXS_cjs.a(this,"config");chunk3SBZTZXS_cjs.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;}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 D(`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 D("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 U=class extends Error{constructor(e,s,n){super(e);chunk3SBZTZXS_cjs.a(this,"code",s);chunk3SBZTZXS_cjs.a(this,"configuredChannels",n);this.name="ChannelSelectionError";}},L=chunk3SBZTZXS_cjs.b.create({service:"gateway:channel-selection"});function X(g){if(!(!g||typeof g!="string"))return g.toLowerCase().trim()}async function ot(g){let{channel:t,sessionId:e,userId:s,defaultChannel:n,fallbackChannels:i,sessionManager:r,pluginLoader:a,contactStore:l}=g,c=X(t);if(c){let y=rt(c,a);if(y){if(e){let S=at(e,r);if(S){if(S.channelInfo.chatId||S.channelInfo.userId)return L.debug("enriching explicit channel with session info",{sessionId:e,chatId:S.channelInfo.chatId,userId:S.channelInfo.userId}),{...y,channelInfo:{...y.channelInfo,chatId:S.channelInfo.chatId,userId:S.channelInfo.userId}}}else if(s&&r){L.debug("session not found, creating new session for private chat",{userId:s});let se=s,$={platform:y.channelInfo.platform,channelId:y.channel,chatId:se,userId:s};try{let ne=await r.getOrCreate($);return L.info("auto-created session for private chat",{sessionId:ne.id,chatId:se,userId:s}),{channel:y.channel,source:"session-bound",channelInfo:ne.channel}}catch(ne){L.warn("failed to auto-create session, using explicit channel info",{userId:s,error:String(ne)});}}}if(s&&l){let S=await js(c,s,l,a);if(S)return S}return y}if(e){let S=at(e,r);if(S){if((!S.channelInfo.chatId||!S.channelInfo.userId)&&S.channelInfo.platform!=="api"){let $=Ks(S.channelInfo.platform,r);if($)return L.debug("session missing chatId/userId, using session with complete info",{originalSessionId:e,newSessionId:$.channelInfo.chatId}),$}return S}}throw new U(`Channel \u4E0D\u53EF\u7528\u6216\u672A\u914D\u7F6E: ${c}`,"CHANNEL_UNAVAILABLE",[])}if(e){let y=at(e,r);if(y)return y}if(s&&l){let y=await qs(s,l,a);if(y)return y}let p=lt(a);if(p.length===0)throw new U("\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 u=X(n);if(u){let y=rt(u,a);if(y)return L.debug("using default channel",{channel:u}),{...y,source:"default"};L.warn("default channel unavailable",{channel:u});}if(p.length===1){let y=p[0],S=a?.getPlugin(y);return {channel:y,source:"single-configured",channelInfo:{platform:S?.platform,channelId:y}}}let h=(i??[]).map(X).filter(y=>y!==void 0);for(let y of h){let S=rt(y,a);if(S)return L.debug("using fallback channel",{channel:y}),{...S,source:"fallback"};L.debug("fallback channel unavailable, trying next",{channel:y});}throw u?new U(`\u914D\u7F6E\u7684\u9ED8\u8BA4 Channel \u4E0D\u53EF\u7528: ${u}`,"CHANNEL_UNAVAILABLE",p):new U(`\u9700\u8981\u660E\u786E\u6307\u5B9A Channel\uFF08\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF09: ${p.join(", ")}\u3002\u8BF7\u901A\u8FC7 channel \u53C2\u6570\u6307\u5B9A\u8981\u4F7F\u7528\u7684 Channel\uFF0C\u6216\u5728 gateway.json \u4E2D\u914D\u7F6E defaults.channel\u3002`,"MULTIPLE_CHANNELS",p)}function rt(g,t){if(!t)return null;let e=t.getPlugin(g);if(e&&t.isRunning(g))return {channel:g,source:"explicit",channelInfo:{platform:e.platform,channelId:g}};let s=X(g);if(!s)return null;let n=t.getAllPlugins();for(let i of n)if(t.isRunning(i.id)&&X(i.platform)===s)return {channel:i.id,source:"explicit",channelInfo:{platform:i.platform,channelId:i.id}};return null}function at(g,t){if(!t)return null;let e=t.get(g);return e?{channel:e.channel.channelId,source:"session-bound",channelInfo:e.channel}:null}async function js(g,t,e,s){let n=s?.getPlugin(g);if(!n)return null;let i=await e.findByPlatformId(n.platform,t);return i?{channel:g,source:"explicit",channelInfo:{platform:n.platform,channelId:g,userId:i.stableId,chatId:i.stableId}}:null}async function qs(g,t,e){let s=lt(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,g);if(r)return {channel:n,source:"single-configured",channelInfo:{platform:i.platform,channelId:n,userId:r.stableId,chatId:r.stableId}}}return null}function lt(g){if(!g)return [];let t=[],e=g.getAllPlugins();for(let s of e)g.isRunning(s.id)&&t.push(s.id);return t}function ct(g){switch(g.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: ${g.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 g.message;case "UNKNOWN_CHANNEL":return `\u672A\u77E5\u7684 Channel: ${g.message}\u3002\u8BF7\u68C0\u67E5 Channel ID \u662F\u5426\u6B63\u786E\u3002`;default:return g.message}}function Ks(g,t){if(!t)return null;let e=t.getAll?.()??[];for(let s of e)if(s.channel.platform===g&&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===g&&s.channel.chatId)return {channel:s.channel.channelId,source:"session-bound",channelInfo:s.channel};return null}var m=chunk3SBZTZXS_cjs.b.create({service:"gateway:websocket-server"});function Ys(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function qe(g,t){for(let[e,s]of t.entries())if(s===g)return e;return null}var q=class{constructor(t={}){chunk3SBZTZXS_cjs.a(this,"config");chunk3SBZTZXS_cjs.a(this,"server",null);chunk3SBZTZXS_cjs.a(this,"wss",null);chunk3SBZTZXS_cjs.a(this,"httpsServer",null);chunk3SBZTZXS_cjs.a(this,"httpRedirectServer",null);chunk3SBZTZXS_cjs.a(this,"connections",new Map);chunk3SBZTZXS_cjs.a(this,"subscriptions",new Map);chunk3SBZTZXS_cjs.a(this,"sessionSubscriptions",new Map);chunk3SBZTZXS_cjs.a(this,"sessionLastActivity",new Map);chunk3SBZTZXS_cjs.a(this,"cleanupInterval",null);chunk3SBZTZXS_cjs.a(this,"heartbeatInterval",null);chunk3SBZTZXS_cjs.a(this,"startTime",0);chunk3SBZTZXS_cjs.a(this,"running",false);chunk3SBZTZXS_cjs.a(this,"channelResolveParams",null);chunk3SBZTZXS_cjs.a(this,"pluginLoaderRef",null);this.config={...nt,...t};}setChannelResolveDeps(t){this.channelResolveParams=t,m.debug("channel resolve deps set",{hasSessionManager:!!t.sessionManager,hasPluginLoader:!!t.pluginLoader,hasContactStore:!!t.contactStore});}setPluginLoader(t){this.pluginLoaderRef=t;}getChannelResolveParams(){return this.channelResolveParams?this.channelResolveParams:{}}async start(){if(this.running){m.warn("WebSocket server is already running");return}m.debug("WebSocket server start: checking configuration",{port:this.config.port,hostname:this.config.hostname,path:this.config.path,https:this.config.https?.enabled??false}),this.startTime=Date.now();let t={onOpen:(n,i)=>{this.handleConnection(i);},onMessage:async(n,i)=>{try{let r=JSON.parse(n.data.toString());await this.handleMessage(i,r);}catch(r){m.error("Error processing WebSocket message",{error:r.message}),this.sendError(i,r.message);}},onClose:(n,i)=>{this.handleDisconnection(i);},onError:(n,i)=>{m.error("WebSocket error",{error:n.type});}},e=this.config.https?.enabled??false;m.debug("WebSocket server start: choosing server type",{https:e});try{e?(m.debug("WebSocket server start: starting HTTPS server"),await this.startHTTPSServer(t)):(m.debug("WebSocket server start: starting HTTP server"),await this.startHTTPServer(t)),m.debug("WebSocket server start: HTTP/HTTPS server started successfully");}catch(n){throw m.error("WebSocket server start: HTTP/HTTPS server failed",{error:n instanceof Error?n.message:String(n)}),n}m.debug("WebSocket server start: server initialization complete"),this.cleanupInterval=setInterval(()=>this.cleanupExpiredSessions(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let s=e?"wss":"ws";m.info("WebSocket server started",{url:`${s}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(t){m.debug("HTTP server start: creating server",{port:this.config.port,hostname:this.config.hostname}),this.server=utils.createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true}),m.debug("HTTP server start: server created, checking raw server");let e=this.server.raw;e?(m.debug("HTTP server start: raw server available, setting up WebSocket upgrade"),this.setupWebSocketUpgrade(e,t),m.debug("HTTP server start: WebSocket upgrade configured")):m.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(t){let e=this.config.https,s=this.loadSSLCertificates(e);if(!s){m.error("Failed to load SSL certificates, falling back to HTTP"),await this.startHTTPServer(t);return}this.server=utils.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=Js__default.default.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,t),await new Promise(i=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{m.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:z__namespace.default.readFileSync(t.certPath),key:z__namespace.default.readFileSync(t.keyPath)}:null}catch(e){return m.error("Failed to load SSL certificates",{error:e.message}),null}}setupWebSocketUpgrade(t,e){this.wss=new ws$1.WebSocketServer({noServer:true}),t.on("upgrade",(s,n,i)=>{try{let a=new URL(s.url||"/",`http://${s.headers.host}`).pathname,l=this.config.path||"";(a===l||l===""&&(a==="/"||a===""))&&this.wss.handleUpgrade(s,n,i,c=>{e.onOpen?.({type:"open"},c),c.on("message",p=>{e.onMessage?.({data:p},c);}),c.on("close",(p,u)=>{e.onClose?.({code:p,reason:u},c);}),c.on("error",p=>{e.onError?.({type:"error",message:p.message},c);});});}catch{}});}startHTTPRedirectServer(t){this.httpRedirectServer=Qs__default.default.createServer((e,s)=>{let i=`https://${e.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${e.url}`;m.debug("Redirecting HTTP to HTTPS",{from:e.url,to:i}),s.writeHead(301,{Location:i,"Content-Type":"text/plain"}),s.end(`Redirecting to ${i}`);}),this.httpRedirectServer.listen(t,this.config.hostname,()=>{m.info("HTTP redirect server started",{port:t,hostname:this.config.hostname});});}async stop(){if(!this.running){m.warn("WebSocket server is not running");return}m.info("Stopping WebSocket server"),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let[t,e]of this.connections.entries())try{e.close(1e3,"Server shutting down");}catch(s){m.debug("Error closing connection",{clientId:t,error:String(s)});}this.connections.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.sessionLastActivity.clear(),this.wss&&(this.wss.close(),this.wss=null),this.httpsServer&&(await new Promise(t=>{this.httpsServer.close(()=>t());}),this.httpsServer=null),this.httpRedirectServer&&(await new Promise(t=>{this.httpRedirectServer.close(()=>t());}),this.httpRedirectServer=null),this.server&&(await this.server.stop(),this.server=null),this.running=false,m.info("WebSocket server stopped");}broadcastToSession(t,e){this.touchSession(t);let s=this.sessionSubscriptions.get(t);if(!s||s.size===0){m.debug("No clients subscribed to session",{sessionId:t});return}let n=e?.properties?.sessionId;if(typeof n=="string"&&n&&n!==t)return;let i=JSON.stringify({type:"event",sessionId:t,payload:e});for(let r of s){let a=this.subscriptions.get(r);if(a&&a.ws.readyState===a.ws.OPEN&&a.subscribedSessions.has(t)){if(a.subscribedEventTypes.size>0&&!a.subscribedEventTypes.has(e.type)){m.debug("Event type not subscribed, skipping",{clientId:r,sessionId:t,eventType:e.type,subscribedTypes:Array.from(a.subscribedEventTypes)});continue}a.ws.send(i),m.debug("Event pushed to client",{clientId:r,sessionId:t,eventType:e.type});}}}getConnectionCount(){return this.connections.size}getSubscriptionCount(){return this.sessionSubscriptions.size}getConnectionInfos(){let t=[];for(let[e,s]of this.subscriptions.entries())t.push({clientId:e,state:s.ws.readyState===s.ws.OPEN?"connected":"disconnected",connectedAt:s.connectedAt,lastActivityAt:s.lastActivityAt,authInfo:s.authInfo});return t}isRunning(){return this.running}handleConnection(t){if(this.connections.size>=(this.config.maxConnections??le.maxConnections)){m.warn("Maximum connections reached, rejecting new connection"),t.close(1013,"Maximum connections reached");return}let e=Ys();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()}),m.info("WebSocket client connected",{clientId:e,totalConnections:this.connections.size}),this.sendMessage(t,{type:"connected",clientId:e,payload:{version:"1.0.0",capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}handleDisconnection(t){let e=qe(t,this.connections);if(!e)return;this.connections.delete(e);let s=this.subscriptions.get(e);if(s){for(let n of s.subscribedSessions){let i=this.sessionSubscriptions.get(n);i&&(i.delete(e),i.size===0&&this.sessionSubscriptions.delete(n));}this.subscriptions.delete(e);}m.info("WebSocket client disconnected",{clientId:e,totalConnections:this.connections.size});}async handleMessage(t,e){let s=qe(t,this.connections);if(!s){this.sendError(t,"Client not found");return}let n=this.subscriptions.get(s);switch(n&&(n.lastActivityAt=Date.now()),e.type){case "ping":this.sendMessage(t,{type:"pong"});break;case "initialize":await this.handleInitialize(t,e);break;case "subscribe":await this.handleSubscribe(t,e);break;case "unsubscribe":await this.handleUnsubscribe(t,e);break;case "message":await this.handleMessageRequest(t,e);break;case "interrupt":await this.handleInterrupt(t,e);break;case "releaseSubscription":await this.handleReleaseSubscription(t,e);break;default:this.sendError(t,`Unknown message type: ${e.type}`);}}async handleInitialize(t,e){this.sendMessage(t,{type:"initialize_response",success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}async handleSubscribe(t,e){if(e.type!=="subscribe"||!e.sessionId){this.sendError(t,"Invalid subscribe request");return}let s=qe(t,this.connections);if(!s){this.sendError(t,"Client not found");return}let n=this.subscriptions.get(s);if(!n){this.sendError(t,"Subscription not found");return}n.subscribedSessions.add(e.sessionId),this.sessionSubscriptions.has(e.sessionId)||this.sessionSubscriptions.set(e.sessionId,new Set),this.sessionSubscriptions.get(e.sessionId).add(s);let i=e;if(i.backendSessionId){let r=this.getChannelResolveParams();if(r.sessionManager)try{await r.sessionManager.bindBackendSession(i.sessionId,i.backendSessionId),m.info("backend session bound on subscribe",{gatewaySessionId:i.sessionId,backendSessionId:i.backendSessionId});}catch(a){m.warn("failed to bind backend session on subscribe",{sessionId:i.sessionId,backendSessionId:i.backendSessionId,error:String(a)});}}if(this.touchSession(e.sessionId),e.payload?.eventTypes)for(let r of e.payload.eventTypes)n.subscribedEventTypes.add(r);m.info("Client subscribed to session",{clientId:s,sessionId:e.sessionId,backendSessionId:i.backendSessionId}),this.sendMessage(t,{type:"subscribed",sessionId:e.sessionId});}async handleUnsubscribe(t,e){if(e.type!=="unsubscribe"||!e.sessionId){this.sendError(t,"Invalid unsubscribe request");return}let s=qe(t,this.connections);if(!s)return;let n=this.subscriptions.get(s);if(!n)return;n.subscribedSessions.delete(e.sessionId);let i=this.sessionSubscriptions.get(e.sessionId);i&&(i.delete(s),i.size===0&&this.sessionSubscriptions.delete(e.sessionId)),m.info("Client unsubscribed from session",{clientId:s,sessionId:e.sessionId}),this.sendMessage(t,{type:"unsubscribed",sessionId:e.sessionId});}async handleMessageRequest(t,e){if(e.type!=="message"||!e.sessionId||!e.payload){this.sendError(t,"Invalid message request");return}m.debug("Message received",{sessionId:e.sessionId}),this.sendMessage(t,{type:"response",sessionId:e.sessionId,success:true,result:{received:true}});}async handleInterrupt(t,e){if(e.type!=="interrupt"||!e.sessionId){this.sendError(t,"Invalid interrupt request");return}m.info("Interrupt requested via WebSocket",{sessionId:e.sessionId}),this.sendMessage(t,{type:"interrupted",sessionId:e.sessionId,success:true});}async handleReleaseSubscription(t,e){if(e.type!=="releaseSubscription"||!e.sessionId){this.sendError(t,"Invalid releaseSubscription request");return}m.info("Release subscription requested via WebSocket",{sessionId:e.sessionId}),this.releaseSessionResources(e.sessionId),this.sendMessage(t,{type:"subscriptionReleased",sessionId:e.sessionId});}touchSession(t){this.sessionLastActivity.set(t,Date.now());}checkConnectionTimeout(){let t=Date.now(),e=this.config.connectionTimeout??le.connectionTimeout,s=[];for(let[n,i]of this.subscriptions.entries())t-i.lastActivityAt>e&&s.push(n);for(let n of s){let i=this.subscriptions.get(n);if(i){m.info("Closing inactive connection",{clientId:n,lastActivityAt:i.lastActivityAt,timeoutMs:e});try{i.ws.close(1001,"Connection timeout");}catch(r){m.debug("Error closing timed out connection",{clientId:n,error:String(r)});}}}s.length>0&&m.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size-s.length});}cleanupExpiredSessions(){let t=Date.now(),e=[],s=this.config.sessionExpireMs??le.sessionExpireMs;for(let[n,i]of this.sessionLastActivity.entries())t-i>s&&e.push(n);for(let n of e)m.info("Session expired due to inactivity, releasing resources",{sessionId:n,lastActivity:this.sessionLastActivity.get(n),expireMs:s}),this.releaseSessionResources(n),this.sessionLastActivity.delete(n);e.length>0&&m.debug("Cleaned up expired sessions",{count:e.length,remainingActive:this.sessionLastActivity.size});}releaseSessionResources(t){let e=this.sessionSubscriptions.get(t);if(e){for(let s of e){let n=this.subscriptions.get(s);n&&n.ws.readyState===n.ws.OPEN&&this.sendMessage(n.ws,{type:"session_closed",sessionId:t,payload:{reason:"Session resources released due to expiration or explicit release"}});}for(let s of e){let n=this.subscriptions.get(s);n&&n.subscribedSessions.delete(t);}this.sessionSubscriptions.delete(t),m.info("Session resources released",{sessionId:t,clientCount:e.size});}}sendMessage(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e));}sendError(t,e,s){this.sendMessage(t,{type:"error",message:e,code:s});}createRoutes(){return [{method:"get",path:"/health",handler:t=>{let e={status:"healthy",timestamp:Date.now(),version:"1.0.0"};return t.json(e)}},{method:"get",path:"/status",handler:t=>{let e={status:this.running?"running":"stopped",connections:this.connections.size,sessions:this.sessionSubscriptions.size,subscriptions:this.subscriptions.size,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0"};return t.json(e)}},{method:"get",path:"/channels",handler:async t=>{let e=this.channelResolveParams?.pluginLoader;if(!e)return t.json({error:"Plugin loader not available"},503);let n=e.getAllPlugins().map(i=>({id:i.id,platform:i.platform,name:i.name,version:i.version}));return t.json({channels:n,total:n.length})}},{method:"get",path:"/contacts",handler:async t=>{let e=t.req.query("platform"),s=parseInt(t.req.query("limit")||"100",10),n=parseInt(t.req.query("offset")||"0",10),i=this.channelResolveParams?.contactStore;if(!i)return t.json({error:"Contact store not available"},503);try{if(e){let r=await i.listByPlatform(e,s,n);return t.json({contacts:r.contacts.map(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 m.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 m.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"),l=[],p=this.getChannelResolveParams().sessionManager?.getAll?.()??[];for(let h of p){let y=!n||h.channel.platform===n,S=!i||h.channel.channelId===i,se=!r||h.channel.userId===r,$=!a||h.channel.chatId===a;y&&S&&(!r&&!a||se&&$)&&l.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 u=l.slice(s,s+e);return t.json({sessions:u,total:l.length,hasMore:s+e<l.length})}},{method:"get",path:"/sessions/:sessionId",handler:async t=>{let e=t.req.param("sessionId"),s=this.sessionSubscriptions.get(e);return s?t.json({id:e,state:"active",subscriberCount:s.size,lastActiveAt:this.sessionLastActivity.get(e)||Date.now()}):t.json({error:"Session not found"},404)}},{method:"post",path:"/initialize",handler:async t=>{let e=await t.req.json().catch(()=>({}));return m.debug("ACP initialize request received",{body:e}),t.json({success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"],version:"1.0.0"}})}},{method:"post",path:"/session",handler:async t=>{let e=await t.req.json().catch(()=>({}));if(!this.channelResolveParams?.sessionManager)return t.json({error:"Session manager not available"},500);let s=e.channel?.platform,n=e.channel?.channelId;if(!s||!n)return t.json({error:"platform and channelId are required"},400);let i={platform:s,channelId:n,userId:e.channel?.userId,chatId:e.channel?.chatId},r=await this.channelResolveParams.sessionManager.getOrCreate(i),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);try{let n=this.getChannelResolveParams(),i=await ot({...n,sessionId:e,channel:s.channel,userId:s.userId??s.chatId});m.debug("channel resolved for message",{sessionId:e,channel:i.channel,source:i.source,channelInfo:i.channelInfo});let r=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,a={...i.channelInfo};if(!a.chatId){let p=s.chatId??i.channelInfo.userId;p&&(a.chatId=p,m.debug("filled channelInfo.chatId from request body or session",{chatId:a.chatId}));}if(!a.userId&&a.chatId&&(a.userId=s.userId??a.chatId,m.debug("filled channelInfo.userId from chatId",{userId:a.userId})),!a.chatId)return m.error("channelInfo missing chatId, cannot send message",{sessionId:e,channelInfo:a,body:{userId:s.userId,chatId:s.chatId}}),t.json({error:"channelInfo missing chatId"},400);let l={id:r,sessionId:e,type:"output",content:typeof s.content=="string"?[{type:"text",text:s.content}]:s.content||[],metadata:{channel:a,replyToMessageId:s.replyToMessageId,processorId:s.processorId??"gateway",agent:s.agent??"gateway"},timestamp:Date.now()};if(this.pluginLoaderRef)try{await this.pluginLoaderRef(i.channel,l,{}),m.debug("message sent via pluginLoader",{messageId:r,channel:i.channel});}catch(p){return m.error("failed to send message",{sessionId:e,error:String(p)}),t.json({error:String(p)},500)}else return m.error("no pluginLoader available for sending message",{sessionId:e}),t.json({error:"Plugin loader not available"},500);let c={messageId:r,sessionId:e,createdAt:Date.now(),metadata:{channel:i.channel,channelSource:i.source,channelInfo:i.channelInfo}};return t.status(202),t.json(c)}catch(n){return n instanceof U?(m.warn("channel selection failed",{sessionId:e,error:n.message}),t.json({error:ct(n),code:n.code},400)):(m.error("send message error",{sessionId:e,error:String(n)}),t.json({error:String(n)},500))}}},{method:"get",path:"/subscriptions",handler:t=>{let e=Array.from(this.sessionSubscriptions.entries()).map(([n,i])=>({sessionId:n,subscriberCount:i.size,subscribers:Array.from(i)})),s={subscriptions:e,total:e.length};return t.json(s)}}]}};var I=class{constructor(){chunk3SBZTZXS_cjs.a(this,"version","1.0.0");chunk3SBZTZXS_cjs.a(this,"log");chunk3SBZTZXS_cjs.a(this,"config",null);chunk3SBZTZXS_cjs.a(this,"messageHandler",null);chunk3SBZTZXS_cjs.a(this,"_status","stopped");chunk3SBZTZXS_cjs.a(this,"lastActivity",0);chunk3SBZTZXS_cjs.a(this,"startPromise",null);chunk3SBZTZXS_cjs.a(this,"stopPromise",null);}initLog(){this.log=chunk3SBZTZXS_cjs.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(`
11
+ `)}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=O(),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)}),[]}}};var me=class extends I{constructor(e="telegram-main"){super();chunk3SBZTZXS_cjs.a(this,"id");chunk3SBZTZXS_cjs.a(this,"platform","telegram");chunk3SBZTZXS_cjs.a(this,"name","Telegram Bot");chunk3SBZTZXS_cjs.a(this,"botConfig",null);chunk3SBZTZXS_cjs.a(this,"baseUrl","");chunk3SBZTZXS_cjs.a(this,"abortController",null);chunk3SBZTZXS_cjs.a(this,"lastUpdateId",0);chunk3SBZTZXS_cjs.a(this,"typingTimers",new Map);chunk3SBZTZXS_cjs.a(this,"sentMessages",new Map);chunk3SBZTZXS_cjs.a(this,"sessionIdMap",new Map);chunk3SBZTZXS_cjs.a(this,"commandRouter",new Map);chunk3SBZTZXS_cjs.a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});chunk3SBZTZXS_cjs.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(p=>p.type==="image"),l=e.content.find(p=>p.type==="file"),c;if(a){let p=a.image,u=n||void 0;c=await this.sendPhoto(s,p,u);}else if(l){let p=l.data,u=n||void 0;c=await this.sendDocument(s,p,u);}else try{c=await this.sendApiMessage(s,n,{parseMode:r,replyTo:i?parseInt(i,10):void 0});}catch(p){if(r!=="None"&&this.isParseError(p))this.log.debug("parse error, retrying with plain text",{parseMode:r,error:String(p)}),c=await this.sendApiMessage(s,n,{parseMode:"None",replyTo:i?parseInt(i,10):void 0});else throw p}return this.sentMessages.set(e.id,{chatId:s,messageId:parseInt(c,10),timestamp:Date.now()}),this.sessionIdMap.set(e.id,e.sessionId),c}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 utils.PKG.file(url.fileURLToPath(s)).bytes(),r=s.split("/").pop()||r;else {let c=await utils.Fetch.post(`${this.baseUrl}/sendPhoto`,{chat_id:e,photo:s,caption:n});if(!c.data.ok)throw new Error(`sendPhoto failed: ${c.data.description||"unknown error"}`);return c.data.result.message_id.toString()}else if(s instanceof URL){let c=await utils.Fetch.post(`${this.baseUrl}/sendPhoto`,{chat_id:e,photo:s.toString(),caption:n});if(!c.data.ok)throw new Error(`sendPhoto failed: ${c.data.description||"unknown error"}`);return c.data.result.message_id.toString()}else a=s;this.log.debug("sendPhoto: calling Fetch.postForm",{url:`${this.baseUrl}/sendPhoto?${i}`,filename:r});let l=await utils.Fetch.postForm(`${this.baseUrl}/sendPhoto?${i}`,[{name:"photo",value:a,filename:r}]);if(this.log.debug("sendPhoto: response received",{ok:l.ok,status:l.status,data:l.data}),!l.ok)throw new Error(`sendPhoto failed: ${l.data.description||"unknown error"}`);return l.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 utils.PKG.file(url.fileURLToPath(s)).bytes(),r=s.split("/").pop()||r;else {let c=await utils.Fetch.post(`${this.baseUrl}/sendDocument`,{chat_id:e,document:s,caption:n});if(!c.data.ok)throw new Error(`sendDocument failed: ${c.data.description||"unknown error"}`);return c.data.result.message_id.toString()}else if(s instanceof URL){let c=await utils.Fetch.post(`${this.baseUrl}/sendDocument`,{chat_id:e,document:s.toString(),caption:n});if(!c.data.ok)throw new Error(`sendDocument failed: ${c.data.description||"unknown error"}`);return c.data.result.message_id.toString()}else a=s;this.log.debug("sendDocument: calling Fetch.postForm",{url:`${this.baseUrl}/sendDocument?${i}`,filename:r});let l=await utils.Fetch.postForm(`${this.baseUrl}/sendDocument?${i}`,[{name:"document",value:a,filename:r}]);if(this.log.debug("sendDocument: response received",{ok:l.ok,status:l.status,data:l.data}),!l.ok)throw new Error(`sendDocument failed: ${l.data.description||"unknown error"}`);return l.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(l=>l.type==="emoji"&&(l.emoji==="\u{1F441}"||l.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.commandRouter.get(n);if(r){let h={chatId:e.chat.id.toString(),userId:e.from?.id.toString(),args:i,messageId:e.message_id,reply:async(y,S)=>this.sendApiMessage(e.chat.id.toString(),y,S)};try{return await r.handler(h),!0}catch(y){return this.log.error("Command handler error",{command:n,error:String(y)}),true}}let a=n.replace(/^\//,""),l=await this.getCommandList(),c=new Map;for(let h of l){let y=h.name.replace(/[-_]/g,"").toLowerCase();c.set(y,h.name);}let p=c.get(a)??a;if(l.some(h=>h.name===p)){await this.sendTyping(e.chat.id.toString());let h=v(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(h),true}return false}async toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return v(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 utils.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 utils.Fetch.get(i,{responseType:"arrayBuffer"});if(!r.ok)throw new Error(`Failed to download file: ${r.status}`);let a=utils.Filesystem.dirname(s);await utils.Filesystem.mkdir(a,{recursive:true});let l=Buffer.from(r.data);return await utils.PKG.file(s).write(l),s}async parseContent(e){let s=[],n=e.text??e.caption??"",i=x()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",r=utils.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 l=`photo_${a.file_unique_id}.jpg`,c=utils.Filesystem.join(r,`${e.chat.id}_${a.file_unique_id}_${l}`);await this.downloadBinaryFile(a.file_id,c),this.log.debug("photo downloaded",{filePath:c,fileId:a.file_id}),s.push({type:"image",image:url.pathToFileURL(c).href,mime:"image/jpeg"});}catch(l){this.log.warn("failed to download photo, storing as file",{platform:"telegram",fileId:a.file_id,error:String(l)}),s.push({type:"image",image:a.file_id,mime:"image/jpeg"});}}if(e.document){let a=e.document.mime_type||"application/octet-stream",l=e.document.file_name||"file",c=e.document.file_id;if(a.startsWith("text/"))try{this.log.debug("downloading text file",{fileId:c,fileName:l,mimeType:a});let p=await this.parseFileContent(c),u=await utils.TruncateContent.truncate(p,{maxChars:5e3,label:`file: ${l}`});s.push({type:"text",text:`\u{1F4CE} File: ${l}
12
+
13
+ ${u.content}`});}catch(p){this.log.warn("failed to download text file, storing as file",{platform:"telegram",fileId:c,error:String(p)}),s.push({type:"file",data:c,mime:a});}else try{let p=l.includes(".")?l.split(".").pop():utils.Filesystem.mimeTypeToExt(a)||"bin",u=`${e.document.file_unique_id||c}.${p}`,h=utils.Filesystem.join(r,`${e.chat.id}_${c}_${u}`);this.log.debug("downloading binary file",{filePath:h,fileId:c,fileName:l,mimeType:a}),await this.downloadBinaryFile(c,h),s.push({type:"file",data:url.pathToFileURL(h).href,mime:a});}catch(p){this.log.warn("failed to download file, storing as file",{platform:"telegram",fileId:c,error:String(p)}),s.push({type:"file",data:c,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 p=await utils.TruncateContent.truncate(s,{maxChars:r,label:"telegram message"});a=p.content,this.log.debug("sendApiMessage: message truncated",{originalLength:s.length,maxLength:r,outputPath:p.truncated?p.outputPath:void 0});}let l={chat_id:e,text:a};return n?.parseMode&&n.parseMode!=="None"&&(l.parse_mode=n.parseMode),n?.replyTo&&(l.reply_to_message_id=n.replyTo),n?.replyMarkup&&(l.reply_markup=n.replyMarkup),(await this.request("sendMessage",l)).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 utils.Fetch.post(n,s,{timeout:this.retryState.maxDelay,retries:0,headers:{"Content-Type":"application/json"},signal:this.abortController?.signal}),l=a.data;if(!l.ok){if(l.error_code===429){this.log.warn("Rate limited, retrying after",{retryAfter:a.headers.get("Retry-After")});let c=parseInt(a.headers.get("Retry-After")??"1",10)*1e3;await this.sleep(c);continue}throw f(this.id,"CHANNEL_CONNECTION_FAILED",`Telegram API error: ${l.description}`,l.error_code!==400&&l.error_code!==401)}return l}catch(a){if(a instanceof D||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 l=Math.min(this.retryState.initialDelay*2**r,this.retryState.maxDelay);await this.sleep(l);}}throw f(this.id,"CHANNEL_CONNECTION_FAILED",`Failed after ${this.retryState.maxAttempts+1} attempts: ${i?.message}`,true)}async syncBotCommands(){try{let e=await this.getCommandList();if(this.log.debug("syncBotCommands: commands fetched",{count:e.length,commands:e}),e.length===0){this.log.debug("no commands available");return}let s=new Map,n=e.map(i=>{let r=i.name.replace(/[-_]/g,"").toLowerCase();return s.set(r,i.name),{command:r,description:i.description||r}}).filter(i=>{let r=/^[a-zA-Z0-9_]{1,32}$/.test(i.command);return r||this.log.debug("syncBotCommands: filtered invalid telegram name",{telegramName:i.command,originalName:s.get(i.command)}),r}).map(i=>{let r=i.description||i.command;return r=r.replace(/<[^>]*>/g,"").replace(/./g,a=>a.charCodeAt(0)<=31||a.charCodeAt(0)===127?"":a).trim(),r.length>250&&(this.log.debug("syncBotCommands: truncating description",{command:i.command,originalLength:r.length}),r=r.substring(0,250)+"..."),{...i,description:r}});if(n.length===0){this.log.debug("syncBotCommands: no valid commands after filtering");return}this.log.debug("syncBotCommands: setting telegram commands",{telegramCommands:n}),await this.request("setMyCommands",{commands:n}),this.log.debug("bot commands synced",{count:n.length});}catch(e){this.log.warn("failed to sync bot commands",{error:String(e)});}}};var fe=class extends I{constructor(e="discord-main"){super();chunk3SBZTZXS_cjs.a(this,"id");chunk3SBZTZXS_cjs.a(this,"platform","discord");chunk3SBZTZXS_cjs.a(this,"name","Discord Bot");chunk3SBZTZXS_cjs.a(this,"botConfig",null);chunk3SBZTZXS_cjs.a(this,"baseUrl","https://discord.com/api/v10");chunk3SBZTZXS_cjs.a(this,"gatewayWs",null);chunk3SBZTZXS_cjs.a(this,"heartbeatInterval",null);chunk3SBZTZXS_cjs.a(this,"sessionId",null);chunk3SBZTZXS_cjs.a(this,"sequenceNumber",null);chunk3SBZTZXS_cjs.a(this,"abortController",null);chunk3SBZTZXS_cjs.a(this,"processedMessageIds",new Set);chunk3SBZTZXS_cjs.a(this,"sentMessages",new Map);chunk3SBZTZXS_cjs.a(this,"sessionIdMap",new Map);chunk3SBZTZXS_cjs.a(this,"commandRouter",new Map);chunk3SBZTZXS_cjs.a(this,"reconnectAttempts",0);chunk3SBZTZXS_cjs.a(this,"maxReconnectAttempts",5);chunk3SBZTZXS_cjs.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(c=>c.type==="image"),r=e.content.find(c=>c.type==="file"),a=e.metadata.context?.replyTo,l;return i?l=await this.createMessage(s,n,a):r?l=await this.createMessage(s,n,a):l=await this.createMessage(s,n,a),this.sentMessages.set(e.id,{channelId:s,messageId:l.id,timestamp:Date.now()}),this.sessionIdMap.set(e.id,e.sessionId),l.id}async createMessage(e,s,n){let r=this.getCapabilities().maxMessageLength-500,a=s;if(s.length>r){let c=await utils.TruncateContent.truncate(s,{maxChars:r,label:"discord message"});a=c.content,this.log.debug("createMessage: message truncated",{originalLength:s.length,maxLength:r,outputPath:c.truncated?c.outputPath:void 0});}let l={content:a};return n&&(l.message_reference={message_id:n}),this.request("POST",`/channels/${e}/messages`,l)}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 v(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=x()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=utils.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",l=a.includes(".")?a.split(".").pop()??"":"png",c=utils.Filesystem.join(i,`discord_${e.channel_id}_${r.id}.${l}`);await this.downloadFile(r.url,c),s.push({type:"image",image:url.pathToFileURL(c).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",l=a.includes(".")?a.split(".").pop()??"":utils.Filesystem.mimeTypeToExt(r.content_type||"")||"bin",c=utils.Filesystem.join(i,`discord_${e.channel_id}_${r.id}.${l}`);if(r.content_type?.startsWith("text/")){let p=await this.downloadTextFile(r.url),u=await utils.TruncateContent.truncate(p,{maxChars:5e3,label:`file: ${a}`});s.push({type:"text",text:`\u{1F4CE} File: ${a}
14
+
15
+ ${u.content}`});}else await this.downloadFile(r.url,c),s.push({type:"file",data:url.pathToFileURL(c).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 utils.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=utils.Filesystem.dirname(s);await utils.Filesystem.mkdir(i,{recursive:true});let r=Buffer.from(n.data);return await utils.PKG.file(s).write(r),s}async downloadTextFile(e){let s=await utils.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 utils.Fetch.get(i,{headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"}}):r=await utils.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 ye=class extends I{constructor(e="slack-main"){super();chunk3SBZTZXS_cjs.a(this,"id");chunk3SBZTZXS_cjs.a(this,"platform","slack");chunk3SBZTZXS_cjs.a(this,"name","Slack Bot");chunk3SBZTZXS_cjs.a(this,"botConfig",null);chunk3SBZTZXS_cjs.a(this,"baseUrl","https://slack.com/api");chunk3SBZTZXS_cjs.a(this,"socketModeClient",null);chunk3SBZTZXS_cjs.a(this,"abortController",null);chunk3SBZTZXS_cjs.a(this,"processedMessageIds",new Set);chunk3SBZTZXS_cjs.a(this,"sentMessages",new Map);chunk3SBZTZXS_cjs.a(this,"sessionIdMap",new Map);chunk3SBZTZXS_cjs.a(this,"commandRouter",new Map);chunk3SBZTZXS_cjs.a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});chunk3SBZTZXS_cjs.a(this,"socketReconnectAttempts",0);chunk3SBZTZXS_cjs.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(c=>c.type==="image"),r=e.content.find(c=>c.type==="file"),a=e.metadata.context?.threadId,l;return i?l=await this.postImage(s,i.image,n,a):r?l=await this.postFile(s,r.data,r.mime,n,a):l=await this.postMessage(s,n,a),this.sentMessages.set(e.id,{channelId:s,ts:l.ts,timestamp:Date.now()}),this.sessionIdMap.set(e.id,e.sessionId),l.ts}async postMessage(e,s,n){let r=this.getCapabilities().maxMessageLength-500,a=s;if(s.length>r){let c=await utils.TruncateContent.truncate(s,{maxChars:r,label:"slack message"});a=c.content,this.log.debug("postMessage: message truncated",{originalLength:s.length,maxLength:r,outputPath:c.truncated?c.outputPath:void 0});}let l={channel:e,text:a};return n&&(l.thread_ts=n),this.request("chat.postMessage",l)}async postImage(e,s,n,i){let r;if(typeof s=="string")if(s.startsWith("http")){let l=await utils.Fetch.get(s,{responseType:"arrayBuffer"}),c=s.split("/").pop()||"image.jpg";r=await this.uploadFile(new Uint8Array(l.data),c);}else if(s.startsWith("file://")){let l=await utils.PKG.file(url.fileURLToPath(s)).bytes(),c=s.split("/").pop()||"image.jpg";r=await this.uploadFile(l,c);}else r=s;else if(s instanceof URL){let l=await utils.Fetch.get(s.toString(),{responseType:"arrayBuffer"}),c=s.pathname.split("/").pop()||"image.jpg";r=await this.uploadFile(new Uint8Array(l.data),c);}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,l="file";if(typeof s=="string")if(s.startsWith("http")){let u=await utils.Fetch.get(s,{responseType:"arrayBuffer"});a=new Uint8Array(u.data),l=s.split("/").pop()||"file";}else s.startsWith("file://")?(a=await utils.PKG.file(url.fileURLToPath(s)).bytes(),l=s.split("/").pop()||"file"):(a=await utils.PKG.file(s).bytes(),l=s.split("/").pop()||"file");else if(s instanceof URL){let u=await utils.Fetch.get(s.toString(),{responseType:"arrayBuffer"});a=new Uint8Array(u.data),l=s.pathname.split("/").pop()||"file";}else a=s;await this.uploadFile(a,l);let p={channel:e,text:i||`File: ${l}`,attachments:[{fallback:l,text:i||l,fields:[{title:"File",value:l,short:true}]}]};return r&&(p.thread_ts=r),this.request("chat.postMessage",p)}async uploadFile(e,s){let n=await utils.Fetch.postForm(`${this.baseUrl}/files.upload`,[{name:"file",value:e,filename:s}],{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 y=>(await this.postMessage(e.channel,y,e.thread_ts)).ts};try{return await r.handler(h),!0}catch(y){return this.log.error("Command handler error",{command:n,error:String(y)}),true}}let a=await this.getCommandList(),l=n.replace(/^\//,""),c=new Map;for(let h of a){let y=h.name.replace(/[-_]/g,"").toLowerCase();c.set(y,h.name);}let p=c.get(l)??l;if(a.some(h=>h.name===p)){let h=v(this.buildSessionId(this.id,e.channel,e.user),"input",[{type:"command",command:p,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()).length===0)return;let n=[...Array.from(this.commandRouter.values()).map(i=>({command:i.command.replace(/^\//,""),description:i.description}))];if(n.length===0)return;await this.request("commands.set",{commands:n}),this.log.debug("Bot commands synced",{count:n.length});}catch(e){this.log.warn("Failed to sync bot commands",{error:String(e)});}}async toGatewayMessage(e){let s=this.buildSessionId(this.id,e.channel,e.user);return v(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=x()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=utils.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`,l=a.includes(".")?a.split(".").pop():"jpg",c=utils.Filesystem.join(i,`slack_${e.channel}_${r.id}.${l}`);await this.downloadFile(r.url_private_download||r.url_private,c),s.push({type:"image",image:url.pathToFileURL(c).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}`,l=a.includes(".")?a.split(".").pop():utils.Filesystem.mimeTypeToExt(r.mimetype)||"bin",c=utils.Filesystem.join(i,`slack_${e.channel}_${r.id}.${l}`);if(r.mimetype.startsWith("text/")){let p=await this.downloadTextFile(r.url_private),u=await utils.TruncateContent.truncate(p,{maxChars:5e3,label:`file: ${a}`});s.push({type:"text",text:`\u{1F4CE} File: ${a}
16
+
17
+ ${u.content}`});}else await this.downloadFile(r.url_private_download||r.url_private,c),s.push({type:"file",data:url.pathToFileURL(c).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 utils.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=utils.Filesystem.dirname(s);await utils.Filesystem.mkdir(i,{recursive:true});let r=Buffer.from(n.data);return await utils.PKG.file(s).write(r),s}async downloadTextFile(e){let s=await utils.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 utils.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 be=class extends I{constructor(e="feishu-main"){super();chunk3SBZTZXS_cjs.a(this,"id");chunk3SBZTZXS_cjs.a(this,"platform","feishu");chunk3SBZTZXS_cjs.a(this,"name","Feishu Bot");chunk3SBZTZXS_cjs.a(this,"botConfig",null);chunk3SBZTZXS_cjs.a(this,"baseUrl","https://open.feishu.cn/open-apis");chunk3SBZTZXS_cjs.a(this,"tenantAccessToken",null);chunk3SBZTZXS_cjs.a(this,"tokenExpireTime",0);chunk3SBZTZXS_cjs.a(this,"abortController",null);chunk3SBZTZXS_cjs.a(this,"processedMessageIds",new Set);chunk3SBZTZXS_cjs.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(l=>l.type==="image"),r=e.content.find(l=>l.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 utils.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 c=await utils.TruncateContent.truncate(s,{maxChars:i,label:"feishu message"});r=c.content,this.log.debug("sendMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:c.truncated?c.outputPath:void 0});}let l=(await utils.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(l.code!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`Feishu API error: ${l.msg}`);return l.data.message_id}async sendImage(e,s,n){let i;if(typeof s=="string")if(s.startsWith("http")){let a=await utils.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 utils.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 utils.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 l=await utils.Fetch.get(s,{responseType:"arrayBuffer"});i=await this.uploadFile(new Uint8Array(l.data),"file");}else i=s;else if(s instanceof URL){let l=await utils.Fetch.get(s.toString(),{responseType:"arrayBuffer"});i=await this.uploadFile(new Uint8Array(l.data),"file");}else i=await this.uploadFile(s,"file");let a=await utils.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 utils.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 utils.Fetch.postForm(`${this.baseUrl}/im/v1/files`,[{name:"file",value:e,filename:s}],{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 v(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=x()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=utils.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=utils.Filesystem.join(i,`feishu_${e.chat_id}_${r.image_key}.jpg`);await this.downloadImage(r.image_key,a),s.push({type:"image",image:url.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}`,l=a.includes(".")?a.split(".").pop():utils.Filesystem.mimeTypeToExt(r.file_type)||"bin",c=utils.Filesystem.join(i,`feishu_${e.chat_id}_${r.file_key}.${l}`);await this.downloadFile(r.file_key,c),s.push({type:"file",data:url.pathToFileURL(c).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 utils.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=utils.Filesystem.dirname(s);await utils.Filesystem.mkdir(i,{recursive:true});let r=Buffer.from(n.data);return await utils.PKG.file(s).write(r),s}async downloadFile(e,s){await this.ensureTokenValid();let n=await utils.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=utils.Filesystem.dirname(s);await utils.Filesystem.mkdir(i,{recursive:true});let r=Buffer.from(n.data);return await utils.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 Ce=class extends I{constructor(e="wechat-main"){super();chunk3SBZTZXS_cjs.a(this,"id");chunk3SBZTZXS_cjs.a(this,"platform","wechat");chunk3SBZTZXS_cjs.a(this,"name","WeChat Bot");chunk3SBZTZXS_cjs.a(this,"botConfig",null);chunk3SBZTZXS_cjs.a(this,"accessToken",null);chunk3SBZTZXS_cjs.a(this,"tokenExpireTime",0);chunk3SBZTZXS_cjs.a(this,"abortController",null);chunk3SBZTZXS_cjs.a(this,"processedMessageIds",new Set);chunk3SBZTZXS_cjs.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 utils.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 c=await utils.TruncateContent.truncate(s,{maxChars:i,label:"wechat message"});r=c.content,this.log.debug("sendOfficialMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:c.truncated?c.outputPath:void 0});}let l=(await utils.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(l.errcode!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`WeChat API error: ${l.errmsg}`);return l.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,s){let i=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let c=await utils.TruncateContent.truncate(s,{maxChars:i,label:"wecom message"});r=c.content,this.log.debug("sendWeComMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:c.truncated?c.outputPath:void 0});}let l=(await utils.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(l.errcode!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`WeCom API error: ${l.errmsg}`);return l.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 utils.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 utils.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 c=await utils.Fetch.get(e,{responseType:"arrayBuffer"});i=new Uint8Array(c.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}`,l=await utils.Fetch.postForm(a,[{name:"media",value:i,filename:"image.jpg"}],{headers:{Authorization:`Bearer ${this.accessToken}`}});if(l.data.errcode!==0||!l.data.media_id)throw f(this.id,"MESSAGE_SEND_FAILED",`Image upload failed: ${l.data.errmsg}`);return l.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 v(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 Se=class extends I{constructor(e="webchat-main"){super();chunk3SBZTZXS_cjs.a(this,"id");chunk3SBZTZXS_cjs.a(this,"platform","webchat");chunk3SBZTZXS_cjs.a(this,"name","WebChat");chunk3SBZTZXS_cjs.a(this,"webChatConfig",null);chunk3SBZTZXS_cjs.a(this,"connections",new Map);chunk3SBZTZXS_cjs.a(this,"heartbeatInterval",null);chunk3SBZTZXS_cjs.a(this,"abortController",null);chunk3SBZTZXS_cjs.a(this,"processedMessageIds",new Set);chunk3SBZTZXS_cjs.a(this,"sentMessages",new Map);chunk3SBZTZXS_cjs.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(this.wsServer&&s){let a={type:"message",sessionId:s,properties:{sessionId:s,content:e.content,timestamp:e.timestamp||Date.now()}};return this.wsServer.broadcastToSession(s,a),this.sentMessages.set(e.id,{sessionId:s,messageId:e.id,timestamp:Date.now()}),e.id}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(),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}}pushEvent(e,s){this.wsServer&&this.wsServer.broadcastToSession(e,s);}getWebSocketServer(){return this.wsServer}async handleConnection(e,s){let n=this.generateConnectionId();if(this.connections.size>=(this.webChatConfig?.maxConnections??1e3)){e.close(1013,"Maximum connections reached");return}let i={id:n,ws:e,userId:s,lastActivity:Date.now()};this.connections.set(n,i),e.onmessage=r=>{this.handleWebSocketMessage(i,r.data.toString());},e.onclose=()=>{this.connections.delete(n),this.log.debug("WebSocket closed",{connId:n,userId:s});},e.onerror=r=>{this.log.error("WebSocket error",{connId:n,userId:s,error:String(r)});},this.log.info("WebSocket connected",{connId:n,userId:s});}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 q(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=v(s.sessionId,"input",s.content,{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},context:{conversationId:s.sessionId},...s.metadata});await this.handleMessage(n);}startHeartbeat(){let e=this.webChatConfig?.heartbeatInterval??3e4;this.heartbeatInterval=setInterval(()=>{let s=Date.now(),n=this.webChatConfig?.connectionTimeout??6e4;for(let[i,r]of this.connections)s-r.lastActivity>n&&(this.log.info("Closing inactive connection",{connId:i}),r.ws.close(1001,"Connection timeout"),this.connections.delete(i));},e);}findConnectionByUser(e){for(let s of this.connections.values())if(s.userId===e)return s}generateConnectionId(){return `conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}};var we=class extends I{constructor(e="signal-main"){super();chunk3SBZTZXS_cjs.a(this,"id");chunk3SBZTZXS_cjs.a(this,"platform","signal");chunk3SBZTZXS_cjs.a(this,"name","Signal Bot");chunk3SBZTZXS_cjs.a(this,"botConfig",null);chunk3SBZTZXS_cjs.a(this,"abortController",null);chunk3SBZTZXS_cjs.a(this,"lastTimestamp",0);chunk3SBZTZXS_cjs.a(this,"pollingIntervalMs",5e3);chunk3SBZTZXS_cjs.a(this,"processedMessageIds",new Set);chunk3SBZTZXS_cjs.a(this,"sentMessages",new Map);chunk3SBZTZXS_cjs.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 v(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=x()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=utils.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",l=utils.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 l=await utils.TruncateContent.truncate(s,{maxChars:i,label:"signal message"});r=l.content,this.log.debug("sendMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:l.truncated?l.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 utils.Fetch.get(i,{headers:r}):e==="POST"?a=await utils.Fetch.post(i,n,{headers:r}):e==="DELETE"?a=await utils.Fetch.del(i,{headers:r}):a=await utils.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 ve=class extends I{constructor(e="nostr-main"){super();chunk3SBZTZXS_cjs.a(this,"id");chunk3SBZTZXS_cjs.a(this,"platform","nostr");chunk3SBZTZXS_cjs.a(this,"name","Nostr Bot");chunk3SBZTZXS_cjs.a(this,"botConfig",null);chunk3SBZTZXS_cjs.a(this,"relayConnections",new Map);chunk3SBZTZXS_cjs.a(this,"subscriptions",new Map);chunk3SBZTZXS_cjs.a(this,"abortController",null);chunk3SBZTZXS_cjs.a(this,"processedEventIds",new Set);chunk3SBZTZXS_cjs.a(this,"sentMessages",new Map);chunk3SBZTZXS_cjs.a(this,"relayReconnectAttempts",new Map);chunk3SBZTZXS_cjs.a(this,"maxReconnectAttempts",5);chunk3SBZTZXS_cjs.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 v(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(l=>l.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 gt=class extends I{constructor(e){super();chunk3SBZTZXS_cjs.a(this,"id");chunk3SBZTZXS_cjs.a(this,"platform");chunk3SBZTZXS_cjs.a(this,"name");chunk3SBZTZXS_cjs.a(this,"version");chunk3SBZTZXS_cjs.a(this,"options");this.id=e.id,this.platform=e.platform||"custom",this.name=e.name,this.version=e.version||"1.0.0",this.options=e,this.initLog();}async doStart(){this.options.setup?.initialize&&await this.options.setup.initialize(),this.log.info("Channel plugin started",{id:this.id,platform:this.platform});}async doStop(){this.options.setup?.destroy&&await this.options.setup.destroy(),this.log.info("Channel plugin stopped",{id:this.id});}async send(e){let 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 tn(g){return new gt(g)}var pt={telegram:me,discord:fe,slack:ye,feishu:be,wechat:Ce,webchat:Se,signal:we,nostr:ve};function Ro(){return Object.keys(pt)}var V=class V{constructor(t){chunk3SBZTZXS_cjs.a(this,"log",chunk3SBZTZXS_cjs.b.create({service:"gateway:server"}));chunk3SBZTZXS_cjs.a(this,"config");chunk3SBZTZXS_cjs.a(this,"router");chunk3SBZTZXS_cjs.a(this,"sessionManager");chunk3SBZTZXS_cjs.a(this,"pluginLoader");chunk3SBZTZXS_cjs.a(this,"messageStore");chunk3SBZTZXS_cjs.a(this,"contactStore",null);chunk3SBZTZXS_cjs.a(this,"wsServer",null);chunk3SBZTZXS_cjs.a(this,"running",false);chunk3SBZTZXS_cjs.a(this,"connections",0);chunk3SBZTZXS_cjs.a(this,"gatewayAgent",null);this.log.debug("GatewayServer.constructor: starting"),this.config=t,this.log.debug("GatewayServer.constructor: creating MessageRouter");let e=Q()?O().hookRegistry:void 0;this.router=new je(e),this.log.debug("GatewayServer.constructor: creating GatewaySessionManager");let s=x();this.sessionManager=new ue({storagePath:`${s.Path.data}/gateway/sessions`,enablePersistence:true}),this.log.debug("GatewayServer.constructor: creating ChannelPluginLoader"),this.pluginLoader=new he({healthCheckInterval:6e4}),this.log.debug("GatewayServer.constructor: pluginLoader created");let n=Q();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:n}),this.messageStore=new ce({storagePath:`${s.Path.data}/gateway/messages`}),this.pluginLoader.setMessageHandler({onMessage:i=>this.onMessage(i),onEvent:i=>this.onEvent(i)}),this.log.debug("GatewayServer.constructor: completed");}async loadChannelPlugins(){try{let{config:t}=await P(),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=pt[s];if(!i){this.log.warn("no plugin class found for platform",{platform:s});continue}let r=`${s}-main`,a=new i(r),l={enabled:!0,platform:n,session:{autoCreate:!0,resetPolicy:"onNewConversation"},routing:{broadcast:!0,dispatchToSubAgent:!0}};try{await this.pluginLoader.register(a,l),this.log.info("channel plugin registered",{platform:s,id:r});}catch(c){this.log.error("failed to register channel plugin",{platform:s,error:String(c)});}}}catch(t){this.log.error("failed to load channel plugins",{error:String(t)});}}async start(){if(this.log.debug("GatewayServer.start: called"),this.running){this.log.warn("gateway server is already running");return}this.log.info("starting gateway server",{port:this.config.port,hostname:this.config.hostname}),this.log.debug("GatewayServer.start: initializing sessionManager"),await this.sessionManager.initialize(),this.log.debug("GatewayServer.start: sessionManager initialized"),this.log.debug("GatewayServer.start: initializing contactStore");let e=`${x().Path.data}/gateway`,s=new ge({baseDir:e});this.contactStore=new pe(s,{cacheSize:1e3}),this.contactStore.initialize&&await this.contactStore.initialize(),this.log.debug("GatewayServer.start: contactStore initialized"),this.log.debug("GatewayServer.start: creating WebSocket server"),this.wsServer=new q({port:this.config.port,hostname:this.config.hostname,path:String(this.config.path??"/")}),this.log.debug("GatewayServer.start: calling wsServer.start()"),await this.wsServer.start(),this.log.debug("GatewayServer.start: wsServer started"),await this.loadChannelPlugins(),this.log.debug("GatewayServer.start: starting plugins in background"),this.pluginLoader.startAll().catch(p=>{this.log.error("plugin startup error",{error:String(p)});}),this.log.debug("GatewayServer.start: plugins startup initiated"),this.log.debug("GatewayServer.start: starting health check timer"),this.pluginLoader.startHealthCheckTimer();let{config:n}=await P(),i=n.defaults;this.wsServer.setChannelResolveDeps({sessionManager:{get:p=>this.sessionManager.get(p),getOrCreate:(p,u)=>this.sessionManager.getOrCreate(p,u),bindBackendSession:(p,u)=>this.sessionManager.bindBackendSession(p,u),getAll:()=>this.sessionManager.getAllSessions()},pluginLoader:{getPlugin:p=>this.pluginLoader.getPlugin(p),getAllPlugins:()=>this.pluginLoader.getAllPlugins(),isRunning:p=>this.pluginLoader.isRunning(p)},defaultChannel:i?.channel,fallbackChannels:i?.fallbackChannels,contactStore:this.contactStore?{findByPlatformId:(p,u)=>this.contactStore.findByPlatformId(p,u),findByUid:p=>this.contactStore.findByUid(p),listByPlatform:(p,u,h)=>this.contactStore.listByPlatform(p,u,h),count:p=>this.contactStore.count(p)}:void 0}),this.wsServer.setPluginLoader((p,u,h)=>this.sendToChannel(p,u,h));let r=await this.messageStore.loadFromDisk();this.log.debug("loaded messages from disk",{count:r});let a=Date.now(),l=6e4,c=()=>{let p=Date.now()-a,u=this.pluginLoader.getAllPlugins(),h=u.filter(y=>this.pluginLoader.isRunning(y.id));h.length===u.length&&u.length>0?(this.log.debug("all plugins ready, proceeding with message retry"),this.retryPendingMessages().catch(y=>{this.log.error("failed to retry pending messages",{error:String(y)});})):p>l?(this.log.warn("plugin startup timeout, proceeding with message retry anyway",{elapsed:p}),this.retryPendingMessages().catch(y=>{this.log.error("failed to retry pending messages",{error:String(y)});})):(this.log.debug("waiting for plugins to be ready",{elapsed:p,ready:h.length,total:u.length}),setTimeout(c,100));};c(),this.running=true,this.log.debug("GatewayServer.start: completed"),this.log.info("gateway server started");}async stop(){if(!this.running){this.log.warn("gateway server is not running");return}this.log.info("stopping gateway server"),this.wsServer&&(this.log.debug("stopping WebSocket server"),await this.wsServer.stop(),this.wsServer=null,this.log.debug("WebSocket server stopped")),this.pluginLoader.stopHealthCheckTimer(),await this.pluginLoader.stopAll(),await this.router.shutdown(),await this.sessionManager.close(),await this.messageStore.close(),this.contactStore?.close&&await this.contactStore.close(),this.running=false,this.log.info("gateway server stopped");}getStatus(){return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections}}async onMessage(t){this.log.debug("message received",{id:t.id,sessionId:t.sessionId,type:t.type});let e=this.messageStore.get(t.id);if(e&&e.retryCount>V.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(plugin.HookEvent.GatewayMessageReceive,{...t,channel:t.metadata.channel,processorId:t.metadata.processorId,agent:t.metadata.agent}),t.type==="input"&&await this.saveContactFromMessage(t),await this.sessionManager.incrementMessageCountOrCreate(t.sessionId,t.metadata.channel);let s=true;try{let n=await this.router.route(t);if(s=n.success,!n.dispatched&&t.type==="input"){let{config:i}=await P(),r=i.agentProcessing??{mode:"localAgent",localAgentPriority:1,subAgentPriority:2,timeout:3e5,retryOnFailure:!0};this.log.debug("no subscribers, dispatching to agent",{id:t.id,mode:r.mode}),this.dispatchToAgent(t,r).catch(a=>{this.log.error("agent dispatch failed",{id:t.id,error:String(a)}),s=!1;});}}catch(n){s=false,this.log.error("route failed",{messageId:t.id,error:String(n)});}t.type==="input"&&!s&&await this.messageStore.incrementRetry(t.id);}async saveContactFromMessage(t){if(!this.contactStore)return;let{platform:e,channelId:s,userId:n,chatId:i}=t.metadata.channel;if(!e||e==="api")return;let r=n||i;if(r)try{let 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(!Q()){this.log.debug("no agent adapter, message remains pending",{id:t.id});return}let s=O(),n=t.metadata.channel,r=this.sessionManager.get(t.sessionId)?.backendSessionId||void 0,a=this.buildChannelContext(t,n);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(!O().sdk)return null;this.gatewayAgent=vt({});}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.info("dispatching message to GatewayAgent",{id:t.id,sessionId:t.sessionId,backendSessionId:i}),this.triggerHook(plugin.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(l=>{let c=l.data?.id;this.executeGatewayAgent(t,e,r,c,s);});}):n.sdk.session.create({title:`Gateway-${e?.platform||"unknown"}`}).then(a=>{let l=a.data?.id;this.executeGatewayAgent(t,e,r,l,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.info("backend session bound",{gatewaySessionId:t.sessionId,backendSessionId:r})),this.triggerHook(plugin.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.info("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 l=`\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:l}],metadata:{channel:e,processorId:n,proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}).catch(c=>{this.log.error("failed to send error response",{error:String(c)});});}this.triggerHook(plugin.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.info("dispatching message to SubAgent",{id:t.id,sessionId:t.sessionId}),this.triggerHook(plugin.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",l=e?.userId||e?.chatId||"unknown user",c=`${a}:${l}`,p={source:t.sessionId,title:`[${a}] Message from ${l}`,agent:"gateway",sessionId:i,parts:t.content,system:s,channel:{platform:a,contactUid:c,channelId:e?.channelId,userId:l}};r.run(p).then(u=>{this.handleAgentResult(t,e,u,"subAgent",i);},u=>{this.handleAgentError(t,e,u,"subAgent",i);});}async triggerHook(t,e){if(Q())try{await O().hookRegistry.triggerEvent(t,e,{messageStore:{store:async(n,i)=>{let r=Ie(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()-V.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>V.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(c=>{this.log.error("failed to re-dispatch stuck message",{messageId:r.id,error:String(c)});});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(c=>{this.log.error("failed to retry message",{messageId:r.id,error:String(c)});});}}}this.log.info("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(plugin.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(plugin.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(Q())try{await O().hookRegistry.triggerEvent(plugin.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(p,u)=>{let h=Ie(p);await this.messageStore.store(h,u);},updateStatus:async(p,u,h)=>{await this.messageStore.updateStatus(p,u,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 l;try{l=await a.send(e),this.log.debug("sendToChannel: plugin.send completed",{pluginId:t,messageId:e.id,result:l});}catch(c){throw this.log.error("sendToChannel: plugin.send failed",{pluginId:t,messageId:e.id,error:String(c)}),await this.messageStore.incrementRetry(e.id),await this.messageStore.updateStatus(e.id,"failed",{error:String(c)}),c}return l}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)}};chunk3SBZTZXS_cjs.a(V,"MAX_RETRY_COUNT",3),chunk3SBZTZXS_cjs.a(V,"SEVEN_DAYS_MS",10080*60*1e3);var Ot=V;exports.$=Bs;exports.A=xs;exports.B=ks;exports.C=Ts;exports.D=Es;exports.E=_s;exports.F=Rs;exports.G=Ds;exports.H=Ns;exports.I=Gs;exports.J=Ls;exports.K=Us;exports.L=wt;exports.M=Vn;exports.N=Jn;exports.O=Q;exports.P=O;exports.Q=x;exports.R=tt;exports.S=v;exports.T=Bt;exports.U=Ie;exports.V=Qe;exports.W=Ye;exports.X=Ze;exports.Y=nt;exports.Z=Fs;exports._=Os;exports.a=xe;exports.aa=Ws;exports.b=ke;exports.ba=je;exports.c=Te;exports.ca=ce;exports.d=Ee;exports.da=de;exports.e=_e;exports.ea=ue;exports.f=Re;exports.fa=he;exports.g=De;exports.ga=q;exports.h=ut;exports.ha=I;exports.i=ht;exports.ia=me;exports.j=mt;exports.ja=fe;exports.k=ft;exports.ka=ye;exports.l=yt;exports.la=be;exports.m=Ne;exports.ma=Ce;exports.n=Ge;exports.na=Se;exports.o=Le;exports.oa=we;exports.p=Ue;exports.pa=ve;exports.q=Fe;exports.qa=tn;exports.r=Oe;exports.ra=pt;exports.s=Me;exports.sa=Ro;exports.t=et;exports.ta=Ot;exports.u=Qt;exports.v=bt;exports.w=Ct;exports.x=St;exports.y=As;exports.z=Ms;
@@ -0,0 +1 @@
1
+ 'use strict';var chunkRFOEJ3A2_cjs=require('./chunk-RFOEJ3A2.cjs');require('./chunk-3SBZTZXS.cjs');Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.fa}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ta}});Object.defineProperty(exports,"GatewayWebSocketServer",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ga}});
@@ -0,0 +1 @@
1
+ export{fa as ChannelPluginLoader,ta as GatewayServer,ga as GatewayWebSocketServer}from'./chunk-OBFSXYWV.mjs';import'./chunk-RGPJTZUB.mjs';