@easbot/gateway 0.3.17 → 0.3.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +28 -1
- package/README.md +27 -1
- package/dist/chunks/{chunk-JRI2CLB3.cjs → chunk-6SU6Q632.cjs} +8 -8
- package/dist/chunks/{chunk-VVKUBVKT.mjs → chunk-GMRR37C2.mjs} +8 -8
- package/dist/chunks/server-BBSQKKRF.cjs +1 -0
- package/dist/chunks/server-UBBH7SQ3.mjs +1 -0
- package/dist/index.cjs +23 -23
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.mjs +17 -17
- package/package.json +5 -5
- package/dist/chunks/server-CGEOYYKW.cjs +0 -1
- package/dist/chunks/server-QO3EP45A.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var chunk6C5TBG7Z_cjs=require('./chunk-6C5TBG7Z.cjs'),utils=require('@easbot/utils'),u=require('zod'),ue=require('path'),te=require('fs'),$=require('fs/promises'),ws=require('ws'),$i=require('https'),Wi=require('http'),Hi=require('crypto'),url=require('url'),os$1=require('os'),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 u__default=/*#__PURE__*/_interopDefault(u);var ue__namespace=/*#__PURE__*/_interopNamespace(ue);var te__namespace=/*#__PURE__*/_interopNamespace(te);var $__namespace=/*#__PURE__*/_interopNamespace($);var $i__default=/*#__PURE__*/_interopDefault($i);var Wi__default=/*#__PURE__*/_interopDefault(Wi);var Hi__default=/*#__PURE__*/_interopDefault(Hi);function I(o,t,e,s){return {id:utils.Identifier.ascending("message"),sessionId:o,type:t,content:e,metadata:{channel:{platform:s?.channel?.platform??"api",channelId:s?.channel?.channelId??"default",userId:s?.channel?.userId,chatId:s?.channel?.chatId,...Object.fromEntries(Object.entries(s?.channel??{}).filter(([n])=>!["platform","channelId","userId","chatId"].includes(n)))},context:s?.context,agent:s?.agent},timestamp:Date.now()}}function Cn(o,t,e,s){return I(o,t,[{type:"text",text:e}],s)}function Ke(o){let t={platform:o.channel?.platform??"api",channelId:o.channel?.channelId??"unknown",chatId:o.channel?.chatId,userId:o.channel?.userId,chatType:o.channel?.chatType,chatTitle:o.channel?.chatTitle};return {id:o.id,sessionId:o.sessionId,type:o.type,content:Array.isArray(o.content)?o.content:[{type:"text",text:String(o.content??"")}],metadata:{channel:t,replyToMessageId:o.replyToMessageId,processorId:o.processorId,agent:o.agent,proactive:o.proactive??!o.replyToMessageId},timestamp:o.timestamp??Date.now()}}function Ve(o){if(!o.platform)throw new Error("Invalid session: platform is required");if(!o.channelId)throw new Error("Invalid session: channelId is required");let t=o.chatId??"",e=o.userId??t;if(!t&&!o.userId)throw new Error(`Invalid session: chatId and userId cannot both be empty. platform=${o.platform}, channelId=${o.channelId}`);return [o.platform,o.channelId,t,e].join("_")}function Je(){return {status:"active",messageCount:0,lastMessageAt:null}}function Qe(o,t){if(!o||!t)throw new Error("platform and stableId are required");return `${o}:${t}`}function Xe(o){if(!o||typeof o!="string")return null;let t=o.indexOf(":");if(t<=0||t>=o.length-1)return null;let e=o.slice(0,t),s=o.slice(t+1);return !e||!s?null:{platform:e,stableId:s}}function Tt(o){let{platform:t,stableId:e,profile:s={},aliases:n={},metadata:i}=o;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:Qe(t,e),platform:t,stableId:e,aliases:{...n},profile:{...s},createdAt:r,lastSeenAt:r,metadata:i}}function _t(o,t){return `sub_${o}_${t}`}var vn=utils.Log.create({service:"gateway:config"});u__default.default.enum(["telegram","slack","feishu","wechat","weixin","webchat","signal","nostr","dingtalk"]);u__default.default.enum(["low","medium","high","critical"]);var Ze=u__default.default.object({enabled:u__default.default.boolean().default(true),botToken:u__default.default.string().describe("Telegram Bot Token"),webhookUrl:u__default.default.string().optional().describe("Webhook URL for receiving updates"),polling:u__default.default.object({enabled:u__default.default.boolean().default(true),interval:u__default.default.number().int().positive().optional().describe("Polling interval in ms"),timeout:u__default.default.number().int().positive().optional().default(30).describe("Long polling timeout in seconds")}).refine(o=>o===void 0||o.enabled,{message:"polling.enabled must be true when polling is configured"}).optional(),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),et=u__default.default.object({enabled:u__default.default.boolean().default(true),botToken:u__default.default.string().describe("Slack Bot Token (xoxb-*)"),appToken:u__default.default.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:u__default.default.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),tt=u__default.default.object({enabled:u__default.default.boolean().default(true),appId:u__default.default.string().describe("Feishu App ID"),appSecret:u__default.default.string().describe("Feishu App Secret"),encryptKey:u__default.default.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:u__default.default.string().optional().describe("Feishu Verification Token"),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),st=u__default.default.object({enabled:u__default.default.boolean().default(true),mode:u__default.default.enum(["official","wecom"]).default("official"),appId:u__default.default.string().describe("WeChat App ID"),appSecret:u__default.default.string().describe("WeChat App Secret"),token:u__default.default.string().optional().describe("WeChat Token for message verification"),encodingAESKey:u__default.default.string().optional().describe("WeChat Encoding AES Key"),agentId:u__default.default.string().optional().describe("WeCom Agent ID"),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),In=u__default.default.object({enabled:u__default.default.boolean().default(true),stateDir:u__default.default.string().optional().describe("Override the default account persistence directory (default: ~/.easbot/channels/weixin)"),baseUrl:u__default.default.string().optional().describe("Override the iLink API baseUrl (default: https://ilinkai.weixin.qq.com)"),cdnBaseUrl:u__default.default.string().optional().describe("Override the CDN baseUrl (default: https://novac2c.cdn.weixin.qq.com/c2c)"),maxMessageLength:u__default.default.number().int().positive().optional().default(4e3),timeout:u__default.default.number().int().positive().optional().default(3e4)}),nt=u__default.default.object({enabled:u__default.default.boolean().default(true),path:u__default.default.string().optional().default("/"),heartbeatInterval:u__default.default.number().int().positive().optional().default(3e4),connectionTimeout:u__default.default.number().int().positive().optional().default(36e5),maxConnections:u__default.default.number().int().positive().optional().default(1e3),cors:u__default.default.boolean().optional().default(true)}),it=u__default.default.object({enabled:u__default.default.boolean().default(true),serviceUrl:u__default.default.string().optional().default("https://chat.signal.org"),phoneNumber:u__default.default.string().describe("Signal phone number"),password:u__default.default.string().optional().describe("Signal account password"),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),rt=u__default.default.object({enabled:u__default.default.boolean().default(true),relays:u__default.default.array(u__default.default.string()).min(1).describe("Nostr relay URLs"),privateKey:u__default.default.string().optional().describe("Nostr private key (hex)"),publicKey:u__default.default.string().optional().describe("Nostr public key (hex)"),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),An=u__default.default.object({enabled:u__default.default.boolean().default(true),appKey:u__default.default.string().describe("DingTalk AppKey"),appSecret:u__default.default.string().describe("DingTalk AppSecret"),token:u__default.default.string().optional().describe("DingTalk token for signature verification"),encryptKey:u__default.default.string().optional().describe("DingTalk encrypt key for message encryption"),webhook:u__default.default.object({enabled:u__default.default.boolean().default(true),path:u__default.default.string().optional().default("/dingtalk/webhook"),port:u__default.default.number().int().positive().optional().describe("Webhook server port")}).optional(),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),ss=u__default.default.object({telegram:Ze.optional(),slack:et.optional(),feishu:tt.optional(),wechat:st.optional(),weixin:In.optional(),webchat:nt.optional(),signal:it.optional(),nostr:rt.optional(),dingtalk:An.optional()}),ns=u__default.default.object({enabled:u__default.default.boolean().default(false),cert:u__default.default.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:u__default.default.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:u__default.default.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:u__default.default.string().optional().describe("Path to SSL key file (alias of key)"),ca:u__default.default.string().optional().describe("Path to CA certificate file"),forceRedirect:u__default.default.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:u__default.default.number().int().positive().optional().default(80).describe("HTTP redirect port")}),Pn=u__default.default.object({name:u__default.default.string().describe("Token name/description"),value:u__default.default.string().describe("Token value"),permissions:u__default.default.array(u__default.default.string()).default(["*"]).describe("Associated permissions"),expiresAt:u__default.default.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:u__default.default.string().optional().describe("Token description")}),xn=u__default.default.object({enabled:u__default.default.boolean().default(true),tokens:u__default.default.array(Pn).default([]).describe("List of valid tokens"),onInvalid:u__default.default.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:u__default.default.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:u__default.default.array(u__default.default.string()).default([]).describe("Default permissions for anonymous users")}),Mn=u__default.default.object({enabled:u__default.default.boolean().default(false),authorizationServer:u__default.default.string().describe("OAuth2 authorization server URL"),clientId:u__default.default.string().describe("OAuth2 client ID"),clientSecret:u__default.default.string().describe("OAuth2 client secret"),tokenValidationEndpoint:u__default.default.string().describe("OAuth2 token validation endpoint"),scope:u__default.default.array(u__default.default.string()).default([]).describe("OAuth2 scopes")}),is=u__default.default.object({type:u__default.default.enum(["token","oauth2"]).default("token"),token:xn.optional(),oauth2:Mn.optional()}),rs=u__default.default.object({mode:u__default.default.enum(["pull","push","both"]).default("both"),interval:u__default.default.number().int().positive().default(3e4),pushEvents:u__default.default.array(u__default.default.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:u__default.default.enum(["latest","local","remote"]).default("latest")}),kn=u__default.default.object({id:u__default.default.string().describe("Gateway node ID"),address:u__default.default.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:u__default.default.boolean().default(true),metadata:u__default.default.record(u__default.default.string(),u__default.default.any()).optional()}),as=u__default.default.object({nodeId:u__default.default.string().describe("Current gateway node ID"),nodes:u__default.default.array(kn).default([]).describe("Other gateway nodes in the cluster"),sync:rs.optional()}),at=u__default.default.object({maxConnectionsPerChannel:u__default.default.number().int().positive().default(100),idleTimeout:u__default.default.number().int().positive().default(3e5),reuseStrategy:u__default.default.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:u__default.default.number().int().positive().default(6e4),acquireTimeout:u__default.default.number().int().positive().default(5e3),warmupCount:u__default.default.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),ot=u__default.default.object({maxLength:u__default.default.number().int().positive().default(1e4),concurrency:u__default.default.number().int().positive().default(100),batchSize:u__default.default.number().int().positive().default(10),batchTimeout:u__default.default.number().int().positive().default(100),priorityLevels:u__default.default.number().int().positive().default(4)}),ct=u__default.default.object({failureThreshold:u__default.default.number().int().positive().default(5),successThreshold:u__default.default.number().int().positive().default(3),timeout:u__default.default.number().int().positive().default(3e4),halfOpenDuration:u__default.default.number().int().positive().default(15e3)}),lt=u__default.default.object({heartbeatInterval:u__default.default.number().int().positive().default(6e4),heartbeatTimeout:u__default.default.number().int().positive().default(3e5),heartbeatCheckInterval:u__default.default.number().int().positive().default(3e5),autoDeregisterTimeout:u__default.default.number().int().positive().default(6e5),maxAgents:u__default.default.number().int().positive().default(100),persistenceFile:u__default.default.string().optional().describe("Path to persist agent registrations"),maxRegistrations:u__default.default.number().int().positive().default(1e3)}),dt=u__default.default.object({sessionTimeout:u__default.default.number().int().positive().default(18e5),resumeGracePeriod:u__default.default.number().int().positive().default(3e5),maxSessions:u__default.default.number().int().positive().default(1e4),persistenceFile:u__default.default.string().optional().describe("Path to persist sessions")}),gt=u__default.default.object({enabled:u__default.default.boolean().default(true),port:u__default.default.number().int().positive().default(8080),hostname:u__default.default.string().default("localhost"),path:u__default.default.string().optional().default("/"),maxConnections:u__default.default.number().int().positive().optional().default(1e3),connectionTimeout:u__default.default.number().int().positive().optional().default(36e5),heartbeatInterval:u__default.default.number().int().positive().optional().default(3e4),sessionExpireMs:u__default.default.number().int().positive().optional().default(36e5),https:ns.optional(),auth:is.optional(),cors:u__default.default.boolean().default(true),corsOrigins:u__default.default.array(u__default.default.string()).optional(),mdns:u__default.default.boolean().default(false),mdnsDomain:u__default.default.string().optional().default("gateway.easbot.local")}),Tn=u__default.default.object({channel:u__default.default.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:u__default.default.array(u__default.default.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),_n=u__default.default.enum(["localAgent","subAgent","both"]),En=u__default.default.object({mode:_n.default("localAgent").describe("Agent processing mode: localAgent, subAgent, or both"),localAgentPriority:u__default.default.number().int().min(1).max(10).default(1).describe("Priority for localAgent (lower = higher priority)"),subAgentPriority:u__default.default.number().int().min(1).max(10).default(2).describe("Priority for subAgent (lower = higher priority)"),timeout:u__default.default.number().int().positive().optional().default(3e5).describe("Timeout for agent execution in milliseconds"),retryOnFailure:u__default.default.boolean().default(true).describe("Retry with subAgent when localAgent fails")}),ut=u__default.default.object({autoRegister:u__default.default.boolean().default(true).describe("Whether to auto-register agent on startup"),heartbeatInterval:u__default.default.number().int().positive().default(3e4).describe("Heartbeat interval in milliseconds"),maxReconnectAttempts:u__default.default.number().int().min(0).default(5).describe("Maximum reconnect attempts"),reconnectDelay:u__default.default.number().int().positive().default(3e3).describe("Reconnect delay in milliseconds"),heartbeatTimeout:u__default.default.number().int().positive().default(9e4).describe("Heartbeat timeout in milliseconds")}),Ye=u__default.default.object({server:gt.optional(),channels:ss.optional(),cluster:as.optional(),connectionPool:at.optional(),messageQueue:ot.optional(),circuitBreaker:ct.optional(),agentRegistry:lt.optional(),session:dt.optional(),defaults:Tn.optional(),agentProcessing:En.optional(),client:ut.optional().describe("Gateway client config for agent registration"),defaultAgent:u__default.default.string().optional().describe("Default agent ID for routing"),logLevel:u__default.default.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(u__default.default.unknown());function Et(o){let t=Ye.safeParse(o);return t.success||vn.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:Ye.parse({})}function Rn(o){return Ye.parse(o)}var D=utils.Log.create({service:"sdk-event-bus"}),pt=(i=>(i.SDK_SESSION_STATUS="agent.status",i.SDK_ERROR="sdk.error",i.SDK_SESSION_UPDATE="sdk.session_update",i.SDK_PERMISSION_REQUEST="sdk.permission_request",i.SDK_SESSION_DELETED="sdk.session_deleted",i))(pt||{});u.z.object({sessionId:u.z.string(),status:u.z.enum(["idle","busy","retry"]),timestamp:u.z.number()});u.z.object({error:u.z.string(),context:u.z.record(u.z.string(),u.z.any()).optional(),timestamp:u.z.number()});u.z.object({sessionId:u.z.string(),sessionEvent:u.z.unknown(),timestamp:u.z.number()});u.z.object({requestId:u.z.string(),sessionId:u.z.string(),permission:u.z.string(),tool:u.z.object({callId:u.z.string().optional()}).optional(),metadata:u.z.record(u.z.string(),u.z.any()).optional(),timestamp:u.z.number()});u.z.object({sessionId:u.z.string(),timestamp:u.z.number()});var we=class{constructor(){chunk6C5TBG7Z_cjs.a(this,"subscriptions",new Map);chunk6C5TBG7Z_cjs.a(this,"wildcardSubscriptions",new Set);chunk6C5TBG7Z_cjs.a(this,"destroyed",false);}subscribe(t,e){if(this.destroyed)return D.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{};let s=this.subscriptions.get(t)??new Set;return s.add(e),this.subscriptions.set(t,s),D.debug("Subscribed to event",{eventType:t}),()=>{s.delete(e),s.size===0&&this.subscriptions.delete(t),D.debug("Unsubscribed from event",{eventType:t});}}subscribeAll(t){return this.destroyed?(D.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{}):(this.wildcardSubscriptions.add(t),D.debug("Subscribed to all events"),()=>{this.wildcardSubscriptions.delete(t),D.debug("Unsubscribed from all events");})}async publish(t){if(this.destroyed){D.warn("Cannot publish to destroyed SdkEventBus",{type:t.type});return}D.debug("Publishing event",{type:t.type});let e=this.collectCallbacks(t);if(e.length===0){D.debug("No subscribers for event",{type:t.type});return}let s=await Promise.allSettled(e.map(async r=>{try{await r(t);}catch(a){throw D.error("Event callback error",{type:t.type,error:a instanceof Error?a.message:String(a)}),a}})),n=s.filter(r=>r.status==="fulfilled").length,i=s.filter(r=>r.status==="rejected").length;i>0?D.warn("Event callbacks completed with errors",{type:t.type,fulfilled:n,rejected:i}):D.debug("Event callbacks completed",{type:t.type,count:n});}publishSync(t){if(this.destroyed)return;let e=this.collectCallbacks(t);for(let s of e)Promise.resolve().then(()=>s(t)).catch(n=>{D.error("Event callback error (sync)",{type:t.type,error:n instanceof Error?n.message:String(n)});});}collectCallbacks(t){let e=[],s=this.subscriptions.get(t.type);return s&&e.push(...s),e.push(...this.wildcardSubscriptions),e}subscriberCount(t){return t?this.subscriptions.get(t)?.size??0:this.totalSubscribers()}totalSubscribers(){let t=this.wildcardSubscriptions.size;for(let e of this.subscriptions.values())t+=e.size;return t}hasSubscribers(t){return t?(this.subscriptions.get(t)?.size??0)>0||this.wildcardSubscriptions.size>0:this.totalSubscribers()>0}clear(){this.subscriptions.clear(),this.wildcardSubscriptions.clear(),D.debug("All subscriptions cleared");}destroy(){this.clear(),this.destroyed=true,D.info("SdkEventBus destroyed");}isDestroyed(){return this.destroyed}};var P=utils.Log.create({service:"sdk-event-bridge"}),ve=class{constructor(t,e,s){chunk6C5TBG7Z_cjs.a(this,"sdk");chunk6C5TBG7Z_cjs.a(this,"sdkEventBus");chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"started",false);chunk6C5TBG7Z_cjs.a(this,"sessionFilter");chunk6C5TBG7Z_cjs.a(this,"_cachedPrimaryAgents",null);chunk6C5TBG7Z_cjs.a(this,"_messageMetaCache",new Map);this.sdk=t,this.sdkEventBus=e,this.sessionFilter=s;}async getMessageMeta(t,e){let s=`${t}:${e}`,n=this._messageMetaCache.get(s);if(n)return n;let i=await this.sdk.session.message({sessionId:t,messageId:e},{throwOnError:true}).then(a=>a.data).catch(a=>{P.error("unexpected error when fetching message",{error:a,sessionId:t,messageId:e});});if(!i)return;let r={role:i.info.role,agent:i.info.agent};return this._messageMetaCache.set(s,r),r}clearMessageMetaCache(t){let e=`${t}:`;for(let s of this._messageMetaCache.keys())s.startsWith(e)&&this._messageMetaCache.delete(s);}async pushSessionEvent(t){let e=t.properties.sessionId??"";if(!e){P.debug("Dropping session event without sessionId",{type:t.type});return}await this.sdkEventBus?.publish({type:"sdk.session_update",properties:{sessionId:e,sessionEvent:t,timestamp:Date.now()}});}async start(){if(this.started){P.warn("SdkEventBridge already started");return}this.started=true,this.abortController=new AbortController,P.info("Starting SDK event bridge"),this.runEventLoop().catch(t=>{if(this.abortController?.signal.aborted){P.debug("Event loop stopped due to abort");return}P.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&&(P.info("Stopping SDK event bridge"),this.started=false,this.abortController?.abort(),this.abortController=null,this._messageMetaCache.clear(),this._cachedPrimaryAgents=null,P.info("SDK event bridge stopped"));}isStarted(){return this.started}async runEventLoop(){for(;;){if(this.abortController?.signal.aborted){P.debug("Event loop aborted");return}try{let t=this.abortController?.signal;if(!t)return;if(t.aborted){P.debug("Event loop aborted before event call");return}let e=await this.sdk.global.event({signal:t});for await(let s of e.stream){if(this.abortController?.signal.aborted){P.debug("Event loop aborted during iteration");return}let n=s?.payload;n&&await this.handleEvent(n).catch(i=>{P.error("Failed to handle event",{error:i instanceof Error?i.message:String(i),type:n.type});});}}catch(t){if(this.abortController?.signal.aborted){P.debug("Event loop aborted, not reconnecting");return}P.error("Event stream error, reconnecting...",{error:t instanceof Error?t.message:String(t)}),await new Promise(e=>setTimeout(e,1e3));}}}async handleEvent(t){switch(P.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:P.debug("Unknown event type, ignoring",{type:t.type});}}async handleSessionDeleted(t){let{sessionId:e}=t;this.sessionFilter&&!this.sessionFilter(e)||(this.clearMessageMetaCache(e),P.debug("Publishing session deleted event to SdkEventBus",{sessionId:e}),await this.sdkEventBus?.publish({type:"sdk.session_deleted",properties:{sessionId:e,timestamp:Date.now()}}));}async handlePermissionAsked(t){let{id:e,sessionId:s,permission:n,tool:i,metadata:r}=t;this.sessionFilter&&!this.sessionFilter(s)||(P.debug("Publishing permission request to SdkEventBus",{id:e,sessionId:s,permission:n}),await this.sdkEventBus?.publish({type:"sdk.permission_request",properties:{requestId:e,sessionId:s,permission:n,tool:i,metadata:r,timestamp:Date.now()}}));}async handleMessagePartUpdated(t){let{part:e,delta:s}=t;if(this.sessionFilter&&!this.sessionFilter(e.sessionId))return;P.debug("Handling message part update",{type:e.type,sessionId:e.sessionId,messageId:e.messageId});let n=await this.getMessageMeta(e.sessionId,e.messageId);n?.role==="assistant"&&(n.agent&&await this.shouldFilterAgent(n.agent)||(e.type==="tool"?await this.handleToolPart(e):e.type==="text"?await this.handleTextPart(e,s):e.type==="reasoning"?await this.handleReasoningPart(e,s):e.type==="step-start"?await this.handleStepStartPart(e):e.type==="step-finish"&&await this.handleStepFinishPart(e)));}async handleToolPart(t){let{sessionId:e,callId:s,tool:n,state:i}=t,r;switch(i.status){case "pending":r={status:"pending"};break;case "running":r={status:"running",input:i.input};break;case "completed":r={status:"completed",input:i.input,output:i.output,title:i.title,metadata:i.metadata};break;case "error":r={status:"error",input:i.input,error:i.error};break;default:P.warn("Unknown tool state, falling back to pending",{tool:n,callId:s,status:i.status}),r={status:"pending"};break}await this.pushSessionEvent({type:"part.updated",properties:{sessionId:e,part:{type:"tool",tool:n,callId:s,state:r}}});}async handleTextPart(t,e){if(t.ignored===true||!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"text",text:n,messageId:t.messageId,time:t.time}}});}async handleStepStartPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-start",messageId:t.messageId}}});}async handleStepFinishPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-finish",messageId:t.messageId,tokens:t.tokens}}});}async handleReasoningPart(t,e){if(!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"reasoning",text:n,messageId:t.messageId,time:t.time}}});}async handleSessionStatus(t){let{sessionId:e,status:s}=t;await this.pushSessionEvent({type:"session.status",properties:{sessionId:e,status:s}}),s.type==="idle"&&this.clearMessageMetaCache(e),P.debug("Session status update sent",{sessionId:e,status:s.type});}async shouldFilterAgent(t){if(!this._cachedPrimaryAgents)try{let s=(await this.sdk.app.agents({})).data||[];this._cachedPrimaryAgents=new Set(s.filter(n=>n.mode==="primary"&&n.hidden!==!0).map(n=>n.name));}catch{this._cachedPrimaryAgents=new Set;}return !this._cachedPrimaryAgents.has(t)}};var ht=utils.Log.create({service:"sdk-message-collector"}),os={includeThinking:false,includeToolDetails:false,includeToolOutput:false,includeSteps:false},Gn={includeThinking:true,includeToolDetails:true,includeToolOutput:true,includeSteps:true},de=class{constructor(t=os){chunk6C5TBG7Z_cjs.a(this,"filterConfig",t);chunk6C5TBG7Z_cjs.a(this,"events",[]);chunk6C5TBG7Z_cjs.a(this,"isComplete",false);chunk6C5TBG7Z_cjs.a(this,"hasTextEnd",false);chunk6C5TBG7Z_cjs.a(this,"hasStepFinish",false);chunk6C5TBG7Z_cjs.a(this,"error","");chunk6C5TBG7Z_cjs.a(this,"sessionStatus","idle");chunk6C5TBG7Z_cjs.a(this,"sessionId","");chunk6C5TBG7Z_cjs.a(this,"messageId","");ht.debug("MessageEventCollector created",{filterConfig:t});}addEvent(t){if(!this.shouldIncludeEvent(t)){this.checkCompletion(t);return}this.events.push(t),this.checkCompletion(t);}shouldIncludeEvent(t){if(t.type!=="part.updated")return true;let e=t.properties.part;return e?!(e.type==="reasoning"&&!this.filterConfig.includeThinking||e.type==="tool"&&e.state?.status==="running"&&!this.filterConfig.includeToolDetails||(e.type==="step-start"||e.type==="step-finish")&&!this.filterConfig.includeSteps):true}checkCompletion(t){if(t.properties.sessionId&&(this.sessionId=t.properties.sessionId),t.properties.info?.id&&(this.sessionId=t.properties.info.id),t.type==="part.updated"){let e=t.properties.part;if(!e)return;e.type==="text"&&e.time?.end?(this.hasTextEnd=true,e.messageId&&(this.messageId=e.messageId)):e.type==="step-finish"&&(this.hasStepFinish=true,e.messageId&&(this.messageId=e.messageId));return}if(t.type==="session.status"){let e=t.properties.status?.type;(e==="idle"||e==="busy"||e==="retry")&&(this.sessionStatus=e);return}t.type==="session.error"&&(this.sessionStatus="error",t.properties.error?.data?.message&&(this.error=t.properties.error.data.message));}checkComplete(){return this.isComplete=!!this.error||this.hasTextEnd&&this.hasStepFinish,this.isComplete&&ht.debug("MessageEventCollector.checkComplete",{isComplete:this.isComplete,hasError:!!this.error,hasTextEnd:this.hasTextEnd,hasStepFinish:this.hasStepFinish}),this.isComplete}hasTextEndReady(){return this.hasTextEnd}isTextOnlyComplete(){return this.hasTextEnd&&!this.hasStepFinish&&!this.error}resetForNextMessage(){this.hasTextEnd=false,this.hasStepFinish=false,this.error="",this.isComplete=false,this.events=[];}getSessionStatus(){return this.sessionStatus}getCurrentMessageId(){return this.messageId}assembleMessage(){let t=this.events.filter(a=>a.type==="part.updated"&&a.properties.part?.type==="text"&&a.properties.part?.time?.end).map(a=>a.properties.part.text??"").join(""),e;if(this.filterConfig.includeThinking){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="reasoning"&&c.properties.part?.time?.end).map(c=>{let d=c.properties.part.text??"";return d=d.replace("[REDACTED]","").trim(),d}).filter(c=>c.length>0).join("");a&&(e=a);}let s;if(this.filterConfig.includeToolDetails){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="tool"&&(c.properties.part?.state?.status==="completed"||c.properties.part?.state?.status==="error"));a.length>0&&(s=a.map(c=>{let d=c.properties.part,g=d.state;return {name:d.tool,callId:d.callId,title:g.title,status:g.status,output:this.filterConfig.includeToolOutput?g.output:void 0,error:g.error,input:g.input}}));}let i=this.events.find(a=>a.type==="part.updated"&&a.properties.part?.type==="step-finish")?.properties.part?.tokens,r={role:"assistant",text:t,thinking:e,tools:s,metadata:{sessionId:this.sessionId,sessionStatus:this.sessionStatus,messageId:this.messageId,timestamp:Date.now(),tokens:i?{input:i.input,output:i.output,total:i.input+i.output+i.reasoning}:void 0,error:this.error||void 0}};return ht.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="",ht.debug("MessageEventCollector.reset",{hasTextEnd:false,hasStepFinish:false});}};var B=class extends Error{constructor(e,s,n){super(e,{cause:n});chunk6C5TBG7Z_cjs.a(this,"code",s);this.name="GatewayAgentError";}},Ie=class{constructor(t,e={}){chunk6C5TBG7Z_cjs.a(this,"sdk",t);chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:agent"}));chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"filterConfig");chunk6C5TBG7Z_cjs.a(this,"sessionId");chunk6C5TBG7Z_cjs.a(this,"eventBus");chunk6C5TBG7Z_cjs.a(this,"eventBridge");chunk6C5TBG7Z_cjs.a(this,"bridgeStarted",false);this.config=e,this.filterConfig={includeThinking:e.filterConfig?.includeThinking??false,includeToolDetails:e.filterConfig?.includeToolDetails??false,includeToolOutput:e.filterConfig?.includeToolOutput??true,includeSteps:e.filterConfig?.includeSteps??false},this.eventBus=new we,this.eventBridge=new ve(t,this.eventBus);}async getCommandPart(t){let e=t.parts?.find(n=>n.type==="command");if(!e)return;let s=false;try{s=(await this.sdk.command.get({name:e.command})).data?.commandType==="local";}catch(n){this.log.warn("Failed to get command",{command:e.command,error:String(n)});}return {...e,local:s}}async run(t,e){this.log.debug("GatewayAgent.run: starting",{source:t.source,agent:t.agent,partsCount:t.parts?.length??0});let s=await this.getCommandPart(t);return s?s.local?this.runLocalCommand(t,s):this.runPromptCommand(t,s,e):this.runPrompt(t,e)}async runLocalCommand(t,e){this.log.debug("GatewayAgent.runLocalCommand: starting",{command:e.command,arguments:e.arguments});try{let s=await this.ensureSession(t.source);if(!s)throw new B("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 B(s instanceof Error?s.message:String(s),"COMMAND_ERROR",s instanceof Error?s:void 0)}}async runPromptCommand(t,e,s){this.log.debug("GatewayAgent.runPromptCommand: starting",{command:e.command,arguments:e.arguments});try{let n=await this.ensureSession(t.source);if(!n)throw new B("Failed to create or get session","NO_SESSION");let i=new de(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=!0);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,b=null,S=()=>{b&&clearTimeout(b);},T=_=>{S();try{a();}catch{}g({messages:p,finishReason:_});};b=setTimeout(()=>{this.log.warn("runPromptCommand: event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),T("timeout");},12e4),a=this.eventBus.subscribeAll(_=>{if(_.type==="sdk.session_update"){let U=_.properties;if(U.sessionId!==n)return;if(i.addEvent(U.sessionEvent),i.checkComplete()){let E=i.assembleMessage();if(p.push(E),i.resetForNextMessage(),!E.text||E.text.trim().length===0){this.log.debug("runPromptCommand: skipping onMessage for empty-text message",{messageId:E.metadata.messageId,hasThinking:!!E.thinking,hasTools:(E.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(E)).catch(ee=>{this.log.error("runPromptCommand: onMessage callback error",{error:ee instanceof Error?ee.message:String(ee)});});}}let M=i.getSessionStatus();if(h==="busy"&&M==="idle"&&p.length>0){this.log.debug("runPromptCommand: turn complete (busy -> idle)",{messageCount:p.length}),T("idle");return}(M==="idle"||M==="busy"||M==="retry")&&(h=M);});});await this.sdk.session.command({sessionId:n,command:e.command,arguments:e.arguments??"",agent:t.agent,model:t.model?`${t.model.providerId}/${t.model.modelId}`:void 0});let d=await c;try{a();}catch{}return this.log.debug("GatewayAgent.runPromptCommand: completed",{sessionId:n,command:e.command,messageCount:d.messages.length,finishReason:d.finishReason}),this.assembleResult(d.messages,n,t,d.finishReason)}catch(n){throw this.log.error("GatewayAgent.runPromptCommand: failed",{error:n instanceof Error?n.message:String(n)}),new B(n instanceof Error?n.message:String(n),"COMMAND_ERROR",n instanceof Error?n:void 0)}}async runPrompt(t,e){this.log.debug("GatewayAgent.runPrompt: starting",{source:t.source,agent:t.agent});try{let s=await this.ensureSession(t.source);if(!s)throw new B("Failed to create or get session","NO_SESSION");let n=await this.sendAndCollect(s,t,e);return this.log.debug("GatewayAgent.runPrompt: completed",{sessionId:s,outputLength:n.output.length,messageCount:Array.isArray(n.metadata.messages)?n.metadata.messages.length:void 0}),n}catch(s){throw this.log.error("GatewayAgent.runPrompt: failed",{error:s instanceof Error?s.message:String(s)}),s instanceof B?s:new B(s instanceof Error?s.message:String(s),"EXECUTION_ERROR",s instanceof Error?s:void 0)}}async ensureSession(t){if(t)try{if((await this.sdk.session.get({sessionId:t})).data)return this.sessionId=t,this.log.debug("Using existing session",{sessionId:t}),t}catch{this.log.debug("Session not found, will create new",{sessionId:t});}let e=await this.sdk.session.create({title:"Gateway Session"});if(!e.data?.id)throw new B("Failed to create session","CREATE_SESSION_FAILED");return this.sessionId=e.data.id,this.log.debug("Created new session",{sessionId:this.sessionId}),this.sessionId}async sendAndCollect(t,e,s){let n=[];for(let g of e.parts??[])if(g.type==="text")n.push({type:"text",text:g.text??""});else if(g.type==="image"){let p="";typeof g.image=="string"?p=g.image:g.image instanceof URL?p=g.image.toString():g.image instanceof Uint8Array&&(p=`data:${g.mime??"image/png"};base64,${Buffer.from(g.image).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"image/png"});}else if(g.type==="file"){let p="";typeof g.data=="string"?p=g.data:g.data instanceof URL?p=g.data.toString():g.data instanceof Uint8Array&&(p=`data:${g.mime??"application/octet-stream"};base64,${Buffer.from(g.data).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"application/octet-stream"});}n.length===0&&n.push({type:"text",text:""});let i=new de(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=true);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,b=null,S=()=>{b&&clearTimeout(b);},T=_=>{S();try{a();}catch{}g({messages:p,finishReason:_});};b=setTimeout(()=>{this.log.warn("Event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),T("timeout");},12e4),a=this.eventBus.subscribeAll(_=>{if(_.type==="sdk.session_update"){let U=_.properties;if(U.sessionId!==t)return;if(i.addEvent(U.sessionEvent),i.checkComplete()){let E=i.assembleMessage();if(p.push(E),i.resetForNextMessage(),this.log.debug("sendAndCollect: message complete",{messageId:E.metadata.messageId,messageCount:p.length,textLength:E.text?.length??0}),!E.text||E.text.trim().length===0){this.log.debug("sendAndCollect: skipping onMessage for empty-text message",{messageId:E.metadata.messageId,hasThinking:!!E.thinking,hasTools:(E.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(E)).catch(ee=>{this.log.error("sendAndCollect: onMessage callback error",{error:ee instanceof Error?ee.message:String(ee)});});}}let M=i.getSessionStatus();if(h==="busy"&&M==="idle"&&p.length>0){this.log.debug("sendAndCollect: turn complete (busy -> idle)",{messageCount:p.length}),T("idle");return}(M==="idle"||M==="busy"||M==="retry")&&(h=M);});});await this.sdk.session.prompt({sessionId:t,parts:n,system:e.system,agent:e.agent,model:e.model?{providerId:e.model.providerId,modelId:e.model.modelId}:void 0});let d=await c;try{a();}catch{}return this.assembleResult(d.messages,t,e,d.finishReason)}assembleResult(t,e,s,n="idle"){let i=t.map(c=>this.formatOutput(c)).filter(c=>c.length>0).join(`
|
|
1
|
+
'use strict';var chunk6C5TBG7Z_cjs=require('./chunk-6C5TBG7Z.cjs'),utils=require('@easbot/utils'),u=require('zod'),ue=require('path'),te=require('fs'),$=require('fs/promises'),ws=require('ws'),$i=require('https'),Wi=require('http'),Hi=require('crypto'),url=require('url'),os$1=require('os'),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 u__default=/*#__PURE__*/_interopDefault(u);var ue__namespace=/*#__PURE__*/_interopNamespace(ue);var te__namespace=/*#__PURE__*/_interopNamespace(te);var $__namespace=/*#__PURE__*/_interopNamespace($);var $i__default=/*#__PURE__*/_interopDefault($i);var Wi__default=/*#__PURE__*/_interopDefault(Wi);var Hi__default=/*#__PURE__*/_interopDefault(Hi);function I(o,t,e,s){return {id:utils.Identifier.ascending("message"),sessionId:o,type:t,content:e,metadata:{channel:{platform:s?.channel?.platform??"api",channelId:s?.channel?.channelId??"default",userId:s?.channel?.userId,chatId:s?.channel?.chatId,...Object.fromEntries(Object.entries(s?.channel??{}).filter(([n])=>!["platform","channelId","userId","chatId"].includes(n)))},context:s?.context,agent:s?.agent},timestamp:Date.now()}}function Cn(o,t,e,s){return I(o,t,[{type:"text",text:e}],s)}function Ke(o){let t={platform:o.channel?.platform??"api",channelId:o.channel?.channelId??"unknown",chatId:o.channel?.chatId,userId:o.channel?.userId,chatType:o.channel?.chatType,chatTitle:o.channel?.chatTitle};return {id:o.id,sessionId:o.sessionId,type:o.type,content:Array.isArray(o.content)?o.content:[{type:"text",text:String(o.content??"")}],metadata:{channel:t,replyToMessageId:o.replyToMessageId,processorId:o.processorId,agent:o.agent,proactive:o.proactive??!o.replyToMessageId},timestamp:o.timestamp??Date.now()}}function Ve(o){if(!o.platform)throw new Error("Invalid session: platform is required");if(!o.channelId)throw new Error("Invalid session: channelId is required");let t=o.chatId??"",e=o.userId??t;if(!t&&!o.userId)throw new Error(`Invalid session: chatId and userId cannot both be empty. platform=${o.platform}, channelId=${o.channelId}`);return [o.platform,o.channelId,t,e].join("_")}function Je(){return {status:"active",messageCount:0,lastMessageAt:null}}function Qe(o,t){if(!o||!t)throw new Error("platform and stableId are required");return `${o}:${t}`}function Xe(o){if(!o||typeof o!="string")return null;let t=o.indexOf(":");if(t<=0||t>=o.length-1)return null;let e=o.slice(0,t),s=o.slice(t+1);return !e||!s?null:{platform:e,stableId:s}}function _t(o){let{platform:t,stableId:e,profile:s={},aliases:n={},metadata:i}=o;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:Qe(t,e),platform:t,stableId:e,aliases:{...n},profile:{...s},createdAt:r,lastSeenAt:r,metadata:i}}function Et(o,t){return `sub_${o}_${t}`}var vn=utils.Log.create({service:"gateway:config"});u__default.default.enum(["telegram","slack","feishu","wechat","weixin","webchat","signal","nostr","dingtalk"]);u__default.default.enum(["low","medium","high","critical"]);var Ze=u__default.default.object({enabled:u__default.default.boolean().default(true),botToken:u__default.default.string().describe("Telegram Bot Token"),webhookUrl:u__default.default.string().optional().describe("Webhook URL for receiving updates"),polling:u__default.default.object({enabled:u__default.default.boolean().default(true),interval:u__default.default.number().int().positive().optional().describe("Polling interval in ms"),timeout:u__default.default.number().int().positive().optional().default(30).describe("Long polling timeout in seconds")}).refine(o=>o===void 0||o.enabled,{message:"polling.enabled must be true when polling is configured"}).optional(),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),et=u__default.default.object({enabled:u__default.default.boolean().default(true),botToken:u__default.default.string().describe("Slack Bot Token (xoxb-*)"),appToken:u__default.default.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:u__default.default.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),tt=u__default.default.object({enabled:u__default.default.boolean().default(true),appId:u__default.default.string().describe("Feishu App ID"),appSecret:u__default.default.string().describe("Feishu App Secret"),encryptKey:u__default.default.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:u__default.default.string().optional().describe("Feishu Verification Token"),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),st=u__default.default.object({enabled:u__default.default.boolean().default(true),mode:u__default.default.enum(["official","wecom"]).default("official"),appId:u__default.default.string().describe("WeChat App ID"),appSecret:u__default.default.string().describe("WeChat App Secret"),token:u__default.default.string().optional().describe("WeChat Token for message verification"),encodingAESKey:u__default.default.string().optional().describe("WeChat Encoding AES Key"),agentId:u__default.default.string().optional().describe("WeCom Agent ID"),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),In=u__default.default.object({enabled:u__default.default.boolean().default(true),stateDir:u__default.default.string().optional().describe("Override the default account persistence directory (default: ~/.easbot/channels/weixin)"),baseUrl:u__default.default.string().optional().describe("Override the iLink API baseUrl (default: https://ilinkai.weixin.qq.com)"),cdnBaseUrl:u__default.default.string().optional().describe("Override the CDN baseUrl (default: https://novac2c.cdn.weixin.qq.com/c2c)"),maxMessageLength:u__default.default.number().int().positive().optional().default(4e3),timeout:u__default.default.number().int().positive().optional().default(3e4)}),nt=u__default.default.object({enabled:u__default.default.boolean().default(true),path:u__default.default.string().optional().default("/"),heartbeatInterval:u__default.default.number().int().positive().optional().default(3e4),connectionTimeout:u__default.default.number().int().positive().optional().default(36e5),maxConnections:u__default.default.number().int().positive().optional().default(1e3),cors:u__default.default.boolean().optional().default(true)}),it=u__default.default.object({enabled:u__default.default.boolean().default(true),serviceUrl:u__default.default.string().optional().default("https://chat.signal.org"),phoneNumber:u__default.default.string().describe("Signal phone number"),password:u__default.default.string().optional().describe("Signal account password"),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),rt=u__default.default.object({enabled:u__default.default.boolean().default(true),relays:u__default.default.array(u__default.default.string()).min(1).describe("Nostr relay URLs"),privateKey:u__default.default.string().optional().describe("Nostr private key (hex)"),publicKey:u__default.default.string().optional().describe("Nostr public key (hex)"),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),An=u__default.default.object({enabled:u__default.default.boolean().default(true),appKey:u__default.default.string().describe("DingTalk AppKey"),appSecret:u__default.default.string().describe("DingTalk AppSecret"),token:u__default.default.string().optional().describe("DingTalk token for signature verification"),encryptKey:u__default.default.string().optional().describe("DingTalk encrypt key for message encryption"),webhook:u__default.default.object({enabled:u__default.default.boolean().default(true),path:u__default.default.string().optional().default("/dingtalk/webhook"),port:u__default.default.number().int().positive().optional().describe("Webhook server port")}).optional(),maxConnections:u__default.default.number().int().positive().optional().default(100),timeout:u__default.default.number().int().positive().optional().default(3e4)}),ns=u__default.default.object({telegram:Ze.optional(),slack:et.optional(),feishu:tt.optional(),wechat:st.optional(),weixin:In.optional(),webchat:nt.optional(),signal:it.optional(),nostr:rt.optional(),dingtalk:An.optional()}),is=u__default.default.object({enabled:u__default.default.boolean().default(false),cert:u__default.default.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:u__default.default.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:u__default.default.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:u__default.default.string().optional().describe("Path to SSL key file (alias of key)"),ca:u__default.default.string().optional().describe("Path to CA certificate file"),forceRedirect:u__default.default.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:u__default.default.number().int().positive().optional().default(80).describe("HTTP redirect port")}),Pn=u__default.default.object({name:u__default.default.string().describe("Token name/description"),value:u__default.default.string().describe("Token value"),permissions:u__default.default.array(u__default.default.string()).default(["*"]).describe("Associated permissions"),expiresAt:u__default.default.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:u__default.default.string().optional().describe("Token description")}),xn=u__default.default.object({enabled:u__default.default.boolean().default(true),tokens:u__default.default.array(Pn).default([]).describe("List of valid tokens"),onInvalid:u__default.default.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:u__default.default.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:u__default.default.array(u__default.default.string()).default([]).describe("Default permissions for anonymous users")}),Mn=u__default.default.object({enabled:u__default.default.boolean().default(false),authorizationServer:u__default.default.string().describe("OAuth2 authorization server URL"),clientId:u__default.default.string().describe("OAuth2 client ID"),clientSecret:u__default.default.string().describe("OAuth2 client secret"),tokenValidationEndpoint:u__default.default.string().describe("OAuth2 token validation endpoint"),scope:u__default.default.array(u__default.default.string()).default([]).describe("OAuth2 scopes")}),rs=u__default.default.object({type:u__default.default.enum(["token","oauth2"]).default("token"),token:xn.optional(),oauth2:Mn.optional()}),as=u__default.default.object({mode:u__default.default.enum(["pull","push","both"]).default("both"),interval:u__default.default.number().int().positive().default(3e4),pushEvents:u__default.default.array(u__default.default.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:u__default.default.enum(["latest","local","remote"]).default("latest")}),kn=u__default.default.object({id:u__default.default.string().describe("Gateway node ID"),address:u__default.default.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:u__default.default.boolean().default(true),metadata:u__default.default.record(u__default.default.string(),u__default.default.any()).optional()}),os=u__default.default.object({nodeId:u__default.default.string().describe("Current gateway node ID"),nodes:u__default.default.array(kn).default([]).describe("Other gateway nodes in the cluster"),sync:as.optional()}),at=u__default.default.object({maxConnectionsPerChannel:u__default.default.number().int().positive().default(100),idleTimeout:u__default.default.number().int().positive().default(3e5),reuseStrategy:u__default.default.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:u__default.default.number().int().positive().default(6e4),acquireTimeout:u__default.default.number().int().positive().default(5e3),warmupCount:u__default.default.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),ot=u__default.default.object({maxLength:u__default.default.number().int().positive().default(1e4),concurrency:u__default.default.number().int().positive().default(100),batchSize:u__default.default.number().int().positive().default(10),batchTimeout:u__default.default.number().int().positive().default(100),priorityLevels:u__default.default.number().int().positive().default(4)}),ct=u__default.default.object({failureThreshold:u__default.default.number().int().positive().default(5),successThreshold:u__default.default.number().int().positive().default(3),timeout:u__default.default.number().int().positive().default(3e4),halfOpenDuration:u__default.default.number().int().positive().default(15e3)}),lt=u__default.default.object({heartbeatInterval:u__default.default.number().int().positive().default(6e4),heartbeatTimeout:u__default.default.number().int().positive().default(3e5),heartbeatCheckInterval:u__default.default.number().int().positive().default(3e5),autoDeregisterTimeout:u__default.default.number().int().positive().default(6e5),maxAgents:u__default.default.number().int().positive().default(100),persistenceFile:u__default.default.string().optional().describe("Path to persist agent registrations"),maxRegistrations:u__default.default.number().int().positive().default(1e3)}),dt=u__default.default.object({sessionTimeout:u__default.default.number().int().positive().default(18e5),resumeGracePeriod:u__default.default.number().int().positive().default(3e5),maxSessions:u__default.default.number().int().positive().default(1e4),persistenceFile:u__default.default.string().optional().describe("Path to persist sessions")}),gt=u__default.default.object({enabled:u__default.default.boolean().default(true),port:u__default.default.number().int().positive().default(8080),hostname:u__default.default.string().default("localhost"),path:u__default.default.string().optional().default("/"),maxConnections:u__default.default.number().int().positive().optional().default(1e3),connectionTimeout:u__default.default.number().int().positive().optional().default(36e5),heartbeatInterval:u__default.default.number().int().positive().optional().default(3e4),sessionExpireMs:u__default.default.number().int().positive().optional().default(36e5),https:is.optional(),auth:rs.optional(),cors:u__default.default.boolean().default(true),corsOrigins:u__default.default.array(u__default.default.string()).optional(),mdns:u__default.default.boolean().default(false),mdnsDomain:u__default.default.string().optional().default("gateway.easbot.local")}),Tn=u__default.default.object({channel:u__default.default.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:u__default.default.array(u__default.default.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),_n=u__default.default.enum(["localAgent","subAgent","both"]),En=u__default.default.object({mode:_n.default("localAgent").describe("Agent processing mode: localAgent, subAgent, or both"),localAgentPriority:u__default.default.number().int().min(1).max(10).default(1).describe("Priority for localAgent (lower = higher priority)"),subAgentPriority:u__default.default.number().int().min(1).max(10).default(2).describe("Priority for subAgent (lower = higher priority)"),timeout:u__default.default.number().int().positive().optional().default(3e5).describe("Timeout for agent execution in milliseconds"),retryOnFailure:u__default.default.boolean().default(true).describe("Retry with subAgent when localAgent fails")}),ut=u__default.default.object({autoRegister:u__default.default.boolean().default(true).describe("Whether to auto-register agent on startup"),heartbeatInterval:u__default.default.number().int().positive().default(3e4).describe("Heartbeat interval in milliseconds"),maxReconnectAttempts:u__default.default.number().int().min(0).default(5).describe("Maximum reconnect attempts"),reconnectDelay:u__default.default.number().int().positive().default(3e3).describe("Reconnect delay in milliseconds"),heartbeatTimeout:u__default.default.number().int().positive().default(9e4).describe("Heartbeat timeout in milliseconds")}),Ye=u__default.default.object({server:gt.optional(),channels:ns.optional(),cluster:os.optional(),connectionPool:at.optional(),messageQueue:ot.optional(),circuitBreaker:ct.optional(),agentRegistry:lt.optional(),session:dt.optional(),defaults:Tn.optional(),agentProcessing:En.optional(),client:ut.optional().describe("Gateway client config for agent registration"),defaultAgent:u__default.default.string().optional().describe("Default agent ID for routing"),logLevel:u__default.default.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(u__default.default.unknown());function Rt(o){let t=Ye.safeParse(o);return t.success||vn.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:Ye.parse({})}function Rn(o){return Ye.parse(o)}var D=utils.Log.create({service:"sdk-event-bus"}),pt=(i=>(i.SDK_SESSION_STATUS="agent.status",i.SDK_ERROR="sdk.error",i.SDK_SESSION_UPDATE="sdk.session_update",i.SDK_PERMISSION_REQUEST="sdk.permission_request",i.SDK_SESSION_DELETED="sdk.session_deleted",i))(pt||{});u.z.object({sessionId:u.z.string(),status:u.z.enum(["idle","busy","retry"]),timestamp:u.z.number()});u.z.object({error:u.z.string(),context:u.z.record(u.z.string(),u.z.any()).optional(),timestamp:u.z.number()});u.z.object({sessionId:u.z.string(),sessionEvent:u.z.unknown(),timestamp:u.z.number()});u.z.object({requestId:u.z.string(),sessionId:u.z.string(),permission:u.z.string(),tool:u.z.object({callId:u.z.string().optional()}).optional(),metadata:u.z.record(u.z.string(),u.z.any()).optional(),timestamp:u.z.number()});u.z.object({sessionId:u.z.string(),timestamp:u.z.number()});var we=class{constructor(){chunk6C5TBG7Z_cjs.a(this,"subscriptions",new Map);chunk6C5TBG7Z_cjs.a(this,"wildcardSubscriptions",new Set);chunk6C5TBG7Z_cjs.a(this,"destroyed",false);}subscribe(t,e){if(this.destroyed)return D.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{};let s=this.subscriptions.get(t)??new Set;return s.add(e),this.subscriptions.set(t,s),D.debug("Subscribed to event",{eventType:t}),()=>{s.delete(e),s.size===0&&this.subscriptions.delete(t),D.debug("Unsubscribed from event",{eventType:t});}}subscribeAll(t){return this.destroyed?(D.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{}):(this.wildcardSubscriptions.add(t),D.debug("Subscribed to all events"),()=>{this.wildcardSubscriptions.delete(t),D.debug("Unsubscribed from all events");})}async publish(t){if(this.destroyed){D.warn("Cannot publish to destroyed SdkEventBus",{type:t.type});return}D.debug("Publishing event",{type:t.type});let e=this.collectCallbacks(t);if(e.length===0){D.debug("No subscribers for event",{type:t.type});return}let s=await Promise.allSettled(e.map(async r=>{try{await r(t);}catch(a){throw D.error("Event callback error",{type:t.type,error:a instanceof Error?a.message:String(a)}),a}})),n=s.filter(r=>r.status==="fulfilled").length,i=s.filter(r=>r.status==="rejected").length;i>0?D.warn("Event callbacks completed with errors",{type:t.type,fulfilled:n,rejected:i}):D.debug("Event callbacks completed",{type:t.type,count:n});}publishSync(t){if(this.destroyed)return;let e=this.collectCallbacks(t);for(let s of e)Promise.resolve().then(()=>s(t)).catch(n=>{D.error("Event callback error (sync)",{type:t.type,error:n instanceof Error?n.message:String(n)});});}collectCallbacks(t){let e=[],s=this.subscriptions.get(t.type);return s&&e.push(...s),e.push(...this.wildcardSubscriptions),e}subscriberCount(t){return t?this.subscriptions.get(t)?.size??0:this.totalSubscribers()}totalSubscribers(){let t=this.wildcardSubscriptions.size;for(let e of this.subscriptions.values())t+=e.size;return t}hasSubscribers(t){return t?(this.subscriptions.get(t)?.size??0)>0||this.wildcardSubscriptions.size>0:this.totalSubscribers()>0}clear(){this.subscriptions.clear(),this.wildcardSubscriptions.clear(),D.debug("All subscriptions cleared");}destroy(){this.clear(),this.destroyed=true,D.info("SdkEventBus destroyed");}isDestroyed(){return this.destroyed}};var P=utils.Log.create({service:"sdk-event-bridge"}),ve=class{constructor(t,e,s){chunk6C5TBG7Z_cjs.a(this,"sdk");chunk6C5TBG7Z_cjs.a(this,"sdkEventBus");chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"started",false);chunk6C5TBG7Z_cjs.a(this,"sessionFilter");chunk6C5TBG7Z_cjs.a(this,"_cachedPrimaryAgents",null);chunk6C5TBG7Z_cjs.a(this,"_messageMetaCache",new Map);this.sdk=t,this.sdkEventBus=e,this.sessionFilter=s;}async getMessageMeta(t,e){let s=`${t}:${e}`,n=this._messageMetaCache.get(s);if(n)return n;let i=await this.sdk.session.message({sessionId:t,messageId:e},{throwOnError:true}).then(a=>a.data).catch(a=>{P.error("unexpected error when fetching message",{error:a,sessionId:t,messageId:e});});if(!i)return;let r={role:i.info.role,agent:i.info.agent};return this._messageMetaCache.set(s,r),r}clearMessageMetaCache(t){let e=`${t}:`;for(let s of this._messageMetaCache.keys())s.startsWith(e)&&this._messageMetaCache.delete(s);}async pushSessionEvent(t){let e=t.properties.sessionId??"";if(!e){P.debug("Dropping session event without sessionId",{type:t.type});return}await this.sdkEventBus?.publish({type:"sdk.session_update",properties:{sessionId:e,sessionEvent:t,timestamp:Date.now()}});}async start(){if(this.started){P.warn("SdkEventBridge already started");return}this.started=true,this.abortController=new AbortController,P.info("Starting SDK event bridge"),this.runEventLoop().catch(t=>{if(this.abortController?.signal.aborted){P.debug("Event loop stopped due to abort");return}P.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&&(P.info("Stopping SDK event bridge"),this.started=false,this.abortController?.abort(),this.abortController=null,this._messageMetaCache.clear(),this._cachedPrimaryAgents=null,P.info("SDK event bridge stopped"));}isStarted(){return this.started}async runEventLoop(){for(;;){if(this.abortController?.signal.aborted){P.debug("Event loop aborted");return}try{let t=this.abortController?.signal;if(!t)return;if(t.aborted){P.debug("Event loop aborted before event call");return}let e=await this.sdk.global.event({signal:t});for await(let s of e.stream){if(this.abortController?.signal.aborted){P.debug("Event loop aborted during iteration");return}let n=s?.payload;n&&await this.handleEvent(n).catch(i=>{P.error("Failed to handle event",{error:i instanceof Error?i.message:String(i),type:n.type});});}}catch(t){if(this.abortController?.signal.aborted){P.debug("Event loop aborted, not reconnecting");return}P.error("Event stream error, reconnecting...",{error:t instanceof Error?t.message:String(t)}),await new Promise(e=>setTimeout(e,1e3));}}}async handleEvent(t){switch(P.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:P.debug("Unknown event type, ignoring",{type:t.type});}}async handleSessionDeleted(t){let{sessionId:e}=t;this.sessionFilter&&!this.sessionFilter(e)||(this.clearMessageMetaCache(e),P.debug("Publishing session deleted event to SdkEventBus",{sessionId:e}),await this.sdkEventBus?.publish({type:"sdk.session_deleted",properties:{sessionId:e,timestamp:Date.now()}}));}async handlePermissionAsked(t){let{id:e,sessionId:s,permission:n,tool:i,metadata:r}=t;this.sessionFilter&&!this.sessionFilter(s)||(P.debug("Publishing permission request to SdkEventBus",{id:e,sessionId:s,permission:n}),await this.sdkEventBus?.publish({type:"sdk.permission_request",properties:{requestId:e,sessionId:s,permission:n,tool:i,metadata:r,timestamp:Date.now()}}));}async handleMessagePartUpdated(t){let{part:e,delta:s}=t;if(this.sessionFilter&&!this.sessionFilter(e.sessionId))return;P.debug("Handling message part update",{type:e.type,sessionId:e.sessionId,messageId:e.messageId});let n=await this.getMessageMeta(e.sessionId,e.messageId);n?.role==="assistant"&&(n.agent&&await this.shouldFilterAgent(n.agent)||(e.type==="tool"?await this.handleToolPart(e):e.type==="text"?await this.handleTextPart(e,s):e.type==="reasoning"?await this.handleReasoningPart(e,s):e.type==="step-start"?await this.handleStepStartPart(e):e.type==="step-finish"&&await this.handleStepFinishPart(e)));}async handleToolPart(t){let{sessionId:e,callId:s,tool:n,state:i}=t,r;switch(i.status){case "pending":r={status:"pending"};break;case "running":r={status:"running",input:i.input};break;case "completed":r={status:"completed",input:i.input,output:i.output,title:i.title,metadata:i.metadata};break;case "error":r={status:"error",input:i.input,error:i.error};break;default:P.warn("Unknown tool state, falling back to pending",{tool:n,callId:s,status:i.status}),r={status:"pending"};break}await this.pushSessionEvent({type:"part.updated",properties:{sessionId:e,part:{type:"tool",tool:n,callId:s,state:r}}});}async handleTextPart(t,e){if(t.ignored===true||!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"text",text:n,messageId:t.messageId,time:t.time}}});}async handleStepStartPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-start",messageId:t.messageId}}});}async handleStepFinishPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-finish",messageId:t.messageId,tokens:t.tokens}}});}async handleReasoningPart(t,e){if(!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"reasoning",text:n,messageId:t.messageId,time:t.time}}});}async handleSessionStatus(t){let{sessionId:e,status:s}=t;await this.pushSessionEvent({type:"session.status",properties:{sessionId:e,status:s}}),s.type==="idle"&&this.clearMessageMetaCache(e),P.debug("Session status update sent",{sessionId:e,status:s.type});}async shouldFilterAgent(t){if(!this._cachedPrimaryAgents)try{let s=(await this.sdk.app.agents({})).data||[];this._cachedPrimaryAgents=new Set(s.filter(n=>n.mode==="primary"&&n.hidden!==!0).map(n=>n.name));}catch{this._cachedPrimaryAgents=new Set;}return !this._cachedPrimaryAgents.has(t)}};var ht=utils.Log.create({service:"sdk-message-collector"}),cs={includeThinking:false,includeToolDetails:false,includeToolOutput:false,includeSteps:false},Gn={includeThinking:true,includeToolDetails:true,includeToolOutput:true,includeSteps:true},de=class{constructor(t=cs){chunk6C5TBG7Z_cjs.a(this,"filterConfig",t);chunk6C5TBG7Z_cjs.a(this,"events",[]);chunk6C5TBG7Z_cjs.a(this,"isComplete",false);chunk6C5TBG7Z_cjs.a(this,"hasTextEnd",false);chunk6C5TBG7Z_cjs.a(this,"hasStepFinish",false);chunk6C5TBG7Z_cjs.a(this,"error","");chunk6C5TBG7Z_cjs.a(this,"sessionStatus","idle");chunk6C5TBG7Z_cjs.a(this,"sessionId","");chunk6C5TBG7Z_cjs.a(this,"messageId","");ht.debug("MessageEventCollector created",{filterConfig:t});}addEvent(t){if(!this.shouldIncludeEvent(t)){this.checkCompletion(t);return}this.events.push(t),this.checkCompletion(t);}shouldIncludeEvent(t){if(t.type!=="part.updated")return true;let e=t.properties.part;return e?!(e.type==="reasoning"&&!this.filterConfig.includeThinking||e.type==="tool"&&e.state?.status==="running"&&!this.filterConfig.includeToolDetails||(e.type==="step-start"||e.type==="step-finish")&&!this.filterConfig.includeSteps):true}checkCompletion(t){if(t.properties.sessionId&&(this.sessionId=t.properties.sessionId),t.properties.info?.id&&(this.sessionId=t.properties.info.id),t.type==="part.updated"){let e=t.properties.part;if(!e)return;e.type==="text"&&e.time?.end?(this.hasTextEnd=true,e.messageId&&(this.messageId=e.messageId)):e.type==="step-finish"&&(this.hasStepFinish=true,e.messageId&&(this.messageId=e.messageId));return}if(t.type==="session.status"){let e=t.properties.status?.type;(e==="idle"||e==="busy"||e==="retry")&&(this.sessionStatus=e);return}t.type==="session.error"&&(this.sessionStatus="error",t.properties.error?.data?.message&&(this.error=t.properties.error.data.message));}checkComplete(){return this.isComplete=!!this.error||this.hasTextEnd&&this.hasStepFinish,this.isComplete&&ht.debug("MessageEventCollector.checkComplete",{isComplete:this.isComplete,hasError:!!this.error,hasTextEnd:this.hasTextEnd,hasStepFinish:this.hasStepFinish}),this.isComplete}hasTextEndReady(){return this.hasTextEnd}isTextOnlyComplete(){return this.hasTextEnd&&!this.hasStepFinish&&!this.error}resetForNextMessage(){this.hasTextEnd=false,this.hasStepFinish=false,this.error="",this.isComplete=false,this.events=[];}getSessionStatus(){return this.sessionStatus}getCurrentMessageId(){return this.messageId}assembleMessage(){let t=this.events.filter(a=>a.type==="part.updated"&&a.properties.part?.type==="text"&&a.properties.part?.time?.end).map(a=>a.properties.part.text??"").join(""),e;if(this.filterConfig.includeThinking){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="reasoning"&&c.properties.part?.time?.end).map(c=>{let d=c.properties.part.text??"";return d=d.replace("[REDACTED]","").trim(),d}).filter(c=>c.length>0).join("");a&&(e=a);}let s;if(this.filterConfig.includeToolDetails){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="tool"&&(c.properties.part?.state?.status==="completed"||c.properties.part?.state?.status==="error"));a.length>0&&(s=a.map(c=>{let d=c.properties.part,g=d.state;return {name:d.tool,callId:d.callId,title:g.title,status:g.status,output:this.filterConfig.includeToolOutput?g.output:void 0,error:g.error,input:g.input}}));}let i=this.events.find(a=>a.type==="part.updated"&&a.properties.part?.type==="step-finish")?.properties.part?.tokens,r={role:"assistant",text:t,thinking:e,tools:s,metadata:{sessionId:this.sessionId,sessionStatus:this.sessionStatus,messageId:this.messageId,timestamp:Date.now(),tokens:i?{input:i.input,output:i.output,total:i.input+i.output+i.reasoning}:void 0,error:this.error||void 0}};return ht.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="",ht.debug("MessageEventCollector.reset",{hasTextEnd:false,hasStepFinish:false});}};var B=class extends Error{constructor(e,s,n){super(e,{cause:n});chunk6C5TBG7Z_cjs.a(this,"code",s);this.name="GatewayAgentError";}},Ie=class{constructor(t,e={}){chunk6C5TBG7Z_cjs.a(this,"sdk",t);chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:agent"}));chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"filterConfig");chunk6C5TBG7Z_cjs.a(this,"sessionId");chunk6C5TBG7Z_cjs.a(this,"eventBus");chunk6C5TBG7Z_cjs.a(this,"eventBridge");chunk6C5TBG7Z_cjs.a(this,"bridgeStarted",false);this.config=e,this.filterConfig={includeThinking:e.filterConfig?.includeThinking??false,includeToolDetails:e.filterConfig?.includeToolDetails??false,includeToolOutput:e.filterConfig?.includeToolOutput??true,includeSteps:e.filterConfig?.includeSteps??false},this.eventBus=new we,this.eventBridge=new ve(t,this.eventBus);}async getCommandPart(t){let e=t.parts?.find(n=>n.type==="command");if(!e)return;let s=false;try{s=(await this.sdk.command.get({name:e.command})).data?.commandType==="local";}catch(n){this.log.warn("Failed to get command",{command:e.command,error:String(n)});}return {...e,local:s}}async run(t,e){this.log.debug("GatewayAgent.run: starting",{source:t.source,agent:t.agent,partsCount:t.parts?.length??0});let s=await this.getCommandPart(t);return s?s.local?this.runLocalCommand(t,s):this.runPromptCommand(t,s,e):this.runPrompt(t,e)}async runLocalCommand(t,e){this.log.debug("GatewayAgent.runLocalCommand: starting",{command:e.command,arguments:e.arguments});try{let s=await this.ensureSession(t.source);if(!s)throw new B("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 B(s instanceof Error?s.message:String(s),"COMMAND_ERROR",s instanceof Error?s:void 0)}}async runPromptCommand(t,e,s){this.log.debug("GatewayAgent.runPromptCommand: starting",{command:e.command,arguments:e.arguments});try{let n=await this.ensureSession(t.source);if(!n)throw new B("Failed to create or get session","NO_SESSION");let i=new de(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=!0);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,b=null,S=()=>{b&&clearTimeout(b);},T=_=>{S();try{a();}catch{}g({messages:p,finishReason:_});};b=setTimeout(()=>{this.log.warn("runPromptCommand: event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),T("timeout");},12e4),a=this.eventBus.subscribeAll(_=>{if(_.type==="sdk.session_update"){let U=_.properties;if(U.sessionId!==n)return;if(i.addEvent(U.sessionEvent),i.checkComplete()){let E=i.assembleMessage();if(p.push(E),i.resetForNextMessage(),!E.text||E.text.trim().length===0){this.log.debug("runPromptCommand: skipping onMessage for empty-text message",{messageId:E.metadata.messageId,hasThinking:!!E.thinking,hasTools:(E.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(E)).catch(ee=>{this.log.error("runPromptCommand: onMessage callback error",{error:ee instanceof Error?ee.message:String(ee)});});}}let M=i.getSessionStatus();if(h==="busy"&&M==="idle"&&p.length>0){this.log.debug("runPromptCommand: turn complete (busy -> idle)",{messageCount:p.length}),T("idle");return}(M==="idle"||M==="busy"||M==="retry")&&(h=M);});});await this.sdk.session.command({sessionId:n,command:e.command,arguments:e.arguments??"",agent:t.agent,model:t.model?`${t.model.providerId}/${t.model.modelId}`:void 0});let d=await c;try{a();}catch{}return this.log.debug("GatewayAgent.runPromptCommand: completed",{sessionId:n,command:e.command,messageCount:d.messages.length,finishReason:d.finishReason}),this.assembleResult(d.messages,n,t,d.finishReason)}catch(n){throw this.log.error("GatewayAgent.runPromptCommand: failed",{error:n instanceof Error?n.message:String(n)}),new B(n instanceof Error?n.message:String(n),"COMMAND_ERROR",n instanceof Error?n:void 0)}}async runPrompt(t,e){this.log.debug("GatewayAgent.runPrompt: starting",{source:t.source,agent:t.agent});try{let s=await this.ensureSession(t.source);if(!s)throw new B("Failed to create or get session","NO_SESSION");let n=await this.sendAndCollect(s,t,e);return this.log.debug("GatewayAgent.runPrompt: completed",{sessionId:s,outputLength:n.output.length,messageCount:Array.isArray(n.metadata.messages)?n.metadata.messages.length:void 0}),n}catch(s){throw this.log.error("GatewayAgent.runPrompt: failed",{error:s instanceof Error?s.message:String(s)}),s instanceof B?s:new B(s instanceof Error?s.message:String(s),"EXECUTION_ERROR",s instanceof Error?s:void 0)}}async ensureSession(t){if(t)try{if((await this.sdk.session.get({sessionId:t})).data)return this.sessionId=t,this.log.debug("Using existing session",{sessionId:t}),t}catch{this.log.debug("Session not found, will create new",{sessionId:t});}let e=await this.sdk.session.create({title:"Gateway Session"});if(!e.data?.id)throw new B("Failed to create session","CREATE_SESSION_FAILED");return this.sessionId=e.data.id,this.log.debug("Created new session",{sessionId:this.sessionId}),this.sessionId}async sendAndCollect(t,e,s){let n=[];for(let g of e.parts??[])if(g.type==="text")n.push({type:"text",text:g.text??""});else if(g.type==="image"){let p="";typeof g.image=="string"?p=g.image:g.image instanceof URL?p=g.image.toString():g.image instanceof Uint8Array&&(p=`data:${g.mime??"image/png"};base64,${Buffer.from(g.image).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"image/png"});}else if(g.type==="file"){let p="";typeof g.data=="string"?p=g.data:g.data instanceof URL?p=g.data.toString():g.data instanceof Uint8Array&&(p=`data:${g.mime??"application/octet-stream"};base64,${Buffer.from(g.data).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"application/octet-stream"});}n.length===0&&n.push({type:"text",text:""});let i=new de(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=true);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,b=null,S=()=>{b&&clearTimeout(b);},T=_=>{S();try{a();}catch{}g({messages:p,finishReason:_});};b=setTimeout(()=>{this.log.warn("Event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),T("timeout");},12e4),a=this.eventBus.subscribeAll(_=>{if(_.type==="sdk.session_update"){let U=_.properties;if(U.sessionId!==t)return;if(i.addEvent(U.sessionEvent),i.checkComplete()){let E=i.assembleMessage();if(p.push(E),i.resetForNextMessage(),this.log.debug("sendAndCollect: message complete",{messageId:E.metadata.messageId,messageCount:p.length,textLength:E.text?.length??0}),!E.text||E.text.trim().length===0){this.log.debug("sendAndCollect: skipping onMessage for empty-text message",{messageId:E.metadata.messageId,hasThinking:!!E.thinking,hasTools:(E.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(E)).catch(ee=>{this.log.error("sendAndCollect: onMessage callback error",{error:ee instanceof Error?ee.message:String(ee)});});}}let M=i.getSessionStatus();if(h==="busy"&&M==="idle"&&p.length>0){this.log.debug("sendAndCollect: turn complete (busy -> idle)",{messageCount:p.length}),T("idle");return}(M==="idle"||M==="busy"||M==="retry")&&(h=M);});});await this.sdk.session.prompt({sessionId:t,parts:n,system:e.system,agent:e.agent,model:e.model?{providerId:e.model.providerId,modelId:e.model.modelId}:void 0});let d=await c;try{a();}catch{}return this.assembleResult(d.messages,t,e,d.finishReason)}assembleResult(t,e,s,n="idle"){let i=t.map(c=>this.formatOutput(c)).filter(c=>c.length>0).join(`
|
|
2
2
|
|
|
3
3
|
`),a=t[t.length-1]?.metadata.tokens;return {output:i,title:s.title??"Gateway Response",metadata:{sessionId:e,source:s.source,agent:s.agent,messageCount:t.length,finishReason:n,messages:t,...a?{tokens:a}:{}}}}formatOutput(t){let e=[];if(t.text&&e.push(t.text),t.tools&&this.filterConfig.includeToolOutput)for(let s of t.tools)s.output&&e.push(`
|
|
4
4
|
[Tool: ${s.name}]
|
|
@@ -7,8 +7,8 @@ ${String(s.output)}
|
|
|
7
7
|
[Tool Error: ${s.name}]
|
|
8
8
|
${s.error}
|
|
9
9
|
`);return e.join(`
|
|
10
|
-
`).trim()}getSessionId(){return this.sessionId}resetSession(){this.sessionId=void 0;}async stop(){this.bridgeStarted&&(await this.eventBridge.stop(),this.bridgeStarted=false,this.sessionId=void 0);}};var
|
|
11
|
-
`&&t[r]!=="\r";)r++;continue}if(!s&&a==="/"&&t[r+1]==="*"){for(r+=2;r<t.length-1;){if(t[r]==="*"&&t[r+1]==="/"){r+=2;break}r++;}continue}i.push(a);}return e=i.join("").trim(),e?JSON.parse(e):null}catch(t){return z.debug("Failed to load config file",{file:o,error:String(t)}),null}}function ft(o,t){let e={...o,...t};return (o.server||t.server)&&(e.server={...o.server,...t.server}),(o.channels||t.channels)&&(e.channels={...o.channels,...t.channels}),e}async function ni(){let o=w(),t=Dt(),e=[],s=ue__namespace.default.join(o.Path.config);e.push(s),e.push(t.directory);try{let{Filesystem:i}=await import('@easbot/utils'),r=await Array.fromAsync(i.up({targets:[".easbot"],start:t.directory,stop:t.worktree}));e.push(...r);}catch{z.debug("Filesystem utils not available, using basic directories");}let n=process.env.EASBOT_CONFIG_DIR;return n&&(e.push(n),z.debug("Using EASBOT_CONFIG_DIR",{path:n})),[...new Set(e)]}async function ii(o){let t=["gateway.json"],e={};for(let s of t){let n=ue__namespace.default.join(o,s),i=await ms(n);if(i)if("gateway"in i&&i.gateway){let r=i.gateway,a={};"enabled"in r&&(a.enabled=r.enabled),"port"in r&&(a.port=r.port),"hostname"in r&&(a.hostname=r.hostname),"path"in r&&(a.path=r.path),"https"in r&&(a.https=r.https),e=ft(e,{server:a,channels:r.channels}),z.debug("Loaded gateway config from file",{file:n});}else "gateway"in i||(e=ft(e,i),z.debug("Loaded gateway config from file (direct format)",{file:n}));}return e}async function ri(o){let t=["easbot.json"];for(let e of t){let s=ue__namespace.default.join(o,e),n=await ms(s);if(n?.gateway)return z.debug("Loaded gateway config from easbot.json",{file:s}),n.gateway}return {}}function ai(){return Ae||(Ae=async()=>{let o=await ni(),t={};for(let s of o){let n=await ii(s);t=ft(t,n);let i=await ri(s);t=ft(t,i);}let e=Et(t);return Pe=e,z.info("Gateway config loaded",{directories:o.length,port:e.server?.port,logLevel:e.logLevel}),{config:e,directories:o}}),Ae}async function k(){return ai()()}async function ls(o){return o&&(Ae=void 0,Pe=null),(await k()).config}function ds(){return Pe}function gs(){return Pe!==null}function oi(){Ae=void 0,Pe=null,z.debug("Config cache cleared");}function ci(){return Dt().directory}async function li(){let{config:o}=await k();return gt.parse({...yt,...o.server})}async function di(o){let{config:t}=await k(),e=t.channels?.[o],n={telegram:Ze.parse(Qn),slack:et.parse(Xn),feishu:tt.parse(Yn),wechat:st.parse(Zn),webchat:nt.parse(ei),signal:it.parse(ti),nostr:rt.parse(si)}[o];if(!n)throw new Error(`Unknown channel type: ${o}`);return {...n,...e}}async function gi(){let{config:o}=await k();return at.parse({...jn,...o.connectionPool})}async function ui(){let{config:o}=await k();return ot.parse({...qn,...o.messageQueue})}async function pi(){let{config:o}=await k();return ct.parse({...Kn,...o.circuitBreaker})}async function hi(){let{config:o}=await k();return lt.parse({...Vn,...o.agentRegistry})}async function mi(){let{config:o}=await k();return dt.parse({...Jn,...o.session})}async function fi(){let{config:o}=await k();if(o.client)return ut.parse(o.client)}async function yi(){let{config:o}=await k();if(!(o.client?.autoRegister??true))return;let e=o.server,s=e?.hostname??"localhost",n=e?.port??8080,i=e?.path||"/acp";return `ws://${s}:${n}${i}`}async function bi(){let{config:o}=await k();return o.server?.https}async function Si(){let{config:o}=await k();return o.server?.auth}async function Ci(){let{config:o}=await k();return o.cluster}async function wi(){let{config:o}=await k();return o.defaultAgent}async function us(){let{config:o}=await k();return o.logLevel??"INFO"}var Lt=yt,xe={maxConnections:1e3,connectionTimeout:36e5};var vi={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var bt={heartbeatInterval:6e4,heartbeatTimeout:3e5,heartbeatCheckInterval:3e5,autoDeregisterTimeout:6e5,maxAgents:100,maxRegistrations:1e3};var St={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};var Ii={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var j=class o extends Error{constructor(e,s){super(e);chunk6C5TBG7Z_cjs.a(this,"code");chunk6C5TBG7Z_cjs.a(this,"recoverable");chunk6C5TBG7Z_cjs.a(this,"details");chunk6C5TBG7Z_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,o);}toJSON(){return {name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,details:this.details,cause:this.cause?.message,stack:this.stack}}static isRecoverable(e){if(e instanceof o)return e.recoverable;let s=e.code;return ["ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH"].includes(s??"")}};function f(o,t,e,s=true){return new j(e,{code:t,recoverable:s,details:{channelId:o}})}var Ct=class{constructor(t,e){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:router"}));chunk6C5TBG7Z_cjs.a(this,"subscribers",new Map);chunk6C5TBG7Z_cjs.a(this,"subscriptions",new Map);chunk6C5TBG7Z_cjs.a(this,"messageSubscriptions",new Map);chunk6C5TBG7Z_cjs.a(this,"channelPlugins",new Map);chunk6C5TBG7Z_cjs.a(this,"cancelHandlers",new Set);chunk6C5TBG7Z_cjs.a(this,"processingMessages",new Map);chunk6C5TBG7Z_cjs.a(this,"hookRegistry",null);chunk6C5TBG7Z_cjs.a(this,"sessionManager",null);this.hookRegistry=t??null,this.sessionManager=e??null;}setSessionManager(t){this.sessionManager=t;}async triggerHook(t,e,s){if(this.hookRegistry)try{await this.hookRegistry.triggerEvent(t,e,s);}catch{}}async triggerBeforeSend(t,e,s){if(this.sessionManager)try{await this.sessionManager.bindBackendSession(t.sessionId,s.sessionId);}catch{}await this.triggerHook("gateway.message.process",{messageId:t.id,sessionId:t.sessionId,processorId:e,processType:"subscription",agent:e,timestamp:Date.now()});}onCancel(t){this.cancelHandlers.add(t);}offCancel(t){this.cancelHandlers.delete(t);}async emitCancel(t){for(let e of this.cancelHandlers)try{await e(t);}catch(s){this.log.error("cancel handler error",{error:String(s)});}}selectSubscriber(t){let e=this.messageSubscriptions.get(t.sessionId);if(!e||e.size===0){if(this.sessionManager){let r=this.sessionManager.get(t.sessionId);r?.backendSessionId&&(e=this.messageSubscriptions.get(r.backendSessionId));}if(!e||e.size===0){for(let[,r]of this.messageSubscriptions)if(r.size>0){e=r;break}}}if(!e||e.size===0)return null;let s=e.values().next().value;if(!s)return null;let n=this.subscriptions.get(s);if(!n)return null;let i=this.subscribers.get(n.subscriberId);return i?{subscription:n,subscriber:i}:null}async route(t){let e=this.selectSubscriber(t);if(!e)return {success:true,dispatched:false,dispatchedToSubAgent:false};let{subscription:s,subscriber:n}=e;if(t.type==="input"){let i=this.processingMessages.get(t.id);if(i&&i!==n.id)return {success:true,dispatched:false,dispatchedToSubAgent:false};this.processingMessages.set(t.id,n.id);}try{return await this.triggerBeforeSend(t,n.id,{sessionId:s.sessionId,subscriberId:s.subscriberId}),await n.connection.send(t),n.lastActiveAt=Date.now(),{success:!0,dispatched:!0,dispatchedToSubAgent:!1}}catch(i){return this.log.warn("failed to send message to subscriber",{subscriberId:n.id,error:String(i)}),t.type==="input"&&this.processingMessages.delete(t.id),{success:false,dispatched:false,dispatchedToSubAgent:false,error:i instanceof Error?i.message:String(i)}}}async completeMessage(t,e,s,n="completed"){this.processingMessages.delete(e),await this.emitCancel({sessionId:t,messageId:e,processedBy:s,reason:n,timestamp:Date.now()});}async subscribe(t,e){let s=_t(e.id,t);if(this.subscriptions.has(s))return this.subscriptions.get(s);for(let[i,r]of this.subscriptions.entries())r.subscriberId===e.id&&r.sessionId===t&&i!==s&&await this.unsubscribe(i);let n={id:s,subscriberId:e.id,sessionId:t,createdAt:Date.now()};return this.subscribers.set(e.id,e),this.subscriptions.set(s,n),this.messageSubscriptions.has(t)||this.messageSubscriptions.set(t,new Set),this.messageSubscriptions.get(t).add(s),n}async unsubscribe(t){let e=this.subscriptions.get(t);if(!e){this.log.warn("subscription not found",{subscriptionId:t});return}this.subscriptions.delete(t);let s=this.messageSubscriptions.get(e.sessionId);s&&(s.delete(t),s.size===0&&this.messageSubscriptions.delete(e.sessionId));}async unsubscribeAll(t){for(let[e,s]of this.subscriptions.entries())s.subscriberId===t&&await this.unsubscribe(e);this.subscribers.delete(t);}registerChannel(t){this.channelPlugins.set(t.id,t),this.log.info("channel plugin registered",{id:t.id,platform:t.platform});}unregisterChannel(t){this.channelPlugins.delete(t),this.log.info("channel plugin unregistered",{id:t});}getSubscriber(t){return this.subscribers.get(t)}getSubscription(t){return this.subscriptions.get(t)}getMessageSubscriptions(){return this.messageSubscriptions}getSubscriberCount(t){return this.messageSubscriptions.get(t)?.size??0}getStats(){return {subscribers:this.subscribers.size,subscriptions:this.subscriptions.size,sessions:this.messageSubscriptions.size}}async shutdown(){this.processingMessages.clear(),this.subscribers.clear(),this.subscriptions.clear(),this.messageSubscriptions.clear(),this.channelPlugins.clear(),this.cancelHandlers.clear(),this.log.info("router shutdown");}};var Me=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:message-store"}));chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"messages",new Map);chunk6C5TBG7Z_cjs.a(this,"sessionMessages",new Map);chunk6C5TBG7Z_cjs.a(this,"cleanupTimer",null);chunk6C5TBG7Z_cjs.a(this,"accessOrder",[]);chunk6C5TBG7Z_cjs.a(this,"storagePath");chunk6C5TBG7Z_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=ue__namespace.join(this.storagePath,s.name),i=await $__namespace.readdir(n);for(let r of i)if(r.endsWith(".json"))try{let a=ue__namespace.join(n,r),c=await $__namespace.readFile(a,"utf-8"),d=JSON.parse(c);d.status!=="completed"&&d.status!=="delivered"&&(this.messages.has(d.message.id)||(this.messages.set(d.message.id,d),this.addToSessionMessages(d.message.sessionId,d.message.id),t++));}catch(a){this.log.debug("failed to load message file",{file:r,error:String(a)});}}t>0&&this.log.debug("loaded messages from disk",{count:t});}catch(e){this.log.warn("failed to load messages from disk",{error:String(e)});}return t}addToSessionMessages(t,e){this.sessionMessages.has(t)||this.sessionMessages.set(t,new Set),this.sessionMessages.get(t).add(e);}async ensureDir(t){try{await $__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 ue__namespace.join(this.storagePath,`${this.sanitizeFileName(t)}.json`)}getSessionDir(t){return ue__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=ue__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.debug("LRU eviction completed",{evicted:e,remaining:this.messages.size});}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e>-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t);}deleteMessage(t){let e=this.messages.get(t);if(e){let s=this.sessionMessages.get(e.message.sessionId);s&&(s.delete(t),s.size===0&&this.sessionMessages.delete(e.message.sessionId)),this.messages.delete(t);let n=this.accessOrder.indexOf(t);n>-1&&this.accessOrder.splice(n,1);}}getStats(){let t={total:this.messages.size,pending:0,processing:0,completed:0,failed:0,cancelled:0,delivered:0,read:0,sessions:this.sessionMessages.size};for(let e of this.messages.values()){let s=e.status;s in t&&s!=="total"&&s!=="sessions"&&t[s]++;}return t}async close(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.messages.clear(),this.sessionMessages.clear(),this.accessOrder=[],this.log.info("MessageStore closed");}};var se=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:session-store"}));chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"sessions",new Map);chunk6C5TBG7Z_cjs.a(this,"channelSessions",new Map);chunk6C5TBG7Z_cjs.a(this,"autoSaveTimer",null);chunk6C5TBG7Z_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 te__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(!te__namespace.existsSync(t)){this.log.debug("no saved sessions found");return}let e=await te__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 ue__namespace.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){te__namespace.existsSync(this.config.storagePath)||await te__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 ki="./data/gateway",Ti="contacts",_i="index.json",ie=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:contact-store"}));chunk6C5TBG7Z_cjs.a(this,"baseDir");chunk6C5TBG7Z_cjs.a(this,"contactDir");chunk6C5TBG7Z_cjs.a(this,"indexPath");chunk6C5TBG7Z_cjs.a(this,"index");chunk6C5TBG7Z_cjs.a(this,"indexFileMap");chunk6C5TBG7Z_cjs.a(this,"dirty",false);chunk6C5TBG7Z_cjs.a(this,"saveTimer",null);chunk6C5TBG7Z_cjs.a(this,"SAVE_DEBOUNCE_MS",1e3);this.baseDir=t.baseDir??ki,this.contactDir=ue__namespace.join(this.baseDir,Ti),this.indexPath=ue__namespace.join(this.contactDir,_i),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=Xe(t);if(e){let s=this.getFilePath(e.platform,e.stableId);this.indexFileMap[t]=s;}}}getFilePath(t,e){let s=this.sanitizeFilename(e);return ue__namespace.join(this.contactDir,t,`${s}.json`)}sanitizeFilename(t){return t.replace(/[/\\:*?"<>|]/g,"_")}getPlatformDir(t){return ue__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(ue__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=Tt(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=Xe(t);return e?this.findByPlatformId(e.platform,e.stableId):null}async findByPlatformId(t,e){let s=Qe(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 c of r){let d=await this.findByUid(c);d&&a.push(d);}return {contacts:a,total:i,hasMore:s+e<i}}async findByUsername(t){let e=t.toLowerCase(),s=this.index.byUsername[e];return s?this.findByUid(s):null}async findByEmail(t){let e=t.toLowerCase(),s=this.index.byEmail[e];return s?this.findByUid(s):null}async findByPhone(t){let e=t.replace(/\s/g,""),s=this.index.byPhone[e];return s?this.findByUid(s):null}async search(t){if(t.platform){let c=await this.listByPlatform(t.platform,t.limit,t.offset),d=c.contacts;if(t.username){let g=t.username.toLowerCase();d=d.filter(p=>p.profile.username?.toLowerCase().includes(g));}if(t.email){let g=t.email.toLowerCase();d=d.filter(p=>p.profile.email?.toLowerCase().includes(g));}if(t.phone){let g=t.phone.replace(/\s/g,"");d=d.filter(p=>p.profile.phone?.replace(/\s/g,"").includes(g));}return {contacts:d,total:c.total,hasMore:c.hasMore}}let e=[];for(let c of Object.keys(this.index.byPlatform)){let d=await this.listByPlatform(c,1e3,0);e.push(...d.contacts);}let s=e;if(t.username){let c=t.username.toLowerCase();s=s.filter(d=>d.profile.username?.toLowerCase().includes(c));}if(t.email){let c=t.email.toLowerCase();s=s.filter(d=>d.profile.email?.toLowerCase().includes(c));}if(t.phone){let c=t.phone.replace(/\s/g,"");s=s.filter(d=>d.profile.phone?.replace(/\s/g,"").includes(c));}let n=s.length,i=t.limit??100,r=t.offset??0;return {contacts:s.slice(r,r+i),total:n,hasMore:r+i<n}}async count(t){return t?(this.index.byPlatform[t]||[]).length:Object.keys(this.index.byUid).length}async exists(t){return await this.findByUid(t)!==null}async addAlias(t,e,s){let n=await this.findByUid(t);if(!n)return null;let i={...n,aliases:{...n.aliases,[e]:{...n.aliases[e],...s}},lastSeenAt:Date.now()};return this.save(i)}async close(){this.saveTimer&&clearTimeout(this.saveTimer),this.dirty&&await this.doSaveIndex(),this.log.info("contact store closed");}updateSearchIndices(t){let{uid:e,profile:s}=t;s.username&&(this.index.byUsername[s.username.toLowerCase()]=e),s.email&&(this.index.byEmail[s.email.toLowerCase()]=e),s.phone&&(this.index.byPhone[s.phone.replace(/\s/g,"")]=e);}removeFromSearchIndices(t){let{uid:e,profile:s}=t;if(s.username){let n=s.username.toLowerCase();this.index.byUsername[n]===e&&delete this.index.byUsername[n];}if(s.email){let n=s.email.toLowerCase();this.index.byEmail[n]===e&&delete this.index.byEmail[n];}if(s.phone){let n=s.phone.replace(/\s/g,"");this.index.byPhone[n]===e&&delete this.index.byPhone[n];}}};var Gt=class{constructor(t){chunk6C5TBG7Z_cjs.a(this,"cache",new Map);chunk6C5TBG7Z_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}},ke=class{constructor(t,e={}){chunk6C5TBG7Z_cjs.a(this,"store",t);chunk6C5TBG7Z_cjs.a(this,"cache");chunk6C5TBG7Z_cjs.a(this,"usernameIndex");chunk6C5TBG7Z_cjs.a(this,"emailIndex");chunk6C5TBG7Z_cjs.a(this,"phoneIndex");chunk6C5TBG7Z_cjs.a(this,"platformIndex");chunk6C5TBG7Z_cjs.a(this,"initialized",false);this.cache=new Gt(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 H=utils.Log.create({service:"gateway:storage:agent-registry"}),Te=class{constructor(t){chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"filePath");chunk6C5TBG7Z_cjs.a(this,"cache",new Map);chunk6C5TBG7Z_cjs.a(this,"initialized",false);this.config=t,this.filePath=ue__namespace.join(t.dataDir,"agent-registry.json");}async initialize(){if(!this.initialized)try{await $__namespace.mkdir(this.config.dataDir,{recursive:!0}),this.initialized=!0,H.debug("Agent registry store initialized",{dataDir:this.config.dataDir});}catch(t){throw H.error("Failed to initialize agent registry store",{dataDir:this.config.dataDir,error:String(t)}),t}}async loadFromDisk(){await this.initialize();try{let t=await $__namespace.readFile(this.filePath,"utf-8"),e=JSON.parse(t),s=new Map;for(let n of e)n.agent?.id&&s.set(n.agent.id,n);return H.debug("Agent registry loaded from disk",{count:s.size}),s}catch(t){return t.code==="ENOENT"?(H.debug("Agent registry file not found, starting fresh"),new Map):(H.error("Failed to load agent registry from disk",{error:String(t)}),new Map)}}async saveToDisk(){await this.initialize();try{let t=Array.from(this.cache.values());await $__namespace.writeFile(this.filePath,JSON.stringify(t,null,2),"utf-8"),H.debug("Agent registry saved to disk",{count:this.cache.size});}catch(t){throw H.error("Failed to save agent registry to disk",{error:String(t)}),t}}async loadAll(){let t=await this.loadFromDisk();return this.cache=t,Array.from(this.cache.values()).map(e=>e.agent)}async save(t){await this.initialize();let e={agent:t,storedAt:Date.now()};this.cache.set(t.id,e),await this.saveToDisk(),H.debug("Agent registration saved",{agentId:t.id});}async saveAll(t){await this.initialize();for(let e of t){let s={agent:e,storedAt:Date.now()};this.cache.set(e.id,s);}await this.saveToDisk(),H.debug("All agent registrations saved",{count:t.length});}async delete(t){await this.initialize(),this.cache.has(t)&&(this.cache.delete(t),await this.saveToDisk(),H.debug("Agent registration deleted",{agentId:t}));}getFilePath(){return this.filePath}};var _e=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:session"}));chunk6C5TBG7Z_cjs.a(this,"sessionStore");chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_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 se({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=Ve(t),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),n):(n={id:s,channel:t,backendSessionId:null,subscribers:new Set,state:Je(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(n),n)}get(t){return this.sessionStore.get(t)}async closeSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.state.status="closed",await this.sessionStore.delete(t);}async closeById(t){return this.closeSession(t)}async bindBackendSession(t,e){let s=this.sessionStore.get(t);if(!s)throw new Error(`Session not found: ${t}`);s.backendSessionId=e,await this.sessionStore.set(s);}async unbindBackendSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.backendSessionId=null,await this.sessionStore.set(e);}findByBackendSessionId(t){for(let e of this.sessionStore.getAll())if(e.backendSessionId===t)return e}getState(t){return this.sessionStore.get(t)?.state}async incrementMessageCountOrCreate(t,e){let s=this.sessionStore.get(t);if(!s){if(!e)throw new Error(`Cannot create session: channelInfo is required when session "${t}" does not exist`);let n=Ve(e);n!==t&&this.log.warn("sessionId mismatch, using correct sessionId from channelInfo",{providedSessionId:t,correctSessionId:n}),s={id:n,channel:e,backendSessionId:null,subscribers:new Set,state:Je(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(s),this.log.debug("session auto-created from message",{sessionId:n,platform:e.platform,channelId:e.channelId,chatId:e.chatId,userId:e.userId});}return s.state.messageCount++,s.state.lastMessageAt=Date.now(),s.lastActiveAt=Date.now(),await this.sessionStore.set(s),s}async incrementMessageCount(t){let e=this.sessionStore.get(t);e&&(e.state.messageCount++,e.state.lastMessageAt=Date.now(),e.lastActiveAt=Date.now(),await this.sessionStore.set(e));}async addSubscriber(t,e){let s=this.sessionStore.get(t);if(!s){this.log.warn("session not found",{sessionId:t});return}s.subscribers.add(e),await this.sessionStore.set(s);}async removeSubscriber(t,e){let s=this.sessionStore.get(t);s&&(s.subscribers.delete(e),await this.sessionStore.set(s));}query(t){let e=this.sessionStore.getAll();return t.platform&&(e=e.filter(s=>s.channel.platform===t.platform)),t.channelId&&(e=e.filter(s=>s.channel.channelId===t.channelId)),t.userId&&(e=e.filter(s=>s.channel.userId===t.userId)),t.status&&(e=e.filter(s=>s.state.status===t.status)),e}getSessionsByChannel(t){return this.sessionStore.getByChannel(t)}getAllSessions(){return this.sessionStore.getAll()}getSessionCount(){return this.sessionStore.size()}async cleanupIdleSessions(t){let e=Date.now(),s=[];for(let n of this.sessionStore.getAll())n.state.status==="idle"&&e-n.lastActiveAt>t&&s.push(n.id);for(let n of s)await this.closeSession(n);return s.length}async save(){}getStats(){return this.sessionStore.getStats()}};var Ee=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:plugin-loader"}));chunk6C5TBG7Z_cjs.a(this,"plugins",new Map);chunk6C5TBG7Z_cjs.a(this,"messageHandler",null);chunk6C5TBG7Z_cjs.a(this,"healthCheckTimer",null);chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_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;}updateSessionHandler(t){this.messageHandler&&(this.messageHandler.session=t,this.log.debug("session handler updated"));}async register(t,e){if(this.plugins.has(t.id)){this.log.warn("plugin already registered",{id:t.id});return}this.plugins.set(t.id,{plugin:t,config:e,started:false,reconnectAttempts:0}),this.log.info("plugin registered",{id:t.id,platform:t.platform,name:t.name});}async unregister(t){let e=this.plugins.get(t);if(!e){this.log.warn("plugin not found",{id:t});return}this.cancelReconnect(t),e.started&&await this.stop(t),this.plugins.delete(t),this.log.info("plugin unregistered",{id:t});}async start(t){let e=this.plugins.get(t);if(!e)throw new j(`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 j("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 V=class extends Error{constructor(e,s,n){super(e);chunk6C5TBG7Z_cjs.a(this,"code",s);chunk6C5TBG7Z_cjs.a(this,"configuredChannels",n);this.name="ChannelSelectionError";}},K=utils.Log.create({service:"gateway:channel-selection"});function he(o){if(!(!o||typeof o!="string"))return o.toLowerCase().trim()}async function Bt(o){let{channel:t,sessionId:e,userId:s,defaultChannel:n,fallbackChannels:i,sessionManager:r,pluginLoader:a,contactStore:c}=o,d=he(t);if(d){let b=Ut(d,a);if(b){if(e){let S=Ft(e,r);if(S){if(S.channelInfo.chatId||S.channelInfo.userId)return K.debug("enriching explicit channel with session info",{sessionId:e,chatId:S.channelInfo.chatId,userId:S.channelInfo.userId}),{...b,channelInfo:{...b.channelInfo,chatId:S.channelInfo.chatId,userId:S.channelInfo.userId}}}else if(s&&r){K.debug("session not found, creating new session for private chat",{userId:s});let T=s,_={platform:b.channelInfo.platform,channelId:b.channel,chatId:T,userId:s};try{let M=await r.getOrCreate(_);return K.debug("auto-created session for private chat",{sessionId:M.id,chatId:T,userId:s}),{channel:b.channel,source:"session-bound",channelInfo:M.channel}}catch(M){K.warn("failed to auto-create session, using explicit channel info",{userId:s,error:String(M)});}}}if(s&&c){let S=await Li(d,s,c,a);if(S)return S}return b}if(e){let S=Ft(e,r);if(S){if((!S.channelInfo.chatId||!S.channelInfo.userId)&&S.channelInfo.platform!=="api"){let _=Ui(S.channelInfo.platform,r);if(_)return K.debug("session missing chatId/userId, using session with complete info",{originalSessionId:e,newSessionId:_.channelInfo.chatId}),_}return S}}throw new V(`Channel \u4E0D\u53EF\u7528\u6216\u672A\u914D\u7F6E: ${d}`,"CHANNEL_UNAVAILABLE",[])}if(e){let b=Ft(e,r);if(b)return b}if(s&&c){let b=await Gi(s,c,a);if(b)return b}let g=Ot(a);if(g.length===0)throw new V("\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684 Channel\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F\u3002\u8BF7\u81F3\u5C11\u914D\u7F6E\u4E00\u4E2A Channel\u3002","NO_CHANNEL",[]);let p=he(n);if(p){let b=Ut(p,a);if(b)return K.debug("using default channel",{channel:p}),{...b,source:"default"};K.warn("default channel unavailable",{channel:p});}if(g.length===1){let b=g[0],S=a?.getPlugin(b);return {channel:b,source:"single-configured",channelInfo:{platform:S?.platform,channelId:b}}}let h=(i??[]).map(he).filter(b=>b!==void 0);for(let b of h){let S=Ut(b,a);if(S)return K.debug("using fallback channel",{channel:b}),{...S,source:"fallback"};K.debug("fallback channel unavailable, trying next",{channel:b});}throw p?new V(`\u914D\u7F6E\u7684\u9ED8\u8BA4 Channel \u4E0D\u53EF\u7528: ${p}`,"CHANNEL_UNAVAILABLE",g):new V(`\u9700\u8981\u660E\u786E\u6307\u5B9A Channel\uFF08\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF09: ${g.join(", ")}\u3002\u8BF7\u901A\u8FC7 channel \u53C2\u6570\u6307\u5B9A\u8981\u4F7F\u7528\u7684 Channel\uFF0C\u6216\u5728 gateway.json \u4E2D\u914D\u7F6E defaults.channel\u3002`,"MULTIPLE_CHANNELS",g)}function Ut(o,t){if(!t)return null;let e=t.getPlugin(o);if(e&&t.isRunning(o))return {channel:o,source:"explicit",channelInfo:{platform:e.platform,channelId:o}};let s=he(o);if(!s)return null;let n=t.getAllPlugins();for(let i of n)if(t.isRunning(i.id)&&he(i.platform)===s)return {channel:i.id,source:"explicit",channelInfo:{platform:i.platform,channelId:i.id}};return null}function Ft(o,t){if(!t)return null;let e=t.get(o);return e?{channel:e.channel.channelId,source:"session-bound",channelInfo:e.channel}:null}async function Li(o,t,e,s){let n=s?.getPlugin(o);if(!n)return null;let i=await e.findByPlatformId(n.platform,t);return i?{channel:o,source:"explicit",channelInfo:{platform:n.platform,channelId:o,userId:i.stableId,chatId:i.stableId}}:null}async function Gi(o,t,e){let s=Ot(e);if(s.length===0)return null;for(let n of s){let i=e?.getPlugin(n);if(!i)continue;let r=await t.findByPlatformId(i.platform,o);if(r)return {channel:n,source:"single-configured",channelInfo:{platform:i.platform,channelId:n,userId:r.stableId,chatId:r.stableId}}}return null}function Ot(o){if(!o)return [];let t=[],e=o.getAllPlugins();for(let s of e)o.isRunning(s.id)&&t.push(s.id);return t}function $t(o){switch(o.code){case "NO_CHANNEL":return "\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684 Channel\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F\u3002\u8BF7\u5728 gateway.json \u4E2D\u914D\u7F6E\u81F3\u5C11\u4E00\u4E2A Channel\u3002";case "MULTIPLE_CHANNELS":return `\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF0C\u9700\u8981\u660E\u786E\u6307\u5B9A: ${o.configuredChannels?.join(", ")||""}\u3002\u8BF7\u901A\u8FC7 channel \u53C2\u6570\u6307\u5B9A\u8981\u4F7F\u7528\u7684 Channel\uFF0C\u6216\u5728 gateway.json \u4E2D\u914D\u7F6E defaults.channel \u4F5C\u4E3A\u9ED8\u8BA4\u503C\u3002`;case "CHANNEL_UNAVAILABLE":return o.message;case "UNKNOWN_CHANNEL":return `\u672A\u77E5\u7684 Channel: ${o.message}\u3002\u8BF7\u68C0\u67E5 Channel ID \u662F\u5426\u6B63\u786E\u3002`;default:return o.message}}function Ui(o,t){if(!t)return null;let e=t.getAll?.()??[];for(let s of e)if(s.channel.platform===o&&s.channel.chatId&&s.channel.userId)return {channel:s.channel.channelId,source:"session-bound",channelInfo:s.channel};for(let s of e)if(s.channel.platform===o&&s.channel.chatId)return {channel:s.channel.channelId,source:"session-bound",channelInfo:s.channel};return null}var y=utils.Log.create({service:"gateway:websocket-server"});function Wt(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function N(o,t){for(let[e,s]of t.entries())if(s===o)return e;return null}var re=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"server",null);chunk6C5TBG7Z_cjs.a(this,"wss",null);chunk6C5TBG7Z_cjs.a(this,"httpsServer",null);chunk6C5TBG7Z_cjs.a(this,"httpRedirectServer",null);chunk6C5TBG7Z_cjs.a(this,"connections",new Map);chunk6C5TBG7Z_cjs.a(this,"subscriptions",new Map);chunk6C5TBG7Z_cjs.a(this,"clientLastActivity",new Map);chunk6C5TBG7Z_cjs.a(this,"cleanupInterval",null);chunk6C5TBG7Z_cjs.a(this,"heartbeatInterval",null);chunk6C5TBG7Z_cjs.a(this,"startTime",0);chunk6C5TBG7Z_cjs.a(this,"running",false);chunk6C5TBG7Z_cjs.a(this,"channelResolveParams",null);chunk6C5TBG7Z_cjs.a(this,"pluginLoaderRef",null);chunk6C5TBG7Z_cjs.a(this,"agentSyncRef",null);chunk6C5TBG7Z_cjs.a(this,"agentRegistryRef",null);chunk6C5TBG7Z_cjs.a(this,"routerRef",null);chunk6C5TBG7Z_cjs.a(this,"subscribers",new Map);this.config={...Lt,...t};}setChannelResolveDeps(t){this.channelResolveParams=t;}setPluginLoader(t){this.pluginLoaderRef=t;}getGatewayId(){let t=this.config.https?.enabled?"https":"http",e=this.config.hostname||"localhost",s=this.config.port||8080,n=`${t}://${e}:${s}`;return Hi__default.default.createHash("sha256").update(n).digest("hex").substring(0,16)}setAgentSync(t){this.agentSyncRef=t;}setAgentRegistry(t){this.agentRegistryRef=t;}setRouter(t){this.routerRef=t;}getChannelResolveParams(){return this.channelResolveParams?this.channelResolveParams:{}}async start(){if(this.running){y.warn("WebSocket server is already running");return}y.debug("WebSocket server starting",{port:this.config.port,hostname:this.config.hostname,https:this.config.https?.enabled??false}),this.startTime=Date.now();let t={onOpen:(n,i)=>{this.handleConnection(i);},onMessage:async(n,i)=>{try{let r=JSON.parse(n.data.toString());await this.handleMessage(i,r);}catch(r){y.error("Error processing WebSocket message",{error:r.message}),this.sendError(i,r.message);}},onClose:(n,i)=>{this.handleDisconnection(i);},onError:(n,i)=>{y.error("WebSocket error",{error:n.type});}},e=this.config.https?.enabled??false;try{e?await this.startHTTPSServer(t):await this.startHTTPServer(t);}catch(n){throw y.error("WebSocket server start: HTTP/HTTPS server failed",{error:n instanceof Error?n.message:String(n)}),n}this.cleanupInterval=setInterval(()=>this.cleanupInactiveClients(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let s=e?"wss":"ws";y.info("WebSocket server started",{url:`${s}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(t){this.server=utils.createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let e=this.server.raw;e?this.setupWebSocketUpgrade(e,t):y.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(t){let e=this.config.https,s=this.loadSSLCertificates(e);if(!s){y.error("Failed to load SSL certificates, falling back to HTTP"),await this.startHTTPServer(t);return}this.server=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=$i__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,()=>{y.info("HTTPS server started",{port:this.config.port,hostname:this.config.hostname}),i();});}),e.forceRedirect&&e.httpPort&&this.startHTTPRedirectServer(e.httpPort);}loadSSLCertificates(t){try{return t.cert&&t.key?{cert:t.cert,key:t.key}:t.certPath&&t.keyPath?{cert:te__namespace.default.readFileSync(t.certPath),key:te__namespace.default.readFileSync(t.keyPath)}:null}catch(e){return y.error("Failed to load SSL certificates",{error:e.message}),null}}setupWebSocketUpgrade(t,e){this.wss=new ws.WebSocketServer({noServer:true}),t.on("upgrade",(s,n,i)=>{try{let a=new URL(s.url||"/",`http://${s.headers.host}`).pathname,c=this.config.path||"";(a===c||c===""&&(a==="/"||a===""))&&this.wss.handleUpgrade(s,n,i,d=>{e.onOpen?.({type:"open"},d),d.on("message",g=>{e.onMessage?.({data:g},d);}),d.on("close",(g,p)=>{e.onClose?.({code:g,reason:p},d);}),d.on("error",g=>{e.onError?.({type:"error",message:g.message},d);});});}catch{}});}startHTTPRedirectServer(t){this.httpRedirectServer=Wi__default.default.createServer((e,s)=>{let i=`https://${e.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${e.url}`;s.writeHead(301,{Location:i,"Content-Type":"text/plain"}),s.end(`Redirecting to ${i}`);}),this.httpRedirectServer.listen(t,this.config.hostname,()=>{y.info("HTTP redirect server started",{port:t,hostname:this.config.hostname});});}async stop(){if(!this.running){y.warn("WebSocket server is not running");return}y.info("Stopping WebSocket server"),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let[t,e]of this.connections.entries())try{e.close(1e3,"Server shutting down");}catch{}this.connections.clear(),this.subscriptions.clear(),this.subscribers.clear(),this.clientLastActivity.clear(),this.wss&&(this.wss.close(),this.wss=null),this.httpsServer&&(await new Promise(t=>{this.httpsServer.close(()=>t());}),this.httpsServer=null),this.httpRedirectServer&&(await new Promise(t=>{this.httpRedirectServer.close(()=>t());}),this.httpRedirectServer=null),this.server&&(await this.server.stop(),this.server=null),this.running=false,y.info("WebSocket server stopped");}touchClient(t){this.clientLastActivity.set(t,Date.now());let e=this.subscriptions.get(t);e&&(e.lastActivityAt=Date.now());}getConnectionCount(){return this.connections.size}getStartTime(){return this.startTime}getSubscriptionCount(){return this.subscribers.size}getConnectionInfos(){let t=[];for(let[e,s]of this.subscriptions.entries())t.push({clientId:e,state:s.ws.readyState===s.ws.OPEN?"connected":"disconnected",connectedAt:s.connectedAt,lastActivityAt:s.lastActivityAt,authInfo:s.authInfo});return t}isRunning(){return this.running}handleConnection(t){if(this.connections.size>=(this.config.maxConnections??xe.maxConnections)){y.warn("Maximum connections reached, rejecting new connection"),t.close(1013,"Maximum connections reached");return}let e=Wt();this.connections.set(e,t),this.subscriptions.set(e,{clientId:e,ws:t,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()}),y.debug("WebSocket client connected",{clientId:e,totalConnections:this.connections.size}),this.sendMessage(t,{type:"connected",clientId:e,payload:{version:"1.0.0",capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}async handleDisconnection(t){let e=N(t,this.connections);e&&(this.connections.delete(e),await this.cleanupClientResources(e),y.debug("WebSocket client disconnected",{clientId:e,totalConnections:this.connections.size}));}async cleanupClientResources(t){if(y.debug("Cleaning up client resources",{clientId:t}),this.routerRef){try{await this.routerRef.unsubscribeAll(t);}catch{}this.subscribers.delete(t),y.debug("Subscriber cleaned up from router",{clientId:t});}if(this.agentSyncRef)try{await this.agentSyncRef.cleanupClient(t);}catch{}this.subscriptions.delete(t),this.clientLastActivity.delete(t);}async handleMessage(t,e){let s=N(t,this.connections);if(!s){this.sendError(t,"Client not found");return}let n=this.subscriptions.get(s);switch(n&&(n.lastActivityAt=Date.now()),e.type){case "ping":this.sendMessage(t,{type:"pong"});break;case "subscribe":await this.handleSubscribe(t,e);break;case "unsubscribe":await this.handleUnsubscribe(t,e);break;case "message":await this.handleMessageRequest(t,e);break;case "interrupt":await this.handleInterrupt(t,e);break;case "releaseSubscription":await this.handleReleaseSubscription(t,e);break;case "agent_list_request":await this.handleAgentListRequest(t,e);break;case "agent_subscribe":await this.handleAgentSubscribe(t,e);break;case "agent_register":await this.handleAgentRegister(t,e);break;case "agent_deregister":await this.handleAgentDeregister(t,e);break;default:this.sendError(t,`Unknown message type: ${e.type}`);}}async handleSubscribe(t,e){if(e.type!=="subscribe"||!e.sessionId){this.sendError(t,"Invalid subscribe request");return}let s=e.clientId,n;if(s){n=s;let r=N(t,this.connections);r&&r!==n&&(await this.cleanupClientResources(r),this.connections.delete(r),y.info("Client reconnected with different clientId, cleaned up old resources",{oldClientId:r,newClientId:n})),this.connections.set(n,t);}else n=N(t,this.connections)??Wt(),N(t,this.connections)||this.connections.set(n,t);let i=this.subscriptions.get(n);if(i?(i.ws=t,i.lastActivityAt=Date.now()):(i={clientId:n,ws:t,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()},this.subscriptions.set(n,i)),e.payload?.eventTypes)for(let r of e.payload.eventTypes)i.subscribedEventTypes.add(r);if(y.debug("Client subscribed to session",{clientId:n,sessionId:e.sessionId}),this.routerRef){if(this.subscribers.get(n))try{await this.routerRef.unsubscribeAll(n);}catch{}let a=e.payload?.clientType||"tui",c={id:n,type:a,createdAt:Date.now(),lastActiveAt:Date.now(),connection:{send:async d=>{this.sendMessage(t,{type:"message",sessionId:d.sessionId,payload:{id:d.id,type:d.type,content:d.content,metadata:d.metadata,timestamp:d.timestamp}});},close:async()=>{t.close(1e3,"Subscriber closed");},isConnected:()=>t.readyState===t.OPEN}};this.subscribers.set(n,c),await this.routerRef.subscribe(e.sessionId,c),y.debug("Subscriber registered to router",{clientId:n,sessionId:e.sessionId});}this.sendMessage(t,{type:"subscribed",sessionId:e.sessionId});}async handleUnsubscribe(t,e){if(e.type!=="unsubscribe"||!e.sessionId){this.sendError(t,"Invalid unsubscribe request");return}let s=N(t,this.connections);if(s){if(y.debug("Client unsubscribed from session",{clientId:s,sessionId:e.sessionId}),this.routerRef){let n=this.subscribers.get(s);if(n){let i=`sub_${n.id}_${e.sessionId}`;try{await this.routerRef.unsubscribe(i),y.debug("Subscriber unregistered from router",{clientId:s,sessionId:e.sessionId});}catch(r){y.debug("Failed to unsubscribe from router (subscription may not exist)",{clientId:s,sessionId:e.sessionId,error:String(r)});}this.subscribers.delete(s);}}this.sendMessage(t,{type:"unsubscribed",sessionId:e.sessionId});}}async handleMessageRequest(t,e){if(e.type!=="message"||!e.sessionId||!e.payload){this.sendError(t,"Invalid message request");return}let s=this.getClientIdByWs(t)||"unknown";y.debug("Message received from WebSocket client",{clientId:s,sessionId:e.sessionId});let n=e.payload,i=n.message?{...n.message}:{id:`ws_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:e.sessionId,content:n.content||[{type:"text",text:""}]};y.debug("Message received from WebSocket client (use HTTP API to send)",{messageId:i.id,sessionId:e.sessionId}),this.sendMessage(t,{type:"response",sessionId:e.sessionId,success:true,result:{received:true}});}getClientIdByWs(t){return N(t,this.connections)}getClientWs(t){return this.connections.get(t)}async handleInterrupt(t,e){if(e.type!=="interrupt"||!e.sessionId){this.sendError(t,"Invalid interrupt request");return}y.debug("Interrupt requested via WebSocket",{sessionId:e.sessionId}),this.sendMessage(t,{type:"interrupted",sessionId:e.sessionId,success:true});}async handleReleaseSubscription(t,e){if(e.type!=="releaseSubscription"||!e.sessionId){this.sendError(t,"Invalid releaseSubscription request");return}let s=N(t,this.connections);if(!s){this.sendError(t,"Client not found");return}if(y.debug("Release subscription requested via WebSocket",{clientId:s,sessionId:e.sessionId}),this.routerRef){let i=`sub_${s}_${e.sessionId}`;try{await this.routerRef.unsubscribe(i);}catch{}}let n=this.subscriptions.get(s);n&&n.subscribedSessions.delete(e.sessionId),this.sendMessage(t,{type:"subscriptionReleased",sessionId:e.sessionId});}async checkConnectionTimeout(){let t=Date.now(),e=this.config.connectionTimeout??xe.connectionTimeout,s=[];for(let[n,i]of this.subscriptions.entries())t-i.lastActivityAt>e&&s.push(n);for(let n of s){await this.cleanupClientResources(n);let i=this.connections.get(n);if(i){y.debug("Closing inactive connection",{clientId:n,lastActivityAt:this.clientLastActivity.get(n),timeoutMs:e});try{i.close(1001,"Connection timeout");}catch(r){y.debug("Error closing timed out connection",{clientId:n,error:String(r)});}this.connections.delete(n);}}s.length>0&&y.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size});}async cleanupInactiveClients(){let t=Date.now(),e=[],s=this.config.connectionTimeout??xe.connectionTimeout;for(let[n,i]of this.clientLastActivity.entries())t-i>s&&e.push(n);for(let n of e){await this.cleanupClientResources(n);let i=this.connections.get(n);if(i){y.debug("Client inactive, closing connection",{clientId:n,lastActivity:this.clientLastActivity.get(n),timeoutMs:s});try{i.close(1001,"Client inactive");}catch(r){y.debug("Error closing inactive client",{clientId:n,error:String(r)});}this.connections.delete(n);}}e.length>0&&y.debug("Cleaned up inactive clients",{count:e.length,remainingActive:this.clientLastActivity.size});}sendMessage(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e));}sendError(t,e,s){this.sendMessage(t,{type:"error",message:e,code:s});}createRoutes(){return [{method:"get",path:"/health",handler:t=>{let e={status:"healthy",timestamp:Date.now(),version:"1.0.0"};return t.json(e)}},{method:"get",path:"/status",handler:async t=>{let e=await mt();if(e)return t.json(e);let s={status:this.running?"running":"stopped",connections:this.connections.size,sessions:0,messageSubscriptions:0,agentSubscriptions:0,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0",channels:[]};return t.json(s)}},{method:"get",path:"/channels",handler:async t=>{let e=this.channelResolveParams?.pluginLoader;if(!e)return t.json({error:"Plugin loader not available"},503);let n=e.getAllPlugins().map(i=>({id:i.id,platform:i.platform,name:i.name,version:i.version}));return t.json({channels:n,total:n.length})}},{method:"get",path:"/contacts",handler:async t=>{let e=t.req.query("platform"),s=parseInt(t.req.query("limit")||"100",10),n=parseInt(t.req.query("offset")||"0",10),i=this.channelResolveParams?.contactStore;if(!i)return t.json({error:"Contact store not available"},503);try{if(e){let r=await i.listByPlatform(e,s,n);return t.json({contacts:r.contacts.map(a=>({uid:a.uid,platform:a.platform,stableId:a.stableId,profile:a.profile,lastSeenAt:a.lastSeenAt,createdAt:a.createdAt})),total:r.total,hasMore:r.hasMore})}else {let r=await i.count();return t.json({total:r,message:"Specify platform query parameter to list contacts"})}}catch(r){return y.error("failed to list contacts",{error:String(r)}),t.json({error:String(r)},500)}}},{method:"get",path:"/contacts/:uid",handler:async t=>{let e=t.req.param("uid"),s=this.channelResolveParams?.contactStore;if(!s)return t.json({error:"Contact store not available"},503);try{let n=await s.findByUid(e);return n?t.json({uid:n.uid,platform:n.platform,stableId:n.stableId,profile:n.profile,aliases:n.aliases,lastSeenAt:n.lastSeenAt,createdAt:n.createdAt}):t.json({error:"Contact not found"},404)}catch(n){return y.error("failed to get contact",{uid:e,error:String(n)}),t.json({error:String(n)},500)}}},{method:"get",path:"/sessions",handler:async t=>{let e=parseInt(t.req.query("limit")||"100",10),s=parseInt(t.req.query("offset")||"0",10),n=t.req.query("platform"),i=t.req.query("channelId"),r=t.req.query("userId"),a=t.req.query("chatId"),c=[],g=this.getChannelResolveParams().sessionManager?.getAll?.()??[];for(let h of g){let b=!n||h.channel.platform===n,S=!i||h.channel.channelId===i,T=!r||h.channel.userId===r,_=!a||h.channel.chatId===a;b&&S&&(!r&&!a||T&&_)&&c.push({id:h.id,platform:h.channel.platform,channelId:h.channel.channelId,userId:h.channel.userId,chatId:h.channel.chatId,chatType:h.channel.chatType,chatTitle:h.channel.chatTitle,state:h.state.status,createdAt:h.createdAt,lastActiveAt:h.lastActiveAt});}let p=c.slice(s,s+e);return t.json({sessions:p,total:c.length,hasMore:s+e<c.length})}},{method:"get",path:"/sessions/:sessionId",handler:async t=>{let e=t.req.param("sessionId"),n=this.channelResolveParams?.sessionManager?.get(e);if(!n)return t.json({error:"Session not found"},404);let i=0;return n.backendSessionId&&this.routerRef&&(i=this.routerRef.getMessageSubscriptions().get(n.backendSessionId)?.size??0),t.json({id:n.id,platform:n.channel.platform,channelId:n.channel.channelId,userId:n.channel.userId,chatId:n.channel.chatId,state:n.state.status,backendSessionId:n.backendSessionId,subscriberCount:i,createdAt:n.createdAt,lastActiveAt:n.lastActiveAt})}},{method:"post",path:"/session",handler:async t=>{let e=await t.req.json().catch(()=>({}));if(!this.channelResolveParams?.sessionManager)return t.json({error:"Session manager not available"},500);let s=e.channel?.platform,n=e.channel?.channelId;if(!s||!n)return t.json({error:"platform and channelId are required"},400);let i={platform:s,channelId:n,userId:e.channel?.userId,chatId:e.channel?.chatId},r=await this.channelResolveParams.sessionManager.getOrCreate(i),a={id:r.id,createdAt:r.createdAt};return t.json(a)}},{method:"post",path:"/session/:sessionId/prompt",handler:async t=>{let e=t.req.param("sessionId"),s=await t.req.json().catch(()=>({}));if(!e)return t.json({error:"No sessionId provided"},400);let n=this.getChannelResolveParams(),i=e;if(n.sessionManager){let r=n.sessionManager.get(e);if(r)i=r.id;else {let a=n.sessionManager.findByBackendSessionId(e);a&&(y.debug("found gateway session via backendSessionId",{backendSessionId:e,gatewaySessionId:a.id}),i=a.id);}}try{let r=await Bt({...n,sessionId:i,channel:s.channel,userId:s.userId??s.chatId});y.debug("channel resolved for message",{sessionId:e,channel:r.channel,source:r.source,channelInfo:r.channelInfo});let a=utils.Identifier.ascending("message"),c={...r.channelInfo};if(!c.chatId){let p=s.chatId??r.channelInfo.userId;p&&(c.chatId=p,y.debug("filled channelInfo.chatId from request body or session",{chatId:c.chatId}));}if(!c.userId&&c.chatId&&(c.userId=s.userId??c.chatId,y.debug("filled channelInfo.userId from chatId",{userId:c.userId})),!c.chatId)return y.error("channelInfo missing chatId, cannot send message",{sessionId:i,channelInfo:c,body:{userId:s.userId,chatId:s.chatId}}),t.json({error:"channelInfo missing chatId"},400);let d={id:a,sessionId:i,type:"output",content:typeof s.content=="string"?[{type:"text",text:s.content}]:s.content||[],metadata:{channel:c,replyToMessageId:s.replyToMessageId,processorId:s.processorId??"gateway",agent:s.agent??"gateway"},timestamp:Date.now()};if(this.pluginLoaderRef)try{await this.pluginLoaderRef(r.channel,d,{}),y.debug("message sent via pluginLoader",{messageId:a,channel:r.channel});}catch(p){return y.error("failed to send message",{sessionId:i,error:String(p)}),t.json({error:String(p)},500)}else return y.error("no pluginLoader available for sending message",{sessionId:i}),t.json({error:"Plugin loader not available"},500);let g={messageId:a,sessionId:i,createdAt:Date.now(),metadata:{channel:r.channel,channelSource:r.source,channelInfo:r.channelInfo}};return t.status(202),t.json(g)}catch(r){return r instanceof V?(y.warn("channel selection failed",{sessionId:i,error:r.message}),t.json({error:$t(r),code:r.code},400)):(y.error("send message error",{sessionId:i,error:String(r)}),t.json({error:String(r)},500))}}},{method:"get",path:"/subscriptions",handler:t=>{let e=t.req.query("sessionId"),s=t.req.query("subscriberId");y.debug("subscriptions endpoint called",{routerRefExists:!!this.routerRef,agentSyncRefExists:!!this.agentSyncRef,filterSessionId:e,filterSubscriberId:s});let n=[];if(this.routerRef){let r=this.routerRef,a=r.getMessageSubscriptions();y.debug("messageSubscriptions",{size:a.size,entries:Array.from(a.entries())});for(let[c,d]of a.entries()){if(e&&e!=="agent-list"&&c!==e)continue;let g=new Map;for(let p of d){let h=r.getSubscription(p);if(h){if(s&&h.subscriberId!==s)continue;g.set(h.subscriberId,{id:h.subscriberId,subscriptionId:p});}}g.size>0&&n.push({type:"message",sessionId:c,subscriberCount:g.size,subscribers:Array.from(g.values())});}}if(this.agentSyncRef&&!(e&&e!=="agent-list")){let r=this.agentSyncRef.getSubscribers();y.debug("agentSubscribers",{count:r.length,subscribers:r,filterSubscriberId:s});let a=s?r.filter(c=>c===s):r;y.debug("filteredAgents",{filteredAgents:a}),a.length>0&&n.push({type:"agent",sessionId:"agent-list",subscriberCount:a.length,subscribers:a.map(c=>({id:c,subscriptionId:`agent_sub_${c}`}))});}let i={subscriptions:n,total:n.length};return y.debug("subscriptions response",{subscriptionsCount:n.length,subscriptions:n.map(r=>({type:r.type,sessionId:r.sessionId,subscriberCount:r.subscriberCount}))}),t.json(i)}}]}async handleAgentListRequest(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_list_request"){this.sendError(t,"Invalid agent list request");return}let s=N(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentListRequest(s,e.requestId);}async handleAgentSubscribe(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_subscribe"){this.sendError(t,"Invalid agent subscribe request");return}let s=e.clientId,n;if(s){n=s;let i=N(t,this.connections);i&&i!==n&&this.connections.delete(i),this.connections.set(n,t);}else n=N(t,this.connections)??Wt(),N(t,this.connections)||this.connections.set(n,t);await this.agentSyncRef.handleAgentSubscribe(n,e.subscribe);}async handleAgentRegister(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_register"||!e.payload){this.sendError(t,"Invalid agent register request");return}let s=N(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentRegister(s,e.payload);}async handleAgentDeregister(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_deregister"||!e.payload){this.sendError(t,"Invalid agent deregister request");return}let s=N(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentDeregister(s,e.payload);}};function ji(o){return o.toLowerCase().replace(/^\//,"").replace(/@[^\s]+$/,"")}function qi(o){return o.replace(/[-_]/g,"").toLowerCase()}var ae=[{command:"new",description:"Reset session and start a new conversation"},{command:"status",description:"Show gateway and channel status"},{command:"commands",description:"Show available commands"}],A=class{constructor(){chunk6C5TBG7Z_cjs.a(this,"version","1.0.0");chunk6C5TBG7Z_cjs.a(this,"log");chunk6C5TBG7Z_cjs.a(this,"config",null);chunk6C5TBG7Z_cjs.a(this,"messageHandler",null);chunk6C5TBG7Z_cjs.a(this,"_status","stopped");chunk6C5TBG7Z_cjs.a(this,"lastActivity",0);chunk6C5TBG7Z_cjs.a(this,"startPromise",null);chunk6C5TBG7Z_cjs.a(this,"stopPromise",null);}initLog(){this.log=utils.Log.create({service:`channel:${this.platform}`});}async start(t,e){if(this.startPromise)return this.log.warn("plugin start already in progress"),this.startPromise;if(this._status==="running"){this.log.warn("plugin is already running");return}this.startPromise=this.doStartInternal(t,e);try{await this.startPromise;}finally{this.startPromise=null;}}async doStartInternal(t,e){this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=t,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(s){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(s)}),s}}async stop(){if(this.stopPromise)return this.log.warn("plugin stop already in progress"),this.stopPromise;if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}this.stopPromise=this.doStopInternal();try{await this.stopPromise;}finally{this.stopPromise=null;}}async doStopInternal(){this.log.info("stopping channel plugin",{id:this.id}),this._status="stopping";try{await this.doStop(),this._status="stopped",this.log.info("channel plugin stopped",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(t)}),t}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(t){return {healthy:false,lastCheck:Date.now(),error:t instanceof Error?t.message:String(t)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}getCapabilities(){return {supportsText:true,supportsMedia:false,supportsReply:false,supportsThread:false,supportsEdit:false,supportsDelete:false,supportsTyping:false,supportsBatchSend:false,supportsMarkdown:false,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,supportsSlashCommands:false,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:4096,maxMediaCount:1}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}extractText(t){return t.content.filter(e=>e.type==="text").map(e=>e.text??"").join(`
|
|
10
|
+
`).trim()}getSessionId(){return this.sessionId}resetSession(){this.sessionId=void 0;}async stop(){this.bridgeStarted&&(await this.eventBridge.stop(),this.bridgeStarted=false,this.sessionId=void 0);}};var ls=utils.Log.create({service:"gateway:interfaces"}),O;function so(o){O=o,o?ls.debug("Agent adapter registered",{hasSubAgentRunner:!!o.subAgentRunner}):ls.debug("Agent adapter cleared");}function no(){return O}function ge(){return O!==void 0}function Q(){if(!O)throw new Error("Agent adapter not set. Call setAgentAdapter() before using Gateway.");return O}var Bn={Path:{home:process.env.HOME||process.env.USERPROFILE||"",data:".easbot",cache:".easbot/cache",config:".easbot",state:".easbot/state",log:".easbot/log",bin:".easbot/bin"}},On={directory:process.cwd(),worktree:process.cwd()};function w(){return O?O.global:Bn}function Nt(){return O?O.instance:On}var Dt=null;function hs(o){Dt=o;}async function mt(){return Dt?Dt():null}function $n(){if(!O?.sdk)throw new Error("SDK not available. Agent adapter is not set or has no SDK.");return O.sdk}function ms(o){let t=$n();return new Ie(t,o)}var z=utils.Log.create({service:"gateway:config"}),yt={enabled:true,port:8080,hostname:"localhost",path:"",maxConnections:1e3,connectionTimeout:36e5,heartbeatInterval:3e4,sessionExpireMs:36e5,cors:true,mdns:false,mdnsDomain:"gateway.easbot.local",https:{enabled:false,cert:"",key:"",certPath:void 0,keyPath:void 0,ca:void 0,forceRedirect:false,httpPort:80}},jn={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0},qn={maxLength:1e4,concurrency:100,batchSize:10,batchTimeout:100,priorityLevels:4},Kn={failureThreshold:5,successThreshold:3,timeout:3e4,halfOpenDuration:15e3},Vn={heartbeatInterval:6e4,heartbeatTimeout:3e5,heartbeatCheckInterval:3e5,autoDeregisterTimeout:6e5,maxAgents:100,maxRegistrations:1e3},Jn={sessionTimeout:18e5,resumeGracePeriod:3e5,maxSessions:1e3},Qn={enabled:true,botToken:"",maxConnections:100,timeout:3e4,polling:{enabled:true,timeout:30}},Xn={enabled:true,botToken:"",maxConnections:100,timeout:3e4},Yn={enabled:true,appId:"",appSecret:"",maxConnections:100,timeout:3e4},Zn={enabled:true,mode:"official",appId:"",appSecret:"",maxConnections:100,timeout:3e4},ei={enabled:true,path:"/ws",heartbeatInterval:6e4,connectionTimeout:36e5,maxConnections:1e3,cors:true},ti={enabled:true,serviceUrl:"https://chat.signal.org",phoneNumber:"",maxConnections:100,timeout:3e4},si={enabled:true,relays:[],maxConnections:100,timeout:3e4},Ae,Pe=null;async function fs(o){try{if(!te.existsSync(o))return null;let t=await $__namespace.default.readFile(o,"utf-8");t=t.replace(/\{env:([^}]+)\}/g,(r,a)=>{let c=process.env[a];return c===void 0?(z.debug("Environment variable not found",{varName:a,file:o}),""):c});let e=t,s=!1,n=!1,i=[];for(let r=0;r<t.length;r++){let a=t[r];if(n){i.push(a),n=!1;continue}if(a==="\\"){i.push(a),n=!0;continue}if(a==='"'){s=!s,i.push(a);continue}if(!s&&a==="/"&&t[r+1]==="/"){for(;r<t.length&&t[r]!==`
|
|
11
|
+
`&&t[r]!=="\r";)r++;continue}if(!s&&a==="/"&&t[r+1]==="*"){for(r+=2;r<t.length-1;){if(t[r]==="*"&&t[r+1]==="/"){r+=2;break}r++;}continue}i.push(a);}return e=i.join("").trim(),e?JSON.parse(e):null}catch(t){return z.debug("Failed to load config file",{file:o,error:String(t)}),null}}function ft(o,t){let e={...o,...t};return (o.server||t.server)&&(e.server={...o.server,...t.server}),(o.channels||t.channels)&&(e.channels={...o.channels,...t.channels}),e}async function ni(){let o=w(),t=Nt(),e=[],s=ue__namespace.default.join(o.Path.config);e.push(s),e.push(t.directory);try{let{Filesystem:i}=await import('@easbot/utils'),r=await Array.fromAsync(i.up({targets:[".easbot"],start:t.directory,stop:t.worktree}));e.push(...r);}catch{z.debug("Filesystem utils not available, using basic directories");}let n=process.env.EASBOT_CONFIG_DIR;return n&&(e.push(n),z.debug("Using EASBOT_CONFIG_DIR",{path:n})),[...new Set(e)]}async function ii(o){let t=["gateway.json"],e={};for(let s of t){let n=ue__namespace.default.join(o,s),i=await fs(n);if(i)if("gateway"in i&&i.gateway){let r=i.gateway,a={};"enabled"in r&&(a.enabled=r.enabled),"port"in r&&(a.port=r.port),"hostname"in r&&(a.hostname=r.hostname),"path"in r&&(a.path=r.path),"https"in r&&(a.https=r.https),e=ft(e,{server:a,channels:r.channels}),z.debug("Loaded gateway config from file",{file:n});}else "gateway"in i||(e=ft(e,i),z.debug("Loaded gateway config from file (direct format)",{file:n}));}return e}async function ri(o){let t=["easbot.json"];for(let e of t){let s=ue__namespace.default.join(o,e),n=await fs(s);if(n?.gateway)return z.debug("Loaded gateway config from easbot.json",{file:s}),n.gateway}return {}}function ai(){return Ae||(Ae=async()=>{let o=await ni(),t={};for(let s of o){let n=await ii(s);t=ft(t,n);let i=await ri(s);t=ft(t,i);}let e=Rt(t);return Pe=e,z.info("Gateway config loaded",{directories:o.length,port:e.server?.port,logLevel:e.logLevel}),{config:e,directories:o}}),Ae}async function k(){return ai()()}async function ds(o){return o&&(Ae=void 0,Pe=null),(await k()).config}function gs(){return Pe}function us(){return Pe!==null}function oi(){Ae=void 0,Pe=null,z.debug("Config cache cleared");}function ci(){return Nt().directory}async function li(){let{config:o}=await k();return gt.parse({...yt,...o.server})}async function di(o){let{config:t}=await k(),e=t.channels?.[o],n={telegram:Ze.parse(Qn),slack:et.parse(Xn),feishu:tt.parse(Yn),wechat:st.parse(Zn),webchat:nt.parse(ei),signal:it.parse(ti),nostr:rt.parse(si)}[o];if(!n)throw new Error(`Unknown channel type: ${o}`);return {...n,...e}}async function gi(){let{config:o}=await k();return at.parse({...jn,...o.connectionPool})}async function ui(){let{config:o}=await k();return ot.parse({...qn,...o.messageQueue})}async function pi(){let{config:o}=await k();return ct.parse({...Kn,...o.circuitBreaker})}async function hi(){let{config:o}=await k();return lt.parse({...Vn,...o.agentRegistry})}async function mi(){let{config:o}=await k();return dt.parse({...Jn,...o.session})}async function fi(){let{config:o}=await k();if(o.client)return ut.parse(o.client)}async function yi(){let{config:o}=await k();if(!(o.client?.autoRegister??true))return;let e=o.server,s=e?.hostname??"localhost",n=e?.port??8080,i=e?.path||"/acp";return `ws://${s}:${n}${i}`}async function bi(){let{config:o}=await k();return o.server?.https}async function Si(){let{config:o}=await k();return o.server?.auth}async function Ci(){let{config:o}=await k();return o.cluster}async function wi(){let{config:o}=await k();return o.defaultAgent}async function ps(){let{config:o}=await k();return o.logLevel??"INFO"}var Gt=yt,xe={maxConnections:1e3,connectionTimeout:36e5};var vi={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};var bt={heartbeatInterval:6e4,heartbeatTimeout:3e5,heartbeatCheckInterval:3e5,autoDeregisterTimeout:6e5,maxAgents:100,maxRegistrations:1e3};var St={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};var Ii={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var j=class o extends Error{constructor(e,s){super(e);chunk6C5TBG7Z_cjs.a(this,"code");chunk6C5TBG7Z_cjs.a(this,"recoverable");chunk6C5TBG7Z_cjs.a(this,"details");chunk6C5TBG7Z_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,o);}toJSON(){return {name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,details:this.details,cause:this.cause?.message,stack:this.stack}}static isRecoverable(e){if(e instanceof o)return e.recoverable;let s=e.code;return ["ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH"].includes(s??"")}};function f(o,t,e,s=true){return new j(e,{code:t,recoverable:s,details:{channelId:o}})}var Ct=class{constructor(t,e){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:router"}));chunk6C5TBG7Z_cjs.a(this,"subscribers",new Map);chunk6C5TBG7Z_cjs.a(this,"subscriptions",new Map);chunk6C5TBG7Z_cjs.a(this,"messageSubscriptions",new Map);chunk6C5TBG7Z_cjs.a(this,"channelPlugins",new Map);chunk6C5TBG7Z_cjs.a(this,"cancelHandlers",new Set);chunk6C5TBG7Z_cjs.a(this,"processingMessages",new Map);chunk6C5TBG7Z_cjs.a(this,"hookRegistry",null);chunk6C5TBG7Z_cjs.a(this,"sessionManager",null);this.hookRegistry=t??null,this.sessionManager=e??null;}setSessionManager(t){this.sessionManager=t;}async triggerHook(t,e,s){if(this.hookRegistry)try{await this.hookRegistry.triggerEvent(t,e,s);}catch{}}async triggerBeforeSend(t,e,s){if(this.sessionManager)try{await this.sessionManager.bindBackendSession(t.sessionId,s.sessionId);}catch{}await this.triggerHook("gateway.message.process",{messageId:t.id,sessionId:t.sessionId,processorId:e,processType:"subscription",agent:e,timestamp:Date.now()});}onCancel(t){this.cancelHandlers.add(t);}offCancel(t){this.cancelHandlers.delete(t);}async emitCancel(t){for(let e of this.cancelHandlers)try{await e(t);}catch(s){this.log.error("cancel handler error",{error:String(s)});}}selectSubscriber(t){let e=this.messageSubscriptions.get(t.sessionId);if(!e||e.size===0){if(this.sessionManager){let r=this.sessionManager.get(t.sessionId);r?.backendSessionId&&(e=this.messageSubscriptions.get(r.backendSessionId));}if(!e||e.size===0){for(let[,r]of this.messageSubscriptions)if(r.size>0){e=r;break}}}if(!e||e.size===0)return null;let s=e.values().next().value;if(!s)return null;let n=this.subscriptions.get(s);if(!n)return null;let i=this.subscribers.get(n.subscriberId);return i?{subscription:n,subscriber:i}:null}async route(t){let e=this.selectSubscriber(t);if(!e)return {success:true,dispatched:false,dispatchedToSubAgent:false};let{subscription:s,subscriber:n}=e;if(t.type==="input"){let i=this.processingMessages.get(t.id);if(i&&i!==n.id)return {success:true,dispatched:false,dispatchedToSubAgent:false};this.processingMessages.set(t.id,n.id);}try{return await this.triggerBeforeSend(t,n.id,{sessionId:s.sessionId,subscriberId:s.subscriberId}),await n.connection.send(t),n.lastActiveAt=Date.now(),{success:!0,dispatched:!0,dispatchedToSubAgent:!1}}catch(i){return this.log.warn("failed to send message to subscriber",{subscriberId:n.id,error:String(i)}),t.type==="input"&&this.processingMessages.delete(t.id),{success:false,dispatched:false,dispatchedToSubAgent:false,error:i instanceof Error?i.message:String(i)}}}async completeMessage(t,e,s,n="completed"){this.processingMessages.delete(e),await this.emitCancel({sessionId:t,messageId:e,processedBy:s,reason:n,timestamp:Date.now()});}async subscribe(t,e){let s=Et(e.id,t);if(this.subscriptions.has(s))return this.subscriptions.get(s);for(let[i,r]of this.subscriptions.entries())r.subscriberId===e.id&&r.sessionId===t&&i!==s&&await this.unsubscribe(i);let n={id:s,subscriberId:e.id,sessionId:t,createdAt:Date.now()};return this.subscribers.set(e.id,e),this.subscriptions.set(s,n),this.messageSubscriptions.has(t)||this.messageSubscriptions.set(t,new Set),this.messageSubscriptions.get(t).add(s),n}async unsubscribe(t){let e=this.subscriptions.get(t);if(!e){this.log.warn("subscription not found",{subscriptionId:t});return}this.subscriptions.delete(t);let s=this.messageSubscriptions.get(e.sessionId);s&&(s.delete(t),s.size===0&&this.messageSubscriptions.delete(e.sessionId));}async unsubscribeAll(t){for(let[e,s]of this.subscriptions.entries())s.subscriberId===t&&await this.unsubscribe(e);this.subscribers.delete(t);}registerChannel(t){this.channelPlugins.set(t.id,t),this.log.info("channel plugin registered",{id:t.id,platform:t.platform});}unregisterChannel(t){this.channelPlugins.delete(t),this.log.info("channel plugin unregistered",{id:t});}getSubscriber(t){return this.subscribers.get(t)}getSubscription(t){return this.subscriptions.get(t)}getMessageSubscriptions(){return this.messageSubscriptions}getSubscriberCount(t){return this.messageSubscriptions.get(t)?.size??0}getStats(){return {subscribers:this.subscribers.size,subscriptions:this.subscriptions.size,sessions:this.messageSubscriptions.size}}async shutdown(){this.processingMessages.clear(),this.subscribers.clear(),this.subscriptions.clear(),this.messageSubscriptions.clear(),this.channelPlugins.clear(),this.cancelHandlers.clear(),this.log.info("router shutdown");}};var Me=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:message-store"}));chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"messages",new Map);chunk6C5TBG7Z_cjs.a(this,"sessionMessages",new Map);chunk6C5TBG7Z_cjs.a(this,"cleanupTimer",null);chunk6C5TBG7Z_cjs.a(this,"accessOrder",[]);chunk6C5TBG7Z_cjs.a(this,"storagePath");chunk6C5TBG7Z_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=ue__namespace.join(this.storagePath,s.name),i=await $__namespace.readdir(n);for(let r of i)if(r.endsWith(".json"))try{let a=ue__namespace.join(n,r),c=await $__namespace.readFile(a,"utf-8"),d=JSON.parse(c);d.status!=="completed"&&d.status!=="delivered"&&(this.messages.has(d.message.id)||(this.messages.set(d.message.id,d),this.addToSessionMessages(d.message.sessionId,d.message.id),t++));}catch(a){this.log.debug("failed to load message file",{file:r,error:String(a)});}}t>0&&this.log.debug("loaded messages from disk",{count:t});}catch(e){this.log.warn("failed to load messages from disk",{error:String(e)});}return t}addToSessionMessages(t,e){this.sessionMessages.has(t)||this.sessionMessages.set(t,new Set),this.sessionMessages.get(t).add(e);}async ensureDir(t){try{await $__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 ue__namespace.join(this.storagePath,`${this.sanitizeFileName(t)}.json`)}getSessionDir(t){return ue__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=ue__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.debug("LRU eviction completed",{evicted:e,remaining:this.messages.size});}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e>-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t);}deleteMessage(t){let e=this.messages.get(t);if(e){let s=this.sessionMessages.get(e.message.sessionId);s&&(s.delete(t),s.size===0&&this.sessionMessages.delete(e.message.sessionId)),this.messages.delete(t);let n=this.accessOrder.indexOf(t);n>-1&&this.accessOrder.splice(n,1);}}getStats(){let t={total:this.messages.size,pending:0,processing:0,completed:0,failed:0,cancelled:0,delivered:0,read:0,sessions:this.sessionMessages.size};for(let e of this.messages.values()){let s=e.status;s in t&&s!=="total"&&s!=="sessions"&&t[s]++;}return t}async close(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.messages.clear(),this.sessionMessages.clear(),this.accessOrder=[],this.log.info("MessageStore closed");}};var se=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:session-store"}));chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"sessions",new Map);chunk6C5TBG7Z_cjs.a(this,"channelSessions",new Map);chunk6C5TBG7Z_cjs.a(this,"autoSaveTimer",null);chunk6C5TBG7Z_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 te__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(!te__namespace.existsSync(t)){this.log.debug("no saved sessions found");return}let e=await te__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 ue__namespace.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){te__namespace.existsSync(this.config.storagePath)||await te__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 ki="./data/gateway",Ti="contacts",_i="index.json",ie=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:contact-store"}));chunk6C5TBG7Z_cjs.a(this,"baseDir");chunk6C5TBG7Z_cjs.a(this,"contactDir");chunk6C5TBG7Z_cjs.a(this,"indexPath");chunk6C5TBG7Z_cjs.a(this,"index");chunk6C5TBG7Z_cjs.a(this,"indexFileMap");chunk6C5TBG7Z_cjs.a(this,"dirty",false);chunk6C5TBG7Z_cjs.a(this,"saveTimer",null);chunk6C5TBG7Z_cjs.a(this,"SAVE_DEBOUNCE_MS",1e3);this.baseDir=t.baseDir??ki,this.contactDir=ue__namespace.join(this.baseDir,Ti),this.indexPath=ue__namespace.join(this.contactDir,_i),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=Xe(t);if(e){let s=this.getFilePath(e.platform,e.stableId);this.indexFileMap[t]=s;}}}getFilePath(t,e){let s=this.sanitizeFilename(e);return ue__namespace.join(this.contactDir,t,`${s}.json`)}sanitizeFilename(t){return t.replace(/[/\\:*?"<>|]/g,"_")}getPlatformDir(t){return ue__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(ue__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=_t(t);return this.save(e)}async getOrCreate(t,e,s){let n=await this.findByPlatformId(t,e);return n||this.create({platform:t,stableId:e,profile:s})}async findByUid(t){let e=Xe(t);return e?this.findByPlatformId(e.platform,e.stableId):null}async findByPlatformId(t,e){let s=Qe(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 c of r){let d=await this.findByUid(c);d&&a.push(d);}return {contacts:a,total:i,hasMore:s+e<i}}async findByUsername(t){let e=t.toLowerCase(),s=this.index.byUsername[e];return s?this.findByUid(s):null}async findByEmail(t){let e=t.toLowerCase(),s=this.index.byEmail[e];return s?this.findByUid(s):null}async findByPhone(t){let e=t.replace(/\s/g,""),s=this.index.byPhone[e];return s?this.findByUid(s):null}async search(t){if(t.platform){let c=await this.listByPlatform(t.platform,t.limit,t.offset),d=c.contacts;if(t.username){let g=t.username.toLowerCase();d=d.filter(p=>p.profile.username?.toLowerCase().includes(g));}if(t.email){let g=t.email.toLowerCase();d=d.filter(p=>p.profile.email?.toLowerCase().includes(g));}if(t.phone){let g=t.phone.replace(/\s/g,"");d=d.filter(p=>p.profile.phone?.replace(/\s/g,"").includes(g));}return {contacts:d,total:c.total,hasMore:c.hasMore}}let e=[];for(let c of Object.keys(this.index.byPlatform)){let d=await this.listByPlatform(c,1e3,0);e.push(...d.contacts);}let s=e;if(t.username){let c=t.username.toLowerCase();s=s.filter(d=>d.profile.username?.toLowerCase().includes(c));}if(t.email){let c=t.email.toLowerCase();s=s.filter(d=>d.profile.email?.toLowerCase().includes(c));}if(t.phone){let c=t.phone.replace(/\s/g,"");s=s.filter(d=>d.profile.phone?.replace(/\s/g,"").includes(c));}let n=s.length,i=t.limit??100,r=t.offset??0;return {contacts:s.slice(r,r+i),total:n,hasMore:r+i<n}}async count(t){return t?(this.index.byPlatform[t]||[]).length:Object.keys(this.index.byUid).length}async exists(t){return await this.findByUid(t)!==null}async addAlias(t,e,s){let n=await this.findByUid(t);if(!n)return null;let i={...n,aliases:{...n.aliases,[e]:{...n.aliases[e],...s}},lastSeenAt:Date.now()};return this.save(i)}async close(){this.saveTimer&&clearTimeout(this.saveTimer),this.dirty&&await this.doSaveIndex(),this.log.info("contact store closed");}updateSearchIndices(t){let{uid:e,profile:s}=t;s.username&&(this.index.byUsername[s.username.toLowerCase()]=e),s.email&&(this.index.byEmail[s.email.toLowerCase()]=e),s.phone&&(this.index.byPhone[s.phone.replace(/\s/g,"")]=e);}removeFromSearchIndices(t){let{uid:e,profile:s}=t;if(s.username){let n=s.username.toLowerCase();this.index.byUsername[n]===e&&delete this.index.byUsername[n];}if(s.email){let n=s.email.toLowerCase();this.index.byEmail[n]===e&&delete this.index.byEmail[n];}if(s.phone){let n=s.phone.replace(/\s/g,"");this.index.byPhone[n]===e&&delete this.index.byPhone[n];}}};var Ut=class{constructor(t){chunk6C5TBG7Z_cjs.a(this,"cache",new Map);chunk6C5TBG7Z_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}},ke=class{constructor(t,e={}){chunk6C5TBG7Z_cjs.a(this,"store",t);chunk6C5TBG7Z_cjs.a(this,"cache");chunk6C5TBG7Z_cjs.a(this,"usernameIndex");chunk6C5TBG7Z_cjs.a(this,"emailIndex");chunk6C5TBG7Z_cjs.a(this,"phoneIndex");chunk6C5TBG7Z_cjs.a(this,"platformIndex");chunk6C5TBG7Z_cjs.a(this,"initialized",false);this.cache=new Ut(e.cacheSize??1e3),this.usernameIndex=new Map,this.emailIndex=new Map,this.phoneIndex=new Map,this.platformIndex=new Map;}async initialize(){this.initialized||("initialize"in this.store&&typeof this.store.initialize=="function"&&await this.store.initialize(),await this.warmCache(),this.initialized=true);}async warmCache(){try{let t=["telegram","discord","slack","feishu","wechat","webchat","signal","nostr"];for(let e of t)try{let s=await this.store.listByPlatform(e,1e3,0);for(let n of s.contacts)this.cacheContact(n);}catch{}}catch{}}cacheContact(t){let{uid:e,profile:s}=t;this.cache.set(e,t),s.username&&this.usernameIndex.set(s.username.toLowerCase(),e),s.email&&this.emailIndex.set(s.email.toLowerCase(),e),s.phone&&this.phoneIndex.set(s.phone.replace(/\s/g,""),e),this.platformIndex.has(t.platform)||this.platformIndex.set(t.platform,new Set),this.platformIndex.get(t.platform).add(e);}invalidateContact(t){let{uid:e,profile:s}=t;if(this.cache.delete(e),s.username){let i=s.username.toLowerCase();this.usernameIndex.get(i)===e&&this.usernameIndex.delete(i);}if(s.email){let i=s.email.toLowerCase();this.emailIndex.get(i)===e&&this.emailIndex.delete(i);}if(s.phone){let i=s.phone.replace(/\s/g,"");this.phoneIndex.get(i)===e&&this.phoneIndex.delete(i);}let n=this.platformIndex.get(t.platform);n&&n.delete(e);}async save(t){this.invalidateContact(t);let e=await this.store.save(t);return this.cacheContact(e),e}async create(t){let e=await this.store.create(t);return this.cacheContact(e),e}async getOrCreate(t,e,s){let n=this.cache.get(`${t}:${e}`);if(n)return n;let i=await this.store.getOrCreate(t,e,s);return this.cacheContact(i),i}async findByUid(t){let e=this.cache.get(t);if(e)return e;let s=await this.store.findByUid(t);return s&&this.cacheContact(s),s}async findByPlatformId(t,e){return this.findByUid(`${t}:${e}`)}async update(t,e){let s=await this.cache.get(t);s&&this.invalidateContact(s);let n=await this.store.update(t,e);return n&&this.cacheContact(n),n}async touch(t){await this.store.touch(t);}async delete(t){let e=await this.cache.get(t);return e&&this.invalidateContact(e),this.store.delete(t)}async listByPlatform(t,e=100,s=0){return this.store.listByPlatform(t,e,s)}async findByUsername(t){let e=t.toLowerCase(),s=this.usernameIndex.get(e);return s?this.findByUid(s):this.store.findByUsername(t)}async findByEmail(t){let e=t.toLowerCase(),s=this.emailIndex.get(e);return s?this.findByUid(s):this.store.findByEmail(t)}async findByPhone(t){let e=t.replace(/\s/g,""),s=this.phoneIndex.get(e);return s?this.findByUid(s):this.store.findByPhone(t)}async search(t){return this.store.search(t)}async count(t){return t?this.platformIndex.get(t)?.size??0:this.cache.size}async exists(t){return this.cache.has(t)?true:this.store.exists(t)}async addAlias(t,e,s){let n=await this.store.addAlias(t,e,s);return n&&(this.invalidateContact(n),this.cacheContact(n)),n}async close(){this.cache.clear(),this.usernameIndex.clear(),this.emailIndex.clear(),this.phoneIndex.clear(),this.platformIndex.clear(),"close"in this.store&&typeof this.store.close=="function"&&await this.store.close();}};var H=utils.Log.create({service:"gateway:storage:agent-registry"}),Te=class{constructor(t){chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"filePath");chunk6C5TBG7Z_cjs.a(this,"cache",new Map);chunk6C5TBG7Z_cjs.a(this,"initialized",false);this.config=t,this.filePath=ue__namespace.join(t.dataDir,"agent-registry.json");}async initialize(){if(!this.initialized)try{await $__namespace.mkdir(this.config.dataDir,{recursive:!0}),this.initialized=!0,H.debug("Agent registry store initialized",{dataDir:this.config.dataDir});}catch(t){throw H.error("Failed to initialize agent registry store",{dataDir:this.config.dataDir,error:String(t)}),t}}async loadFromDisk(){await this.initialize();try{let t=await $__namespace.readFile(this.filePath,"utf-8"),e=JSON.parse(t),s=new Map;for(let n of e)n.agent?.id&&s.set(n.agent.id,n);return H.debug("Agent registry loaded from disk",{count:s.size}),s}catch(t){return t.code==="ENOENT"?(H.debug("Agent registry file not found, starting fresh"),new Map):(H.error("Failed to load agent registry from disk",{error:String(t)}),new Map)}}async saveToDisk(){await this.initialize();try{let t=Array.from(this.cache.values());await $__namespace.writeFile(this.filePath,JSON.stringify(t,null,2),"utf-8"),H.debug("Agent registry saved to disk",{count:this.cache.size});}catch(t){throw H.error("Failed to save agent registry to disk",{error:String(t)}),t}}async loadAll(){let t=await this.loadFromDisk();return this.cache=t,Array.from(this.cache.values()).map(e=>e.agent)}async save(t){await this.initialize();let e={agent:t,storedAt:Date.now()};this.cache.set(t.id,e),await this.saveToDisk(),H.debug("Agent registration saved",{agentId:t.id});}async saveAll(t){await this.initialize();for(let e of t){let s={agent:e,storedAt:Date.now()};this.cache.set(e.id,s);}await this.saveToDisk(),H.debug("All agent registrations saved",{count:t.length});}async delete(t){await this.initialize(),this.cache.has(t)&&(this.cache.delete(t),await this.saveToDisk(),H.debug("Agent registration deleted",{agentId:t}));}getFilePath(){return this.filePath}};var _e=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:session"}));chunk6C5TBG7Z_cjs.a(this,"sessionStore");chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_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 se({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=Ve(t),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),n):(n={id:s,channel:t,backendSessionId:null,subscribers:new Set,state:Je(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(n),n)}get(t){return this.sessionStore.get(t)}async closeSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.state.status="closed",await this.sessionStore.delete(t);}async closeById(t){return this.closeSession(t)}async bindBackendSession(t,e){let s=this.sessionStore.get(t);if(!s)throw new Error(`Session not found: ${t}`);s.backendSessionId=e,await this.sessionStore.set(s);}async unbindBackendSession(t){let e=this.sessionStore.get(t);if(!e){this.log.warn("session not found",{sessionId:t});return}e.backendSessionId=null,await this.sessionStore.set(e);}findByBackendSessionId(t){for(let e of this.sessionStore.getAll())if(e.backendSessionId===t)return e}getState(t){return this.sessionStore.get(t)?.state}async incrementMessageCountOrCreate(t,e){let s=this.sessionStore.get(t);if(!s){if(!e)throw new Error(`Cannot create session: channelInfo is required when session "${t}" does not exist`);let n=Ve(e);n!==t&&this.log.warn("sessionId mismatch, using correct sessionId from channelInfo",{providedSessionId:t,correctSessionId:n}),s={id:n,channel:e,backendSessionId:null,subscribers:new Set,state:Je(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(s),this.log.debug("session auto-created from message",{sessionId:n,platform:e.platform,channelId:e.channelId,chatId:e.chatId,userId:e.userId});}return s.state.messageCount++,s.state.lastMessageAt=Date.now(),s.lastActiveAt=Date.now(),await this.sessionStore.set(s),s}async incrementMessageCount(t){let e=this.sessionStore.get(t);e&&(e.state.messageCount++,e.state.lastMessageAt=Date.now(),e.lastActiveAt=Date.now(),await this.sessionStore.set(e));}async addSubscriber(t,e){let s=this.sessionStore.get(t);if(!s){this.log.warn("session not found",{sessionId:t});return}s.subscribers.add(e),await this.sessionStore.set(s);}async removeSubscriber(t,e){let s=this.sessionStore.get(t);s&&(s.subscribers.delete(e),await this.sessionStore.set(s));}query(t){let e=this.sessionStore.getAll();return t.platform&&(e=e.filter(s=>s.channel.platform===t.platform)),t.channelId&&(e=e.filter(s=>s.channel.channelId===t.channelId)),t.userId&&(e=e.filter(s=>s.channel.userId===t.userId)),t.status&&(e=e.filter(s=>s.state.status===t.status)),e}getSessionsByChannel(t){return this.sessionStore.getByChannel(t)}getAllSessions(){return this.sessionStore.getAll()}getSessionCount(){return this.sessionStore.size()}async cleanupIdleSessions(t){let e=Date.now(),s=[];for(let n of this.sessionStore.getAll())n.state.status==="idle"&&e-n.lastActiveAt>t&&s.push(n.id);for(let n of s)await this.closeSession(n);return s.length}async save(){}getStats(){return this.sessionStore.getStats()}};var Ee=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:plugin-loader"}));chunk6C5TBG7Z_cjs.a(this,"plugins",new Map);chunk6C5TBG7Z_cjs.a(this,"messageHandler",null);chunk6C5TBG7Z_cjs.a(this,"healthCheckTimer",null);chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_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;}updateSessionHandler(t){this.messageHandler&&(this.messageHandler.session=t,this.log.debug("session handler updated"));}async register(t,e){if(this.plugins.has(t.id)){this.log.warn("plugin already registered",{id:t.id});return}this.plugins.set(t.id,{plugin:t,config:e,started:false,reconnectAttempts:0}),this.log.info("plugin registered",{id:t.id,platform:t.platform,name:t.name});}async unregister(t){let e=this.plugins.get(t);if(!e){this.log.warn("plugin not found",{id:t});return}this.cancelReconnect(t),e.started&&await this.stop(t),this.plugins.delete(t),this.log.info("plugin unregistered",{id:t});}async start(t){let e=this.plugins.get(t);if(!e)throw new j(`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 j("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 V=class extends Error{constructor(e,s,n){super(e);chunk6C5TBG7Z_cjs.a(this,"code",s);chunk6C5TBG7Z_cjs.a(this,"configuredChannels",n);this.name="ChannelSelectionError";}},K=utils.Log.create({service:"gateway:channel-selection"});function he(o){if(!(!o||typeof o!="string"))return o.toLowerCase().trim()}async function Ot(o){let{channel:t,sessionId:e,userId:s,defaultChannel:n,fallbackChannels:i,sessionManager:r,pluginLoader:a,contactStore:c}=o,d=he(t);if(d){let b=Ft(d,a);if(b){if(e){let S=Bt(e,r);if(S){if(S.channelInfo.chatId||S.channelInfo.userId)return K.debug("enriching explicit channel with session info",{sessionId:e,chatId:S.channelInfo.chatId,userId:S.channelInfo.userId}),{...b,channelInfo:{...b.channelInfo,chatId:S.channelInfo.chatId,userId:S.channelInfo.userId}}}else if(s&&r){K.debug("session not found, creating new session for private chat",{userId:s});let T=s,_={platform:b.channelInfo.platform,channelId:b.channel,chatId:T,userId:s};try{let M=await r.getOrCreate(_);return K.debug("auto-created session for private chat",{sessionId:M.id,chatId:T,userId:s}),{channel:b.channel,source:"session-bound",channelInfo:M.channel}}catch(M){K.warn("failed to auto-create session, using explicit channel info",{userId:s,error:String(M)});}}}if(s&&c){let S=await Li(d,s,c,a);if(S)return S}return b}if(e){let S=Bt(e,r);if(S){if((!S.channelInfo.chatId||!S.channelInfo.userId)&&S.channelInfo.platform!=="api"){let _=Ui(S.channelInfo.platform,r);if(_)return K.debug("session missing chatId/userId, using session with complete info",{originalSessionId:e,newSessionId:_.channelInfo.chatId}),_}return S}}throw new V(`Channel \u4E0D\u53EF\u7528\u6216\u672A\u914D\u7F6E: ${d}`,"CHANNEL_UNAVAILABLE",[])}if(e){let b=Bt(e,r);if(b)return b}if(s&&c){let b=await Gi(s,c,a);if(b)return b}let g=$t(a);if(g.length===0)throw new V("\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684 Channel\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F\u3002\u8BF7\u81F3\u5C11\u914D\u7F6E\u4E00\u4E2A Channel\u3002","NO_CHANNEL",[]);let p=he(n);if(p){let b=Ft(p,a);if(b)return K.debug("using default channel",{channel:p}),{...b,source:"default"};K.warn("default channel unavailable",{channel:p});}if(g.length===1){let b=g[0],S=a?.getPlugin(b);return {channel:b,source:"single-configured",channelInfo:{platform:S?.platform,channelId:b}}}let h=(i??[]).map(he).filter(b=>b!==void 0);for(let b of h){let S=Ft(b,a);if(S)return K.debug("using fallback channel",{channel:b}),{...S,source:"fallback"};K.debug("fallback channel unavailable, trying next",{channel:b});}throw p?new V(`\u914D\u7F6E\u7684\u9ED8\u8BA4 Channel \u4E0D\u53EF\u7528: ${p}`,"CHANNEL_UNAVAILABLE",g):new V(`\u9700\u8981\u660E\u786E\u6307\u5B9A Channel\uFF08\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF09: ${g.join(", ")}\u3002\u8BF7\u901A\u8FC7 channel \u53C2\u6570\u6307\u5B9A\u8981\u4F7F\u7528\u7684 Channel\uFF0C\u6216\u5728 gateway.json \u4E2D\u914D\u7F6E defaults.channel\u3002`,"MULTIPLE_CHANNELS",g)}function Ft(o,t){if(!t)return null;let e=t.getPlugin(o);if(e&&t.isRunning(o))return {channel:o,source:"explicit",channelInfo:{platform:e.platform,channelId:o}};let s=he(o);if(!s)return null;let n=t.getAllPlugins();for(let i of n)if(t.isRunning(i.id)&&he(i.platform)===s)return {channel:i.id,source:"explicit",channelInfo:{platform:i.platform,channelId:i.id}};return null}function Bt(o,t){if(!t)return null;let e=t.get(o);return e?{channel:e.channel.channelId,source:"session-bound",channelInfo:e.channel}:null}async function Li(o,t,e,s){let n=s?.getPlugin(o);if(!n)return null;let i=await e.findByPlatformId(n.platform,t);return i?{channel:o,source:"explicit",channelInfo:{platform:n.platform,channelId:o,userId:i.stableId,chatId:i.stableId}}:null}async function Gi(o,t,e){let s=$t(e);if(s.length===0)return null;for(let n of s){let i=e?.getPlugin(n);if(!i)continue;let r=await t.findByPlatformId(i.platform,o);if(r)return {channel:n,source:"single-configured",channelInfo:{platform:i.platform,channelId:n,userId:r.stableId,chatId:r.stableId}}}return null}function $t(o){if(!o)return [];let t=[],e=o.getAllPlugins();for(let s of e)o.isRunning(s.id)&&t.push(s.id);return t}function Wt(o){switch(o.code){case "NO_CHANNEL":return "\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684 Channel\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F\u3002\u8BF7\u5728 gateway.json \u4E2D\u914D\u7F6E\u81F3\u5C11\u4E00\u4E2A Channel\u3002";case "MULTIPLE_CHANNELS":return `\u591A\u4E2A Channel \u5DF2\u914D\u7F6E\uFF0C\u9700\u8981\u660E\u786E\u6307\u5B9A: ${o.configuredChannels?.join(", ")||""}\u3002\u8BF7\u901A\u8FC7 channel \u53C2\u6570\u6307\u5B9A\u8981\u4F7F\u7528\u7684 Channel\uFF0C\u6216\u5728 gateway.json \u4E2D\u914D\u7F6E defaults.channel \u4F5C\u4E3A\u9ED8\u8BA4\u503C\u3002`;case "CHANNEL_UNAVAILABLE":return o.message;case "UNKNOWN_CHANNEL":return `\u672A\u77E5\u7684 Channel: ${o.message}\u3002\u8BF7\u68C0\u67E5 Channel ID \u662F\u5426\u6B63\u786E\u3002`;default:return o.message}}function Ui(o,t){if(!t)return null;let e=t.getAll?.()??[];for(let s of e)if(s.channel.platform===o&&s.channel.chatId&&s.channel.userId)return {channel:s.channel.channelId,source:"session-bound",channelInfo:s.channel};for(let s of e)if(s.channel.platform===o&&s.channel.chatId)return {channel:s.channel.channelId,source:"session-bound",channelInfo:s.channel};return null}var y=utils.Log.create({service:"gateway:websocket-server"});function Ht(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function N(o,t){for(let[e,s]of t.entries())if(s===o)return e;return null}var re=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"server",null);chunk6C5TBG7Z_cjs.a(this,"wss",null);chunk6C5TBG7Z_cjs.a(this,"httpsServer",null);chunk6C5TBG7Z_cjs.a(this,"httpRedirectServer",null);chunk6C5TBG7Z_cjs.a(this,"connections",new Map);chunk6C5TBG7Z_cjs.a(this,"subscriptions",new Map);chunk6C5TBG7Z_cjs.a(this,"clientLastActivity",new Map);chunk6C5TBG7Z_cjs.a(this,"cleanupInterval",null);chunk6C5TBG7Z_cjs.a(this,"heartbeatInterval",null);chunk6C5TBG7Z_cjs.a(this,"startTime",0);chunk6C5TBG7Z_cjs.a(this,"running",false);chunk6C5TBG7Z_cjs.a(this,"channelResolveParams",null);chunk6C5TBG7Z_cjs.a(this,"pluginLoaderRef",null);chunk6C5TBG7Z_cjs.a(this,"agentSyncRef",null);chunk6C5TBG7Z_cjs.a(this,"agentRegistryRef",null);chunk6C5TBG7Z_cjs.a(this,"routerRef",null);chunk6C5TBG7Z_cjs.a(this,"subscribers",new Map);this.config={...Gt,...t};}setChannelResolveDeps(t){this.channelResolveParams=t;}setPluginLoader(t){this.pluginLoaderRef=t;}getGatewayId(){let t=this.config.https?.enabled?"https":"http",e=this.config.hostname||"localhost",s=this.config.port||8080,n=`${t}://${e}:${s}`;return Hi__default.default.createHash("sha256").update(n).digest("hex").substring(0,16)}setAgentSync(t){this.agentSyncRef=t;}setAgentRegistry(t){this.agentRegistryRef=t;}setRouter(t){this.routerRef=t;}getChannelResolveParams(){return this.channelResolveParams?this.channelResolveParams:{}}async start(){if(this.running){y.warn("WebSocket server is already running");return}y.debug("WebSocket server starting",{port:this.config.port,hostname:this.config.hostname,https:this.config.https?.enabled??false}),this.startTime=Date.now();let t={onOpen:(n,i)=>{this.handleConnection(i);},onMessage:async(n,i)=>{try{let r=JSON.parse(n.data.toString());await this.handleMessage(i,r);}catch(r){y.error("Error processing WebSocket message",{error:r.message}),this.sendError(i,r.message);}},onClose:(n,i)=>{this.handleDisconnection(i);},onError:(n,i)=>{y.error("WebSocket error",{error:n.type});}},e=this.config.https?.enabled??false;try{e?await this.startHTTPSServer(t):await this.startHTTPServer(t);}catch(n){throw y.error("WebSocket server start: HTTP/HTTPS server failed",{error:n instanceof Error?n.message:String(n)}),n}this.cleanupInterval=setInterval(()=>this.cleanupInactiveClients(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let s=e?"wss":"ws";y.info("WebSocket server started",{url:`${s}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(t){this.server=utils.createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let e=this.server.raw;e?this.setupWebSocketUpgrade(e,t):y.warn("HTTP server start: raw server is undefined");}async startHTTPSServer(t){let e=this.config.https,s=this.loadSSLCertificates(e);if(!s){y.error("Failed to load SSL certificates, falling back to HTTP"),await this.startHTTPServer(t);return}this.server=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=$i__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,()=>{y.info("HTTPS server started",{port:this.config.port,hostname:this.config.hostname}),i();});}),e.forceRedirect&&e.httpPort&&this.startHTTPRedirectServer(e.httpPort);}loadSSLCertificates(t){try{return t.cert&&t.key?{cert:t.cert,key:t.key}:t.certPath&&t.keyPath?{cert:te__namespace.default.readFileSync(t.certPath),key:te__namespace.default.readFileSync(t.keyPath)}:null}catch(e){return y.error("Failed to load SSL certificates",{error:e.message}),null}}setupWebSocketUpgrade(t,e){this.wss=new ws.WebSocketServer({noServer:true}),t.on("upgrade",(s,n,i)=>{try{let a=new URL(s.url||"/",`http://${s.headers.host}`).pathname,c=this.config.path||"";(a===c||c===""&&(a==="/"||a===""))&&this.wss.handleUpgrade(s,n,i,d=>{e.onOpen?.({type:"open"},d),d.on("message",g=>{e.onMessage?.({data:g},d);}),d.on("close",(g,p)=>{e.onClose?.({code:g,reason:p},d);}),d.on("error",g=>{e.onError?.({type:"error",message:g.message},d);});});}catch{}});}startHTTPRedirectServer(t){this.httpRedirectServer=Wi__default.default.createServer((e,s)=>{let i=`https://${e.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${e.url}`;s.writeHead(301,{Location:i,"Content-Type":"text/plain"}),s.end(`Redirecting to ${i}`);}),this.httpRedirectServer.listen(t,this.config.hostname,()=>{y.info("HTTP redirect server started",{port:t,hostname:this.config.hostname});});}async stop(){if(!this.running){y.warn("WebSocket server is not running");return}y.info("Stopping WebSocket server"),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let[t,e]of this.connections.entries())try{e.close(1e3,"Server shutting down");}catch{}this.connections.clear(),this.subscriptions.clear(),this.subscribers.clear(),this.clientLastActivity.clear(),this.wss&&(this.wss.close(),this.wss=null),this.httpsServer&&(await new Promise(t=>{this.httpsServer.close(()=>t());}),this.httpsServer=null),this.httpRedirectServer&&(await new Promise(t=>{this.httpRedirectServer.close(()=>t());}),this.httpRedirectServer=null),this.server&&(await this.server.stop(),this.server=null),this.running=false,y.info("WebSocket server stopped");}touchClient(t){this.clientLastActivity.set(t,Date.now());let e=this.subscriptions.get(t);e&&(e.lastActivityAt=Date.now());}getConnectionCount(){return this.connections.size}getStartTime(){return this.startTime}getSubscriptionCount(){return this.subscribers.size}getConnectionInfos(){let t=[];for(let[e,s]of this.subscriptions.entries())t.push({clientId:e,state:s.ws.readyState===s.ws.OPEN?"connected":"disconnected",connectedAt:s.connectedAt,lastActivityAt:s.lastActivityAt,authInfo:s.authInfo});return t}isRunning(){return this.running}handleConnection(t){if(this.connections.size>=(this.config.maxConnections??xe.maxConnections)){y.warn("Maximum connections reached, rejecting new connection"),t.close(1013,"Maximum connections reached");return}let e=Ht();this.connections.set(e,t),this.subscriptions.set(e,{clientId:e,ws:t,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()}),y.debug("WebSocket client connected",{clientId:e,totalConnections:this.connections.size}),this.sendMessage(t,{type:"connected",clientId:e,payload:{version:"1.0.0",capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}async handleDisconnection(t){let e=N(t,this.connections);e&&(this.connections.delete(e),await this.cleanupClientResources(e),y.debug("WebSocket client disconnected",{clientId:e,totalConnections:this.connections.size}));}async cleanupClientResources(t){if(y.debug("Cleaning up client resources",{clientId:t}),this.routerRef){try{await this.routerRef.unsubscribeAll(t);}catch{}this.subscribers.delete(t),y.debug("Subscriber cleaned up from router",{clientId:t});}if(this.agentSyncRef)try{await this.agentSyncRef.cleanupClient(t);}catch{}this.subscriptions.delete(t),this.clientLastActivity.delete(t);}async handleMessage(t,e){let s=N(t,this.connections);if(!s){this.sendError(t,"Client not found");return}let n=this.subscriptions.get(s);switch(n&&(n.lastActivityAt=Date.now()),e.type){case "ping":this.sendMessage(t,{type:"pong"});break;case "subscribe":await this.handleSubscribe(t,e);break;case "unsubscribe":await this.handleUnsubscribe(t,e);break;case "message":await this.handleMessageRequest(t,e);break;case "interrupt":await this.handleInterrupt(t,e);break;case "releaseSubscription":await this.handleReleaseSubscription(t,e);break;case "agent_list_request":await this.handleAgentListRequest(t,e);break;case "agent_subscribe":await this.handleAgentSubscribe(t,e);break;case "agent_register":await this.handleAgentRegister(t,e);break;case "agent_deregister":await this.handleAgentDeregister(t,e);break;default:this.sendError(t,`Unknown message type: ${e.type}`);}}async handleSubscribe(t,e){if(e.type!=="subscribe"||!e.sessionId){this.sendError(t,"Invalid subscribe request");return}let s=e.clientId,n;if(s){n=s;let r=N(t,this.connections);r&&r!==n&&(await this.cleanupClientResources(r),this.connections.delete(r),y.info("Client reconnected with different clientId, cleaned up old resources",{oldClientId:r,newClientId:n})),this.connections.set(n,t);}else n=N(t,this.connections)??Ht(),N(t,this.connections)||this.connections.set(n,t);let i=this.subscriptions.get(n);if(i?(i.ws=t,i.lastActivityAt=Date.now()):(i={clientId:n,ws:t,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()},this.subscriptions.set(n,i)),e.payload?.eventTypes)for(let r of e.payload.eventTypes)i.subscribedEventTypes.add(r);if(y.debug("Client subscribed to session",{clientId:n,sessionId:e.sessionId}),this.routerRef){if(this.subscribers.get(n))try{await this.routerRef.unsubscribeAll(n);}catch{}let a=e.payload?.clientType||"tui",c={id:n,type:a,createdAt:Date.now(),lastActiveAt:Date.now(),connection:{send:async d=>{this.sendMessage(t,{type:"message",sessionId:d.sessionId,payload:{id:d.id,type:d.type,content:d.content,metadata:d.metadata,timestamp:d.timestamp}});},close:async()=>{t.close(1e3,"Subscriber closed");},isConnected:()=>t.readyState===t.OPEN}};this.subscribers.set(n,c),await this.routerRef.subscribe(e.sessionId,c),y.debug("Subscriber registered to router",{clientId:n,sessionId:e.sessionId});}this.sendMessage(t,{type:"subscribed",sessionId:e.sessionId});}async handleUnsubscribe(t,e){if(e.type!=="unsubscribe"||!e.sessionId){this.sendError(t,"Invalid unsubscribe request");return}let s=N(t,this.connections);if(s){if(y.debug("Client unsubscribed from session",{clientId:s,sessionId:e.sessionId}),this.routerRef){let n=this.subscribers.get(s);if(n){let i=`sub_${n.id}_${e.sessionId}`;try{await this.routerRef.unsubscribe(i),y.debug("Subscriber unregistered from router",{clientId:s,sessionId:e.sessionId});}catch(r){y.debug("Failed to unsubscribe from router (subscription may not exist)",{clientId:s,sessionId:e.sessionId,error:String(r)});}this.subscribers.delete(s);}}this.sendMessage(t,{type:"unsubscribed",sessionId:e.sessionId});}}async handleMessageRequest(t,e){if(e.type!=="message"||!e.sessionId||!e.payload){this.sendError(t,"Invalid message request");return}let s=this.getClientIdByWs(t)||"unknown";y.debug("Message received from WebSocket client",{clientId:s,sessionId:e.sessionId});let n=e.payload,i=n.message?{...n.message}:{id:`ws_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:e.sessionId,content:n.content||[{type:"text",text:""}]};y.debug("Message received from WebSocket client (use HTTP API to send)",{messageId:i.id,sessionId:e.sessionId}),this.sendMessage(t,{type:"response",sessionId:e.sessionId,success:true,result:{received:true}});}getClientIdByWs(t){return N(t,this.connections)}getClientWs(t){return this.connections.get(t)}async handleInterrupt(t,e){if(e.type!=="interrupt"||!e.sessionId){this.sendError(t,"Invalid interrupt request");return}y.debug("Interrupt requested via WebSocket",{sessionId:e.sessionId}),this.sendMessage(t,{type:"interrupted",sessionId:e.sessionId,success:true});}async handleReleaseSubscription(t,e){if(e.type!=="releaseSubscription"||!e.sessionId){this.sendError(t,"Invalid releaseSubscription request");return}let s=N(t,this.connections);if(!s){this.sendError(t,"Client not found");return}if(y.debug("Release subscription requested via WebSocket",{clientId:s,sessionId:e.sessionId}),this.routerRef){let i=`sub_${s}_${e.sessionId}`;try{await this.routerRef.unsubscribe(i);}catch{}}let n=this.subscriptions.get(s);n&&n.subscribedSessions.delete(e.sessionId),this.sendMessage(t,{type:"subscriptionReleased",sessionId:e.sessionId});}async checkConnectionTimeout(){let t=Date.now(),e=this.config.connectionTimeout??xe.connectionTimeout,s=[];for(let[n,i]of this.subscriptions.entries())t-i.lastActivityAt>e&&s.push(n);for(let n of s){await this.cleanupClientResources(n);let i=this.connections.get(n);if(i){y.debug("Closing inactive connection",{clientId:n,lastActivityAt:this.clientLastActivity.get(n),timeoutMs:e});try{i.close(1001,"Connection timeout");}catch(r){y.debug("Error closing timed out connection",{clientId:n,error:String(r)});}this.connections.delete(n);}}s.length>0&&y.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size});}async cleanupInactiveClients(){let t=Date.now(),e=[],s=this.config.connectionTimeout??xe.connectionTimeout;for(let[n,i]of this.clientLastActivity.entries())t-i>s&&e.push(n);for(let n of e){await this.cleanupClientResources(n);let i=this.connections.get(n);if(i){y.debug("Client inactive, closing connection",{clientId:n,lastActivity:this.clientLastActivity.get(n),timeoutMs:s});try{i.close(1001,"Client inactive");}catch(r){y.debug("Error closing inactive client",{clientId:n,error:String(r)});}this.connections.delete(n);}}e.length>0&&y.debug("Cleaned up inactive clients",{count:e.length,remainingActive:this.clientLastActivity.size});}sendMessage(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e));}sendError(t,e,s){this.sendMessage(t,{type:"error",message:e,code:s});}createRoutes(){return [{method:"get",path:"/health",handler:t=>{let e={status:"healthy",timestamp:Date.now(),version:"1.0.0"};return t.json(e)}},{method:"get",path:"/status",handler:async t=>{let e=await mt();if(e)return t.json(e);let s={status:this.running?"running":"stopped",connections:this.connections.size,sessions:0,messageSubscriptions:0,agentSubscriptions:0,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0",channels:[]};return t.json(s)}},{method:"get",path:"/channels",handler:async t=>{let e=this.channelResolveParams?.pluginLoader;if(!e)return t.json({error:"Plugin loader not available"},503);let n=e.getAllPlugins().map(i=>({id:i.id,platform:i.platform,name:i.name,version:i.version}));return t.json({channels:n,total:n.length})}},{method:"get",path:"/contacts",handler:async t=>{let e=t.req.query("platform"),s=parseInt(t.req.query("limit")||"100",10),n=parseInt(t.req.query("offset")||"0",10),i=this.channelResolveParams?.contactStore;if(!i)return t.json({error:"Contact store not available"},503);try{if(e){let r=await i.listByPlatform(e,s,n);return t.json({contacts:r.contacts.map(a=>({uid:a.uid,platform:a.platform,stableId:a.stableId,profile:a.profile,lastSeenAt:a.lastSeenAt,createdAt:a.createdAt})),total:r.total,hasMore:r.hasMore})}else {let r=await i.count();return t.json({total:r,message:"Specify platform query parameter to list contacts"})}}catch(r){return y.error("failed to list contacts",{error:String(r)}),t.json({error:String(r)},500)}}},{method:"get",path:"/contacts/:uid",handler:async t=>{let e=t.req.param("uid"),s=this.channelResolveParams?.contactStore;if(!s)return t.json({error:"Contact store not available"},503);try{let n=await s.findByUid(e);return n?t.json({uid:n.uid,platform:n.platform,stableId:n.stableId,profile:n.profile,aliases:n.aliases,lastSeenAt:n.lastSeenAt,createdAt:n.createdAt}):t.json({error:"Contact not found"},404)}catch(n){return y.error("failed to get contact",{uid:e,error:String(n)}),t.json({error:String(n)},500)}}},{method:"get",path:"/sessions",handler:async t=>{let e=parseInt(t.req.query("limit")||"100",10),s=parseInt(t.req.query("offset")||"0",10),n=t.req.query("platform"),i=t.req.query("channelId"),r=t.req.query("userId"),a=t.req.query("chatId"),c=[],g=this.getChannelResolveParams().sessionManager?.getAll?.()??[];for(let h of g){let b=!n||h.channel.platform===n,S=!i||h.channel.channelId===i,T=!r||h.channel.userId===r,_=!a||h.channel.chatId===a;b&&S&&(!r&&!a||T&&_)&&c.push({id:h.id,platform:h.channel.platform,channelId:h.channel.channelId,userId:h.channel.userId,chatId:h.channel.chatId,chatType:h.channel.chatType,chatTitle:h.channel.chatTitle,state:h.state.status,createdAt:h.createdAt,lastActiveAt:h.lastActiveAt});}let p=c.slice(s,s+e);return t.json({sessions:p,total:c.length,hasMore:s+e<c.length})}},{method:"get",path:"/sessions/:sessionId",handler:async t=>{let e=t.req.param("sessionId"),n=this.channelResolveParams?.sessionManager?.get(e);if(!n)return t.json({error:"Session not found"},404);let i=0;return n.backendSessionId&&this.routerRef&&(i=this.routerRef.getMessageSubscriptions().get(n.backendSessionId)?.size??0),t.json({id:n.id,platform:n.channel.platform,channelId:n.channel.channelId,userId:n.channel.userId,chatId:n.channel.chatId,state:n.state.status,backendSessionId:n.backendSessionId,subscriberCount:i,createdAt:n.createdAt,lastActiveAt:n.lastActiveAt})}},{method:"post",path:"/session",handler:async t=>{let e=await t.req.json().catch(()=>({}));if(!this.channelResolveParams?.sessionManager)return t.json({error:"Session manager not available"},500);let s=e.channel?.platform,n=e.channel?.channelId;if(!s||!n)return t.json({error:"platform and channelId are required"},400);let i={platform:s,channelId:n,userId:e.channel?.userId,chatId:e.channel?.chatId},r=await this.channelResolveParams.sessionManager.getOrCreate(i),a={id:r.id,createdAt:r.createdAt};return t.json(a)}},{method:"post",path:"/session/:sessionId/prompt",handler:async t=>{let e=t.req.param("sessionId"),s=await t.req.json().catch(()=>({}));if(!e)return t.json({error:"No sessionId provided"},400);let n=this.getChannelResolveParams(),i=e;if(n.sessionManager){let r=n.sessionManager.get(e);if(r)i=r.id;else {let a=n.sessionManager.findByBackendSessionId(e);a&&(y.debug("found gateway session via backendSessionId",{backendSessionId:e,gatewaySessionId:a.id}),i=a.id);}}try{let r=await Ot({...n,sessionId:i,channel:s.channel,userId:s.userId??s.chatId});y.debug("channel resolved for message",{sessionId:e,channel:r.channel,source:r.source,channelInfo:r.channelInfo});let a=utils.Identifier.ascending("message"),c={...r.channelInfo};if(!c.chatId){let p=s.chatId??r.channelInfo.userId;p&&(c.chatId=p,y.debug("filled channelInfo.chatId from request body or session",{chatId:c.chatId}));}if(!c.userId&&c.chatId&&(c.userId=s.userId??c.chatId,y.debug("filled channelInfo.userId from chatId",{userId:c.userId})),!c.chatId)return y.error("channelInfo missing chatId, cannot send message",{sessionId:i,channelInfo:c,body:{userId:s.userId,chatId:s.chatId}}),t.json({error:"channelInfo missing chatId"},400);let d={id:a,sessionId:i,type:"output",content:typeof s.content=="string"?[{type:"text",text:s.content}]:s.content||[],metadata:{channel:c,replyToMessageId:s.replyToMessageId,processorId:s.processorId??"gateway",agent:s.agent??"gateway"},timestamp:Date.now()};if(this.pluginLoaderRef)try{await this.pluginLoaderRef(r.channel,d,{}),y.debug("message sent via pluginLoader",{messageId:a,channel:r.channel});}catch(p){return y.error("failed to send message",{sessionId:i,error:String(p)}),t.json({error:String(p)},500)}else return y.error("no pluginLoader available for sending message",{sessionId:i}),t.json({error:"Plugin loader not available"},500);let g={messageId:a,sessionId:i,createdAt:Date.now(),metadata:{channel:r.channel,channelSource:r.source,channelInfo:r.channelInfo}};return t.status(202),t.json(g)}catch(r){return r instanceof V?(y.warn("channel selection failed",{sessionId:i,error:r.message}),t.json({error:Wt(r),code:r.code},400)):(y.error("send message error",{sessionId:i,error:String(r)}),t.json({error:String(r)},500))}}},{method:"get",path:"/subscriptions",handler:t=>{let e=t.req.query("sessionId"),s=t.req.query("subscriberId");y.debug("subscriptions endpoint called",{routerRefExists:!!this.routerRef,agentSyncRefExists:!!this.agentSyncRef,filterSessionId:e,filterSubscriberId:s});let n=[];if(this.routerRef){let r=this.routerRef,a=r.getMessageSubscriptions();y.debug("messageSubscriptions",{size:a.size,entries:Array.from(a.entries())});for(let[c,d]of a.entries()){if(e&&e!=="agent-list"&&c!==e)continue;let g=new Map;for(let p of d){let h=r.getSubscription(p);if(h){if(s&&h.subscriberId!==s)continue;g.set(h.subscriberId,{id:h.subscriberId,subscriptionId:p});}}g.size>0&&n.push({type:"message",sessionId:c,subscriberCount:g.size,subscribers:Array.from(g.values())});}}if(this.agentSyncRef&&!(e&&e!=="agent-list")){let r=this.agentSyncRef.getSubscribers();y.debug("agentSubscribers",{count:r.length,subscribers:r,filterSubscriberId:s});let a=s?r.filter(c=>c===s):r;y.debug("filteredAgents",{filteredAgents:a}),a.length>0&&n.push({type:"agent",sessionId:"agent-list",subscriberCount:a.length,subscribers:a.map(c=>({id:c,subscriptionId:`agent_sub_${c}`}))});}let i={subscriptions:n,total:n.length};return y.debug("subscriptions response",{subscriptionsCount:n.length,subscriptions:n.map(r=>({type:r.type,sessionId:r.sessionId,subscriberCount:r.subscriberCount}))}),t.json(i)}}]}async handleAgentListRequest(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_list_request"){this.sendError(t,"Invalid agent list request");return}let s=N(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentListRequest(s,e.requestId);}async handleAgentSubscribe(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_subscribe"){this.sendError(t,"Invalid agent subscribe request");return}let s=e.clientId,n;if(s){n=s;let i=N(t,this.connections);i&&i!==n&&this.connections.delete(i),this.connections.set(n,t);}else n=N(t,this.connections)??Ht(),N(t,this.connections)||this.connections.set(n,t);await this.agentSyncRef.handleAgentSubscribe(n,e.subscribe);}async handleAgentRegister(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_register"||!e.payload){this.sendError(t,"Invalid agent register request");return}let s=N(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentRegister(s,e.payload);}async handleAgentDeregister(t,e){if(!this.agentSyncRef){this.sendError(t,"Agent sync not configured");return}if(e.type!=="agent_deregister"||!e.payload){this.sendError(t,"Invalid agent deregister request");return}let s=N(t,this.connections);if(!s){this.sendError(t,"Client not found");return}await this.agentSyncRef.handleAgentDeregister(s,e.payload);}};function ji(o){return o.toLowerCase().replace(/^\//,"").replace(/@[^\s]+$/,"")}function qi(o){return o.replace(/[-_]/g,"").toLowerCase()}var ae=[{command:"new",description:"Reset session and start a new conversation"},{command:"status",description:"Show gateway and channel status"},{command:"commands",description:"Show available commands"}],A=class{constructor(){chunk6C5TBG7Z_cjs.a(this,"version","1.0.0");chunk6C5TBG7Z_cjs.a(this,"log");chunk6C5TBG7Z_cjs.a(this,"config",null);chunk6C5TBG7Z_cjs.a(this,"messageHandler",null);chunk6C5TBG7Z_cjs.a(this,"_status","stopped");chunk6C5TBG7Z_cjs.a(this,"lastActivity",0);chunk6C5TBG7Z_cjs.a(this,"startPromise",null);chunk6C5TBG7Z_cjs.a(this,"stopPromise",null);}initLog(){this.log=utils.Log.create({service:`channel:${this.platform}`});}async start(t,e){if(this.startPromise)return this.log.warn("plugin start already in progress"),this.startPromise;if(this._status==="running"){this.log.warn("plugin is already running");return}this.startPromise=this.doStartInternal(t,e);try{await this.startPromise;}finally{this.startPromise=null;}}async doStartInternal(t,e){this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=t,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(s){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(s)}),s}}async stop(){if(this.stopPromise)return this.log.warn("plugin stop already in progress"),this.stopPromise;if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}this.stopPromise=this.doStopInternal();try{await this.stopPromise;}finally{this.stopPromise=null;}}async doStopInternal(){this.log.info("stopping channel plugin",{id:this.id}),this._status="stopping";try{await this.doStop(),this._status="stopped",this.log.info("channel plugin stopped",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(t)}),t}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(t){return {healthy:false,lastCheck:Date.now(),error:t instanceof Error?t.message:String(t)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}getCapabilities(){return {supportsText:true,supportsMedia:false,supportsReply:false,supportsThread:false,supportsEdit:false,supportsDelete:false,supportsTyping:false,supportsBatchSend:false,supportsMarkdown:false,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,supportsSlashCommands:false,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:4096,maxMediaCount:1}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}extractText(t){return t.content.filter(e=>e.type==="text").map(e=>e.text??"").join(`
|
|
12
12
|
`)}buildSessionId(t,e,s){let n=[this.platform,t,e];return s&&n.push(s),n.join("_")}async handleMessage(t){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:t.id});return}this.updateActivity(),await this.messageHandler.onMessage(t);}async handleEvent(t,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:t});return}await this.messageHandler.onEvent({type:t,channelId:this.id,data:e,timestamp:Date.now()});}async getCommandList(){try{let t=Q(),s=(await t.sdk.config.get().then(i=>i.data).catch(()=>{}))?.context?.mode??"general";return (await t.sdk.command.list({contextMode:s},{throwOnError:!0})).data??[]}catch(t){return this.log.warn("failed to get command list",{error:String(t)}),[]}}async processLocalCommand(t,e,s){switch(t.toLowerCase().replace(/^\//,"").replace(/@[^\s]+$/,"")){case "new":return this.handleNewCommand(e);case "status":return this.handleStatusCommand(e);case "commands":return this.handleCommandsCommand();default:return {handled:false}}}async handleCommandsCommand(){try{let e=(await this.getCommandList()).filter(n=>n.hidden!==!0),s=[];s.push("\u{1F4D6} **Available Commands**"),s.push(""),s.push("**Local**");for(let n of ae)s.push(`\`/${n.command}\` - ${n.description}`);if(s.push(""),s.push("**EASBot**"),e.length===0)s.push("_No commands available_");else for(let n of e){let i=n.description?.trim()||n.name;s.push(`\`/${n.name}\` - ${i}`);}return {handled:!0,reply:s.join(`
|
|
13
13
|
`)}}catch(t){return this.log.error("failed to process /commands command",{error:String(t)}),{handled:true,reply:`\u274C Failed to list commands: ${String(t)}`}}}async handleNewCommand(t){try{return this.messageHandler?.session?this.messageHandler.session.getSession(t)?(await this.messageHandler.session.unbindBackendSession(t),this.log.debug("session backendSessionId cleared",{sessionId:t}),{handled:!0,reply:"\u2705 Session reset. Next message will create a new session."}):{handled:!0,reply:"\u274C Session not found"}:{handled:!0,reply:"\u274C Session management interface unavailable"}}catch(e){return this.log.error("failed to process /new command",{error:String(e)}),{handled:true,reply:`\u274C Operation failed: ${String(e)}`}}}async handleStatusCommand(t){try{let e=this.getStatus(),s=await this.healthCheck(),n;this.messageHandler?.session&&(n=this.messageHandler.session.getSession(t)?.backendSessionId),this.log.debug("handleStatusCommand: getting gateway status via global function");let i=await mt();return this.log.debug("handleStatusCommand: gateway status retrieved",{hasGatewayStatus:!!i}),{handled:!0,reply:this.formatStatusReport(e,s,t,n,i)}}catch(e){return this.log.error("failed to process /status command",{error:String(e)}),{handled:true,reply:`\u274C Failed to get status: ${String(e)}`}}}async processCommand(t){let e=t.text.trim();if(!e.startsWith("/"))return {handled:false};let s=e.split(/\s+/),n=s[0]??"",i=s.slice(1),r=ji(n),a=await this.processLocalCommand(n,t.sessionId,t.chatId);if(a.handled)return {handled:true,reply:a.reply};let d=(await this.getCommandList()).find(g=>qi(g.name)===r);if(d){let g={};return t.messageId&&(g.messageId=t.messageId),t.replyToMessageId&&(g.replyToMessageId=t.replyToMessageId),{handled:true,gatewayMessage:I(t.sessionId,"input",[{type:"command",command:d.name,arguments:i.join(" ")}],{channel:t.channelInfo,...Object.keys(g).length>0?{context:g}:{}})}}return {handled:false}}formatStatusReport(t,e,s,n,i){let r=[];if(r.push("\u{1F4CA} **Gateway Status Report**"),r.push(""),r.push("---"),r.push(""),r.push("### Gateway"),i){let g=i.status==="running"?"\u{1F7E2}":"\u26AA";if(r.push(`- **Status**: ${g} ${i.status}`),r.push(`- **Version**: ${i.version??"unknown"}`),r.push(`- **Uptime**: ${this.formatUptime(i.uptime)}`),r.push(`- **Connections**: ${i.connections}`),r.push(`- **Sessions**: ${i.sessions}`),r.push(`- **Message Subscriptions**: ${i.messageSubscriptions}`),r.push(`- **Agent Subscriptions**: ${i.agentSubscriptions}`),i.agents&&r.push(`- **Agents**: ${i.agents.total} (healthy: ${i.agents.healthy}, unhealthy: ${i.agents.unhealthy})`),i.channels&&i.channels.length>0){let p=i.channels.map(h=>h.platform).join(", ");r.push(`- **Channels**: ${p}`);}}else r.push("- **Status**: N/A");r.push(""),r.push("### Channel");let a=t.status==="running"?"\u{1F7E2}":t.status==="error"?"\u{1F534}":"\u26AA";r.push(`- **Platform**: ${this.platform}`),r.push(`- **Plugin ID**: ${this.id}`),r.push(`- **Name**: ${this.name}`),r.push(`- **Status**: ${a} ${t.status}`),r.push(`- **Health**: ${e.healthy?"\u2705 OK":"\u274C Error"}`),e.error&&r.push(`- **Error**: ${e.error}`),this.version&&r.push(`- **Version**: ${this.version}`),r.push(`- **Last Activity**: ${new Date(t.lastActivity??Date.now()).toLocaleString()}`),r.push(""),r.push("### Session");let c=s.split("_"),d=c.length>=2?`${c[0]}_${c[1]}...`:s;return r.push(`- **Session ID**: \`${d}\``),r.push(`- **Backend Session**: ${n?`\`${n}\``:"\u274C Not Bound"}`),r.push(""),r.push("---"),r.push(`*Report generated: ${new Date().toLocaleString()}*`),r.join(`
|
|
14
14
|
`)}formatUptime(t){if(t<=0)return "0s";let e=Math.floor(t/1e3),s=Math.floor(e/60),n=Math.floor(s/60),i=Math.floor(n/24),r=[];return i>0&&r.push(`${i}d`),n%24>0&&r.push(`${n%24}h`),s%60>0&&r.push(`${s%60}m`),(e%60>0||r.length===0)&&r.push(`${e%60}s`),r.slice(0,2).join(" ")}};var Re=class extends A{constructor(e="telegram-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","telegram");chunk6C5TBG7Z_cjs.a(this,"name","Telegram Bot");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"baseUrl","");chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"lastUpdateId",0);chunk6C5TBG7Z_cjs.a(this,"typingTimers",new Map);chunk6C5TBG7Z_cjs.a(this,"sentMessages",new Map);chunk6C5TBG7Z_cjs.a(this,"sessionIdMap",new Map);chunk6C5TBG7Z_cjs.a(this,"commandRouter",new Map);chunk6C5TBG7Z_cjs.a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});chunk6C5TBG7Z_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!==false&&this.startPolling();}async doStop(){this.abortController?.abort(),this.abortController=null,this.pollingStopped=false,this.retryState.attempts=0,this.clearAllTyping(),this.commandRouter.clear(),this.botConfig=null,this.log.debug("Telegram plugin stopped");}async doHealthCheck(){return this._status!=="running"?false:this.pollingStopped?(this.log.warn("Polling was stopped, attempting restart"),this.restartPolling(),true):this.abortController!=null&&!this.abortController.signal.aborted}async send(e){let s=e.metadata.channel.chatId;if(!s)throw 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(g=>g.type==="image"),c=e.content.find(g=>g.type==="file"),d;if(a){let g=a.image,p=n||void 0;d=await this.sendPhoto(s,g,p);}else if(c){let g=c.data,p=n||void 0;d=await this.sendDocument(s,g,p);}else try{d=await this.sendApiMessage(s,n,{parseMode:r,replyTo:i?parseInt(i,10):void 0});}catch(g){if(r!=="None"&&this.isParseError(g))this.log.debug("parse error, retrying with plain text",{parseMode:r,error:String(g)}),d=await this.sendApiMessage(s,n,{parseMode:"None",replyTo:i?parseInt(i,10):void 0});else throw g}return this.sentMessages.set(e.id,{chatId:s,messageId:parseInt(d,10),timestamp:Date.now()}),this.sessionIdMap.set(e.id,e.sessionId),d}async sendPhoto(e,s,n){this.log.debug("sendPhoto called",{chatId:e,image:s,imageType:typeof s,caption:n});let i=new URLSearchParams({chat_id:e});n&&i.set("caption",n);let r="photo.jpg",a;if(typeof s=="string")if(s.startsWith("file://"))a=await utils.PKG.file(url.fileURLToPath(s)).bytes(),r=s.split("/").pop()||r;else {let d=await utils.Fetch.post(`${this.baseUrl}/sendPhoto`,{chat_id:e,photo:s,caption:n});if(!d.data.ok)throw new Error(`sendPhoto failed: ${d.data.description||"unknown error"}`);return d.data.result.message_id.toString()}else if(s instanceof URL){let d=await utils.Fetch.post(`${this.baseUrl}/sendPhoto`,{chat_id:e,photo:s.toString(),caption:n});if(!d.data.ok)throw new Error(`sendPhoto failed: ${d.data.description||"unknown error"}`);return d.data.result.message_id.toString()}else a=s;this.log.debug("sendPhoto: calling Fetch.postForm",{url:`${this.baseUrl}/sendPhoto?${i}`,filename:r});let c=await utils.Fetch.postForm(`${this.baseUrl}/sendPhoto?${i}`,[{name:"photo",value:a,filename:r}],{timeout:3e5});if(this.log.debug("sendPhoto: response received",{ok:c.ok,status:c.status,data:c.data}),!c.ok)throw new Error(`sendPhoto failed: ${c.data.description||"unknown error"}`);return c.data.result.message_id.toString()}async sendDocument(e,s,n){this.log.debug("sendDocument called",{chatId:e,file:s,fileType:typeof s,caption:n});let i=new URLSearchParams({chat_id:e});n&&i.set("caption",n);let r="document",a;if(typeof s=="string")if(s.startsWith("file://"))a=await utils.PKG.file(url.fileURLToPath(s)).bytes(),r=s.split("/").pop()||r;else {let d=await utils.Fetch.post(`${this.baseUrl}/sendDocument`,{chat_id:e,document:s,caption:n});if(!d.data.ok)throw new Error(`sendDocument failed: ${d.data.description||"unknown error"}`);return d.data.result.message_id.toString()}else if(s instanceof URL){let d=await utils.Fetch.post(`${this.baseUrl}/sendDocument`,{chat_id:e,document:s.toString(),caption:n});if(!d.data.ok)throw new Error(`sendDocument failed: ${d.data.description||"unknown error"}`);return d.data.result.message_id.toString()}else a=s;this.log.debug("sendDocument: calling Fetch.postForm",{url:`${this.baseUrl}/sendDocument?${i}`,filename:r});let c=await utils.Fetch.postForm(`${this.baseUrl}/sendDocument?${i}`,[{name:"document",value:a,filename:r}],{timeout:3e5});if(this.log.debug("sendDocument: response received",{ok:c.ok,status:c.status,data:c.data}),!c.ok)throw new Error(`sendDocument failed: ${c.data.description||"unknown error"}`);return c.data.result.message_id.toString()}isParseError(e){let s=String(e);return s.includes("can't parse entities")||s.includes("parse")}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:false,supportsEdit:true,supportsDelete:true,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:true,supportsHtml:true,supportsDeliveryReceipt:true,supportsReadReceipt:true,supportsSlashCommands:true,supportsNativeCommands:true,commandPrefix:"/",maxMessageLength:4096,maxMediaCount:10}}async sendTyping(e){await this.sendChatAction(e,"typing");}async sendChatAction(e,s){await this.request("sendChatAction",{chat_id:e,action:s}),this.scheduleTypingStop(e,5e3);}scheduleTypingStop(e,s){let n=this.typingTimers.get(e);n&&clearTimeout(n);let i=setTimeout(()=>{this.typingTimers.delete(e);},s);this.typingTimers.set(e,i);}clearAllTyping(){for(let e of this.typingTimers.values())clearTimeout(e);this.typingTimers.clear();}detectParseMode(e){let s=this.extractText(e);return s.includes("<")&&s.includes("</")?"HTML":s.includes("*")||s.includes("_")||s.includes("`")?"Markdown":"None"}startPolling(){this.abortController=new AbortController,this.pollLoop(),this.log.debug("Polling started");}pollLoop(){(async()=>{try{await this.poll(),this.abortController?.signal.aborted||this.pollLoop();}catch(s){this.handlePollingError(s);}})();}async poll(){let e=this.botConfig?.polling?.timeout??30,s=await this.getUpdates(this.lastUpdateId+1,100,e);for(let n of s)if(this.lastUpdateId=Math.max(this.lastUpdateId,n.update_id),n.message&&await this.handleTelegramMessage(n.message),n.edited_message&&await this.handleTelegramMessage(n.edited_message),n.message_reaction&&await this.handleMessageReaction(n.message_reaction),n.message_reaction_count&&n.message_reaction_count.length>0)for(let i of n.message_reaction_count)await this.handleMessageReactionCount(i);this.retryState.attempts=0;}async handleMessageReaction(e){let s=this.findSentMessageEntry(e.message_id);if(!s)return;let n=s.gatewayMessageId,i=this.sessionIdMap.get(n),a=e.new_reaction.some(c=>c.type==="emoji"&&(c.emoji==="\u{1F441}"||c.emoji==="\u2705"))?"message_read":"message_delivered";this.log.debug("message reaction received",{messageId:n,telegramMessageId:e.message_id,sessionId:i,eventType:a,reactions:e.new_reaction}),this.messageHandler&&await this.messageHandler.onEvent({type:a,channelId:this.id,data:{id:n,sessionId:i,platform:"telegram",channelId:this.id,reactions:e.new_reaction,telegramMessageId:e.message_id,timestamp:e.date*1e3},timestamp:Date.now()});}async handleMessageReactionCount(e){let s=this.findSentMessageEntry(e.message_id);if(!s)return;let n=s.gatewayMessageId,i=this.sessionIdMap.get(n),r=this.sentMessages.get(n);r&&Date.now()-r.timestamp>3e4&&(this.log.debug("message reaction count received (delivery confirmation)",{messageId:n,telegramMessageId:e.message_id,sessionId:i,reactions:e.reactions}),this.messageHandler&&await this.messageHandler.onEvent({type:"message_delivered",channelId:this.id,data:{id:n,sessionId:i,platform:"telegram",channelId:this.id,reactions:e.reactions,telegramMessageId:e.message_id,timestamp:e.date*1e3},timestamp:Date.now()}));}findSentMessageEntry(e){for(let[s,n]of this.sentMessages.entries())if(n.messageId===e)return {gatewayMessageId:s,...n}}handlePollingError(e){if(!this.abortController?.signal.aborted)if(this.log.error("Polling error",{error:String(e)}),this.retryState.attempts<this.retryState.maxAttempts){let s=Math.min(this.retryState.initialDelay*2**this.retryState.attempts,this.retryState.maxDelay);this.retryState.attempts++,this.log.debug("Retrying polling",{attempt:this.retryState.attempts,delay:s}),this.sleep(s).then(()=>this.pollLoop());}else this.log.error("Polling failed after max attempts, needs restart",{attempts:this.retryState.maxAttempts}),this.pollingStopped=true;}restartPolling(){this.retryState.attempts=0,this.pollingStopped=false,this.abortController=new AbortController,this.pollLoop(),this.log.debug("Polling restarted");}sleep(e){return new Promise(s=>setTimeout(s,e))}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot||e.text?.startsWith("/")&&await this.handleCommand(e))return;await this.sendTyping(e.chat.id.toString());let s=await this.toGatewayMessage(e);await this.handleMessage(s);}async handleCommand(e){let s=this.buildSessionId(this.id,e.chat.id.toString(),e.from?.id.toString()),n=await this.processCommand({text:e.text??"",sessionId:s,chatId:e.chat.id.toString(),channelInfo:{platform:"telegram",channelId:this.id,userId:e.from?.id.toString(),chatId:e.chat.id.toString(),username:e.from?.username,firstName:e.from?.first_name,lastName:e.from?.last_name,chatType:e.chat.type,chatTitle:e.chat.title},messageId:e.message_id.toString(),replyToMessageId:e.reply_to_message?.message_id.toString()});return n.handled?(n.reply?await this.sendApiMessage(e.chat.id.toString(),n.reply,{parseMode:"Markdown",replyTo:e.message_id}):n.gatewayMessage&&(await this.sendTyping(e.chat.id.toString()),await this.handleMessage(n.gatewayMessage)),true):false}async toGatewayMessage(e){let s=this.processMessageAndGetSessionId(e);return I(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 c=Buffer.from(r.data);return await utils.PKG.file(s).write(c),s}async parseContent(e){let s=[],n=e.text??e.caption??"",i=w()?.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 c=`photo_${a.file_unique_id}.jpg`,d=utils.Filesystem.join(r,`${e.chat.id}_${a.file_unique_id}_${c}`);await this.downloadBinaryFile(a.file_id,d),this.log.debug("photo downloaded",{filePath:d,fileId:a.file_id}),s.push({type:"image",image:url.pathToFileURL(d).href,mime:"image/jpeg"});}catch(c){this.log.warn("failed to download photo, storing as file",{platform:"telegram",fileId:a.file_id,error:String(c)}),s.push({type:"image",image:a.file_id,mime:"image/jpeg"});}}if(e.document){let a=e.document.mime_type||"application/octet-stream",c=e.document.file_name||"file",d=e.document.file_id;if(a.startsWith("text/"))try{this.log.debug("downloading text file",{fileId:d,fileName:c,mimeType:a});let g=await this.parseFileContent(d),p=await utils.TruncateContent.truncate(g,{maxChars:5e3,label:`file: ${c}`});s.push({type:"text",text:`\u{1F4CE} File: ${c}
|
|
@@ -18,18 +18,18 @@ ${p.content}`});}catch(g){this.log.warn("failed to download text file, storing a
|
|
|
18
18
|
${p.content}`});}else await this.downloadFile(r.url,d),s.push({type:"file",data:url.pathToFileURL(d).href,mime:r.content_type});}catch(a){this.log.warn("failed to download file, storing as URL",{attachmentId:r.id,error:String(a)}),s.push({type:"file",data:r.url,mime:r.content_type});}return s}async downloadFile(e,s){let n=await 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 Ne=class extends A{constructor(e="slack-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","slack");chunk6C5TBG7Z_cjs.a(this,"name","Slack Bot");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"baseUrl","https://slack.com/api");chunk6C5TBG7Z_cjs.a(this,"socketModeClient",null);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"processedMessageIds",new Set);chunk6C5TBG7Z_cjs.a(this,"sentMessages",new Map);chunk6C5TBG7Z_cjs.a(this,"sessionIdMap",new Map);chunk6C5TBG7Z_cjs.a(this,"commandRouter",new Map);chunk6C5TBG7Z_cjs.a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});chunk6C5TBG7Z_cjs.a(this,"socketReconnectAttempts",0);chunk6C5TBG7Z_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(d=>d.type==="image"),r=e.content.find(d=>d.type==="file"),a=e.metadata.context?.threadId,c;return i?c=await this.postImage(s,i.image,n,a):r?c=await this.postFile(s,r.data,r.mime,n,a):c=await this.postMessage(s,n,a),this.sentMessages.set(e.id,{channelId:s,ts:c.ts,timestamp:Date.now()}),this.sessionIdMap.set(e.id,e.sessionId),c.ts}async postMessage(e,s,n){let r=this.getCapabilities().maxMessageLength-500,a=s;if(s.length>r){let d=await utils.TruncateContent.truncate(s,{maxChars:r,label:"slack message"});a=d.content,this.log.debug("postMessage: message truncated",{originalLength:s.length,maxLength:r,outputPath:d.truncated?d.outputPath:void 0});}let c={channel:e,text:a};return n&&(c.thread_ts=n),this.request("chat.postMessage",c)}async postImage(e,s,n,i){let r;if(typeof s=="string")if(s.startsWith("http")){let c=await utils.Fetch.get(s,{responseType:"arrayBuffer"}),d=s.split("/").pop()||"image.jpg";r=await this.uploadFile(new Uint8Array(c.data),d);}else if(s.startsWith("file://")){let c=await utils.PKG.file(url.fileURLToPath(s)).bytes(),d=s.split("/").pop()||"image.jpg";r=await this.uploadFile(c,d);}else r=s;else if(s instanceof URL){let c=await utils.Fetch.get(s.toString(),{responseType:"arrayBuffer"}),d=s.pathname.split("/").pop()||"image.jpg";r=await this.uploadFile(new Uint8Array(c.data),d);}else r=await this.uploadFile(s,"image.jpg");let a={channel:e,text:n||"",attachments:[{image_url:r}]};return i&&(a.thread_ts=i),this.request("chat.postMessage",a)}async postFile(e,s,n,i,r){let a,c="file";if(typeof s=="string")if(s.startsWith("http")){let p=await utils.Fetch.get(s,{responseType:"arrayBuffer"});a=new Uint8Array(p.data),c=s.split("/").pop()||"file";}else s.startsWith("file://")?(a=await utils.PKG.file(url.fileURLToPath(s)).bytes(),c=s.split("/").pop()||"file"):(a=await utils.PKG.file(s).bytes(),c=s.split("/").pop()||"file");else if(s instanceof URL){let p=await utils.Fetch.get(s.toString(),{responseType:"arrayBuffer"});a=new Uint8Array(p.data),c=s.pathname.split("/").pop()||"file";}else a=s;await this.uploadFile(a,c);let g={channel:e,text:i||`File: ${c}`,attachments:[{fallback:c,text:i||c,fields:[{title:"File",value:c,short:true}]}]};return r&&(g.thread_ts=r),this.request("chat.postMessage",g)}async uploadFile(e,s){let n=await utils.Fetch.postForm(`${this.baseUrl}/files.upload`,[{name:"file",value:e,filename:s}],{timeout:3e5,headers:{Authorization:`Bearer ${this.botConfig?.botToken}`}});if(!n.data.ok||!n.data.file)throw f(this.id,"MESSAGE_SEND_FAILED",`File upload failed: ${n.data.error}`);return n.data.file.url_private}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:true,supportsEdit:false,supportsDelete:false,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:true,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,supportsSlashCommands:true,supportsNativeCommands:true,commandPrefix:"/",maxMessageLength:3e4,maxMediaCount:10}}async startSocketMode(){if(!this.botConfig?.appToken||this.abortController?.signal.aborted)return;let e="wss://wss-primary.slack.com/socket";this.socketModeClient=new WebSocket(e),this.socketModeClient.onmessage=async s=>{try{let n=JSON.parse(s.data.toString());await this.handleSocketModeEvent(n);}catch(n){this.log.error("Socket mode event error",{error:String(n)});}},this.socketModeClient.onerror=s=>{this.log.error("Socket mode error",{error:String(s)});},this.socketModeClient.onclose=()=>{if(!this.abortController?.signal.aborted)if(this.log.info("Socket mode disconnected"),this.socketReconnectAttempts<this.maxSocketReconnectAttempts){let s=Math.min(1e3*2**this.socketReconnectAttempts,3e4);this.socketReconnectAttempts++,this.log.info("Attempting to reconnect to Socket mode",{attempt:this.socketReconnectAttempts,delay:s}),setTimeout(()=>this.startSocketMode(),s);}else this.log.error("Max Socket reconnect attempts reached");},this.log.info("Socket mode started");}async handleSocketModeEvent(e){if(e.envelope_id&&this.socketModeClient?.send(JSON.stringify({envelope_id:e.envelope_id})),e.type==="events_api"&&e.payload?.event){let s=e.payload.event;s.type==="message"&&!s.subtype&&await this.handleSlackMessage(e.payload.event),s.type==="reaction_added"&&await this.handleReactionEvent(e.payload.event);}}async handleReactionEvent(e){if(e.reaction!=="white_check_mark"&&e.reaction!=="eyes")return;let s=this.findSentMessageEntry(e.item.ts);if(!s)return;let n=s.gatewayMessageId,i=this.sessionIdMap.get(n),a=e.reaction==="white_check_mark"?"message_read":"message_delivered";this.log.debug("message reaction received",{messageId:n,slackTs:e.item.ts,sessionId:i,eventType:a}),this.messageHandler&&await this.messageHandler.onEvent({type:a,channelId:this.id,data:{id:n,sessionId:i,platform:"slack",channelId:this.id,reaction:e.reaction,slackTs:e.item.ts},timestamp:Date.now()});}findSentMessageEntry(e){for(let[s,n]of this.sentMessages.entries())if(n.ts===e)return {gatewayMessageId:s,...n}}async handleSlackMessage(e){if(this.updateActivity(),e.user==="USLACKBOT"||this.processedMessageIds.has(e.ts))return;if(this.processedMessageIds.add(e.ts),this.processedMessageIds.size>1e4){let n=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(n.slice(-5e3));}if(e.text?.startsWith("/")&&await this.handleCommand(e))return;let s=await this.toGatewayMessage(e);await this.handleMessage(s);}async handleCommand(e){let s=(e.text??"").split(" "),n=s[0]?.toLowerCase()??"",i=s.slice(1),r=this.commandRouter.get(n);if(r){let d={channelId:e.channel,userId:e.user,args:i,ts:e.ts,reply:async g=>(await this.postMessage(e.channel,g,e.thread_ts)).ts};try{return await r.handler(d),!0}catch(g){return this.log.error("Command handler error",{command:n,error:String(g)}),true}}let a=this.buildSessionId(this.id,e.channel,e.user),c=await this.processCommand({text:e.text??"",sessionId:a,chatId:e.channel,channelInfo:{platform:"slack",channelId:this.id,userId:e.user,chatId:e.channel,ts:e.ts,threadTs:e.thread_ts},messageId:e.ts,replyToMessageId:e.thread_ts});return c.handled?(c.reply?await this.postMessage(e.channel,c.reply,e.thread_ts):c.gatewayMessage&&await this.handleMessage(c.gatewayMessage),true):false}async getCommandList(){try{return (await this.request("commands.list",{})).map(s=>({name:s.name,description:s.description}))}catch{return []}}async syncBotCommands(){try{let e=ae.map(i=>({command:i.command,description:i.description})),s=Array.from(this.commandRouter.values()).map(i=>({command:i.command.replace(/^\//,""),description:i.description})),n=[...e,...s];if(n.length===0)return;await this.request("commands.set",{commands:n}),this.log.debug("Bot commands synced",{count:n.length});}catch(e){this.log.warn("Failed to sync bot commands",{error:String(e)});}}async toGatewayMessage(e){let s=this.buildSessionId(this.id,e.channel,e.user);return I(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=w()?.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`,c=a.includes(".")?a.split(".").pop():"jpg",d=utils.Filesystem.join(i,`slack_${e.channel}_${r.id}.${c}`);await this.downloadFile(r.url_private_download||r.url_private,d),s.push({type:"image",image:url.pathToFileURL(d).href,mime:r.mimetype});}catch(a){this.log.warn("failed to download image, storing as URL",{fileId:r.id,error:String(a)}),s.push({type:"image",image:r.url_private,mime:r.mimetype});}else try{let a=r.name||`file_${r.id}`,c=a.includes(".")?a.split(".").pop():utils.Filesystem.mimeTypeToExt(r.mimetype)||"bin",d=utils.Filesystem.join(i,`slack_${e.channel}_${r.id}.${c}`);if(r.mimetype.startsWith("text/")){let g=await this.downloadTextFile(r.url_private),p=await utils.TruncateContent.truncate(g,{maxChars:5e3,label:`file: ${a}`});s.push({type:"text",text:`\u{1F4CE} File: ${a}
|
|
19
19
|
|
|
20
20
|
${p.content}`});}else await this.downloadFile(r.url_private_download||r.url_private,d),s.push({type:"file",data:url.pathToFileURL(d).href,mime:r.mimetype});}catch(a){this.log.warn("failed to download file, storing as URL",{fileId:r.id,error:String(a)}),s.push({type:"file",data:r.url_private,mime:r.mimetype});}return s}async downloadFile(e,s){let n=await 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 Le=class extends A{constructor(e="feishu-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","feishu");chunk6C5TBG7Z_cjs.a(this,"name","Feishu Bot");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"baseUrl","https://open.feishu.cn/open-apis");chunk6C5TBG7Z_cjs.a(this,"tenantAccessToken",null);chunk6C5TBG7Z_cjs.a(this,"tokenExpireTime",0);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"processedMessageIds",new Set);chunk6C5TBG7Z_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(c=>c.type==="image"),r=e.content.find(c=>c.type==="file"),a;return i?a=await this.sendImage(s,i.image,n):r?a=await this.sendFile(s,r.data,n):a=await this.sendMessage(s,n),a}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:false,supportsEdit:false,supportsDelete:false,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:true,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:4e3,maxMediaCount:10}}async handleWebhookEvent(e){this.updateActivity();let s=e.event?.message?.message_id;if(s&&this.processedMessageIds.has(s)){this.log.debug("Duplicate message ignored",{messageId:s});return}if(s&&(this.processedMessageIds.add(s),this.processedMessageIds.size>1e4)){let n=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(n.slice(-5e3));}if(e.event?.message){let n=e.event.message,i;if(n.message_type==="text")try{let a=JSON.parse(n.content);a.text?.trim().startsWith("/")&&(i=a.text);}catch{}if(i!==void 0){let a=this.buildSessionId(this.id,n.chat_id,n.sender.sender_id.open_id),c=await this.processCommand({text:i,sessionId:a,chatId:n.chat_id,channelInfo:{platform:"feishu",channelId:this.id,userId:n.sender.sender_id.open_id,chatId:n.chat_id,messageId:n.message_id,rootId:n.root_id,parentId:n.parent_id,tenantKey:e.tenant_key},messageId:n.message_id,replyToMessageId:n.parent_id??n.root_id});if(c.handled){c.reply?await this.sendMessage(n.chat_id,c.reply):c.gatewayMessage&&await this.handleMessage(c.gatewayMessage);return}}let r=await this.toGatewayMessage(e);await this.handleMessage(r);}}async refreshTenantAccessToken(){let s=(await 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 d=await utils.TruncateContent.truncate(s,{maxChars:i,label:"feishu message"});r=d.content,this.log.debug("sendMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:d.truncated?d.outputPath:void 0});}let c=(await 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(c.code!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`Feishu API error: ${c.msg}`);return c.data.message_id}async sendImage(e,s,n){let i;if(typeof s=="string")if(s.startsWith("http")){let a=await 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 c=await utils.Fetch.get(s,{responseType:"arrayBuffer"});i=await this.uploadFile(new Uint8Array(c.data),"file");}else i=s;else if(s instanceof URL){let c=await utils.Fetch.get(s.toString(),{responseType:"arrayBuffer"});i=await this.uploadFile(new Uint8Array(c.data),"file");}else i=await this.uploadFile(s,"file");let a=await 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}],{timeout:3e5,headers:{Authorization:`Bearer ${this.tenantAccessToken}`}});if(n.data.code!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`File upload failed: ${n.data.msg}`);return n.data.data.file_key}async toGatewayMessage(e){let s=e.event.message,n=this.buildSessionId(this.id,s.chat_id,s.sender.sender_id.open_id);return I(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=w()?.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}`,c=a.includes(".")?a.split(".").pop():utils.Filesystem.mimeTypeToExt(r.file_type)||"bin",d=utils.Filesystem.join(i,`feishu_${e.chat_id}_${r.file_key}.${c}`);await this.downloadFile(r.file_key,d),s.push({type:"file",data:url.pathToFileURL(d).href,mime:r.file_type??"application/octet-stream"});}catch(a){this.log.warn("failed to download file, storing as key",{fileKey:r.file_key,error:String(a)}),s.push({type:"file",data:r.file_key,mime:r.file_type??"application/octet-stream"});}break;default:s.push({type:"text",text:JSON.stringify(r)});}}catch{s.push({type:"text",text:e.content});}return s}async downloadImage(e,s){await this.ensureTokenValid();let n=await 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(`
|
|
21
|
-
`)}buildSessionId(e,s,n){let i=["feishu",e,s];return n&&i.push(n),i.join("_")}};var Ge=class extends A{constructor(e="wechat-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","wechat");chunk6C5TBG7Z_cjs.a(this,"name","WeChat Bot");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"accessToken",null);chunk6C5TBG7Z_cjs.a(this,"tokenExpireTime",0);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"processedMessageIds",new Set);chunk6C5TBG7Z_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 d=await utils.TruncateContent.truncate(s,{maxChars:i,label:"wechat message"});r=d.content,this.log.debug("sendOfficialMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:d.truncated?d.outputPath:void 0});}let c=(await 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(c.errcode!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`WeChat API error: ${c.errmsg}`);return c.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,s){let i=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let d=await utils.TruncateContent.truncate(s,{maxChars:i,label:"wecom message"});r=d.content,this.log.debug("sendWeComMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:d.truncated?d.outputPath:void 0});}let c=(await 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(c.errcode!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`WeCom API error: ${c.errmsg}`);return c.msgid??Date.now().toString()}async sendImage(e,s){let n;if(typeof s=="string")s.startsWith("http")?n=await this.uploadImage(s):n=s;else if(s instanceof URL)n=await this.uploadImage(s.toString());else throw 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 d=await utils.Fetch.get(e,{responseType:"arrayBuffer"});i=new Uint8Array(d.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}`,c=await utils.Fetch.postForm(a,[{name:"media",value:i,filename:"image.jpg"}],{timeout:3e5,headers:{Authorization:`Bearer ${this.accessToken}`}});if(c.data.errcode!==0||!c.data.media_id)throw f(this.id,"MESSAGE_SEND_FAILED",`Image upload failed: ${c.data.errmsg}`);return c.data.media_id}parseXmlMessage(e){let s=r=>e.match(new RegExp(`<${r}><!\\[CDATA\\[(.*?)\\]\\]></${r}>`))?.[1],n=r=>{let a=e.match(new RegExp(`<${r}>(\\d+)</${r}>`));return a?.[1]?parseInt(a[1],10):void 0},i=s("MsgType");return i?{ToUserName:s("ToUserName")??"",FromUserName:s("FromUserName")??"",CreateTime:n("CreateTime")??0,MsgType:i,Content:s("Content"),MsgId:n("MsgId"),PicUrl:s("PicUrl"),MediaId:s("MediaId")}:null}toGatewayMessage(e){let s=this.buildSessionId(this.id,e.FromUserName,e.FromUserName);return I(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="weixin";function zt(){let o=process.env.EASBOT_DATA_PATH;if(o)return utils.Filesystem.normalize(o);let t=w()?.Path?.data;return t?utils.Filesystem.normalize(t):utils.Filesystem.normalize(ue.join(os$1.homedir(),".easbot"))}function Es(){return utils.Filesystem.join(zt(),"gateway","channels","weixin")}function Xi(){return utils.Filesystem.join(zt(),"gateway")}function Yi(){return utils.Filesystem.join(zt(),"gateway","sessions")}function Rs(o,t){return `${Se}_${o}_${t}_${t}`}function Zi(){return {status:"idle",messageCount:0,lastMessageAt:null}}function er(o){let t={};return o.displayName&&(t.displayName=o.displayName),o.username&&(t.username=o.username),t}async function jt(){let o=new ie({baseDir:Xi()});return await o.initialize(),o}async function Ds(){let o=new se({storagePath:Yi()});return await o.initialize(),o}async function tr(o){let t=await jt();{let e=er(o),s=await t.findByPlatformId(Se,o.userId);if(s){let r=Date.now(),a={...s,profile:{...s.profile,...e},aliases:o.aliases?{...s.aliases,...o.aliases}:s.aliases,metadata:o.metadata?{...s.metadata??{},...o.metadata}:s.metadata,lastSeenAt:r};return {contact:await t.save(a),created:false}}return {contact:await t.create({platform:Se,stableId:o.userId,profile:e,aliases:o.aliases,metadata:o.metadata}),created:true}}}async function sr(o){let t=await Ds();{let e=o.channelId??"weixin-main",s=Rs(e,o.userId),n=t.get(s);if(n)return n.lastActiveAt=Date.now(),await t.set(n),{session:{id:n.id,channel:n.channel,backendSessionId:n.backendSessionId,subscribers:[...n.subscribers],state:n.state,createdAt:n.createdAt,lastActiveAt:n.lastActiveAt},created:false};let i=Date.now(),r={platform:Se,channelId:e,userId:o.userId,chatId:o.userId},a={id:s,channel:r,backendSessionId:null,subscribers:new Set,state:Zi(),createdAt:i,lastActiveAt:i};return await t.set(a),{session:{id:a.id,channel:a.channel,backendSessionId:a.backendSessionId,subscribers:[...a.subscribers],state:a.state,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt},created:true}}}async function yd(o){let t=await tr(o),e=await sr(o);return {contact:t.contact,session:e.session,created:{contact:t.created,session:e.created}}}async function bd(o,t="weixin-main"){let e=false,s=false;try{let n=await jt(),i=`${Se}:${o}`;e=await n.delete(i);}catch{}try{let n=await Ds(),i=Rs(t,o);n.get(i)&&(await n.delete(i),s=!0);}catch{}return {removed:{contact:e,session:s}}}async function Sd(){return (await(await jt()).listByPlatform(Se,1e4,0)).contacts}var Ls="https://ilinkai.weixin.qq.com",Kt="https://novac2c.cdn.weixin.qq.com/c2c",Gs=null;function Us(o){Gs=o;}function Ce(){let o=Gs||process.env.WEIXIN_STATE_DIR||Es()||ue.join(os$1.homedir(),".easbot","channels","weixin");return te.existsSync(o)||te.mkdirSync(o,{recursive:true}),o}function Vt(){return ue.join(Ce(),"account.json")}function Jt(){let o=Vt();if(!te.existsSync(o))return null;try{return JSON.parse(te.readFileSync(o,"utf-8"))}catch{return null}}function xd(o){let t=Vt();te.writeFileSync(t,JSON.stringify(o,null,2),"utf-8"),te.chmodSync(t,384);}function Md(){let o=Vt();te.existsSync(o)&&te.unlinkSync(o);}var gr="0.1.0";function Ue(){return {channel_version:gr}}function ur(){return Hi.randomBytes(4).toString("base64")}function pr(o){let t={"X-WECHAT-UIN":ur()};return o&&(t.AuthorizationType="ilink_bot_token",t.Authorization=`Bearer ${o}`),t}async function Fe(o,t,e,s,n=4e4,i){let r=await utils.Fetch.post(`${o}${t}`,e,{timeout:n,headers:pr(s),signal:i});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);return r.data}async function Fs(o,t,e,s){let n={get_updates_buf:e,base_info:Ue()};try{return await Fe(o,"/ilink/bot/getupdates",n,t,4e4,s)}catch(i){if(i instanceof Error&&i.name==="AbortError")return {ret:0,msgs:[],get_updates_buf:e};throw i}}async function Qt(o,t,e){let s={msg:e,base_info:Ue()};await Fe(o,"/ilink/bot/sendmessage",s,t);}async function Bs(o,t,e){return Fe(o,"/ilink/bot/getuploadurl",{...e,base_info:Ue()},t)}async function Os(o,t,e,s){return Fe(o,"/ilink/bot/getconfig",{ilink_user_id:e,context_token:s,base_info:Ue()},t)}async function $s(o,t,e){return Fe(o,"/ilink/bot/sendtyping",{...e,base_info:Ue()},t)}var Be={USER:1,BOT:2},R={TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},Xt={FINISH:2},It={IMAGE:1,VIDEO:2,FILE:3},Ws={TYPING:1,CANCEL:2};function Cr(o,t){let e=Hi.createCipheriv("aes-128-ecb",t,null);return Buffer.concat([e.update(o),e.final()])}function wr(o,t){let e=Hi.createDecipheriv("aes-128-ecb",t,null);return Buffer.concat([e.update(o),e.final()])}function vr(o,t){return `${t}/download?encrypted_query_param=${encodeURIComponent(o)}`}function Ir(o,t,e){return `${o}/upload?encrypted_query_param=${encodeURIComponent(t)}&filekey=${encodeURIComponent(e)}`}function Ar(o){let t=Buffer.from(o,"base64");if(t.length===16)return t;if(t.length===32&&/^[0-9a-fA-F]{32}$/.test(t.toString("ascii")))return Buffer.from(t.toString("ascii"),"hex");throw new Error(`Invalid aes_key: expected 16 raw bytes or 32 hex chars, got ${t.length} bytes`)}async function js(o){let t=vr(o.encryptQueryParam,o.cdnBaseUrl),e=await utils.Fetch.get(t,{responseType:"arrayBuffer",timeout:6e4});if(!e.ok)throw new Error(`CDN download failed: HTTP ${e.status}`);return wr(Buffer.from(e.data),Ar(o.aesKey))}async function qs(o){let t=te.readFileSync(o.filePath),e=t.length,s=Hi.createHash("md5").update(t).digest("hex"),n=Hi.randomBytes(16),i=Hi.randomBytes(16).toString("hex"),r=Cr(t,n),a=r.length,c=await Bs(o.apiBaseUrl,o.token,{filekey:i,media_type:o.mediaType,to_user_id:o.toUserId,rawsize:e,rawfilemd5:s,filesize:a,no_need_thumb:true,aeskey:n.toString("hex")});if(!c.upload_param)throw new Error("No upload_param in response");let d=Ir(o.cdnBaseUrl,c.upload_param,i),g=new Uint8Array(r),p=await utils.Fetch.request(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Blob([g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength)]),timeout:12e4,responseType:"json"});if(!p.ok)throw new Error(`CDN upload failed: HTTP ${p.status}`);return {encryptQueryParam:p.headers.get("x-encrypted-param")||"",aesKey:Buffer.from(n.toString("hex")).toString("base64"),fileSize:a,rawSize:e,fileName:ue.basename(o.filePath)}}function Ks(o){let t=ue.extname(o).toLowerCase(),e=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".heic"],s=[".mp4",".mov",".avi",".mkv",".webm"];return e.includes(t)?It.IMAGE:s.includes(t)?It.VIDEO:It.FILE}function Ys(){return ue.join(Ce(),"access.json")}function Zs(){return ue.join(Ce(),"pending-pairings.json")}function en(){let o=Zs();if(!te.existsSync(o))return {};try{return JSON.parse(te.readFileSync(o,"utf-8"))}catch{return {}}}function At(o){te.writeFileSync(Zs(),JSON.stringify(o,null,2),"utf-8");}function tn(){let o=Ys();if(!te.existsSync(o))return {policy:"pairing",allowFrom:[]};try{return JSON.parse(te.readFileSync(o,"utf-8"))}catch{return {policy:"pairing",allowFrom:[]}}}function Pr(o){te.writeFileSync(Ys(),JSON.stringify(o,null,2),"utf-8");}function sn(o){let t=tn();return t.policy==="disabled"?true:t.allowFrom.includes(o)}function nn(o){let t=en(),e=Date.now();for(let n of Object.keys(t))t[n].expiresAt<e&&delete t[n];for(let[n,i]of Object.entries(t))if(i.userId===o)return At(t),n;let s=String(Math.floor(1e5+Math.random()*9e5));return t[s]={userId:o,expiresAt:e+600*1e3},At(t),s}function Zd(o){let t=en(),e=t[o];if(!e||e.expiresAt<Date.now())return delete t[o],At(t),null;delete t[o],At(t);let s=tn();return s.allowFrom.includes(e.userId)||(s.allowFrom.push(e.userId),Pr(s)),e.userId}function xr(o){let t="",e=0;for(;e<o.length;)if(o.startsWith("```",e)){let s=e+3;for(;s<o.length&&o[s]!==`
|
|
21
|
+
`)}buildSessionId(e,s,n){let i=["feishu",e,s];return n&&i.push(n),i.join("_")}};var Ge=class extends A{constructor(e="wechat-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","wechat");chunk6C5TBG7Z_cjs.a(this,"name","WeChat Bot");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"accessToken",null);chunk6C5TBG7Z_cjs.a(this,"tokenExpireTime",0);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"processedMessageIds",new Set);chunk6C5TBG7Z_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 d=await utils.TruncateContent.truncate(s,{maxChars:i,label:"wechat message"});r=d.content,this.log.debug("sendOfficialMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:d.truncated?d.outputPath:void 0});}let c=(await 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(c.errcode!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`WeChat API error: ${c.errmsg}`);return c.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,s){let i=this.getCapabilities().maxMessageLength-500,r=s;if(s.length>i){let d=await utils.TruncateContent.truncate(s,{maxChars:i,label:"wecom message"});r=d.content,this.log.debug("sendWeComMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:d.truncated?d.outputPath:void 0});}let c=(await 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(c.errcode!==0)throw f(this.id,"MESSAGE_SEND_FAILED",`WeCom API error: ${c.errmsg}`);return c.msgid??Date.now().toString()}async sendImage(e,s){let n;if(typeof s=="string")s.startsWith("http")?n=await this.uploadImage(s):n=s;else if(s instanceof URL)n=await this.uploadImage(s.toString());else throw 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 d=await utils.Fetch.get(e,{responseType:"arrayBuffer"});i=new Uint8Array(d.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}`,c=await utils.Fetch.postForm(a,[{name:"media",value:i,filename:"image.jpg"}],{timeout:3e5,headers:{Authorization:`Bearer ${this.accessToken}`}});if(c.data.errcode!==0||!c.data.media_id)throw f(this.id,"MESSAGE_SEND_FAILED",`Image upload failed: ${c.data.errmsg}`);return c.data.media_id}parseXmlMessage(e){let s=r=>e.match(new RegExp(`<${r}><!\\[CDATA\\[(.*?)\\]\\]></${r}>`))?.[1],n=r=>{let a=e.match(new RegExp(`<${r}>(\\d+)</${r}>`));return a?.[1]?parseInt(a[1],10):void 0},i=s("MsgType");return i?{ToUserName:s("ToUserName")??"",FromUserName:s("FromUserName")??"",CreateTime:n("CreateTime")??0,MsgType:i,Content:s("Content"),MsgId:n("MsgId"),PicUrl:s("PicUrl"),MediaId:s("MediaId")}:null}toGatewayMessage(e){let s=this.buildSessionId(this.id,e.FromUserName,e.FromUserName);return I(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="weixin";function jt(){let o=process.env.EASBOT_DATA_PATH;if(o)return utils.Filesystem.normalize(o);let t=w()?.Path?.data;return t?utils.Filesystem.normalize(t):utils.Filesystem.normalize(ue.join(os$1.homedir(),".easbot"))}function Rs(){return utils.Filesystem.join(jt(),"gateway","channels","weixin")}function Xi(){return utils.Filesystem.join(jt(),"gateway")}function Yi(){return utils.Filesystem.join(jt(),"gateway","sessions")}function Ds(o,t){return `${Se}_${o}_${t}_${t}`}function Zi(){return {status:"idle",messageCount:0,lastMessageAt:null}}function er(o){let t={};return o.displayName&&(t.displayName=o.displayName),o.username&&(t.username=o.username),t}async function qt(){let o=new ie({baseDir:Xi()});return await o.initialize(),o}async function Ns(){let o=new se({storagePath:Yi()});return await o.initialize(),o}async function tr(o){let t=await qt();{let e=er(o),s=await t.findByPlatformId(Se,o.userId);if(s){let r=Date.now(),a={...s,profile:{...s.profile,...e},aliases:o.aliases?{...s.aliases,...o.aliases}:s.aliases,metadata:o.metadata?{...s.metadata??{},...o.metadata}:s.metadata,lastSeenAt:r};return {contact:await t.save(a),created:false}}return {contact:await t.create({platform:Se,stableId:o.userId,profile:e,aliases:o.aliases,metadata:o.metadata}),created:true}}}async function sr(o){let t=await Ns();{let e=o.channelId??"weixin-main",s=Ds(e,o.userId),n=t.get(s);if(n)return n.lastActiveAt=Date.now(),await t.set(n),{session:{id:n.id,channel:n.channel,backendSessionId:n.backendSessionId,subscribers:[...n.subscribers],state:n.state,createdAt:n.createdAt,lastActiveAt:n.lastActiveAt},created:false};let i=Date.now(),r={platform:Se,channelId:e,userId:o.userId,chatId:o.userId},a={id:s,channel:r,backendSessionId:null,subscribers:new Set,state:Zi(),createdAt:i,lastActiveAt:i};return await t.set(a),{session:{id:a.id,channel:a.channel,backendSessionId:a.backendSessionId,subscribers:[...a.subscribers],state:a.state,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt},created:true}}}async function Cd(o){let t=await tr(o),e=await sr(o);return {contact:t.contact,session:e.session,created:{contact:t.created,session:e.created}}}async function wd(o,t="weixin-main"){let e=false,s=false;try{let n=await qt(),i=`${Se}:${o}`;e=await n.delete(i);}catch{}try{let n=await Ns(),i=Ds(t,o);n.get(i)&&(await n.delete(i),s=!0);}catch{}return {removed:{contact:e,session:s}}}async function vd(){return (await(await qt()).listByPlatform(Se,1e4,0)).contacts}var Vt="https://ilinkai.weixin.qq.com",Jt="https://novac2c.cdn.weixin.qq.com/c2c",Gs=null;function Us(o){Gs=o;}function Ce(){let o=Gs||process.env.WEIXIN_STATE_DIR||Rs()||ue.join(os$1.homedir(),".easbot","channels","weixin");return te.existsSync(o)||te.mkdirSync(o,{recursive:true}),o}function Qt(){return ue.join(Ce(),"account.json")}function It(){let o=Qt();if(!te.existsSync(o))return null;try{return JSON.parse(te.readFileSync(o,"utf-8"))}catch{return null}}function Td(o){let t=Qt();te.writeFileSync(t,JSON.stringify(o,null,2),"utf-8"),te.chmodSync(t,384);}function _d(){let o=Qt();te.existsSync(o)&&te.unlinkSync(o);}var gr="0.1.0";function Ue(){return {channel_version:gr}}function ur(){return Hi.randomBytes(4).toString("base64")}function pr(o){let t={"X-WECHAT-UIN":ur()};return o&&(t.AuthorizationType="ilink_bot_token",t.Authorization=`Bearer ${o}`),t}async function Fe(o,t,e,s,n=4e4,i){let r=await utils.Fetch.post(`${o}${t}`,e,{timeout:n,headers:pr(s),signal:i});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);return r.data}async function Fs(o,t,e,s){let n={get_updates_buf:e,base_info:Ue()};try{return await Fe(o,"/ilink/bot/getupdates",n,t,4e4,s)}catch(i){if(i instanceof Error&&i.name==="AbortError")return {ret:0,msgs:[],get_updates_buf:e};throw i}}async function Xt(o,t,e){let s={msg:e,base_info:Ue()};await Fe(o,"/ilink/bot/sendmessage",s,t);}async function Bs(o,t,e){return Fe(o,"/ilink/bot/getuploadurl",{...e,base_info:Ue()},t)}async function Os(o,t,e,s){return Fe(o,"/ilink/bot/getconfig",{ilink_user_id:e,context_token:s,base_info:Ue()},t)}async function $s(o,t,e){return Fe(o,"/ilink/bot/sendtyping",{...e,base_info:Ue()},t)}var Be={USER:1,BOT:2},R={TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},Yt={FINISH:2},At={IMAGE:1,VIDEO:2,FILE:3},Ws={TYPING:1,CANCEL:2};function Cr(o,t){let e=Hi.createCipheriv("aes-128-ecb",t,null);return Buffer.concat([e.update(o),e.final()])}function wr(o,t){let e=Hi.createDecipheriv("aes-128-ecb",t,null);return Buffer.concat([e.update(o),e.final()])}function vr(o,t){return `${t}/download?encrypted_query_param=${encodeURIComponent(o)}`}function Ir(o,t,e){return `${o}/upload?encrypted_query_param=${encodeURIComponent(t)}&filekey=${encodeURIComponent(e)}`}function Ar(o){let t=Buffer.from(o,"base64");if(t.length===16)return t;if(t.length===32&&/^[0-9a-fA-F]{32}$/.test(t.toString("ascii")))return Buffer.from(t.toString("ascii"),"hex");throw new Error(`Invalid aes_key: expected 16 raw bytes or 32 hex chars, got ${t.length} bytes`)}async function js(o){let t=vr(o.encryptQueryParam,o.cdnBaseUrl),e=await utils.Fetch.get(t,{responseType:"arrayBuffer",timeout:6e4});if(!e.ok)throw new Error(`CDN download failed: HTTP ${e.status}`);return wr(Buffer.from(e.data),Ar(o.aesKey))}async function qs(o){let t=te.readFileSync(o.filePath),e=t.length,s=Hi.createHash("md5").update(t).digest("hex"),n=Hi.randomBytes(16),i=Hi.randomBytes(16).toString("hex"),r=Cr(t,n),a=r.length,c=await Bs(o.apiBaseUrl,o.token,{filekey:i,media_type:o.mediaType,to_user_id:o.toUserId,rawsize:e,rawfilemd5:s,filesize:a,no_need_thumb:true,aeskey:n.toString("hex")});if(!c.upload_param)throw new Error("No upload_param in response");let d=Ir(o.cdnBaseUrl,c.upload_param,i),g=new Uint8Array(r),p=await utils.Fetch.request(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Blob([g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength)]),timeout:12e4,responseType:"json"});if(!p.ok)throw new Error(`CDN upload failed: HTTP ${p.status}`);return {encryptQueryParam:p.headers.get("x-encrypted-param")||"",aesKey:Buffer.from(n.toString("hex")).toString("base64"),fileSize:a,rawSize:e,fileName:ue.basename(o.filePath)}}function Ks(o){let t=ue.extname(o).toLowerCase(),e=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".heic"],s=[".mp4",".mov",".avi",".mkv",".webm"];return e.includes(t)?At.IMAGE:s.includes(t)?At.VIDEO:At.FILE}function Ys(){return ue.join(Ce(),"access.json")}function Zs(){return ue.join(Ce(),"pending-pairings.json")}function en(){let o=Zs();if(!te.existsSync(o))return {};try{return JSON.parse(te.readFileSync(o,"utf-8"))}catch{return {}}}function Pt(o){te.writeFileSync(Zs(),JSON.stringify(o,null,2),"utf-8");}function tn(){let o=Ys();if(!te.existsSync(o))return {policy:"pairing",allowFrom:[]};try{return JSON.parse(te.readFileSync(o,"utf-8"))}catch{return {policy:"pairing",allowFrom:[]}}}function Pr(o){te.writeFileSync(Ys(),JSON.stringify(o,null,2),"utf-8");}function sn(o){let t=tn();return t.policy==="disabled"?true:t.allowFrom.includes(o)}function nn(o){let t=en(),e=Date.now();for(let n of Object.keys(t))t[n].expiresAt<e&&delete t[n];for(let[n,i]of Object.entries(t))if(i.userId===o)return Pt(t),n;let s=String(Math.floor(1e5+Math.random()*9e5));return t[s]={userId:o,expiresAt:e+600*1e3},Pt(t),s}function sg(o){let t=en(),e=t[o];if(!e||e.expiresAt<Date.now())return delete t[o],Pt(t),null;delete t[o],Pt(t);let s=tn();return s.allowFrom.includes(e.userId)||(s.allowFrom.push(e.userId),Pr(s)),e.userId}function xr(o){let t="",e=0;for(;e<o.length;)if(o.startsWith("```",e)){let s=e+3;for(;s<o.length&&o[s]!==`
|
|
22
22
|
`;)s++;s<o.length&&s++;let n=s;for(;s<o.length;){if(o.startsWith("```",s)){for(t+=o.slice(n,s),s+=3;s<o.length&&o[s]!==`
|
|
23
23
|
`;)s++;s<o.length&&s++;break}s++;}s>=o.length&&!o.startsWith("```",s-3)&&(t+=o.slice(e)),e=s;}else t+=o[e],e++;return t}function an(o){return xr(o).replace(/`([^`]+)`/g,"$1").replace(/\*\*\*(.+?)\*\*\*/g,"$1").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/___(.+?)___/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/~~(.+?)~~/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1 ($2)").replace(/!\[([^\]]*)\]\([^)]+\)/g,"[$1]").replace(/^>\s+/gm,"").replace(/^[-*_]{3,}$/gm,"---").replace(/^[\s]*[-*+]\s+/gm,"- ").replace(/^[\s]*(\d+)\.\s+/gm,"$1. ").replace(/\n{3,}/g,`
|
|
24
24
|
|
|
25
|
-
`).trim()}async function Oe(o){let t=Hi.randomUUID();return await
|
|
25
|
+
`).trim()}async function Oe(o){let t=Hi.randomUUID();return await Xt(o.baseUrl,o.token,{to_user_id:o.to,from_user_id:"",client_id:t,message_type:Be.BOT,message_state:Yt.FINISH,context_token:o.contextToken,item_list:[{type:R.TEXT,text_item:{text:an(o.text)}}]}),{messageId:t}}async function Mr(o){let t="";for(let e of o.items)t=Hi.randomUUID(),await Xt(o.baseUrl,o.token,{to_user_id:o.to,from_user_id:"",client_id:t,message_type:Be.BOT,message_state:Yt.FINISH,context_token:o.contextToken,item_list:[e]});return t}async function on(o){let t=Ks(o.filePath),e=await qs({filePath:o.filePath,toUserId:o.to,mediaType:t,apiBaseUrl:o.baseUrl,token:o.token,cdnBaseUrl:o.cdnBaseUrl}),s={encrypt_query_param:e.encryptQueryParam,aes_key:e.aesKey,encrypt_type:1},n=[];switch(o.text&&n.push({type:R.TEXT,text_item:{text:an(o.text)}}),t){case 1:n.push({type:R.IMAGE,image_item:{media:s,mid_size:e.fileSize}});break;case 2:n.push({type:R.VIDEO,video_item:{media:s,video_size:e.fileSize}});break;default:n.push({type:R.FILE,file_item:{media:s,file_name:e.fileName,len:String(e.rawSize)}});break}return {messageId:await Mr({items:n,to:o.to,baseUrl:o.baseUrl,token:o.token,contextToken:o.contextToken})}}var Nr=/^\s*(y|yes|n|no)\s+([a-km-z]{5})\s*$/i,ce=utils.Log.create({service:"weixin-sdk"}),dn=new Map;function xt(o){return dn.get(o)}function gn(){return ue.join(Ce(),"cursor.txt")}function Lr(){let o=gn();return te.existsSync(o)?te.readFileSync(o,"utf-8").trim():""}function Gr(o){te.writeFileSync(gn(),o,"utf-8");}function Ur(o){if(o)return o;let t=w()?.Path?.data||process.env.EASBOT_DATA_PATH;return t?utils.Filesystem.join(t,"gateway","downloads"):ue.join(os$1.tmpdir(),"weixin-media")}async function Fr(o,t,e){let s,n,i="",r="";switch(o.type){case R.IMAGE:s=o.image_item?.media?.encrypt_query_param,n=o.image_item?.aeskey?Buffer.from(o.image_item.aeskey,"hex").toString("base64"):o.image_item?.media?.aes_key,i=".jpg",r="image";break;case R.VOICE:s=o.voice_item?.media?.encrypt_query_param,n=o.voice_item?.media?.aes_key,i=".silk",r="voice";break;case R.FILE:s=o.file_item?.media?.encrypt_query_param,n=o.file_item?.media?.aes_key,i=o.file_item?.file_name?`.${o.file_item.file_name.split(".").pop()}`:"",r="file";break;case R.VIDEO:s=o.video_item?.media?.encrypt_query_param,n=o.video_item?.media?.aes_key,i=".mp4",r="video";break;default:return null}if(!s||!n)return null;try{let a=await js({encryptQueryParam:s,aesKey:n,cdnBaseUrl:t}),c=Ur(e);te.existsSync(c)||te.mkdirSync(c,{recursive:!0});let d=o.file_item?.file_name||`${Date.now()}${i}`,g=ue.basename(d),p=ue.join(c,g);return te.writeFileSync(p,a),{path:p,type:r}}catch(a){return ce.error("failed to download media",{error:String(a)}),null}}function Br(o){let t=o.match(Nr);if(!t)return null;let e=t[1]?.toLowerCase().startsWith("y")?"allow":"deny",s=t[2]?.toLowerCase();return s?{requestId:s,behavior:e}:null}async function un(o){let{baseUrl:t,cdnBaseUrl:e,token:s,onMessage:n,onPermissionResponse:i,abortSignal:r,downloadDir:a}=o,c=Lr(),d=0;for(ce.info("starting message poll loop");!r.aborted;)try{let g=await Fs(t,s,c,r);if(g.errcode===-14){ce.warn("session expired (errcode -14), pausing 30s"),await new Promise(p=>setTimeout(p,3e4));continue}if(g.ret!==0&&g.ret!==void 0)throw new Error(`getUpdates error: ret=${g.ret} errcode=${g.errcode} ${g.errmsg}`);if(d=0,g.get_updates_buf&&(c=g.get_updates_buf,Gr(c)),g.msgs&&g.msgs.length>0)for(let p of g.msgs)await Or(p,{baseUrl:t,cdnBaseUrl:e,token:s,onMessage:n,onPermissionResponse:i,downloadDir:a});}catch(g){if(r.aborted)break;d+=1,ce.error("poll error",{consecutiveErrors:d,error:g instanceof Error?g.message:String(g)}),d>=3?(ce.warn("too many consecutive errors, backing off 30s"),await new Promise(p=>setTimeout(p,3e4)),d=0):await new Promise(p=>setTimeout(p,2e3));}ce.info("poll loop stopped");}async function Or(o,t){if(o.message_type!==Be.USER)return;let e=o.from_user_id;if(!e)return;if(o.context_token&&dn.set(e,o.context_token),!sn(e)){let r=nn(e);try{await Oe({to:e,text:`Your pairing code is: ${r}
|
|
26
26
|
|
|
27
27
|
Ask the operator to confirm:
|
|
28
28
|
easbot weixin access pair ${r}`,baseUrl:t.baseUrl,token:t.token,contextToken:o.context_token||""});}catch(a){ce.error("failed to send pairing code",{fromUserId:e,error:String(a)});}return}let s="",n,i;if(o.item_list){for(let r of o.item_list)if(r.type===R.TEXT&&r.text_item?.text)s+=`${s?`
|
|
29
29
|
`:""}${r.text_item.text}`;else if(r.type===R.IMAGE||r.type===R.VOICE||r.type===R.FILE||r.type===R.VIDEO){let a=await Fr(r,t.cdnBaseUrl,t.downloadDir);a&&(n=a.path,i=a.type),r.type===R.VOICE&&r.voice_item?.text&&(s+=`${s?`
|
|
30
|
-
`:""}[Voice transcription]: ${r.voice_item.text}`);}}if(!(!s&&!n)){if(s&&t.onPermissionResponse){let r=Br(s);if(r){let{consumePendingPermission:a}=await import('./permissions-CQIMDMA3.cjs'),c=a(r.requestId,e);if(c){await t.onPermissionResponse({requestId:c.request_id,behavior:r.behavior,fromUserId:e});return}}}await t.onMessage({fromUserId:e,messageId:String(o.message_id||""),text:s||"(media attachment)",attachmentPath:n,attachmentType:i});}}var $e=class extends A{constructor(e="weixin-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","weixin");chunk6C5TBG7Z_cjs.a(this,"name","WeChat iLink");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"account",null);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"processedMessageIds",new Set);chunk6C5TBG7Z_cjs.a(this,"sentMessages",new Map);chunk6C5TBG7Z_cjs.a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});chunk6C5TBG7Z_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");this.botConfig=this.config.platform,Us(this.resolveStateDir());let e=
|
|
30
|
+
`:""}[Voice transcription]: ${r.voice_item.text}`);}}if(!(!s&&!n)){if(s&&t.onPermissionResponse){let r=Br(s);if(r){let{consumePendingPermission:a}=await import('./permissions-CQIMDMA3.cjs'),c=a(r.requestId,e);if(c){await t.onPermissionResponse({requestId:c.request_id,behavior:r.behavior,fromUserId:e});return}}}await t.onMessage({fromUserId:e,messageId:String(o.message_id||""),text:s||"(media attachment)",attachmentPath:n,attachmentType:i});}}function Jr(o,t){return o===t?true:!o||!t?false:o.token===t.token&&o.userId===t.userId&&o.baseUrl===t.baseUrl&&o.savedAt===t.savedAt}var $e=class extends A{constructor(e="weixin-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","weixin");chunk6C5TBG7Z_cjs.a(this,"name","WeChat iLink");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"account",null);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"processedMessageIds",new Set);chunk6C5TBG7Z_cjs.a(this,"sentMessages",new Map);chunk6C5TBG7Z_cjs.a(this,"retryState",{attempts:0,maxAttempts:3,initialDelay:1e3,maxDelay:3e4});chunk6C5TBG7Z_cjs.a(this,"pollingStopped",false);chunk6C5TBG7Z_cjs.a(this,"accountWatcher",null);chunk6C5TBG7Z_cjs.a(this,"reloadDebounceTimer",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw f(this.id,"CHANNEL_INIT_FAILED","Config not set");this.botConfig=this.config.platform,Us(this.resolveStateDir());let e=It();if(!e?.token)throw f(this.id,"CONFIG_MISSING_REQUIRED","WeChat account not connected. Run `easbot weixin login` to bind a personal WeChat account.");this.account={token:e.token,baseUrl:e.baseUrl||this.botConfig.baseUrl||Vt,userId:e.userId,savedAt:e.savedAt},this.abortController=new AbortController,this.startStateFileWatchers(),this.runPollLoop().catch(s=>{this.log.error("poll loop crashed",{error:String(s)});}),this.log.info("Weixin plugin started",{userId:this.account.userId,baseUrl:this.account.baseUrl,stateDir:this.resolveStateDir()});}resolveStateDir(){let e=this.botConfig?.stateDir;if(e)return e;let s=w()?.Path?.data;return s?utils.Filesystem.join(s,"gateway","channels","weixin"):ue.join(os$1.homedir(),".easbot","channels","weixin")}async doStop(){this.stopStateFileWatchers(),this.abortController?.abort(),this.abortController=null,this.processedMessageIds.clear(),this.sentMessages.clear(),this.pollingStopped=false,this.retryState.attempts=0,this.botConfig=null,this.account=null,this.log.debug("Weixin plugin stopped");}async doHealthCheck(){if(this._status!=="running")return false;if(this.pollingStopped)return this.log.warn("weixin poll loop was stopped, attempting restart"),this.restartPollLoop(),true;if(this.abortController?.signal.aborted)return false;let e=It();return !!e&&!!e.token}startStateFileWatchers(){let e=this.resolveStateDir();if(!te.existsSync(e)){this.log.warn("weixin state dir missing, skip watcher",{stateDir:e});return}try{this.accountWatcher=te.watch(e,{persistent:!1},(s,n)=>{(n==="account.json"||n==="access.json")&&this.scheduleReloadAccount();}),this.accountWatcher.on("error",s=>{this.log.error("state file watcher error",{error:String(s)});}),this.log.debug("weixin state file watcher started",{stateDir:e});}catch(s){this.log.error("failed to start state file watcher",{error:String(s)});}}stopStateFileWatchers(){this.reloadDebounceTimer&&(clearTimeout(this.reloadDebounceTimer),this.reloadDebounceTimer=null),this.accountWatcher&&(this.accountWatcher.close(),this.accountWatcher=null);}scheduleReloadAccount(){this.reloadDebounceTimer&&clearTimeout(this.reloadDebounceTimer),this.reloadDebounceTimer=setTimeout(()=>{this.reloadDebounceTimer=null,this.reloadAccountIfChanged();},200);}reloadAccountIfChanged(){let e=It();if(!e){this.log.warn("account.json deleted or unreadable, leaving plugin running");return}let s=this.account,n=e.baseUrl||this.botConfig?.baseUrl||Vt,i={token:e.token,baseUrl:n,userId:e.userId,savedAt:e.savedAt};Jr(s,i)||(this.log.info("weixin account changed, reloading",{oldUserId:s?.userId,newUserId:e.userId}),this.account=i,this._status==="running"&&this.restartPollLoop());}async send(e){if(!this.account)throw f(this.id,"MESSAGE_SEND_FAILED","Weixin plugin not started");let s=e.metadata.channel.userId;if(!s)throw f(this.id,"MESSAGE_SEND_FAILED","User ID is required");let n=this.extractText(e),i=this.botConfig?.cdnBaseUrl||Jt,r=xt(s)||"",a=this.botConfig?.maxMessageLength??4e3,c=n;if(n.length>a){let h=await utils.TruncateContent.truncate(n,{maxChars:a,label:"weixin message"});c=h.content,this.log.debug("send: message truncated",{originalLength:n.length,maxLength:a,outputPath:h.truncated?h.outputPath:void 0});}let d=e.content.find(h=>h.type==="image"),g=e.content.find(h=>h.type==="file"),p;if(d||g){let h=d??g,b="image"in h?h.image:h.data,S=await this.resolveAttachmentToPath(b,this.id);p=await on({filePath:S,to:s,text:c,baseUrl:this.account.baseUrl,token:this.account.token,contextToken:r,cdnBaseUrl:i});}else p=await Oe({to:s,text:c,baseUrl:this.account.baseUrl,token:this.account.token,contextToken:r});return this.sentMessages.set(e.id,{userId:s,clientId:p.messageId,timestamp:Date.now()}),p.messageId}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:false,supportsThread:false,supportsEdit:false,supportsDelete:false,supportsTyping:true,supportsBatchSend:false,supportsMarkdown:false,supportsHtml:false,supportsDeliveryReceipt:false,supportsReadReceipt:false,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:this.botConfig?.maxMessageLength??4e3,maxMediaCount:1}}resolveDownloadDir(){let e=w()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot";return utils.Filesystem.join(e,"gateway","downloads")}async runPollLoop(){if(!this.account||!this.abortController)return;let e=this.botConfig?.cdnBaseUrl||Jt,s=this.resolveDownloadDir();await utils.Filesystem.mkdir(s,{recursive:true});try{await un({baseUrl:this.account.baseUrl,cdnBaseUrl:e,token:this.account.token,onMessage:async n=>this.handleWeixinMessage(n),abortSignal:this.abortController.signal,downloadDir:s});}catch(n){this.log.error("poll loop crashed",{error:String(n)}),this.pollingStopped=true;}}restartPollLoop(){this.account&&(this.retryState.attempts=0,this.pollingStopped=false,this.abortController=new AbortController,this.runPollLoop(),this.log.debug("weixin poll loop restarted"));}async handleWeixinMessage(e){this.updateActivity();let s=e.messageId||`${e.fromUserId}:${e.text}`;if(this.processedMessageIds.has(s)){this.log.debug("duplicate weixin message ignored",{messageKey:s});return}if(this.processedMessageIds.add(s),this.processedMessageIds.size>1e4){let a=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(a.slice(-5e3));}let n=this.buildSessionId(this.id,e.fromUserId,e.fromUserId),i={platform:this.platform,channelId:this.id,userId:e.fromUserId,chatId:e.fromUserId,chatType:"private"};if(e.text.trim().startsWith("/")){let a=await this.processCommand({text:e.text,sessionId:n,chatId:e.fromUserId,channelInfo:i,messageId:e.messageId});if(a.handled){a.reply?await this.sendCommandReply(e.fromUserId,a.reply):a.gatewayMessage&&await this.handleMessage(a.gatewayMessage);return}}let r=I(n,"input",await this.parseContent(e),{channel:i,context:{messageId:e.messageId,source:"ilink"}});await this.handleMessage(r);}async sendCommandReply(e,s){if(!this.account)return;let n=xt(e)??"";try{await Oe({to:e,text:s,baseUrl:this.account.baseUrl,token:this.account.token,contextToken:n}),this.log.debug("weixin command reply sent",{toUserId:e,length:s.length});}catch(i){this.log.error("weixin command reply failed",{toUserId:e,error:String(i)});}}async parseContent(e){let s=[],n=w()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=utils.Filesystem.join(n,"gateway","downloads");if(e.attachmentPath){let r=url.pathToFileURL(e.attachmentPath).href,a=utils.Filesystem.mimeType(e.attachmentPath),c=e.attachmentPath.split(/[\\/]/).pop()||e.attachmentPath;if(e.attachmentType==="image"){let d=a.startsWith("image/")?a:"image/jpeg";s.push({type:"image",image:r,mime:d});}else if(e.attachmentType==="voice")this.log.debug("weixin voice: skip raw attachment, transcription in text",{attachmentPath:e.attachmentPath});else if(utils.Filesystem.isTextMime(a))try{let d=await $.readFile(e.attachmentPath,"utf-8"),g=await utils.TruncateContent.truncate(d,{maxChars:5e3,label:`file: ${c}`});s.push({type:"text",text:`\u{1F4CE} File: ${c}
|
|
31
31
|
|
|
32
|
-
${g.content}`}),this.log.debug("weixin text file inlined",{fileName:c,mime:a,length:d.length});}catch(d){this.log.warn("weixin text file read failed, fallback to file part",{fileName:c,error:String(d)}),s.push({type:"file",data:r,mime:a});}else s.push({type:"file",data:r,mime:a});this.log.debug("weixin attachment resolved",{downloadDir:i,source:e.attachmentPath});}return e.text&&s.push({type:"text",text:e.text}),s}async resolveAttachmentToPath(e,s){if(typeof e=="string")return /^https?:\/\//i.test(e)?this.downloadUrlToLocal(e,s):e.startsWith("file://")?url.fileURLToPath(e):e;if(e instanceof URL)return /^https?:$/i.test(e.protocol)?this.downloadUrlToLocal(e.toString(),s):this.resolveAttachmentToPath(e.toString(),s);let n=w()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=utils.Filesystem.join(n,"gateway","downloads");await utils.Filesystem.mkdir(i,{recursive:true});let r=utils.Filesystem.join(i,`${s}_${Date.now()}.bin`);return await utils.Filesystem.write(r,Buffer.from(e)),r}async downloadUrlToLocal(e,s){let n=w()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=utils.Filesystem.join(n,"gateway","downloads");await utils.Filesystem.mkdir(i,{recursive:true});let r=new URL(e).pathname.split("/").pop()||`weixin_${Date.now()}`,a=utils.Filesystem.join(i,`${s}_${r}`);this.log.debug("weixin download remote attachment",{url:e,dest:a});let c=await utils.Fetch.get(e,{responseType:"arrayBuffer",timeout:12e4});if(!c.ok)throw new Error(`Failed to download attachment from ${e}: HTTP ${c.status}`);return await utils.Filesystem.write(a,Buffer.from(c.data)),this.log.debug("weixin remote attachment downloaded",{url:e,dest:a,bytes:c.data.byteLength}),a}async sendTyping(e){if(!this.account)return;let s=Pt(e);if(!s){this.log.debug("sendTyping skipped: no context token",{userId:e});return}try{let n=await Os(this.account.baseUrl,this.account.token,e,s);n.typing_ticket&&await $s(this.account.baseUrl,this.account.token,{ilink_user_id:e,typing_ticket:n.typing_ticket,status:Ws.TYPING});}catch(n){this.log.debug("sendTyping failed",{userId:e,error:String(n)});}}buildSessionId(e,s,n){let i=n??s;return `${this.platform}_${e}_${s}_${i}`}};var We=class extends A{constructor(e="webchat-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","webchat");chunk6C5TBG7Z_cjs.a(this,"name","WebChat");chunk6C5TBG7Z_cjs.a(this,"webChatConfig",null);chunk6C5TBG7Z_cjs.a(this,"connections",new Map);chunk6C5TBG7Z_cjs.a(this,"heartbeatInterval",null);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"processedMessageIds",new Set);chunk6C5TBG7Z_cjs.a(this,"sentMessages",new Map);chunk6C5TBG7Z_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(!n)throw f(this.id,"MESSAGE_SEND_FAILED","User ID is required");let i=this.findConnectionByUser(n);if(!i)throw f(this.id,"MESSAGE_SEND_FAILED","User not connected");let r={type:"message",sessionId:s,content:e.content,metadata:e.metadata};return i.ws.send(JSON.stringify(r)),i.lastActivity=Date.now(),this.sentMessages.set(e.id,{sessionId:s,messageId:e.id,timestamp:Date.now()}),e.id}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:true,supportsEdit:true,supportsDelete:true,supportsTyping:true,supportsBatchSend:true,supportsMarkdown:true,supportsHtml:true,supportsDeliveryReceipt:true,supportsReadReceipt:true,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:1e5,maxMediaCount:20}}getWebSocketServer(){return this.wsServer}async handleConnection(e,s){let n=this.generateConnectionId();if(this.connections.size>=(this.webChatConfig?.maxConnections??1e3)){e.close(1013,"Maximum connections reached");return}let i={id:n,ws:e,userId:s,lastActivity:Date.now()};this.connections.set(n,i),e.onmessage=r=>{this.handleWebSocketMessage(i,r.data.toString());},e.onclose=()=>{this.connections.delete(n),this.log.debug("WebSocket closed",{connId:n,userId:s});},e.onerror=r=>{this.log.error("WebSocket error",{connId:n,userId:s,error:String(r)});},this.log.debug("WebSocket connected",{connId:n,userId:s});}getConnectionCount(){return this.connections.size}getWsServerConnectionCount(){return this.wsServer?.getConnectionCount()??0}async startWebSocketServer(){if(!this.webChatConfig)return;let e={port:this.webChatConfig.port,hostname:this.webChatConfig.hostname,path:this.webChatConfig.path,maxConnections:this.webChatConfig.maxConnections,connectionTimeout:this.webChatConfig.connectionTimeout,heartbeatInterval:this.webChatConfig.heartbeatInterval,sessionExpireMs:this.webChatConfig.sessionExpireMs,https:this.webChatConfig.https};this.wsServer=new re(e),await this.wsServer.start(),this.log.info("WebSocket server started",{url:`${this.webChatConfig.https?.enabled?"wss":"ws"}://${this.webChatConfig.hostname}:${this.webChatConfig.port}${this.webChatConfig.path}`});}async handleWebSocketMessage(e,s){this.updateActivity(),e.lastActivity=Date.now();try{let n=JSON.parse(s);switch(n.type){case "message":await this.handleChatMessage(e,n);break;case "ping":e.ws.send(JSON.stringify({type:"pong"}));break;case "subscribe":n.sessionId&&(e.sessionId=n.sessionId);break;case "unsubscribe":e.sessionId=void 0;break;case "message_delivered":await this.handleMessageAcknowledgment(e,n,"message_delivered");break;case "message_read":await this.handleMessageAcknowledgment(e,n,"message_read");break}}catch(n){this.log.error("Failed to handle WebSocket message",{error:String(n)});}}async handleMessageAcknowledgment(e,s,n){s.messageId&&(this.log.debug("message acknowledgment received",{type:n,messageId:s.messageId,userId:e.userId}),this.messageHandler&&await this.messageHandler.onEvent({type:n,channelId:this.id,data:{messageId:s.messageId,sessionId:e.sessionId,platform:"webchat",channelId:this.id,userId:e.userId},timestamp:Date.now()}));}async handleChatMessage(e,s){if(!s.content||!s.sessionId||this.processedMessageIds.has(s.messageId??""))return;if(s.messageId&&(this.processedMessageIds.add(s.messageId),this.processedMessageIds.size>1e4)){let r=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(r.slice(-5e3));}let n=s.content.find(r=>r.type==="text");if(n?.text.trim().startsWith("/")){let r=this.buildSessionId(this.id,s.sessionId,e.userId),a=await this.processCommand({text:n.text,sessionId:r,chatId:s.sessionId,channelInfo:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},messageId:s.messageId});if(a.handled){if(a.reply){let c=I(s.sessionId,"output",[{type:"text",text:a.reply}],{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},context:{conversationId:s.sessionId},...s.metadata});await this.send(c);}else a.gatewayMessage&&await this.handleMessage(a.gatewayMessage);return}}let i=I(s.sessionId,"input",s.content,{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},context:{conversationId:s.sessionId},...s.metadata});await this.handleMessage(i);}startHeartbeat(){let e=this.webChatConfig?.heartbeatInterval??3e4;this.heartbeatInterval=setInterval(()=>{let s=Date.now(),n=this.webChatConfig?.connectionTimeout??6e4;for(let[i,r]of this.connections)s-r.lastActivity>n&&(this.log.debug("Closing inactive connection",{connId:i}),r.ws.close(1001,"Connection timeout"),this.connections.delete(i));},e);}findConnectionByUser(e){for(let s of this.connections.values())if(s.userId===e)return s}generateConnectionId(){return `conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}};var He=class extends A{constructor(e="signal-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","signal");chunk6C5TBG7Z_cjs.a(this,"name","Signal Bot");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"lastTimestamp",0);chunk6C5TBG7Z_cjs.a(this,"pollingIntervalMs",5e3);chunk6C5TBG7Z_cjs.a(this,"processedMessageIds",new Set);chunk6C5TBG7Z_cjs.a(this,"sentMessages",new Map);chunk6C5TBG7Z_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:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:65536,maxMediaCount:10}}startPolling(){this.pollLoop(),this.log.info("Polling started",{interval:this.pollingIntervalMs});}pollLoop(){if(this.abortController?.signal.aborted)return;(async()=>{try{await this.poll();}catch(s){this.log.error("Polling error",{error:String(s)});}})().then(()=>{this.abortController?.signal.aborted||setTimeout(()=>this.pollLoop(),this.pollingIntervalMs);});}async poll(){let e=await this.receiveMessages(this.lastTimestamp);for(let s of e){let n=`${s.envelope.sourceNumber}_${s.envelope.timestamp}`;if(!this.processedMessageIds.has(n)){if(this.processedMessageIds.add(n),this.processedMessageIds.size>1e4){let i=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(i.slice(-5e3));}this.lastTimestamp=s.envelope.timestamp,s.envelope.dataMessage&&await this.handleSignalMessage(s);}}}async handleSignalMessage(e){this.updateActivity();let s=e.envelope.dataMessage?.message;if(s?.trim().startsWith("/")){let i=this.buildSessionId(this.id,e.envelope.sourceNumber),r=await this.processCommand({text:s,sessionId:i,chatId:e.envelope.sourceNumber,channelInfo:{platform:"signal",channelId:this.id,userId:e.envelope.sourceNumber,chatId:e.envelope.sourceNumber,timestamp:e.envelope.dataMessage?.timestamp},messageId:e.envelope.dataMessage?.timestamp?.toString()});if(r.handled){r.reply?await this.sendMessage(e.envelope.sourceNumber,r.reply):r.gatewayMessage&&await this.handleMessage(r.gatewayMessage);return}}let n=await this.toGatewayMessage(e);await this.handleMessage(n);}async toGatewayMessage(e){let s=this.buildSessionId(this.id,e.envelope.sourceNumber),n=e.envelope.dataMessage;return I(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=w()?.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",c=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 c=await utils.TruncateContent.truncate(s,{maxChars:i,label:"signal message"});r=c.content,this.log.debug("sendMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:c.truncated?c.outputPath:void 0});}return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:r})}async request(e,s,n){let i=`${this.botConfig?.serviceUrl}${s}`,r={"Content-Type":"application/json"};this.botConfig?.password&&(r.Authorization=`Basic ${Buffer.from(`${this.botConfig.phoneNumber}:${this.botConfig.password}`).toString("base64")}`);let a;if(e==="GET"?a=await 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 ze=class extends A{constructor(e="nostr-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","nostr");chunk6C5TBG7Z_cjs.a(this,"name","Nostr Bot");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"relayConnections",new Map);chunk6C5TBG7Z_cjs.a(this,"subscriptions",new Map);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"processedEventIds",new Set);chunk6C5TBG7Z_cjs.a(this,"sentMessages",new Map);chunk6C5TBG7Z_cjs.a(this,"relayReconnectAttempts",new Map);chunk6C5TBG7Z_cjs.a(this,"maxReconnectAttempts",5);chunk6C5TBG7Z_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:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:65536,maxMediaCount:1}}async connectToRelay(e){if(this.abortController?.signal.aborted)return;let s=new WebSocket(e);s.onopen=()=>{this.log.info("Connected to relay",{relay:e}),this.relayReconnectAttempts.set(e,0);for(let[n,i]of this.subscriptions)this.subscribeToRelay(s,n,i);},s.onmessage=n=>{this.handleRelayMessage(e,n.data.toString());},s.onclose=()=>{if(this.abortController?.signal.aborted)return;this.log.info("Disconnected from relay",{relay:e}),this.relayConnections.delete(e);let n=this.relayReconnectAttempts.get(e)??0;if(n<this.maxReconnectAttempts){let i=Math.min(1e3*2**n,3e4);this.relayReconnectAttempts.set(e,n+1),this.log.info("Attempting to reconnect to relay",{relay:e,attempt:n+1,delay:i}),setTimeout(()=>this.connectToRelay(e),i);}else this.log.error("Max reconnect attempts reached for relay",{relay:e});},s.onerror=n=>{this.log.error("Relay error",{relay:e,error:String(n)});},this.relayConnections.set(e,s);}handleRelayMessage(e,s){this.updateActivity();try{let n=JSON.parse(s);if(n[0]==="EVENT"&&n[2]){let i=n[2];this.handleNostrEvent(i);}if(n[0]==="OK"){let i=n[1],r=n[2];this.log.debug("Event published",{eventId:i,success:r});}}catch(n){this.log.error("Failed to handle relay message",{error:String(n)});}return Promise.resolve()}async handleNostrEvent(e){if(e.kind!==1||this.processedEventIds.has(e.id))return;if(this.processedEventIds.add(e.id),this.processedEventIds.size>1e4){let n=Array.from(this.processedEventIds);this.processedEventIds=new Set(n.slice(-5e3));}if(e.pubkey===this.botConfig?.publicKey)return;if(e.content?.trim().startsWith("/")){let n=this.buildSessionId(this.id,e.pubkey),i=await this.processCommand({text:e.content,sessionId:n,chatId:e.pubkey,channelInfo:{platform:"nostr",channelId:this.id,userId:e.pubkey,chatId:e.pubkey,eventId:e.id,createdAt:e.created_at},messageId:e.id});if(i.handled){i.reply?await this.createEvent(i.reply):i.gatewayMessage&&await this.handleMessage(i.gatewayMessage);return}}let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.buildSessionId(this.id,e.pubkey);return I(s,"input",this.parseContent(e),{channel:{platform:"nostr",channelId:this.id,userId:e.pubkey,chatId:e.pubkey,eventId:e.id,createdAt:e.created_at,tags:e.tags},context:{replyTo:this.findReplyTo(e.tags),conversationId:e.pubkey}})}parseContent(e){let s=[];e.content&&s.push({type:"text",text:e.content});for(let n of e.tags)if(n[0]==="url"&&n[1]){let i=n[1];i.match(/\.(jpg|jpeg|png|gif|webp)$/i)&&s.push({type:"image",image:i});}return s}findReplyTo(e){for(let s of e)if(s[0]==="e"&&s[1])return s[1]}buildSessionId(e,s,n){let i=["nostr",e,s];return n&&i.push(n),i.join("_")}subscribeToRelay(e,s,n){let i=["REQ",s,n];e.send(JSON.stringify(i));}unsubscribeFromRelay(e,s){let n=["CLOSE",s];e.send(JSON.stringify(n));}async createEvent(e,s){let n=[];s&&n.push(["e",s,"","reply"]);let i={id:"",pubkey:this.botConfig?.publicKey??"",created_at:Math.floor(Date.now()/1e3),kind:1,tags:n,content:e,sig:""};return i.id=await this.computeEventId(i),i.sig=await this.signEvent(i),i}async computeEventId(e){let s=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),i=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(r)).map(c=>c.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw 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 Zt=class extends A{constructor(e){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform");chunk6C5TBG7Z_cjs.a(this,"name");chunk6C5TBG7Z_cjs.a(this,"version");chunk6C5TBG7Z_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 Vr(o){return new Zt(o)}var es={telegram:Re,discord:De,slack:Ne,feishu:Le,wechat:Ge,weixin:$e,webchat:We,signal:He,nostr:ze};function Iu(){return Object.keys(es)}var v=utils.Log.create({service:"gateway:net:registry"});function mn(o){if(!o)return {url:"",protocol:"unsupported"};let t=o.trim();return t.startsWith("ws://")||t.startsWith("wss://")||t.startsWith("acp-ws://")?(t.startsWith("acp-ws://")&&(t=t.replace("acp-ws://","ws://")),t.includes("/acp")||(t=t.replace(/\/$/,"")+"/acp"),{url:t,protocol:"websocket"}):t.startsWith("http://")||t.startsWith("https://")?(t.includes("/acp")||(t=t.replace(/\/$/,"")+"/acp"),{url:t,protocol:"http"}):{url:t,protocol:"unsupported"}}async function Qr(o,t){try{let e=await utils.Fetch.post(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}},{timeout:t});if(!e.ok)return !1;let s=e.data;return !(!s||s.error)}catch{return false}}async function Xr(o,t){return new Promise(e=>{let s=null,n=false,i=setTimeout(()=>{n||(n=true,s?.close(),e(false));},t);try{s=new WebSocket(o),s.onopen=()=>{let r={jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}};s.send(JSON.stringify(r));},s.onmessage=r=>{try{let a=JSON.parse(r.data);a.id===1&&!a.error?n||(n=!0,clearTimeout(i),s?.close(),e(!0)):a.error&&(n||(n=!0,clearTimeout(i),s?.close(),e(!1)));}catch{}},s.onerror=()=>{n||(n=!0,clearTimeout(i),e(!1));},s.onclose=()=>{n||(n=!0,clearTimeout(i),e(!1));};}catch{n||(n=true,clearTimeout(i),e(false));}})}async function Yr(o,t){try{let e=await utils.Fetch.post(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}},{timeout:t});if(!e.ok||!e.data?.result?.agentCapabilities)return [];let s=e.data.result.agentCapabilities,n=[];return s.mcpCapabilities&&(s.mcpCapabilities.http&&n.push("mcp:http"),s.mcpCapabilities.sse&&n.push("mcp:sse")),s.promptCapabilities&&(s.promptCapabilities.image&&n.push("prompt:image"),s.promptCapabilities.embeddedContext&&n.push("prompt:context")),s.sessionCapabilities&&(s.sessionCapabilities.fork&&n.push("session:fork"),s.sessionCapabilities.resume&&n.push("session:resume")),n}catch{return []}}var je=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"agents",new Map);chunk6C5TBG7Z_cjs.a(this,"heartbeatTimer",null);chunk6C5TBG7Z_cjs.a(this,"roundRobinIndex",0);chunk6C5TBG7Z_cjs.a(this,"store",null);chunk6C5TBG7Z_cjs.a(this,"eventCallbacks",new Set);let{dataDir:e,...s}=t;this.config={...bt,...s},e&&(this.store=new Te({dataDir:e}));}async load(){if(this.store)try{let t=await this.store.loadAll(),e=Date.now();for(let s of t)e-s.lastHeartbeat>this.config.heartbeatTimeout&&(s.status="unhealthy"),this.agents.set(s.id,s);v.info("Agent registry loaded from storage",{count:t.length});}catch(t){v.error("Failed to load agent registry from storage",{error:String(t)});}}async register(t){if(this.agents.has(t.id))throw new Error(`Agent with ID "${t.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),s={...t,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(t.id,s);let{url:n,protocol:i}=mn(t.address);if(i!=="http"&&i!=="websocket")throw new Error(`Unsupported protocol: ${t.address}. Only http/https/ws/wss are supported`);let r=await Yr(n,3e4).catch(()=>[]);r.length>0&&(s.capabilities=r),this.store&&await this.store.save(s),v.info("Agent registered",{agentId:t.id,name:t.name,capabilities:s.capabilities,address:t.address,totalAgents:this.agents.size}),this.emitEvent({type:"register",agent:s});}async deregister(t){let e=this.agents.get(t);if(!e){v.warn("Attempted to deregister unknown agent",{agentId:t});return}this.agents.delete(t),this.store&&await this.store.delete(t),v.info("Agent deregistered",{agentId:t,name:e.name,totalAgents:this.agents.size}),this.emitEvent({type:"deregister",agent:e});}async heartbeat(t,e){let s=this.agents.get(t);if(!s)throw v.warn("Heartbeat received from unknown agent",{agentId:t}),new Error(`Agent "${t}" is not registered`);let n=s.status;s.lastHeartbeat=Date.now(),s.status="healthy",e&&(s.metadata={...s.metadata,...e});let i=6e4,r=Date.now();this.store&&(n!=="healthy"||r-s.lastHeartbeat>=i)&&this.store.save(s).catch(a=>{v.error("Failed to save agent to store",{agentId:t,error:String(a)});}),n!=="healthy"&&this.emitEvent({type:"status_change",agent:s,oldStatus:n});}setStatus(t,e){let s=this.agents.get(t);if(!s){v.warn("Attempted to set status for unknown agent",{agentId:t});return}let n=s.status;n!==e&&(s.status=e,this.store&&this.store.save(s).catch(i=>{v.error("Failed to save agent status to store",{agentId:t,error:String(i)});}),this.emitEvent({type:"status_change",agent:s,oldStatus:n}));}getAgent(t){return this.agents.get(t)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(t=>t.status==="healthy")}selectAgent(t){let{strategy:e,capabilities:s,healthyOnly:n=true}=t,i=n?this.getHealthyAgents():this.getAllAgents();if(s&&s.length>0&&(i=i.filter(a=>s.every(c=>a.capabilities.includes(c)))),i.length===0){v.warn("No agents available for selection",{strategy:e,capabilities:s,healthyOnly:n,totalAgents:this.agents.size});return}let r;switch(e){case "random":r=this.selectRandom(i);break;case "round-robin":r=this.selectRoundRobin(i);break;case "least-connections":r=this.selectLeastConnections(i);break;default:r=this.selectRandom(i);}return v.debug("Agent selected",{agentId:r.id,strategy:e,connectionCount:r.connectionCount}),r}incrementConnection(t){let e=this.agents.get(t);e&&(e.connectionCount++,v.debug("Agent connection incremented",{agentId:t,connectionCount:e.connectionCount}));}decrementConnection(t){let e=this.agents.get(t);e&&e.connectionCount>0&&(e.connectionCount--,v.debug("Agent connection decremented",{agentId:t,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){v.warn("Heartbeat check is already running");return}v.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,v.info("Heartbeat check stopped"));}async checkHeartbeats(){let t=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:s}=this.config,n=[],i=0,r=[];for(let[a,c]of this.agents.entries()){let d=t-c.lastHeartbeat;if(d>s){n.push(a);continue}(d>e||c.status==="unhealthy")&&r.push((async()=>{let{url:g,protocol:p}=mn(c.address),h=this.config.heartbeatTimeout/2;v.debug("Checking agent connectivity",{agentId:a,url:g,protocol:p});let b=false;try{p==="http"?b=await Qr(g,h):b=await Xr(g,h);}catch(T){v.debug("Agent connectivity check error",{agentId:a,error:String(T)}),b=false;}let S=c.status;b?(c.lastHeartbeat=t,c.status!=="healthy"&&(c.status="healthy",v.debug("Agent recovered, marked as healthy",{agentId:a,name:c.name,previousStatus:S}),this.store&&this.store.save(c).catch(T=>{v.error("Failed to save agent to store",{agentId:a,error:String(T)});}),this.emitEvent({type:"status_change",agent:c,oldStatus:S}))):c.status==="healthy"&&(c.status="unhealthy",i++,v.warn("Agent marked as unhealthy due to connectivity check failed",{agentId:a,name:c.name,url:g,protocol:p,lastHeartbeat:c.lastHeartbeat,timeSinceLastHeartbeat:d,timeout:e}),this.store&&this.store.save(c).catch(T=>{v.error("Failed to save agent to store",{agentId:a,error:String(T)});}),this.emitEvent({type:"status_change",agent:c,oldStatus:S}));})());}await Promise.all(r);for(let a of n){let c=this.agents.get(a);c&&(v.debug("Auto-deregistering agent due to timeout",{agentId:a,name:c.name,lastHeartbeat:c.lastHeartbeat,timeout:s}),this.agents.delete(a),this.store&&await this.store.delete(a),this.emitEvent({type:"deregister",agent:c}));}(i>0||n.length>0)&&v.debug("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:n.length,totalAgents:this.agents.size});}onEvent(t){this.eventCallbacks.add(t);}offEvent(t){this.eventCallbacks.delete(t);}emitEvent(t){for(let e of this.eventCallbacks)try{e(t);}catch(s){v.error("Agent event callback error",{eventType:t.type,agentId:t.agent.id,error:String(s)});}}selectRandom(t){let e=Math.floor(Math.random()*t.length);return t[e]}selectRoundRobin(t){if(t.length===0)throw new Error("No candidates available for round-robin selection");this.roundRobinIndex>=t.length&&(this.roundRobinIndex=0);let e=t[this.roundRobinIndex];return this.roundRobinIndex=(this.roundRobinIndex+1)%t.length,e}selectLeastConnections(t){return t.reduce((e,s)=>s.connectionCount<e.connectionCount?s:e)}getStats(){let t=this.getAllAgents();return {totalAgents:t.length,healthyAgents:t.filter(e=>e.status==="healthy").length,unhealthyAgents:t.filter(e=>e.status==="unhealthy").length,offlineAgents:t.filter(e=>e.status==="offline").length,totalConnections:t.reduce((e,s)=>e+s.connectionCount,0)}}setAgentStatus(t,e){this.setStatus(t,e);}setLastHeartbeat(t,e){let s=this.agents.get(t);s&&(s.lastHeartbeat=e);}};var x=utils.Log.create({service:"gateway:net:sync-manager"}),qe=class{constructor(t){chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"internalConfig");chunk6C5TBG7Z_cjs.a(this,"registry");chunk6C5TBG7Z_cjs.a(this,"localNodeId");chunk6C5TBG7Z_cjs.a(this,"localNodeName");chunk6C5TBG7Z_cjs.a(this,"remoteNodes",new Map);chunk6C5TBG7Z_cjs.a(this,"remoteAgents",new Map);chunk6C5TBG7Z_cjs.a(this,"syncTimer",null);chunk6C5TBG7Z_cjs.a(this,"cleanupTimer",null);chunk6C5TBG7Z_cjs.a(this,"reconnectTimer",null);chunk6C5TBG7Z_cjs.a(this,"heartbeatTimer",null);chunk6C5TBG7Z_cjs.a(this,"running",false);chunk6C5TBG7Z_cjs.a(this,"agentListChangeCallbacks",new Set);this.registry=t.registry,this.localNodeId=t.localNodeId,this.localNodeName=t.localNodeName,this.config={...St,...t.config},this.internalConfig={maxConcurrentSync:3,remoteAgentTtl:300*1e3,cleanupInterval:180*1e3,maxRetryCount:5,baseRetryDelay:15e3};}async start(){if(this.running){x.warn("Agent sync manager is already running");return}x.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let t of this.config.remoteNodes)this.remoteNodes.set(t.id,{info:{id:t.id,name:t.id,address:t.address,port:t.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced",retryCount:0,nextRetryAt:0});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.cleanupTimer=setInterval(()=>this.cleanupStaleAgents(),this.internalConfig.cleanupInterval),this.reconnectTimer=setInterval(()=>this.reconnectFailedNodes(),this.internalConfig.baseRetryDelay),this.heartbeatTimer=setInterval(()=>this.checkNodeHealth(),6e4),this.registry.onEvent(t=>this.handleLocalAgentEvent(t)),this.running=true,x.info("Agent sync manager started");}async stop(){if(!this.running){x.warn("Agent sync manager is not running");return}x.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,x.info("Agent sync manager stopped");}async pullFromAllNodes(){let t=Array.from(this.remoteNodes.keys()),e=this.internalConfig.maxConcurrentSync;for(let s=0;s<t.length;s+=e){let i=t.slice(s,s+e).map(r=>this.pullFromNode(r).catch(a=>{x.error("Failed to pull from node",{nodeId:r,error:a.message});}));await Promise.all(i);}}async pullFromNode(t){let e=this.remoteNodes.get(t);if(!e)throw new Error(`Unknown remote node: ${t}`);e.status="syncing";let s=this.config.remoteNodes.find(i=>i.id===t);if(!s)throw new Error(`Remote node not found in config: ${t}`);let n=Date.now();try{let i=`http://${s.address}:${s.port}/sync/agents`,r=await utils.Fetch.get(i,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);let a=r.data.agents||[];for(let c of a)c.sourceGatewayId=t,this.remoteAgents.set(c.id,{agent:c,cachedAt:n});return e.lastSyncAt=n,e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",e.retryCount=0,delete e.error,a}catch(i){e.status="error",e.error=i.message,e.info.status="offline";let r=this.calculateRetryDelay(e.retryCount);throw e.retryCount++,e.nextRetryAt=n+r,x.error("Failed to pull from node",{nodeId:t,error:i.message,retryCount:e.retryCount,nextRetryAt:e.nextRetryAt}),i}}calculateRetryDelay(t){let{baseRetryDelay:e,maxRetryCount:s}=this.internalConfig;return Math.min(e*2**t,e*2**s)}async pushEvent(t){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[s]of this.remoteNodes.entries())e.push(this.pushToNode(s,t));await Promise.allSettled(e);}async pushToNode(t,e){let s=this.config.remoteNodes.find(n=>n.id===t);if(!s){x.warn("Unknown remote node for push",{nodeId:t});return}try{let n=`http://${s.address}:${s.port}/sync/events`,i=await utils.Fetch.post(n,e,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}`);x.debug("Pushed event to node",{nodeId:t,eventType:e.type});}catch(n){x.error("Failed to push to node",{nodeId:t,eventType:e.type,error:n.message});}}async handleSyncMessage(t){switch(t.type){case "agent_list_request":await this.handleAgentListRequest(t);break;case "agent_list_response":await this.handleAgentListResponse(t);break;case "agent_register":await this.handleAgentRegister(t);break;case "agent_deregister":await this.handleAgentDeregister(t);break;case "agent_heartbeat":await this.handleAgentHeartbeat(t);break;case "agent_status_change":await this.handleAgentStatusChange(t);break;default:x.warn("Unknown sync message type",{type:t.type});}}async handleAgentListRequest(t){let e=this.getLocalAgentsForSync(),s={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:t.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(t.sourceNodeId,s);}async handleAgentListResponse(t){for(let e of t.agents)this.remoteAgents.set(e.id,{agent:e,cachedAt:Date.now()});this.notifyAgentListChange(t.agents,"add");}async handleAgentRegister(t){let{agent:e}=t,s=this.remoteAgents.get(e.id);if(s){let n=this.resolveConflict(s.agent,e);this.remoteAgents.set(e.id,{agent:n,cachedAt:Date.now()});}else this.remoteAgents.set(e.id,{agent:e,cachedAt:Date.now()});this.notifyAgentListChange([e],"add");}async handleAgentDeregister(t){let{agentId:e}=t,s=this.remoteAgents.get(e);this.remoteAgents.delete(e),s&&this.notifyAgentListChange([s.agent],"remove");}async handleAgentHeartbeat(t){let{agentId:e,heartbeatAt:s,status:n}=t,i=this.remoteAgents.get(e);i&&(i.agent.updatedAt=s,i.agent.status=n,i.cachedAt=Date.now());}async handleAgentStatusChange(t){let{agentId:e,newStatus:s,changedAt:n}=t,i=this.remoteAgents.get(e);if(i){({...i.agent});i.agent.status=s,i.agent.updatedAt=n,i.cachedAt=Date.now(),x.debug("Remote agent status changed",{agentId:e,newStatus:s,sourceNodeId:t.sourceNodeId}),this.notifyAgentListChange([i.agent],"update");}}cleanupStaleAgents(){if(!this.running)return;let t=Date.now(),e=this.internalConfig.remoteAgentTtl,s=0;for(let[n,i]of this.remoteAgents.entries())t-i.cachedAt>e&&(this.remoteAgents.delete(n),s++);s>0&&x.debug("Cleaned up stale remote agents",{cleanedCount:s,remainingCount:this.remoteAgents.size});}async reconnectFailedNodes(){if(!this.running)return;let t=Date.now(),e=[];for(let[s,n]of this.remoteNodes.entries())n.status==="error"&&n.nextRetryAt>0&&t>=n.nextRetryAt&&e.push(s);if(e.length>0){x.debug("Retrying failed nodes",{nodeCount:e.length});for(let s of e)try{await this.pullFromNode(s);}catch{}}}async checkNodeHealth(){if(this.running)for(let[t,e]of this.remoteNodes.entries()){let s=this.config.remoteNodes.find(n=>n.id===t);if(s)try{let n=`http://${s.address}:${s.port}/status`,i=await utils.Fetch.get(n,{timeout:5e3});i.ok?(e.info.status="online",e.retryCount=0,x.debug("Node health check passed",{nodeId:t})):(e.info.status="offline",x.warn("Node health check failed",{nodeId:t,status:i.status}));}catch(n){e.info.status="offline",x.warn("Node health check error",{nodeId:t,error:n.message});}}}async handleLocalAgentEvent(t){if(!this.config.pushEvents.includes(t.type))return;let e=this.agentToSyncInfo(t.agent),s=Date.now();switch(t.type){case "register":await this.pushEvent({type:"agent_register",sourceNodeId:this.localNodeId,timestamp:s,agent:e});break;case "deregister":await this.pushEvent({type:"agent_deregister",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id});break;case "heartbeat":await this.pushEvent({type:"agent_heartbeat",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id,heartbeatAt:t.agent.lastHeartbeat,status:t.agent.status});break;case "status_change":await this.pushEvent({type:"agent_status_change",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id,oldStatus:t.oldStatus??"healthy",newStatus:t.agent.status,changedAt:s});break}}agentToSyncInfo(t){return {id:t.id,name:t.name,sourceGatewayId:this.localNodeId,address:t.address,capabilities:t.capabilities,status:t.status,updatedAt:t.lastHeartbeat,metadata:t.metadata}}resolveConflict(t,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>t.updatedAt?e:e.updatedAt<t.updatedAt?t:e.id>t.id?e:t;case "local":return t;case "remote":return e;default:return e.updatedAt>t.updatedAt?e:e.updatedAt<t.updatedAt?t:e.id>t.id?e:t}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(t=>this.agentToSyncInfo(t))}notifyAgentListChange(t,e){for(let s of this.agentListChangeCallbacks)try{for(let n of t)s(t,e,n);}catch(n){x.error("Agent list change callback error",{error:String(n)});}}onAgentListChange(t){this.agentListChangeCallbacks.add(t);}offAgentListChange(t){this.agentListChangeCallbacks.delete(t);}getMergedAgentList(){let t=new Map;for(let e of this.getLocalAgentsForSync())t.set(e.id,e);for(let[e,s]of this.remoteAgents.entries())t.has(e)||t.set(e,s.agent);return Array.from(t.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values()).map(t=>t.agent)}getStats(){let t=this.registry.getAllAgents(),e=0,s=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:s++;let n=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(n||0)&&(n=i.lastSyncAt);return {localAgentCount:t.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:t.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:s,lastSyncAt:n}}isRunning(){return this.running}addRemoteNode(t){this.remoteNodes.set(t.id,{info:{id:t.id,name:t.id,address:t.address,port:t.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced",retryCount:0,nextRetryAt:0}),x.debug("Remote node added",{nodeId:t.id,address:t.address});}removeRemoteNode(t){this.remoteNodes.delete(t);for(let[e,s]of this.remoteAgents.entries())s.agent.sourceGatewayId===t&&this.remoteAgents.delete(e);x.debug("Remote node removed",{nodeId:t});}};var G=utils.Log.create({service:"gateway:ws-agent-sync"}),Mt=class{constructor(t){chunk6C5TBG7Z_cjs.a(this,"wsServer");chunk6C5TBG7Z_cjs.a(this,"syncManager");chunk6C5TBG7Z_cjs.a(this,"gatewayId");chunk6C5TBG7Z_cjs.a(this,"subscribers",new Map);chunk6C5TBG7Z_cjs.a(this,"getClientWs");this.wsServer=t.wsServer,this.syncManager=t.syncManager,this.getClientWs=t.getClientWs,this.gatewayId=t.wsServer.getGatewayId();}async handleAgentListRequest(t,e){let s=this.getClientWs(t);if(!s){G.warn("Client not found for agent list request",{clientId:t,requestId:e});return}let n=this.syncManager.getMergedAgentList();this.sendMessage(s,{type:"agent_list_response",requestId:e,agents:n});}async handleAgentSubscribe(t,e){let s=this.getClientWs(t);if(!s){G.warn("Client not found for agent subscribe",{clientId:t});return}if(e){this.subscribers.delete(t),this.subscribers.set(t,{clientId:t,ws:s,subscribedAt:Date.now()});let n=this.syncManager.getMergedAgentList();this.sendMessage(s,{type:"agent_list_response",agents:n});}else this.subscribers.delete(t);}broadcastAgentUpdate(t,e){if(this.subscribers.size===0)return;let s={type:"agent_update",action:t,agent:e};for(let[n,i]of this.subscribers.entries())try{i.ws.readyState===i.ws.OPEN&&this.sendMessage(i.ws,s);}catch(r){G.error("Failed to send agent update to client",{clientId:n,error:r.message});}}broadcastAgentList(){if(this.subscribers.size===0)return;let t=this.syncManager.getMergedAgentList();for(let[e,s]of this.subscribers.entries())try{s.ws.readyState===s.ws.OPEN&&this.sendMessage(s.ws,{type:"agent_list_response",requestId:`broadcast_${Date.now()}`,agents:t});}catch(n){G.error("Failed to send agent list to client",{clientId:e,error:n.message});}}cleanupClientSubscription(t){this.subscribers.delete(t);}getSubscriberCount(){return this.subscribers.size}getSubscribers(){return Array.from(this.subscribers.keys())}sendMessage(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e));}async handleAgentRegister(t,e){if(!e.agentId){G.warn("Agent register payload missing agentId",{clientId:t});return}if(!this.getClientWs(t)){G.warn("Client not found for agent register",{clientId:t});return}let n={id:e.agentId,name:e.name??e.agentId,sourceGatewayId:this.gatewayId,address:e.address??"",capabilities:e.capabilities??[],status:"healthy",updatedAt:Date.now(),metadata:e.metadata};try{let i=this.syncManager.registry;if(i.agents.has(n.id)){await i.heartbeat(n.id,n.metadata),G.debug("Agent heartbeat from client",{clientId:t,agentId:n.id});return}let r={...n.metadata,sourceGatewayId:this.gatewayId};await i.register({id:n.id,name:n.name,address:n.address,capabilities:n.capabilities,metadata:r}),G.debug("Agent registered from client",{clientId:t,agentId:n.id,name:n.name}),this.broadcastAgentUpdate("add",n);}catch(i){G.warn("Failed to register agent from client",{clientId:t,agentId:e.agentId,error:String(i)});}}async handleAgentDeregister(t,e){if(!e.agentId){G.warn("Agent deregister payload missing agentId",{clientId:t});return}if(!this.getClientWs(t)){G.warn("Client not found for agent deregister",{clientId:t});return}try{await this.syncManager.registry.deregister(e.agentId),G.debug("Agent deregistered from client",{clientId:t,agentId:e.agentId});let n={id:e.agentId,name:"unknown",sourceGatewayId:this.gatewayId,address:"",capabilities:[],status:"offline",updatedAt:Date.now()};this.broadcastAgentUpdate("remove",n);}catch(n){G.warn("Failed to deregister agent from client",{clientId:t,agentId:e.agentId,error:String(n)});}}async cleanupClient(t){this.subscribers.delete(t);let e=this.syncManager.registry.getAllAgents().filter(s=>s.metadata?.sourceGatewayId===this.gatewayId);for(let s of e)try{await this.syncManager.registry.deregister(s.id);let n={id:s.id,name:s.name,sourceGatewayId:this.gatewayId,address:s.address,capabilities:s.capabilities,status:"offline",updatedAt:Date.now()};this.broadcastAgentUpdate("remove",n);}catch{}}};var le=class le{constructor(t){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:server"}));chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"router");chunk6C5TBG7Z_cjs.a(this,"sessionManager");chunk6C5TBG7Z_cjs.a(this,"pluginLoader");chunk6C5TBG7Z_cjs.a(this,"messageStore");chunk6C5TBG7Z_cjs.a(this,"contactStore",null);chunk6C5TBG7Z_cjs.a(this,"wsServer",null);chunk6C5TBG7Z_cjs.a(this,"agentRegistry");chunk6C5TBG7Z_cjs.a(this,"agentSyncManager",null);chunk6C5TBG7Z_cjs.a(this,"wsAgentSync",null);chunk6C5TBG7Z_cjs.a(this,"running",false);chunk6C5TBG7Z_cjs.a(this,"connections",0);chunk6C5TBG7Z_cjs.a(this,"gatewayAgent",null);chunk6C5TBG7Z_cjs.a(this,"bindingLocks",new Map);this.log.debug("GatewayServer.constructor: starting"),this.config=t,this.log.debug("GatewayServer.constructor: creating MessageRouter");let e=ge()?Q().hookRegistry:void 0;this.router=new Ct(e),this.log.debug("GatewayServer.constructor: creating GatewaySessionManager");let s=w();this.sessionManager=new _e({storagePath:`${s.Path.data}/gateway/sessions`,enablePersistence:true}),this.pluginLoader=new Ee({healthCheckInterval:6e4});let n=ge();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:n}),this.messageStore=new Me({storagePath:`${s.Path.data}/gateway/messages`}),this.agentRegistry=new je({dataDir:`${s.Path.data}/gateway/net`});let i={getSession:r=>{let a=this.sessionManager.get(r);return a?{backendSessionId:a.backendSessionId}:void 0},unbindBackendSession:r=>this.sessionManager.unbindBackendSession(r)};this.pluginLoader.setMessageHandler({onMessage:r=>this.onMessage(r),onEvent:r=>this.onEvent(r),session:i}),this.log.debug("GatewayServer.constructor: completed");}async loadChannelPlugins(){try{let{config:t}=await k(),e=t.channels;if(!e){this.log.debug("no channel config found, skipping plugin loading");return}for(let[s,n]of Object.entries(e)){if(!n?.enabled){this.log.debug("channel disabled or not configured",{platform:s});continue}let i=es[s];if(!i){this.log.warn("no plugin class found for platform",{platform:s});continue}let r=`${s}-main`,a=new i(r),c={enabled:!0,platform:n,session:{autoCreate:!0,resetPolicy:"onNewConversation"},routing:{broadcast:!0,dispatchToSubAgent:!0}};try{await this.pluginLoader.register(a,c),this.log.info("channel plugin registered",{platform:s,id:r});}catch(d){this.log.error("failed to register channel plugin",{platform:s,error:String(d)});}}}catch(t){this.log.error("failed to load channel plugins",{error:String(t)});}}async start(){if(this.log.debug("GatewayServer.start: called"),this.running){this.log.warn("gateway server is already running");return}this.log.info("starting gateway server",{port:this.config.port,hostname:this.config.hostname}),await this.sessionManager.initialize(),this.log.debug("GatewayServer.start: sessionManager initialized"),await this.agentRegistry.load(),this.log.debug("GatewayServer.start: agentRegistry initialized");let e=`${w().Path.data}/gateway`,s=new ie({baseDir:e});this.contactStore=new ke(s,{cacheSize:1e3}),this.contactStore.initialize&&await this.contactStore.initialize(),this.log.debug("GatewayServer.start: contactStore initialized"),this.wsServer=new re({port:this.config.port,hostname:this.config.hostname,path:String(this.config.path??"/")}),await this.wsServer.start(),this.log.debug("GatewayServer.start: wsServer started"),await this.loadChannelPlugins(),this.pluginLoader.startAll().catch(g=>{this.log.error("plugin startup error",{error:String(g)});}),this.log.debug("GatewayServer.start: plugins startup initiated"),this.pluginLoader.startHealthCheckTimer();let{config:n}=await k(),i=n.defaults;this.wsServer.setChannelResolveDeps({sessionManager:{get:g=>this.sessionManager.get(g),getOrCreate:(g,p)=>this.sessionManager.getOrCreate(g,p),bindBackendSession:(g,p)=>this.sessionManager.bindBackendSession(g,p),findByBackendSessionId:g=>this.sessionManager.findByBackendSessionId(g),getAll:()=>this.sessionManager.getAllSessions()},pluginLoader:{getPlugin:g=>this.pluginLoader.getPlugin(g),getAllPlugins:()=>this.pluginLoader.getAllPlugins(),isRunning:g=>this.pluginLoader.isRunning(g)},defaultChannel:i?.channel,fallbackChannels:i?.fallbackChannels,contactStore:this.contactStore?{findByPlatformId:(g,p)=>this.contactStore.findByPlatformId(g,p),findByUid:g=>this.contactStore.findByUid(g),listByPlatform:(g,p,h)=>this.contactStore.listByPlatform(g,p,h),count:g=>this.contactStore.count(g)}:void 0}),this.wsServer.setPluginLoader((g,p,h)=>this.sendToChannel(g,p,h)),this.wsServer.setRouter(this.router),this.router.setSessionManager({get:g=>this.sessionManager.get(g),bindBackendSession:(g,p)=>this.sessionManager.bindBackendSession(g,p)}),this.pluginLoader.setMessageHandler({onMessage:g=>this.onMessage(g),onEvent:g=>this.onEvent(g),session:{getSession:g=>{let p=this.sessionManager.get(g);return p?{backendSessionId:p.backendSessionId}:void 0},unbindBackendSession:g=>this.sessionManager.unbindBackendSession(g)}}),this.agentSyncManager=new qe({registry:this.agentRegistry,localNodeId:"gateway",localNodeName:"gateway"}),this.wsAgentSync=new Mt({wsServer:this.wsServer,syncManager:this.agentSyncManager,getClientWs:g=>this.wsServer.getClientWs(g)}),this.wsServer.setAgentSync(this.wsAgentSync),this.wsServer.setAgentRegistry(this.agentRegistry),this.log.debug("GatewayServer.start: agent sync initialized"),this.log.debug("GatewayServer.start: registering gateway status provider"),ps(async()=>{let g=this.sessionManager.getAllSessions(),p=this.router.getStats?.()??{subscribers:0},h=this.agentRegistry.getStats?.()??{totalAgents:0,healthyAgents:0,unhealthyAgents:0},b=this.wsAgentSync?.getSubscriberCount?.()??0,S=this.wsServer?.getStartTime?.()??0,M=this.pluginLoader.getAllPlugins().filter(U=>this.pluginLoader.isRunning(U.id)).map(U=>({id:U.id,platform:U.platform,name:U.name,version:U.version}));return {status:this.running?"running":"stopped",connections:this.wsServer?.getConnectionCount?.()??0,sessions:g.length,messageSubscriptions:p.subscribers??0,agentSubscriptions:b,uptime:this.running&&S?Date.now()-S:0,version:"1.0.0",agents:{total:h.totalAgents,healthy:h.healthyAgents,unhealthy:h.unhealthyAgents},channels:M}});let r=await this.messageStore.loadFromDisk();this.log.debug("loaded messages from disk",{count:r});let a=Date.now(),c=6e4,d=()=>{let g=Date.now()-a,p=this.pluginLoader.getAllPlugins(),h=p.filter(b=>this.pluginLoader.isRunning(b.id));h.length===p.length&&p.length>0?(this.log.debug("all plugins ready, proceeding with message retry"),this.retryPendingMessages().catch(b=>{this.log.error("failed to retry pending messages",{error:String(b)});})):g>c?(this.log.warn("plugin startup timeout, proceeding with message retry anyway",{elapsed:g}),this.retryPendingMessages().catch(b=>{this.log.error("failed to retry pending messages",{error:String(b)});})):(this.log.debug("waiting for plugins to be ready",{elapsed:g,ready:h.length,total:p.length}),setTimeout(d,100));};d(),this.running=true,this.log.debug("GatewayServer.start: completed"),this.log.info("gateway server started");}async stop(){if(!this.running){this.log.warn("gateway server is not running");return}if(this.log.info("stopping gateway server"),this.wsServer&&(await this.wsServer.stop(),this.wsServer=null,this.log.debug("WebSocket server stopped")),this.pluginLoader.stopHealthCheckTimer(),await this.pluginLoader.stopAll(),await this.router.shutdown(),await this.sessionManager.close(),await this.messageStore.close(),this.contactStore?.close&&await this.contactStore.close(),this.gatewayAgent){try{await this.gatewayAgent.stop();}catch(t){this.log.warn("Failed to stop gatewayAgent during server shutdown",{error:String(t)});}this.gatewayAgent=null;}this.running=false,this.log.info("gateway server stopped");}getStatus(){let t=this.agentRegistry.getStats();return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections,agents:{total:t.totalAgents,healthy:t.healthyAgents,unhealthy:t.unhealthyAgents}}}async onMessage(t){this.log.debug("message received",{id:t.id,sessionId:t.sessionId,type:t.type});let e=this.messageStore.get(t.id);if(e&&e.retryCount>le.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=t.metadata.channel,n=this.buildChannelContext(t,s),i={...t,metadata:{...t.metadata,system:n}},r=true;try{let a=await this.router.route(i);if(r=a.success,!a.dispatched&&t.type==="input"){let{config:c}=await k(),d=c.agentProcessing??{mode:"localAgent",localAgentPriority:1,subAgentPriority:2,timeout:3e5,retryOnFailure:!0};this.log.debug("no subscribers, dispatching to agent",{id:t.id,mode:d.mode}),this.dispatchToAgent(i,d).catch(g=>{this.log.error("agent dispatch failed",{id:t.id,error:String(g)}),r=!1;});}}catch(a){r=false,this.log.error("route failed",{messageId:t.id,error:String(a)});}t.type==="input"&&!r&&await this.messageStore.incrementRetry(t.id);}async saveContactFromMessage(t){if(!this.contactStore)return;let{platform:e,channelId:s,userId:n,chatId:i}=t.metadata.channel;if(!e||e==="api")return;let r=n||i;if(r)try{let a=await this.contactStore.getOrCreate(e,r,{username:t.metadata.channel?.username,displayName:t.metadata.channel?.firstName});this.log.debug("contact saved",{uid:a.uid});}catch(a){this.log.warn("failed to save contact",{platform:e,stableId:r,error:String(a)});}}async dispatchToAgent(t,e){if(!ge()){this.log.debug("no agent adapter, message remains pending",{id:t.id});return}let s=Q(),n=t.metadata.channel,r=this.sessionManager.get(t.sessionId)?.backendSessionId||void 0,a=t.metadata.system;switch(e.mode){case "localAgent":{this.dispatchToGatewayAgent(t,n,a,s,r);break}case "subAgent":{this.dispatchToSubAgent(t,n,a,s,r);break}default:{this.dispatchToGatewayAgent(t,n,a,s,r);break}}}getGatewayAgent(){if(!this.gatewayAgent){if(!Q().sdk)return null;this.gatewayAgent=hs({});}return this.gatewayAgent}dispatchToGatewayAgent(t,e,s,n,i){let r=this.getGatewayAgent();if(!r){this.log.debug("no GatewayAgent available, message remains pending",{id:t.id});return}this.log.debug("dispatching message to GatewayAgent",{id:t.id,sessionId:t.sessionId,backendSessionId:i}),this.triggerHook(plugin.HookEvent.GatewayMessageProcess,{id:t.id,sessionId:t.sessionId,backendSessionId:i,processorId:"gatewayAgent",processType:"gatewayAgent",agent:t?.metadata?.agent??"gateway",timestamp:Date.now()});let a=t.sessionId,d=(this.bindingLocks.get(a)??Promise.resolve()).catch(()=>{}).then(()=>this.resolveAndBindBackendSession(t,e,n,i)).then(g=>{g!==void 0&&this.executeGatewayAgent(t,e,r,g,s);}).catch(g=>{this.log.error("dispatchToGatewayAgent: binding pipeline failed",{id:t.id,sessionId:t.sessionId,error:String(g)}),this.handleAgentError(t,e,g,"gatewayAgent",i);}).finally(()=>{this.bindingLocks.get(a)===d&&this.bindingLocks.delete(a);});this.bindingLocks.set(a,d);}async resolveAndBindBackendSession(t,e,s,n){let r=`Gateway-${e?.platform||"unknown"}`;if(n){try{if((await s.sdk.session.get({sessionId:n})).data)return n}catch(p){this.log.warn("dispatchToGatewayAgent: session.get failed, will re-create",{sessionId:n,error:String(p)});}let g=(await s.sdk.session.create({title:r})).data?.id;if(g)return await this.sessionManager.bindBackendSession(t.sessionId,g),this.log.debug("backend session re-bound (previous session expired)",{gatewaySessionId:t.sessionId,backendSessionId:g}),g;this.log.warn("dispatchToGatewayAgent: session.create returned no id (re-bind)",{messageId:t.id});return}let c=(await s.sdk.session.create({title:r})).data?.id;if(c)return await this.sessionManager.bindBackendSession(t.sessionId,c),this.log.debug("backend session bound (first message)",{gatewaySessionId:t.sessionId,backendSessionId:c}),c;this.log.warn("dispatchToGatewayAgent: session.create returned no id (first bind)",{messageId:t.id});}buildChannelContext(t,e){let s=e?.platform||"unknown",n=e?.userId||e?.chatId||"unknown user",i=`${s}:${n}`,r=e?.chatType||"unknown";return `## External Channel Message
|
|
32
|
+
${g.content}`}),this.log.debug("weixin text file inlined",{fileName:c,mime:a,length:d.length});}catch(d){this.log.warn("weixin text file read failed, fallback to file part",{fileName:c,error:String(d)}),s.push({type:"file",data:r,mime:a});}else s.push({type:"file",data:r,mime:a});this.log.debug("weixin attachment resolved",{downloadDir:i,source:e.attachmentPath});}return e.text&&s.push({type:"text",text:e.text}),s}async resolveAttachmentToPath(e,s){if(typeof e=="string")return /^https?:\/\//i.test(e)?this.downloadUrlToLocal(e,s):e.startsWith("file://")?url.fileURLToPath(e):e;if(e instanceof URL)return /^https?:$/i.test(e.protocol)?this.downloadUrlToLocal(e.toString(),s):this.resolveAttachmentToPath(e.toString(),s);let n=w()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=utils.Filesystem.join(n,"gateway","downloads");await utils.Filesystem.mkdir(i,{recursive:true});let r=utils.Filesystem.join(i,`${s}_${Date.now()}.bin`);return await utils.Filesystem.write(r,Buffer.from(e)),r}async downloadUrlToLocal(e,s){let n=w()?.Path?.data||process.env.EASBOT_DATA_PATH||".easbot",i=utils.Filesystem.join(n,"gateway","downloads");await utils.Filesystem.mkdir(i,{recursive:true});let r=new URL(e).pathname.split("/").pop()||`weixin_${Date.now()}`,a=utils.Filesystem.join(i,`${s}_${r}`);this.log.debug("weixin download remote attachment",{url:e,dest:a});let c=await utils.Fetch.get(e,{responseType:"arrayBuffer",timeout:12e4});if(!c.ok)throw new Error(`Failed to download attachment from ${e}: HTTP ${c.status}`);return await utils.Filesystem.write(a,Buffer.from(c.data)),this.log.debug("weixin remote attachment downloaded",{url:e,dest:a,bytes:c.data.byteLength}),a}async sendTyping(e){if(!this.account)return;let s=xt(e);if(!s){this.log.debug("sendTyping skipped: no context token",{userId:e});return}try{let n=await Os(this.account.baseUrl,this.account.token,e,s);n.typing_ticket&&await $s(this.account.baseUrl,this.account.token,{ilink_user_id:e,typing_ticket:n.typing_ticket,status:Ws.TYPING});}catch(n){this.log.debug("sendTyping failed",{userId:e,error:String(n)});}}buildSessionId(e,s,n){let i=n??s;return `${this.platform}_${e}_${s}_${i}`}};var We=class extends A{constructor(e="webchat-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","webchat");chunk6C5TBG7Z_cjs.a(this,"name","WebChat");chunk6C5TBG7Z_cjs.a(this,"webChatConfig",null);chunk6C5TBG7Z_cjs.a(this,"connections",new Map);chunk6C5TBG7Z_cjs.a(this,"heartbeatInterval",null);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"processedMessageIds",new Set);chunk6C5TBG7Z_cjs.a(this,"sentMessages",new Map);chunk6C5TBG7Z_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(!n)throw f(this.id,"MESSAGE_SEND_FAILED","User ID is required");let i=this.findConnectionByUser(n);if(!i)throw f(this.id,"MESSAGE_SEND_FAILED","User not connected");let r={type:"message",sessionId:s,content:e.content,metadata:e.metadata};return i.ws.send(JSON.stringify(r)),i.lastActivity=Date.now(),this.sentMessages.set(e.id,{sessionId:s,messageId:e.id,timestamp:Date.now()}),e.id}getCapabilities(){return {...super.getCapabilities(),supportsText:true,supportsMedia:true,supportsReply:true,supportsThread:true,supportsEdit:true,supportsDelete:true,supportsTyping:true,supportsBatchSend:true,supportsMarkdown:true,supportsHtml:true,supportsDeliveryReceipt:true,supportsReadReceipt:true,supportsSlashCommands:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:1e5,maxMediaCount:20}}getWebSocketServer(){return this.wsServer}async handleConnection(e,s){let n=this.generateConnectionId();if(this.connections.size>=(this.webChatConfig?.maxConnections??1e3)){e.close(1013,"Maximum connections reached");return}let i={id:n,ws:e,userId:s,lastActivity:Date.now()};this.connections.set(n,i),e.onmessage=r=>{this.handleWebSocketMessage(i,r.data.toString());},e.onclose=()=>{this.connections.delete(n),this.log.debug("WebSocket closed",{connId:n,userId:s});},e.onerror=r=>{this.log.error("WebSocket error",{connId:n,userId:s,error:String(r)});},this.log.debug("WebSocket connected",{connId:n,userId:s});}getConnectionCount(){return this.connections.size}getWsServerConnectionCount(){return this.wsServer?.getConnectionCount()??0}async startWebSocketServer(){if(!this.webChatConfig)return;let e={port:this.webChatConfig.port,hostname:this.webChatConfig.hostname,path:this.webChatConfig.path,maxConnections:this.webChatConfig.maxConnections,connectionTimeout:this.webChatConfig.connectionTimeout,heartbeatInterval:this.webChatConfig.heartbeatInterval,sessionExpireMs:this.webChatConfig.sessionExpireMs,https:this.webChatConfig.https};this.wsServer=new re(e),await this.wsServer.start(),this.log.info("WebSocket server started",{url:`${this.webChatConfig.https?.enabled?"wss":"ws"}://${this.webChatConfig.hostname}:${this.webChatConfig.port}${this.webChatConfig.path}`});}async handleWebSocketMessage(e,s){this.updateActivity(),e.lastActivity=Date.now();try{let n=JSON.parse(s);switch(n.type){case "message":await this.handleChatMessage(e,n);break;case "ping":e.ws.send(JSON.stringify({type:"pong"}));break;case "subscribe":n.sessionId&&(e.sessionId=n.sessionId);break;case "unsubscribe":e.sessionId=void 0;break;case "message_delivered":await this.handleMessageAcknowledgment(e,n,"message_delivered");break;case "message_read":await this.handleMessageAcknowledgment(e,n,"message_read");break}}catch(n){this.log.error("Failed to handle WebSocket message",{error:String(n)});}}async handleMessageAcknowledgment(e,s,n){s.messageId&&(this.log.debug("message acknowledgment received",{type:n,messageId:s.messageId,userId:e.userId}),this.messageHandler&&await this.messageHandler.onEvent({type:n,channelId:this.id,data:{messageId:s.messageId,sessionId:e.sessionId,platform:"webchat",channelId:this.id,userId:e.userId},timestamp:Date.now()}));}async handleChatMessage(e,s){if(!s.content||!s.sessionId||this.processedMessageIds.has(s.messageId??""))return;if(s.messageId&&(this.processedMessageIds.add(s.messageId),this.processedMessageIds.size>1e4)){let r=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(r.slice(-5e3));}let n=s.content.find(r=>r.type==="text");if(n?.text.trim().startsWith("/")){let r=this.buildSessionId(this.id,s.sessionId,e.userId),a=await this.processCommand({text:n.text,sessionId:r,chatId:s.sessionId,channelInfo:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},messageId:s.messageId});if(a.handled){if(a.reply){let c=I(s.sessionId,"output",[{type:"text",text:a.reply}],{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},context:{conversationId:s.sessionId},...s.metadata});await this.send(c);}else a.gatewayMessage&&await this.handleMessage(a.gatewayMessage);return}}let i=I(s.sessionId,"input",s.content,{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:s.sessionId,connectionId:e.id},context:{conversationId:s.sessionId},...s.metadata});await this.handleMessage(i);}startHeartbeat(){let e=this.webChatConfig?.heartbeatInterval??3e4;this.heartbeatInterval=setInterval(()=>{let s=Date.now(),n=this.webChatConfig?.connectionTimeout??6e4;for(let[i,r]of this.connections)s-r.lastActivity>n&&(this.log.debug("Closing inactive connection",{connId:i}),r.ws.close(1001,"Connection timeout"),this.connections.delete(i));},e);}findConnectionByUser(e){for(let s of this.connections.values())if(s.userId===e)return s}generateConnectionId(){return `conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}};var He=class extends A{constructor(e="signal-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","signal");chunk6C5TBG7Z_cjs.a(this,"name","Signal Bot");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"lastTimestamp",0);chunk6C5TBG7Z_cjs.a(this,"pollingIntervalMs",5e3);chunk6C5TBG7Z_cjs.a(this,"processedMessageIds",new Set);chunk6C5TBG7Z_cjs.a(this,"sentMessages",new Map);chunk6C5TBG7Z_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:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:65536,maxMediaCount:10}}startPolling(){this.pollLoop(),this.log.info("Polling started",{interval:this.pollingIntervalMs});}pollLoop(){if(this.abortController?.signal.aborted)return;(async()=>{try{await this.poll();}catch(s){this.log.error("Polling error",{error:String(s)});}})().then(()=>{this.abortController?.signal.aborted||setTimeout(()=>this.pollLoop(),this.pollingIntervalMs);});}async poll(){let e=await this.receiveMessages(this.lastTimestamp);for(let s of e){let n=`${s.envelope.sourceNumber}_${s.envelope.timestamp}`;if(!this.processedMessageIds.has(n)){if(this.processedMessageIds.add(n),this.processedMessageIds.size>1e4){let i=Array.from(this.processedMessageIds);this.processedMessageIds=new Set(i.slice(-5e3));}this.lastTimestamp=s.envelope.timestamp,s.envelope.dataMessage&&await this.handleSignalMessage(s);}}}async handleSignalMessage(e){this.updateActivity();let s=e.envelope.dataMessage?.message;if(s?.trim().startsWith("/")){let i=this.buildSessionId(this.id,e.envelope.sourceNumber),r=await this.processCommand({text:s,sessionId:i,chatId:e.envelope.sourceNumber,channelInfo:{platform:"signal",channelId:this.id,userId:e.envelope.sourceNumber,chatId:e.envelope.sourceNumber,timestamp:e.envelope.dataMessage?.timestamp},messageId:e.envelope.dataMessage?.timestamp?.toString()});if(r.handled){r.reply?await this.sendMessage(e.envelope.sourceNumber,r.reply):r.gatewayMessage&&await this.handleMessage(r.gatewayMessage);return}}let n=await this.toGatewayMessage(e);await this.handleMessage(n);}async toGatewayMessage(e){let s=this.buildSessionId(this.id,e.envelope.sourceNumber),n=e.envelope.dataMessage;return I(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=w()?.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",c=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 c=await utils.TruncateContent.truncate(s,{maxChars:i,label:"signal message"});r=c.content,this.log.debug("sendMessage: message truncated",{originalLength:s.length,maxLength:i,outputPath:c.truncated?c.outputPath:void 0});}return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:r})}async request(e,s,n){let i=`${this.botConfig?.serviceUrl}${s}`,r={"Content-Type":"application/json"};this.botConfig?.password&&(r.Authorization=`Basic ${Buffer.from(`${this.botConfig.phoneNumber}:${this.botConfig.password}`).toString("base64")}`);let a;if(e==="GET"?a=await 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 ze=class extends A{constructor(e="nostr-main"){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform","nostr");chunk6C5TBG7Z_cjs.a(this,"name","Nostr Bot");chunk6C5TBG7Z_cjs.a(this,"botConfig",null);chunk6C5TBG7Z_cjs.a(this,"relayConnections",new Map);chunk6C5TBG7Z_cjs.a(this,"subscriptions",new Map);chunk6C5TBG7Z_cjs.a(this,"abortController",null);chunk6C5TBG7Z_cjs.a(this,"processedEventIds",new Set);chunk6C5TBG7Z_cjs.a(this,"sentMessages",new Map);chunk6C5TBG7Z_cjs.a(this,"relayReconnectAttempts",new Map);chunk6C5TBG7Z_cjs.a(this,"maxReconnectAttempts",5);chunk6C5TBG7Z_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:true,supportsNativeCommands:false,commandPrefix:"/",maxMessageLength:65536,maxMediaCount:1}}async connectToRelay(e){if(this.abortController?.signal.aborted)return;let s=new WebSocket(e);s.onopen=()=>{this.log.info("Connected to relay",{relay:e}),this.relayReconnectAttempts.set(e,0);for(let[n,i]of this.subscriptions)this.subscribeToRelay(s,n,i);},s.onmessage=n=>{this.handleRelayMessage(e,n.data.toString());},s.onclose=()=>{if(this.abortController?.signal.aborted)return;this.log.info("Disconnected from relay",{relay:e}),this.relayConnections.delete(e);let n=this.relayReconnectAttempts.get(e)??0;if(n<this.maxReconnectAttempts){let i=Math.min(1e3*2**n,3e4);this.relayReconnectAttempts.set(e,n+1),this.log.info("Attempting to reconnect to relay",{relay:e,attempt:n+1,delay:i}),setTimeout(()=>this.connectToRelay(e),i);}else this.log.error("Max reconnect attempts reached for relay",{relay:e});},s.onerror=n=>{this.log.error("Relay error",{relay:e,error:String(n)});},this.relayConnections.set(e,s);}handleRelayMessage(e,s){this.updateActivity();try{let n=JSON.parse(s);if(n[0]==="EVENT"&&n[2]){let i=n[2];this.handleNostrEvent(i);}if(n[0]==="OK"){let i=n[1],r=n[2];this.log.debug("Event published",{eventId:i,success:r});}}catch(n){this.log.error("Failed to handle relay message",{error:String(n)});}return Promise.resolve()}async handleNostrEvent(e){if(e.kind!==1||this.processedEventIds.has(e.id))return;if(this.processedEventIds.add(e.id),this.processedEventIds.size>1e4){let n=Array.from(this.processedEventIds);this.processedEventIds=new Set(n.slice(-5e3));}if(e.pubkey===this.botConfig?.publicKey)return;if(e.content?.trim().startsWith("/")){let n=this.buildSessionId(this.id,e.pubkey),i=await this.processCommand({text:e.content,sessionId:n,chatId:e.pubkey,channelInfo:{platform:"nostr",channelId:this.id,userId:e.pubkey,chatId:e.pubkey,eventId:e.id,createdAt:e.created_at},messageId:e.id});if(i.handled){i.reply?await this.createEvent(i.reply):i.gatewayMessage&&await this.handleMessage(i.gatewayMessage);return}}let s=this.toGatewayMessage(e);await this.handleMessage(s);}toGatewayMessage(e){let s=this.buildSessionId(this.id,e.pubkey);return I(s,"input",this.parseContent(e),{channel:{platform:"nostr",channelId:this.id,userId:e.pubkey,chatId:e.pubkey,eventId:e.id,createdAt:e.created_at,tags:e.tags},context:{replyTo:this.findReplyTo(e.tags),conversationId:e.pubkey}})}parseContent(e){let s=[];e.content&&s.push({type:"text",text:e.content});for(let n of e.tags)if(n[0]==="url"&&n[1]){let i=n[1];i.match(/\.(jpg|jpeg|png|gif|webp)$/i)&&s.push({type:"image",image:i});}return s}findReplyTo(e){for(let s of e)if(s[0]==="e"&&s[1])return s[1]}buildSessionId(e,s,n){let i=["nostr",e,s];return n&&i.push(n),i.join("_")}subscribeToRelay(e,s,n){let i=["REQ",s,n];e.send(JSON.stringify(i));}unsubscribeFromRelay(e,s){let n=["CLOSE",s];e.send(JSON.stringify(n));}async createEvent(e,s){let n=[];s&&n.push(["e",s,"","reply"]);let i={id:"",pubkey:this.botConfig?.publicKey??"",created_at:Math.floor(Date.now()/1e3),kind:1,tags:n,content:e,sig:""};return i.id=await this.computeEventId(i),i.sig=await this.signEvent(i),i}async computeEventId(e){let s=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),i=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(r)).map(c=>c.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw 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 es=class extends A{constructor(e){super();chunk6C5TBG7Z_cjs.a(this,"id");chunk6C5TBG7Z_cjs.a(this,"platform");chunk6C5TBG7Z_cjs.a(this,"name");chunk6C5TBG7Z_cjs.a(this,"version");chunk6C5TBG7Z_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 Xr(o){return new es(o)}var ts={telegram:Re,discord:De,slack:Ne,feishu:Le,wechat:Ge,weixin:$e,webchat:We,signal:He,nostr:ze};function Mu(){return Object.keys(ts)}var v=utils.Log.create({service:"gateway:net:registry"});function mn(o){if(!o)return {url:"",protocol:"unsupported"};let t=o.trim();return t.startsWith("ws://")||t.startsWith("wss://")||t.startsWith("acp-ws://")?(t.startsWith("acp-ws://")&&(t=t.replace("acp-ws://","ws://")),t.includes("/acp")||(t=t.replace(/\/$/,"")+"/acp"),{url:t,protocol:"websocket"}):t.startsWith("http://")||t.startsWith("https://")?(t.includes("/acp")||(t=t.replace(/\/$/,"")+"/acp"),{url:t,protocol:"http"}):{url:t,protocol:"unsupported"}}async function Zr(o,t){try{let e=await utils.Fetch.post(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}},{timeout:t});if(!e.ok)return !1;let s=e.data;return !(!s||s.error)}catch{return false}}async function ea(o,t){return new Promise(e=>{let s=null,n=false,i=setTimeout(()=>{n||(n=true,s?.close(),e(false));},t);try{s=new WebSocket(o),s.onopen=()=>{let r={jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}};s.send(JSON.stringify(r));},s.onmessage=r=>{try{let a=JSON.parse(r.data);a.id===1&&!a.error?n||(n=!0,clearTimeout(i),s?.close(),e(!0)):a.error&&(n||(n=!0,clearTimeout(i),s?.close(),e(!1)));}catch{}},s.onerror=()=>{n||(n=!0,clearTimeout(i),e(!1));},s.onclose=()=>{n||(n=!0,clearTimeout(i),e(!1));};}catch{n||(n=true,clearTimeout(i),e(false));}})}async function ta(o,t){try{let e=await utils.Fetch.post(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:1}},{timeout:t});if(!e.ok||!e.data?.result?.agentCapabilities)return [];let s=e.data.result.agentCapabilities,n=[];return s.mcpCapabilities&&(s.mcpCapabilities.http&&n.push("mcp:http"),s.mcpCapabilities.sse&&n.push("mcp:sse")),s.promptCapabilities&&(s.promptCapabilities.image&&n.push("prompt:image"),s.promptCapabilities.embeddedContext&&n.push("prompt:context")),s.sessionCapabilities&&(s.sessionCapabilities.fork&&n.push("session:fork"),s.sessionCapabilities.resume&&n.push("session:resume")),n}catch{return []}}var je=class{constructor(t={}){chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"agents",new Map);chunk6C5TBG7Z_cjs.a(this,"heartbeatTimer",null);chunk6C5TBG7Z_cjs.a(this,"roundRobinIndex",0);chunk6C5TBG7Z_cjs.a(this,"store",null);chunk6C5TBG7Z_cjs.a(this,"eventCallbacks",new Set);let{dataDir:e,...s}=t;this.config={...bt,...s},e&&(this.store=new Te({dataDir:e}));}async load(){if(this.store)try{let t=await this.store.loadAll(),e=Date.now();for(let s of t)e-s.lastHeartbeat>this.config.heartbeatTimeout&&(s.status="unhealthy"),this.agents.set(s.id,s);v.info("Agent registry loaded from storage",{count:t.length});}catch(t){v.error("Failed to load agent registry from storage",{error:String(t)});}}async register(t){if(this.agents.has(t.id))throw new Error(`Agent with ID "${t.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),s={...t,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(t.id,s);let{url:n,protocol:i}=mn(t.address);if(i!=="http"&&i!=="websocket")throw new Error(`Unsupported protocol: ${t.address}. Only http/https/ws/wss are supported`);let r=await ta(n,3e4).catch(()=>[]);r.length>0&&(s.capabilities=r),this.store&&await this.store.save(s),v.info("Agent registered",{agentId:t.id,name:t.name,capabilities:s.capabilities,address:t.address,totalAgents:this.agents.size}),this.emitEvent({type:"register",agent:s});}async deregister(t){let e=this.agents.get(t);if(!e){v.warn("Attempted to deregister unknown agent",{agentId:t});return}this.agents.delete(t),this.store&&await this.store.delete(t),v.info("Agent deregistered",{agentId:t,name:e.name,totalAgents:this.agents.size}),this.emitEvent({type:"deregister",agent:e});}async heartbeat(t,e){let s=this.agents.get(t);if(!s)throw v.warn("Heartbeat received from unknown agent",{agentId:t}),new Error(`Agent "${t}" is not registered`);let n=s.status;s.lastHeartbeat=Date.now(),s.status="healthy",e&&(s.metadata={...s.metadata,...e});let i=6e4,r=Date.now();this.store&&(n!=="healthy"||r-s.lastHeartbeat>=i)&&this.store.save(s).catch(a=>{v.error("Failed to save agent to store",{agentId:t,error:String(a)});}),n!=="healthy"&&this.emitEvent({type:"status_change",agent:s,oldStatus:n});}setStatus(t,e){let s=this.agents.get(t);if(!s){v.warn("Attempted to set status for unknown agent",{agentId:t});return}let n=s.status;n!==e&&(s.status=e,this.store&&this.store.save(s).catch(i=>{v.error("Failed to save agent status to store",{agentId:t,error:String(i)});}),this.emitEvent({type:"status_change",agent:s,oldStatus:n}));}getAgent(t){return this.agents.get(t)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(t=>t.status==="healthy")}selectAgent(t){let{strategy:e,capabilities:s,healthyOnly:n=true}=t,i=n?this.getHealthyAgents():this.getAllAgents();if(s&&s.length>0&&(i=i.filter(a=>s.every(c=>a.capabilities.includes(c)))),i.length===0){v.warn("No agents available for selection",{strategy:e,capabilities:s,healthyOnly:n,totalAgents:this.agents.size});return}let r;switch(e){case "random":r=this.selectRandom(i);break;case "round-robin":r=this.selectRoundRobin(i);break;case "least-connections":r=this.selectLeastConnections(i);break;default:r=this.selectRandom(i);}return v.debug("Agent selected",{agentId:r.id,strategy:e,connectionCount:r.connectionCount}),r}incrementConnection(t){let e=this.agents.get(t);e&&(e.connectionCount++,v.debug("Agent connection incremented",{agentId:t,connectionCount:e.connectionCount}));}decrementConnection(t){let e=this.agents.get(t);e&&e.connectionCount>0&&(e.connectionCount--,v.debug("Agent connection decremented",{agentId:t,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){v.warn("Heartbeat check is already running");return}v.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,v.info("Heartbeat check stopped"));}async checkHeartbeats(){let t=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:s}=this.config,n=[],i=0,r=[];for(let[a,c]of this.agents.entries()){let d=t-c.lastHeartbeat;if(d>s){n.push(a);continue}(d>e||c.status==="unhealthy")&&r.push((async()=>{let{url:g,protocol:p}=mn(c.address),h=this.config.heartbeatTimeout/2;v.debug("Checking agent connectivity",{agentId:a,url:g,protocol:p});let b=false;try{p==="http"?b=await Zr(g,h):b=await ea(g,h);}catch(T){v.debug("Agent connectivity check error",{agentId:a,error:String(T)}),b=false;}let S=c.status;b?(c.lastHeartbeat=t,c.status!=="healthy"&&(c.status="healthy",v.debug("Agent recovered, marked as healthy",{agentId:a,name:c.name,previousStatus:S}),this.store&&this.store.save(c).catch(T=>{v.error("Failed to save agent to store",{agentId:a,error:String(T)});}),this.emitEvent({type:"status_change",agent:c,oldStatus:S}))):c.status==="healthy"&&(c.status="unhealthy",i++,v.warn("Agent marked as unhealthy due to connectivity check failed",{agentId:a,name:c.name,url:g,protocol:p,lastHeartbeat:c.lastHeartbeat,timeSinceLastHeartbeat:d,timeout:e}),this.store&&this.store.save(c).catch(T=>{v.error("Failed to save agent to store",{agentId:a,error:String(T)});}),this.emitEvent({type:"status_change",agent:c,oldStatus:S}));})());}await Promise.all(r);for(let a of n){let c=this.agents.get(a);c&&(v.debug("Auto-deregistering agent due to timeout",{agentId:a,name:c.name,lastHeartbeat:c.lastHeartbeat,timeout:s}),this.agents.delete(a),this.store&&await this.store.delete(a),this.emitEvent({type:"deregister",agent:c}));}(i>0||n.length>0)&&v.debug("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:n.length,totalAgents:this.agents.size});}onEvent(t){this.eventCallbacks.add(t);}offEvent(t){this.eventCallbacks.delete(t);}emitEvent(t){for(let e of this.eventCallbacks)try{e(t);}catch(s){v.error("Agent event callback error",{eventType:t.type,agentId:t.agent.id,error:String(s)});}}selectRandom(t){let e=Math.floor(Math.random()*t.length);return t[e]}selectRoundRobin(t){if(t.length===0)throw new Error("No candidates available for round-robin selection");this.roundRobinIndex>=t.length&&(this.roundRobinIndex=0);let e=t[this.roundRobinIndex];return this.roundRobinIndex=(this.roundRobinIndex+1)%t.length,e}selectLeastConnections(t){return t.reduce((e,s)=>s.connectionCount<e.connectionCount?s:e)}getStats(){let t=this.getAllAgents();return {totalAgents:t.length,healthyAgents:t.filter(e=>e.status==="healthy").length,unhealthyAgents:t.filter(e=>e.status==="unhealthy").length,offlineAgents:t.filter(e=>e.status==="offline").length,totalConnections:t.reduce((e,s)=>e+s.connectionCount,0)}}setAgentStatus(t,e){this.setStatus(t,e);}setLastHeartbeat(t,e){let s=this.agents.get(t);s&&(s.lastHeartbeat=e);}};var x=utils.Log.create({service:"gateway:net:sync-manager"}),qe=class{constructor(t){chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"internalConfig");chunk6C5TBG7Z_cjs.a(this,"registry");chunk6C5TBG7Z_cjs.a(this,"localNodeId");chunk6C5TBG7Z_cjs.a(this,"localNodeName");chunk6C5TBG7Z_cjs.a(this,"remoteNodes",new Map);chunk6C5TBG7Z_cjs.a(this,"remoteAgents",new Map);chunk6C5TBG7Z_cjs.a(this,"syncTimer",null);chunk6C5TBG7Z_cjs.a(this,"cleanupTimer",null);chunk6C5TBG7Z_cjs.a(this,"reconnectTimer",null);chunk6C5TBG7Z_cjs.a(this,"heartbeatTimer",null);chunk6C5TBG7Z_cjs.a(this,"running",false);chunk6C5TBG7Z_cjs.a(this,"agentListChangeCallbacks",new Set);this.registry=t.registry,this.localNodeId=t.localNodeId,this.localNodeName=t.localNodeName,this.config={...St,...t.config},this.internalConfig={maxConcurrentSync:3,remoteAgentTtl:300*1e3,cleanupInterval:180*1e3,maxRetryCount:5,baseRetryDelay:15e3};}async start(){if(this.running){x.warn("Agent sync manager is already running");return}x.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let t of this.config.remoteNodes)this.remoteNodes.set(t.id,{info:{id:t.id,name:t.id,address:t.address,port:t.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced",retryCount:0,nextRetryAt:0});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.cleanupTimer=setInterval(()=>this.cleanupStaleAgents(),this.internalConfig.cleanupInterval),this.reconnectTimer=setInterval(()=>this.reconnectFailedNodes(),this.internalConfig.baseRetryDelay),this.heartbeatTimer=setInterval(()=>this.checkNodeHealth(),6e4),this.registry.onEvent(t=>this.handleLocalAgentEvent(t)),this.running=true,x.info("Agent sync manager started");}async stop(){if(!this.running){x.warn("Agent sync manager is not running");return}x.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,x.info("Agent sync manager stopped");}async pullFromAllNodes(){let t=Array.from(this.remoteNodes.keys()),e=this.internalConfig.maxConcurrentSync;for(let s=0;s<t.length;s+=e){let i=t.slice(s,s+e).map(r=>this.pullFromNode(r).catch(a=>{x.error("Failed to pull from node",{nodeId:r,error:a.message});}));await Promise.all(i);}}async pullFromNode(t){let e=this.remoteNodes.get(t);if(!e)throw new Error(`Unknown remote node: ${t}`);e.status="syncing";let s=this.config.remoteNodes.find(i=>i.id===t);if(!s)throw new Error(`Remote node not found in config: ${t}`);let n=Date.now();try{let i=`http://${s.address}:${s.port}/sync/agents`,r=await utils.Fetch.get(i,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);let a=r.data.agents||[];for(let c of a)c.sourceGatewayId=t,this.remoteAgents.set(c.id,{agent:c,cachedAt:n});return e.lastSyncAt=n,e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",e.retryCount=0,delete e.error,a}catch(i){e.status="error",e.error=i.message,e.info.status="offline";let r=this.calculateRetryDelay(e.retryCount);throw e.retryCount++,e.nextRetryAt=n+r,x.error("Failed to pull from node",{nodeId:t,error:i.message,retryCount:e.retryCount,nextRetryAt:e.nextRetryAt}),i}}calculateRetryDelay(t){let{baseRetryDelay:e,maxRetryCount:s}=this.internalConfig;return Math.min(e*2**t,e*2**s)}async pushEvent(t){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[s]of this.remoteNodes.entries())e.push(this.pushToNode(s,t));await Promise.allSettled(e);}async pushToNode(t,e){let s=this.config.remoteNodes.find(n=>n.id===t);if(!s){x.warn("Unknown remote node for push",{nodeId:t});return}try{let n=`http://${s.address}:${s.port}/sync/events`,i=await utils.Fetch.post(n,e,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}`);x.debug("Pushed event to node",{nodeId:t,eventType:e.type});}catch(n){x.error("Failed to push to node",{nodeId:t,eventType:e.type,error:n.message});}}async handleSyncMessage(t){switch(t.type){case "agent_list_request":await this.handleAgentListRequest(t);break;case "agent_list_response":await this.handleAgentListResponse(t);break;case "agent_register":await this.handleAgentRegister(t);break;case "agent_deregister":await this.handleAgentDeregister(t);break;case "agent_heartbeat":await this.handleAgentHeartbeat(t);break;case "agent_status_change":await this.handleAgentStatusChange(t);break;default:x.warn("Unknown sync message type",{type:t.type});}}async handleAgentListRequest(t){let e=this.getLocalAgentsForSync(),s={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:t.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(t.sourceNodeId,s);}async handleAgentListResponse(t){for(let e of t.agents)this.remoteAgents.set(e.id,{agent:e,cachedAt:Date.now()});this.notifyAgentListChange(t.agents,"add");}async handleAgentRegister(t){let{agent:e}=t,s=this.remoteAgents.get(e.id);if(s){let n=this.resolveConflict(s.agent,e);this.remoteAgents.set(e.id,{agent:n,cachedAt:Date.now()});}else this.remoteAgents.set(e.id,{agent:e,cachedAt:Date.now()});this.notifyAgentListChange([e],"add");}async handleAgentDeregister(t){let{agentId:e}=t,s=this.remoteAgents.get(e);this.remoteAgents.delete(e),s&&this.notifyAgentListChange([s.agent],"remove");}async handleAgentHeartbeat(t){let{agentId:e,heartbeatAt:s,status:n}=t,i=this.remoteAgents.get(e);i&&(i.agent.updatedAt=s,i.agent.status=n,i.cachedAt=Date.now());}async handleAgentStatusChange(t){let{agentId:e,newStatus:s,changedAt:n}=t,i=this.remoteAgents.get(e);if(i){({...i.agent});i.agent.status=s,i.agent.updatedAt=n,i.cachedAt=Date.now(),x.debug("Remote agent status changed",{agentId:e,newStatus:s,sourceNodeId:t.sourceNodeId}),this.notifyAgentListChange([i.agent],"update");}}cleanupStaleAgents(){if(!this.running)return;let t=Date.now(),e=this.internalConfig.remoteAgentTtl,s=0;for(let[n,i]of this.remoteAgents.entries())t-i.cachedAt>e&&(this.remoteAgents.delete(n),s++);s>0&&x.debug("Cleaned up stale remote agents",{cleanedCount:s,remainingCount:this.remoteAgents.size});}async reconnectFailedNodes(){if(!this.running)return;let t=Date.now(),e=[];for(let[s,n]of this.remoteNodes.entries())n.status==="error"&&n.nextRetryAt>0&&t>=n.nextRetryAt&&e.push(s);if(e.length>0){x.debug("Retrying failed nodes",{nodeCount:e.length});for(let s of e)try{await this.pullFromNode(s);}catch{}}}async checkNodeHealth(){if(this.running)for(let[t,e]of this.remoteNodes.entries()){let s=this.config.remoteNodes.find(n=>n.id===t);if(s)try{let n=`http://${s.address}:${s.port}/status`,i=await utils.Fetch.get(n,{timeout:5e3});i.ok?(e.info.status="online",e.retryCount=0,x.debug("Node health check passed",{nodeId:t})):(e.info.status="offline",x.warn("Node health check failed",{nodeId:t,status:i.status}));}catch(n){e.info.status="offline",x.warn("Node health check error",{nodeId:t,error:n.message});}}}async handleLocalAgentEvent(t){if(!this.config.pushEvents.includes(t.type))return;let e=this.agentToSyncInfo(t.agent),s=Date.now();switch(t.type){case "register":await this.pushEvent({type:"agent_register",sourceNodeId:this.localNodeId,timestamp:s,agent:e});break;case "deregister":await this.pushEvent({type:"agent_deregister",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id});break;case "heartbeat":await this.pushEvent({type:"agent_heartbeat",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id,heartbeatAt:t.agent.lastHeartbeat,status:t.agent.status});break;case "status_change":await this.pushEvent({type:"agent_status_change",sourceNodeId:this.localNodeId,timestamp:s,agentId:t.agent.id,oldStatus:t.oldStatus??"healthy",newStatus:t.agent.status,changedAt:s});break}}agentToSyncInfo(t){return {id:t.id,name:t.name,sourceGatewayId:this.localNodeId,address:t.address,capabilities:t.capabilities,status:t.status,updatedAt:t.lastHeartbeat,metadata:t.metadata}}resolveConflict(t,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>t.updatedAt?e:e.updatedAt<t.updatedAt?t:e.id>t.id?e:t;case "local":return t;case "remote":return e;default:return e.updatedAt>t.updatedAt?e:e.updatedAt<t.updatedAt?t:e.id>t.id?e:t}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(t=>this.agentToSyncInfo(t))}notifyAgentListChange(t,e){for(let s of this.agentListChangeCallbacks)try{for(let n of t)s(t,e,n);}catch(n){x.error("Agent list change callback error",{error:String(n)});}}onAgentListChange(t){this.agentListChangeCallbacks.add(t);}offAgentListChange(t){this.agentListChangeCallbacks.delete(t);}getMergedAgentList(){let t=new Map;for(let e of this.getLocalAgentsForSync())t.set(e.id,e);for(let[e,s]of this.remoteAgents.entries())t.has(e)||t.set(e,s.agent);return Array.from(t.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values()).map(t=>t.agent)}getStats(){let t=this.registry.getAllAgents(),e=0,s=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:s++;let n=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(n||0)&&(n=i.lastSyncAt);return {localAgentCount:t.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:t.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:s,lastSyncAt:n}}isRunning(){return this.running}addRemoteNode(t){this.remoteNodes.set(t.id,{info:{id:t.id,name:t.id,address:t.address,port:t.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced",retryCount:0,nextRetryAt:0}),x.debug("Remote node added",{nodeId:t.id,address:t.address});}removeRemoteNode(t){this.remoteNodes.delete(t);for(let[e,s]of this.remoteAgents.entries())s.agent.sourceGatewayId===t&&this.remoteAgents.delete(e);x.debug("Remote node removed",{nodeId:t});}};var G=utils.Log.create({service:"gateway:ws-agent-sync"}),kt=class{constructor(t){chunk6C5TBG7Z_cjs.a(this,"wsServer");chunk6C5TBG7Z_cjs.a(this,"syncManager");chunk6C5TBG7Z_cjs.a(this,"gatewayId");chunk6C5TBG7Z_cjs.a(this,"subscribers",new Map);chunk6C5TBG7Z_cjs.a(this,"getClientWs");this.wsServer=t.wsServer,this.syncManager=t.syncManager,this.getClientWs=t.getClientWs,this.gatewayId=t.wsServer.getGatewayId();}async handleAgentListRequest(t,e){let s=this.getClientWs(t);if(!s){G.warn("Client not found for agent list request",{clientId:t,requestId:e});return}let n=this.syncManager.getMergedAgentList();this.sendMessage(s,{type:"agent_list_response",requestId:e,agents:n});}async handleAgentSubscribe(t,e){let s=this.getClientWs(t);if(!s){G.warn("Client not found for agent subscribe",{clientId:t});return}if(e){this.subscribers.delete(t),this.subscribers.set(t,{clientId:t,ws:s,subscribedAt:Date.now()});let n=this.syncManager.getMergedAgentList();this.sendMessage(s,{type:"agent_list_response",agents:n});}else this.subscribers.delete(t);}broadcastAgentUpdate(t,e){if(this.subscribers.size===0)return;let s={type:"agent_update",action:t,agent:e};for(let[n,i]of this.subscribers.entries())try{i.ws.readyState===i.ws.OPEN&&this.sendMessage(i.ws,s);}catch(r){G.error("Failed to send agent update to client",{clientId:n,error:r.message});}}broadcastAgentList(){if(this.subscribers.size===0)return;let t=this.syncManager.getMergedAgentList();for(let[e,s]of this.subscribers.entries())try{s.ws.readyState===s.ws.OPEN&&this.sendMessage(s.ws,{type:"agent_list_response",requestId:`broadcast_${Date.now()}`,agents:t});}catch(n){G.error("Failed to send agent list to client",{clientId:e,error:n.message});}}cleanupClientSubscription(t){this.subscribers.delete(t);}getSubscriberCount(){return this.subscribers.size}getSubscribers(){return Array.from(this.subscribers.keys())}sendMessage(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e));}async handleAgentRegister(t,e){if(!e.agentId){G.warn("Agent register payload missing agentId",{clientId:t});return}if(!this.getClientWs(t)){G.warn("Client not found for agent register",{clientId:t});return}let n={id:e.agentId,name:e.name??e.agentId,sourceGatewayId:this.gatewayId,address:e.address??"",capabilities:e.capabilities??[],status:"healthy",updatedAt:Date.now(),metadata:e.metadata};try{let i=this.syncManager.registry;if(i.agents.has(n.id)){await i.heartbeat(n.id,n.metadata),G.debug("Agent heartbeat from client",{clientId:t,agentId:n.id});return}let r={...n.metadata,sourceGatewayId:this.gatewayId};await i.register({id:n.id,name:n.name,address:n.address,capabilities:n.capabilities,metadata:r}),G.debug("Agent registered from client",{clientId:t,agentId:n.id,name:n.name}),this.broadcastAgentUpdate("add",n);}catch(i){G.warn("Failed to register agent from client",{clientId:t,agentId:e.agentId,error:String(i)});}}async handleAgentDeregister(t,e){if(!e.agentId){G.warn("Agent deregister payload missing agentId",{clientId:t});return}if(!this.getClientWs(t)){G.warn("Client not found for agent deregister",{clientId:t});return}try{await this.syncManager.registry.deregister(e.agentId),G.debug("Agent deregistered from client",{clientId:t,agentId:e.agentId});let n={id:e.agentId,name:"unknown",sourceGatewayId:this.gatewayId,address:"",capabilities:[],status:"offline",updatedAt:Date.now()};this.broadcastAgentUpdate("remove",n);}catch(n){G.warn("Failed to deregister agent from client",{clientId:t,agentId:e.agentId,error:String(n)});}}async cleanupClient(t){this.subscribers.delete(t);let e=this.syncManager.registry.getAllAgents().filter(s=>s.metadata?.sourceGatewayId===this.gatewayId);for(let s of e)try{await this.syncManager.registry.deregister(s.id);let n={id:s.id,name:s.name,sourceGatewayId:this.gatewayId,address:s.address,capabilities:s.capabilities,status:"offline",updatedAt:Date.now()};this.broadcastAgentUpdate("remove",n);}catch{}}};var le=class le{constructor(t){chunk6C5TBG7Z_cjs.a(this,"log",utils.Log.create({service:"gateway:server"}));chunk6C5TBG7Z_cjs.a(this,"config");chunk6C5TBG7Z_cjs.a(this,"router");chunk6C5TBG7Z_cjs.a(this,"sessionManager");chunk6C5TBG7Z_cjs.a(this,"pluginLoader");chunk6C5TBG7Z_cjs.a(this,"messageStore");chunk6C5TBG7Z_cjs.a(this,"contactStore",null);chunk6C5TBG7Z_cjs.a(this,"wsServer",null);chunk6C5TBG7Z_cjs.a(this,"agentRegistry");chunk6C5TBG7Z_cjs.a(this,"agentSyncManager",null);chunk6C5TBG7Z_cjs.a(this,"wsAgentSync",null);chunk6C5TBG7Z_cjs.a(this,"running",false);chunk6C5TBG7Z_cjs.a(this,"connections",0);chunk6C5TBG7Z_cjs.a(this,"gatewayAgent",null);chunk6C5TBG7Z_cjs.a(this,"bindingLocks",new Map);this.log.debug("GatewayServer.constructor: starting"),this.config=t,this.log.debug("GatewayServer.constructor: creating MessageRouter");let e=ge()?Q().hookRegistry:void 0;this.router=new Ct(e),this.log.debug("GatewayServer.constructor: creating GatewaySessionManager");let s=w();this.sessionManager=new _e({storagePath:`${s.Path.data}/gateway/sessions`,enablePersistence:true}),this.pluginLoader=new Ee({healthCheckInterval:6e4});let n=ge();this.log.debug("GatewayServer.constructor: hasAgentAdapter",{hasAdapter:n}),this.messageStore=new Me({storagePath:`${s.Path.data}/gateway/messages`}),this.agentRegistry=new je({dataDir:`${s.Path.data}/gateway/net`});let i={getSession:r=>{let a=this.sessionManager.get(r);return a?{backendSessionId:a.backendSessionId}:void 0},unbindBackendSession:r=>this.sessionManager.unbindBackendSession(r)};this.pluginLoader.setMessageHandler({onMessage:r=>this.onMessage(r),onEvent:r=>this.onEvent(r),session:i}),this.log.debug("GatewayServer.constructor: completed");}async loadChannelPlugins(){try{let{config:t}=await k(),e=t.channels;if(!e){this.log.debug("no channel config found, skipping plugin loading");return}for(let[s,n]of Object.entries(e)){if(!n?.enabled){this.log.debug("channel disabled or not configured",{platform:s});continue}let i=ts[s];if(!i){this.log.warn("no plugin class found for platform",{platform:s});continue}let r=`${s}-main`,a=new i(r),c={enabled:!0,platform:n,session:{autoCreate:!0,resetPolicy:"onNewConversation"},routing:{broadcast:!0,dispatchToSubAgent:!0}};try{await this.pluginLoader.register(a,c),this.log.info("channel plugin registered",{platform:s,id:r});}catch(d){this.log.error("failed to register channel plugin",{platform:s,error:String(d)});}}}catch(t){this.log.error("failed to load channel plugins",{error:String(t)});}}async start(){if(this.log.debug("GatewayServer.start: called"),this.running){this.log.warn("gateway server is already running");return}this.log.info("starting gateway server",{port:this.config.port,hostname:this.config.hostname}),await this.sessionManager.initialize(),this.log.debug("GatewayServer.start: sessionManager initialized"),await this.agentRegistry.load(),this.log.debug("GatewayServer.start: agentRegistry initialized");let e=`${w().Path.data}/gateway`,s=new ie({baseDir:e});this.contactStore=new ke(s,{cacheSize:1e3}),this.contactStore.initialize&&await this.contactStore.initialize(),this.log.debug("GatewayServer.start: contactStore initialized"),this.wsServer=new re({port:this.config.port,hostname:this.config.hostname,path:String(this.config.path??"/")}),await this.wsServer.start(),this.log.debug("GatewayServer.start: wsServer started"),await this.loadChannelPlugins(),this.pluginLoader.startAll().catch(g=>{this.log.error("plugin startup error",{error:String(g)});}),this.log.debug("GatewayServer.start: plugins startup initiated"),this.pluginLoader.startHealthCheckTimer();let{config:n}=await k(),i=n.defaults;this.wsServer.setChannelResolveDeps({sessionManager:{get:g=>this.sessionManager.get(g),getOrCreate:(g,p)=>this.sessionManager.getOrCreate(g,p),bindBackendSession:(g,p)=>this.sessionManager.bindBackendSession(g,p),findByBackendSessionId:g=>this.sessionManager.findByBackendSessionId(g),getAll:()=>this.sessionManager.getAllSessions()},pluginLoader:{getPlugin:g=>this.pluginLoader.getPlugin(g),getAllPlugins:()=>this.pluginLoader.getAllPlugins(),isRunning:g=>this.pluginLoader.isRunning(g)},defaultChannel:i?.channel,fallbackChannels:i?.fallbackChannels,contactStore:this.contactStore?{findByPlatformId:(g,p)=>this.contactStore.findByPlatformId(g,p),findByUid:g=>this.contactStore.findByUid(g),listByPlatform:(g,p,h)=>this.contactStore.listByPlatform(g,p,h),count:g=>this.contactStore.count(g)}:void 0}),this.wsServer.setPluginLoader((g,p,h)=>this.sendToChannel(g,p,h)),this.wsServer.setRouter(this.router),this.router.setSessionManager({get:g=>this.sessionManager.get(g),bindBackendSession:(g,p)=>this.sessionManager.bindBackendSession(g,p)}),this.pluginLoader.setMessageHandler({onMessage:g=>this.onMessage(g),onEvent:g=>this.onEvent(g),session:{getSession:g=>{let p=this.sessionManager.get(g);return p?{backendSessionId:p.backendSessionId}:void 0},unbindBackendSession:g=>this.sessionManager.unbindBackendSession(g)}}),this.agentSyncManager=new qe({registry:this.agentRegistry,localNodeId:"gateway",localNodeName:"gateway"}),this.wsAgentSync=new kt({wsServer:this.wsServer,syncManager:this.agentSyncManager,getClientWs:g=>this.wsServer.getClientWs(g)}),this.wsServer.setAgentSync(this.wsAgentSync),this.wsServer.setAgentRegistry(this.agentRegistry),this.log.debug("GatewayServer.start: agent sync initialized"),this.log.debug("GatewayServer.start: registering gateway status provider"),hs(async()=>{let g=this.sessionManager.getAllSessions(),p=this.router.getStats?.()??{subscribers:0},h=this.agentRegistry.getStats?.()??{totalAgents:0,healthyAgents:0,unhealthyAgents:0},b=this.wsAgentSync?.getSubscriberCount?.()??0,S=this.wsServer?.getStartTime?.()??0,M=this.pluginLoader.getAllPlugins().filter(U=>this.pluginLoader.isRunning(U.id)).map(U=>({id:U.id,platform:U.platform,name:U.name,version:U.version}));return {status:this.running?"running":"stopped",connections:this.wsServer?.getConnectionCount?.()??0,sessions:g.length,messageSubscriptions:p.subscribers??0,agentSubscriptions:b,uptime:this.running&&S?Date.now()-S:0,version:"1.0.0",agents:{total:h.totalAgents,healthy:h.healthyAgents,unhealthy:h.unhealthyAgents},channels:M}});let r=await this.messageStore.loadFromDisk();this.log.debug("loaded messages from disk",{count:r});let a=Date.now(),c=6e4,d=()=>{let g=Date.now()-a,p=this.pluginLoader.getAllPlugins(),h=p.filter(b=>this.pluginLoader.isRunning(b.id));h.length===p.length&&p.length>0?(this.log.debug("all plugins ready, proceeding with message retry"),this.retryPendingMessages().catch(b=>{this.log.error("failed to retry pending messages",{error:String(b)});})):g>c?(this.log.warn("plugin startup timeout, proceeding with message retry anyway",{elapsed:g}),this.retryPendingMessages().catch(b=>{this.log.error("failed to retry pending messages",{error:String(b)});})):(this.log.debug("waiting for plugins to be ready",{elapsed:g,ready:h.length,total:p.length}),setTimeout(d,100));};d(),this.running=true,this.log.debug("GatewayServer.start: completed"),this.log.info("gateway server started");}async stop(){if(!this.running){this.log.warn("gateway server is not running");return}if(this.log.info("stopping gateway server"),this.wsServer&&(await this.wsServer.stop(),this.wsServer=null,this.log.debug("WebSocket server stopped")),this.pluginLoader.stopHealthCheckTimer(),await this.pluginLoader.stopAll(),await this.router.shutdown(),await this.sessionManager.close(),await this.messageStore.close(),this.contactStore?.close&&await this.contactStore.close(),this.gatewayAgent){try{await this.gatewayAgent.stop();}catch(t){this.log.warn("Failed to stop gatewayAgent during server shutdown",{error:String(t)});}this.gatewayAgent=null;}this.running=false,this.log.info("gateway server stopped");}getStatus(){let t=this.agentRegistry.getStats();return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections,agents:{total:t.totalAgents,healthy:t.healthyAgents,unhealthy:t.unhealthyAgents}}}async onMessage(t){this.log.debug("message received",{id:t.id,sessionId:t.sessionId,type:t.type});let e=this.messageStore.get(t.id);if(e&&e.retryCount>le.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=t.metadata.channel,n=this.buildChannelContext(t,s),i={...t,metadata:{...t.metadata,system:n}},r=true;try{let a=await this.router.route(i);if(r=a.success,!a.dispatched&&t.type==="input"){let{config:c}=await k(),d=c.agentProcessing??{mode:"localAgent",localAgentPriority:1,subAgentPriority:2,timeout:3e5,retryOnFailure:!0};this.log.debug("no subscribers, dispatching to agent",{id:t.id,mode:d.mode}),this.dispatchToAgent(i,d).catch(g=>{this.log.error("agent dispatch failed",{id:t.id,error:String(g)}),r=!1;});}}catch(a){r=false,this.log.error("route failed",{messageId:t.id,error:String(a)});}t.type==="input"&&!r&&await this.messageStore.incrementRetry(t.id);}async saveContactFromMessage(t){if(!this.contactStore)return;let{platform:e,channelId:s,userId:n,chatId:i}=t.metadata.channel;if(!e||e==="api")return;let r=n||i;if(r)try{let a=await this.contactStore.getOrCreate(e,r,{username:t.metadata.channel?.username,displayName:t.metadata.channel?.firstName});this.log.debug("contact saved",{uid:a.uid});}catch(a){this.log.warn("failed to save contact",{platform:e,stableId:r,error:String(a)});}}async dispatchToAgent(t,e){if(!ge()){this.log.debug("no agent adapter, message remains pending",{id:t.id});return}let s=Q(),n=t.metadata.channel,r=this.sessionManager.get(t.sessionId)?.backendSessionId||void 0,a=t.metadata.system;switch(e.mode){case "localAgent":{this.dispatchToGatewayAgent(t,n,a,s,r);break}case "subAgent":{this.dispatchToSubAgent(t,n,a,s,r);break}default:{this.dispatchToGatewayAgent(t,n,a,s,r);break}}}getGatewayAgent(){if(!this.gatewayAgent){if(!Q().sdk)return null;this.gatewayAgent=ms({});}return this.gatewayAgent}dispatchToGatewayAgent(t,e,s,n,i){let r=this.getGatewayAgent();if(!r){this.log.debug("no GatewayAgent available, message remains pending",{id:t.id});return}this.log.debug("dispatching message to GatewayAgent",{id:t.id,sessionId:t.sessionId,backendSessionId:i}),this.triggerHook(plugin.HookEvent.GatewayMessageProcess,{id:t.id,sessionId:t.sessionId,backendSessionId:i,processorId:"gatewayAgent",processType:"gatewayAgent",agent:t?.metadata?.agent??"gateway",timestamp:Date.now()});let a=t.sessionId,d=(this.bindingLocks.get(a)??Promise.resolve()).catch(()=>{}).then(()=>this.resolveAndBindBackendSession(t,e,n,i)).then(g=>{g!==void 0&&this.executeGatewayAgent(t,e,r,g,s);}).catch(g=>{this.log.error("dispatchToGatewayAgent: binding pipeline failed",{id:t.id,sessionId:t.sessionId,error:String(g)}),this.handleAgentError(t,e,g,"gatewayAgent",i);}).finally(()=>{this.bindingLocks.get(a)===d&&this.bindingLocks.delete(a);});this.bindingLocks.set(a,d);}async resolveAndBindBackendSession(t,e,s,n){let r=`Gateway-${e?.platform||"unknown"}`;if(n){try{if((await s.sdk.session.get({sessionId:n})).data)return n}catch(p){this.log.warn("dispatchToGatewayAgent: session.get failed, will re-create",{sessionId:n,error:String(p)});}let g=(await s.sdk.session.create({title:r})).data?.id;if(g)return await this.sessionManager.bindBackendSession(t.sessionId,g),this.log.debug("backend session re-bound (previous session expired)",{gatewaySessionId:t.sessionId,backendSessionId:g}),g;this.log.warn("dispatchToGatewayAgent: session.create returned no id (re-bind)",{messageId:t.id});return}let c=(await s.sdk.session.create({title:r})).data?.id;if(c)return await this.sessionManager.bindBackendSession(t.sessionId,c),this.log.debug("backend session bound (first message)",{gatewaySessionId:t.sessionId,backendSessionId:c}),c;this.log.warn("dispatchToGatewayAgent: session.create returned no id (first bind)",{messageId:t.id});}buildChannelContext(t,e){let s=e?.platform||"unknown",n=e?.userId||e?.chatId||"unknown user",i=`${s}:${n}`,r=e?.chatType||"unknown";return `## External Channel Message
|
|
33
33
|
- Platform: ${s}
|
|
34
34
|
- Chat Type: ${r} (e.g., private, group)
|
|
35
35
|
- From: ${n} (contactUid: ${i})
|
|
@@ -41,4 +41,4 @@ ${g.content}`}),this.log.debug("weixin text file inlined",{fileName:c,mime:a,len
|
|
|
41
41
|
- Use gateway tool to proactively send messages (works for both private and group chats):
|
|
42
42
|
\`\`\`json
|
|
43
43
|
{"operation": "send", "sessionId": "${t.sessionId}", "content": "Your message here"}
|
|
44
|
-
\`\`\``}executeGatewayAgent(t,e,s,n,i){let r={source:n??"",title:`[${e?.platform||"unknown"}] Message from ${e?.userId||e?.chatId||"unknown"}]`,agent:t?.metadata?.agent,parts:t.content,system:i},a=false;s.run(r,{onMessage:c=>{let d=c.text??"";!d||d.trim().length===0||e?.channelId&&(a=true,this.sendToChannel(e.channelId,{id:utils.Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:d}],metadata:{channel:e,processorId:"gatewayAgent",proactive:false,replyToMessageId:t.id,streaming:true,messageId:c.metadata.messageId},timestamp:Date.now()},{}).catch(g=>{this.log.error("executeGatewayAgent: sendToChannel failed in onMessage",{id:t.id,error:String(g)});}));}}).then(c=>{this.handleAgentResult(t,e,c,"gatewayAgent",n,a);},c=>{this.handleAgentError(t,e,c,"gatewayAgent",n);});}handleAgentResult(t,e,s,n,i,r=false){let a=s.metadata.sessionId;a&&this.sessionManager.get(t.sessionId)&&i!==a&&(this.sessionManager.bindBackendSession(t.sessionId,a),this.log.debug("backend session re-bound (session changed during execution)",{gatewaySessionId:t.sessionId,previousBackendSessionId:i,newBackendSessionId:a})),this.triggerHook(plugin.HookEvent.GatewayMessageComplete,{id:t.id,sessionId:t.sessionId,backendSessionId:a||i,processorId:n,status:"completed",timestamp:Date.now()}),s.output&&!r&&e?.channelId&&(this.log.debug("sending response to channel",{id:t.id,channelId:e.channelId,outputLength:s.output.length}),this.sendToChannel(e.channelId,{id:utils.Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:s.output}],metadata:{channel:e,processorId:n,proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}),this.log.debug("agent response sent to channel",{id:t.id,channelId:e.channelId})),this.sessionManager.incrementMessageCount(t.sessionId);}handleAgentError(t,e,s,n,i){this.log.error(`${n} dispatch failed`,{id:t.id,error:String(s)});let r=e?.channelId;if(r){let c=`\u26A0\uFE0F \u5904\u7406\u5931\u8D25: ${s instanceof Error?s.message:String(s)}`;this.sendToChannel(r,{id:utils.Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:c}],metadata:{channel:e,processorId:n,proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}).catch(d=>{this.log.error("failed to send error response",{error:String(d)});});}this.triggerHook(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.debug("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",c=e?.userId||e?.chatId||"unknown user",d=`${a}:${c}`,g={source:t.sessionId,title:`[${a}] Message from ${c}`,agent:"gateway",sessionId:i,parts:t.content,system:s,channel:{platform:a,contactUid:d,channelId:e?.channelId,userId:c}};r.run(g).then(p=>{this.handleAgentResult(t,e,p,"subAgent",i);},p=>{this.handleAgentError(t,e,p,"subAgent",i);});}async triggerHook(t,e){if(ge())try{await Q().hookRegistry.triggerEvent(t,e,{messageStore:{store:async(n,i)=>{let r=Ke(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()-le.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>le.MAX_RETRY_COUNT){this.log.debug("message retry count exceeded, skipping",{messageId:r.id,retryCount:i.retryCount});continue}let a=r.metadata.channel?.channelId;if(!a){this.log.debug("message has no pluginId, skipping",{messageId:r.id});continue}if(!this.pluginLoader.getPlugin(a)||!this.pluginLoader.isRunning(a)){this.log.debug("plugin not available, skipping",{messageId:r.id,pluginId:a});continue}if(r.type==="input")i.status==="processing"&&(this.log.debug("found stuck processing input message, re-dispatching via onMessage",{messageId:r.id,sessionId:s.id}),await this.messageStore.updateStatus(r.id,"pending")),this.onMessage(r).then(()=>{e++;}).catch(d=>{this.log.error("failed to re-dispatch stuck message",{messageId:r.id,error:String(d)});});else if(r.type==="output"){if(i.status!=="pending"&&i.status!=="failed"){this.log.debug("output message not in retryable state, skipping",{messageId:r.id,status:i.status});continue}this.log.debug("retrying output message",{messageId:r.id,pluginId:a,status:i.status}),this.sendToChannel(a,r,{isRetry:true}).then(()=>{e++;}).catch(d=>{this.log.error("failed to retry message",{messageId:r.id,error:String(d)});});}}}this.log.debug("retryPendingMessages completed",{totalProcessed:e});}async onEvent(t){switch(this.log.debug("channel event",{type:t.type,channelId:t.channelId}),t.type){case "connected":this.connections++;break;case "disconnected":this.connections--;break;case "error":this.log.error("channel error",{channelId:t.channelId,data:t.data});break;case "message_delivered":this.log.debug("message delivered event received",{id:t.data?.id,sessionId:t.data?.sessionId,channelId:t.channelId}),await this.triggerHook(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(ge())try{await Q().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(g,p)=>{let h=Ke(g);await this.messageStore.store(h,p);},updateStatus:async(g,p,h)=>{await this.messageStore.updateStatus(g,p,h);}}});}catch{this.log.debug("hook trigger skipped (no context)");}let a=this.pluginLoader.getPlugin(t);if(!a)throw new Error(`Plugin not found: ${t}`);this.log.debug("sendToChannel: calling plugin.send",{pluginId:t,messageId:e.id});let c;try{c=await a.send(e),this.log.debug("sendToChannel: plugin.send completed",{pluginId:t,messageId:e.id,result:c});}catch(d){throw this.log.error("sendToChannel: plugin.send failed",{pluginId:t,messageId:e.id,error:String(d)}),await this.messageStore.incrementRetry(e.id),await this.messageStore.updateStatus(e.id,"failed",{error:String(d)}),d}return c}async sendProactiveMessage(t,e,s,n,i={}){let r={id:utils.Identifier.ascending("message"),sessionId:e,type:"output",content:s,metadata:{channel:n,processorId:i.processorId,agent:i.agent,proactive:true},timestamp:Date.now()};return this.sendToChannel(t,r,{})}getSessionManager(){return this.sessionManager}getRouter(){return this.router}getPluginLoader(){return this.pluginLoader}getMessageStore(){return this.messageStore}getContactStore(){return this.contactStore}async getMessageHistory(t,e){return this.messageStore.getSessionHistory(t,e)}};chunk6C5TBG7Z_cjs.a(le,"MAX_RETRY_COUNT",3),chunk6C5TBG7Z_cjs.a(le,"SEVEN_DAYS_MS",10080*60*1e3);var yn=le;exports.$=I;exports.$a=yn;exports.A=ci;exports.Aa=sr;exports.B=li;exports.Ba=
|
|
44
|
+
\`\`\``}executeGatewayAgent(t,e,s,n,i){let r={source:n??"",title:`[${e?.platform||"unknown"}] Message from ${e?.userId||e?.chatId||"unknown"}]`,agent:t?.metadata?.agent,parts:t.content,system:i},a=false;s.run(r,{onMessage:c=>{let d=c.text??"";!d||d.trim().length===0||e?.channelId&&(a=true,this.sendToChannel(e.channelId,{id:utils.Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:d}],metadata:{channel:e,processorId:"gatewayAgent",proactive:false,replyToMessageId:t.id,streaming:true,messageId:c.metadata.messageId},timestamp:Date.now()},{}).catch(g=>{this.log.error("executeGatewayAgent: sendToChannel failed in onMessage",{id:t.id,error:String(g)});}));}}).then(c=>{this.handleAgentResult(t,e,c,"gatewayAgent",n,a);},c=>{this.handleAgentError(t,e,c,"gatewayAgent",n);});}handleAgentResult(t,e,s,n,i,r=false){let a=s.metadata.sessionId;a&&this.sessionManager.get(t.sessionId)&&i!==a&&(this.sessionManager.bindBackendSession(t.sessionId,a),this.log.debug("backend session re-bound (session changed during execution)",{gatewaySessionId:t.sessionId,previousBackendSessionId:i,newBackendSessionId:a})),this.triggerHook(plugin.HookEvent.GatewayMessageComplete,{id:t.id,sessionId:t.sessionId,backendSessionId:a||i,processorId:n,status:"completed",timestamp:Date.now()}),s.output&&!r&&e?.channelId&&(this.log.debug("sending response to channel",{id:t.id,channelId:e.channelId,outputLength:s.output.length}),this.sendToChannel(e.channelId,{id:utils.Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:s.output}],metadata:{channel:e,processorId:n,proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}),this.log.debug("agent response sent to channel",{id:t.id,channelId:e.channelId})),this.sessionManager.incrementMessageCount(t.sessionId);}handleAgentError(t,e,s,n,i){this.log.error(`${n} dispatch failed`,{id:t.id,error:String(s)});let r=e?.channelId;if(r){let c=`\u26A0\uFE0F \u5904\u7406\u5931\u8D25: ${s instanceof Error?s.message:String(s)}`;this.sendToChannel(r,{id:utils.Identifier.ascending("message"),sessionId:t.sessionId,type:"output",content:[{type:"text",text:c}],metadata:{channel:e,processorId:n,proactive:false,replyToMessageId:t.id},timestamp:Date.now()},{}).catch(d=>{this.log.error("failed to send error response",{error:String(d)});});}this.triggerHook(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.debug("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",c=e?.userId||e?.chatId||"unknown user",d=`${a}:${c}`,g={source:t.sessionId,title:`[${a}] Message from ${c}`,agent:"gateway",sessionId:i,parts:t.content,system:s,channel:{platform:a,contactUid:d,channelId:e?.channelId,userId:c}};r.run(g).then(p=>{this.handleAgentResult(t,e,p,"subAgent",i);},p=>{this.handleAgentError(t,e,p,"subAgent",i);});}async triggerHook(t,e){if(ge())try{await Q().hookRegistry.triggerEvent(t,e,{messageStore:{store:async(n,i)=>{let r=Ke(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()-le.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>le.MAX_RETRY_COUNT){this.log.debug("message retry count exceeded, skipping",{messageId:r.id,retryCount:i.retryCount});continue}let a=r.metadata.channel?.channelId;if(!a){this.log.debug("message has no pluginId, skipping",{messageId:r.id});continue}if(!this.pluginLoader.getPlugin(a)||!this.pluginLoader.isRunning(a)){this.log.debug("plugin not available, skipping",{messageId:r.id,pluginId:a});continue}if(r.type==="input")i.status==="processing"&&(this.log.debug("found stuck processing input message, re-dispatching via onMessage",{messageId:r.id,sessionId:s.id}),await this.messageStore.updateStatus(r.id,"pending")),this.onMessage(r).then(()=>{e++;}).catch(d=>{this.log.error("failed to re-dispatch stuck message",{messageId:r.id,error:String(d)});});else if(r.type==="output"){if(i.status!=="pending"&&i.status!=="failed"){this.log.debug("output message not in retryable state, skipping",{messageId:r.id,status:i.status});continue}this.log.debug("retrying output message",{messageId:r.id,pluginId:a,status:i.status}),this.sendToChannel(a,r,{isRetry:true}).then(()=>{e++;}).catch(d=>{this.log.error("failed to retry message",{messageId:r.id,error:String(d)});});}}}this.log.debug("retryPendingMessages completed",{totalProcessed:e});}async onEvent(t){switch(this.log.debug("channel event",{type:t.type,channelId:t.channelId}),t.type){case "connected":this.connections++;break;case "disconnected":this.connections--;break;case "error":this.log.error("channel error",{channelId:t.channelId,data:t.data});break;case "message_delivered":this.log.debug("message delivered event received",{id:t.data?.id,sessionId:t.data?.sessionId,channelId:t.channelId}),await this.triggerHook(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(ge())try{await Q().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(g,p)=>{let h=Ke(g);await this.messageStore.store(h,p);},updateStatus:async(g,p,h)=>{await this.messageStore.updateStatus(g,p,h);}}});}catch{this.log.debug("hook trigger skipped (no context)");}let a=this.pluginLoader.getPlugin(t);if(!a)throw new Error(`Plugin not found: ${t}`);this.log.debug("sendToChannel: calling plugin.send",{pluginId:t,messageId:e.id});let c;try{c=await a.send(e),this.log.debug("sendToChannel: plugin.send completed",{pluginId:t,messageId:e.id,result:c});}catch(d){throw this.log.error("sendToChannel: plugin.send failed",{pluginId:t,messageId:e.id,error:String(d)}),await this.messageStore.incrementRetry(e.id),await this.messageStore.updateStatus(e.id,"failed",{error:String(d)}),d}return c}async sendProactiveMessage(t,e,s,n,i={}){let r={id:utils.Identifier.ascending("message"),sessionId:e,type:"output",content:s,metadata:{channel:n,processorId:i.processorId,agent:i.agent,proactive:true},timestamp:Date.now()};return this.sendToChannel(t,r,{})}getSessionManager(){return this.sessionManager}getRouter(){return this.router}getPluginLoader(){return this.pluginLoader}getMessageStore(){return this.messageStore}getContactStore(){return this.contactStore}async getMessageHistory(t,e){return this.messageStore.getSessionHistory(t,e)}};chunk6C5TBG7Z_cjs.a(le,"MAX_RETRY_COUNT",3),chunk6C5TBG7Z_cjs.a(le,"SEVEN_DAYS_MS",10080*60*1e3);var yn=le;exports.$=I;exports.$a=yn;exports.A=ci;exports.Aa=sr;exports.B=li;exports.Ba=Cd;exports.C=di;exports.Ca=wd;exports.D=gi;exports.Da=vd;exports.E=ui;exports.Ea=Vt;exports.F=pi;exports.Fa=Jt;exports.G=hi;exports.Ga=Us;exports.H=mi;exports.Ha=It;exports.I=fi;exports.Ia=Td;exports.J=yi;exports.Ja=_d;exports.K=bi;exports.Ka=Os;exports.L=Si;exports.La=$s;exports.M=Ci;exports.Ma=Ws;exports.N=wi;exports.Na=sg;exports.O=ps;exports.Oa=Oe;exports.P=pt;exports.Pa=on;exports.Q=we;exports.Qa=xt;exports.R=ve;exports.Ra=un;exports.S=cs;exports.Sa=$e;exports.T=Gn;exports.Ta=We;exports.U=de;exports.Ua=He;exports.V=so;exports.Va=ze;exports.W=no;exports.Wa=Xr;exports.X=ge;exports.Xa=ts;exports.Y=Q;exports.Ya=Mu;exports.Z=w;exports.Za=je;exports._=Nt;exports._a=qe;exports.a=Ze;exports.aa=Cn;exports.b=et;exports.ba=Ke;exports.c=tt;exports.ca=Ve;exports.d=st;exports.da=Je;exports.e=nt;exports.ea=Et;exports.f=it;exports.fa=Gt;exports.g=rt;exports.ga=vi;exports.h=ns;exports.ha=bt;exports.i=is;exports.ia=St;exports.j=rs;exports.ja=Ii;exports.k=as;exports.ka=Ct;exports.l=os;exports.la=Me;exports.m=at;exports.ma=se;exports.n=ot;exports.na=_e;exports.o=ct;exports.oa=Ee;exports.p=lt;exports.pa=re;exports.q=dt;exports.qa=A;exports.r=gt;exports.ra=Re;exports.s=ut;exports.sa=De;exports.t=Ye;exports.ta=Ne;exports.u=Rt;exports.ua=Le;exports.v=Rn;exports.va=Ge;exports.w=ds;exports.wa=Se;exports.x=gs;exports.xa=Xi;exports.y=us;exports.ya=Yi;exports.z=oi;exports.za=tr;
|