@easbot/gateway 0.2.47 → 0.2.49

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 +1 @@
1
- 'use strict';var chunkEKVLJAIP_cjs=require('./chunk-EKVLJAIP.cjs');require('./chunk-AUPHFE34.cjs'),require('./chunk-GY3SWWW3.cjs');Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.oa}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.$a}});Object.defineProperty(exports,"GatewayWebSocketServer",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.pa}});
1
+ 'use strict';var chunkRZS4QZWL_cjs=require('./chunk-RZS4QZWL.cjs');require('./chunk-AUPHFE34.cjs'),require('./chunk-GY3SWWW3.cjs');Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.oa}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.$a}});Object.defineProperty(exports,"GatewayWebSocketServer",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.pa}});
@@ -0,0 +1 @@
1
+ export{oa as ChannelPluginLoader,$a as GatewayServer,pa as GatewayWebSocketServer}from'./chunk-LBRRMDDL.mjs';import'./chunk-7OFQ65NG.mjs';import'./chunk-HAMGVOQD.mjs';
package/dist/index.cjs CHANGED
@@ -1,37 +1,45 @@
1
- 'use strict';var chunkTQ74GHLT_cjs=require('./chunks/chunk-TQ74GHLT.cjs'),chunkEKVLJAIP_cjs=require('./chunks/chunk-EKVLJAIP.cjs'),chunkAUPHFE34_cjs=require('./chunks/chunk-AUPHFE34.cjs'),chunkGY3SWWW3_cjs=require('./chunks/chunk-GY3SWWW3.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 d=chunkAUPHFE34_cjs.a.create({service:"gateway"}),w=class e extends Error{constructor(t,n,o){super(t);chunkGY3SWWW3_cjs.a(this,"type");chunkGY3SWWW3_cjs.a(this,"stage");chunkGY3SWWW3_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=o,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function oe(e){let r=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return r.includes(t??"")}function Ft(){process.on("unhandledRejection",e=>{let r=e instanceof Error?e:new Error(String(e));oe(r)||d.error("unhandled promise rejection",{error:r.message,stack:r.stack});}),process.on("uncaughtException",e=>{oe(e)||(d.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}exports.Gateway=void 0;(er=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},r,t={server:null,config:null,initialized:false,status:"stopped"};async function n(l={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let g={directory:l.directory??".easbot",printLogs:l.printLogs??false,logLevel:l.logLevel??"INFO"};return e.directory=g.directory,e.initPromise=(async()=>{let R=chunkEKVLJAIP_cjs.Z();try{await chunkAUPHFE34_cjs.a.init({logDir:R.Path.log,print:g.printLogs,level:g.logLevel});}catch(a){throw new w("Failed to initialize log infrastructure","log",a instanceof Error?a:void 0)}try{Ft();}catch(a){throw new w("Failed to install unhandled exception handlers","server",a instanceof Error?a:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),d.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{e.config=await chunkEKVLJAIP_cjs.w(g.directory);}catch(a){throw new w("Failed to load gateway configuration","config",a instanceof Error?a:void 0)}e.initialized=true,d.info("gateway runtime initialized",{directory:g.directory,logLevel:g.logLevel});})(),e.initPromise}er.init=n;function o(){return e.initialized}er.isInitialized=o;function c(){return r||(r=async()=>{if(!e.initialized)throw new w("Gateway not initialized. Call init() first.","server");let l=chunkEKVLJAIP_cjs._(),g=await chunkEKVLJAIP_cjs.w(l.directory);return g.server?.enabled?(t={server:null,config:g,initialized:true,status:"stopped"},d.info("gateway initialized",{port:g.server?.port,hostname:g.server?.hostname}),t):(d.debug("gateway server disabled or not configured"),{server:null,config:g,initialized:true,status:"stopped"})}),r}function u(){return c()()}er.state=u;async function C(){return (await u()).server}er.get=C;async function i(){return (await u()).config?.server?.enabled??false}er.isEnabled=i;async function f(){return (await u()).config}er.config=f;function p(){return t.status}er.getStatus=p;async function s(l){d.debug("Gateway.start: called"),e.initialized||await n();let g=await u();if(!(g.config?.server?.enabled??true))throw d.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){d.info("gateway server is already running");return}if(t.status==="starting"){d.info("gateway server is starting");return}t.status="starting";try{let a={...g.config?.server,...l};d.debug("gateway start: creating server with config",{port:a.port,hostname:a.hostname,path:a.path,https:a.https?.enabled});let T=await ae(a);t.server=T,t.status="running",t.error=void 0,d.info("gateway server started",{port:a.port,hostname:a.hostname});}catch(a){throw t.status="error",t.error=a instanceof Error?a.message:String(a),d.error("failed to start gateway server",{error:t.error}),a}}er.start=s;async function m(){if(t.status==="stopped"){d.info("gateway server is already stopped");return}if(t.status==="stopping"){d.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,await chunkAUPHFE34_cjs.a.close(),d.info("gateway server stopped");}catch(l){throw t.status="error",t.error=l instanceof Error?l.message:String(l),d.error("failed to stop gateway server",{error:t.error}),l}}er.stop=m;async function h(l){d.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await m(),await s(l);}er.restart=h;async function Y(){let l=chunkEKVLJAIP_cjs._(),g=await chunkEKVLJAIP_cjs.w(l.directory);return t.config=g,e.config=g,d.info("gateway config reloaded"),g}er.reloadConfig=Y;async function ae(l,g){d.debug("createGatewayServer: starting");let{GatewayServer:R}=await import('./chunks/server-JXSJH7GK.cjs'),a=new R(l),T=g?.startupTimeout??3e4;if(await(async()=>{let v=new Promise((x,ce)=>{setTimeout(()=>{ce(new Error(`Gateway server startup timeout after ${T}ms`));},T);});try{await Promise.race([a.start(),v]);}catch(x){d.error("gateway server start failed, attempting cleanup",{error:x instanceof Error?x.message:String(x)});try{await a.stop();}catch{}throw x}})(),g?.onStarted)try{await g.onStarted(a);}catch(v){d.warn("server started but onStarted callback failed",{error:v instanceof Error?v.message:String(v)});}return d.info("gateway server created and started",{port:l.port,hostname:l.hostname}),a}er.createGatewayServer=ae;})(exports.Gateway||(exports.Gateway={}));async function qt(e){let r=await qrcode.toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${r}
2
- `);}async function L(e){let r=await fetch(`${e}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!r.ok)throw new Error(`Failed to get QR code: HTTP ${r.status}`);let t=await r.json();if(!t.qrcode)throw new Error("No qrcode in response");let n=t.qrcode_img_content||"";return n&&await qt(n),{qrcodeUrl:n,qrcodeId:t.qrcode,message:"Scan the QR code with WeChat to connect."}}async function K(e){let{qrcodeId:r,apiBaseUrl:t,timeoutMs:n=48e4,maxRetries:o=3}=e,c=Date.now()+n,u=r,C=0;for(;Date.now()<c;){try{let i=new AbortController,f=setTimeout(()=>i.abort(),6e4),p=await fetch(`${t}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(u)}`,{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
- `);break;case "expired":{if(C+=1,C>=o)return {connected:!1,message:"QR code expired after maximum retries."};process.stderr.write(`QR code expired, refreshing...
4
- `),u=(await L(t)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
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 zt(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 Qt(e){let r=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 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 t=>{let{name:n,arguments:o}=t.params,c=chunkEKVLJAIP_cjs.Ha();if(!c)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let u=c.baseUrl||chunkEKVLJAIP_cjs.Ea,C=chunkEKVLJAIP_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=chunkEKVLJAIP_cjs.Qa(i)||"";try{if(p&&p.length>0){for(let[m,h]of p.entries()){if(!fs.existsSync(h))return {content:[{type:"text",text:`File not found: ${h}`}],isError:!0};await chunkEKVLJAIP_cjs.Pa({filePath:h,to:i,text:m===0?f:"",baseUrl:u,token:c.token,contextToken:s,cdnBaseUrl:C});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await chunkEKVLJAIP_cjs.Oa({to:i,text:f,baseUrl:u,token:c.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=chunkEKVLJAIP_cjs.Qa(i),p=await chunkEKVLJAIP_cjs.Ka(u,c.token,i,f);return p.typing_ticket&&await chunkEKVLJAIP_cjs.La(u,c.token,{ilink_user_id:i,typing_ticket:p.typing_ticket,status:chunkEKVLJAIP_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(e,r){r.enableConfigs(),r.initializeAnalyticsSink();let t=chunkEKVLJAIP_cjs.Ha();t||(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=Qt(e),o=new stdio_js.StdioServerTransport;r.registerPermissionHandler(n,async s=>{let m=s.channel_context?.chat_id,h=m?{chatId:m,contextToken:chunkEKVLJAIP_cjs.Qa(m)}:chunkTQ74GHLT_cjs.b();if(!h){r.logForDebugging(`[Weixin MCP] No active chat available for permission request ${s.request_id}`);return}try{chunkTQ74GHLT_cjs.c(s,h.chatId,h.contextToken),await chunkEKVLJAIP_cjs.Oa({to:h.chatId,text:zt(s),baseUrl:c,token:t.token,contextToken:h.contextToken||""});}catch(Y){process.stderr.write(`[weixin] Failed to relay permission request ${s.request_id}: ${Y}
7
- `);}}),await n.connect(o);let c=t.baseUrl||chunkEKVLJAIP_cjs.Ea,u=new AbortController,C=false,i=async()=>{C||(C=true,u.signal.aborted||u.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 chunkEKVLJAIP_cjs.Ra({baseUrl:c,cdnBaseUrl:chunkEKVLJAIP_cjs.Fa,token:t.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:u.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>","","User routing:",' easbot weixin ensure-user <userId> [--display-name "<name>"] [--username "<u>"] [--channel-id <id>]'," easbot weixin list-users"," easbot weixin remove-user <userId> [--channel-id <id>]"].join(`
1
+ 'use strict';var chunkTQ74GHLT_cjs=require('./chunks/chunk-TQ74GHLT.cjs'),chunkRZS4QZWL_cjs=require('./chunks/chunk-RZS4QZWL.cjs'),chunkAUPHFE34_cjs=require('./chunks/chunk-AUPHFE34.cjs'),chunkGY3SWWW3_cjs=require('./chunks/chunk-GY3SWWW3.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 l=chunkAUPHFE34_cjs.a.create({service:"gateway"}),S=class e extends Error{constructor(t,n,o){super(t);chunkGY3SWWW3_cjs.a(this,"type");chunkGY3SWWW3_cjs.a(this,"stage");chunkGY3SWWW3_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=o,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function se(e){let r=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return r.includes(t??"")}function $t(){process.on("unhandledRejection",e=>{let r=e instanceof Error?e:new Error(String(e));se(r)||l.error("unhandled promise rejection",{error:r.message,stack:r.stack});}),process.on("uncaughtException",e=>{se(e)||(l.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}exports.Gateway=void 0;(rr=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},r,t={server:null,config:null,initialized:false,status:"stopped"};async function n(c={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let g={directory:c.directory??".easbot",printLogs:c.printLogs??false,logLevel:c.logLevel??"INFO"};return e.directory=g.directory,e.initPromise=(async()=>{let R=chunkRZS4QZWL_cjs.Z();try{await chunkAUPHFE34_cjs.a.init({logDir:R.Path.log,print:g.printLogs,level:g.logLevel});}catch(a){throw new S("Failed to initialize log infrastructure","log",a instanceof Error?a:void 0)}try{$t();}catch(a){throw new S("Failed to install unhandled exception handlers","server",a instanceof Error?a:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),l.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{e.config=await chunkRZS4QZWL_cjs.w(g.directory);}catch(a){throw new S("Failed to load gateway configuration","config",a instanceof Error?a:void 0)}e.initialized=true,l.info("gateway runtime initialized",{directory:g.directory,logLevel:g.logLevel});})(),e.initPromise}rr.init=n;function o(){return e.initialized}rr.isInitialized=o;function u(){return r||(r=async()=>{if(!e.initialized)throw new S("Gateway not initialized. Call init() first.","server");let c=chunkRZS4QZWL_cjs._(),g=await chunkRZS4QZWL_cjs.w(c.directory);return g.server?.enabled?(t={server:null,config:g,initialized:true,status:"stopped"},l.info("gateway initialized",{port:g.server?.port,hostname:g.server?.hostname}),t):(l.debug("gateway server disabled or not configured"),{server:null,config:g,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 t.status}rr.getStatus=p;async function s(c){l.debug("Gateway.start: called"),e.initialized||await n();let g=await d();if(!(g.config?.server?.enabled??true))throw l.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){l.info("gateway server is already running");return}if(t.status==="starting"){l.info("gateway server is starting");return}t.status="starting";try{let a={...g.config?.server,...c};l.debug("gateway start: creating server with config",{port:a.port,hostname:a.hostname,path:a.path,https:a.https?.enabled});let T=await ge(a);t.server=T,t.status="running",t.error=void 0,l.info("gateway server started",{port:a.port,hostname:a.hostname});}catch(a){throw t.status="error",t.error=a instanceof Error?a.message:String(a),l.error("failed to start gateway server",{error:t.error}),a}}rr.start=s;async function m(){if(t.status==="stopped"){l.info("gateway server is already stopped");return}if(t.status==="stopping"){l.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,await chunkAUPHFE34_cjs.a.close(),l.info("gateway server stopped");}catch(c){throw t.status="error",t.error=c instanceof Error?c.message:String(c),l.error("failed to stop gateway server",{error:t.error}),c}}rr.stop=m;async function h(c){l.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await m(),await s(c);}rr.restart=h;async function J(){let c=chunkRZS4QZWL_cjs._(),g=await chunkRZS4QZWL_cjs.w(c.directory);return t.config=g,e.config=g,l.info("gateway config reloaded"),g}rr.reloadConfig=J;async function ge(c,g){l.debug("createGatewayServer: starting");let{GatewayServer:R}=await import('./chunks/server-4SVVHWFK.cjs'),a=new R(c),T=g?.startupTimeout??3e4;if(await(async()=>{let v=new Promise((x,le)=>{setTimeout(()=>{le(new Error(`Gateway server startup timeout after ${T}ms`));},T);});try{await Promise.race([a.start(),v]);}catch(x){l.error("gateway server start failed, attempting cleanup",{error:x instanceof Error?x.message:String(x)});try{await a.stop();}catch{}throw x}})(),g?.onStarted)try{await g.onStarted(a);}catch(v){l.warn("server started but onStarted callback failed",{error:v instanceof Error?v.message:String(v)});}return l.info("gateway server created and started",{port:c.port,hostname:c.hostname}),a}rr.createGatewayServer=ge;})(exports.Gateway||(exports.Gateway={}));async function qt(e){let r=await qrcode.toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${r}
2
+ `);}async function L(e){let r=await fetch(`${e}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!r.ok)throw new Error(`Failed to get QR code: HTTP ${r.status}`);let t=await r.json();if(!t.qrcode)throw new Error("No qrcode in response");let n=t.qrcode_img_content||"";return n&&await qt(n),{qrcodeUrl:n,qrcodeId:t.qrcode,message:"Scan the QR code with WeChat to connect."}}async function K(e){let{qrcodeId:r,apiBaseUrl:t,timeoutMs:n=48e4,maxRetries:o=3}=e,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(`${t}/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
+ `);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
+ `),d=(await L(t)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
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(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 Vt(e){let r=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 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 t=>{let{name:n,arguments:o}=t.params,u=chunkRZS4QZWL_cjs.Ha();if(!u)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let d=u.baseUrl||chunkRZS4QZWL_cjs.Ea,y=chunkRZS4QZWL_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=chunkRZS4QZWL_cjs.Qa(i)||"";try{if(p&&p.length>0){for(let[m,h]of p.entries()){if(!fs.existsSync(h))return {content:[{type:"text",text:`File not found: ${h}`}],isError:!0};await chunkRZS4QZWL_cjs.Pa({filePath:h,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 chunkRZS4QZWL_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=chunkRZS4QZWL_cjs.Qa(i),p=await chunkRZS4QZWL_cjs.Ka(d,u.token,i,f);return p.typing_ticket&&await chunkRZS4QZWL_cjs.La(d,u.token,{ilink_user_id:i,typing_ticket:p.typing_ticket,status:chunkRZS4QZWL_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(e,r){r.enableConfigs(),r.initializeAnalyticsSink();let t=chunkRZS4QZWL_cjs.Ha();t||(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(e),o=new stdio_js.StdioServerTransport;r.registerPermissionHandler(n,async s=>{let m=s.channel_context?.chat_id,h=m?{chatId:m,contextToken:chunkRZS4QZWL_cjs.Qa(m)}:chunkTQ74GHLT_cjs.b();if(!h){r.logForDebugging(`[Weixin MCP] No active chat available for permission request ${s.request_id}`);return}try{chunkTQ74GHLT_cjs.c(s,h.chatId,h.contextToken),await chunkRZS4QZWL_cjs.Oa({to:h.chatId,text:jt(s),baseUrl:u,token:t.token,contextToken:h.contextToken||""});}catch(J){process.stderr.write(`[weixin] Failed to relay permission request ${s.request_id}: ${J}
7
+ `);}}),await n.connect(o);let u=t.baseUrl||chunkRZS4QZWL_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 chunkRZS4QZWL_cjs.Ra({baseUrl:u,cdnBaseUrl:chunkRZS4QZWL_cjs.Fa,token:t.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
- `);}async function jt(e=false){if(e){chunkEKVLJAIP_cjs.Ja(),process.stdout.write(`WeChat account cleared.
11
- `);return}let r=chunkEKVLJAIP_cjs.Ha();if(r){process.stdout.write(["Already connected:",` User ID: ${r.userId||"unknown"}`,` Connected since: ${r.savedAt}`,"","Run `easbot weixin login clear` to disconnect."].join(`
10
+ `);}async function Kt(e=false){if(e){chunkRZS4QZWL_cjs.Ja(),process.stdout.write(`WeChat account cleared.
11
+ `);return}let r=chunkRZS4QZWL_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(`
12
12
  `)+`
13
13
  `);return}process.stdout.write(`Starting WeChat QR login...
14
14
 
15
- `);let t=await L(chunkEKVLJAIP_cjs.Ea);process.stdout.write(`
15
+ `);let t=await L(chunkRZS4QZWL_cjs.Ea);process.stdout.write(`
16
16
  Scan the QR code above with WeChat, or open this URL:
17
17
  ${t.qrcodeUrl||""}
18
18
 
19
- `);let n=await K({qrcodeId:t.qrcodeId,apiBaseUrl:chunkEKVLJAIP_cjs.Ea});(!n.connected||!n.token)&&(process.stderr.write(`Login failed: ${n.message}
20
- `),process.exit(1)),chunkEKVLJAIP_cjs.Ia({token:n.token,baseUrl:n.baseUrl||chunkEKVLJAIP_cjs.Ea,userId:n.userId,savedAt:new Date().toISOString()}),process.stdout.write(["Connected successfully!",` User ID: ${n.userId||"unknown"}`,` Base URL: ${n.baseUrl||chunkEKVLJAIP_cjs.Ea}`].join(`
19
+ `);let n=await K({qrcodeId:t.qrcodeId,apiBaseUrl:chunkRZS4QZWL_cjs.Ea});(!n.connected||!n.token)&&(process.stderr.write(`Login failed: ${n.message}
20
+ `),process.exit(1)),chunkRZS4QZWL_cjs.Ia({token:n.token,baseUrl:n.baseUrl||chunkRZS4QZWL_cjs.Ea,userId:n.userId,savedAt:new Date().toISOString()}),process.stdout.write(["Connected successfully!",` User ID: ${n.userId||"unknown"}`,` Base URL: ${n.baseUrl||chunkRZS4QZWL_cjs.Ea}`].join(`
21
21
  `)+`
22
- `);}function Vt(e){(e[0]!=="pair"||!e[1])&&(ie(),process.exit(1));let r=chunkEKVLJAIP_cjs.Na(e[1]);r||(process.stderr.write(`Invalid or expired pairing code.
22
+ `);}function Yt(e){(e[0]!=="pair"||!e[1])&&(ae(),process.exit(1));let r=chunkRZS4QZWL_cjs.Na(e[1]);r||(process.stderr.write(`Invalid or expired pairing code.
23
23
  `),process.exit(1)),process.stdout.write(`Paired successfully: ${r}
24
- `);}function Kt(e){if(e.length===0)return 'Usage: easbot weixin ensure-user <userId> [--display-name "<name>"] [--username "<u>"] [--channel-id <id>]';let r=e[0];if(!r)return "userId is required";let t={userId:r};for(let n=1;n<e.length;n++){let o=e[n];if(o==="--display-name"||o==="-d"){let c=e[++n];if(!c)return "--display-name requires a value";t.displayName=c;}else if(o==="--username"||o==="-u"){let c=e[++n];if(!c)return "--username requires a value";t.username=c;}else if(o==="--channel-id"||o==="-c"){let c=e[++n];if(!c)return "--channel-id requires a value";t.channelId=c;}}return t}function Yt(e){let r=Kt(e);typeof r=="string"&&(process.stderr.write(`${r}
25
- `),process.exit(1)),chunkEKVLJAIP_cjs.Ba(r).then(t=>{let{contact:n,session:o,created:c}=t,u=c.contact&&c.session?"\u5DF2\u521B\u5EFA":"\u5DF2\u5B58\u5728\uFF08\u5DF2\u66F4\u65B0\uFF09";process.stdout.write([`[weixin routing] ${u} user: ${r.userId}`,` contact.uid: ${n.uid}`,` contact.path: ${chunkEKVLJAIP_cjs.xa()}/contacts/${n.platform}/${n.stableId}.json`,` session.id: ${o.id}`,` session.path: ${chunkEKVLJAIP_cjs.ya()}/sessions.json`,` profile: ${JSON.stringify(n.profile)}`].join(`
24
+ `);}function Jt(e,r){let t={userId:r,channelId:"weixin-main"};for(let n=0;n<e.length;n++){let o=e[n];if(o==="--display-name"||o==="-d"){let u=e[++n];if(!u)return "--display-name requires a value";t.displayName=u;}else return `Unknown argument: ${o}`}return t}function ce(){let e=chunkRZS4QZWL_cjs.Ha();return e?.userId||(process.stderr.write("No weixin account logged in. Run `easbot weixin login` first.\n"),process.exit(1)),e.userId}async function Xt(){try{let e=chunkRZS4QZWL_cjs.Ha();if(!e){process.stdout.write(`No weixin account logged in.
25
+ `),process.stdout.write("Run `easbot weixin login` to bind your WeChat via iLink.\n");return}process.stdout.write(`weixin current user:
26
+ `),process.stdout.write(` userId: ${e.userId??"(unknown)"}
27
+ `),process.stdout.write(` baseUrl: ${e.baseUrl}
28
+ `),process.stdout.write(` savedAt: ${utils.formatLocalISO(new Date(e.savedAt))}
29
+ `);let t=(await chunkRZS4QZWL_cjs.Da()).find(n=>n.stableId===e.userId);t?(process.stdout.write(` contact: registered
30
+ `),process.stdout.write(` uid: ${t.uid}
31
+ `),t.profile.displayName&&process.stdout.write(` display: ${t.profile.displayName}
32
+ `),t.profile.username&&process.stdout.write(` username: ${t.profile.username}
33
+ `),process.stdout.write(` lastSeen: ${utils.formatLocalISO(new Date(t.lastSeenAt))}
34
+ `)):(process.stdout.write(` contact: not registered
35
+ `),process.stdout.write(" hint: run `easbot weixin ensure-user` to register\n"));}catch(e){process.stderr.write(`user failed: ${e}
36
+ `),process.exit(1);}}async function Zt(e){let r=ce(),t=Jt(e,r);typeof t=="string"&&(process.stderr.write(`${t}
37
+ `),process.exit(1));try{let n=await chunkRZS4QZWL_cjs.Ba(t),{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: ${chunkRZS4QZWL_cjs.xa()}/contacts/${o.platform}/${o.stableId}.json`,` session.id: ${u.id}`,` session.path: ${chunkRZS4QZWL_cjs.ya()}/sessions.json`,` profile: ${JSON.stringify(o.profile)}`].join(`
26
38
  `)+`
27
- `);}).catch(t=>{process.stderr.write(`ensure-user failed: ${t}
28
- `),process.exit(1);});}function Jt(){chunkEKVLJAIP_cjs.Da().then(e=>{if(e.length===0){process.stdout.write(`No weixin users registered.
29
- `),process.stdout.write("Use `easbot weixin ensure-user <userId>` to add one.\n");return}process.stdout.write(`weixin users (${e.length}):
30
- `);for(let r of e){let t=r.profile.displayName??r.profile.username??"(no name)";process.stdout.write(` - ${r.stableId} ${t} lastSeen=${new Date(r.lastSeenAt).toISOString()}
31
- `);}}).catch(e=>{process.stderr.write(`list-users failed: ${e}
32
- `),process.exit(1);});}function Xt(e){e.length===0&&(process.stderr.write(`Usage: easbot weixin remove-user <userId> [--channel-id <id>]
33
- `),process.exit(1));let r=e[0];r||(process.stderr.write(`userId is required
34
- `),process.exit(1));let t="weixin-main";for(let n=1;n<e.length;n++)(e[n]==="--channel-id"||e[n]==="-c")&&(t=e[++n]??t);chunkEKVLJAIP_cjs.Ca(r,t).then(n=>{process.stdout.write(`[weixin routing] removed user: ${r} contact=${n.removed.contact} session=${n.removed.session}
35
- `);}).catch(n=>{process.stderr.write(`remove-user failed: ${n}
36
- `),process.exit(1);});}async function Zt(e,r,t){let[n,...o]=e;switch(n){case "serve":r||(process.stderr.write(`[weixin] serve handler not available in this context.
37
- `),process.exit(1)),await se(t??"0.0.0",r);return;case "login":await jt(o[0]==="clear");return;case "access":Vt(o);return;case "ensure-user":Yt(o);return;case "list-users":Jt();return;case "remove-user":Xt(o);return;default:ie();}}async function un(e){let{Log:r}=await import('./chunks/log-JFEBRH2W.cjs'),t=false;await r.init({logDir:e.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:e.print??false,dev:e.dev??t,level:e.level??("INFO")});}Object.defineProperty(exports,"AgentRegistry",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Za}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.p}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.k}});Object.defineProperty(exports,"AgentSyncManager",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs._a}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.j}});Object.defineProperty(exports,"BaseChannelPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.qa}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.h}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.oa}});Object.defineProperty(exports,"ChannelPluginRegistry",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Xa}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.o}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.m}});Object.defineProperty(exports,"DEBUG_AGENT_FILTER",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.T}});Object.defineProperty(exports,"DEFAULT_AGENT_FILTER",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.S}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ha}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ja}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ia}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ga}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.fa}});Object.defineProperty(exports,"DiscordPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.sa}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.c}});Object.defineProperty(exports,"FeishuPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ua}});Object.defineProperty(exports,"GatewayClientConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.s}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.l}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.t}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.$a}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.r}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.na}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.i}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.n}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ka}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.la}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.g}});Object.defineProperty(exports,"NostrPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Va}});Object.defineProperty(exports,"SdkEventBridge",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.R}});Object.defineProperty(exports,"SdkEventBus",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Q}});Object.defineProperty(exports,"SdkEventType",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.P}});Object.defineProperty(exports,"SdkMessageCollector",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.U}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.q}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ma}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.f}});Object.defineProperty(exports,"SignalPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Ua}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.b}});Object.defineProperty(exports,"SlackPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ta}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.a}});Object.defineProperty(exports,"TelegramPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ra}});Object.defineProperty(exports,"WEIXIN_PLATFORM",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.wa}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.d}});Object.defineProperty(exports,"WeChatPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.va}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.e}});Object.defineProperty(exports,"WebChatPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Ta}});Object.defineProperty(exports,"WeixinPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Sa}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.z}});Object.defineProperty(exports,"convertToGatewayMessage",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ba}});Object.defineProperty(exports,"createChannelPlugin",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Wa}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.da}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.$}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.aa}});Object.defineProperty(exports,"ensureContact",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.za}});Object.defineProperty(exports,"ensureSession",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Aa}});Object.defineProperty(exports,"ensureUser",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Ba}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ca}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.ea}});Object.defineProperty(exports,"getAgentAdapter",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.W}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.G}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.L}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.C}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.F}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.M}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.x}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.A}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.D}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.N}});Object.defineProperty(exports,"getGatewayClientConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.I}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.J}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.K}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.O}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.E}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.B}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.H}});Object.defineProperty(exports,"getSupportedPlatforms",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Ya}});Object.defineProperty(exports,"hasAgentAdapter",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.X}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.y}});Object.defineProperty(exports,"listWeixinContacts",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Da}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.w}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.v}});Object.defineProperty(exports,"removeUser",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Ca}});Object.defineProperty(exports,"requireAgentAdapter",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Y}});Object.defineProperty(exports,"setAgentAdapter",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.V}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.u}});Object.defineProperty(exports,"weixinSetStateDir",{enumerable:true,get:function(){return chunkEKVLJAIP_cjs.Ga}});exports.handleWeixinCli=Zt;exports.initLog=un;
39
+ `);}catch(n){process.stderr.write(`ensure-user failed: ${n}
40
+ `),process.exit(1);}}async function er(e){let r=ce();e.length>0&&(process.stderr.write(`Unknown argument: ${e[0]}
41
+ `),process.stderr.write(`Usage: easbot weixin remove-user
42
+ `),process.exit(1));try{let t=await chunkRZS4QZWL_cjs.Ca(r,"weixin-main");process.stdout.write(`[weixin routing] removed user: ${r} contact=${t.removed.contact} session=${t.removed.session}
43
+ `);}catch(t){process.stderr.write(`remove-user failed: ${t}
44
+ `),process.exit(1);}}async function tr(e,r,t){let[n,...o]=e;switch(n){case "serve":r||(process.stderr.write(`[weixin] serve handler not available in this context.
45
+ `),process.exit(1)),await ie(t??"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();}}async function mn(e){let{Log:r}=await import('./chunks/log-JFEBRH2W.cjs'),t=false;await r.init({logDir:e.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:e.print??false,dev:e.dev??t,level:e.level??("INFO")});}Object.defineProperty(exports,"AgentRegistry",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Za}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.p}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.k}});Object.defineProperty(exports,"AgentSyncManager",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs._a}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.j}});Object.defineProperty(exports,"BaseChannelPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.qa}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.h}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.oa}});Object.defineProperty(exports,"ChannelPluginRegistry",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Xa}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.o}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.m}});Object.defineProperty(exports,"DEBUG_AGENT_FILTER",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.T}});Object.defineProperty(exports,"DEFAULT_AGENT_FILTER",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.S}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ha}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ja}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ia}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ga}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.fa}});Object.defineProperty(exports,"DiscordPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.sa}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.c}});Object.defineProperty(exports,"FeishuPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ua}});Object.defineProperty(exports,"GatewayClientConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.s}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.l}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.t}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.$a}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.r}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.na}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.i}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.n}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ka}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.la}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.g}});Object.defineProperty(exports,"NostrPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Va}});Object.defineProperty(exports,"SdkEventBridge",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.R}});Object.defineProperty(exports,"SdkEventBus",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Q}});Object.defineProperty(exports,"SdkEventType",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.P}});Object.defineProperty(exports,"SdkMessageCollector",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.U}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.q}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ma}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.f}});Object.defineProperty(exports,"SignalPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Ua}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.b}});Object.defineProperty(exports,"SlackPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ta}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.a}});Object.defineProperty(exports,"TelegramPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ra}});Object.defineProperty(exports,"WEIXIN_PLATFORM",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.wa}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.d}});Object.defineProperty(exports,"WeChatPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.va}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.e}});Object.defineProperty(exports,"WebChatPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Ta}});Object.defineProperty(exports,"WeixinPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Sa}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.z}});Object.defineProperty(exports,"convertToGatewayMessage",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ba}});Object.defineProperty(exports,"createChannelPlugin",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Wa}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.da}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.$}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.aa}});Object.defineProperty(exports,"ensureContact",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.za}});Object.defineProperty(exports,"ensureSession",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Aa}});Object.defineProperty(exports,"ensureUser",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Ba}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ca}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.ea}});Object.defineProperty(exports,"getAgentAdapter",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.W}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.G}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.L}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.C}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.F}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.M}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.x}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.A}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.D}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.N}});Object.defineProperty(exports,"getGatewayClientConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.I}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.J}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.K}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.O}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.E}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.B}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.H}});Object.defineProperty(exports,"getSupportedPlatforms",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Ya}});Object.defineProperty(exports,"hasAgentAdapter",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.X}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.y}});Object.defineProperty(exports,"listWeixinContacts",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Da}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.w}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.v}});Object.defineProperty(exports,"removeUser",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Ca}});Object.defineProperty(exports,"requireAgentAdapter",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Y}});Object.defineProperty(exports,"setAgentAdapter",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.V}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.u}});Object.defineProperty(exports,"weixinSetStateDir",{enumerable:true,get:function(){return chunkRZS4QZWL_cjs.Ga}});exports.handleWeixinCli=tr;exports.initLog=mn;
package/dist/index.mjs CHANGED
@@ -1,14 +1,14 @@
1
- import {b,c}from'./chunks/chunk-NXFFFRVB.mjs';import {Z,w as w$1,_,Ca,Da,Ba,xa,ya,Na,Ja,Ha,Ia,Ea,Qa,Oa,Ra,Fa,Ka,La,Ma,Pa}from'./chunks/chunk-VEA6YZG4.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-VEA6YZG4.mjs';import {a}from'./chunks/chunk-7OFQ65NG.mjs';import {a as a$1}from'./chunks/chunk-HAMGVOQD.mjs';import {Fetch}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 d=a.create({service:"gateway"}),w=class e extends Error{constructor(t,n,o){super(t);a$1(this,"type");a$1(this,"stage");a$1(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=o,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function se(e){let r=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return r.includes(t??"")}function Nt(){process.on("unhandledRejection",e=>{let r=e instanceof Error?e:new Error(String(e));se(r)||d.error("unhandled promise rejection",{error:r.message,stack:r.stack});}),process.on("uncaughtException",e=>{se(e)||(d.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}var K;(tr=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},r,t={server:null,config:null,initialized:false,status:"stopped"};async function n(l={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let g={directory:l.directory??".easbot",printLogs:l.printLogs??false,logLevel:l.logLevel??"INFO"};return e.directory=g.directory,e.initPromise=(async()=>{let T=Z();try{await a.init({logDir:T.Path.log,print:g.printLogs,level:g.logLevel});}catch(a){throw new w("Failed to initialize log infrastructure","log",a instanceof Error?a:void 0)}try{Nt();}catch(a){throw new w("Failed to install unhandled exception handlers","server",a instanceof Error?a:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),d.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{e.config=await w$1(g.directory);}catch(a){throw new w("Failed to load gateway configuration","config",a instanceof Error?a:void 0)}e.initialized=true,d.info("gateway runtime initialized",{directory:g.directory,logLevel:g.logLevel});})(),e.initPromise}tr.init=n;function o(){return e.initialized}tr.isInitialized=o;function c(){return r||(r=async()=>{if(!e.initialized)throw new w("Gateway not initialized. Call init() first.","server");let l=_(),g=await w$1(l.directory);return g.server?.enabled?(t={server:null,config:g,initialized:true,status:"stopped"},d.info("gateway initialized",{port:g.server?.port,hostname:g.server?.hostname}),t):(d.debug("gateway server disabled or not configured"),{server:null,config:g,initialized:true,status:"stopped"})}),r}function u(){return c()()}tr.state=u;async function C(){return (await u()).server}tr.get=C;async function i(){return (await u()).config?.server?.enabled??false}tr.isEnabled=i;async function f(){return (await u()).config}tr.config=f;function p(){return t.status}tr.getStatus=p;async function s(l){d.debug("Gateway.start: called"),e.initialized||await n();let g=await u();if(!(g.config?.server?.enabled??true))throw d.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){d.info("gateway server is already running");return}if(t.status==="starting"){d.info("gateway server is starting");return}t.status="starting";try{let a={...g.config?.server,...l};d.debug("gateway start: creating server with config",{port:a.port,hostname:a.hostname,path:a.path,https:a.https?.enabled});let I=await ce(a);t.server=I,t.status="running",t.error=void 0,d.info("gateway server started",{port:a.port,hostname:a.hostname});}catch(a){throw t.status="error",t.error=a instanceof Error?a.message:String(a),d.error("failed to start gateway server",{error:t.error}),a}}tr.start=s;async function m(){if(t.status==="stopped"){d.info("gateway server is already stopped");return}if(t.status==="stopping"){d.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,await a.close(),d.info("gateway server stopped");}catch(l){throw t.status="error",t.error=l instanceof Error?l.message:String(l),d.error("failed to stop gateway server",{error:t.error}),l}}tr.stop=m;async function h(l){d.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await m(),await s(l);}tr.restart=h;async function J(){let l=_(),g=await w$1(l.directory);return t.config=g,e.config=g,d.info("gateway config reloaded"),g}tr.reloadConfig=J;async function ce(l,g){d.debug("createGatewayServer: starting");let{GatewayServer:T}=await import('./chunks/server-OGBOUOJL.mjs'),a=new T(l),I=g?.startupTimeout??3e4;if(await(async()=>{let v=new Promise((x,le)=>{setTimeout(()=>{le(new Error(`Gateway server startup timeout after ${I}ms`));},I);});try{await Promise.race([a.start(),v]);}catch(x){d.error("gateway server start failed, attempting cleanup",{error:x instanceof Error?x.message:String(x)});try{await a.stop();}catch{}throw x}})(),g?.onStarted)try{await g.onStarted(a);}catch(v){d.warn("server started but onStarted callback failed",{error:v instanceof Error?v.message:String(v)});}return d.info("gateway server created and started",{port:l.port,hostname:l.hostname}),a}tr.createGatewayServer=ce;})(K||(K={}));async function Wt(e){let r=await toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${r}
2
- `);}async function D(e){let r=await fetch(`${e}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!r.ok)throw new Error(`Failed to get QR code: HTTP ${r.status}`);let t=await r.json();if(!t.qrcode)throw new Error("No qrcode in response");let n=t.qrcode_img_content||"";return n&&await Wt(n),{qrcodeUrl:n,qrcodeId:t.qrcode,message:"Scan the QR code with WeChat to connect."}}async function Y(e){let{qrcodeId:r,apiBaseUrl:t,timeoutMs:n=48e4,maxRetries:o=3}=e,c=Date.now()+n,u=r,C=0;for(;Date.now()<c;){try{let i=new AbortController,f=setTimeout(()=>i.abort(),6e4),p=await fetch(`${t}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(u)}`,{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
- `);break;case "expired":{if(C+=1,C>=o)return {connected:!1,message:"QR code expired after maximum retries."};process.stderr.write(`QR code expired, refreshing...
4
- `),u=(await D(t)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
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 Qt(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 jt(e){let r=new 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 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 t=>{let{name:n,arguments:o}=t.params,c=Ha();if(!c)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let u=c.baseUrl||Ea,C=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,h]of p.entries()){if(!existsSync(h))return {content:[{type:"text",text:`File not found: ${h}`}],isError:!0};await Pa({filePath:h,to:i,text:m===0?f:"",baseUrl:u,token:c.token,contextToken:s,cdnBaseUrl:C});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await Oa({to:i,text:f,baseUrl:u,token:c.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(u,c.token,i,f);return p.typing_ticket&&await La(u,c.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(e,r){r.enableConfigs(),r.initializeAnalyticsSink();let t=Ha();t||(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=jt(e),o=new StdioServerTransport;r.registerPermissionHandler(n,async s=>{let m=s.channel_context?.chat_id,h=m?{chatId:m,contextToken:Qa(m)}:b();if(!h){r.logForDebugging(`[Weixin MCP] No active chat available for permission request ${s.request_id}`);return}try{c(s,h.chatId,h.contextToken),await Oa({to:h.chatId,text:Qt(s),baseUrl:c$1,token:t.token,contextToken:h.contextToken||""});}catch(J){process.stderr.write(`[weixin] Failed to relay permission request ${s.request_id}: ${J}
7
- `);}}),await n.connect(o);let c$1=t.baseUrl||Ea,u=new AbortController,C=false,i=async()=>{C||(C=true,u.signal.aborted||u.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:c$1,cdnBaseUrl:Fa,token:t.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:u.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>","","User routing:",' easbot weixin ensure-user <userId> [--display-name "<name>"] [--username "<u>"] [--channel-id <id>]'," easbot weixin list-users"," easbot weixin remove-user <userId> [--channel-id <id>]"].join(`
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-LBRRMDDL.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-LBRRMDDL.mjs';import {a}from'./chunks/chunk-7OFQ65NG.mjs';import {a as a$1}from'./chunks/chunk-HAMGVOQD.mjs';import {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 l=a.create({service:"gateway"}),S=class e extends Error{constructor(t,n,o){super(t);a$1(this,"type");a$1(this,"stage");a$1(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=o,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function ie(e){let r=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return r.includes(t??"")}function Wt(){process.on("unhandledRejection",e=>{let r=e instanceof Error?e:new Error(String(e));ie(r)||l.error("unhandled promise rejection",{error:r.message,stack:r.stack});}),process.on("uncaughtException",e=>{ie(e)||(l.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}var K;(nr=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},r,t={server:null,config:null,initialized:false,status:"stopped"};async function n(c={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let g={directory:c.directory??".easbot",printLogs:c.printLogs??false,logLevel:c.logLevel??"INFO"};return e.directory=g.directory,e.initPromise=(async()=>{let T=Z();try{await a.init({logDir:T.Path.log,print:g.printLogs,level:g.logLevel});}catch(a){throw new S("Failed to initialize log infrastructure","log",a instanceof Error?a:void 0)}try{Wt();}catch(a){throw new S("Failed to install unhandled exception handlers","server",a instanceof Error?a:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),l.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{e.config=await w(g.directory);}catch(a){throw new S("Failed to load gateway configuration","config",a instanceof Error?a:void 0)}e.initialized=true,l.info("gateway runtime initialized",{directory:g.directory,logLevel:g.logLevel});})(),e.initPromise}nr.init=n;function o(){return e.initialized}nr.isInitialized=o;function u(){return r||(r=async()=>{if(!e.initialized)throw new S("Gateway not initialized. Call init() first.","server");let c=_(),g=await w(c.directory);return g.server?.enabled?(t={server:null,config:g,initialized:true,status:"stopped"},l.info("gateway initialized",{port:g.server?.port,hostname:g.server?.hostname}),t):(l.debug("gateway server disabled or not configured"),{server:null,config:g,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 t.status}nr.getStatus=p;async function s(c){l.debug("Gateway.start: called"),e.initialized||await n();let g=await d();if(!(g.config?.server?.enabled??true))throw l.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){l.info("gateway server is already running");return}if(t.status==="starting"){l.info("gateway server is starting");return}t.status="starting";try{let a={...g.config?.server,...c};l.debug("gateway start: creating server with config",{port:a.port,hostname:a.hostname,path:a.path,https:a.https?.enabled});let I=await le(a);t.server=I,t.status="running",t.error=void 0,l.info("gateway server started",{port:a.port,hostname:a.hostname});}catch(a){throw t.status="error",t.error=a instanceof Error?a.message:String(a),l.error("failed to start gateway server",{error:t.error}),a}}nr.start=s;async function m(){if(t.status==="stopped"){l.info("gateway server is already stopped");return}if(t.status==="stopping"){l.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,await a.close(),l.info("gateway server stopped");}catch(c){throw t.status="error",t.error=c instanceof Error?c.message:String(c),l.error("failed to stop gateway server",{error:t.error}),c}}nr.stop=m;async function h(c){l.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await m(),await s(c);}nr.restart=h;async function X(){let c=_(),g=await w(c.directory);return t.config=g,e.config=g,l.info("gateway config reloaded"),g}nr.reloadConfig=X;async function le(c,g){l.debug("createGatewayServer: starting");let{GatewayServer:T}=await import('./chunks/server-BJCPH37W.mjs'),a=new T(c),I=g?.startupTimeout??3e4;if(await(async()=>{let v=new Promise((x,de)=>{setTimeout(()=>{de(new Error(`Gateway server startup timeout after ${I}ms`));},I);});try{await Promise.race([a.start(),v]);}catch(x){l.error("gateway server start failed, attempting cleanup",{error:x instanceof Error?x.message:String(x)});try{await a.stop();}catch{}throw x}})(),g?.onStarted)try{await g.onStarted(a);}catch(v){l.warn("server started but onStarted callback failed",{error:v instanceof Error?v.message:String(v)});}return l.info("gateway server created and started",{port:c.port,hostname:c.hostname}),a}nr.createGatewayServer=le;})(K||(K={}));async function Ot(e){let r=await toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${r}
2
+ `);}async function D(e){let r=await fetch(`${e}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!r.ok)throw new Error(`Failed to get QR code: HTTP ${r.status}`);let t=await r.json();if(!t.qrcode)throw new Error("No qrcode in response");let n=t.qrcode_img_content||"";return n&&await Ot(n),{qrcodeUrl:n,qrcodeId:t.qrcode,message:"Scan the QR code with WeChat to connect."}}async function Y(e){let{qrcodeId:r,apiBaseUrl:t,timeoutMs:n=48e4,maxRetries:o=3}=e,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(`${t}/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
+ `);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
+ `),d=(await D(t)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
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(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 Kt(e){let r=new 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 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 t=>{let{name:n,arguments:o}=t.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,h]of p.entries()){if(!existsSync(h))return {content:[{type:"text",text:`File not found: ${h}`}],isError:!0};await Pa({filePath:h,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(e,r){r.enableConfigs(),r.initializeAnalyticsSink();let t=Ha();t||(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(e),o=new StdioServerTransport;r.registerPermissionHandler(n,async s=>{let m=s.channel_context?.chat_id,h=m?{chatId:m,contextToken:Qa(m)}:b();if(!h){r.logForDebugging(`[Weixin MCP] No active chat available for permission request ${s.request_id}`);return}try{c(s,h.chatId,h.contextToken),await Oa({to:h.chatId,text:Vt(s),baseUrl:u,token:t.token,contextToken:h.contextToken||""});}catch(X){process.stderr.write(`[weixin] Failed to relay permission request ${s.request_id}: ${X}
7
+ `);}}),await n.connect(o);let u=t.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:t.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(`
9
9
  `)+`
10
- `);}async function Vt(e=false){if(e){Ja(),process.stdout.write(`WeChat account cleared.
11
- `);return}let r=Ha();if(r){process.stdout.write(["Already connected:",` User ID: ${r.userId||"unknown"}`,` Connected since: ${r.savedAt}`,"","Run `easbot weixin login clear` to disconnect."].join(`
10
+ `);}async function Yt(e=false){if(e){Ja(),process.stdout.write(`WeChat account cleared.
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(`
12
12
  `)+`
13
13
  `);return}process.stdout.write(`Starting WeChat QR login...
14
14
 
@@ -19,19 +19,27 @@ ${t.qrcodeUrl||""}
19
19
  `);let n=await Y({qrcodeId:t.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 Kt(e){(e[0]!=="pair"||!e[1])&&(ae(),process.exit(1));let r=Na(e[1]);r||(process.stderr.write(`Invalid or expired pairing code.
22
+ `);}function Jt(e){(e[0]!=="pair"||!e[1])&&(ce(),process.exit(1));let r=Na(e[1]);r||(process.stderr.write(`Invalid or expired pairing code.
23
23
  `),process.exit(1)),process.stdout.write(`Paired successfully: ${r}
24
- `);}function Yt(e){if(e.length===0)return 'Usage: easbot weixin ensure-user <userId> [--display-name "<name>"] [--username "<u>"] [--channel-id <id>]';let r=e[0];if(!r)return "userId is required";let t={userId:r};for(let n=1;n<e.length;n++){let o=e[n];if(o==="--display-name"||o==="-d"){let c=e[++n];if(!c)return "--display-name requires a value";t.displayName=c;}else if(o==="--username"||o==="-u"){let c=e[++n];if(!c)return "--username requires a value";t.username=c;}else if(o==="--channel-id"||o==="-c"){let c=e[++n];if(!c)return "--channel-id requires a value";t.channelId=c;}}return t}function Jt(e){let r=Yt(e);typeof r=="string"&&(process.stderr.write(`${r}
25
- `),process.exit(1)),Ba(r).then(t=>{let{contact:n,session:o,created:c}=t,u=c.contact&&c.session?"\u5DF2\u521B\u5EFA":"\u5DF2\u5B58\u5728\uFF08\u5DF2\u66F4\u65B0\uFF09";process.stdout.write([`[weixin routing] ${u} user: ${r.userId}`,` contact.uid: ${n.uid}`,` contact.path: ${xa()}/contacts/${n.platform}/${n.stableId}.json`,` session.id: ${o.id}`,` session.path: ${ya()}/sessions.json`,` profile: ${JSON.stringify(n.profile)}`].join(`
24
+ `);}function Xt(e,r){let t={userId:r,channelId:"weixin-main"};for(let n=0;n<e.length;n++){let o=e[n];if(o==="--display-name"||o==="-d"){let u=e[++n];if(!u)return "--display-name requires a value";t.displayName=u;}else return `Unknown argument: ${o}`}return t}function ge(){let e=Ha();return e?.userId||(process.stderr.write("No weixin account logged in. Run `easbot weixin login` first.\n"),process.exit(1)),e.userId}async function Zt(){try{let e=Ha();if(!e){process.stdout.write(`No weixin account logged in.
25
+ `),process.stdout.write("Run `easbot weixin login` to bind your WeChat via iLink.\n");return}process.stdout.write(`weixin current user:
26
+ `),process.stdout.write(` userId: ${e.userId??"(unknown)"}
27
+ `),process.stdout.write(` baseUrl: ${e.baseUrl}
28
+ `),process.stdout.write(` savedAt: ${formatLocalISO(new Date(e.savedAt))}
29
+ `);let t=(await Da()).find(n=>n.stableId===e.userId);t?(process.stdout.write(` contact: registered
30
+ `),process.stdout.write(` uid: ${t.uid}
31
+ `),t.profile.displayName&&process.stdout.write(` display: ${t.profile.displayName}
32
+ `),t.profile.username&&process.stdout.write(` username: ${t.profile.username}
33
+ `),process.stdout.write(` lastSeen: ${formatLocalISO(new Date(t.lastSeenAt))}
34
+ `)):(process.stdout.write(` contact: not registered
35
+ `),process.stdout.write(" hint: run `easbot weixin ensure-user` to register\n"));}catch(e){process.stderr.write(`user failed: ${e}
36
+ `),process.exit(1);}}async function er(e){let r=ge(),t=Xt(e,r);typeof t=="string"&&(process.stderr.write(`${t}
37
+ `),process.exit(1));try{let n=await Ba(t),{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(`
26
38
  `)+`
27
- `);}).catch(t=>{process.stderr.write(`ensure-user failed: ${t}
28
- `),process.exit(1);});}function Xt(){Da().then(e=>{if(e.length===0){process.stdout.write(`No weixin users registered.
29
- `),process.stdout.write("Use `easbot weixin ensure-user <userId>` to add one.\n");return}process.stdout.write(`weixin users (${e.length}):
30
- `);for(let r of e){let t=r.profile.displayName??r.profile.username??"(no name)";process.stdout.write(` - ${r.stableId} ${t} lastSeen=${new Date(r.lastSeenAt).toISOString()}
31
- `);}}).catch(e=>{process.stderr.write(`list-users failed: ${e}
32
- `),process.exit(1);});}function Zt(e){e.length===0&&(process.stderr.write(`Usage: easbot weixin remove-user <userId> [--channel-id <id>]
33
- `),process.exit(1));let r=e[0];r||(process.stderr.write(`userId is required
34
- `),process.exit(1));let t="weixin-main";for(let n=1;n<e.length;n++)(e[n]==="--channel-id"||e[n]==="-c")&&(t=e[++n]??t);Ca(r,t).then(n=>{process.stdout.write(`[weixin routing] removed user: ${r} contact=${n.removed.contact} session=${n.removed.session}
35
- `);}).catch(n=>{process.stderr.write(`remove-user failed: ${n}
36
- `),process.exit(1);});}async function er(e,r,t){let[n,...o]=e;switch(n){case "serve":r||(process.stderr.write(`[weixin] serve handler not available in this context.
37
- `),process.exit(1)),await ie(t??"0.0.0",r);return;case "login":await Vt(o[0]==="clear");return;case "access":Kt(o);return;case "ensure-user":Jt(o);return;case "list-users":Xt();return;case "remove-user":Zt(o);return;default:ae();}}async function pn(e){let{Log:r}=await import('./chunks/log-MIT4H7S5.mjs'),t=false;await r.init({logDir:e.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:e.print??false,dev:e.dev??t,level:e.level??("INFO")});}export{K as Gateway,er as handleWeixinCli,pn as initLog};
39
+ `);}catch(n){process.stderr.write(`ensure-user failed: ${n}
40
+ `),process.exit(1);}}async function tr(e){let r=ge();e.length>0&&(process.stderr.write(`Unknown argument: ${e[0]}
41
+ `),process.stderr.write(`Usage: easbot weixin remove-user
42
+ `),process.exit(1));try{let t=await Ca(r,"weixin-main");process.stdout.write(`[weixin routing] removed user: ${r} contact=${t.removed.contact} session=${t.removed.session}
43
+ `);}catch(t){process.stderr.write(`remove-user failed: ${t}
44
+ `),process.exit(1);}}async function rr(e,r,t){let[n,...o]=e;switch(n){case "serve":r||(process.stderr.write(`[weixin] serve handler not available in this context.
45
+ `),process.exit(1)),await ae(t??"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();}}async function yn(e){let{Log:r}=await import('./chunks/log-MIT4H7S5.mjs'),t=false;await r.init({logDir:e.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:e.print??false,dev:e.dev??t,level:e.level??("INFO")});}export{K as Gateway,rr as handleWeixinCli,yn as initLog};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/gateway",
3
- "version": "0.2.47",
3
+ "version": "0.2.49",
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/sdk": "0.2.47",
73
- "@easbot/plugin": "0.2.47",
74
- "@easbot/types": "0.2.47",
75
- "@easbot/utils": "0.2.47"
72
+ "@easbot/plugin": "0.2.49",
73
+ "@easbot/sdk": "0.2.49",
74
+ "@easbot/types": "0.2.49",
75
+ "@easbot/utils": "0.2.49"
76
76
  },
77
77
  "devDependencies": {
78
78
  "@types/qrcode": "^1.5.6",
@@ -1 +0,0 @@
1
- export{oa as ChannelPluginLoader,$a as GatewayServer,pa as GatewayWebSocketServer}from'./chunk-VEA6YZG4.mjs';import'./chunk-7OFQ65NG.mjs';import'./chunk-HAMGVOQD.mjs';