@easbot/gateway 0.3.10 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- '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||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 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(`
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}]
@@ -1,4 +1,4 @@
1
- import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Identifier,Filesystem,TruncateContent,Fetch,PKG,createServer}from'@easbot/utils';import u,{z as z$1}from'zod';import*as pe from'path';import pe__default,{join,extname,basename}from'path';import*as se from'fs';import se__default,{existsSync,readFileSync,writeFileSync,mkdirSync,chmodSync,unlinkSync}from'fs';import*as W from'fs/promises';import W__default,{readFile}from'fs/promises';import {WebSocketServer}from'ws';import Wi from'https';import Hi from'http';import zi,{randomUUID,createHash,randomBytes,createCipheriv,createDecipheriv}from'crypto';import {pathToFileURL,fileURLToPath}from'url';import {homedir,tmpdir}from'os';import {HookEvent}from'@easbot/plugin';function A(o,t,e,s){return {id:Identifier.ascending("message"),sessionId:o,type:t,content:e,metadata:{channel:{platform:s?.channel?.platform??"api",channelId:s?.channel?.channelId??"default",userId:s?.channel?.userId,chatId:s?.channel?.chatId,...Object.fromEntries(Object.entries(s?.channel??{}).filter(([n])=>!["platform","channelId","userId","chatId"].includes(n)))},context:s?.context,agent:s?.agent},timestamp:Date.now()}}function wn(o,t,e,s){return A(o,t,[{type:"text",text:e}],s)}function Ve(o){let t={platform:o.channel?.platform??"api",channelId:o.channel?.channelId??"unknown",chatId:o.channel?.chatId,userId:o.channel?.userId,chatType:o.channel?.chatType,chatTitle:o.channel?.chatTitle};return {id:o.id,sessionId:o.sessionId,type:o.type,content:Array.isArray(o.content)?o.content:[{type:"text",text:String(o.content??"")}],metadata:{channel:t,replyToMessageId:o.replyToMessageId,processorId:o.processorId,agent:o.agent,proactive:o.proactive??!o.replyToMessageId},timestamp:o.timestamp??Date.now()}}function Je(o){if(!o.platform)throw new Error("Invalid session: platform is required");if(!o.channelId)throw new Error("Invalid session: channelId is required");let t=o.chatId??"",e=o.userId??t;if(!t&&!o.userId)throw new Error(`Invalid session: chatId and userId cannot both be empty. platform=${o.platform}, channelId=${o.channelId}`);return [o.platform,o.channelId,t,e].join("_")}function Qe(){return {status:"active",messageCount:0,lastMessageAt:null}}function Xe(o,t){if(!o||!t)throw new Error("platform and stableId are required");return `${o}:${t}`}function Ye(o){if(!o||typeof o!="string")return null;let t=o.indexOf(":");if(t<=0||t>=o.length-1)return null;let e=o.slice(0,t),s=o.slice(t+1);return !e||!s?null:{platform:e,stableId:s}}function _t(o){let{platform:t,stableId:e,profile:s={},aliases:n={},metadata:i}=o;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:Xe(t,e),platform:t,stableId:e,aliases:{...n},profile:{...s},createdAt:r,lastSeenAt:r,metadata:i}}function Et(o,t){return `sub_${o}_${t}`}var In=Log.create({service:"gateway:config"});u.enum(["telegram","slack","feishu","wechat","weixin","webchat","signal","nostr","dingtalk"]);u.enum(["low","medium","high","critical"]);var et=u.object({enabled:u.boolean().default(true),botToken:u.string().describe("Telegram Bot Token"),webhookUrl:u.string().optional().describe("Webhook URL for receiving updates"),polling:u.object({enabled:u.boolean().default(true),interval:u.number().int().positive().optional().describe("Polling interval in ms"),timeout:u.number().int().positive().optional().default(30).describe("Long polling timeout in seconds")}).refine(o=>o===void 0||o.enabled,{message:"polling.enabled must be true when polling is configured"}).optional(),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),tt=u.object({enabled:u.boolean().default(true),botToken:u.string().describe("Slack Bot Token (xoxb-*)"),appToken:u.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:u.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),st=u.object({enabled:u.boolean().default(true),appId:u.string().describe("Feishu App ID"),appSecret:u.string().describe("Feishu App Secret"),encryptKey:u.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:u.string().optional().describe("Feishu Verification Token"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),nt=u.object({enabled:u.boolean().default(true),mode:u.enum(["official","wecom"]).default("official"),appId:u.string().describe("WeChat App ID"),appSecret:u.string().describe("WeChat App Secret"),token:u.string().optional().describe("WeChat Token for message verification"),encodingAESKey:u.string().optional().describe("WeChat Encoding AES Key"),agentId:u.string().optional().describe("WeCom Agent ID"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),An=u.object({enabled:u.boolean().default(true),stateDir:u.string().optional().describe("Override the default account persistence directory (default: ~/.easbot/channels/weixin)"),baseUrl:u.string().optional().describe("Override the iLink API baseUrl (default: https://ilinkai.weixin.qq.com)"),cdnBaseUrl:u.string().optional().describe("Override the CDN baseUrl (default: https://novac2c.cdn.weixin.qq.com/c2c)"),maxMessageLength:u.number().int().positive().optional().default(4e3),timeout:u.number().int().positive().optional().default(3e4)}),it=u.object({enabled:u.boolean().default(true),path:u.string().optional().default("/"),heartbeatInterval:u.number().int().positive().optional().default(3e4),connectionTimeout:u.number().int().positive().optional().default(36e5),maxConnections:u.number().int().positive().optional().default(1e3),cors:u.boolean().optional().default(true)}),rt=u.object({enabled:u.boolean().default(true),serviceUrl:u.string().optional().default("https://chat.signal.org"),phoneNumber:u.string().describe("Signal phone number"),password:u.string().optional().describe("Signal account password"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),at=u.object({enabled:u.boolean().default(true),relays:u.array(u.string()).min(1).describe("Nostr relay URLs"),privateKey:u.string().optional().describe("Nostr private key (hex)"),publicKey:u.string().optional().describe("Nostr public key (hex)"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),Pn=u.object({enabled:u.boolean().default(true),appKey:u.string().describe("DingTalk AppKey"),appSecret:u.string().describe("DingTalk AppSecret"),token:u.string().optional().describe("DingTalk token for signature verification"),encryptKey:u.string().optional().describe("DingTalk encrypt key for message encryption"),webhook:u.object({enabled:u.boolean().default(true),path:u.string().optional().default("/dingtalk/webhook"),port:u.number().int().positive().optional().describe("Webhook server port")}).optional(),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),ns=u.object({telegram:et.optional(),slack:tt.optional(),feishu:st.optional(),wechat:nt.optional(),weixin:An.optional(),webchat:it.optional(),signal:rt.optional(),nostr:at.optional(),dingtalk:Pn.optional()}),is=u.object({enabled:u.boolean().default(false),cert:u.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:u.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:u.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:u.string().optional().describe("Path to SSL key file (alias of key)"),ca:u.string().optional().describe("Path to CA certificate file"),forceRedirect:u.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:u.number().int().positive().optional().default(80).describe("HTTP redirect port")}),xn=u.object({name:u.string().describe("Token name/description"),value:u.string().describe("Token value"),permissions:u.array(u.string()).default(["*"]).describe("Associated permissions"),expiresAt:u.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:u.string().optional().describe("Token description")}),Mn=u.object({enabled:u.boolean().default(true),tokens:u.array(xn).default([]).describe("List of valid tokens"),onInvalid:u.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:u.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:u.array(u.string()).default([]).describe("Default permissions for anonymous users")}),kn=u.object({enabled:u.boolean().default(false),authorizationServer:u.string().describe("OAuth2 authorization server URL"),clientId:u.string().describe("OAuth2 client ID"),clientSecret:u.string().describe("OAuth2 client secret"),tokenValidationEndpoint:u.string().describe("OAuth2 token validation endpoint"),scope:u.array(u.string()).default([]).describe("OAuth2 scopes")}),rs=u.object({type:u.enum(["token","oauth2"]).default("token"),token:Mn.optional(),oauth2:kn.optional()}),as=u.object({mode:u.enum(["pull","push","both"]).default("both"),interval:u.number().int().positive().default(3e4),pushEvents:u.array(u.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:u.enum(["latest","local","remote"]).default("latest")}),Tn=u.object({id:u.string().describe("Gateway node ID"),address:u.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:u.boolean().default(true),metadata:u.record(u.string(),u.any()).optional()}),os=u.object({nodeId:u.string().describe("Current gateway node ID"),nodes:u.array(Tn).default([]).describe("Other gateway nodes in the cluster"),sync:as.optional()}),ot=u.object({maxConnectionsPerChannel:u.number().int().positive().default(100),idleTimeout:u.number().int().positive().default(3e5),reuseStrategy:u.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:u.number().int().positive().default(6e4),acquireTimeout:u.number().int().positive().default(5e3),warmupCount:u.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),ct=u.object({maxLength:u.number().int().positive().default(1e4),concurrency:u.number().int().positive().default(100),batchSize:u.number().int().positive().default(10),batchTimeout:u.number().int().positive().default(100),priorityLevels:u.number().int().positive().default(4)}),lt=u.object({failureThreshold:u.number().int().positive().default(5),successThreshold:u.number().int().positive().default(3),timeout:u.number().int().positive().default(3e4),halfOpenDuration:u.number().int().positive().default(15e3)}),dt=u.object({heartbeatInterval:u.number().int().positive().default(6e4),heartbeatTimeout:u.number().int().positive().default(3e5),heartbeatCheckInterval:u.number().int().positive().default(3e5),autoDeregisterTimeout:u.number().int().positive().default(6e5),maxAgents:u.number().int().positive().default(100),persistenceFile:u.string().optional().describe("Path to persist agent registrations"),maxRegistrations:u.number().int().positive().default(1e3)}),gt=u.object({sessionTimeout:u.number().int().positive().default(18e5),resumeGracePeriod:u.number().int().positive().default(3e5),maxSessions:u.number().int().positive().default(1e4),persistenceFile:u.string().optional().describe("Path to persist sessions")}),ut=u.object({enabled:u.boolean().default(true),port:u.number().int().positive().default(8080),hostname:u.string().default("localhost"),path:u.string().optional().default("/"),maxConnections:u.number().int().positive().optional().default(1e3),connectionTimeout:u.number().int().positive().optional().default(36e5),heartbeatInterval:u.number().int().positive().optional().default(3e4),sessionExpireMs:u.number().int().positive().optional().default(36e5),https:is.optional(),auth:rs.optional(),cors:u.boolean().default(true),corsOrigins:u.array(u.string()).optional(),mdns:u.boolean().default(false),mdnsDomain:u.string().optional().default("gateway.easbot.local")}),_n=u.object({channel:u.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:u.array(u.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),En=u.enum(["localAgent","subAgent","both"]),Rn=u.object({mode:En.default("localAgent").describe("Agent processing mode: localAgent, subAgent, or both"),localAgentPriority:u.number().int().min(1).max(10).default(1).describe("Priority for localAgent (lower = higher priority)"),subAgentPriority:u.number().int().min(1).max(10).default(2).describe("Priority for subAgent (lower = higher priority)"),timeout:u.number().int().positive().optional().default(3e5).describe("Timeout for agent execution in milliseconds"),retryOnFailure:u.boolean().default(true).describe("Retry with subAgent when localAgent fails")}),pt=u.object({autoRegister:u.boolean().default(true).describe("Whether to auto-register agent on startup"),heartbeatInterval:u.number().int().positive().default(3e4).describe("Heartbeat interval in milliseconds"),maxReconnectAttempts:u.number().int().min(0).default(5).describe("Maximum reconnect attempts"),reconnectDelay:u.number().int().positive().default(3e3).describe("Reconnect delay in milliseconds"),heartbeatTimeout:u.number().int().positive().default(9e4).describe("Heartbeat timeout in milliseconds")}),Ze=u.object({server:ut.optional(),channels:ns.optional(),cluster:os.optional(),connectionPool:ot.optional(),messageQueue:ct.optional(),circuitBreaker:lt.optional(),agentRegistry:dt.optional(),session:gt.optional(),defaults:_n.optional(),agentProcessing:Rn.optional(),client:pt.optional().describe("Gateway client config for agent registration"),defaultAgent:u.string().optional().describe("Default agent ID for routing"),logLevel:u.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(u.unknown());function Rt(o){let t=Ze.safeParse(o);return t.success||In.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:Ze.parse({})}function Dn(o){return Ze.parse(o)}var N=Log.create({service:"sdk-event-bus"}),ht=(i=>(i.SDK_SESSION_STATUS="agent.status",i.SDK_ERROR="sdk.error",i.SDK_SESSION_UPDATE="sdk.session_update",i.SDK_PERMISSION_REQUEST="sdk.permission_request",i.SDK_SESSION_DELETED="sdk.session_deleted",i))(ht||{});z$1.object({sessionId:z$1.string(),status:z$1.enum(["idle","busy","retry"]),timestamp:z$1.number()});z$1.object({error:z$1.string(),context:z$1.record(z$1.string(),z$1.any()).optional(),timestamp:z$1.number()});z$1.object({sessionId:z$1.string(),sessionEvent:z$1.unknown(),timestamp:z$1.number()});z$1.object({requestId:z$1.string(),sessionId:z$1.string(),permission:z$1.string(),tool:z$1.object({callId:z$1.string().optional()}).optional(),metadata:z$1.record(z$1.string(),z$1.any()).optional(),timestamp:z$1.number()});z$1.object({sessionId:z$1.string(),timestamp:z$1.number()});var ve=class{constructor(){a(this,"subscriptions",new Map);a(this,"wildcardSubscriptions",new Set);a(this,"destroyed",false);}subscribe(t,e){if(this.destroyed)return N.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{};let s=this.subscriptions.get(t)??new Set;return s.add(e),this.subscriptions.set(t,s),N.debug("Subscribed to event",{eventType:t}),()=>{s.delete(e),s.size===0&&this.subscriptions.delete(t),N.debug("Unsubscribed from event",{eventType:t});}}subscribeAll(t){return this.destroyed?(N.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{}):(this.wildcardSubscriptions.add(t),N.debug("Subscribed to all events"),()=>{this.wildcardSubscriptions.delete(t),N.debug("Unsubscribed from all events");})}async publish(t){if(this.destroyed){N.warn("Cannot publish to destroyed SdkEventBus",{type:t.type});return}N.debug("Publishing event",{type:t.type});let e=this.collectCallbacks(t);if(e.length===0){N.debug("No subscribers for event",{type:t.type});return}let s=await Promise.allSettled(e.map(async r=>{try{await r(t);}catch(a){throw N.error("Event callback error",{type:t.type,error:a instanceof Error?a.message:String(a)}),a}})),n=s.filter(r=>r.status==="fulfilled").length,i=s.filter(r=>r.status==="rejected").length;i>0?N.warn("Event callbacks completed with errors",{type:t.type,fulfilled:n,rejected:i}):N.debug("Event callbacks completed",{type:t.type,count:n});}publishSync(t){if(this.destroyed)return;let e=this.collectCallbacks(t);for(let s of e)Promise.resolve().then(()=>s(t)).catch(n=>{N.error("Event callback error (sync)",{type:t.type,error:n instanceof Error?n.message:String(n)});});}collectCallbacks(t){let e=[],s=this.subscriptions.get(t.type);return s&&e.push(...s),e.push(...this.wildcardSubscriptions),e}subscriberCount(t){return t?this.subscriptions.get(t)?.size??0:this.totalSubscribers()}totalSubscribers(){let t=this.wildcardSubscriptions.size;for(let e of this.subscriptions.values())t+=e.size;return t}hasSubscribers(t){return t?(this.subscriptions.get(t)?.size??0)>0||this.wildcardSubscriptions.size>0:this.totalSubscribers()>0}clear(){this.subscriptions.clear(),this.wildcardSubscriptions.clear(),N.debug("All subscriptions cleared");}destroy(){this.clear(),this.destroyed=true,N.info("SdkEventBus destroyed");}isDestroyed(){return this.destroyed}};var x=Log.create({service:"sdk-event-bridge"}),Ie=class{constructor(t,e,s){a(this,"sdk");a(this,"sdkEventBus");a(this,"abortController",null);a(this,"started",false);a(this,"sessionFilter");a(this,"_cachedPrimaryAgents",null);a(this,"_messageMetaCache",new Map);this.sdk=t,this.sdkEventBus=e,this.sessionFilter=s;}async getMessageMeta(t,e){let s=`${t}:${e}`,n=this._messageMetaCache.get(s);if(n)return n;let i=await this.sdk.session.message({sessionId:t,messageId:e},{throwOnError:true}).then(a=>a.data).catch(a=>{x.error("unexpected error when fetching message",{error:a,sessionId:t,messageId:e});});if(!i)return;let r={role:i.info.role,agent:i.info.agent};return this._messageMetaCache.set(s,r),r}clearMessageMetaCache(t){let e=`${t}:`;for(let s of this._messageMetaCache.keys())s.startsWith(e)&&this._messageMetaCache.delete(s);}async pushSessionEvent(t){let e=t.properties.sessionId??"";if(!e){x.debug("Dropping session event without sessionId",{type:t.type});return}await this.sdkEventBus?.publish({type:"sdk.session_update",properties:{sessionId:e,sessionEvent:t,timestamp:Date.now()}});}async start(){if(this.started){x.warn("SdkEventBridge already started");return}this.started=true,this.abortController=new AbortController,x.info("Starting SDK event bridge"),this.runEventLoop().catch(t=>{if(this.abortController?.signal.aborted){x.debug("Event loop stopped due to abort");return}x.error("Event loop failed",{error:t instanceof Error?t.message:String(t)}),this.sdkEventBus?.publish({type:"sdk.error",properties:{error:t instanceof Error?t.message:String(t),context:{source:"event_loop"},timestamp:Date.now()}});});}async stop(){this.started&&(x.info("Stopping SDK event bridge"),this.started=false,this.abortController?.abort(),this.abortController=null,this._messageMetaCache.clear(),this._cachedPrimaryAgents=null,x.info("SDK event bridge stopped"));}isStarted(){return this.started}async runEventLoop(){for(;;){if(this.abortController?.signal.aborted){x.debug("Event loop aborted");return}try{let t=this.abortController?.signal;if(!t)return;if(t.aborted){x.debug("Event loop aborted before event call");return}let e=await this.sdk.global.event({signal:t});for await(let s of e.stream){if(this.abortController?.signal.aborted){x.debug("Event loop aborted during iteration");return}let n=s?.payload;n&&await this.handleEvent(n).catch(i=>{x.error("Failed to handle event",{error:i instanceof Error?i.message:String(i),type:n.type});});}}catch(t){if(this.abortController?.signal.aborted){x.debug("Event loop aborted, not reconnecting");return}x.error("Event stream error, reconnecting...",{error:t instanceof Error?t.message:String(t)}),await new Promise(e=>setTimeout(e,1e3));}}}async handleEvent(t){switch(x.debug("Handling event",{type:t.type}),t.type){case "permission.asked":await this.handlePermissionAsked(t.properties);break;case "message.part.updated":await this.handleMessagePartUpdated(t.properties);break;case "session.status":await this.handleSessionStatus(t.properties);break;case "session.deleted":await this.handleSessionDeleted(t.properties);break;default:x.debug("Unknown event type, ignoring",{type:t.type});}}async handleSessionDeleted(t){let{sessionId:e}=t;this.sessionFilter&&!this.sessionFilter(e)||(this.clearMessageMetaCache(e),x.debug("Publishing session deleted event to SdkEventBus",{sessionId:e}),await this.sdkEventBus?.publish({type:"sdk.session_deleted",properties:{sessionId:e,timestamp:Date.now()}}));}async handlePermissionAsked(t){let{id:e,sessionId:s,permission:n,tool:i,metadata:r}=t;this.sessionFilter&&!this.sessionFilter(s)||(x.debug("Publishing permission request to SdkEventBus",{id:e,sessionId:s,permission:n}),await this.sdkEventBus?.publish({type:"sdk.permission_request",properties:{requestId:e,sessionId:s,permission:n,tool:i,metadata:r,timestamp:Date.now()}}));}async handleMessagePartUpdated(t){let{part:e,delta:s}=t;if(this.sessionFilter&&!this.sessionFilter(e.sessionId))return;x.debug("Handling message part update",{type:e.type,sessionId:e.sessionId,messageId:e.messageId});let n=await this.getMessageMeta(e.sessionId,e.messageId);!n||n.role!=="assistant"||n.agent&&await this.shouldFilterAgent(n.agent)||(e.type==="tool"?await this.handleToolPart(e):e.type==="text"?await this.handleTextPart(e,s):e.type==="reasoning"?await this.handleReasoningPart(e,s):e.type==="step-start"?await this.handleStepStartPart(e):e.type==="step-finish"&&await this.handleStepFinishPart(e));}async handleToolPart(t){let{sessionId:e,callId:s,tool:n,state:i}=t,r;switch(i.status){case "pending":r={status:"pending"};break;case "running":r={status:"running",input:i.input};break;case "completed":r={status:"completed",input:i.input,output:i.output,title:i.title,metadata:i.metadata};break;case "error":r={status:"error",input:i.input,error:i.error};break;default:x.warn("Unknown tool state, falling back to pending",{tool:n,callId:s,status:i.status}),r={status:"pending"};break}await this.pushSessionEvent({type:"part.updated",properties:{sessionId:e,part:{type:"tool",tool:n,callId:s,state:r}}});}async handleTextPart(t,e){if(t.ignored===true||!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"text",text:n,messageId:t.messageId,time:t.time}}});}async handleStepStartPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-start",messageId:t.messageId}}});}async handleStepFinishPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-finish",messageId:t.messageId,tokens:t.tokens}}});}async handleReasoningPart(t,e){if(!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"reasoning",text:n,messageId:t.messageId,time:t.time}}});}async handleSessionStatus(t){let{sessionId:e,status:s}=t;await this.pushSessionEvent({type:"session.status",properties:{sessionId:e,status:s}}),s.type==="idle"&&this.clearMessageMetaCache(e),x.debug("Session status update sent",{sessionId:e,status:s.type});}async shouldFilterAgent(t){if(!this._cachedPrimaryAgents)try{let s=(await this.sdk.app.agents({})).data||[];this._cachedPrimaryAgents=new Set(s.filter(n=>n.mode==="primary"&&n.hidden!==!0).map(n=>n.name));}catch{this._cachedPrimaryAgents=new Set;}return !this._cachedPrimaryAgents.has(t)}};var mt=Log.create({service:"sdk-message-collector"}),cs={includeThinking:false,includeToolDetails:false,includeToolOutput:false,includeSteps:false},Un={includeThinking:true,includeToolDetails:true,includeToolOutput:true,includeSteps:true},ge=class{constructor(t=cs){a(this,"filterConfig",t);a(this,"events",[]);a(this,"isComplete",false);a(this,"hasTextEnd",false);a(this,"hasStepFinish",false);a(this,"error","");a(this,"sessionStatus","idle");a(this,"sessionId","");a(this,"messageId","");mt.debug("MessageEventCollector created",{filterConfig:t});}addEvent(t){if(!this.shouldIncludeEvent(t)){this.checkCompletion(t);return}this.events.push(t),this.checkCompletion(t);}shouldIncludeEvent(t){if(t.type!=="part.updated")return true;let e=t.properties.part;return e?!(e.type==="reasoning"&&!this.filterConfig.includeThinking||e.type==="tool"&&e.state?.status==="running"&&!this.filterConfig.includeToolDetails||(e.type==="step-start"||e.type==="step-finish")&&!this.filterConfig.includeSteps):true}checkCompletion(t){if(t.properties.sessionId&&(this.sessionId=t.properties.sessionId),t.properties.info?.id&&(this.sessionId=t.properties.info.id),t.type==="part.updated"){let e=t.properties.part;if(!e)return;e.type==="text"&&e.time?.end?(this.hasTextEnd=true,e.messageId&&(this.messageId=e.messageId)):e.type==="step-finish"&&(this.hasStepFinish=true,e.messageId&&(this.messageId=e.messageId));return}if(t.type==="session.status"){let e=t.properties.status?.type;(e==="idle"||e==="busy"||e==="retry")&&(this.sessionStatus=e);return}t.type==="session.error"&&(this.sessionStatus="error",t.properties.error?.data?.message&&(this.error=t.properties.error.data.message));}checkComplete(){return this.isComplete=!!this.error||this.hasTextEnd&&this.hasStepFinish,this.isComplete&&mt.debug("MessageEventCollector.checkComplete",{isComplete:this.isComplete,hasError:!!this.error,hasTextEnd:this.hasTextEnd,hasStepFinish:this.hasStepFinish}),this.isComplete}hasTextEndReady(){return this.hasTextEnd}isTextOnlyComplete(){return this.hasTextEnd&&!this.hasStepFinish&&!this.error}resetForNextMessage(){this.hasTextEnd=false,this.hasStepFinish=false,this.error="",this.isComplete=false,this.events=[];}getSessionStatus(){return this.sessionStatus}getCurrentMessageId(){return this.messageId}assembleMessage(){let t=this.events.filter(a=>a.type==="part.updated"&&a.properties.part?.type==="text"&&a.properties.part?.time?.end).map(a=>a.properties.part.text??"").join(""),e;if(this.filterConfig.includeThinking){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="reasoning"&&c.properties.part?.time?.end).map(c=>{let d=c.properties.part.text??"";return d=d.replace("[REDACTED]","").trim(),d}).filter(c=>c.length>0).join("");a&&(e=a);}let s;if(this.filterConfig.includeToolDetails){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="tool"&&(c.properties.part?.state?.status==="completed"||c.properties.part?.state?.status==="error"));a.length>0&&(s=a.map(c=>{let d=c.properties.part,g=d.state;return {name:d.tool,callId:d.callId,title:g.title,status:g.status,output:this.filterConfig.includeToolOutput?g.output:void 0,error:g.error,input:g.input}}));}let i=this.events.find(a=>a.type==="part.updated"&&a.properties.part?.type==="step-finish")?.properties.part?.tokens,r={role:"assistant",text:t,thinking:e,tools:s,metadata:{sessionId:this.sessionId,sessionStatus:this.sessionStatus,messageId:this.messageId,timestamp:Date.now(),tokens:i?{input:i.input,output:i.output,total:i.input+i.output+i.reasoning}:void 0,error:this.error||void 0}};return mt.debug("Message assembled",{textLength:t.length,thinkingLength:e?.length??0,toolsCount:s?.length??0,isComplete:this.isComplete,includeThinking:this.filterConfig.includeThinking,includeToolDetails:this.filterConfig.includeToolDetails,includeToolOutput:this.filterConfig.includeToolOutput}),r}reset(){this.events=[],this.isComplete=false,this.hasTextEnd=false,this.hasStepFinish=false,this.error="",this.sessionStatus="idle",this.sessionId="",this.messageId="",mt.debug("MessageEventCollector.reset",{hasTextEnd:false,hasStepFinish:false});}};var O=class extends Error{constructor(e,s,n){super(e,{cause:n});a(this,"code",s);this.name="GatewayAgentError";}},Ae=class{constructor(t,e={}){a(this,"sdk",t);a(this,"log",Log.create({service:"gateway:agent"}));a(this,"config");a(this,"filterConfig");a(this,"sessionId");a(this,"eventBus");a(this,"eventBridge");a(this,"bridgeStarted",false);this.config=e,this.filterConfig={includeThinking:e.filterConfig?.includeThinking??false,includeToolDetails:e.filterConfig?.includeToolDetails??false,includeToolOutput:e.filterConfig?.includeToolOutput??true,includeSteps:e.filterConfig?.includeSteps??false},this.eventBus=new ve,this.eventBridge=new Ie(t,this.eventBus);}async getCommandPart(t){let e=t.parts?.find(n=>n.type==="command");if(!e)return;let s=false;try{s=(await this.sdk.command.get({name:e.command})).data?.commandType==="local";}catch(n){this.log.warn("Failed to get command",{command:e.command,error:String(n)});}return {...e,local:s}}async run(t,e){this.log.debug("GatewayAgent.run: starting",{source:t.source,agent:t.agent,partsCount:t.parts?.length??0});let s=await this.getCommandPart(t);return s?s.local?this.runLocalCommand(t,s):this.runPromptCommand(t,s,e):this.runPrompt(t,e)}async runLocalCommand(t,e){this.log.debug("GatewayAgent.runLocalCommand: starting",{command:e.command,arguments:e.arguments});try{let s=await this.ensureSession(t.source);if(!s)throw new O("Failed to create or get session","NO_SESSION");let i=(await this.sdk.session.command({sessionId:s,command:e.command,arguments:e.arguments??"",agent:t.agent,model:t.model?`${t.model.providerId}/${t.model.modelId}`:void 0})).data;return this.log.debug("GatewayAgent.runLocalCommand: completed",{sessionId:s,success:i?.success}),{output:i?.output??"",title:t.title??`Command: ${e.command}`,metadata:{sessionId:s,source:t.source,agent:t.agent,success:i?.success,error:i?.error}}}catch(s){throw this.log.error("GatewayAgent.runLocalCommand: failed",{error:s instanceof Error?s.message:String(s)}),new O(s instanceof Error?s.message:String(s),"COMMAND_ERROR",s instanceof Error?s:void 0)}}async runPromptCommand(t,e,s){this.log.debug("GatewayAgent.runPromptCommand: starting",{command:e.command,arguments:e.arguments});try{let n=await this.ensureSession(t.source);if(!n)throw new O("Failed to create or get session","NO_SESSION");let i=new ge(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=!0);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,S=null,C=()=>{S&&clearTimeout(S);},_=E=>{C();try{a();}catch{}g({messages:p,finishReason:E});};S=setTimeout(()=>{this.log.warn("runPromptCommand: event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),_("timeout");},12e4),a=this.eventBus.subscribeAll(E=>{if(E.type==="sdk.session_update"){let F=E.properties;if(F.sessionId!==n)return;if(i.addEvent(F.sessionEvent),i.checkComplete()){let R=i.assembleMessage();if(p.push(R),i.resetForNextMessage(),!R.text||R.text.trim().length===0){this.log.debug("runPromptCommand: skipping onMessage for empty-text message",{messageId:R.metadata.messageId,hasThinking:!!R.thinking,hasTools:(R.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(R)).catch(te=>{this.log.error("runPromptCommand: onMessage callback error",{error:te instanceof Error?te.message:String(te)});});}}let k=i.getSessionStatus();if(h==="busy"&&k==="idle"&&p.length>0){this.log.debug("runPromptCommand: turn complete (busy -> idle)",{messageCount:p.length}),_("idle");return}(k==="idle"||k==="busy"||k==="retry")&&(h=k);});});await this.sdk.session.command({sessionId:n,command:e.command,arguments:e.arguments??"",agent:t.agent,model:t.model?`${t.model.providerId}/${t.model.modelId}`:void 0});let d=await c;try{a();}catch{}return this.log.debug("GatewayAgent.runPromptCommand: completed",{sessionId:n,command:e.command,messageCount:d.messages.length,finishReason:d.finishReason}),this.assembleResult(d.messages,n,t,d.finishReason)}catch(n){throw this.log.error("GatewayAgent.runPromptCommand: failed",{error:n instanceof Error?n.message:String(n)}),new O(n instanceof Error?n.message:String(n),"COMMAND_ERROR",n instanceof Error?n:void 0)}}async runPrompt(t,e){this.log.debug("GatewayAgent.runPrompt: starting",{source:t.source,agent:t.agent});try{let s=await this.ensureSession(t.source);if(!s)throw new O("Failed to create or get session","NO_SESSION");let n=await this.sendAndCollect(s,t,e);return this.log.debug("GatewayAgent.runPrompt: completed",{sessionId:s,outputLength:n.output.length,messageCount:Array.isArray(n.metadata.messages)?n.metadata.messages.length:void 0}),n}catch(s){throw this.log.error("GatewayAgent.runPrompt: failed",{error:s instanceof Error?s.message:String(s)}),s instanceof O?s:new O(s instanceof Error?s.message:String(s),"EXECUTION_ERROR",s instanceof Error?s:void 0)}}async ensureSession(t){if(t)try{if((await this.sdk.session.get({sessionId:t})).data)return this.sessionId=t,this.log.debug("Using existing session",{sessionId:t}),t}catch{this.log.debug("Session not found, will create new",{sessionId:t});}let e=await this.sdk.session.create({title:"Gateway Session"});if(!e.data?.id)throw new O("Failed to create session","CREATE_SESSION_FAILED");return this.sessionId=e.data.id,this.log.debug("Created new session",{sessionId:this.sessionId}),this.sessionId}async sendAndCollect(t,e,s){let n=[];for(let g of e.parts??[])if(g.type==="text")n.push({type:"text",text:g.text??""});else if(g.type==="image"){let p="";typeof g.image=="string"?p=g.image:g.image instanceof URL?p=g.image.toString():g.image instanceof Uint8Array&&(p=`data:${g.mime??"image/png"};base64,${Buffer.from(g.image).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"image/png"});}else if(g.type==="file"){let p="";typeof g.data=="string"?p=g.data:g.data instanceof URL?p=g.data.toString():g.data instanceof Uint8Array&&(p=`data:${g.mime??"application/octet-stream"};base64,${Buffer.from(g.data).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"application/octet-stream"});}n.length===0&&n.push({type:"text",text:""});let i=new ge(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=true);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,S=null,C=()=>{S&&clearTimeout(S);},_=E=>{C();try{a();}catch{}g({messages:p,finishReason:E});};S=setTimeout(()=>{this.log.warn("Event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),_("timeout");},12e4),a=this.eventBus.subscribeAll(E=>{if(E.type==="sdk.session_update"){let F=E.properties;if(F.sessionId!==t)return;if(i.addEvent(F.sessionEvent),i.checkComplete()){let R=i.assembleMessage();if(p.push(R),i.resetForNextMessage(),this.log.debug("sendAndCollect: message complete",{messageId:R.metadata.messageId,messageCount:p.length,textLength:R.text?.length??0}),!R.text||R.text.trim().length===0){this.log.debug("sendAndCollect: skipping onMessage for empty-text message",{messageId:R.metadata.messageId,hasThinking:!!R.thinking,hasTools:(R.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(R)).catch(te=>{this.log.error("sendAndCollect: onMessage callback error",{error:te instanceof Error?te.message:String(te)});});}}let k=i.getSessionStatus();if(h==="busy"&&k==="idle"&&p.length>0){this.log.debug("sendAndCollect: turn complete (busy -> idle)",{messageCount:p.length}),_("idle");return}(k==="idle"||k==="busy"||k==="retry")&&(h=k);});});await this.sdk.session.prompt({sessionId:t,parts:n,system:e.system,agent:e.agent,model:e.model?{providerId:e.model.providerId,modelId:e.model.modelId}:void 0});let d=await c;try{a();}catch{}return this.assembleResult(d.messages,t,e,d.finishReason)}assembleResult(t,e,s,n="idle"){let i=t.map(c=>this.formatOutput(c)).filter(c=>c.length>0).join(`
1
+ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Identifier,Filesystem,TruncateContent,Fetch,PKG,createServer}from'@easbot/utils';import u,{z as z$1}from'zod';import*as pe from'path';import pe__default,{join,extname,basename}from'path';import*as se from'fs';import se__default,{existsSync,readFileSync,writeFileSync,mkdirSync,chmodSync,unlinkSync}from'fs';import*as W from'fs/promises';import W__default,{readFile}from'fs/promises';import {WebSocketServer}from'ws';import Wi from'https';import Hi from'http';import zi,{randomUUID,createHash,randomBytes,createCipheriv,createDecipheriv}from'crypto';import {pathToFileURL,fileURLToPath}from'url';import {homedir,tmpdir}from'os';import {HookEvent}from'@easbot/plugin';function A(o,t,e,s){return {id:Identifier.ascending("message"),sessionId:o,type:t,content:e,metadata:{channel:{platform:s?.channel?.platform??"api",channelId:s?.channel?.channelId??"default",userId:s?.channel?.userId,chatId:s?.channel?.chatId,...Object.fromEntries(Object.entries(s?.channel??{}).filter(([n])=>!["platform","channelId","userId","chatId"].includes(n)))},context:s?.context,agent:s?.agent},timestamp:Date.now()}}function wn(o,t,e,s){return A(o,t,[{type:"text",text:e}],s)}function Ve(o){let t={platform:o.channel?.platform??"api",channelId:o.channel?.channelId??"unknown",chatId:o.channel?.chatId,userId:o.channel?.userId,chatType:o.channel?.chatType,chatTitle:o.channel?.chatTitle};return {id:o.id,sessionId:o.sessionId,type:o.type,content:Array.isArray(o.content)?o.content:[{type:"text",text:String(o.content??"")}],metadata:{channel:t,replyToMessageId:o.replyToMessageId,processorId:o.processorId,agent:o.agent,proactive:o.proactive??!o.replyToMessageId},timestamp:o.timestamp??Date.now()}}function Je(o){if(!o.platform)throw new Error("Invalid session: platform is required");if(!o.channelId)throw new Error("Invalid session: channelId is required");let t=o.chatId??"",e=o.userId??t;if(!t&&!o.userId)throw new Error(`Invalid session: chatId and userId cannot both be empty. platform=${o.platform}, channelId=${o.channelId}`);return [o.platform,o.channelId,t,e].join("_")}function Qe(){return {status:"active",messageCount:0,lastMessageAt:null}}function Xe(o,t){if(!o||!t)throw new Error("platform and stableId are required");return `${o}:${t}`}function Ye(o){if(!o||typeof o!="string")return null;let t=o.indexOf(":");if(t<=0||t>=o.length-1)return null;let e=o.slice(0,t),s=o.slice(t+1);return !e||!s?null:{platform:e,stableId:s}}function _t(o){let{platform:t,stableId:e,profile:s={},aliases:n={},metadata:i}=o;if(!t||!e)throw new Error("platform and stableId are required");let r=Date.now();return {uid:Xe(t,e),platform:t,stableId:e,aliases:{...n},profile:{...s},createdAt:r,lastSeenAt:r,metadata:i}}function Et(o,t){return `sub_${o}_${t}`}var In=Log.create({service:"gateway:config"});u.enum(["telegram","slack","feishu","wechat","weixin","webchat","signal","nostr","dingtalk"]);u.enum(["low","medium","high","critical"]);var et=u.object({enabled:u.boolean().default(true),botToken:u.string().describe("Telegram Bot Token"),webhookUrl:u.string().optional().describe("Webhook URL for receiving updates"),polling:u.object({enabled:u.boolean().default(true),interval:u.number().int().positive().optional().describe("Polling interval in ms"),timeout:u.number().int().positive().optional().default(30).describe("Long polling timeout in seconds")}).refine(o=>o===void 0||o.enabled,{message:"polling.enabled must be true when polling is configured"}).optional(),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),tt=u.object({enabled:u.boolean().default(true),botToken:u.string().describe("Slack Bot Token (xoxb-*)"),appToken:u.string().optional().describe("Slack App Token (xapp-*) for Socket Mode"),signingSecret:u.string().optional().describe("Slack Signing Secret for webhook verification"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),st=u.object({enabled:u.boolean().default(true),appId:u.string().describe("Feishu App ID"),appSecret:u.string().describe("Feishu App Secret"),encryptKey:u.string().optional().describe("Feishu Encrypt Key for message encryption"),verificationToken:u.string().optional().describe("Feishu Verification Token"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),nt=u.object({enabled:u.boolean().default(true),mode:u.enum(["official","wecom"]).default("official"),appId:u.string().describe("WeChat App ID"),appSecret:u.string().describe("WeChat App Secret"),token:u.string().optional().describe("WeChat Token for message verification"),encodingAESKey:u.string().optional().describe("WeChat Encoding AES Key"),agentId:u.string().optional().describe("WeCom Agent ID"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),An=u.object({enabled:u.boolean().default(true),stateDir:u.string().optional().describe("Override the default account persistence directory (default: ~/.easbot/channels/weixin)"),baseUrl:u.string().optional().describe("Override the iLink API baseUrl (default: https://ilinkai.weixin.qq.com)"),cdnBaseUrl:u.string().optional().describe("Override the CDN baseUrl (default: https://novac2c.cdn.weixin.qq.com/c2c)"),maxMessageLength:u.number().int().positive().optional().default(4e3),timeout:u.number().int().positive().optional().default(3e4)}),it=u.object({enabled:u.boolean().default(true),path:u.string().optional().default("/"),heartbeatInterval:u.number().int().positive().optional().default(3e4),connectionTimeout:u.number().int().positive().optional().default(36e5),maxConnections:u.number().int().positive().optional().default(1e3),cors:u.boolean().optional().default(true)}),rt=u.object({enabled:u.boolean().default(true),serviceUrl:u.string().optional().default("https://chat.signal.org"),phoneNumber:u.string().describe("Signal phone number"),password:u.string().optional().describe("Signal account password"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),at=u.object({enabled:u.boolean().default(true),relays:u.array(u.string()).min(1).describe("Nostr relay URLs"),privateKey:u.string().optional().describe("Nostr private key (hex)"),publicKey:u.string().optional().describe("Nostr public key (hex)"),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),Pn=u.object({enabled:u.boolean().default(true),appKey:u.string().describe("DingTalk AppKey"),appSecret:u.string().describe("DingTalk AppSecret"),token:u.string().optional().describe("DingTalk token for signature verification"),encryptKey:u.string().optional().describe("DingTalk encrypt key for message encryption"),webhook:u.object({enabled:u.boolean().default(true),path:u.string().optional().default("/dingtalk/webhook"),port:u.number().int().positive().optional().describe("Webhook server port")}).optional(),maxConnections:u.number().int().positive().optional().default(100),timeout:u.number().int().positive().optional().default(3e4)}),ns=u.object({telegram:et.optional(),slack:tt.optional(),feishu:st.optional(),wechat:nt.optional(),weixin:An.optional(),webchat:it.optional(),signal:rt.optional(),nostr:at.optional(),dingtalk:Pn.optional()}),is=u.object({enabled:u.boolean().default(false),cert:u.string().describe("Path to SSL certificate file (\u6216 certPath)"),key:u.string().describe("Path to SSL key file (\u6216 keyPath)"),certPath:u.string().optional().describe("Path to SSL certificate file (alias of cert)"),keyPath:u.string().optional().describe("Path to SSL key file (alias of key)"),ca:u.string().optional().describe("Path to CA certificate file"),forceRedirect:u.boolean().optional().default(false).describe("Force redirect HTTP to HTTPS"),httpPort:u.number().int().positive().optional().default(80).describe("HTTP redirect port")}),xn=u.object({name:u.string().describe("Token name/description"),value:u.string().describe("Token value"),permissions:u.array(u.string()).default(["*"]).describe("Associated permissions"),expiresAt:u.number().int().positive().optional().describe("Expiration timestamp (Unix timestamp)"),description:u.string().optional().describe("Token description")}),Mn=u.object({enabled:u.boolean().default(true),tokens:u.array(xn).default([]).describe("List of valid tokens"),onInvalid:u.enum(["reject","anonymous"]).default("reject").describe("Behavior when token validation fails"),allowAnonymous:u.boolean().default(false).describe("Allow anonymous access"),defaultPermissions:u.array(u.string()).default([]).describe("Default permissions for anonymous users")}),kn=u.object({enabled:u.boolean().default(false),authorizationServer:u.string().describe("OAuth2 authorization server URL"),clientId:u.string().describe("OAuth2 client ID"),clientSecret:u.string().describe("OAuth2 client secret"),tokenValidationEndpoint:u.string().describe("OAuth2 token validation endpoint"),scope:u.array(u.string()).default([]).describe("OAuth2 scopes")}),rs=u.object({type:u.enum(["token","oauth2"]).default("token"),token:Mn.optional(),oauth2:kn.optional()}),as=u.object({mode:u.enum(["pull","push","both"]).default("both"),interval:u.number().int().positive().default(3e4),pushEvents:u.array(u.enum(["register","deregister","heartbeat","status_change"])).default(["register","deregister","status_change"]),conflictResolution:u.enum(["latest","local","remote"]).default("latest")}),Tn=u.object({id:u.string().describe("Gateway node ID"),address:u.string().describe("Gateway node address (e.g., http://localhost:3001)"),enabled:u.boolean().default(true),metadata:u.record(u.string(),u.any()).optional()}),os=u.object({nodeId:u.string().describe("Current gateway node ID"),nodes:u.array(Tn).default([]).describe("Other gateway nodes in the cluster"),sync:as.optional()}),ot=u.object({maxConnectionsPerChannel:u.number().int().positive().default(100),idleTimeout:u.number().int().positive().default(3e5),reuseStrategy:u.enum(["lru","fifo","random"]).default("lru"),healthCheckInterval:u.number().int().positive().default(6e4),acquireTimeout:u.number().int().positive().default(5e3),warmupCount:u.number().int().nonnegative().default(0).describe("Number of connections to warm up")}),ct=u.object({maxLength:u.number().int().positive().default(1e4),concurrency:u.number().int().positive().default(100),batchSize:u.number().int().positive().default(10),batchTimeout:u.number().int().positive().default(100),priorityLevels:u.number().int().positive().default(4)}),lt=u.object({failureThreshold:u.number().int().positive().default(5),successThreshold:u.number().int().positive().default(3),timeout:u.number().int().positive().default(3e4),halfOpenDuration:u.number().int().positive().default(15e3)}),dt=u.object({heartbeatInterval:u.number().int().positive().default(6e4),heartbeatTimeout:u.number().int().positive().default(3e5),heartbeatCheckInterval:u.number().int().positive().default(3e5),autoDeregisterTimeout:u.number().int().positive().default(6e5),maxAgents:u.number().int().positive().default(100),persistenceFile:u.string().optional().describe("Path to persist agent registrations"),maxRegistrations:u.number().int().positive().default(1e3)}),gt=u.object({sessionTimeout:u.number().int().positive().default(18e5),resumeGracePeriod:u.number().int().positive().default(3e5),maxSessions:u.number().int().positive().default(1e4),persistenceFile:u.string().optional().describe("Path to persist sessions")}),ut=u.object({enabled:u.boolean().default(true),port:u.number().int().positive().default(8080),hostname:u.string().default("localhost"),path:u.string().optional().default("/"),maxConnections:u.number().int().positive().optional().default(1e3),connectionTimeout:u.number().int().positive().optional().default(36e5),heartbeatInterval:u.number().int().positive().optional().default(3e4),sessionExpireMs:u.number().int().positive().optional().default(36e5),https:is.optional(),auth:rs.optional(),cors:u.boolean().default(true),corsOrigins:u.array(u.string()).optional(),mdns:u.boolean().default(false),mdnsDomain:u.string().optional().default("gateway.easbot.local")}),_n=u.object({channel:u.string().optional().describe("Default channel ID, used when multiple channels are configured"),fallbackChannels:u.array(u.string()).optional().describe("Fallback channel list, sorted by priority, used for degraded channel selection")}),En=u.enum(["localAgent","subAgent","both"]),Rn=u.object({mode:En.default("localAgent").describe("Agent processing mode: localAgent, subAgent, or both"),localAgentPriority:u.number().int().min(1).max(10).default(1).describe("Priority for localAgent (lower = higher priority)"),subAgentPriority:u.number().int().min(1).max(10).default(2).describe("Priority for subAgent (lower = higher priority)"),timeout:u.number().int().positive().optional().default(3e5).describe("Timeout for agent execution in milliseconds"),retryOnFailure:u.boolean().default(true).describe("Retry with subAgent when localAgent fails")}),pt=u.object({autoRegister:u.boolean().default(true).describe("Whether to auto-register agent on startup"),heartbeatInterval:u.number().int().positive().default(3e4).describe("Heartbeat interval in milliseconds"),maxReconnectAttempts:u.number().int().min(0).default(5).describe("Maximum reconnect attempts"),reconnectDelay:u.number().int().positive().default(3e3).describe("Reconnect delay in milliseconds"),heartbeatTimeout:u.number().int().positive().default(9e4).describe("Heartbeat timeout in milliseconds")}),Ze=u.object({server:ut.optional(),channels:ns.optional(),cluster:os.optional(),connectionPool:ot.optional(),messageQueue:ct.optional(),circuitBreaker:lt.optional(),agentRegistry:dt.optional(),session:gt.optional(),defaults:_n.optional(),agentProcessing:Rn.optional(),client:pt.optional().describe("Gateway client config for agent registration"),defaultAgent:u.string().optional().describe("Default agent ID for routing"),logLevel:u.enum(["DEBUG","INFO","WARN","ERROR"]).optional().default("INFO")}).catchall(u.unknown());function Rt(o){let t=Ze.safeParse(o);return t.success||In.warn("Invalid gateway config",{issues:t.error.issues}),t.success?t.data:Ze.parse({})}function Dn(o){return Ze.parse(o)}var N=Log.create({service:"sdk-event-bus"}),ht=(i=>(i.SDK_SESSION_STATUS="agent.status",i.SDK_ERROR="sdk.error",i.SDK_SESSION_UPDATE="sdk.session_update",i.SDK_PERMISSION_REQUEST="sdk.permission_request",i.SDK_SESSION_DELETED="sdk.session_deleted",i))(ht||{});z$1.object({sessionId:z$1.string(),status:z$1.enum(["idle","busy","retry"]),timestamp:z$1.number()});z$1.object({error:z$1.string(),context:z$1.record(z$1.string(),z$1.any()).optional(),timestamp:z$1.number()});z$1.object({sessionId:z$1.string(),sessionEvent:z$1.unknown(),timestamp:z$1.number()});z$1.object({requestId:z$1.string(),sessionId:z$1.string(),permission:z$1.string(),tool:z$1.object({callId:z$1.string().optional()}).optional(),metadata:z$1.record(z$1.string(),z$1.any()).optional(),timestamp:z$1.number()});z$1.object({sessionId:z$1.string(),timestamp:z$1.number()});var ve=class{constructor(){a(this,"subscriptions",new Map);a(this,"wildcardSubscriptions",new Set);a(this,"destroyed",false);}subscribe(t,e){if(this.destroyed)return N.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{};let s=this.subscriptions.get(t)??new Set;return s.add(e),this.subscriptions.set(t,s),N.debug("Subscribed to event",{eventType:t}),()=>{s.delete(e),s.size===0&&this.subscriptions.delete(t),N.debug("Unsubscribed from event",{eventType:t});}}subscribeAll(t){return this.destroyed?(N.warn("Cannot subscribe to destroyed SdkEventBus"),()=>{}):(this.wildcardSubscriptions.add(t),N.debug("Subscribed to all events"),()=>{this.wildcardSubscriptions.delete(t),N.debug("Unsubscribed from all events");})}async publish(t){if(this.destroyed){N.warn("Cannot publish to destroyed SdkEventBus",{type:t.type});return}N.debug("Publishing event",{type:t.type});let e=this.collectCallbacks(t);if(e.length===0){N.debug("No subscribers for event",{type:t.type});return}let s=await Promise.allSettled(e.map(async r=>{try{await r(t);}catch(a){throw N.error("Event callback error",{type:t.type,error:a instanceof Error?a.message:String(a)}),a}})),n=s.filter(r=>r.status==="fulfilled").length,i=s.filter(r=>r.status==="rejected").length;i>0?N.warn("Event callbacks completed with errors",{type:t.type,fulfilled:n,rejected:i}):N.debug("Event callbacks completed",{type:t.type,count:n});}publishSync(t){if(this.destroyed)return;let e=this.collectCallbacks(t);for(let s of e)Promise.resolve().then(()=>s(t)).catch(n=>{N.error("Event callback error (sync)",{type:t.type,error:n instanceof Error?n.message:String(n)});});}collectCallbacks(t){let e=[],s=this.subscriptions.get(t.type);return s&&e.push(...s),e.push(...this.wildcardSubscriptions),e}subscriberCount(t){return t?this.subscriptions.get(t)?.size??0:this.totalSubscribers()}totalSubscribers(){let t=this.wildcardSubscriptions.size;for(let e of this.subscriptions.values())t+=e.size;return t}hasSubscribers(t){return t?(this.subscriptions.get(t)?.size??0)>0||this.wildcardSubscriptions.size>0:this.totalSubscribers()>0}clear(){this.subscriptions.clear(),this.wildcardSubscriptions.clear(),N.debug("All subscriptions cleared");}destroy(){this.clear(),this.destroyed=true,N.info("SdkEventBus destroyed");}isDestroyed(){return this.destroyed}};var x=Log.create({service:"sdk-event-bridge"}),Ie=class{constructor(t,e,s){a(this,"sdk");a(this,"sdkEventBus");a(this,"abortController",null);a(this,"started",false);a(this,"sessionFilter");a(this,"_cachedPrimaryAgents",null);a(this,"_messageMetaCache",new Map);this.sdk=t,this.sdkEventBus=e,this.sessionFilter=s;}async getMessageMeta(t,e){let s=`${t}:${e}`,n=this._messageMetaCache.get(s);if(n)return n;let i=await this.sdk.session.message({sessionId:t,messageId:e},{throwOnError:true}).then(a=>a.data).catch(a=>{x.error("unexpected error when fetching message",{error:a,sessionId:t,messageId:e});});if(!i)return;let r={role:i.info.role,agent:i.info.agent};return this._messageMetaCache.set(s,r),r}clearMessageMetaCache(t){let e=`${t}:`;for(let s of this._messageMetaCache.keys())s.startsWith(e)&&this._messageMetaCache.delete(s);}async pushSessionEvent(t){let e=t.properties.sessionId??"";if(!e){x.debug("Dropping session event without sessionId",{type:t.type});return}await this.sdkEventBus?.publish({type:"sdk.session_update",properties:{sessionId:e,sessionEvent:t,timestamp:Date.now()}});}async start(){if(this.started){x.warn("SdkEventBridge already started");return}this.started=true,this.abortController=new AbortController,x.info("Starting SDK event bridge"),this.runEventLoop().catch(t=>{if(this.abortController?.signal.aborted){x.debug("Event loop stopped due to abort");return}x.error("Event loop failed",{error:t instanceof Error?t.message:String(t)}),this.sdkEventBus?.publish({type:"sdk.error",properties:{error:t instanceof Error?t.message:String(t),context:{source:"event_loop"},timestamp:Date.now()}});});}async stop(){this.started&&(x.info("Stopping SDK event bridge"),this.started=false,this.abortController?.abort(),this.abortController=null,this._messageMetaCache.clear(),this._cachedPrimaryAgents=null,x.info("SDK event bridge stopped"));}isStarted(){return this.started}async runEventLoop(){for(;;){if(this.abortController?.signal.aborted){x.debug("Event loop aborted");return}try{let t=this.abortController?.signal;if(!t)return;if(t.aborted){x.debug("Event loop aborted before event call");return}let e=await this.sdk.global.event({signal:t});for await(let s of e.stream){if(this.abortController?.signal.aborted){x.debug("Event loop aborted during iteration");return}let n=s?.payload;n&&await this.handleEvent(n).catch(i=>{x.error("Failed to handle event",{error:i instanceof Error?i.message:String(i),type:n.type});});}}catch(t){if(this.abortController?.signal.aborted){x.debug("Event loop aborted, not reconnecting");return}x.error("Event stream error, reconnecting...",{error:t instanceof Error?t.message:String(t)}),await new Promise(e=>setTimeout(e,1e3));}}}async handleEvent(t){switch(x.debug("Handling event",{type:t.type}),t.type){case "permission.asked":await this.handlePermissionAsked(t.properties);break;case "message.part.updated":await this.handleMessagePartUpdated(t.properties);break;case "session.status":await this.handleSessionStatus(t.properties);break;case "session.deleted":await this.handleSessionDeleted(t.properties);break;default:x.debug("Unknown event type, ignoring",{type:t.type});}}async handleSessionDeleted(t){let{sessionId:e}=t;this.sessionFilter&&!this.sessionFilter(e)||(this.clearMessageMetaCache(e),x.debug("Publishing session deleted event to SdkEventBus",{sessionId:e}),await this.sdkEventBus?.publish({type:"sdk.session_deleted",properties:{sessionId:e,timestamp:Date.now()}}));}async handlePermissionAsked(t){let{id:e,sessionId:s,permission:n,tool:i,metadata:r}=t;this.sessionFilter&&!this.sessionFilter(s)||(x.debug("Publishing permission request to SdkEventBus",{id:e,sessionId:s,permission:n}),await this.sdkEventBus?.publish({type:"sdk.permission_request",properties:{requestId:e,sessionId:s,permission:n,tool:i,metadata:r,timestamp:Date.now()}}));}async handleMessagePartUpdated(t){let{part:e,delta:s}=t;if(this.sessionFilter&&!this.sessionFilter(e.sessionId))return;x.debug("Handling message part update",{type:e.type,sessionId:e.sessionId,messageId:e.messageId});let n=await this.getMessageMeta(e.sessionId,e.messageId);n?.role==="assistant"&&(n.agent&&await this.shouldFilterAgent(n.agent)||(e.type==="tool"?await this.handleToolPart(e):e.type==="text"?await this.handleTextPart(e,s):e.type==="reasoning"?await this.handleReasoningPart(e,s):e.type==="step-start"?await this.handleStepStartPart(e):e.type==="step-finish"&&await this.handleStepFinishPart(e)));}async handleToolPart(t){let{sessionId:e,callId:s,tool:n,state:i}=t,r;switch(i.status){case "pending":r={status:"pending"};break;case "running":r={status:"running",input:i.input};break;case "completed":r={status:"completed",input:i.input,output:i.output,title:i.title,metadata:i.metadata};break;case "error":r={status:"error",input:i.input,error:i.error};break;default:x.warn("Unknown tool state, falling back to pending",{tool:n,callId:s,status:i.status}),r={status:"pending"};break}await this.pushSessionEvent({type:"part.updated",properties:{sessionId:e,part:{type:"tool",tool:n,callId:s,state:r}}});}async handleTextPart(t,e){if(t.ignored===true||!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"text",text:n,messageId:t.messageId,time:t.time}}});}async handleStepStartPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-start",messageId:t.messageId}}});}async handleStepFinishPart(t){await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"step-finish",messageId:t.messageId,tokens:t.tokens}}});}async handleReasoningPart(t,e){if(!("time"in t&&t.time&&typeof t.time=="object"&&"end"in t.time&&!!t.time.end))return;let n=t.text;n&&await this.pushSessionEvent({type:"part.updated",properties:{sessionId:t.sessionId,part:{type:"reasoning",text:n,messageId:t.messageId,time:t.time}}});}async handleSessionStatus(t){let{sessionId:e,status:s}=t;await this.pushSessionEvent({type:"session.status",properties:{sessionId:e,status:s}}),s.type==="idle"&&this.clearMessageMetaCache(e),x.debug("Session status update sent",{sessionId:e,status:s.type});}async shouldFilterAgent(t){if(!this._cachedPrimaryAgents)try{let s=(await this.sdk.app.agents({})).data||[];this._cachedPrimaryAgents=new Set(s.filter(n=>n.mode==="primary"&&n.hidden!==!0).map(n=>n.name));}catch{this._cachedPrimaryAgents=new Set;}return !this._cachedPrimaryAgents.has(t)}};var mt=Log.create({service:"sdk-message-collector"}),cs={includeThinking:false,includeToolDetails:false,includeToolOutput:false,includeSteps:false},Un={includeThinking:true,includeToolDetails:true,includeToolOutput:true,includeSteps:true},ge=class{constructor(t=cs){a(this,"filterConfig",t);a(this,"events",[]);a(this,"isComplete",false);a(this,"hasTextEnd",false);a(this,"hasStepFinish",false);a(this,"error","");a(this,"sessionStatus","idle");a(this,"sessionId","");a(this,"messageId","");mt.debug("MessageEventCollector created",{filterConfig:t});}addEvent(t){if(!this.shouldIncludeEvent(t)){this.checkCompletion(t);return}this.events.push(t),this.checkCompletion(t);}shouldIncludeEvent(t){if(t.type!=="part.updated")return true;let e=t.properties.part;return e?!(e.type==="reasoning"&&!this.filterConfig.includeThinking||e.type==="tool"&&e.state?.status==="running"&&!this.filterConfig.includeToolDetails||(e.type==="step-start"||e.type==="step-finish")&&!this.filterConfig.includeSteps):true}checkCompletion(t){if(t.properties.sessionId&&(this.sessionId=t.properties.sessionId),t.properties.info?.id&&(this.sessionId=t.properties.info.id),t.type==="part.updated"){let e=t.properties.part;if(!e)return;e.type==="text"&&e.time?.end?(this.hasTextEnd=true,e.messageId&&(this.messageId=e.messageId)):e.type==="step-finish"&&(this.hasStepFinish=true,e.messageId&&(this.messageId=e.messageId));return}if(t.type==="session.status"){let e=t.properties.status?.type;(e==="idle"||e==="busy"||e==="retry")&&(this.sessionStatus=e);return}t.type==="session.error"&&(this.sessionStatus="error",t.properties.error?.data?.message&&(this.error=t.properties.error.data.message));}checkComplete(){return this.isComplete=!!this.error||this.hasTextEnd&&this.hasStepFinish,this.isComplete&&mt.debug("MessageEventCollector.checkComplete",{isComplete:this.isComplete,hasError:!!this.error,hasTextEnd:this.hasTextEnd,hasStepFinish:this.hasStepFinish}),this.isComplete}hasTextEndReady(){return this.hasTextEnd}isTextOnlyComplete(){return this.hasTextEnd&&!this.hasStepFinish&&!this.error}resetForNextMessage(){this.hasTextEnd=false,this.hasStepFinish=false,this.error="",this.isComplete=false,this.events=[];}getSessionStatus(){return this.sessionStatus}getCurrentMessageId(){return this.messageId}assembleMessage(){let t=this.events.filter(a=>a.type==="part.updated"&&a.properties.part?.type==="text"&&a.properties.part?.time?.end).map(a=>a.properties.part.text??"").join(""),e;if(this.filterConfig.includeThinking){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="reasoning"&&c.properties.part?.time?.end).map(c=>{let d=c.properties.part.text??"";return d=d.replace("[REDACTED]","").trim(),d}).filter(c=>c.length>0).join("");a&&(e=a);}let s;if(this.filterConfig.includeToolDetails){let a=this.events.filter(c=>c.type==="part.updated"&&c.properties.part?.type==="tool"&&(c.properties.part?.state?.status==="completed"||c.properties.part?.state?.status==="error"));a.length>0&&(s=a.map(c=>{let d=c.properties.part,g=d.state;return {name:d.tool,callId:d.callId,title:g.title,status:g.status,output:this.filterConfig.includeToolOutput?g.output:void 0,error:g.error,input:g.input}}));}let i=this.events.find(a=>a.type==="part.updated"&&a.properties.part?.type==="step-finish")?.properties.part?.tokens,r={role:"assistant",text:t,thinking:e,tools:s,metadata:{sessionId:this.sessionId,sessionStatus:this.sessionStatus,messageId:this.messageId,timestamp:Date.now(),tokens:i?{input:i.input,output:i.output,total:i.input+i.output+i.reasoning}:void 0,error:this.error||void 0}};return mt.debug("Message assembled",{textLength:t.length,thinkingLength:e?.length??0,toolsCount:s?.length??0,isComplete:this.isComplete,includeThinking:this.filterConfig.includeThinking,includeToolDetails:this.filterConfig.includeToolDetails,includeToolOutput:this.filterConfig.includeToolOutput}),r}reset(){this.events=[],this.isComplete=false,this.hasTextEnd=false,this.hasStepFinish=false,this.error="",this.sessionStatus="idle",this.sessionId="",this.messageId="",mt.debug("MessageEventCollector.reset",{hasTextEnd:false,hasStepFinish:false});}};var O=class extends Error{constructor(e,s,n){super(e,{cause:n});a(this,"code",s);this.name="GatewayAgentError";}},Ae=class{constructor(t,e={}){a(this,"sdk",t);a(this,"log",Log.create({service:"gateway:agent"}));a(this,"config");a(this,"filterConfig");a(this,"sessionId");a(this,"eventBus");a(this,"eventBridge");a(this,"bridgeStarted",false);this.config=e,this.filterConfig={includeThinking:e.filterConfig?.includeThinking??false,includeToolDetails:e.filterConfig?.includeToolDetails??false,includeToolOutput:e.filterConfig?.includeToolOutput??true,includeSteps:e.filterConfig?.includeSteps??false},this.eventBus=new ve,this.eventBridge=new Ie(t,this.eventBus);}async getCommandPart(t){let e=t.parts?.find(n=>n.type==="command");if(!e)return;let s=false;try{s=(await this.sdk.command.get({name:e.command})).data?.commandType==="local";}catch(n){this.log.warn("Failed to get command",{command:e.command,error:String(n)});}return {...e,local:s}}async run(t,e){this.log.debug("GatewayAgent.run: starting",{source:t.source,agent:t.agent,partsCount:t.parts?.length??0});let s=await this.getCommandPart(t);return s?s.local?this.runLocalCommand(t,s):this.runPromptCommand(t,s,e):this.runPrompt(t,e)}async runLocalCommand(t,e){this.log.debug("GatewayAgent.runLocalCommand: starting",{command:e.command,arguments:e.arguments});try{let s=await this.ensureSession(t.source);if(!s)throw new O("Failed to create or get session","NO_SESSION");let i=(await this.sdk.session.command({sessionId:s,command:e.command,arguments:e.arguments??"",agent:t.agent,model:t.model?`${t.model.providerId}/${t.model.modelId}`:void 0})).data;return this.log.debug("GatewayAgent.runLocalCommand: completed",{sessionId:s,success:i?.success}),{output:i?.output??"",title:t.title??`Command: ${e.command}`,metadata:{sessionId:s,source:t.source,agent:t.agent,success:i?.success,error:i?.error}}}catch(s){throw this.log.error("GatewayAgent.runLocalCommand: failed",{error:s instanceof Error?s.message:String(s)}),new O(s instanceof Error?s.message:String(s),"COMMAND_ERROR",s instanceof Error?s:void 0)}}async runPromptCommand(t,e,s){this.log.debug("GatewayAgent.runPromptCommand: starting",{command:e.command,arguments:e.arguments});try{let n=await this.ensureSession(t.source);if(!n)throw new O("Failed to create or get session","NO_SESSION");let i=new ge(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=!0);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,S=null,C=()=>{S&&clearTimeout(S);},_=E=>{C();try{a();}catch{}g({messages:p,finishReason:E});};S=setTimeout(()=>{this.log.warn("runPromptCommand: event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),_("timeout");},12e4),a=this.eventBus.subscribeAll(E=>{if(E.type==="sdk.session_update"){let F=E.properties;if(F.sessionId!==n)return;if(i.addEvent(F.sessionEvent),i.checkComplete()){let R=i.assembleMessage();if(p.push(R),i.resetForNextMessage(),!R.text||R.text.trim().length===0){this.log.debug("runPromptCommand: skipping onMessage for empty-text message",{messageId:R.metadata.messageId,hasThinking:!!R.thinking,hasTools:(R.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(R)).catch(te=>{this.log.error("runPromptCommand: onMessage callback error",{error:te instanceof Error?te.message:String(te)});});}}let k=i.getSessionStatus();if(h==="busy"&&k==="idle"&&p.length>0){this.log.debug("runPromptCommand: turn complete (busy -> idle)",{messageCount:p.length}),_("idle");return}(k==="idle"||k==="busy"||k==="retry")&&(h=k);});});await this.sdk.session.command({sessionId:n,command:e.command,arguments:e.arguments??"",agent:t.agent,model:t.model?`${t.model.providerId}/${t.model.modelId}`:void 0});let d=await c;try{a();}catch{}return this.log.debug("GatewayAgent.runPromptCommand: completed",{sessionId:n,command:e.command,messageCount:d.messages.length,finishReason:d.finishReason}),this.assembleResult(d.messages,n,t,d.finishReason)}catch(n){throw this.log.error("GatewayAgent.runPromptCommand: failed",{error:n instanceof Error?n.message:String(n)}),new O(n instanceof Error?n.message:String(n),"COMMAND_ERROR",n instanceof Error?n:void 0)}}async runPrompt(t,e){this.log.debug("GatewayAgent.runPrompt: starting",{source:t.source,agent:t.agent});try{let s=await this.ensureSession(t.source);if(!s)throw new O("Failed to create or get session","NO_SESSION");let n=await this.sendAndCollect(s,t,e);return this.log.debug("GatewayAgent.runPrompt: completed",{sessionId:s,outputLength:n.output.length,messageCount:Array.isArray(n.metadata.messages)?n.metadata.messages.length:void 0}),n}catch(s){throw this.log.error("GatewayAgent.runPrompt: failed",{error:s instanceof Error?s.message:String(s)}),s instanceof O?s:new O(s instanceof Error?s.message:String(s),"EXECUTION_ERROR",s instanceof Error?s:void 0)}}async ensureSession(t){if(t)try{if((await this.sdk.session.get({sessionId:t})).data)return this.sessionId=t,this.log.debug("Using existing session",{sessionId:t}),t}catch{this.log.debug("Session not found, will create new",{sessionId:t});}let e=await this.sdk.session.create({title:"Gateway Session"});if(!e.data?.id)throw new O("Failed to create session","CREATE_SESSION_FAILED");return this.sessionId=e.data.id,this.log.debug("Created new session",{sessionId:this.sessionId}),this.sessionId}async sendAndCollect(t,e,s){let n=[];for(let g of e.parts??[])if(g.type==="text")n.push({type:"text",text:g.text??""});else if(g.type==="image"){let p="";typeof g.image=="string"?p=g.image:g.image instanceof URL?p=g.image.toString():g.image instanceof Uint8Array&&(p=`data:${g.mime??"image/png"};base64,${Buffer.from(g.image).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"image/png"});}else if(g.type==="file"){let p="";typeof g.data=="string"?p=g.data:g.data instanceof URL?p=g.data.toString():g.data instanceof Uint8Array&&(p=`data:${g.mime??"application/octet-stream"};base64,${Buffer.from(g.data).toString("base64")}`),n.push({type:"file",url:p,mime:g.mime??"application/octet-stream"});}n.length===0&&n.push({type:"text",text:""});let i=new ge(this.filterConfig);i.reset(),i.resetForNextMessage(),this.bridgeStarted||(await this.eventBridge.start(),this.bridgeStarted=true);let r=s?.onMessage,a=()=>{},c=new Promise(g=>{let p=[],h,S=null,C=()=>{S&&clearTimeout(S);},_=E=>{C();try{a();}catch{}g({messages:p,finishReason:E});};S=setTimeout(()=>{this.log.warn("Event collection timeout, returning partial result",{messageCount:p.length,previousStatus:h}),_("timeout");},12e4),a=this.eventBus.subscribeAll(E=>{if(E.type==="sdk.session_update"){let F=E.properties;if(F.sessionId!==t)return;if(i.addEvent(F.sessionEvent),i.checkComplete()){let R=i.assembleMessage();if(p.push(R),i.resetForNextMessage(),this.log.debug("sendAndCollect: message complete",{messageId:R.metadata.messageId,messageCount:p.length,textLength:R.text?.length??0}),!R.text||R.text.trim().length===0){this.log.debug("sendAndCollect: skipping onMessage for empty-text message",{messageId:R.metadata.messageId,hasThinking:!!R.thinking,hasTools:(R.tools?.length??0)>0});return}r&&Promise.resolve().then(()=>r(R)).catch(te=>{this.log.error("sendAndCollect: onMessage callback error",{error:te instanceof Error?te.message:String(te)});});}}let k=i.getSessionStatus();if(h==="busy"&&k==="idle"&&p.length>0){this.log.debug("sendAndCollect: turn complete (busy -> idle)",{messageCount:p.length}),_("idle");return}(k==="idle"||k==="busy"||k==="retry")&&(h=k);});});await this.sdk.session.prompt({sessionId:t,parts:n,system:e.system,agent:e.agent,model:e.model?{providerId:e.model.providerId,modelId:e.model.modelId}:void 0});let d=await c;try{a();}catch{}return this.assembleResult(d.messages,t,e,d.finishReason)}assembleResult(t,e,s,n="idle"){let i=t.map(c=>this.formatOutput(c)).filter(c=>c.length>0).join(`
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}]
@@ -0,0 +1 @@
1
+ 'use strict';var chunkJRI2CLB3_cjs=require('./chunk-JRI2CLB3.cjs');require('./chunk-6C5TBG7Z.cjs');Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.oa}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.$a}});Object.defineProperty(exports,"GatewayWebSocketServer",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.pa}});
@@ -0,0 +1 @@
1
+ export{oa as ChannelPluginLoader,$a as GatewayServer,pa as GatewayWebSocketServer}from'./chunk-VVKUBVKT.mjs';import'./chunk-HQBRVVXS.mjs';
package/dist/index.cjs CHANGED
@@ -1,35 +1,35 @@
1
- 'use strict';var chunkTQ74GHLT_cjs=require('./chunks/chunk-TQ74GHLT.cjs'),chunkCPQSQ7FU_cjs=require('./chunks/chunk-CPQSQ7FU.cjs'),chunk6C5TBG7Z_cjs=require('./chunks/chunk-6C5TBG7Z.cjs'),utils=require('@easbot/utils'),qrcode=require('qrcode'),fs=require('fs'),index_js=require('@modelcontextprotocol/sdk/server/index.js'),stdio_js=require('@modelcontextprotocol/sdk/server/stdio.js'),types_js=require('@modelcontextprotocol/sdk/types.js');var u=utils.Log.create({service:"gateway"}),T=class e extends Error{constructor(t,r,i){super(t);chunk6C5TBG7Z_cjs.a(this,"type");chunk6C5TBG7Z_cjs.a(this,"stage");chunk6C5TBG7Z_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function de(e){let n=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return n.includes(t??"")}function Jt(){process.on("unhandledRejection",e=>{let n=e instanceof Error?e:new Error(String(e));de(n)||u.error("unhandled promise rejection",{error:n.message,stack:n.stack});}),process.on("uncaughtException",e=>{de(e)||(u.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}exports.Gateway=void 0;(_n=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},n,t={server:null,config:null,initialized:false,status:"stopped"};async function r(g={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let p={directory:g.directory??".easbot",printLogs:g.printLogs??false,logLevel:g.logLevel??"INFO"};return e.directory=p.directory,e.initPromise=(async()=>{chunkCPQSQ7FU_cjs.Z();try{Jt();}catch(d){throw new T("Failed to install unhandled exception handlers","server",d instanceof Error?d:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),u.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{e.config=await chunkCPQSQ7FU_cjs.w(p.directory);}catch(d){throw new T("Failed to load gateway configuration","config",d instanceof Error?d:void 0)}e.initialized=true,u.info("gateway runtime initialized",{directory:p.directory,logLevel:p.logLevel});})(),e.initPromise}_n.init=r;function i(){return e.initialized}_n.isInitialized=i;function a(){return n||(n=async()=>{if(!e.initialized)throw new T("Gateway not initialized. Call init() first.","server");let g=chunkCPQSQ7FU_cjs._(),p=await chunkCPQSQ7FU_cjs.w(g.directory);return p.server?.enabled?(t={server:null,config:p,initialized:true,status:"stopped"},u.info("gateway initialized",{port:p.server?.port,hostname:p.server?.hostname}),t):(u.debug("gateway server disabled or not configured"),{server:null,config:p,initialized:true,status:"stopped"})}),n}function o(){return a()()}_n.state=o;async function f(){return (await o()).server}_n.get=f;async function l(){return (await o()).config?.server?.enabled??false}_n.isEnabled=l;async function w(){return (await o()).config}_n.config=w;function m(){return t.status}_n.getStatus=m;async function c(g){u.debug("Gateway.start: called"),e.initialized||await r();let p=await o();if(!(p.config?.server?.enabled??true))throw u.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){u.info("gateway server is already running");return}if(t.status==="starting"){u.info("gateway server is starting");return}t.status="starting";try{let d={...p.config?.server,...g};u.debug("gateway start: creating server with config",{port:d.port,hostname:d.hostname,path:d.path,https:d.https?.enabled});let E=await Ce(d);t.server=E,t.status="running",t.error=void 0,u.info("gateway server started",{port:d.port,hostname:d.hostname});}catch(d){throw t.status="error",t.error=d instanceof Error?d.message:String(d),u.error("failed to start gateway server",{error:t.error}),d}}_n.start=c;async function x(){if(t.status==="stopped"){u.info("gateway server is already stopped");return}if(t.status==="stopping"){u.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,u.info("gateway server stopped");}catch(g){throw t.status="error",t.error=g instanceof Error?g.message:String(g),u.error("failed to stop gateway server",{error:t.error}),g}}_n.stop=x;async function h(g){u.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await x(),await c(g);}_n.restart=h;async function re(){let g=chunkCPQSQ7FU_cjs._(),p=await chunkCPQSQ7FU_cjs.w(g.directory);return t.config=p,e.config=p,u.info("gateway config reloaded"),p}_n.reloadConfig=re;async function Ce(g,p){u.debug("createGatewayServer: starting");let{GatewayServer:q}=await import('./chunks/server-7LXANJ4O.cjs'),d=new q(g),E=p?.startupTimeout??3e4;if(await(async()=>{let k=new Promise((b,Se)=>{setTimeout(()=>{Se(new Error(`Gateway server startup timeout after ${E}ms`));},E);});try{await Promise.race([d.start(),k]);}catch(b){u.error("gateway server start failed, attempting cleanup",{error:b instanceof Error?b.message:String(b)});try{await d.stop();}catch{}throw b}})(),p?.onStarted)try{await p.onStarted(d);}catch(k){u.warn("server started but onStarted callback failed",{error:k instanceof Error?k.message:String(k)});}return u.info("gateway server created and started",{port:g.port,hostname:g.hostname}),d}_n.createGatewayServer=Ce;})(exports.Gateway||(exports.Gateway={}));async function Zt(e){let n=await qrcode.toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${n}
1
+ 'use strict';var chunkTQ74GHLT_cjs=require('./chunks/chunk-TQ74GHLT.cjs'),chunkJRI2CLB3_cjs=require('./chunks/chunk-JRI2CLB3.cjs'),chunk6C5TBG7Z_cjs=require('./chunks/chunk-6C5TBG7Z.cjs'),utils=require('@easbot/utils'),qrcode=require('qrcode'),fs=require('fs'),index_js=require('@modelcontextprotocol/sdk/server/index.js'),stdio_js=require('@modelcontextprotocol/sdk/server/stdio.js'),types_js=require('@modelcontextprotocol/sdk/types.js');var u=utils.Log.create({service:"gateway"}),T=class e extends Error{constructor(t,r,i){super(t);chunk6C5TBG7Z_cjs.a(this,"type");chunk6C5TBG7Z_cjs.a(this,"stage");chunk6C5TBG7Z_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function de(e){let n=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return n.includes(t??"")}function Jt(){process.on("unhandledRejection",e=>{let n=e instanceof Error?e:new Error(String(e));de(n)||u.error("unhandled promise rejection",{error:n.message,stack:n.stack});}),process.on("uncaughtException",e=>{de(e)||(u.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}exports.Gateway=void 0;(_n=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},n,t={server:null,config:null,initialized:false,status:"stopped"};async function r(g={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let p={directory:g.directory??".easbot",printLogs:g.printLogs??false,logLevel:g.logLevel??"INFO"};return e.directory=p.directory,e.initPromise=(async()=>{chunkJRI2CLB3_cjs.Z();try{Jt();}catch(d){throw new T("Failed to install unhandled exception handlers","server",d instanceof Error?d:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),u.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{e.config=await chunkJRI2CLB3_cjs.w(p.directory);}catch(d){throw new T("Failed to load gateway configuration","config",d instanceof Error?d:void 0)}e.initialized=true,u.info("gateway runtime initialized",{directory:p.directory,logLevel:p.logLevel});})(),e.initPromise}_n.init=r;function i(){return e.initialized}_n.isInitialized=i;function a(){return n||(n=async()=>{if(!e.initialized)throw new T("Gateway not initialized. Call init() first.","server");let g=chunkJRI2CLB3_cjs._(),p=await chunkJRI2CLB3_cjs.w(g.directory);return p.server?.enabled?(t={server:null,config:p,initialized:true,status:"stopped"},u.info("gateway initialized",{port:p.server?.port,hostname:p.server?.hostname}),t):(u.debug("gateway server disabled or not configured"),{server:null,config:p,initialized:true,status:"stopped"})}),n}function o(){return a()()}_n.state=o;async function f(){return (await o()).server}_n.get=f;async function l(){return (await o()).config?.server?.enabled??false}_n.isEnabled=l;async function w(){return (await o()).config}_n.config=w;function m(){return t.status}_n.getStatus=m;async function c(g){u.debug("Gateway.start: called"),e.initialized||await r();let p=await o();if(!(p.config?.server?.enabled??true))throw u.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){u.info("gateway server is already running");return}if(t.status==="starting"){u.info("gateway server is starting");return}t.status="starting";try{let d={...p.config?.server,...g};u.debug("gateway start: creating server with config",{port:d.port,hostname:d.hostname,path:d.path,https:d.https?.enabled});let E=await Ce(d);t.server=E,t.status="running",t.error=void 0,u.info("gateway server started",{port:d.port,hostname:d.hostname});}catch(d){throw t.status="error",t.error=d instanceof Error?d.message:String(d),u.error("failed to start gateway server",{error:t.error}),d}}_n.start=c;async function x(){if(t.status==="stopped"){u.info("gateway server is already stopped");return}if(t.status==="stopping"){u.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,u.info("gateway server stopped");}catch(g){throw t.status="error",t.error=g instanceof Error?g.message:String(g),u.error("failed to stop gateway server",{error:t.error}),g}}_n.stop=x;async function h(g){u.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await x(),await c(g);}_n.restart=h;async function re(){let g=chunkJRI2CLB3_cjs._(),p=await chunkJRI2CLB3_cjs.w(g.directory);return t.config=p,e.config=p,u.info("gateway config reloaded"),p}_n.reloadConfig=re;async function Ce(g,p){u.debug("createGatewayServer: starting");let{GatewayServer:q}=await import('./chunks/server-CGEOYYKW.cjs'),d=new q(g),E=p?.startupTimeout??3e4;if(await(async()=>{let k=new Promise((b,Se)=>{setTimeout(()=>{Se(new Error(`Gateway server startup timeout after ${E}ms`));},E);});try{await Promise.race([d.start(),k]);}catch(b){u.error("gateway server start failed, attempting cleanup",{error:b instanceof Error?b.message:String(b)});try{await d.stop();}catch{}throw b}})(),p?.onStarted)try{await p.onStarted(d);}catch(k){u.warn("server started but onStarted callback failed",{error:k instanceof Error?k.message:String(k)});}return u.info("gateway server created and started",{port:g.port,hostname:g.hostname}),d}_n.createGatewayServer=Ce;})(exports.Gateway||(exports.Gateway={}));async function Zt(e){let n=await qrcode.toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${n}
2
2
  `);}async function D(e){let n=await fetch(`${e}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!n.ok)throw new Error(`Failed to get QR code: HTTP ${n.status}`);let t=await n.json();if(!t.qrcode)throw new Error("No qrcode in response");let r=t.qrcode_img_content||"";return r&&await Zt(r),{qrcodeUrl:r,qrcodeId:t.qrcode,message:"Scan the QR code with WeChat to connect."}}async function Z(e){let{qrcodeId:n,apiBaseUrl:t,timeoutMs:r=48e4,maxRetries:i=3}=e,a=Date.now()+r,o=n,f=0;for(;Date.now()<a;){try{let l=new AbortController,w=setTimeout(()=>l.abort(),6e4),m=await fetch(`${t}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(o)}`,{headers:{"iLink-App-ClientVersion":"1"},signal:l.signal});if(clearTimeout(w),!m.ok)throw new Error(`HTTP ${m.status}`);let c=await m.json();switch(c.status){case "confirmed":return {connected:!0,token:c.bot_token,accountId:c.ilink_bot_id,baseUrl:c.baseurl,userId:c.ilink_user_id,message:"Connected to WeChat successfully!"};case "scaned":process.stderr.write(`QR code scanned, waiting for confirmation...
3
3
  `);break;case "expired":{if(f+=1,f>=i)return {connected:!1,message:"QR code expired after maximum retries."};process.stderr.write(`QR code expired, refreshing...
4
4
  `),o=(await D(t)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
5
5
  `);break;default:break}}catch(l){if(l instanceof Error&&l.name==="AbortError")continue;throw l}await new Promise(l=>setTimeout(l,1e3));}return {connected:false,message:"Login timed out."}}function on(e){return ["Claude Code needs your approval.","",`Tool: ${e.tool_name}`,`Reason: ${e.description}`,`Input: ${e.input_preview}`,"",`Reply with: yes ${e.request_id}`,`Or deny with: no ${e.request_id}`].join(`
6
- `)}function an(e){let n=new index_js.Server({name:"weixin",version:e},{capabilities:{experimental:{"claude/channel":{},"claude/channel/permission":{}},tools:{}},instructions:'Messages from WeChat arrive as <channel source="plugin:weixin:weixin" chat_id="..." sender_id="...">. Reply using the reply tool with the chat_id from the channel tag. Use absolute paths for file attachments.'});return n.setRequestHandler(types_js.ListToolsRequestSchema,async()=>({tools:[{name:"reply",description:"Reply to a WeChat message. Pass the chat_id from the channel tag.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The chat_id from the channel notification"},text:{type:"string",description:"The reply text"},files:{type:"array",items:{type:"string"},description:"Optional absolute file paths to attach"}},required:["chat_id","text"]}},{name:"send_typing",description:"Send a typing indicator to a WeChat user.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The chat_id (user ID)"}},required:["chat_id"]}}]})),n.setRequestHandler(types_js.CallToolRequestSchema,async t=>{let{name:r,arguments:i}=t.params,a=chunkCPQSQ7FU_cjs.Ha();if(!a)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let o=a.baseUrl||chunkCPQSQ7FU_cjs.Ea,f=chunkCPQSQ7FU_cjs.Fa;switch(r){case "reply":{let l=typeof i?.chat_id=="string"?i.chat_id:"",w=typeof i?.text=="string"?i.text:"",m=Array.isArray(i?.files)?i.files.filter(x=>typeof x=="string"):void 0;if(!l||!w)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let c=chunkCPQSQ7FU_cjs.Qa(l)||"";try{if(m&&m.length>0){for(let[x,h]of m.entries()){if(!fs.existsSync(h))return {content:[{type:"text",text:`File not found: ${h}`}],isError:!0};await chunkCPQSQ7FU_cjs.Pa({filePath:h,to:l,text:x===0?w:"",baseUrl:o,token:a.token,contextToken:c,cdnBaseUrl:f});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await chunkCPQSQ7FU_cjs.Oa({to:l,text:w,baseUrl:o,token:a.token,contextToken:c}),{content:[{type:"text",text:"Message sent."}]}}catch(x){return {content:[{type:"text",text:`Failed to send: ${x}`}],isError:true}}}case "send_typing":{let l=typeof i?.chat_id=="string"?i.chat_id:"";if(!l)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let w=chunkCPQSQ7FU_cjs.Qa(l),m=await chunkCPQSQ7FU_cjs.Ka(o,a.token,l,w);return m.typing_ticket&&await chunkCPQSQ7FU_cjs.La(o,a.token,{ilink_user_id:l,typing_ticket:m.typing_ticket,status:chunkCPQSQ7FU_cjs.Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(w){return {content:[{type:"text",text:`Failed to send typing: ${w}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${r}`}],isError:true}}}),n}async function ue(e,n){n.enableConfigs(),n.initializeAnalyticsSink();let t=chunkCPQSQ7FU_cjs.Ha();t||(process.stderr.write("[weixin] No account configured. Run `easbot weixin login` to connect your WeChat account.\n"),await Promise.all([n.shutdown1PEventLogging(),n.shutdownDatadog()]),process.exit(1));let r=an(e),i=new stdio_js.StdioServerTransport;n.registerPermissionHandler(r,async c=>{let x=c.channel_context?.chat_id,h=x?{chatId:x,contextToken:chunkCPQSQ7FU_cjs.Qa(x)}:chunkTQ74GHLT_cjs.b();if(!h){n.logForDebugging(`[Weixin MCP] No active chat available for permission request ${c.request_id}`);return}try{chunkTQ74GHLT_cjs.c(c,h.chatId,h.contextToken),await chunkCPQSQ7FU_cjs.Oa({to:h.chatId,text:on(c),baseUrl:a,token:t.token,contextToken:h.contextToken||""});}catch(re){process.stderr.write(`[weixin] Failed to relay permission request ${c.request_id}: ${re}
7
- `);}}),await r.connect(i);let a=t.baseUrl||chunkCPQSQ7FU_cjs.Ea,o=new AbortController,f=false,l=async()=>{f||(f=true,o.signal.aborted||o.abort(),await Promise.all([n.shutdown1PEventLogging(),n.shutdownDatadog()]),process.exit(0));};process.stdin.on("end",()=>{l();}),process.stdin.on("error",()=>{l();}),process.on("SIGINT",()=>{l();}),process.on("SIGTERM",()=>{l();}),process.on("SIGHUP",()=>{l();});let w=process.ppid,m=setInterval(()=>{try{process.kill(w,0);}catch{process.stderr.write(`[weixin] Parent process exited, shutting down...
8
- `),clearInterval(m),l();}},5e3);n.logForDebugging("[Weixin MCP] Starting poll loop"),await chunkCPQSQ7FU_cjs.Ra({baseUrl:a,cdnBaseUrl:chunkCPQSQ7FU_cjs.Fa,token:t.token,onMessage:async c=>{await r.notification({method:"notifications/claude/channel",params:{content:c.text,meta:{chat_id:c.fromUserId,sender_id:c.fromUserId,message_id:c.messageId,...c.attachmentPath&&{attachment_path:c.attachmentPath},...c.attachmentType&&{attachment_type:c.attachmentType}}}});},onPermissionResponse:async c=>{await r.notification({method:"notifications/claude/channel/permission",params:{request_id:c.requestId,behavior:c.behavior}});},abortSignal:o.signal}),clearInterval(m),await l();}var pe={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var ln=pe.languages,gn=ln.filter(e=>e.supported).map(e=>e.value),v={defaultLocale:"zh-CN",locales:gn},P={},N=(e,n)=>{let t=P[e]||{translation:{}};return P[e]={translation:{...t.translation,...n.translation}},P[e]},F=(e=v.defaultLocale)=>(P[e]||N(e,{translation:{}}),{locale:e,resources:P[e]||{translation:{}}});var dn={translation:{"weixin.sdk.cli.usage":["\u7528\u6CD5\uFF1A"," easbot weixin serve"," easbot weixin login"," easbot weixin login clear"," easbot weixin access pair <code>","","\u5F53\u524D\u7528\u6237\uFF08\u4ECE account.json \u8BFB\u53D6\uFF09\uFF1A"," easbot weixin user",' easbot weixin ensure-user [--display-name "<name>"]'," easbot weixin remove-user"].join(`
6
+ `)}function an(e){let n=new index_js.Server({name:"weixin",version:e},{capabilities:{experimental:{"claude/channel":{},"claude/channel/permission":{}},tools:{}},instructions:'Messages from WeChat arrive as <channel source="plugin:weixin:weixin" chat_id="..." sender_id="...">. Reply using the reply tool with the chat_id from the channel tag. Use absolute paths for file attachments.'});return n.setRequestHandler(types_js.ListToolsRequestSchema,async()=>({tools:[{name:"reply",description:"Reply to a WeChat message. Pass the chat_id from the channel tag.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The chat_id from the channel notification"},text:{type:"string",description:"The reply text"},files:{type:"array",items:{type:"string"},description:"Optional absolute file paths to attach"}},required:["chat_id","text"]}},{name:"send_typing",description:"Send a typing indicator to a WeChat user.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The chat_id (user ID)"}},required:["chat_id"]}}]})),n.setRequestHandler(types_js.CallToolRequestSchema,async t=>{let{name:r,arguments:i}=t.params,a=chunkJRI2CLB3_cjs.Ha();if(!a)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let o=a.baseUrl||chunkJRI2CLB3_cjs.Ea,f=chunkJRI2CLB3_cjs.Fa;switch(r){case "reply":{let l=typeof i?.chat_id=="string"?i.chat_id:"",w=typeof i?.text=="string"?i.text:"",m=Array.isArray(i?.files)?i.files.filter(x=>typeof x=="string"):void 0;if(!l||!w)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let c=chunkJRI2CLB3_cjs.Qa(l)||"";try{if(m&&m.length>0){for(let[x,h]of m.entries()){if(!fs.existsSync(h))return {content:[{type:"text",text:`File not found: ${h}`}],isError:!0};await chunkJRI2CLB3_cjs.Pa({filePath:h,to:l,text:x===0?w:"",baseUrl:o,token:a.token,contextToken:c,cdnBaseUrl:f});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await chunkJRI2CLB3_cjs.Oa({to:l,text:w,baseUrl:o,token:a.token,contextToken:c}),{content:[{type:"text",text:"Message sent."}]}}catch(x){return {content:[{type:"text",text:`Failed to send: ${x}`}],isError:true}}}case "send_typing":{let l=typeof i?.chat_id=="string"?i.chat_id:"";if(!l)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let w=chunkJRI2CLB3_cjs.Qa(l),m=await chunkJRI2CLB3_cjs.Ka(o,a.token,l,w);return m.typing_ticket&&await chunkJRI2CLB3_cjs.La(o,a.token,{ilink_user_id:l,typing_ticket:m.typing_ticket,status:chunkJRI2CLB3_cjs.Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(w){return {content:[{type:"text",text:`Failed to send typing: ${w}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${r}`}],isError:true}}}),n}async function ue(e,n){n.enableConfigs(),n.initializeAnalyticsSink();let t=chunkJRI2CLB3_cjs.Ha();t||(process.stderr.write("[weixin] No account configured. Run `easbot weixin login` to connect your WeChat account.\n"),await Promise.all([n.shutdown1PEventLogging(),n.shutdownDatadog()]),process.exit(1));let r=an(e),i=new stdio_js.StdioServerTransport;n.registerPermissionHandler(r,async c=>{let x=c.channel_context?.chat_id,h=x?{chatId:x,contextToken:chunkJRI2CLB3_cjs.Qa(x)}:chunkTQ74GHLT_cjs.b();if(!h){n.logForDebugging(`[Weixin MCP] No active chat available for permission request ${c.request_id}`);return}try{chunkTQ74GHLT_cjs.c(c,h.chatId,h.contextToken),await chunkJRI2CLB3_cjs.Oa({to:h.chatId,text:on(c),baseUrl:a,token:t.token,contextToken:h.contextToken||""});}catch(re){process.stderr.write(`[weixin] Failed to relay permission request ${c.request_id}: ${re}
7
+ `);}}),await r.connect(i);let a=t.baseUrl||chunkJRI2CLB3_cjs.Ea,o=new AbortController,f=false,l=async()=>{f||(f=true,o.signal.aborted||o.abort(),await Promise.all([n.shutdown1PEventLogging(),n.shutdownDatadog()]),process.exit(0));};process.stdin.on("end",()=>{l();}),process.stdin.on("error",()=>{l();}),process.on("SIGINT",()=>{l();}),process.on("SIGTERM",()=>{l();}),process.on("SIGHUP",()=>{l();});let w=process.ppid,m=setInterval(()=>{try{process.kill(w,0);}catch{process.stderr.write(`[weixin] Parent process exited, shutting down...
8
+ `),clearInterval(m),l();}},5e3);n.logForDebugging("[Weixin MCP] Starting poll loop"),await chunkJRI2CLB3_cjs.Ra({baseUrl:a,cdnBaseUrl:chunkJRI2CLB3_cjs.Fa,token:t.token,onMessage:async c=>{await r.notification({method:"notifications/claude/channel",params:{content:c.text,meta:{chat_id:c.fromUserId,sender_id:c.fromUserId,message_id:c.messageId,...c.attachmentPath&&{attachment_path:c.attachmentPath},...c.attachmentType&&{attachment_type:c.attachmentType}}}});},onPermissionResponse:async c=>{await r.notification({method:"notifications/claude/channel/permission",params:{request_id:c.requestId,behavior:c.behavior}});},abortSignal:o.signal}),clearInterval(m),await l();}var pe={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var ln=pe.languages,gn=ln.filter(e=>e.supported).map(e=>e.value),v={defaultLocale:"zh-CN",locales:gn},P={},N=(e,n)=>{let t=P[e]||{translation:{}};return P[e]={translation:{...t.translation,...n.translation}},P[e]},F=(e=v.defaultLocale)=>(P[e]||N(e,{translation:{}}),{locale:e,resources:P[e]||{translation:{}}});var dn={translation:{"weixin.sdk.cli.usage":["\u7528\u6CD5\uFF1A"," easbot weixin serve"," easbot weixin login"," easbot weixin login clear"," easbot weixin access pair <code>","","\u5F53\u524D\u7528\u6237\uFF08\u4ECE account.json \u8BFB\u53D6\uFF09\uFF1A"," easbot weixin user",' easbot weixin ensure-user [--display-name "<name>"]'," easbot weixin remove-user"].join(`
9
9
  `),"weixin.sdk.cli.serve.unavailable":"[weixin] \u5F53\u524D\u4E0A\u4E0B\u6587\u65E0\u6CD5\u542F\u52A8 serve handler\u3002","weixin.sdk.cli.login.cleared":"\u5DF2\u6E05\u9664\u5FAE\u4FE1\u8D26\u53F7\u7ED1\u5B9A\u3002","weixin.sdk.cli.login.already_connected":"\u5DF2\u8FDE\u63A5\uFF1A","weixin.sdk.cli.login.user_id":" \u7528\u6237 ID\uFF1A{{userId}}","weixin.sdk.cli.login.connected_since":" \u8FDE\u63A5\u65F6\u95F4\uFF1A{{since}}","weixin.sdk.cli.login.disconnect_hint":"\u8FD0\u884C `easbot weixin login clear` \u89E3\u9664\u7ED1\u5B9A\u3002","weixin.sdk.cli.login.starting":"\u6B63\u5728\u542F\u52A8\u5FAE\u4FE1\u626B\u7801\u767B\u5F55...","weixin.sdk.cli.login.scan_hint":"\u8BF7\u7528\u5FAE\u4FE1\u626B\u63CF\u4E0A\u65B9\u4E8C\u7EF4\u7801\uFF0C\u6216\u6253\u5F00\u6B64 URL\uFF1A","weixin.sdk.cli.login.failed":"\u767B\u5F55\u5931\u8D25\uFF1A{{message}}","weixin.sdk.cli.login.connected_success":"\u767B\u5F55\u6210\u529F\uFF01","weixin.sdk.cli.login.base_url":" Base URL\uFF1A{{baseUrl}}","weixin.sdk.cli.access.invalid_code":"\u914D\u5BF9\u7801\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\u3002","weixin.sdk.cli.access.paired":"\u914D\u5BF9\u6210\u529F\uFF1A{{userId}}","weixin.sdk.cli.user.not_logged_in":"\u672A\u767B\u5F55\u4EFB\u4F55\u5FAE\u4FE1\u8D26\u53F7\u3002","weixin.sdk.cli.user.login_hint":"\u8FD0\u884C `easbot weixin login` \u901A\u8FC7 iLink \u7ED1\u5B9A\u4E2A\u4EBA\u5FAE\u4FE1\u3002","weixin.sdk.cli.user.header":"\u5F53\u524D weixin \u7528\u6237\uFF1A","weixin.sdk.cli.user.contact.registered":"\u5DF2\u6CE8\u518C","weixin.sdk.cli.user.contact.not_registered":"\u672A\u6CE8\u518C","weixin.sdk.cli.user.contact.ensure_hint":"\u8FD0\u884C `{{cmd}}` \u5B8C\u6210\u6CE8\u518C","weixin.sdk.cli.user.failed":"\u67E5\u8BE2\u7528\u6237\u5931\u8D25\uFF1A{{error}}","weixin.sdk.cli.ensure_user.requires_display_name":"{{flag}} \u9700\u8981\u4E00\u4E2A\u503C","weixin.sdk.cli.ensure_user.tag.created":"\u5DF2\u521B\u5EFA","weixin.sdk.cli.ensure_user.tag.existed":"\u5DF2\u5B58\u5728\uFF08\u5DF2\u66F4\u65B0\uFF09","weixin.sdk.cli.ensure_user.banner":"[weixin routing] {{tag}} user: {{userId}}","weixin.sdk.cli.ensure_user.failed":"ensure-user \u6267\u884C\u5931\u8D25\uFF1A{{error}}","weixin.sdk.cli.remove_user.usage":"\u7528\u6CD5\uFF1Aeasbot weixin remove-user","weixin.sdk.cli.remove_user.banner":"[weixin routing] removed user: {{userId}} contact={{contact}} session={{session}}","weixin.sdk.cli.remove_user.failed":"remove-user \u6267\u884C\u5931\u8D25\uFF1A{{error}}","weixin.sdk.cli.require_login":"\u672A\u767B\u5F55\u5FAE\u4FE1\u8D26\u53F7\uFF0C\u8BF7\u5148\u8FD0\u884C `easbot weixin login`\u3002","weixin.sdk.cli.unknown_argument":"\u672A\u77E5\u53C2\u6570\uFF1A{{arg}}"}},fe=dn;var un={translation:{"weixin.sdk.cli.usage":["Usage:"," easbot weixin serve"," easbot weixin login"," easbot weixin login clear"," easbot weixin access pair <code>","","Current user (read from account.json):"," easbot weixin user",' easbot weixin ensure-user [--display-name "<name>"]'," easbot weixin remove-user"].join(`
10
10
  `),"weixin.sdk.cli.serve.unavailable":"[weixin] serve handler not available in this context.","weixin.sdk.cli.login.cleared":"WeChat account cleared.","weixin.sdk.cli.login.already_connected":"Already connected:","weixin.sdk.cli.login.user_id":" User ID: {{userId}}","weixin.sdk.cli.login.connected_since":" Connected since: {{since}}","weixin.sdk.cli.login.disconnect_hint":"Run `easbot weixin login clear` to disconnect.","weixin.sdk.cli.login.starting":"Starting WeChat QR login...","weixin.sdk.cli.login.scan_hint":"Scan the QR code above with WeChat, or open this URL:","weixin.sdk.cli.login.failed":"Login failed: {{message}}","weixin.sdk.cli.login.connected_success":"Connected successfully!","weixin.sdk.cli.login.base_url":" Base URL: {{baseUrl}}","weixin.sdk.cli.access.invalid_code":"Invalid or expired pairing code.","weixin.sdk.cli.access.paired":"Paired successfully: {{userId}}","weixin.sdk.cli.user.not_logged_in":"No weixin account logged in.","weixin.sdk.cli.user.login_hint":"Run `easbot weixin login` to bind your WeChat via iLink.","weixin.sdk.cli.user.header":"weixin current user:","weixin.sdk.cli.user.contact.registered":"registered","weixin.sdk.cli.user.contact.not_registered":"not registered","weixin.sdk.cli.user.contact.ensure_hint":"run `{{cmd}}` to register","weixin.sdk.cli.user.failed":"user failed: {{error}}","weixin.sdk.cli.ensure_user.requires_display_name":"{{flag}} requires a value","weixin.sdk.cli.ensure_user.tag.created":"created","weixin.sdk.cli.ensure_user.tag.existed":"exists (updated)","weixin.sdk.cli.ensure_user.banner":"[weixin routing] {{tag}} user: {{userId}}","weixin.sdk.cli.ensure_user.failed":"ensure-user failed: {{error}}","weixin.sdk.cli.remove_user.usage":"Usage: easbot weixin remove-user","weixin.sdk.cli.remove_user.banner":"[weixin routing] removed user: {{userId}} contact={{contact}} session={{session}}","weixin.sdk.cli.remove_user.failed":"remove-user failed: {{error}}","weixin.sdk.cli.require_login":"No weixin account logged in. Run `easbot weixin login` first.","weixin.sdk.cli.unknown_argument":"Unknown argument: {{arg}}"}},me=un;var fn=()=>{F("zh-CN"),F("en-US"),N("zh-CN",fe),N("en-US",me);};fn();var ee=new Map;var te=new Map;var mn=e=>{if(te.has(e))return te.get(e);let n=/{{\s*(\w+)\s*}}/g,t=[],r;for(;(r=n.exec(e))!==null;){let o=r[1];o&&!t.includes(o)&&t.push(o);}let i=new RegExp("{{\\s*("+t.join("|")+")\\s*}}","g"),a={keys:t,regex:i};return te.set(e,a),a},we=(e,n)=>{if(!e||typeof e!="string")return "";if(!n||Object.keys(n).length===0)return e;let{regex:t,keys:r}=mn(e);return r.length===0||!r.some(a=>a in n)?e:e.replace(t,(a,o)=>{let f=n[o];return f==null?"":String(f)})},wn=e=>{let n=utils.resolveLocaleLang(e);return v.locales.includes(n)?n:v.defaultLocale},xe=e=>{if(!ee.has(e)){let{resources:n}=F(e);ee.set(e,n);}return ee.get(e)},xn=(e,n={})=>{let t=wn(n.locale),i=xe(t)?.translation[e];if(i&&typeof i=="string"){let a=we(i,n.vars);return a!=null?String(a):String(e)}if(t!==v.defaultLocale){let o=xe(v.defaultLocale)?.translation[e];if(o&&typeof o=="string"){let f=we(o,n.vars);return f!=null?String(f):String(e)}}return String(n.fallback??e)},s=xn;function he(){process.stdout.write(s("weixin.sdk.cli.usage")+`
11
- `);}async function hn(e=false){if(e){chunkCPQSQ7FU_cjs.Ja(),process.stdout.write(s("weixin.sdk.cli.login.cleared")+`
12
- `);return}let n=chunkCPQSQ7FU_cjs.Ha();if(n){process.stdout.write([s("weixin.sdk.cli.login.already_connected"),s("weixin.sdk.cli.login.user_id",{vars:{userId:n.userId||"unknown"}}),s("weixin.sdk.cli.login.connected_since",{vars:{since:utils.formatLocalISO(new Date(n.savedAt))}}),"",s("weixin.sdk.cli.login.disconnect_hint")].join(`
11
+ `);}async function hn(e=false){if(e){chunkJRI2CLB3_cjs.Ja(),process.stdout.write(s("weixin.sdk.cli.login.cleared")+`
12
+ `);return}let n=chunkJRI2CLB3_cjs.Ha();if(n){process.stdout.write([s("weixin.sdk.cli.login.already_connected"),s("weixin.sdk.cli.login.user_id",{vars:{userId:n.userId||"unknown"}}),s("weixin.sdk.cli.login.connected_since",{vars:{since:utils.formatLocalISO(new Date(n.savedAt))}}),"",s("weixin.sdk.cli.login.disconnect_hint")].join(`
13
13
  `)+`
14
14
  `);return}process.stdout.write(s("weixin.sdk.cli.login.starting")+`
15
15
 
16
- `);let t=await D(chunkCPQSQ7FU_cjs.Ea);process.stdout.write(`
16
+ `);let t=await D(chunkJRI2CLB3_cjs.Ea);process.stdout.write(`
17
17
  ${s("weixin.sdk.cli.login.scan_hint")}
18
18
  ${t.qrcodeUrl||""}
19
19
 
20
- `);let r=await Z({qrcodeId:t.qrcodeId,apiBaseUrl:chunkCPQSQ7FU_cjs.Ea});(!r.connected||!r.token)&&(process.stderr.write(s("weixin.sdk.cli.login.failed",{vars:{message:r.message}})+`
21
- `),process.exit(1)),chunkCPQSQ7FU_cjs.Ia({token:r.token,baseUrl:r.baseUrl||chunkCPQSQ7FU_cjs.Ea,userId:r.userId,savedAt:new Date().toISOString()}),process.stdout.write([s("weixin.sdk.cli.login.connected_success")," "+s("weixin.sdk.cli.login.user_id",{vars:{userId:r.userId||"unknown"}})," "+s("weixin.sdk.cli.login.base_url",{vars:{baseUrl:r.baseUrl||chunkCPQSQ7FU_cjs.Ea}})].join(`
20
+ `);let r=await Z({qrcodeId:t.qrcodeId,apiBaseUrl:chunkJRI2CLB3_cjs.Ea});(!r.connected||!r.token)&&(process.stderr.write(s("weixin.sdk.cli.login.failed",{vars:{message:r.message}})+`
21
+ `),process.exit(1)),chunkJRI2CLB3_cjs.Ia({token:r.token,baseUrl:r.baseUrl||chunkJRI2CLB3_cjs.Ea,userId:r.userId,savedAt:new Date().toISOString()}),process.stdout.write([s("weixin.sdk.cli.login.connected_success")," "+s("weixin.sdk.cli.login.user_id",{vars:{userId:r.userId||"unknown"}})," "+s("weixin.sdk.cli.login.base_url",{vars:{baseUrl:r.baseUrl||chunkJRI2CLB3_cjs.Ea}})].join(`
22
22
  `)+`
23
- `);}function yn(e){(e[0]!=="pair"||!e[1])&&(he(),process.exit(1));let n=chunkCPQSQ7FU_cjs.Na(e[1]);n||(process.stderr.write(s("weixin.sdk.cli.access.invalid_code")+`
23
+ `);}function yn(e){(e[0]!=="pair"||!e[1])&&(he(),process.exit(1));let n=chunkJRI2CLB3_cjs.Na(e[1]);n||(process.stderr.write(s("weixin.sdk.cli.access.invalid_code")+`
24
24
  `),process.exit(1)),process.stdout.write(s("weixin.sdk.cli.access.paired",{vars:{userId:n}})+`
25
- `);}function Cn(e,n){let t={userId:n,channelId:"weixin-main"};for(let r=0;r<e.length;r++){let i=e[r];if(i==="--display-name"||i==="-d"){let a=e[++r];if(!a)return s("weixin.sdk.cli.ensure_user.requires_display_name",{vars:{flag:"--display-name"}});t.displayName=a;}else return s("weixin.sdk.cli.unknown_argument",{vars:{arg:i??""}})}return t}function ye(){let e=chunkCPQSQ7FU_cjs.Ha();return e?.userId||(process.stderr.write(s("weixin.sdk.cli.require_login")+`
26
- `),process.exit(1)),e.userId}async function Sn(){try{let e=chunkCPQSQ7FU_cjs.Ha();if(!e){process.stdout.write(s("weixin.sdk.cli.user.not_logged_in")+`
25
+ `);}function Cn(e,n){let t={userId:n,channelId:"weixin-main"};for(let r=0;r<e.length;r++){let i=e[r];if(i==="--display-name"||i==="-d"){let a=e[++r];if(!a)return s("weixin.sdk.cli.ensure_user.requires_display_name",{vars:{flag:"--display-name"}});t.displayName=a;}else return s("weixin.sdk.cli.unknown_argument",{vars:{arg:i??""}})}return t}function ye(){let e=chunkJRI2CLB3_cjs.Ha();return e?.userId||(process.stderr.write(s("weixin.sdk.cli.require_login")+`
26
+ `),process.exit(1)),e.userId}async function Sn(){try{let e=chunkJRI2CLB3_cjs.Ha();if(!e){process.stdout.write(s("weixin.sdk.cli.user.not_logged_in")+`
27
27
  `),process.stdout.write(s("weixin.sdk.cli.user.login_hint")+`
28
28
  `);return}process.stdout.write(s("weixin.sdk.cli.user.header")+`
29
29
  `),process.stdout.write(` userId: ${e.userId??"(unknown)"}
30
30
  `),process.stdout.write(` baseUrl: ${e.baseUrl}
31
31
  `),process.stdout.write(` savedAt: ${utils.formatLocalISO(new Date(e.savedAt))}
32
- `);let t=(await chunkCPQSQ7FU_cjs.Da()).find(r=>r.stableId===e.userId);t?(process.stdout.write(` contact: ${s("weixin.sdk.cli.user.contact.registered")}
32
+ `);let t=(await chunkJRI2CLB3_cjs.Da()).find(r=>r.stableId===e.userId);t?(process.stdout.write(` contact: ${s("weixin.sdk.cli.user.contact.registered")}
33
33
  `),process.stdout.write(` uid: ${t.uid}
34
34
  `),t.profile.displayName&&process.stdout.write(` display: ${t.profile.displayName}
35
35
  `),t.profile.username&&process.stdout.write(` username: ${t.profile.username}
@@ -38,12 +38,12 @@ ${t.qrcodeUrl||""}
38
38
  `),process.stdout.write(` hint: ${s("weixin.sdk.cli.user.contact.ensure_hint",{vars:{cmd:"easbot weixin ensure-user"}})}
39
39
  `));}catch(e){process.stderr.write(s("weixin.sdk.cli.user.failed",{vars:{error:String(e)}})+`
40
40
  `),process.exit(1);}}async function vn(e){let n=ye(),t=Cn(e,n);typeof t=="string"&&(process.stderr.write(`${t}
41
- `),process.exit(1));try{let r=await chunkCPQSQ7FU_cjs.Ba(t),{contact:i,session:a,created:o}=r,f=o.contact&&o.session?s("weixin.sdk.cli.ensure_user.tag.created"):s("weixin.sdk.cli.ensure_user.tag.existed");process.stdout.write([s("weixin.sdk.cli.ensure_user.banner",{vars:{tag:f,userId:n}}),` contact.uid: ${i.uid}`,` contact.path: ${chunkCPQSQ7FU_cjs.xa()}/contacts/${i.platform}/${i.stableId}.json`,` session.id: ${a.id}`,` session.path: ${chunkCPQSQ7FU_cjs.ya()}/sessions.json`,` profile: ${JSON.stringify(i.profile)}`].join(`
41
+ `),process.exit(1));try{let r=await chunkJRI2CLB3_cjs.Ba(t),{contact:i,session:a,created:o}=r,f=o.contact&&o.session?s("weixin.sdk.cli.ensure_user.tag.created"):s("weixin.sdk.cli.ensure_user.tag.existed");process.stdout.write([s("weixin.sdk.cli.ensure_user.banner",{vars:{tag:f,userId:n}}),` contact.uid: ${i.uid}`,` contact.path: ${chunkJRI2CLB3_cjs.xa()}/contacts/${i.platform}/${i.stableId}.json`,` session.id: ${a.id}`,` session.path: ${chunkJRI2CLB3_cjs.ya()}/sessions.json`,` profile: ${JSON.stringify(i.profile)}`].join(`
42
42
  `)+`
43
43
  `);}catch(r){process.stderr.write(s("weixin.sdk.cli.ensure_user.failed",{vars:{error:String(r)}})+`
44
44
  `),process.exit(1);}}async function kn(e){let n=ye();if(e.length>0){let t=e[0]??"";process.stderr.write(s("weixin.sdk.cli.unknown_argument",{vars:{arg:t}})+`
45
45
  `),process.stderr.write(s("weixin.sdk.cli.remove_user.usage")+`
46
- `),process.exit(1);}try{let t=await chunkCPQSQ7FU_cjs.Ca(n,"weixin-main");process.stdout.write(s("weixin.sdk.cli.remove_user.banner",{vars:{userId:n,contact:String(t.removed.contact),session:String(t.removed.session)}})+`
46
+ `),process.exit(1);}try{let t=await chunkJRI2CLB3_cjs.Ca(n,"weixin-main");process.stdout.write(s("weixin.sdk.cli.remove_user.banner",{vars:{userId:n,contact:String(t.removed.contact),session:String(t.removed.session)}})+`
47
47
  `);}catch(t){process.stderr.write(s("weixin.sdk.cli.remove_user.failed",{vars:{error:String(t)}})+`
48
48
  `),process.exit(1);}}async function bn(e,n,t){let[r,...i]=e;switch(r){case "serve":n||(process.stderr.write(s("weixin.sdk.cli.serve.unavailable")+`
49
- `),process.exit(1)),await ue(t??"0.0.0",n);return;case "login":await hn(i[0]==="clear");return;case "access":yn(i);return;case "user":await Sn();return;case "ensure-user":await vn(i);return;case "remove-user":await kn(i);return;default:he();}}Object.defineProperty(exports,"AgentRegistry",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Za}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.p}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.k}});Object.defineProperty(exports,"AgentSyncManager",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs._a}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.j}});Object.defineProperty(exports,"BaseChannelPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.qa}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.h}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.oa}});Object.defineProperty(exports,"ChannelPluginRegistry",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Xa}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.o}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.m}});Object.defineProperty(exports,"DEBUG_AGENT_FILTER",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.T}});Object.defineProperty(exports,"DEFAULT_AGENT_FILTER",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.S}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ha}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ja}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ia}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ga}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.fa}});Object.defineProperty(exports,"DiscordPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.sa}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.c}});Object.defineProperty(exports,"FeishuPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ua}});Object.defineProperty(exports,"GatewayClientConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.s}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.l}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.t}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.$a}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.r}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.na}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.i}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.n}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ka}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.la}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.g}});Object.defineProperty(exports,"NostrPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Va}});Object.defineProperty(exports,"SdkEventBridge",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.R}});Object.defineProperty(exports,"SdkEventBus",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Q}});Object.defineProperty(exports,"SdkEventType",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.P}});Object.defineProperty(exports,"SdkMessageCollector",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.U}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.q}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ma}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.f}});Object.defineProperty(exports,"SignalPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ua}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.b}});Object.defineProperty(exports,"SlackPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ta}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.a}});Object.defineProperty(exports,"TelegramPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ra}});Object.defineProperty(exports,"WEIXIN_PLATFORM",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.wa}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.d}});Object.defineProperty(exports,"WeChatPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.va}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.e}});Object.defineProperty(exports,"WebChatPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ta}});Object.defineProperty(exports,"WeixinPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Sa}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.z}});Object.defineProperty(exports,"convertToGatewayMessage",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ba}});Object.defineProperty(exports,"createChannelPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Wa}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.da}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.$}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.aa}});Object.defineProperty(exports,"ensureContact",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.za}});Object.defineProperty(exports,"ensureSession",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Aa}});Object.defineProperty(exports,"ensureUser",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ba}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ca}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ea}});Object.defineProperty(exports,"getAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.W}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.G}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.L}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.C}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.F}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.M}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.x}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.A}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.D}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.N}});Object.defineProperty(exports,"getGatewayClientConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.I}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.J}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.K}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.O}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.E}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.B}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.H}});Object.defineProperty(exports,"getSupportedPlatforms",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ya}});Object.defineProperty(exports,"hasAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.X}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.y}});Object.defineProperty(exports,"listWeixinContacts",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Da}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.w}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.v}});Object.defineProperty(exports,"removeUser",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ca}});Object.defineProperty(exports,"requireAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Y}});Object.defineProperty(exports,"setAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.V}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.u}});Object.defineProperty(exports,"weixinSetStateDir",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ga}});exports.handleWeixinCli=bn;
49
+ `),process.exit(1)),await ue(t??"0.0.0",n);return;case "login":await hn(i[0]==="clear");return;case "access":yn(i);return;case "user":await Sn();return;case "ensure-user":await vn(i);return;case "remove-user":await kn(i);return;default:he();}}Object.defineProperty(exports,"AgentRegistry",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Za}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.p}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.k}});Object.defineProperty(exports,"AgentSyncManager",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs._a}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.j}});Object.defineProperty(exports,"BaseChannelPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.qa}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.h}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.oa}});Object.defineProperty(exports,"ChannelPluginRegistry",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Xa}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.o}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.m}});Object.defineProperty(exports,"DEBUG_AGENT_FILTER",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.T}});Object.defineProperty(exports,"DEFAULT_AGENT_FILTER",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.S}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ha}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ja}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ia}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ga}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.fa}});Object.defineProperty(exports,"DiscordPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.sa}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.c}});Object.defineProperty(exports,"FeishuPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ua}});Object.defineProperty(exports,"GatewayClientConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.s}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.l}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.t}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.$a}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.r}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.na}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.i}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.n}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ka}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.la}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.g}});Object.defineProperty(exports,"NostrPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Va}});Object.defineProperty(exports,"SdkEventBridge",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.R}});Object.defineProperty(exports,"SdkEventBus",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Q}});Object.defineProperty(exports,"SdkEventType",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.P}});Object.defineProperty(exports,"SdkMessageCollector",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.U}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.q}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ma}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.f}});Object.defineProperty(exports,"SignalPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ua}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.b}});Object.defineProperty(exports,"SlackPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ta}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.a}});Object.defineProperty(exports,"TelegramPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ra}});Object.defineProperty(exports,"WEIXIN_PLATFORM",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.wa}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.d}});Object.defineProperty(exports,"WeChatPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.va}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.e}});Object.defineProperty(exports,"WebChatPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ta}});Object.defineProperty(exports,"WeixinPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Sa}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.z}});Object.defineProperty(exports,"convertToGatewayMessage",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ba}});Object.defineProperty(exports,"createChannelPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Wa}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.da}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.$}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.aa}});Object.defineProperty(exports,"ensureContact",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.za}});Object.defineProperty(exports,"ensureSession",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Aa}});Object.defineProperty(exports,"ensureUser",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ba}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ca}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ea}});Object.defineProperty(exports,"getAgentAdapter",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.W}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.G}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.L}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.C}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.F}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.M}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.x}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.A}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.D}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.N}});Object.defineProperty(exports,"getGatewayClientConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.I}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.J}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.K}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.O}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.E}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.B}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.H}});Object.defineProperty(exports,"getSupportedPlatforms",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ya}});Object.defineProperty(exports,"hasAgentAdapter",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.X}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.y}});Object.defineProperty(exports,"listWeixinContacts",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Da}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.w}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.v}});Object.defineProperty(exports,"removeUser",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ca}});Object.defineProperty(exports,"requireAgentAdapter",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Y}});Object.defineProperty(exports,"setAgentAdapter",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.V}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.u}});Object.defineProperty(exports,"weixinSetStateDir",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ga}});exports.handleWeixinCli=bn;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import {b,c}from'./chunks/chunk-NXFFFRVB.mjs';import {Z as Z$1,w,_,Ca,Ba,xa,ya,Ha,Da,Na,Ja,Ia,Ea,Qa,Oa,Ra,Fa,Ka,La,Ma,Pa}from'./chunks/chunk-3EE2AOK7.mjs';export{Za as AgentRegistry,p as AgentRegistryConfigSchema,k as AgentSyncConfigSchema,_a as AgentSyncManager,j as AuthConfigSchema,qa as BaseChannelPlugin,h as ChannelConfigSchema,oa as ChannelPluginLoader,Xa as ChannelPluginRegistry,o as CircuitBreakerConfigSchema,m as ConnectionPoolConfigSchema,T as DEBUG_AGENT_FILTER,S as DEFAULT_AGENT_FILTER,ha as DEFAULT_AGENT_REGISTRY_CONFIG,ja as DEFAULT_CONNECTION_POOL_CONFIG,ia as DEFAULT_SYNC_CONFIG,ga as DEFAULT_TOKEN_AUTH_CONFIG,fa as DEFAULT_WEBSOCKET_SERVER_CONFIG,sa as DiscordPlugin,c as FeishuChannelConfigSchema,ua as FeishuPlugin,s as GatewayClientConfigSchema,l as GatewayClusterConfigSchema,t as GatewayConfigSchema,$a as GatewayServer,r as GatewayServerConfigSchema,na as GatewaySessionManager,i as HTTPSConfigSchema,n as MessageQueueConfigSchema,ka as MessageRouter,la as MessageStore,g as NostrChannelConfigSchema,Va as NostrPlugin,R as SdkEventBridge,Q as SdkEventBus,P as SdkEventType,U as SdkMessageCollector,q as SessionConfigSchema,ma as SessionStore,f as SignalChannelConfigSchema,Ua as SignalPlugin,b as SlackChannelConfigSchema,ta as SlackPlugin,a as TelegramChannelConfigSchema,ra as TelegramPlugin,wa as WEIXIN_PLATFORM,d as WeChatChannelConfigSchema,va as WeChatPlugin,e as WebChatChannelConfigSchema,Ta as WebChatPlugin,Sa as WeixinPlugin,z as clearConfigCache,ba as convertToGatewayMessage,Wa as createChannelPlugin,da as createDefaultSessionState,$ as createGatewayMessage,aa as createTextMessage,za as ensureContact,Aa as ensureSession,Ba as ensureUser,ca as generateSessionId,ea as generateSubscriptionId,W as getAgentAdapter,G as getAgentRegistryConfig,L as getAuthConfig,C as getChannelConfig,F as getCircuitBreakerConfig,M as getClusterConfig,x as getConfig,A as getConfigDirectory,D as getConnectionPoolConfig,N as getDefaultAgent,I as getGatewayClientConfig,J as getGatewayClientUrl,K as getHTTPSConfig,O as getLogLevel,E as getMessageQueueConfig,B as getServerConfig,H as getSessionConfig,Ya as getSupportedPlatforms,X as hasAgentAdapter,y as isConfigLoaded,Da as listWeixinContacts,w as loadConfig,v as parsePartialConfig,Ca as removeUser,Y as requireAgentAdapter,V as setAgentAdapter,u as validateConfig,Ga as weixinSetStateDir}from'./chunks/chunk-3EE2AOK7.mjs';import {a}from'./chunks/chunk-HQBRVVXS.mjs';import {Log,Fetch,formatLocalISO,resolveLocaleLang}from'@easbot/utils';import {toString}from'qrcode';import {existsSync}from'fs';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';var u=Log.create({service:"gateway"}),P=class e extends Error{constructor(t,r,i){super(t);a(this,"type");a(this,"stage");a(this,"cause");this.type="GatewayInitializationError",this.stage=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function ue(e){let n=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return n.includes(t??"")}function Xt(){process.on("unhandledRejection",e=>{let n=e instanceof Error?e:new Error(String(e));ue(n)||u.error("unhandled promise rejection",{error:n.message,stack:n.stack});}),process.on("uncaughtException",e=>{ue(e)||(u.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}var Z;(Rn=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},n,t={server:null,config:null,initialized:false,status:"stopped"};async function r(g={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let p={directory:g.directory??".easbot",printLogs:g.printLogs??false,logLevel:g.logLevel??"INFO"};return e.directory=p.directory,e.initPromise=(async()=>{Z$1();try{Xt();}catch(d){throw new P("Failed to install unhandled exception handlers","server",d instanceof Error?d:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),u.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{e.config=await w(p.directory);}catch(d){throw new P("Failed to load gateway configuration","config",d instanceof Error?d:void 0)}e.initialized=true,u.info("gateway runtime initialized",{directory:p.directory,logLevel:p.logLevel});})(),e.initPromise}Rn.init=r;function i(){return e.initialized}Rn.isInitialized=i;function a(){return n||(n=async()=>{if(!e.initialized)throw new P("Gateway not initialized. Call init() first.","server");let g=_(),p=await w(g.directory);return p.server?.enabled?(t={server:null,config:p,initialized:true,status:"stopped"},u.info("gateway initialized",{port:p.server?.port,hostname:p.server?.hostname}),t):(u.debug("gateway server disabled or not configured"),{server:null,config:p,initialized:true,status:"stopped"})}),n}function o(){return a()()}Rn.state=o;async function f(){return (await o()).server}Rn.get=f;async function l(){return (await o()).config?.server?.enabled??false}Rn.isEnabled=l;async function w$1(){return (await o()).config}Rn.config=w$1;function m(){return t.status}Rn.getStatus=m;async function c(g){u.debug("Gateway.start: called"),e.initialized||await r();let p=await o();if(!(p.config?.server?.enabled??true))throw u.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){u.info("gateway server is already running");return}if(t.status==="starting"){u.info("gateway server is starting");return}t.status="starting";try{let d={...p.config?.server,...g};u.debug("gateway start: creating server with config",{port:d.port,hostname:d.hostname,path:d.path,https:d.https?.enabled});let I=await Se(d);t.server=I,t.status="running",t.error=void 0,u.info("gateway server started",{port:d.port,hostname:d.hostname});}catch(d){throw t.status="error",t.error=d instanceof Error?d.message:String(d),u.error("failed to start gateway server",{error:t.error}),d}}Rn.start=c;async function x(){if(t.status==="stopped"){u.info("gateway server is already stopped");return}if(t.status==="stopping"){u.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,u.info("gateway server stopped");}catch(g){throw t.status="error",t.error=g instanceof Error?g.message:String(g),u.error("failed to stop gateway server",{error:t.error}),g}}Rn.stop=x;async function h(g){u.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await x(),await c(g);}Rn.restart=h;async function ie(){let g=_(),p=await w(g.directory);return t.config=p,e.config=p,u.info("gateway config reloaded"),p}Rn.reloadConfig=ie;async function Se(g,p){u.debug("createGatewayServer: starting");let{GatewayServer:W}=await import('./chunks/server-XGZGHXC5.mjs'),d=new W(g),I=p?.startupTimeout??3e4;if(await(async()=>{let b=new Promise((_,ve)=>{setTimeout(()=>{ve(new Error(`Gateway server startup timeout after ${I}ms`));},I);});try{await Promise.race([d.start(),b]);}catch(_){u.error("gateway server start failed, attempting cleanup",{error:_ instanceof Error?_.message:String(_)});try{await d.stop();}catch{}throw _}})(),p?.onStarted)try{await p.onStarted(d);}catch(b){u.warn("server started but onStarted callback failed",{error:b instanceof Error?b.message:String(b)});}return u.info("gateway server created and started",{port:g.port,hostname:g.hostname}),d}Rn.createGatewayServer=Se;})(Z||(Z={}));async function en(e){let n=await toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${n}
1
+ import {b,c}from'./chunks/chunk-NXFFFRVB.mjs';import {Z as Z$1,w,_,Ca,Ba,xa,ya,Ha,Da,Na,Ja,Ia,Ea,Qa,Oa,Ra,Fa,Ka,La,Ma,Pa}from'./chunks/chunk-VVKUBVKT.mjs';export{Za as AgentRegistry,p as AgentRegistryConfigSchema,k as AgentSyncConfigSchema,_a as AgentSyncManager,j as AuthConfigSchema,qa as BaseChannelPlugin,h as ChannelConfigSchema,oa as ChannelPluginLoader,Xa as ChannelPluginRegistry,o as CircuitBreakerConfigSchema,m as ConnectionPoolConfigSchema,T as DEBUG_AGENT_FILTER,S as DEFAULT_AGENT_FILTER,ha as DEFAULT_AGENT_REGISTRY_CONFIG,ja as DEFAULT_CONNECTION_POOL_CONFIG,ia as DEFAULT_SYNC_CONFIG,ga as DEFAULT_TOKEN_AUTH_CONFIG,fa as DEFAULT_WEBSOCKET_SERVER_CONFIG,sa as DiscordPlugin,c as FeishuChannelConfigSchema,ua as FeishuPlugin,s as GatewayClientConfigSchema,l as GatewayClusterConfigSchema,t as GatewayConfigSchema,$a as GatewayServer,r as GatewayServerConfigSchema,na as GatewaySessionManager,i as HTTPSConfigSchema,n as MessageQueueConfigSchema,ka as MessageRouter,la as MessageStore,g as NostrChannelConfigSchema,Va as NostrPlugin,R as SdkEventBridge,Q as SdkEventBus,P as SdkEventType,U as SdkMessageCollector,q as SessionConfigSchema,ma as SessionStore,f as SignalChannelConfigSchema,Ua as SignalPlugin,b as SlackChannelConfigSchema,ta as SlackPlugin,a as TelegramChannelConfigSchema,ra as TelegramPlugin,wa as WEIXIN_PLATFORM,d as WeChatChannelConfigSchema,va as WeChatPlugin,e as WebChatChannelConfigSchema,Ta as WebChatPlugin,Sa as WeixinPlugin,z as clearConfigCache,ba as convertToGatewayMessage,Wa as createChannelPlugin,da as createDefaultSessionState,$ as createGatewayMessage,aa as createTextMessage,za as ensureContact,Aa as ensureSession,Ba as ensureUser,ca as generateSessionId,ea as generateSubscriptionId,W as getAgentAdapter,G as getAgentRegistryConfig,L as getAuthConfig,C as getChannelConfig,F as getCircuitBreakerConfig,M as getClusterConfig,x as getConfig,A as getConfigDirectory,D as getConnectionPoolConfig,N as getDefaultAgent,I as getGatewayClientConfig,J as getGatewayClientUrl,K as getHTTPSConfig,O as getLogLevel,E as getMessageQueueConfig,B as getServerConfig,H as getSessionConfig,Ya as getSupportedPlatforms,X as hasAgentAdapter,y as isConfigLoaded,Da as listWeixinContacts,w as loadConfig,v as parsePartialConfig,Ca as removeUser,Y as requireAgentAdapter,V as setAgentAdapter,u as validateConfig,Ga as weixinSetStateDir}from'./chunks/chunk-VVKUBVKT.mjs';import {a}from'./chunks/chunk-HQBRVVXS.mjs';import {Log,Fetch,formatLocalISO,resolveLocaleLang}from'@easbot/utils';import {toString}from'qrcode';import {existsSync}from'fs';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';var u=Log.create({service:"gateway"}),P=class e extends Error{constructor(t,r,i){super(t);a(this,"type");a(this,"stage");a(this,"cause");this.type="GatewayInitializationError",this.stage=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function ue(e){let n=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return n.includes(t??"")}function Xt(){process.on("unhandledRejection",e=>{let n=e instanceof Error?e:new Error(String(e));ue(n)||u.error("unhandled promise rejection",{error:n.message,stack:n.stack});}),process.on("uncaughtException",e=>{ue(e)||(u.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}var Z;(Rn=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},n,t={server:null,config:null,initialized:false,status:"stopped"};async function r(g={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let p={directory:g.directory??".easbot",printLogs:g.printLogs??false,logLevel:g.logLevel??"INFO"};return e.directory=p.directory,e.initPromise=(async()=>{Z$1();try{Xt();}catch(d){throw new P("Failed to install unhandled exception handlers","server",d instanceof Error?d:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),u.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{e.config=await w(p.directory);}catch(d){throw new P("Failed to load gateway configuration","config",d instanceof Error?d:void 0)}e.initialized=true,u.info("gateway runtime initialized",{directory:p.directory,logLevel:p.logLevel});})(),e.initPromise}Rn.init=r;function i(){return e.initialized}Rn.isInitialized=i;function a(){return n||(n=async()=>{if(!e.initialized)throw new P("Gateway not initialized. Call init() first.","server");let g=_(),p=await w(g.directory);return p.server?.enabled?(t={server:null,config:p,initialized:true,status:"stopped"},u.info("gateway initialized",{port:p.server?.port,hostname:p.server?.hostname}),t):(u.debug("gateway server disabled or not configured"),{server:null,config:p,initialized:true,status:"stopped"})}),n}function o(){return a()()}Rn.state=o;async function f(){return (await o()).server}Rn.get=f;async function l(){return (await o()).config?.server?.enabled??false}Rn.isEnabled=l;async function w$1(){return (await o()).config}Rn.config=w$1;function m(){return t.status}Rn.getStatus=m;async function c(g){u.debug("Gateway.start: called"),e.initialized||await r();let p=await o();if(!(p.config?.server?.enabled??true))throw u.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){u.info("gateway server is already running");return}if(t.status==="starting"){u.info("gateway server is starting");return}t.status="starting";try{let d={...p.config?.server,...g};u.debug("gateway start: creating server with config",{port:d.port,hostname:d.hostname,path:d.path,https:d.https?.enabled});let I=await Se(d);t.server=I,t.status="running",t.error=void 0,u.info("gateway server started",{port:d.port,hostname:d.hostname});}catch(d){throw t.status="error",t.error=d instanceof Error?d.message:String(d),u.error("failed to start gateway server",{error:t.error}),d}}Rn.start=c;async function x(){if(t.status==="stopped"){u.info("gateway server is already stopped");return}if(t.status==="stopping"){u.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,u.info("gateway server stopped");}catch(g){throw t.status="error",t.error=g instanceof Error?g.message:String(g),u.error("failed to stop gateway server",{error:t.error}),g}}Rn.stop=x;async function h(g){u.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await x(),await c(g);}Rn.restart=h;async function ie(){let g=_(),p=await w(g.directory);return t.config=p,e.config=p,u.info("gateway config reloaded"),p}Rn.reloadConfig=ie;async function Se(g,p){u.debug("createGatewayServer: starting");let{GatewayServer:W}=await import('./chunks/server-QO3EP45A.mjs'),d=new W(g),I=p?.startupTimeout??3e4;if(await(async()=>{let b=new Promise((_,ve)=>{setTimeout(()=>{ve(new Error(`Gateway server startup timeout after ${I}ms`));},I);});try{await Promise.race([d.start(),b]);}catch(_){u.error("gateway server start failed, attempting cleanup",{error:_ instanceof Error?_.message:String(_)});try{await d.stop();}catch{}throw _}})(),p?.onStarted)try{await p.onStarted(d);}catch(b){u.warn("server started but onStarted callback failed",{error:b instanceof Error?b.message:String(b)});}return u.info("gateway server created and started",{port:g.port,hostname:g.hostname}),d}Rn.createGatewayServer=Se;})(Z||(Z={}));async function en(e){let n=await toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${n}
2
2
  `);}async function N(e){let n=await fetch(`${e}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!n.ok)throw new Error(`Failed to get QR code: HTTP ${n.status}`);let t=await n.json();if(!t.qrcode)throw new Error("No qrcode in response");let r=t.qrcode_img_content||"";return r&&await en(r),{qrcodeUrl:r,qrcodeId:t.qrcode,message:"Scan the QR code with WeChat to connect."}}async function ee(e){let{qrcodeId:n,apiBaseUrl:t,timeoutMs:r=48e4,maxRetries:i=3}=e,a=Date.now()+r,o=n,f=0;for(;Date.now()<a;){try{let l=new AbortController,w=setTimeout(()=>l.abort(),6e4),m=await fetch(`${t}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(o)}`,{headers:{"iLink-App-ClientVersion":"1"},signal:l.signal});if(clearTimeout(w),!m.ok)throw new Error(`HTTP ${m.status}`);let c=await m.json();switch(c.status){case "confirmed":return {connected:!0,token:c.bot_token,accountId:c.ilink_bot_id,baseUrl:c.baseurl,userId:c.ilink_user_id,message:"Connected to WeChat successfully!"};case "scaned":process.stderr.write(`QR code scanned, waiting for confirmation...
3
3
  `);break;case "expired":{if(f+=1,f>=i)return {connected:!1,message:"QR code expired after maximum retries."};process.stderr.write(`QR code expired, refreshing...
4
4
  `),o=(await N(t)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/gateway",
3
- "version": "0.3.10",
3
+ "version": "0.3.11",
4
4
  "description": "EASBot Gateway - AI Agent Server and Multi-channel Integration Platform - 支持 WebSocket、HTTP、Discord、Telegram、Slack 等多渠道集成",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -58,7 +58,7 @@
58
58
  "@hono/standard-validator": "^0.2.2",
59
59
  "@hono/zod-validator": "^0.7.6",
60
60
  "ai": "^6.0.176",
61
- "better-sqlite3": "^12.9.0",
61
+ "better-sqlite3": "^13.0.1",
62
62
  "commander": "^14.0.3",
63
63
  "qrcode": "^1.5.4",
64
64
  "hono": "^4.12.18",
@@ -68,14 +68,13 @@
68
68
  "ws": "^8.20.0",
69
69
  "xdg-basedir": "^5.1.0",
70
70
  "zod": "^4.4.3",
71
- "@easbot/plugin": "0.3.10",
72
- "@easbot/sdk": "0.3.10",
73
- "@easbot/utils": "0.3.10",
74
- "@easbot/types": "0.3.10"
71
+ "@easbot/plugin": "0.3.11",
72
+ "@easbot/sdk": "0.3.11",
73
+ "@easbot/utils": "0.3.11",
74
+ "@easbot/types": "0.3.11"
75
75
  },
76
76
  "devDependencies": {
77
77
  "@types/qrcode": "^1.5.6",
78
- "@biomejs/biome": "^2.4.14",
79
78
  "@types/better-sqlite3": "^7.6.13",
80
79
  "@types/node": "^25.6.2",
81
80
  "@types/ws": "^8.18.1",
@@ -1 +0,0 @@
1
- 'use strict';var chunkCPQSQ7FU_cjs=require('./chunk-CPQSQ7FU.cjs');require('./chunk-6C5TBG7Z.cjs');Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.oa}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.$a}});Object.defineProperty(exports,"GatewayWebSocketServer",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.pa}});
@@ -1 +0,0 @@
1
- export{oa as ChannelPluginLoader,$a as GatewayServer,pa as GatewayWebSocketServer}from'./chunk-3EE2AOK7.mjs';import'./chunk-HQBRVVXS.mjs';