@easbot/gateway 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,11 +1,11 @@
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 g=utils.Log.create({service:"gateway"}),P=class t extends Error{constructor(e,n,o){super(e);chunk6C5TBG7Z_cjs.a(this,"type");chunk6C5TBG7Z_cjs.a(this,"stage");chunk6C5TBG7Z_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=o,Error.captureStackTrace&&Error.captureStackTrace(this,t);}};function oe(t){let r=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],e=t.code;return r.includes(e??"")}function Nt(){process.on("unhandledRejection",t=>{let r=t instanceof Error?t:new Error(String(t));oe(r)||g.error("unhandled promise rejection",{error:r.message,stack:r.stack});}),process.on("uncaughtException",t=>{oe(t)||(g.error("uncaught exception",{error:t.message,stack:t.stack}),process.exit(1));});}exports.Gateway=void 0;(rr=>{let t={initialized:false,initPromise:null,directory:".easbot",config:null},r,e={server:null,config:null,initialized:false,status:"stopped"};async function n(a={}){if(t.initialized)return;if(t.initPromise)return t.initPromise;let l={directory:a.directory??".easbot",printLogs:a.printLogs??false,logLevel:a.logLevel??"INFO"};return t.directory=l.directory,t.initPromise=(async()=>{chunkCPQSQ7FU_cjs.Z();try{Nt();}catch(c){throw new P("Failed to install unhandled exception handlers","server",c instanceof Error?c:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),g.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{t.config=await chunkCPQSQ7FU_cjs.w(l.directory);}catch(c){throw new P("Failed to load gateway configuration","config",c instanceof Error?c:void 0)}t.initialized=true,g.info("gateway runtime initialized",{directory:l.directory,logLevel:l.logLevel});})(),t.initPromise}rr.init=n;function o(){return t.initialized}rr.isInitialized=o;function u(){return r||(r=async()=>{if(!t.initialized)throw new P("Gateway not initialized. Call init() first.","server");let a=chunkCPQSQ7FU_cjs._(),l=await chunkCPQSQ7FU_cjs.w(a.directory);return l.server?.enabled?(e={server:null,config:l,initialized:true,status:"stopped"},g.info("gateway initialized",{port:l.server?.port,hostname:l.server?.hostname}),e):(g.debug("gateway server disabled or not configured"),{server:null,config:l,initialized:true,status:"stopped"})}),r}function d(){return u()()}rr.state=d;async function y(){return (await d()).server}rr.get=y;async function i(){return (await d()).config?.server?.enabled??false}rr.isEnabled=i;async function f(){return (await d()).config}rr.config=f;function p(){return e.status}rr.getStatus=p;async function s(a){g.debug("Gateway.start: called"),t.initialized||await n();let l=await d();if(!(l.config?.server?.enabled??true))throw g.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(e.status==="running"){g.info("gateway server is already running");return}if(e.status==="starting"){g.info("gateway server is starting");return}e.status="starting";try{let c={...l.config?.server,...a};g.debug("gateway start: creating server with config",{port:c.port,hostname:c.hostname,path:c.path,https:c.https?.enabled});let E=await ge(c);e.server=E,e.status="running",e.error=void 0,g.info("gateway server started",{port:c.port,hostname:c.hostname});}catch(c){throw e.status="error",e.error=c instanceof Error?c.message:String(c),g.error("failed to start gateway server",{error:e.error}),c}}rr.start=s;async function m(){if(e.status==="stopped"){g.info("gateway server is already stopped");return}if(e.status==="stopping"){g.info("gateway server is stopping");return}e.status="stopping";try{e.server&&await e.server.stop(),e.server=null,e.status="stopped",e.error=void 0,await utils.Log.close(),g.info("gateway server stopped");}catch(a){throw e.status="error",e.error=a instanceof Error?a.message:String(a),g.error("failed to stop gateway server",{error:e.error}),a}}rr.stop=m;async function C(a){g.info("restarting gateway server"),(e.status==="running"||e.status==="starting")&&await m(),await s(a);}rr.restart=C;async function Y(){let a=chunkCPQSQ7FU_cjs._(),l=await chunkCPQSQ7FU_cjs.w(a.directory);return e.config=l,t.config=l,g.info("gateway config reloaded"),l}rr.reloadConfig=Y;async function ge(a,l){g.debug("createGatewayServer: starting");let{GatewayServer:G}=await import('./chunks/server-7LXANJ4O.cjs'),c=new G(a),E=l?.startupTimeout??3e4;if(await(async()=>{let S=new Promise((x,le)=>{setTimeout(()=>{le(new Error(`Gateway server startup timeout after ${E}ms`));},E);});try{await Promise.race([c.start(),S]);}catch(x){g.error("gateway server start failed, attempting cleanup",{error:x instanceof Error?x.message:String(x)});try{await c.stop();}catch{}throw x}})(),l?.onStarted)try{await l.onStarted(c);}catch(S){g.warn("server started but onStarted callback failed",{error:S instanceof Error?S.message:String(S)});}return g.info("gateway server created and started",{port:a.port,hostname:a.hostname}),c}rr.createGatewayServer=ge;})(exports.Gateway||(exports.Gateway={}));async function qt(t){let r=await qrcode.toString(t,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${r}
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 g=utils.Log.create({service:"gateway"}),P=class t extends Error{constructor(e,n,o){super(e);chunk6C5TBG7Z_cjs.a(this,"type");chunk6C5TBG7Z_cjs.a(this,"stage");chunk6C5TBG7Z_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=o,Error.captureStackTrace&&Error.captureStackTrace(this,t);}};function oe(t){let r=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],e=t.code;return r.includes(e??"")}function Nt(){process.on("unhandledRejection",t=>{let r=t instanceof Error?t:new Error(String(t));oe(r)||g.error("unhandled promise rejection",{error:r.message,stack:r.stack});}),process.on("uncaughtException",t=>{oe(t)||(g.error("uncaught exception",{error:t.message,stack:t.stack}),process.exit(1));});}exports.Gateway=void 0;(rr=>{let t={initialized:false,initPromise:null,directory:".easbot",config:null},r,e={server:null,config:null,initialized:false,status:"stopped"};async function n(a={}){if(t.initialized)return;if(t.initPromise)return t.initPromise;let l={directory:a.directory??".easbot",printLogs:a.printLogs??false,logLevel:a.logLevel??"INFO"};return t.directory=l.directory,t.initPromise=(async()=>{chunkCPQSQ7FU_cjs.Z();try{Nt();}catch(c){throw new P("Failed to install unhandled exception handlers","server",c instanceof Error?c:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),g.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{t.config=await chunkCPQSQ7FU_cjs.w(l.directory);}catch(c){throw new P("Failed to load gateway configuration","config",c instanceof Error?c:void 0)}t.initialized=true,g.info("gateway runtime initialized",{directory:l.directory,logLevel:l.logLevel});})(),t.initPromise}rr.init=n;function o(){return t.initialized}rr.isInitialized=o;function u(){return r||(r=async()=>{if(!t.initialized)throw new P("Gateway not initialized. Call init() first.","server");let a=chunkCPQSQ7FU_cjs._(),l=await chunkCPQSQ7FU_cjs.w(a.directory);return l.server?.enabled?(e={server:null,config:l,initialized:true,status:"stopped"},g.info("gateway initialized",{port:l.server?.port,hostname:l.server?.hostname}),e):(g.debug("gateway server disabled or not configured"),{server:null,config:l,initialized:true,status:"stopped"})}),r}function d(){return u()()}rr.state=d;async function y(){return (await d()).server}rr.get=y;async function i(){return (await d()).config?.server?.enabled??false}rr.isEnabled=i;async function f(){return (await d()).config}rr.config=f;function p(){return e.status}rr.getStatus=p;async function s(a){g.debug("Gateway.start: called"),t.initialized||await n();let l=await d();if(!(l.config?.server?.enabled??true))throw g.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(e.status==="running"){g.info("gateway server is already running");return}if(e.status==="starting"){g.info("gateway server is starting");return}e.status="starting";try{let c={...l.config?.server,...a};g.debug("gateway start: creating server with config",{port:c.port,hostname:c.hostname,path:c.path,https:c.https?.enabled});let E=await ce(c);e.server=E,e.status="running",e.error=void 0,g.info("gateway server started",{port:c.port,hostname:c.hostname});}catch(c){throw e.status="error",e.error=c instanceof Error?c.message:String(c),g.error("failed to start gateway server",{error:e.error}),c}}rr.start=s;async function m(){if(e.status==="stopped"){g.info("gateway server is already stopped");return}if(e.status==="stopping"){g.info("gateway server is stopping");return}e.status="stopping";try{e.server&&await e.server.stop(),e.server=null,e.status="stopped",e.error=void 0,g.info("gateway server stopped");}catch(a){throw e.status="error",e.error=a instanceof Error?a.message:String(a),g.error("failed to stop gateway server",{error:e.error}),a}}rr.stop=m;async function C(a){g.info("restarting gateway server"),(e.status==="running"||e.status==="starting")&&await m(),await s(a);}rr.restart=C;async function Y(){let a=chunkCPQSQ7FU_cjs._(),l=await chunkCPQSQ7FU_cjs.w(a.directory);return e.config=l,t.config=l,g.info("gateway config reloaded"),l}rr.reloadConfig=Y;async function ce(a,l){g.debug("createGatewayServer: starting");let{GatewayServer:G}=await import('./chunks/server-7LXANJ4O.cjs'),c=new G(a),E=l?.startupTimeout??3e4;if(await(async()=>{let S=new Promise((x,ge)=>{setTimeout(()=>{ge(new Error(`Gateway server startup timeout after ${E}ms`));},E);});try{await Promise.race([c.start(),S]);}catch(x){g.error("gateway server start failed, attempting cleanup",{error:x instanceof Error?x.message:String(x)});try{await c.stop();}catch{}throw x}})(),l?.onStarted)try{await l.onStarted(c);}catch(S){g.warn("server started but onStarted callback failed",{error:S instanceof Error?S.message:String(S)});}return g.info("gateway server created and started",{port:a.port,hostname:a.hostname}),c}rr.createGatewayServer=ce;})(exports.Gateway||(exports.Gateway={}));async function qt(t){let r=await qrcode.toString(t,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${r}
2
2
  `);}async function _(t){let r=await fetch(`${t}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!r.ok)throw new Error(`Failed to get QR code: HTTP ${r.status}`);let e=await r.json();if(!e.qrcode)throw new Error("No qrcode in response");let n=e.qrcode_img_content||"";return n&&await qt(n),{qrcodeUrl:n,qrcodeId:e.qrcode,message:"Scan the QR code with WeChat to connect."}}async function V(t){let{qrcodeId:r,apiBaseUrl:e,timeoutMs:n=48e4,maxRetries:o=3}=t,u=Date.now()+n,d=r,y=0;for(;Date.now()<u;){try{let i=new AbortController,f=setTimeout(()=>i.abort(),6e4),p=await fetch(`${e}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(d)}`,{headers:{"iLink-App-ClientVersion":"1"},signal:i.signal});if(clearTimeout(f),!p.ok)throw new Error(`HTTP ${p.status}`);let s=await p.json();switch(s.status){case "confirmed":return {connected:!0,token:s.bot_token,accountId:s.ilink_bot_id,baseUrl:s.baseurl,userId:s.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(y+=1,y>=o)return {connected:!1,message:"QR code expired after maximum retries."};process.stderr.write(`QR code expired, refreshing...
4
4
  `),d=(await _(e)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
5
5
  `);break;default:break}}catch(i){if(i instanceof Error&&i.name==="AbortError")continue;throw i}await new Promise(i=>setTimeout(i,1e3));}return {connected:false,message:"Login timed out."}}function jt(t){return ["Claude Code needs your approval.","",`Tool: ${t.tool_name}`,`Reason: ${t.description}`,`Input: ${t.input_preview}`,"",`Reply with: yes ${t.request_id}`,`Or deny with: no ${t.request_id}`].join(`
6
- `)}function Vt(t){let r=new index_js.Server({name:"weixin",version:t},{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 r.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"]}}]})),r.setRequestHandler(types_js.CallToolRequestSchema,async e=>{let{name:n,arguments:o}=e.params,u=chunkCPQSQ7FU_cjs.Ha();if(!u)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let d=u.baseUrl||chunkCPQSQ7FU_cjs.Ea,y=chunkCPQSQ7FU_cjs.Fa;switch(n){case "reply":{let i=typeof o?.chat_id=="string"?o.chat_id:"",f=typeof o?.text=="string"?o.text:"",p=Array.isArray(o?.files)?o.files.filter(m=>typeof m=="string"):void 0;if(!i||!f)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let s=chunkCPQSQ7FU_cjs.Qa(i)||"";try{if(p&&p.length>0){for(let[m,C]of p.entries()){if(!fs.existsSync(C))return {content:[{type:"text",text:`File not found: ${C}`}],isError:!0};await chunkCPQSQ7FU_cjs.Pa({filePath:C,to:i,text:m===0?f:"",baseUrl:d,token:u.token,contextToken:s,cdnBaseUrl:y});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await chunkCPQSQ7FU_cjs.Oa({to:i,text:f,baseUrl:d,token:u.token,contextToken:s}),{content:[{type:"text",text:"Message sent."}]}}catch(m){return {content:[{type:"text",text:`Failed to send: ${m}`}],isError:true}}}case "send_typing":{let i=typeof o?.chat_id=="string"?o.chat_id:"";if(!i)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let f=chunkCPQSQ7FU_cjs.Qa(i),p=await chunkCPQSQ7FU_cjs.Ka(d,u.token,i,f);return p.typing_ticket&&await chunkCPQSQ7FU_cjs.La(d,u.token,{ilink_user_id:i,typing_ticket:p.typing_ticket,status:chunkCPQSQ7FU_cjs.Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(f){return {content:[{type:"text",text:`Failed to send typing: ${f}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${n}`}],isError:true}}}),r}async function ie(t,r){r.enableConfigs(),r.initializeAnalyticsSink();let e=chunkCPQSQ7FU_cjs.Ha();e||(process.stderr.write("[weixin] No account configured. Run `easbot weixin login` to connect your WeChat account.\n"),await Promise.all([r.shutdown1PEventLogging(),r.shutdownDatadog()]),process.exit(1));let n=Vt(t),o=new stdio_js.StdioServerTransport;r.registerPermissionHandler(n,async s=>{let m=s.channel_context?.chat_id,C=m?{chatId:m,contextToken:chunkCPQSQ7FU_cjs.Qa(m)}:chunkTQ74GHLT_cjs.b();if(!C){r.logForDebugging(`[Weixin MCP] No active chat available for permission request ${s.request_id}`);return}try{chunkTQ74GHLT_cjs.c(s,C.chatId,C.contextToken),await chunkCPQSQ7FU_cjs.Oa({to:C.chatId,text:jt(s),baseUrl:u,token:e.token,contextToken:C.contextToken||""});}catch(Y){process.stderr.write(`[weixin] Failed to relay permission request ${s.request_id}: ${Y}
6
+ `)}function Vt(t){let r=new index_js.Server({name:"weixin",version:t},{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 r.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"]}}]})),r.setRequestHandler(types_js.CallToolRequestSchema,async e=>{let{name:n,arguments:o}=e.params,u=chunkCPQSQ7FU_cjs.Ha();if(!u)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let d=u.baseUrl||chunkCPQSQ7FU_cjs.Ea,y=chunkCPQSQ7FU_cjs.Fa;switch(n){case "reply":{let i=typeof o?.chat_id=="string"?o.chat_id:"",f=typeof o?.text=="string"?o.text:"",p=Array.isArray(o?.files)?o.files.filter(m=>typeof m=="string"):void 0;if(!i||!f)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let s=chunkCPQSQ7FU_cjs.Qa(i)||"";try{if(p&&p.length>0){for(let[m,C]of p.entries()){if(!fs.existsSync(C))return {content:[{type:"text",text:`File not found: ${C}`}],isError:!0};await chunkCPQSQ7FU_cjs.Pa({filePath:C,to:i,text:m===0?f:"",baseUrl:d,token:u.token,contextToken:s,cdnBaseUrl:y});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await chunkCPQSQ7FU_cjs.Oa({to:i,text:f,baseUrl:d,token:u.token,contextToken:s}),{content:[{type:"text",text:"Message sent."}]}}catch(m){return {content:[{type:"text",text:`Failed to send: ${m}`}],isError:true}}}case "send_typing":{let i=typeof o?.chat_id=="string"?o.chat_id:"";if(!i)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let f=chunkCPQSQ7FU_cjs.Qa(i),p=await chunkCPQSQ7FU_cjs.Ka(d,u.token,i,f);return p.typing_ticket&&await chunkCPQSQ7FU_cjs.La(d,u.token,{ilink_user_id:i,typing_ticket:p.typing_ticket,status:chunkCPQSQ7FU_cjs.Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(f){return {content:[{type:"text",text:`Failed to send typing: ${f}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${n}`}],isError:true}}}),r}async function se(t,r){r.enableConfigs(),r.initializeAnalyticsSink();let e=chunkCPQSQ7FU_cjs.Ha();e||(process.stderr.write("[weixin] No account configured. Run `easbot weixin login` to connect your WeChat account.\n"),await Promise.all([r.shutdown1PEventLogging(),r.shutdownDatadog()]),process.exit(1));let n=Vt(t),o=new stdio_js.StdioServerTransport;r.registerPermissionHandler(n,async s=>{let m=s.channel_context?.chat_id,C=m?{chatId:m,contextToken:chunkCPQSQ7FU_cjs.Qa(m)}:chunkTQ74GHLT_cjs.b();if(!C){r.logForDebugging(`[Weixin MCP] No active chat available for permission request ${s.request_id}`);return}try{chunkTQ74GHLT_cjs.c(s,C.chatId,C.contextToken),await chunkCPQSQ7FU_cjs.Oa({to:C.chatId,text:jt(s),baseUrl:u,token:e.token,contextToken:C.contextToken||""});}catch(Y){process.stderr.write(`[weixin] Failed to relay permission request ${s.request_id}: ${Y}
7
7
  `);}}),await n.connect(o);let u=e.baseUrl||chunkCPQSQ7FU_cjs.Ea,d=new AbortController,y=false,i=async()=>{y||(y=true,d.signal.aborted||d.abort(),await Promise.all([r.shutdown1PEventLogging(),r.shutdownDatadog()]),process.exit(0));};process.stdin.on("end",()=>{i();}),process.stdin.on("error",()=>{i();}),process.on("SIGINT",()=>{i();}),process.on("SIGTERM",()=>{i();}),process.on("SIGHUP",()=>{i();});let f=process.ppid,p=setInterval(()=>{try{process.kill(f,0);}catch{process.stderr.write(`[weixin] Parent process exited, shutting down...
8
- `),clearInterval(p),i();}},5e3);r.logForDebugging("[Weixin MCP] Starting poll loop"),await chunkCPQSQ7FU_cjs.Ra({baseUrl:u,cdnBaseUrl:chunkCPQSQ7FU_cjs.Fa,token:e.token,onMessage:async s=>{await n.notification({method:"notifications/claude/channel",params:{content:s.text,meta:{chat_id:s.fromUserId,sender_id:s.fromUserId,message_id:s.messageId,...s.attachmentPath&&{attachment_path:s.attachmentPath},...s.attachmentType&&{attachment_type:s.attachmentType}}}});},onPermissionResponse:async s=>{await n.notification({method:"notifications/claude/channel/permission",params:{request_id:s.requestId,behavior:s.behavior}});},abortSignal:d.signal}),clearInterval(p),await i();}function ae(){process.stdout.write(["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(`
8
+ `),clearInterval(p),i();}},5e3);r.logForDebugging("[Weixin MCP] Starting poll loop"),await chunkCPQSQ7FU_cjs.Ra({baseUrl:u,cdnBaseUrl:chunkCPQSQ7FU_cjs.Fa,token:e.token,onMessage:async s=>{await n.notification({method:"notifications/claude/channel",params:{content:s.text,meta:{chat_id:s.fromUserId,sender_id:s.fromUserId,message_id:s.messageId,...s.attachmentPath&&{attachment_path:s.attachmentPath},...s.attachmentType&&{attachment_type:s.attachmentType}}}});},onPermissionResponse:async s=>{await n.notification({method:"notifications/claude/channel/permission",params:{request_id:s.requestId,behavior:s.behavior}});},abortSignal:d.signal}),clearInterval(p),await i();}function ie(){process.stdout.write(["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(`
9
9
  `)+`
10
10
  `);}async function Kt(t=false){if(t){chunkCPQSQ7FU_cjs.Ja(),process.stdout.write(`WeChat account cleared.
11
11
  `);return}let r=chunkCPQSQ7FU_cjs.Ha();if(r){process.stdout.write(["Already connected:",` User ID: ${r.userId||"unknown"}`,` Connected since: ${utils.formatLocalISO(new Date(r.savedAt))}`,"","Run `easbot weixin login clear` to disconnect."].join(`
@@ -19,9 +19,9 @@ ${e.qrcodeUrl||""}
19
19
  `);let n=await V({qrcodeId:e.qrcodeId,apiBaseUrl:chunkCPQSQ7FU_cjs.Ea});(!n.connected||!n.token)&&(process.stderr.write(`Login failed: ${n.message}
20
20
  `),process.exit(1)),chunkCPQSQ7FU_cjs.Ia({token:n.token,baseUrl:n.baseUrl||chunkCPQSQ7FU_cjs.Ea,userId:n.userId,savedAt:new Date().toISOString()}),process.stdout.write(["Connected successfully!",` User ID: ${n.userId||"unknown"}`,` Base URL: ${n.baseUrl||chunkCPQSQ7FU_cjs.Ea}`].join(`
21
21
  `)+`
22
- `);}function Yt(t){(t[0]!=="pair"||!t[1])&&(ae(),process.exit(1));let r=chunkCPQSQ7FU_cjs.Na(t[1]);r||(process.stderr.write(`Invalid or expired pairing code.
22
+ `);}function Yt(t){(t[0]!=="pair"||!t[1])&&(ie(),process.exit(1));let r=chunkCPQSQ7FU_cjs.Na(t[1]);r||(process.stderr.write(`Invalid or expired pairing code.
23
23
  `),process.exit(1)),process.stdout.write(`Paired successfully: ${r}
24
- `);}function Jt(t,r){let e={userId:r,channelId:"weixin-main"};for(let n=0;n<t.length;n++){let o=t[n];if(o==="--display-name"||o==="-d"){let u=t[++n];if(!u)return "--display-name requires a value";e.displayName=u;}else return `Unknown argument: ${o}`}return e}function ce(){let t=chunkCPQSQ7FU_cjs.Ha();return t?.userId||(process.stderr.write("No weixin account logged in. Run `easbot weixin login` first.\n"),process.exit(1)),t.userId}async function Xt(){try{let t=chunkCPQSQ7FU_cjs.Ha();if(!t){process.stdout.write(`No weixin account logged in.
24
+ `);}function Jt(t,r){let e={userId:r,channelId:"weixin-main"};for(let n=0;n<t.length;n++){let o=t[n];if(o==="--display-name"||o==="-d"){let u=t[++n];if(!u)return "--display-name requires a value";e.displayName=u;}else return `Unknown argument: ${o}`}return e}function ae(){let t=chunkCPQSQ7FU_cjs.Ha();return t?.userId||(process.stderr.write("No weixin account logged in. Run `easbot weixin login` first.\n"),process.exit(1)),t.userId}async function Xt(){try{let t=chunkCPQSQ7FU_cjs.Ha();if(!t){process.stdout.write(`No weixin account logged in.
25
25
  `),process.stdout.write("Run `easbot weixin login` to bind your WeChat via iLink.\n");return}process.stdout.write(`weixin current user:
26
26
  `),process.stdout.write(` userId: ${t.userId??"(unknown)"}
27
27
  `),process.stdout.write(` baseUrl: ${t.baseUrl}
@@ -33,13 +33,13 @@ ${e.qrcodeUrl||""}
33
33
  `),process.stdout.write(` lastSeen: ${utils.formatLocalISO(new Date(e.lastSeenAt))}
34
34
  `)):(process.stdout.write(` contact: not registered
35
35
  `),process.stdout.write(" hint: run `easbot weixin ensure-user` to register\n"));}catch(t){process.stderr.write(`user failed: ${t}
36
- `),process.exit(1);}}async function Zt(t){let r=ce(),e=Jt(t,r);typeof e=="string"&&(process.stderr.write(`${e}
36
+ `),process.exit(1);}}async function Zt(t){let r=ae(),e=Jt(t,r);typeof e=="string"&&(process.stderr.write(`${e}
37
37
  `),process.exit(1));try{let n=await chunkCPQSQ7FU_cjs.Ba(e),{contact:o,session:u,created:d}=n,y=d.contact&&d.session?"\u5DF2\u521B\u5EFA":"\u5DF2\u5B58\u5728\uFF08\u5DF2\u66F4\u65B0\uFF09";process.stdout.write([`[weixin routing] ${y} user: ${r}`,` contact.uid: ${o.uid}`,` contact.path: ${chunkCPQSQ7FU_cjs.xa()}/contacts/${o.platform}/${o.stableId}.json`,` session.id: ${u.id}`,` session.path: ${chunkCPQSQ7FU_cjs.ya()}/sessions.json`,` profile: ${JSON.stringify(o.profile)}`].join(`
38
38
  `)+`
39
39
  `);}catch(n){process.stderr.write(`ensure-user failed: ${n}
40
- `),process.exit(1);}}async function er(t){let r=ce();t.length>0&&(process.stderr.write(`Unknown argument: ${t[0]}
40
+ `),process.exit(1);}}async function er(t){let r=ae();t.length>0&&(process.stderr.write(`Unknown argument: ${t[0]}
41
41
  `),process.stderr.write(`Usage: easbot weixin remove-user
42
42
  `),process.exit(1));try{let e=await chunkCPQSQ7FU_cjs.Ca(r,"weixin-main");process.stdout.write(`[weixin routing] removed user: ${r} contact=${e.removed.contact} session=${e.removed.session}
43
43
  `);}catch(e){process.stderr.write(`remove-user failed: ${e}
44
44
  `),process.exit(1);}}async function tr(t,r,e){let[n,...o]=t;switch(n){case "serve":r||(process.stderr.write(`[weixin] serve handler not available in this context.
45
- `),process.exit(1)),await ie(e??"0.0.0",r);return;case "login":await Kt(o[0]==="clear");return;case "access":Yt(o);return;case "user":await Xt();return;case "ensure-user":await Zt(o);return;case "remove-user":await er(o);return;default:ae();}}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=tr;
45
+ `),process.exit(1)),await se(e??"0.0.0",r);return;case "login":await Kt(o[0]==="clear");return;case "access":Yt(o);return;case "user":await Xt();return;case "ensure-user":await Zt(o);return;case "remove-user":await er(o);return;default:ie();}}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=tr;
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
1
- import {b,c}from'./chunks/chunk-NXFFFRVB.mjs';import {Z,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}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 g=Log.create({service:"gateway"}),P=class t extends Error{constructor(e,n,o){super(e);a(this,"type");a(this,"stage");a(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=o,Error.captureStackTrace&&Error.captureStackTrace(this,t);}};function se(t){let r=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],e=t.code;return r.includes(e??"")}function Wt(){process.on("unhandledRejection",t=>{let r=t instanceof Error?t:new Error(String(t));se(r)||g.error("unhandled promise rejection",{error:r.message,stack:r.stack});}),process.on("uncaughtException",t=>{se(t)||(g.error("uncaught exception",{error:t.message,stack:t.stack}),process.exit(1));});}var V;(nr=>{let t={initialized:false,initPromise:null,directory:".easbot",config:null},r,e={server:null,config:null,initialized:false,status:"stopped"};async function n(a={}){if(t.initialized)return;if(t.initPromise)return t.initPromise;let l={directory:a.directory??".easbot",printLogs:a.printLogs??false,logLevel:a.logLevel??"INFO"};return t.directory=l.directory,t.initPromise=(async()=>{Z();try{Wt();}catch(c){throw new P("Failed to install unhandled exception handlers","server",c instanceof Error?c:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),g.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{t.config=await w(l.directory);}catch(c){throw new P("Failed to load gateway configuration","config",c instanceof Error?c:void 0)}t.initialized=true,g.info("gateway runtime initialized",{directory:l.directory,logLevel:l.logLevel});})(),t.initPromise}nr.init=n;function o(){return t.initialized}nr.isInitialized=o;function u(){return r||(r=async()=>{if(!t.initialized)throw new P("Gateway not initialized. Call init() first.","server");let a=_(),l=await w(a.directory);return l.server?.enabled?(e={server:null,config:l,initialized:true,status:"stopped"},g.info("gateway initialized",{port:l.server?.port,hostname:l.server?.hostname}),e):(g.debug("gateway server disabled or not configured"),{server:null,config:l,initialized:true,status:"stopped"})}),r}function d(){return u()()}nr.state=d;async function y(){return (await d()).server}nr.get=y;async function i(){return (await d()).config?.server?.enabled??false}nr.isEnabled=i;async function f(){return (await d()).config}nr.config=f;function p(){return e.status}nr.getStatus=p;async function s(a){g.debug("Gateway.start: called"),t.initialized||await n();let l=await d();if(!(l.config?.server?.enabled??true))throw g.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(e.status==="running"){g.info("gateway server is already running");return}if(e.status==="starting"){g.info("gateway server is starting");return}e.status="starting";try{let c={...l.config?.server,...a};g.debug("gateway start: creating server with config",{port:c.port,hostname:c.hostname,path:c.path,https:c.https?.enabled});let T=await le(c);e.server=T,e.status="running",e.error=void 0,g.info("gateway server started",{port:c.port,hostname:c.hostname});}catch(c){throw e.status="error",e.error=c instanceof Error?c.message:String(c),g.error("failed to start gateway server",{error:e.error}),c}}nr.start=s;async function m(){if(e.status==="stopped"){g.info("gateway server is already stopped");return}if(e.status==="stopping"){g.info("gateway server is stopping");return}e.status="stopping";try{e.server&&await e.server.stop(),e.server=null,e.status="stopped",e.error=void 0,await Log.close(),g.info("gateway server stopped");}catch(a){throw e.status="error",e.error=a instanceof Error?a.message:String(a),g.error("failed to stop gateway server",{error:e.error}),a}}nr.stop=m;async function C(a){g.info("restarting gateway server"),(e.status==="running"||e.status==="starting")&&await m(),await s(a);}nr.restart=C;async function J(){let a=_(),l=await w(a.directory);return e.config=l,t.config=l,g.info("gateway config reloaded"),l}nr.reloadConfig=J;async function le(a,l){g.debug("createGatewayServer: starting");let{GatewayServer:L}=await import('./chunks/server-XGZGHXC5.mjs'),c=new L(a),T=l?.startupTimeout??3e4;if(await(async()=>{let S=new Promise((x,de)=>{setTimeout(()=>{de(new Error(`Gateway server startup timeout after ${T}ms`));},T);});try{await Promise.race([c.start(),S]);}catch(x){g.error("gateway server start failed, attempting cleanup",{error:x instanceof Error?x.message:String(x)});try{await c.stop();}catch{}throw x}})(),l?.onStarted)try{await l.onStarted(c);}catch(S){g.warn("server started but onStarted callback failed",{error:S instanceof Error?S.message:String(S)});}return g.info("gateway server created and started",{port:a.port,hostname:a.hostname}),c}nr.createGatewayServer=le;})(V||(V={}));async function Ot(t){let r=await toString(t,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${r}
1
+ import {b,c}from'./chunks/chunk-NXFFFRVB.mjs';import {Z,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}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 g=Log.create({service:"gateway"}),P=class t extends Error{constructor(e,n,o){super(e);a(this,"type");a(this,"stage");a(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=o,Error.captureStackTrace&&Error.captureStackTrace(this,t);}};function se(t){let r=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],e=t.code;return r.includes(e??"")}function Wt(){process.on("unhandledRejection",t=>{let r=t instanceof Error?t:new Error(String(t));se(r)||g.error("unhandled promise rejection",{error:r.message,stack:r.stack});}),process.on("uncaughtException",t=>{se(t)||(g.error("uncaught exception",{error:t.message,stack:t.stack}),process.exit(1));});}var V;(nr=>{let t={initialized:false,initPromise:null,directory:".easbot",config:null},r,e={server:null,config:null,initialized:false,status:"stopped"};async function n(a={}){if(t.initialized)return;if(t.initPromise)return t.initPromise;let l={directory:a.directory??".easbot",printLogs:a.printLogs??false,logLevel:a.logLevel??"INFO"};return t.directory=l.directory,t.initPromise=(async()=>{Z();try{Wt();}catch(c){throw new P("Failed to install unhandled exception handlers","server",c instanceof Error?c:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),g.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{t.config=await w(l.directory);}catch(c){throw new P("Failed to load gateway configuration","config",c instanceof Error?c:void 0)}t.initialized=true,g.info("gateway runtime initialized",{directory:l.directory,logLevel:l.logLevel});})(),t.initPromise}nr.init=n;function o(){return t.initialized}nr.isInitialized=o;function u(){return r||(r=async()=>{if(!t.initialized)throw new P("Gateway not initialized. Call init() first.","server");let a=_(),l=await w(a.directory);return l.server?.enabled?(e={server:null,config:l,initialized:true,status:"stopped"},g.info("gateway initialized",{port:l.server?.port,hostname:l.server?.hostname}),e):(g.debug("gateway server disabled or not configured"),{server:null,config:l,initialized:true,status:"stopped"})}),r}function d(){return u()()}nr.state=d;async function y(){return (await d()).server}nr.get=y;async function i(){return (await d()).config?.server?.enabled??false}nr.isEnabled=i;async function f(){return (await d()).config}nr.config=f;function p(){return e.status}nr.getStatus=p;async function s(a){g.debug("Gateway.start: called"),t.initialized||await n();let l=await d();if(!(l.config?.server?.enabled??true))throw g.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(e.status==="running"){g.info("gateway server is already running");return}if(e.status==="starting"){g.info("gateway server is starting");return}e.status="starting";try{let c={...l.config?.server,...a};g.debug("gateway start: creating server with config",{port:c.port,hostname:c.hostname,path:c.path,https:c.https?.enabled});let T=await ge(c);e.server=T,e.status="running",e.error=void 0,g.info("gateway server started",{port:c.port,hostname:c.hostname});}catch(c){throw e.status="error",e.error=c instanceof Error?c.message:String(c),g.error("failed to start gateway server",{error:e.error}),c}}nr.start=s;async function m(){if(e.status==="stopped"){g.info("gateway server is already stopped");return}if(e.status==="stopping"){g.info("gateway server is stopping");return}e.status="stopping";try{e.server&&await e.server.stop(),e.server=null,e.status="stopped",e.error=void 0,g.info("gateway server stopped");}catch(a){throw e.status="error",e.error=a instanceof Error?a.message:String(a),g.error("failed to stop gateway server",{error:e.error}),a}}nr.stop=m;async function C(a){g.info("restarting gateway server"),(e.status==="running"||e.status==="starting")&&await m(),await s(a);}nr.restart=C;async function J(){let a=_(),l=await w(a.directory);return e.config=l,t.config=l,g.info("gateway config reloaded"),l}nr.reloadConfig=J;async function ge(a,l){g.debug("createGatewayServer: starting");let{GatewayServer:L}=await import('./chunks/server-XGZGHXC5.mjs'),c=new L(a),T=l?.startupTimeout??3e4;if(await(async()=>{let S=new Promise((x,le)=>{setTimeout(()=>{le(new Error(`Gateway server startup timeout after ${T}ms`));},T);});try{await Promise.race([c.start(),S]);}catch(x){g.error("gateway server start failed, attempting cleanup",{error:x instanceof Error?x.message:String(x)});try{await c.stop();}catch{}throw x}})(),l?.onStarted)try{await l.onStarted(c);}catch(S){g.warn("server started but onStarted callback failed",{error:S instanceof Error?S.message:String(S)});}return g.info("gateway server created and started",{port:a.port,hostname:a.hostname}),c}nr.createGatewayServer=ge;})(V||(V={}));async function Ot(t){let r=await toString(t,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${r}
2
2
  `);}async function G(t){let r=await fetch(`${t}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!r.ok)throw new Error(`Failed to get QR code: HTTP ${r.status}`);let e=await r.json();if(!e.qrcode)throw new Error("No qrcode in response");let n=e.qrcode_img_content||"";return n&&await Ot(n),{qrcodeUrl:n,qrcodeId:e.qrcode,message:"Scan the QR code with WeChat to connect."}}async function K(t){let{qrcodeId:r,apiBaseUrl:e,timeoutMs:n=48e4,maxRetries:o=3}=t,u=Date.now()+n,d=r,y=0;for(;Date.now()<u;){try{let i=new AbortController,f=setTimeout(()=>i.abort(),6e4),p=await fetch(`${e}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(d)}`,{headers:{"iLink-App-ClientVersion":"1"},signal:i.signal});if(clearTimeout(f),!p.ok)throw new Error(`HTTP ${p.status}`);let s=await p.json();switch(s.status){case "confirmed":return {connected:!0,token:s.bot_token,accountId:s.ilink_bot_id,baseUrl:s.baseurl,userId:s.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(y+=1,y>=o)return {connected:!1,message:"QR code expired after maximum retries."};process.stderr.write(`QR code expired, refreshing...
4
4
  `),d=(await G(e)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
5
5
  `);break;default:break}}catch(i){if(i instanceof Error&&i.name==="AbortError")continue;throw i}await new Promise(i=>setTimeout(i,1e3));}return {connected:false,message:"Login timed out."}}function Vt(t){return ["Claude Code needs your approval.","",`Tool: ${t.tool_name}`,`Reason: ${t.description}`,`Input: ${t.input_preview}`,"",`Reply with: yes ${t.request_id}`,`Or deny with: no ${t.request_id}`].join(`
6
- `)}function Kt(t){let r=new Server({name:"weixin",version:t},{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 r.setRequestHandler(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"]}}]})),r.setRequestHandler(CallToolRequestSchema,async e=>{let{name:n,arguments:o}=e.params,u=Ha();if(!u)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let d=u.baseUrl||Ea,y=Fa;switch(n){case "reply":{let i=typeof o?.chat_id=="string"?o.chat_id:"",f=typeof o?.text=="string"?o.text:"",p=Array.isArray(o?.files)?o.files.filter(m=>typeof m=="string"):void 0;if(!i||!f)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let s=Qa(i)||"";try{if(p&&p.length>0){for(let[m,C]of p.entries()){if(!existsSync(C))return {content:[{type:"text",text:`File not found: ${C}`}],isError:!0};await Pa({filePath:C,to:i,text:m===0?f:"",baseUrl:d,token:u.token,contextToken:s,cdnBaseUrl:y});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await Oa({to:i,text:f,baseUrl:d,token:u.token,contextToken:s}),{content:[{type:"text",text:"Message sent."}]}}catch(m){return {content:[{type:"text",text:`Failed to send: ${m}`}],isError:true}}}case "send_typing":{let i=typeof o?.chat_id=="string"?o.chat_id:"";if(!i)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let f=Qa(i),p=await Ka(d,u.token,i,f);return p.typing_ticket&&await La(d,u.token,{ilink_user_id:i,typing_ticket:p.typing_ticket,status:Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(f){return {content:[{type:"text",text:`Failed to send typing: ${f}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${n}`}],isError:true}}}),r}async function ae(t,r){r.enableConfigs(),r.initializeAnalyticsSink();let e=Ha();e||(process.stderr.write("[weixin] No account configured. Run `easbot weixin login` to connect your WeChat account.\n"),await Promise.all([r.shutdown1PEventLogging(),r.shutdownDatadog()]),process.exit(1));let n=Kt(t),o=new StdioServerTransport;r.registerPermissionHandler(n,async s=>{let m=s.channel_context?.chat_id,C=m?{chatId:m,contextToken:Qa(m)}:b();if(!C){r.logForDebugging(`[Weixin MCP] No active chat available for permission request ${s.request_id}`);return}try{c(s,C.chatId,C.contextToken),await Oa({to:C.chatId,text:Vt(s),baseUrl:u,token:e.token,contextToken:C.contextToken||""});}catch(J){process.stderr.write(`[weixin] Failed to relay permission request ${s.request_id}: ${J}
6
+ `)}function Kt(t){let r=new Server({name:"weixin",version:t},{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 r.setRequestHandler(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"]}}]})),r.setRequestHandler(CallToolRequestSchema,async e=>{let{name:n,arguments:o}=e.params,u=Ha();if(!u)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let d=u.baseUrl||Ea,y=Fa;switch(n){case "reply":{let i=typeof o?.chat_id=="string"?o.chat_id:"",f=typeof o?.text=="string"?o.text:"",p=Array.isArray(o?.files)?o.files.filter(m=>typeof m=="string"):void 0;if(!i||!f)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let s=Qa(i)||"";try{if(p&&p.length>0){for(let[m,C]of p.entries()){if(!existsSync(C))return {content:[{type:"text",text:`File not found: ${C}`}],isError:!0};await Pa({filePath:C,to:i,text:m===0?f:"",baseUrl:d,token:u.token,contextToken:s,cdnBaseUrl:y});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await Oa({to:i,text:f,baseUrl:d,token:u.token,contextToken:s}),{content:[{type:"text",text:"Message sent."}]}}catch(m){return {content:[{type:"text",text:`Failed to send: ${m}`}],isError:true}}}case "send_typing":{let i=typeof o?.chat_id=="string"?o.chat_id:"";if(!i)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let f=Qa(i),p=await Ka(d,u.token,i,f);return p.typing_ticket&&await La(d,u.token,{ilink_user_id:i,typing_ticket:p.typing_ticket,status:Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(f){return {content:[{type:"text",text:`Failed to send typing: ${f}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${n}`}],isError:true}}}),r}async function ie(t,r){r.enableConfigs(),r.initializeAnalyticsSink();let e=Ha();e||(process.stderr.write("[weixin] No account configured. Run `easbot weixin login` to connect your WeChat account.\n"),await Promise.all([r.shutdown1PEventLogging(),r.shutdownDatadog()]),process.exit(1));let n=Kt(t),o=new StdioServerTransport;r.registerPermissionHandler(n,async s=>{let m=s.channel_context?.chat_id,C=m?{chatId:m,contextToken:Qa(m)}:b();if(!C){r.logForDebugging(`[Weixin MCP] No active chat available for permission request ${s.request_id}`);return}try{c(s,C.chatId,C.contextToken),await Oa({to:C.chatId,text:Vt(s),baseUrl:u,token:e.token,contextToken:C.contextToken||""});}catch(J){process.stderr.write(`[weixin] Failed to relay permission request ${s.request_id}: ${J}
7
7
  `);}}),await n.connect(o);let u=e.baseUrl||Ea,d=new AbortController,y=false,i=async()=>{y||(y=true,d.signal.aborted||d.abort(),await Promise.all([r.shutdown1PEventLogging(),r.shutdownDatadog()]),process.exit(0));};process.stdin.on("end",()=>{i();}),process.stdin.on("error",()=>{i();}),process.on("SIGINT",()=>{i();}),process.on("SIGTERM",()=>{i();}),process.on("SIGHUP",()=>{i();});let f=process.ppid,p=setInterval(()=>{try{process.kill(f,0);}catch{process.stderr.write(`[weixin] Parent process exited, shutting down...
8
- `),clearInterval(p),i();}},5e3);r.logForDebugging("[Weixin MCP] Starting poll loop"),await Ra({baseUrl:u,cdnBaseUrl:Fa,token:e.token,onMessage:async s=>{await n.notification({method:"notifications/claude/channel",params:{content:s.text,meta:{chat_id:s.fromUserId,sender_id:s.fromUserId,message_id:s.messageId,...s.attachmentPath&&{attachment_path:s.attachmentPath},...s.attachmentType&&{attachment_type:s.attachmentType}}}});},onPermissionResponse:async s=>{await n.notification({method:"notifications/claude/channel/permission",params:{request_id:s.requestId,behavior:s.behavior}});},abortSignal:d.signal}),clearInterval(p),await i();}function ce(){process.stdout.write(["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(`
8
+ `),clearInterval(p),i();}},5e3);r.logForDebugging("[Weixin MCP] Starting poll loop"),await Ra({baseUrl:u,cdnBaseUrl:Fa,token:e.token,onMessage:async s=>{await n.notification({method:"notifications/claude/channel",params:{content:s.text,meta:{chat_id:s.fromUserId,sender_id:s.fromUserId,message_id:s.messageId,...s.attachmentPath&&{attachment_path:s.attachmentPath},...s.attachmentType&&{attachment_type:s.attachmentType}}}});},onPermissionResponse:async s=>{await n.notification({method:"notifications/claude/channel/permission",params:{request_id:s.requestId,behavior:s.behavior}});},abortSignal:d.signal}),clearInterval(p),await i();}function ae(){process.stdout.write(["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(`
9
9
  `)+`
10
10
  `);}async function Yt(t=false){if(t){Ja(),process.stdout.write(`WeChat account cleared.
11
11
  `);return}let r=Ha();if(r){process.stdout.write(["Already connected:",` User ID: ${r.userId||"unknown"}`,` Connected since: ${formatLocalISO(new Date(r.savedAt))}`,"","Run `easbot weixin login clear` to disconnect."].join(`
@@ -19,9 +19,9 @@ ${e.qrcodeUrl||""}
19
19
  `);let n=await K({qrcodeId:e.qrcodeId,apiBaseUrl:Ea});(!n.connected||!n.token)&&(process.stderr.write(`Login failed: ${n.message}
20
20
  `),process.exit(1)),Ia({token:n.token,baseUrl:n.baseUrl||Ea,userId:n.userId,savedAt:new Date().toISOString()}),process.stdout.write(["Connected successfully!",` User ID: ${n.userId||"unknown"}`,` Base URL: ${n.baseUrl||Ea}`].join(`
21
21
  `)+`
22
- `);}function Jt(t){(t[0]!=="pair"||!t[1])&&(ce(),process.exit(1));let r=Na(t[1]);r||(process.stderr.write(`Invalid or expired pairing code.
22
+ `);}function Jt(t){(t[0]!=="pair"||!t[1])&&(ae(),process.exit(1));let r=Na(t[1]);r||(process.stderr.write(`Invalid or expired pairing code.
23
23
  `),process.exit(1)),process.stdout.write(`Paired successfully: ${r}
24
- `);}function Xt(t,r){let e={userId:r,channelId:"weixin-main"};for(let n=0;n<t.length;n++){let o=t[n];if(o==="--display-name"||o==="-d"){let u=t[++n];if(!u)return "--display-name requires a value";e.displayName=u;}else return `Unknown argument: ${o}`}return e}function ge(){let t=Ha();return t?.userId||(process.stderr.write("No weixin account logged in. Run `easbot weixin login` first.\n"),process.exit(1)),t.userId}async function Zt(){try{let t=Ha();if(!t){process.stdout.write(`No weixin account logged in.
24
+ `);}function Xt(t,r){let e={userId:r,channelId:"weixin-main"};for(let n=0;n<t.length;n++){let o=t[n];if(o==="--display-name"||o==="-d"){let u=t[++n];if(!u)return "--display-name requires a value";e.displayName=u;}else return `Unknown argument: ${o}`}return e}function ce(){let t=Ha();return t?.userId||(process.stderr.write("No weixin account logged in. Run `easbot weixin login` first.\n"),process.exit(1)),t.userId}async function Zt(){try{let t=Ha();if(!t){process.stdout.write(`No weixin account logged in.
25
25
  `),process.stdout.write("Run `easbot weixin login` to bind your WeChat via iLink.\n");return}process.stdout.write(`weixin current user:
26
26
  `),process.stdout.write(` userId: ${t.userId??"(unknown)"}
27
27
  `),process.stdout.write(` baseUrl: ${t.baseUrl}
@@ -33,13 +33,13 @@ ${e.qrcodeUrl||""}
33
33
  `),process.stdout.write(` lastSeen: ${formatLocalISO(new Date(e.lastSeenAt))}
34
34
  `)):(process.stdout.write(` contact: not registered
35
35
  `),process.stdout.write(" hint: run `easbot weixin ensure-user` to register\n"));}catch(t){process.stderr.write(`user failed: ${t}
36
- `),process.exit(1);}}async function er(t){let r=ge(),e=Xt(t,r);typeof e=="string"&&(process.stderr.write(`${e}
36
+ `),process.exit(1);}}async function er(t){let r=ce(),e=Xt(t,r);typeof e=="string"&&(process.stderr.write(`${e}
37
37
  `),process.exit(1));try{let n=await Ba(e),{contact:o,session:u,created:d}=n,y=d.contact&&d.session?"\u5DF2\u521B\u5EFA":"\u5DF2\u5B58\u5728\uFF08\u5DF2\u66F4\u65B0\uFF09";process.stdout.write([`[weixin routing] ${y} user: ${r}`,` contact.uid: ${o.uid}`,` contact.path: ${xa()}/contacts/${o.platform}/${o.stableId}.json`,` session.id: ${u.id}`,` session.path: ${ya()}/sessions.json`,` profile: ${JSON.stringify(o.profile)}`].join(`
38
38
  `)+`
39
39
  `);}catch(n){process.stderr.write(`ensure-user failed: ${n}
40
- `),process.exit(1);}}async function tr(t){let r=ge();t.length>0&&(process.stderr.write(`Unknown argument: ${t[0]}
40
+ `),process.exit(1);}}async function tr(t){let r=ce();t.length>0&&(process.stderr.write(`Unknown argument: ${t[0]}
41
41
  `),process.stderr.write(`Usage: easbot weixin remove-user
42
42
  `),process.exit(1));try{let e=await Ca(r,"weixin-main");process.stdout.write(`[weixin routing] removed user: ${r} contact=${e.removed.contact} session=${e.removed.session}
43
43
  `);}catch(e){process.stderr.write(`remove-user failed: ${e}
44
44
  `),process.exit(1);}}async function rr(t,r,e){let[n,...o]=t;switch(n){case "serve":r||(process.stderr.write(`[weixin] serve handler not available in this context.
45
- `),process.exit(1)),await ae(e??"0.0.0",r);return;case "login":await Yt(o[0]==="clear");return;case "access":Jt(o);return;case "user":await Zt();return;case "ensure-user":await er(o);return;case "remove-user":await tr(o);return;default:ce();}}export{V as Gateway,rr as handleWeixinCli};
45
+ `),process.exit(1)),await ie(e??"0.0.0",r);return;case "login":await Yt(o[0]==="clear");return;case "access":Jt(o);return;case "user":await Zt();return;case "ensure-user":await er(o);return;case "remove-user":await tr(o);return;default:ae();}}export{V as Gateway,rr as handleWeixinCli};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/gateway",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
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",
@@ -69,10 +69,10 @@
69
69
  "ws": "^8.20.0",
70
70
  "xdg-basedir": "^5.1.0",
71
71
  "zod": "^4.4.3",
72
- "@easbot/plugin": "0.3.0",
73
- "@easbot/sdk": "0.3.0",
74
- "@easbot/utils": "0.3.0",
75
- "@easbot/types": "0.3.0"
72
+ "@easbot/plugin": "0.3.2",
73
+ "@easbot/utils": "0.3.2",
74
+ "@easbot/sdk": "0.3.2",
75
+ "@easbot/types": "0.3.2"
76
76
  },
77
77
  "devDependencies": {
78
78
  "@types/qrcode": "^1.5.6",