@easbot/gateway 0.3.4 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,45 +1,49 @@
1
- 'use strict';var chunkTQ74GHLT_cjs=require('./chunks/chunk-TQ74GHLT.cjs'),chunkCPQSQ7FU_cjs=require('./chunks/chunk-CPQSQ7FU.cjs'),chunk6C5TBG7Z_cjs=require('./chunks/chunk-6C5TBG7Z.cjs'),utils=require('@easbot/utils'),qrcode=require('qrcode'),fs=require('fs'),index_js=require('@modelcontextprotocol/sdk/server/index.js'),stdio_js=require('@modelcontextprotocol/sdk/server/stdio.js'),types_js=require('@modelcontextprotocol/sdk/types.js');var g=utils.Log.create({service:"gateway"}),P=class t extends Error{constructor(e,n,o){super(e);chunk6C5TBG7Z_cjs.a(this,"type");chunk6C5TBG7Z_cjs.a(this,"stage");chunk6C5TBG7Z_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=o,Error.captureStackTrace&&Error.captureStackTrace(this,t);}};function oe(t){let r=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],e=t.code;return r.includes(e??"")}function Nt(){process.on("unhandledRejection",t=>{let r=t instanceof Error?t:new Error(String(t));oe(r)||g.error("unhandled promise rejection",{error:r.message,stack:r.stack});}),process.on("uncaughtException",t=>{oe(t)||(g.error("uncaught exception",{error:t.message,stack:t.stack}),process.exit(1));});}exports.Gateway=void 0;(rr=>{let t={initialized:false,initPromise:null,directory:".easbot",config:null},r,e={server:null,config:null,initialized:false,status:"stopped"};async function n(a={}){if(t.initialized)return;if(t.initPromise)return t.initPromise;let l={directory:a.directory??".easbot",printLogs:a.printLogs??false,logLevel:a.logLevel??"INFO"};return t.directory=l.directory,t.initPromise=(async()=>{chunkCPQSQ7FU_cjs.Z();try{Nt();}catch(c){throw new P("Failed to install unhandled exception handlers","server",c instanceof Error?c:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),g.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{t.config=await chunkCPQSQ7FU_cjs.w(l.directory);}catch(c){throw new P("Failed to load gateway configuration","config",c instanceof Error?c:void 0)}t.initialized=true,g.info("gateway runtime initialized",{directory:l.directory,logLevel:l.logLevel});})(),t.initPromise}rr.init=n;function o(){return t.initialized}rr.isInitialized=o;function u(){return r||(r=async()=>{if(!t.initialized)throw new P("Gateway not initialized. Call init() first.","server");let a=chunkCPQSQ7FU_cjs._(),l=await chunkCPQSQ7FU_cjs.w(a.directory);return l.server?.enabled?(e={server:null,config:l,initialized:true,status:"stopped"},g.info("gateway initialized",{port:l.server?.port,hostname:l.server?.hostname}),e):(g.debug("gateway server disabled or not configured"),{server:null,config:l,initialized:true,status:"stopped"})}),r}function d(){return u()()}rr.state=d;async function y(){return (await d()).server}rr.get=y;async function i(){return (await d()).config?.server?.enabled??false}rr.isEnabled=i;async function f(){return (await d()).config}rr.config=f;function p(){return e.status}rr.getStatus=p;async function s(a){g.debug("Gateway.start: called"),t.initialized||await n();let l=await d();if(!(l.config?.server?.enabled??true))throw g.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(e.status==="running"){g.info("gateway server is already running");return}if(e.status==="starting"){g.info("gateway server is starting");return}e.status="starting";try{let c={...l.config?.server,...a};g.debug("gateway start: creating server with config",{port:c.port,hostname:c.hostname,path:c.path,https:c.https?.enabled});let E=await ce(c);e.server=E,e.status="running",e.error=void 0,g.info("gateway server started",{port:c.port,hostname:c.hostname});}catch(c){throw e.status="error",e.error=c instanceof Error?c.message:String(c),g.error("failed to start gateway server",{error:e.error}),c}}rr.start=s;async function m(){if(e.status==="stopped"){g.info("gateway server is already stopped");return}if(e.status==="stopping"){g.info("gateway server is stopping");return}e.status="stopping";try{e.server&&await e.server.stop(),e.server=null,e.status="stopped",e.error=void 0,g.info("gateway server stopped");}catch(a){throw e.status="error",e.error=a instanceof Error?a.message:String(a),g.error("failed to stop gateway server",{error:e.error}),a}}rr.stop=m;async function C(a){g.info("restarting gateway server"),(e.status==="running"||e.status==="starting")&&await m(),await s(a);}rr.restart=C;async function Y(){let a=chunkCPQSQ7FU_cjs._(),l=await chunkCPQSQ7FU_cjs.w(a.directory);return e.config=l,t.config=l,g.info("gateway config reloaded"),l}rr.reloadConfig=Y;async function ce(a,l){g.debug("createGatewayServer: starting");let{GatewayServer:G}=await import('./chunks/server-7LXANJ4O.cjs'),c=new G(a),E=l?.startupTimeout??3e4;if(await(async()=>{let S=new Promise((x,ge)=>{setTimeout(()=>{ge(new Error(`Gateway server startup timeout after ${E}ms`));},E);});try{await Promise.race([c.start(),S]);}catch(x){g.error("gateway server start failed, attempting cleanup",{error:x instanceof Error?x.message:String(x)});try{await c.stop();}catch{}throw x}})(),l?.onStarted)try{await l.onStarted(c);}catch(S){g.warn("server started but onStarted callback failed",{error:S instanceof Error?S.message:String(S)});}return g.info("gateway server created and started",{port:a.port,hostname:a.hostname}),c}rr.createGatewayServer=ce;})(exports.Gateway||(exports.Gateway={}));async function qt(t){let r=await qrcode.toString(t,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${r}
2
- `);}async function _(t){let r=await fetch(`${t}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!r.ok)throw new Error(`Failed to get QR code: HTTP ${r.status}`);let e=await r.json();if(!e.qrcode)throw new Error("No qrcode in response");let n=e.qrcode_img_content||"";return n&&await qt(n),{qrcodeUrl:n,qrcodeId:e.qrcode,message:"Scan the QR code with WeChat to connect."}}async function V(t){let{qrcodeId:r,apiBaseUrl:e,timeoutMs:n=48e4,maxRetries:o=3}=t,u=Date.now()+n,d=r,y=0;for(;Date.now()<u;){try{let i=new AbortController,f=setTimeout(()=>i.abort(),6e4),p=await fetch(`${e}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(d)}`,{headers:{"iLink-App-ClientVersion":"1"},signal:i.signal});if(clearTimeout(f),!p.ok)throw new Error(`HTTP ${p.status}`);let s=await p.json();switch(s.status){case "confirmed":return {connected:!0,token:s.bot_token,accountId:s.ilink_bot_id,baseUrl:s.baseurl,userId:s.ilink_user_id,message:"Connected to WeChat successfully!"};case "scaned":process.stderr.write(`QR code scanned, waiting for confirmation...
3
- `);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 _(e)).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(t){return ["Claude Code needs your approval.","",`Tool: ${t.tool_name}`,`Reason: ${t.description}`,`Input: ${t.input_preview}`,"",`Reply with: yes ${t.request_id}`,`Or deny with: no ${t.request_id}`].join(`
6
- `)}function Vt(t){let r=new index_js.Server({name:"weixin",version:t},{capabilities:{experimental:{"claude/channel":{},"claude/channel/permission":{}},tools:{}},instructions:'Messages from WeChat arrive as <channel source="plugin:weixin:weixin" chat_id="..." sender_id="...">. Reply using the reply tool with the chat_id from the channel tag. Use absolute paths for file attachments.'});return r.setRequestHandler(types_js.ListToolsRequestSchema,async()=>({tools:[{name:"reply",description:"Reply to a WeChat message. Pass the chat_id from the channel tag.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The chat_id from the channel notification"},text:{type:"string",description:"The reply text"},files:{type:"array",items:{type:"string"},description:"Optional absolute file paths to attach"}},required:["chat_id","text"]}},{name:"send_typing",description:"Send a typing indicator to a WeChat user.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The chat_id (user ID)"}},required:["chat_id"]}}]})),r.setRequestHandler(types_js.CallToolRequestSchema,async e=>{let{name:n,arguments:o}=e.params,u=chunkCPQSQ7FU_cjs.Ha();if(!u)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let d=u.baseUrl||chunkCPQSQ7FU_cjs.Ea,y=chunkCPQSQ7FU_cjs.Fa;switch(n){case "reply":{let i=typeof o?.chat_id=="string"?o.chat_id:"",f=typeof o?.text=="string"?o.text:"",p=Array.isArray(o?.files)?o.files.filter(m=>typeof m=="string"):void 0;if(!i||!f)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let s=chunkCPQSQ7FU_cjs.Qa(i)||"";try{if(p&&p.length>0){for(let[m,C]of p.entries()){if(!fs.existsSync(C))return {content:[{type:"text",text:`File not found: ${C}`}],isError:!0};await chunkCPQSQ7FU_cjs.Pa({filePath:C,to:i,text:m===0?f:"",baseUrl:d,token:u.token,contextToken:s,cdnBaseUrl:y});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await chunkCPQSQ7FU_cjs.Oa({to:i,text:f,baseUrl:d,token:u.token,contextToken:s}),{content:[{type:"text",text:"Message sent."}]}}catch(m){return {content:[{type:"text",text:`Failed to send: ${m}`}],isError:true}}}case "send_typing":{let i=typeof o?.chat_id=="string"?o.chat_id:"";if(!i)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let f=chunkCPQSQ7FU_cjs.Qa(i),p=await chunkCPQSQ7FU_cjs.Ka(d,u.token,i,f);return p.typing_ticket&&await chunkCPQSQ7FU_cjs.La(d,u.token,{ilink_user_id:i,typing_ticket:p.typing_ticket,status:chunkCPQSQ7FU_cjs.Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(f){return {content:[{type:"text",text:`Failed to send typing: ${f}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${n}`}],isError:true}}}),r}async function se(t,r){r.enableConfigs(),r.initializeAnalyticsSink();let e=chunkCPQSQ7FU_cjs.Ha();e||(process.stderr.write("[weixin] No account configured. Run `easbot weixin login` to connect your WeChat account.\n"),await Promise.all([r.shutdown1PEventLogging(),r.shutdownDatadog()]),process.exit(1));let n=Vt(t),o=new stdio_js.StdioServerTransport;r.registerPermissionHandler(n,async s=>{let m=s.channel_context?.chat_id,C=m?{chatId:m,contextToken:chunkCPQSQ7FU_cjs.Qa(m)}:chunkTQ74GHLT_cjs.b();if(!C){r.logForDebugging(`[Weixin MCP] No active chat available for permission request ${s.request_id}`);return}try{chunkTQ74GHLT_cjs.c(s,C.chatId,C.contextToken),await chunkCPQSQ7FU_cjs.Oa({to:C.chatId,text:jt(s),baseUrl:u,token:e.token,contextToken:C.contextToken||""});}catch(Y){process.stderr.write(`[weixin] Failed to relay permission request ${s.request_id}: ${Y}
7
- `);}}),await n.connect(o);let u=e.baseUrl||chunkCPQSQ7FU_cjs.Ea,d=new AbortController,y=false,i=async()=>{y||(y=true,d.signal.aborted||d.abort(),await Promise.all([r.shutdown1PEventLogging(),r.shutdownDatadog()]),process.exit(0));};process.stdin.on("end",()=>{i();}),process.stdin.on("error",()=>{i();}),process.on("SIGINT",()=>{i();}),process.on("SIGTERM",()=>{i();}),process.on("SIGHUP",()=>{i();});let f=process.ppid,p=setInterval(()=>{try{process.kill(f,0);}catch{process.stderr.write(`[weixin] Parent process exited, shutting down...
8
- `),clearInterval(p),i();}},5e3);r.logForDebugging("[Weixin MCP] Starting poll loop"),await chunkCPQSQ7FU_cjs.Ra({baseUrl:u,cdnBaseUrl:chunkCPQSQ7FU_cjs.Fa,token:e.token,onMessage:async s=>{await n.notification({method:"notifications/claude/channel",params:{content:s.text,meta:{chat_id:s.fromUserId,sender_id:s.fromUserId,message_id:s.messageId,...s.attachmentPath&&{attachment_path:s.attachmentPath},...s.attachmentType&&{attachment_type:s.attachmentType}}}});},onPermissionResponse:async s=>{await n.notification({method:"notifications/claude/channel/permission",params:{request_id:s.requestId,behavior:s.behavior}});},abortSignal:d.signal}),clearInterval(p),await i();}function ie(){process.stdout.write(["Usage:"," easbot weixin serve"," easbot weixin login"," easbot weixin login clear"," easbot weixin access pair <code>","","Current user (read from account.json):"," easbot weixin user",' easbot weixin ensure-user [--display-name "<name>"]'," easbot weixin remove-user"].join(`
1
+ 'use strict';var chunkTQ74GHLT_cjs=require('./chunks/chunk-TQ74GHLT.cjs'),chunkCPQSQ7FU_cjs=require('./chunks/chunk-CPQSQ7FU.cjs'),chunk6C5TBG7Z_cjs=require('./chunks/chunk-6C5TBG7Z.cjs'),utils=require('@easbot/utils'),qrcode=require('qrcode'),fs=require('fs'),index_js=require('@modelcontextprotocol/sdk/server/index.js'),stdio_js=require('@modelcontextprotocol/sdk/server/stdio.js'),types_js=require('@modelcontextprotocol/sdk/types.js');var u=utils.Log.create({service:"gateway"}),T=class e extends Error{constructor(t,r,i){super(t);chunk6C5TBG7Z_cjs.a(this,"type");chunk6C5TBG7Z_cjs.a(this,"stage");chunk6C5TBG7Z_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function de(e){let n=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return n.includes(t??"")}function Jt(){process.on("unhandledRejection",e=>{let n=e instanceof Error?e:new Error(String(e));de(n)||u.error("unhandled promise rejection",{error:n.message,stack:n.stack});}),process.on("uncaughtException",e=>{de(e)||(u.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}exports.Gateway=void 0;(_n=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},n,t={server:null,config:null,initialized:false,status:"stopped"};async function r(g={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let p={directory:g.directory??".easbot",printLogs:g.printLogs??false,logLevel:g.logLevel??"INFO"};return e.directory=p.directory,e.initPromise=(async()=>{chunkCPQSQ7FU_cjs.Z();try{Jt();}catch(d){throw new T("Failed to install unhandled exception handlers","server",d instanceof Error?d:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),u.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{e.config=await chunkCPQSQ7FU_cjs.w(p.directory);}catch(d){throw new T("Failed to load gateway configuration","config",d instanceof Error?d:void 0)}e.initialized=true,u.info("gateway runtime initialized",{directory:p.directory,logLevel:p.logLevel});})(),e.initPromise}_n.init=r;function i(){return e.initialized}_n.isInitialized=i;function a(){return n||(n=async()=>{if(!e.initialized)throw new T("Gateway not initialized. Call init() first.","server");let g=chunkCPQSQ7FU_cjs._(),p=await chunkCPQSQ7FU_cjs.w(g.directory);return p.server?.enabled?(t={server:null,config:p,initialized:true,status:"stopped"},u.info("gateway initialized",{port:p.server?.port,hostname:p.server?.hostname}),t):(u.debug("gateway server disabled or not configured"),{server:null,config:p,initialized:true,status:"stopped"})}),n}function o(){return a()()}_n.state=o;async function f(){return (await o()).server}_n.get=f;async function l(){return (await o()).config?.server?.enabled??false}_n.isEnabled=l;async function w(){return (await o()).config}_n.config=w;function m(){return t.status}_n.getStatus=m;async function c(g){u.debug("Gateway.start: called"),e.initialized||await r();let p=await o();if(!(p.config?.server?.enabled??true))throw u.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){u.info("gateway server is already running");return}if(t.status==="starting"){u.info("gateway server is starting");return}t.status="starting";try{let d={...p.config?.server,...g};u.debug("gateway start: creating server with config",{port:d.port,hostname:d.hostname,path:d.path,https:d.https?.enabled});let E=await Ce(d);t.server=E,t.status="running",t.error=void 0,u.info("gateway server started",{port:d.port,hostname:d.hostname});}catch(d){throw t.status="error",t.error=d instanceof Error?d.message:String(d),u.error("failed to start gateway server",{error:t.error}),d}}_n.start=c;async function x(){if(t.status==="stopped"){u.info("gateway server is already stopped");return}if(t.status==="stopping"){u.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,u.info("gateway server stopped");}catch(g){throw t.status="error",t.error=g instanceof Error?g.message:String(g),u.error("failed to stop gateway server",{error:t.error}),g}}_n.stop=x;async function h(g){u.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await x(),await c(g);}_n.restart=h;async function re(){let g=chunkCPQSQ7FU_cjs._(),p=await chunkCPQSQ7FU_cjs.w(g.directory);return t.config=p,e.config=p,u.info("gateway config reloaded"),p}_n.reloadConfig=re;async function Ce(g,p){u.debug("createGatewayServer: starting");let{GatewayServer:q}=await import('./chunks/server-7LXANJ4O.cjs'),d=new q(g),E=p?.startupTimeout??3e4;if(await(async()=>{let k=new Promise((b,Se)=>{setTimeout(()=>{Se(new Error(`Gateway server startup timeout after ${E}ms`));},E);});try{await Promise.race([d.start(),k]);}catch(b){u.error("gateway server start failed, attempting cleanup",{error:b instanceof Error?b.message:String(b)});try{await d.stop();}catch{}throw b}})(),p?.onStarted)try{await p.onStarted(d);}catch(k){u.warn("server started but onStarted callback failed",{error:k instanceof Error?k.message:String(k)});}return u.info("gateway server created and started",{port:g.port,hostname:g.hostname}),d}_n.createGatewayServer=Ce;})(exports.Gateway||(exports.Gateway={}));async function Zt(e){let n=await qrcode.toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${n}
2
+ `);}async function D(e){let n=await fetch(`${e}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!n.ok)throw new Error(`Failed to get QR code: HTTP ${n.status}`);let t=await n.json();if(!t.qrcode)throw new Error("No qrcode in response");let r=t.qrcode_img_content||"";return r&&await Zt(r),{qrcodeUrl:r,qrcodeId:t.qrcode,message:"Scan the QR code with WeChat to connect."}}async function Z(e){let{qrcodeId:n,apiBaseUrl:t,timeoutMs:r=48e4,maxRetries:i=3}=e,a=Date.now()+r,o=n,f=0;for(;Date.now()<a;){try{let l=new AbortController,w=setTimeout(()=>l.abort(),6e4),m=await fetch(`${t}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(o)}`,{headers:{"iLink-App-ClientVersion":"1"},signal:l.signal});if(clearTimeout(w),!m.ok)throw new Error(`HTTP ${m.status}`);let c=await m.json();switch(c.status){case "confirmed":return {connected:!0,token:c.bot_token,accountId:c.ilink_bot_id,baseUrl:c.baseurl,userId:c.ilink_user_id,message:"Connected to WeChat successfully!"};case "scaned":process.stderr.write(`QR code scanned, waiting for confirmation...
3
+ `);break;case "expired":{if(f+=1,f>=i)return {connected:!1,message:"QR code expired after maximum retries."};process.stderr.write(`QR code expired, refreshing...
4
+ `),o=(await D(t)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
5
+ `);break;default:break}}catch(l){if(l instanceof Error&&l.name==="AbortError")continue;throw l}await new Promise(l=>setTimeout(l,1e3));}return {connected:false,message:"Login timed out."}}function on(e){return ["Claude Code needs your approval.","",`Tool: ${e.tool_name}`,`Reason: ${e.description}`,`Input: ${e.input_preview}`,"",`Reply with: yes ${e.request_id}`,`Or deny with: no ${e.request_id}`].join(`
6
+ `)}function an(e){let n=new index_js.Server({name:"weixin",version:e},{capabilities:{experimental:{"claude/channel":{},"claude/channel/permission":{}},tools:{}},instructions:'Messages from WeChat arrive as <channel source="plugin:weixin:weixin" chat_id="..." sender_id="...">. Reply using the reply tool with the chat_id from the channel tag. Use absolute paths for file attachments.'});return n.setRequestHandler(types_js.ListToolsRequestSchema,async()=>({tools:[{name:"reply",description:"Reply to a WeChat message. Pass the chat_id from the channel tag.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The chat_id from the channel notification"},text:{type:"string",description:"The reply text"},files:{type:"array",items:{type:"string"},description:"Optional absolute file paths to attach"}},required:["chat_id","text"]}},{name:"send_typing",description:"Send a typing indicator to a WeChat user.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The chat_id (user ID)"}},required:["chat_id"]}}]})),n.setRequestHandler(types_js.CallToolRequestSchema,async t=>{let{name:r,arguments:i}=t.params,a=chunkCPQSQ7FU_cjs.Ha();if(!a)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let o=a.baseUrl||chunkCPQSQ7FU_cjs.Ea,f=chunkCPQSQ7FU_cjs.Fa;switch(r){case "reply":{let l=typeof i?.chat_id=="string"?i.chat_id:"",w=typeof i?.text=="string"?i.text:"",m=Array.isArray(i?.files)?i.files.filter(x=>typeof x=="string"):void 0;if(!l||!w)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let c=chunkCPQSQ7FU_cjs.Qa(l)||"";try{if(m&&m.length>0){for(let[x,h]of m.entries()){if(!fs.existsSync(h))return {content:[{type:"text",text:`File not found: ${h}`}],isError:!0};await chunkCPQSQ7FU_cjs.Pa({filePath:h,to:l,text:x===0?w:"",baseUrl:o,token:a.token,contextToken:c,cdnBaseUrl:f});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await chunkCPQSQ7FU_cjs.Oa({to:l,text:w,baseUrl:o,token:a.token,contextToken:c}),{content:[{type:"text",text:"Message sent."}]}}catch(x){return {content:[{type:"text",text:`Failed to send: ${x}`}],isError:true}}}case "send_typing":{let l=typeof i?.chat_id=="string"?i.chat_id:"";if(!l)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let w=chunkCPQSQ7FU_cjs.Qa(l),m=await chunkCPQSQ7FU_cjs.Ka(o,a.token,l,w);return m.typing_ticket&&await chunkCPQSQ7FU_cjs.La(o,a.token,{ilink_user_id:l,typing_ticket:m.typing_ticket,status:chunkCPQSQ7FU_cjs.Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(w){return {content:[{type:"text",text:`Failed to send typing: ${w}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${r}`}],isError:true}}}),n}async function ue(e,n){n.enableConfigs(),n.initializeAnalyticsSink();let t=chunkCPQSQ7FU_cjs.Ha();t||(process.stderr.write("[weixin] No account configured. Run `easbot weixin login` to connect your WeChat account.\n"),await Promise.all([n.shutdown1PEventLogging(),n.shutdownDatadog()]),process.exit(1));let r=an(e),i=new stdio_js.StdioServerTransport;n.registerPermissionHandler(r,async c=>{let x=c.channel_context?.chat_id,h=x?{chatId:x,contextToken:chunkCPQSQ7FU_cjs.Qa(x)}:chunkTQ74GHLT_cjs.b();if(!h){n.logForDebugging(`[Weixin MCP] No active chat available for permission request ${c.request_id}`);return}try{chunkTQ74GHLT_cjs.c(c,h.chatId,h.contextToken),await chunkCPQSQ7FU_cjs.Oa({to:h.chatId,text:on(c),baseUrl:a,token:t.token,contextToken:h.contextToken||""});}catch(re){process.stderr.write(`[weixin] Failed to relay permission request ${c.request_id}: ${re}
7
+ `);}}),await r.connect(i);let a=t.baseUrl||chunkCPQSQ7FU_cjs.Ea,o=new AbortController,f=false,l=async()=>{f||(f=true,o.signal.aborted||o.abort(),await Promise.all([n.shutdown1PEventLogging(),n.shutdownDatadog()]),process.exit(0));};process.stdin.on("end",()=>{l();}),process.stdin.on("error",()=>{l();}),process.on("SIGINT",()=>{l();}),process.on("SIGTERM",()=>{l();}),process.on("SIGHUP",()=>{l();});let w=process.ppid,m=setInterval(()=>{try{process.kill(w,0);}catch{process.stderr.write(`[weixin] Parent process exited, shutting down...
8
+ `),clearInterval(m),l();}},5e3);n.logForDebugging("[Weixin MCP] Starting poll loop"),await chunkCPQSQ7FU_cjs.Ra({baseUrl:a,cdnBaseUrl:chunkCPQSQ7FU_cjs.Fa,token:t.token,onMessage:async c=>{await r.notification({method:"notifications/claude/channel",params:{content:c.text,meta:{chat_id:c.fromUserId,sender_id:c.fromUserId,message_id:c.messageId,...c.attachmentPath&&{attachment_path:c.attachmentPath},...c.attachmentType&&{attachment_type:c.attachmentType}}}});},onPermissionResponse:async c=>{await r.notification({method:"notifications/claude/channel/permission",params:{request_id:c.requestId,behavior:c.behavior}});},abortSignal:o.signal}),clearInterval(m),await l();}var pe={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var ln=pe.languages,gn=ln.filter(e=>e.supported).map(e=>e.value),v={defaultLocale:"zh-CN",locales:gn},P={},N=(e,n)=>{let t=P[e]||{translation:{}};return P[e]={translation:{...t.translation,...n.translation}},P[e]},F=(e=v.defaultLocale)=>(P[e]||N(e,{translation:{}}),{locale:e,resources:P[e]||{translation:{}}});var dn={translation:{"weixin.sdk.cli.usage":["\u7528\u6CD5\uFF1A"," easbot weixin serve"," easbot weixin login"," easbot weixin login clear"," easbot weixin access pair <code>","","\u5F53\u524D\u7528\u6237\uFF08\u4ECE account.json \u8BFB\u53D6\uFF09\uFF1A"," easbot weixin user",' easbot weixin ensure-user [--display-name "<name>"]'," easbot weixin remove-user"].join(`
9
+ `),"weixin.sdk.cli.serve.unavailable":"[weixin] \u5F53\u524D\u4E0A\u4E0B\u6587\u65E0\u6CD5\u542F\u52A8 serve handler\u3002","weixin.sdk.cli.login.cleared":"\u5DF2\u6E05\u9664\u5FAE\u4FE1\u8D26\u53F7\u7ED1\u5B9A\u3002","weixin.sdk.cli.login.already_connected":"\u5DF2\u8FDE\u63A5\uFF1A","weixin.sdk.cli.login.user_id":" \u7528\u6237 ID\uFF1A{{userId}}","weixin.sdk.cli.login.connected_since":" \u8FDE\u63A5\u65F6\u95F4\uFF1A{{since}}","weixin.sdk.cli.login.disconnect_hint":"\u8FD0\u884C `easbot weixin login clear` \u89E3\u9664\u7ED1\u5B9A\u3002","weixin.sdk.cli.login.starting":"\u6B63\u5728\u542F\u52A8\u5FAE\u4FE1\u626B\u7801\u767B\u5F55...","weixin.sdk.cli.login.scan_hint":"\u8BF7\u7528\u5FAE\u4FE1\u626B\u63CF\u4E0A\u65B9\u4E8C\u7EF4\u7801\uFF0C\u6216\u6253\u5F00\u6B64 URL\uFF1A","weixin.sdk.cli.login.failed":"\u767B\u5F55\u5931\u8D25\uFF1A{{message}}","weixin.sdk.cli.login.connected_success":"\u767B\u5F55\u6210\u529F\uFF01","weixin.sdk.cli.login.base_url":" Base URL\uFF1A{{baseUrl}}","weixin.sdk.cli.access.invalid_code":"\u914D\u5BF9\u7801\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\u3002","weixin.sdk.cli.access.paired":"\u914D\u5BF9\u6210\u529F\uFF1A{{userId}}","weixin.sdk.cli.user.not_logged_in":"\u672A\u767B\u5F55\u4EFB\u4F55\u5FAE\u4FE1\u8D26\u53F7\u3002","weixin.sdk.cli.user.login_hint":"\u8FD0\u884C `easbot weixin login` \u901A\u8FC7 iLink \u7ED1\u5B9A\u4E2A\u4EBA\u5FAE\u4FE1\u3002","weixin.sdk.cli.user.header":"\u5F53\u524D weixin \u7528\u6237\uFF1A","weixin.sdk.cli.user.contact.registered":"\u5DF2\u6CE8\u518C","weixin.sdk.cli.user.contact.not_registered":"\u672A\u6CE8\u518C","weixin.sdk.cli.user.contact.ensure_hint":"\u8FD0\u884C `{{cmd}}` \u5B8C\u6210\u6CE8\u518C","weixin.sdk.cli.user.failed":"\u67E5\u8BE2\u7528\u6237\u5931\u8D25\uFF1A{{error}}","weixin.sdk.cli.ensure_user.requires_display_name":"{{flag}} \u9700\u8981\u4E00\u4E2A\u503C","weixin.sdk.cli.ensure_user.tag.created":"\u5DF2\u521B\u5EFA","weixin.sdk.cli.ensure_user.tag.existed":"\u5DF2\u5B58\u5728\uFF08\u5DF2\u66F4\u65B0\uFF09","weixin.sdk.cli.ensure_user.banner":"[weixin routing] {{tag}} user: {{userId}}","weixin.sdk.cli.ensure_user.failed":"ensure-user \u6267\u884C\u5931\u8D25\uFF1A{{error}}","weixin.sdk.cli.remove_user.usage":"\u7528\u6CD5\uFF1Aeasbot weixin remove-user","weixin.sdk.cli.remove_user.banner":"[weixin routing] removed user: {{userId}} contact={{contact}} session={{session}}","weixin.sdk.cli.remove_user.failed":"remove-user \u6267\u884C\u5931\u8D25\uFF1A{{error}}","weixin.sdk.cli.require_login":"\u672A\u767B\u5F55\u5FAE\u4FE1\u8D26\u53F7\uFF0C\u8BF7\u5148\u8FD0\u884C `easbot weixin login`\u3002","weixin.sdk.cli.unknown_argument":"\u672A\u77E5\u53C2\u6570\uFF1A{{arg}}"}},fe=dn;var un={translation:{"weixin.sdk.cli.usage":["Usage:"," easbot weixin serve"," easbot weixin login"," easbot weixin login clear"," easbot weixin access pair <code>","","Current user (read from account.json):"," easbot weixin user",' easbot weixin ensure-user [--display-name "<name>"]'," easbot weixin remove-user"].join(`
10
+ `),"weixin.sdk.cli.serve.unavailable":"[weixin] serve handler not available in this context.","weixin.sdk.cli.login.cleared":"WeChat account cleared.","weixin.sdk.cli.login.already_connected":"Already connected:","weixin.sdk.cli.login.user_id":" User ID: {{userId}}","weixin.sdk.cli.login.connected_since":" Connected since: {{since}}","weixin.sdk.cli.login.disconnect_hint":"Run `easbot weixin login clear` to disconnect.","weixin.sdk.cli.login.starting":"Starting WeChat QR login...","weixin.sdk.cli.login.scan_hint":"Scan the QR code above with WeChat, or open this URL:","weixin.sdk.cli.login.failed":"Login failed: {{message}}","weixin.sdk.cli.login.connected_success":"Connected successfully!","weixin.sdk.cli.login.base_url":" Base URL: {{baseUrl}}","weixin.sdk.cli.access.invalid_code":"Invalid or expired pairing code.","weixin.sdk.cli.access.paired":"Paired successfully: {{userId}}","weixin.sdk.cli.user.not_logged_in":"No weixin account logged in.","weixin.sdk.cli.user.login_hint":"Run `easbot weixin login` to bind your WeChat via iLink.","weixin.sdk.cli.user.header":"weixin current user:","weixin.sdk.cli.user.contact.registered":"registered","weixin.sdk.cli.user.contact.not_registered":"not registered","weixin.sdk.cli.user.contact.ensure_hint":"run `{{cmd}}` to register","weixin.sdk.cli.user.failed":"user failed: {{error}}","weixin.sdk.cli.ensure_user.requires_display_name":"{{flag}} requires a value","weixin.sdk.cli.ensure_user.tag.created":"created","weixin.sdk.cli.ensure_user.tag.existed":"exists (updated)","weixin.sdk.cli.ensure_user.banner":"[weixin routing] {{tag}} user: {{userId}}","weixin.sdk.cli.ensure_user.failed":"ensure-user failed: {{error}}","weixin.sdk.cli.remove_user.usage":"Usage: easbot weixin remove-user","weixin.sdk.cli.remove_user.banner":"[weixin routing] removed user: {{userId}} contact={{contact}} session={{session}}","weixin.sdk.cli.remove_user.failed":"remove-user failed: {{error}}","weixin.sdk.cli.require_login":"No weixin account logged in. Run `easbot weixin login` first.","weixin.sdk.cli.unknown_argument":"Unknown argument: {{arg}}"}},me=un;var fn=()=>{F("zh-CN"),F("en-US"),N("zh-CN",fe),N("en-US",me);};fn();var ee=new Map;var te=new Map;var mn=e=>{if(te.has(e))return te.get(e);let n=/{{\s*(\w+)\s*}}/g,t=[],r;for(;(r=n.exec(e))!==null;){let o=r[1];o&&!t.includes(o)&&t.push(o);}let i=new RegExp("{{\\s*("+t.join("|")+")\\s*}}","g"),a={keys:t,regex:i};return te.set(e,a),a},we=(e,n)=>{if(!e||typeof e!="string")return "";if(!n||Object.keys(n).length===0)return e;let{regex:t,keys:r}=mn(e);return r.length===0||!r.some(a=>a in n)?e:e.replace(t,(a,o)=>{let f=n[o];return f==null?"":String(f)})},wn=e=>{let n=utils.resolveLocaleLang(e);return v.locales.includes(n)?n:v.defaultLocale},xe=e=>{if(!ee.has(e)){let{resources:n}=F(e);ee.set(e,n);}return ee.get(e)},xn=(e,n={})=>{let t=wn(n.locale),i=xe(t)?.translation[e];if(i&&typeof i=="string"){let a=we(i,n.vars);return a!=null?String(a):String(e)}if(t!==v.defaultLocale){let o=xe(v.defaultLocale)?.translation[e];if(o&&typeof o=="string"){let f=we(o,n.vars);return f!=null?String(f):String(e)}}return String(n.fallback??e)},s=xn;function he(){process.stdout.write(s("weixin.sdk.cli.usage")+`
11
+ `);}async function hn(e=false){if(e){chunkCPQSQ7FU_cjs.Ja(),process.stdout.write(s("weixin.sdk.cli.login.cleared")+`
12
+ `);return}let n=chunkCPQSQ7FU_cjs.Ha();if(n){process.stdout.write([s("weixin.sdk.cli.login.already_connected"),s("weixin.sdk.cli.login.user_id",{vars:{userId:n.userId||"unknown"}}),s("weixin.sdk.cli.login.connected_since",{vars:{since:utils.formatLocalISO(new Date(n.savedAt))}}),"",s("weixin.sdk.cli.login.disconnect_hint")].join(`
9
13
  `)+`
10
- `);}async function Kt(t=false){if(t){chunkCPQSQ7FU_cjs.Ja(),process.stdout.write(`WeChat account cleared.
11
- `);return}let r=chunkCPQSQ7FU_cjs.Ha();if(r){process.stdout.write(["Already connected:",` User ID: ${r.userId||"unknown"}`,` Connected since: ${utils.formatLocalISO(new Date(r.savedAt))}`,"","Run `easbot weixin login clear` to disconnect."].join(`
12
- `)+`
13
- `);return}process.stdout.write(`Starting WeChat QR login...
14
+ `);return}process.stdout.write(s("weixin.sdk.cli.login.starting")+`
14
15
 
15
- `);let e=await _(chunkCPQSQ7FU_cjs.Ea);process.stdout.write(`
16
- Scan the QR code above with WeChat, or open this URL:
17
- ${e.qrcodeUrl||""}
16
+ `);let t=await D(chunkCPQSQ7FU_cjs.Ea);process.stdout.write(`
17
+ ${s("weixin.sdk.cli.login.scan_hint")}
18
+ ${t.qrcodeUrl||""}
18
19
 
19
- `);let n=await V({qrcodeId:e.qrcodeId,apiBaseUrl:chunkCPQSQ7FU_cjs.Ea});(!n.connected||!n.token)&&(process.stderr.write(`Login failed: ${n.message}
20
- `),process.exit(1)),chunkCPQSQ7FU_cjs.Ia({token:n.token,baseUrl:n.baseUrl||chunkCPQSQ7FU_cjs.Ea,userId:n.userId,savedAt:new Date().toISOString()}),process.stdout.write(["Connected successfully!",` User ID: ${n.userId||"unknown"}`,` Base URL: ${n.baseUrl||chunkCPQSQ7FU_cjs.Ea}`].join(`
20
+ `);let r=await Z({qrcodeId:t.qrcodeId,apiBaseUrl:chunkCPQSQ7FU_cjs.Ea});(!r.connected||!r.token)&&(process.stderr.write(s("weixin.sdk.cli.login.failed",{vars:{message:r.message}})+`
21
+ `),process.exit(1)),chunkCPQSQ7FU_cjs.Ia({token:r.token,baseUrl:r.baseUrl||chunkCPQSQ7FU_cjs.Ea,userId:r.userId,savedAt:new Date().toISOString()}),process.stdout.write([s("weixin.sdk.cli.login.connected_success")," "+s("weixin.sdk.cli.login.user_id",{vars:{userId:r.userId||"unknown"}})," "+s("weixin.sdk.cli.login.base_url",{vars:{baseUrl:r.baseUrl||chunkCPQSQ7FU_cjs.Ea}})].join(`
21
22
  `)+`
22
- `);}function Yt(t){(t[0]!=="pair"||!t[1])&&(ie(),process.exit(1));let r=chunkCPQSQ7FU_cjs.Na(t[1]);r||(process.stderr.write(`Invalid or expired pairing code.
23
- `),process.exit(1)),process.stdout.write(`Paired successfully: ${r}
24
- `);}function Jt(t,r){let e={userId:r,channelId:"weixin-main"};for(let n=0;n<t.length;n++){let o=t[n];if(o==="--display-name"||o==="-d"){let u=t[++n];if(!u)return "--display-name requires a value";e.displayName=u;}else return `Unknown argument: ${o}`}return e}function ae(){let t=chunkCPQSQ7FU_cjs.Ha();return t?.userId||(process.stderr.write("No weixin account logged in. Run `easbot weixin login` first.\n"),process.exit(1)),t.userId}async function Xt(){try{let t=chunkCPQSQ7FU_cjs.Ha();if(!t){process.stdout.write(`No weixin account logged in.
25
- `),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: ${t.userId??"(unknown)"}
27
- `),process.stdout.write(` baseUrl: ${t.baseUrl}
28
- `),process.stdout.write(` savedAt: ${utils.formatLocalISO(new Date(t.savedAt))}
29
- `);let e=(await chunkCPQSQ7FU_cjs.Da()).find(n=>n.stableId===t.userId);e?(process.stdout.write(` contact: registered
30
- `),process.stdout.write(` uid: ${e.uid}
31
- `),e.profile.displayName&&process.stdout.write(` display: ${e.profile.displayName}
32
- `),e.profile.username&&process.stdout.write(` username: ${e.profile.username}
33
- `),process.stdout.write(` lastSeen: ${utils.formatLocalISO(new Date(e.lastSeenAt))}
34
- `)):(process.stdout.write(` contact: not registered
35
- `),process.stdout.write(" hint: run `easbot weixin ensure-user` to register\n"));}catch(t){process.stderr.write(`user failed: ${t}
36
- `),process.exit(1);}}async function Zt(t){let r=ae(),e=Jt(t,r);typeof e=="string"&&(process.stderr.write(`${e}
37
- `),process.exit(1));try{let n=await chunkCPQSQ7FU_cjs.Ba(e),{contact:o,session:u,created:d}=n,y=d.contact&&d.session?"\u5DF2\u521B\u5EFA":"\u5DF2\u5B58\u5728\uFF08\u5DF2\u66F4\u65B0\uFF09";process.stdout.write([`[weixin routing] ${y} user: ${r}`,` contact.uid: ${o.uid}`,` contact.path: ${chunkCPQSQ7FU_cjs.xa()}/contacts/${o.platform}/${o.stableId}.json`,` session.id: ${u.id}`,` session.path: ${chunkCPQSQ7FU_cjs.ya()}/sessions.json`,` profile: ${JSON.stringify(o.profile)}`].join(`
23
+ `);}function yn(e){(e[0]!=="pair"||!e[1])&&(he(),process.exit(1));let n=chunkCPQSQ7FU_cjs.Na(e[1]);n||(process.stderr.write(s("weixin.sdk.cli.access.invalid_code")+`
24
+ `),process.exit(1)),process.stdout.write(s("weixin.sdk.cli.access.paired",{vars:{userId:n}})+`
25
+ `);}function Cn(e,n){let t={userId:n,channelId:"weixin-main"};for(let r=0;r<e.length;r++){let i=e[r];if(i==="--display-name"||i==="-d"){let a=e[++r];if(!a)return s("weixin.sdk.cli.ensure_user.requires_display_name",{vars:{flag:"--display-name"}});t.displayName=a;}else return s("weixin.sdk.cli.unknown_argument",{vars:{arg:i??""}})}return t}function ye(){let e=chunkCPQSQ7FU_cjs.Ha();return e?.userId||(process.stderr.write(s("weixin.sdk.cli.require_login")+`
26
+ `),process.exit(1)),e.userId}async function Sn(){try{let e=chunkCPQSQ7FU_cjs.Ha();if(!e){process.stdout.write(s("weixin.sdk.cli.user.not_logged_in")+`
27
+ `),process.stdout.write(s("weixin.sdk.cli.user.login_hint")+`
28
+ `);return}process.stdout.write(s("weixin.sdk.cli.user.header")+`
29
+ `),process.stdout.write(` userId: ${e.userId??"(unknown)"}
30
+ `),process.stdout.write(` baseUrl: ${e.baseUrl}
31
+ `),process.stdout.write(` savedAt: ${utils.formatLocalISO(new Date(e.savedAt))}
32
+ `);let t=(await chunkCPQSQ7FU_cjs.Da()).find(r=>r.stableId===e.userId);t?(process.stdout.write(` contact: ${s("weixin.sdk.cli.user.contact.registered")}
33
+ `),process.stdout.write(` uid: ${t.uid}
34
+ `),t.profile.displayName&&process.stdout.write(` display: ${t.profile.displayName}
35
+ `),t.profile.username&&process.stdout.write(` username: ${t.profile.username}
36
+ `),process.stdout.write(` lastSeen: ${utils.formatLocalISO(new Date(t.lastSeenAt))}
37
+ `)):(process.stdout.write(` contact: ${s("weixin.sdk.cli.user.contact.not_registered")}
38
+ `),process.stdout.write(` hint: ${s("weixin.sdk.cli.user.contact.ensure_hint",{vars:{cmd:"easbot weixin ensure-user"}})}
39
+ `));}catch(e){process.stderr.write(s("weixin.sdk.cli.user.failed",{vars:{error:String(e)}})+`
40
+ `),process.exit(1);}}async function vn(e){let n=ye(),t=Cn(e,n);typeof t=="string"&&(process.stderr.write(`${t}
41
+ `),process.exit(1));try{let r=await chunkCPQSQ7FU_cjs.Ba(t),{contact:i,session:a,created:o}=r,f=o.contact&&o.session?s("weixin.sdk.cli.ensure_user.tag.created"):s("weixin.sdk.cli.ensure_user.tag.existed");process.stdout.write([s("weixin.sdk.cli.ensure_user.banner",{vars:{tag:f,userId:n}}),` contact.uid: ${i.uid}`,` contact.path: ${chunkCPQSQ7FU_cjs.xa()}/contacts/${i.platform}/${i.stableId}.json`,` session.id: ${a.id}`,` session.path: ${chunkCPQSQ7FU_cjs.ya()}/sessions.json`,` profile: ${JSON.stringify(i.profile)}`].join(`
38
42
  `)+`
39
- `);}catch(n){process.stderr.write(`ensure-user failed: ${n}
40
- `),process.exit(1);}}async function er(t){let r=ae();t.length>0&&(process.stderr.write(`Unknown argument: ${t[0]}
41
- `),process.stderr.write(`Usage: easbot weixin remove-user
42
- `),process.exit(1));try{let e=await chunkCPQSQ7FU_cjs.Ca(r,"weixin-main");process.stdout.write(`[weixin routing] removed user: ${r} contact=${e.removed.contact} session=${e.removed.session}
43
- `);}catch(e){process.stderr.write(`remove-user failed: ${e}
44
- `),process.exit(1);}}async function tr(t,r,e){let[n,...o]=t;switch(n){case "serve":r||(process.stderr.write(`[weixin] serve handler not available in this context.
45
- `),process.exit(1)),await se(e??"0.0.0",r);return;case "login":await Kt(o[0]==="clear");return;case "access":Yt(o);return;case "user":await Xt();return;case "ensure-user":await Zt(o);return;case "remove-user":await er(o);return;default:ie();}}Object.defineProperty(exports,"AgentRegistry",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Za}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.p}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.k}});Object.defineProperty(exports,"AgentSyncManager",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs._a}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.j}});Object.defineProperty(exports,"BaseChannelPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.qa}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.h}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.oa}});Object.defineProperty(exports,"ChannelPluginRegistry",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Xa}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.o}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.m}});Object.defineProperty(exports,"DEBUG_AGENT_FILTER",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.T}});Object.defineProperty(exports,"DEFAULT_AGENT_FILTER",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.S}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ha}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ja}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ia}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ga}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.fa}});Object.defineProperty(exports,"DiscordPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.sa}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.c}});Object.defineProperty(exports,"FeishuPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ua}});Object.defineProperty(exports,"GatewayClientConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.s}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.l}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.t}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.$a}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.r}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.na}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.i}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.n}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ka}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.la}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.g}});Object.defineProperty(exports,"NostrPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Va}});Object.defineProperty(exports,"SdkEventBridge",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.R}});Object.defineProperty(exports,"SdkEventBus",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Q}});Object.defineProperty(exports,"SdkEventType",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.P}});Object.defineProperty(exports,"SdkMessageCollector",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.U}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.q}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ma}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.f}});Object.defineProperty(exports,"SignalPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ua}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.b}});Object.defineProperty(exports,"SlackPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ta}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.a}});Object.defineProperty(exports,"TelegramPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ra}});Object.defineProperty(exports,"WEIXIN_PLATFORM",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.wa}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.d}});Object.defineProperty(exports,"WeChatPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.va}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.e}});Object.defineProperty(exports,"WebChatPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ta}});Object.defineProperty(exports,"WeixinPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Sa}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.z}});Object.defineProperty(exports,"convertToGatewayMessage",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ba}});Object.defineProperty(exports,"createChannelPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Wa}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.da}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.$}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.aa}});Object.defineProperty(exports,"ensureContact",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.za}});Object.defineProperty(exports,"ensureSession",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Aa}});Object.defineProperty(exports,"ensureUser",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ba}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ca}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ea}});Object.defineProperty(exports,"getAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.W}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.G}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.L}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.C}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.F}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.M}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.x}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.A}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.D}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.N}});Object.defineProperty(exports,"getGatewayClientConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.I}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.J}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.K}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.O}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.E}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.B}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.H}});Object.defineProperty(exports,"getSupportedPlatforms",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ya}});Object.defineProperty(exports,"hasAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.X}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.y}});Object.defineProperty(exports,"listWeixinContacts",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Da}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.w}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.v}});Object.defineProperty(exports,"removeUser",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ca}});Object.defineProperty(exports,"requireAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Y}});Object.defineProperty(exports,"setAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.V}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.u}});Object.defineProperty(exports,"weixinSetStateDir",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ga}});exports.handleWeixinCli=tr;
43
+ `);}catch(r){process.stderr.write(s("weixin.sdk.cli.ensure_user.failed",{vars:{error:String(r)}})+`
44
+ `),process.exit(1);}}async function kn(e){let n=ye();if(e.length>0){let t=e[0]??"";process.stderr.write(s("weixin.sdk.cli.unknown_argument",{vars:{arg:t}})+`
45
+ `),process.stderr.write(s("weixin.sdk.cli.remove_user.usage")+`
46
+ `),process.exit(1);}try{let t=await chunkCPQSQ7FU_cjs.Ca(n,"weixin-main");process.stdout.write(s("weixin.sdk.cli.remove_user.banner",{vars:{userId:n,contact:String(t.removed.contact),session:String(t.removed.session)}})+`
47
+ `);}catch(t){process.stderr.write(s("weixin.sdk.cli.remove_user.failed",{vars:{error:String(t)}})+`
48
+ `),process.exit(1);}}async function bn(e,n,t){let[r,...i]=e;switch(r){case "serve":n||(process.stderr.write(s("weixin.sdk.cli.serve.unavailable")+`
49
+ `),process.exit(1)),await ue(t??"0.0.0",n);return;case "login":await hn(i[0]==="clear");return;case "access":yn(i);return;case "user":await Sn();return;case "ensure-user":await vn(i);return;case "remove-user":await kn(i);return;default:he();}}Object.defineProperty(exports,"AgentRegistry",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Za}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.p}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.k}});Object.defineProperty(exports,"AgentSyncManager",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs._a}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.j}});Object.defineProperty(exports,"BaseChannelPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.qa}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.h}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.oa}});Object.defineProperty(exports,"ChannelPluginRegistry",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Xa}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.o}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.m}});Object.defineProperty(exports,"DEBUG_AGENT_FILTER",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.T}});Object.defineProperty(exports,"DEFAULT_AGENT_FILTER",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.S}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ha}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ja}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ia}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ga}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.fa}});Object.defineProperty(exports,"DiscordPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.sa}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.c}});Object.defineProperty(exports,"FeishuPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ua}});Object.defineProperty(exports,"GatewayClientConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.s}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.l}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.t}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.$a}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.r}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.na}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.i}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.n}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ka}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.la}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.g}});Object.defineProperty(exports,"NostrPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Va}});Object.defineProperty(exports,"SdkEventBridge",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.R}});Object.defineProperty(exports,"SdkEventBus",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Q}});Object.defineProperty(exports,"SdkEventType",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.P}});Object.defineProperty(exports,"SdkMessageCollector",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.U}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.q}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ma}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.f}});Object.defineProperty(exports,"SignalPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ua}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.b}});Object.defineProperty(exports,"SlackPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ta}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.a}});Object.defineProperty(exports,"TelegramPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ra}});Object.defineProperty(exports,"WEIXIN_PLATFORM",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.wa}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.d}});Object.defineProperty(exports,"WeChatPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.va}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.e}});Object.defineProperty(exports,"WebChatPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ta}});Object.defineProperty(exports,"WeixinPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Sa}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.z}});Object.defineProperty(exports,"convertToGatewayMessage",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ba}});Object.defineProperty(exports,"createChannelPlugin",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Wa}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.da}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.$}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.aa}});Object.defineProperty(exports,"ensureContact",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.za}});Object.defineProperty(exports,"ensureSession",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Aa}});Object.defineProperty(exports,"ensureUser",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ba}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ca}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.ea}});Object.defineProperty(exports,"getAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.W}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.G}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.L}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.C}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.F}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.M}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.x}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.A}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.D}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.N}});Object.defineProperty(exports,"getGatewayClientConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.I}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.J}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.K}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.O}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.E}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.B}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.H}});Object.defineProperty(exports,"getSupportedPlatforms",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ya}});Object.defineProperty(exports,"hasAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.X}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.y}});Object.defineProperty(exports,"listWeixinContacts",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Da}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.w}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.v}});Object.defineProperty(exports,"removeUser",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ca}});Object.defineProperty(exports,"requireAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Y}});Object.defineProperty(exports,"setAgentAdapter",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.V}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.u}});Object.defineProperty(exports,"weixinSetStateDir",{enumerable:true,get:function(){return chunkCPQSQ7FU_cjs.Ga}});exports.handleWeixinCli=bn;
package/dist/index.mjs CHANGED
@@ -1,45 +1,49 @@
1
- import {b,c}from'./chunks/chunk-NXFFFRVB.mjs';import {Z,w,_,Ca,Ba,xa,ya,Ha,Da,Na,Ja,Ia,Ea,Qa,Oa,Ra,Fa,Ka,La,Ma,Pa}from'./chunks/chunk-3EE2AOK7.mjs';export{Za as AgentRegistry,p as AgentRegistryConfigSchema,k as AgentSyncConfigSchema,_a as AgentSyncManager,j as AuthConfigSchema,qa as BaseChannelPlugin,h as ChannelConfigSchema,oa as ChannelPluginLoader,Xa as ChannelPluginRegistry,o as CircuitBreakerConfigSchema,m as ConnectionPoolConfigSchema,T as DEBUG_AGENT_FILTER,S as DEFAULT_AGENT_FILTER,ha as DEFAULT_AGENT_REGISTRY_CONFIG,ja as DEFAULT_CONNECTION_POOL_CONFIG,ia as DEFAULT_SYNC_CONFIG,ga as DEFAULT_TOKEN_AUTH_CONFIG,fa as DEFAULT_WEBSOCKET_SERVER_CONFIG,sa as DiscordPlugin,c as FeishuChannelConfigSchema,ua as FeishuPlugin,s as GatewayClientConfigSchema,l as GatewayClusterConfigSchema,t as GatewayConfigSchema,$a as GatewayServer,r as GatewayServerConfigSchema,na as GatewaySessionManager,i as HTTPSConfigSchema,n as MessageQueueConfigSchema,ka as MessageRouter,la as MessageStore,g as NostrChannelConfigSchema,Va as NostrPlugin,R as SdkEventBridge,Q as SdkEventBus,P as SdkEventType,U as SdkMessageCollector,q as SessionConfigSchema,ma as SessionStore,f as SignalChannelConfigSchema,Ua as SignalPlugin,b as SlackChannelConfigSchema,ta as SlackPlugin,a as TelegramChannelConfigSchema,ra as TelegramPlugin,wa as WEIXIN_PLATFORM,d as WeChatChannelConfigSchema,va as WeChatPlugin,e as WebChatChannelConfigSchema,Ta as WebChatPlugin,Sa as WeixinPlugin,z as clearConfigCache,ba as convertToGatewayMessage,Wa as createChannelPlugin,da as createDefaultSessionState,$ as createGatewayMessage,aa as createTextMessage,za as ensureContact,Aa as ensureSession,Ba as ensureUser,ca as generateSessionId,ea as generateSubscriptionId,W as getAgentAdapter,G as getAgentRegistryConfig,L as getAuthConfig,C as getChannelConfig,F as getCircuitBreakerConfig,M as getClusterConfig,x as getConfig,A as getConfigDirectory,D as getConnectionPoolConfig,N as getDefaultAgent,I as getGatewayClientConfig,J as getGatewayClientUrl,K as getHTTPSConfig,O as getLogLevel,E as getMessageQueueConfig,B as getServerConfig,H as getSessionConfig,Ya as getSupportedPlatforms,X as hasAgentAdapter,y as isConfigLoaded,Da as listWeixinContacts,w as loadConfig,v as parsePartialConfig,Ca as removeUser,Y as requireAgentAdapter,V as setAgentAdapter,u as validateConfig,Ga as weixinSetStateDir}from'./chunks/chunk-3EE2AOK7.mjs';import {a}from'./chunks/chunk-HQBRVVXS.mjs';import {Log,Fetch,formatLocalISO}from'@easbot/utils';import {toString}from'qrcode';import {existsSync}from'fs';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';var g=Log.create({service:"gateway"}),P=class t extends Error{constructor(e,n,o){super(e);a(this,"type");a(this,"stage");a(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=o,Error.captureStackTrace&&Error.captureStackTrace(this,t);}};function se(t){let r=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],e=t.code;return r.includes(e??"")}function Wt(){process.on("unhandledRejection",t=>{let r=t instanceof Error?t:new Error(String(t));se(r)||g.error("unhandled promise rejection",{error:r.message,stack:r.stack});}),process.on("uncaughtException",t=>{se(t)||(g.error("uncaught exception",{error:t.message,stack:t.stack}),process.exit(1));});}var V;(nr=>{let t={initialized:false,initPromise:null,directory:".easbot",config:null},r,e={server:null,config:null,initialized:false,status:"stopped"};async function n(a={}){if(t.initialized)return;if(t.initPromise)return t.initPromise;let l={directory:a.directory??".easbot",printLogs:a.printLogs??false,logLevel:a.logLevel??"INFO"};return t.directory=l.directory,t.initPromise=(async()=>{Z();try{Wt();}catch(c){throw new P("Failed to install unhandled exception handlers","server",c instanceof Error?c:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),g.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{t.config=await w(l.directory);}catch(c){throw new P("Failed to load gateway configuration","config",c instanceof Error?c:void 0)}t.initialized=true,g.info("gateway runtime initialized",{directory:l.directory,logLevel:l.logLevel});})(),t.initPromise}nr.init=n;function o(){return t.initialized}nr.isInitialized=o;function u(){return r||(r=async()=>{if(!t.initialized)throw new P("Gateway not initialized. Call init() first.","server");let a=_(),l=await w(a.directory);return l.server?.enabled?(e={server:null,config:l,initialized:true,status:"stopped"},g.info("gateway initialized",{port:l.server?.port,hostname:l.server?.hostname}),e):(g.debug("gateway server disabled or not configured"),{server:null,config:l,initialized:true,status:"stopped"})}),r}function d(){return u()()}nr.state=d;async function y(){return (await d()).server}nr.get=y;async function i(){return (await d()).config?.server?.enabled??false}nr.isEnabled=i;async function f(){return (await d()).config}nr.config=f;function p(){return e.status}nr.getStatus=p;async function s(a){g.debug("Gateway.start: called"),t.initialized||await n();let l=await d();if(!(l.config?.server?.enabled??true))throw g.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(e.status==="running"){g.info("gateway server is already running");return}if(e.status==="starting"){g.info("gateway server is starting");return}e.status="starting";try{let c={...l.config?.server,...a};g.debug("gateway start: creating server with config",{port:c.port,hostname:c.hostname,path:c.path,https:c.https?.enabled});let T=await ge(c);e.server=T,e.status="running",e.error=void 0,g.info("gateway server started",{port:c.port,hostname:c.hostname});}catch(c){throw e.status="error",e.error=c instanceof Error?c.message:String(c),g.error("failed to start gateway server",{error:e.error}),c}}nr.start=s;async function m(){if(e.status==="stopped"){g.info("gateway server is already stopped");return}if(e.status==="stopping"){g.info("gateway server is stopping");return}e.status="stopping";try{e.server&&await e.server.stop(),e.server=null,e.status="stopped",e.error=void 0,g.info("gateway server stopped");}catch(a){throw e.status="error",e.error=a instanceof Error?a.message:String(a),g.error("failed to stop gateway server",{error:e.error}),a}}nr.stop=m;async function C(a){g.info("restarting gateway server"),(e.status==="running"||e.status==="starting")&&await m(),await s(a);}nr.restart=C;async function J(){let a=_(),l=await w(a.directory);return e.config=l,t.config=l,g.info("gateway config reloaded"),l}nr.reloadConfig=J;async function ge(a,l){g.debug("createGatewayServer: starting");let{GatewayServer:L}=await import('./chunks/server-XGZGHXC5.mjs'),c=new L(a),T=l?.startupTimeout??3e4;if(await(async()=>{let S=new Promise((x,le)=>{setTimeout(()=>{le(new Error(`Gateway server startup timeout after ${T}ms`));},T);});try{await Promise.race([c.start(),S]);}catch(x){g.error("gateway server start failed, attempting cleanup",{error:x instanceof Error?x.message:String(x)});try{await c.stop();}catch{}throw x}})(),l?.onStarted)try{await l.onStarted(c);}catch(S){g.warn("server started but onStarted callback failed",{error:S instanceof Error?S.message:String(S)});}return g.info("gateway server created and started",{port:a.port,hostname:a.hostname}),c}nr.createGatewayServer=ge;})(V||(V={}));async function Ot(t){let r=await toString(t,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${r}
2
- `);}async function G(t){let r=await fetch(`${t}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!r.ok)throw new Error(`Failed to get QR code: HTTP ${r.status}`);let e=await r.json();if(!e.qrcode)throw new Error("No qrcode in response");let n=e.qrcode_img_content||"";return n&&await Ot(n),{qrcodeUrl:n,qrcodeId:e.qrcode,message:"Scan the QR code with WeChat to connect."}}async function K(t){let{qrcodeId:r,apiBaseUrl:e,timeoutMs:n=48e4,maxRetries:o=3}=t,u=Date.now()+n,d=r,y=0;for(;Date.now()<u;){try{let i=new AbortController,f=setTimeout(()=>i.abort(),6e4),p=await fetch(`${e}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(d)}`,{headers:{"iLink-App-ClientVersion":"1"},signal:i.signal});if(clearTimeout(f),!p.ok)throw new Error(`HTTP ${p.status}`);let s=await p.json();switch(s.status){case "confirmed":return {connected:!0,token:s.bot_token,accountId:s.ilink_bot_id,baseUrl:s.baseurl,userId:s.ilink_user_id,message:"Connected to WeChat successfully!"};case "scaned":process.stderr.write(`QR code scanned, waiting for confirmation...
3
- `);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 G(e)).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(t){return ["Claude Code needs your approval.","",`Tool: ${t.tool_name}`,`Reason: ${t.description}`,`Input: ${t.input_preview}`,"",`Reply with: yes ${t.request_id}`,`Or deny with: no ${t.request_id}`].join(`
6
- `)}function Kt(t){let r=new Server({name:"weixin",version:t},{capabilities:{experimental:{"claude/channel":{},"claude/channel/permission":{}},tools:{}},instructions:'Messages from WeChat arrive as <channel source="plugin:weixin:weixin" chat_id="..." sender_id="...">. Reply using the reply tool with the chat_id from the channel tag. Use absolute paths for file attachments.'});return r.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[{name:"reply",description:"Reply to a WeChat message. Pass the chat_id from the channel tag.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The chat_id from the channel notification"},text:{type:"string",description:"The reply text"},files:{type:"array",items:{type:"string"},description:"Optional absolute file paths to attach"}},required:["chat_id","text"]}},{name:"send_typing",description:"Send a typing indicator to a WeChat user.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The chat_id (user ID)"}},required:["chat_id"]}}]})),r.setRequestHandler(CallToolRequestSchema,async e=>{let{name:n,arguments:o}=e.params,u=Ha();if(!u)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let d=u.baseUrl||Ea,y=Fa;switch(n){case "reply":{let i=typeof o?.chat_id=="string"?o.chat_id:"",f=typeof o?.text=="string"?o.text:"",p=Array.isArray(o?.files)?o.files.filter(m=>typeof m=="string"):void 0;if(!i||!f)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let s=Qa(i)||"";try{if(p&&p.length>0){for(let[m,C]of p.entries()){if(!existsSync(C))return {content:[{type:"text",text:`File not found: ${C}`}],isError:!0};await Pa({filePath:C,to:i,text:m===0?f:"",baseUrl:d,token:u.token,contextToken:s,cdnBaseUrl:y});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await Oa({to:i,text:f,baseUrl:d,token:u.token,contextToken:s}),{content:[{type:"text",text:"Message sent."}]}}catch(m){return {content:[{type:"text",text:`Failed to send: ${m}`}],isError:true}}}case "send_typing":{let i=typeof o?.chat_id=="string"?o.chat_id:"";if(!i)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let f=Qa(i),p=await Ka(d,u.token,i,f);return p.typing_ticket&&await La(d,u.token,{ilink_user_id:i,typing_ticket:p.typing_ticket,status:Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(f){return {content:[{type:"text",text:`Failed to send typing: ${f}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${n}`}],isError:true}}}),r}async function ie(t,r){r.enableConfigs(),r.initializeAnalyticsSink();let e=Ha();e||(process.stderr.write("[weixin] No account configured. Run `easbot weixin login` to connect your WeChat account.\n"),await Promise.all([r.shutdown1PEventLogging(),r.shutdownDatadog()]),process.exit(1));let n=Kt(t),o=new StdioServerTransport;r.registerPermissionHandler(n,async s=>{let m=s.channel_context?.chat_id,C=m?{chatId:m,contextToken:Qa(m)}:b();if(!C){r.logForDebugging(`[Weixin MCP] No active chat available for permission request ${s.request_id}`);return}try{c(s,C.chatId,C.contextToken),await Oa({to:C.chatId,text:Vt(s),baseUrl:u,token:e.token,contextToken:C.contextToken||""});}catch(J){process.stderr.write(`[weixin] Failed to relay permission request ${s.request_id}: ${J}
7
- `);}}),await n.connect(o);let u=e.baseUrl||Ea,d=new AbortController,y=false,i=async()=>{y||(y=true,d.signal.aborted||d.abort(),await Promise.all([r.shutdown1PEventLogging(),r.shutdownDatadog()]),process.exit(0));};process.stdin.on("end",()=>{i();}),process.stdin.on("error",()=>{i();}),process.on("SIGINT",()=>{i();}),process.on("SIGTERM",()=>{i();}),process.on("SIGHUP",()=>{i();});let f=process.ppid,p=setInterval(()=>{try{process.kill(f,0);}catch{process.stderr.write(`[weixin] Parent process exited, shutting down...
8
- `),clearInterval(p),i();}},5e3);r.logForDebugging("[Weixin MCP] Starting poll loop"),await Ra({baseUrl:u,cdnBaseUrl:Fa,token:e.token,onMessage:async s=>{await n.notification({method:"notifications/claude/channel",params:{content:s.text,meta:{chat_id:s.fromUserId,sender_id:s.fromUserId,message_id:s.messageId,...s.attachmentPath&&{attachment_path:s.attachmentPath},...s.attachmentType&&{attachment_type:s.attachmentType}}}});},onPermissionResponse:async s=>{await n.notification({method:"notifications/claude/channel/permission",params:{request_id:s.requestId,behavior:s.behavior}});},abortSignal:d.signal}),clearInterval(p),await i();}function 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(`
1
+ import {b,c}from'./chunks/chunk-NXFFFRVB.mjs';import {Z as Z$1,w,_,Ca,Ba,xa,ya,Ha,Da,Na,Ja,Ia,Ea,Qa,Oa,Ra,Fa,Ka,La,Ma,Pa}from'./chunks/chunk-3EE2AOK7.mjs';export{Za as AgentRegistry,p as AgentRegistryConfigSchema,k as AgentSyncConfigSchema,_a as AgentSyncManager,j as AuthConfigSchema,qa as BaseChannelPlugin,h as ChannelConfigSchema,oa as ChannelPluginLoader,Xa as ChannelPluginRegistry,o as CircuitBreakerConfigSchema,m as ConnectionPoolConfigSchema,T as DEBUG_AGENT_FILTER,S as DEFAULT_AGENT_FILTER,ha as DEFAULT_AGENT_REGISTRY_CONFIG,ja as DEFAULT_CONNECTION_POOL_CONFIG,ia as DEFAULT_SYNC_CONFIG,ga as DEFAULT_TOKEN_AUTH_CONFIG,fa as DEFAULT_WEBSOCKET_SERVER_CONFIG,sa as DiscordPlugin,c as FeishuChannelConfigSchema,ua as FeishuPlugin,s as GatewayClientConfigSchema,l as GatewayClusterConfigSchema,t as GatewayConfigSchema,$a as GatewayServer,r as GatewayServerConfigSchema,na as GatewaySessionManager,i as HTTPSConfigSchema,n as MessageQueueConfigSchema,ka as MessageRouter,la as MessageStore,g as NostrChannelConfigSchema,Va as NostrPlugin,R as SdkEventBridge,Q as SdkEventBus,P as SdkEventType,U as SdkMessageCollector,q as SessionConfigSchema,ma as SessionStore,f as SignalChannelConfigSchema,Ua as SignalPlugin,b as SlackChannelConfigSchema,ta as SlackPlugin,a as TelegramChannelConfigSchema,ra as TelegramPlugin,wa as WEIXIN_PLATFORM,d as WeChatChannelConfigSchema,va as WeChatPlugin,e as WebChatChannelConfigSchema,Ta as WebChatPlugin,Sa as WeixinPlugin,z as clearConfigCache,ba as convertToGatewayMessage,Wa as createChannelPlugin,da as createDefaultSessionState,$ as createGatewayMessage,aa as createTextMessage,za as ensureContact,Aa as ensureSession,Ba as ensureUser,ca as generateSessionId,ea as generateSubscriptionId,W as getAgentAdapter,G as getAgentRegistryConfig,L as getAuthConfig,C as getChannelConfig,F as getCircuitBreakerConfig,M as getClusterConfig,x as getConfig,A as getConfigDirectory,D as getConnectionPoolConfig,N as getDefaultAgent,I as getGatewayClientConfig,J as getGatewayClientUrl,K as getHTTPSConfig,O as getLogLevel,E as getMessageQueueConfig,B as getServerConfig,H as getSessionConfig,Ya as getSupportedPlatforms,X as hasAgentAdapter,y as isConfigLoaded,Da as listWeixinContacts,w as loadConfig,v as parsePartialConfig,Ca as removeUser,Y as requireAgentAdapter,V as setAgentAdapter,u as validateConfig,Ga as weixinSetStateDir}from'./chunks/chunk-3EE2AOK7.mjs';import {a}from'./chunks/chunk-HQBRVVXS.mjs';import {Log,Fetch,formatLocalISO,resolveLocaleLang}from'@easbot/utils';import {toString}from'qrcode';import {existsSync}from'fs';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';var u=Log.create({service:"gateway"}),P=class e extends Error{constructor(t,r,i){super(t);a(this,"type");a(this,"stage");a(this,"cause");this.type="GatewayInitializationError",this.stage=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function ue(e){let n=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return n.includes(t??"")}function Xt(){process.on("unhandledRejection",e=>{let n=e instanceof Error?e:new Error(String(e));ue(n)||u.error("unhandled promise rejection",{error:n.message,stack:n.stack});}),process.on("uncaughtException",e=>{ue(e)||(u.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}var Z;(Rn=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},n,t={server:null,config:null,initialized:false,status:"stopped"};async function r(g={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let p={directory:g.directory??".easbot",printLogs:g.printLogs??false,logLevel:g.logLevel??"INFO"};return e.directory=p.directory,e.initPromise=(async()=>{Z$1();try{Xt();}catch(d){throw new P("Failed to install unhandled exception handlers","server",d instanceof Error?d:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),u.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{e.config=await w(p.directory);}catch(d){throw new P("Failed to load gateway configuration","config",d instanceof Error?d:void 0)}e.initialized=true,u.info("gateway runtime initialized",{directory:p.directory,logLevel:p.logLevel});})(),e.initPromise}Rn.init=r;function i(){return e.initialized}Rn.isInitialized=i;function a(){return n||(n=async()=>{if(!e.initialized)throw new P("Gateway not initialized. Call init() first.","server");let g=_(),p=await w(g.directory);return p.server?.enabled?(t={server:null,config:p,initialized:true,status:"stopped"},u.info("gateway initialized",{port:p.server?.port,hostname:p.server?.hostname}),t):(u.debug("gateway server disabled or not configured"),{server:null,config:p,initialized:true,status:"stopped"})}),n}function o(){return a()()}Rn.state=o;async function f(){return (await o()).server}Rn.get=f;async function l(){return (await o()).config?.server?.enabled??false}Rn.isEnabled=l;async function w$1(){return (await o()).config}Rn.config=w$1;function m(){return t.status}Rn.getStatus=m;async function c(g){u.debug("Gateway.start: called"),e.initialized||await r();let p=await o();if(!(p.config?.server?.enabled??true))throw u.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){u.info("gateway server is already running");return}if(t.status==="starting"){u.info("gateway server is starting");return}t.status="starting";try{let d={...p.config?.server,...g};u.debug("gateway start: creating server with config",{port:d.port,hostname:d.hostname,path:d.path,https:d.https?.enabled});let I=await Se(d);t.server=I,t.status="running",t.error=void 0,u.info("gateway server started",{port:d.port,hostname:d.hostname});}catch(d){throw t.status="error",t.error=d instanceof Error?d.message:String(d),u.error("failed to start gateway server",{error:t.error}),d}}Rn.start=c;async function x(){if(t.status==="stopped"){u.info("gateway server is already stopped");return}if(t.status==="stopping"){u.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,u.info("gateway server stopped");}catch(g){throw t.status="error",t.error=g instanceof Error?g.message:String(g),u.error("failed to stop gateway server",{error:t.error}),g}}Rn.stop=x;async function h(g){u.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await x(),await c(g);}Rn.restart=h;async function ie(){let g=_(),p=await w(g.directory);return t.config=p,e.config=p,u.info("gateway config reloaded"),p}Rn.reloadConfig=ie;async function Se(g,p){u.debug("createGatewayServer: starting");let{GatewayServer:W}=await import('./chunks/server-XGZGHXC5.mjs'),d=new W(g),I=p?.startupTimeout??3e4;if(await(async()=>{let b=new Promise((_,ve)=>{setTimeout(()=>{ve(new Error(`Gateway server startup timeout after ${I}ms`));},I);});try{await Promise.race([d.start(),b]);}catch(_){u.error("gateway server start failed, attempting cleanup",{error:_ instanceof Error?_.message:String(_)});try{await d.stop();}catch{}throw _}})(),p?.onStarted)try{await p.onStarted(d);}catch(b){u.warn("server started but onStarted callback failed",{error:b instanceof Error?b.message:String(b)});}return u.info("gateway server created and started",{port:g.port,hostname:g.hostname}),d}Rn.createGatewayServer=Se;})(Z||(Z={}));async function en(e){let n=await toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${n}
2
+ `);}async function N(e){let n=await fetch(`${e}/ilink/bot/get_bot_qrcode?bot_type=3`);if(!n.ok)throw new Error(`Failed to get QR code: HTTP ${n.status}`);let t=await n.json();if(!t.qrcode)throw new Error("No qrcode in response");let r=t.qrcode_img_content||"";return r&&await en(r),{qrcodeUrl:r,qrcodeId:t.qrcode,message:"Scan the QR code with WeChat to connect."}}async function ee(e){let{qrcodeId:n,apiBaseUrl:t,timeoutMs:r=48e4,maxRetries:i=3}=e,a=Date.now()+r,o=n,f=0;for(;Date.now()<a;){try{let l=new AbortController,w=setTimeout(()=>l.abort(),6e4),m=await fetch(`${t}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(o)}`,{headers:{"iLink-App-ClientVersion":"1"},signal:l.signal});if(clearTimeout(w),!m.ok)throw new Error(`HTTP ${m.status}`);let c=await m.json();switch(c.status){case "confirmed":return {connected:!0,token:c.bot_token,accountId:c.ilink_bot_id,baseUrl:c.baseurl,userId:c.ilink_user_id,message:"Connected to WeChat successfully!"};case "scaned":process.stderr.write(`QR code scanned, waiting for confirmation...
3
+ `);break;case "expired":{if(f+=1,f>=i)return {connected:!1,message:"QR code expired after maximum retries."};process.stderr.write(`QR code expired, refreshing...
4
+ `),o=(await N(t)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
5
+ `);break;default:break}}catch(l){if(l instanceof Error&&l.name==="AbortError")continue;throw l}await new Promise(l=>setTimeout(l,1e3));}return {connected:false,message:"Login timed out."}}function an(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 cn(e){let n=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 n.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"]}}]})),n.setRequestHandler(CallToolRequestSchema,async t=>{let{name:r,arguments:i}=t.params,a=Ha();if(!a)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let o=a.baseUrl||Ea,f=Fa;switch(r){case "reply":{let l=typeof i?.chat_id=="string"?i.chat_id:"",w=typeof i?.text=="string"?i.text:"",m=Array.isArray(i?.files)?i.files.filter(x=>typeof x=="string"):void 0;if(!l||!w)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let c=Qa(l)||"";try{if(m&&m.length>0){for(let[x,h]of m.entries()){if(!existsSync(h))return {content:[{type:"text",text:`File not found: ${h}`}],isError:!0};await Pa({filePath:h,to:l,text:x===0?w:"",baseUrl:o,token:a.token,contextToken:c,cdnBaseUrl:f});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await Oa({to:l,text:w,baseUrl:o,token:a.token,contextToken:c}),{content:[{type:"text",text:"Message sent."}]}}catch(x){return {content:[{type:"text",text:`Failed to send: ${x}`}],isError:true}}}case "send_typing":{let l=typeof i?.chat_id=="string"?i.chat_id:"";if(!l)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let w=Qa(l),m=await Ka(o,a.token,l,w);return m.typing_ticket&&await La(o,a.token,{ilink_user_id:l,typing_ticket:m.typing_ticket,status:Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(w){return {content:[{type:"text",text:`Failed to send typing: ${w}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${r}`}],isError:true}}}),n}async function pe(e,n){n.enableConfigs(),n.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([n.shutdown1PEventLogging(),n.shutdownDatadog()]),process.exit(1));let r=cn(e),i=new StdioServerTransport;n.registerPermissionHandler(r,async c$1=>{let x=c$1.channel_context?.chat_id,h=x?{chatId:x,contextToken:Qa(x)}:b();if(!h){n.logForDebugging(`[Weixin MCP] No active chat available for permission request ${c$1.request_id}`);return}try{c(c$1,h.chatId,h.contextToken),await Oa({to:h.chatId,text:an(c$1),baseUrl:a,token:t.token,contextToken:h.contextToken||""});}catch(ie){process.stderr.write(`[weixin] Failed to relay permission request ${c$1.request_id}: ${ie}
7
+ `);}}),await r.connect(i);let a=t.baseUrl||Ea,o=new AbortController,f=false,l=async()=>{f||(f=true,o.signal.aborted||o.abort(),await Promise.all([n.shutdown1PEventLogging(),n.shutdownDatadog()]),process.exit(0));};process.stdin.on("end",()=>{l();}),process.stdin.on("error",()=>{l();}),process.on("SIGINT",()=>{l();}),process.on("SIGTERM",()=>{l();}),process.on("SIGHUP",()=>{l();});let w=process.ppid,m=setInterval(()=>{try{process.kill(w,0);}catch{process.stderr.write(`[weixin] Parent process exited, shutting down...
8
+ `),clearInterval(m),l();}},5e3);n.logForDebugging("[Weixin MCP] Starting poll loop"),await Ra({baseUrl:a,cdnBaseUrl:Fa,token:t.token,onMessage:async c=>{await r.notification({method:"notifications/claude/channel",params:{content:c.text,meta:{chat_id:c.fromUserId,sender_id:c.fromUserId,message_id:c.messageId,...c.attachmentPath&&{attachment_path:c.attachmentPath},...c.attachmentType&&{attachment_type:c.attachmentType}}}});},onPermissionResponse:async c=>{await r.notification({method:"notifications/claude/channel/permission",params:{request_id:c.requestId,behavior:c.behavior}});},abortSignal:o.signal}),clearInterval(m),await l();}var fe={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var gn=fe.languages,dn=gn.filter(e=>e.supported).map(e=>e.value),k={defaultLocale:"zh-CN",locales:dn},E={},F=(e,n)=>{let t=E[e]||{translation:{}};return E[e]={translation:{...t.translation,...n.translation}},E[e]},q=(e=k.defaultLocale)=>(E[e]||F(e,{translation:{}}),{locale:e,resources:E[e]||{translation:{}}});var un={translation:{"weixin.sdk.cli.usage":["\u7528\u6CD5\uFF1A"," easbot weixin serve"," easbot weixin login"," easbot weixin login clear"," easbot weixin access pair <code>","","\u5F53\u524D\u7528\u6237\uFF08\u4ECE account.json \u8BFB\u53D6\uFF09\uFF1A"," easbot weixin user",' easbot weixin ensure-user [--display-name "<name>"]'," easbot weixin remove-user"].join(`
9
+ `),"weixin.sdk.cli.serve.unavailable":"[weixin] \u5F53\u524D\u4E0A\u4E0B\u6587\u65E0\u6CD5\u542F\u52A8 serve handler\u3002","weixin.sdk.cli.login.cleared":"\u5DF2\u6E05\u9664\u5FAE\u4FE1\u8D26\u53F7\u7ED1\u5B9A\u3002","weixin.sdk.cli.login.already_connected":"\u5DF2\u8FDE\u63A5\uFF1A","weixin.sdk.cli.login.user_id":" \u7528\u6237 ID\uFF1A{{userId}}","weixin.sdk.cli.login.connected_since":" \u8FDE\u63A5\u65F6\u95F4\uFF1A{{since}}","weixin.sdk.cli.login.disconnect_hint":"\u8FD0\u884C `easbot weixin login clear` \u89E3\u9664\u7ED1\u5B9A\u3002","weixin.sdk.cli.login.starting":"\u6B63\u5728\u542F\u52A8\u5FAE\u4FE1\u626B\u7801\u767B\u5F55...","weixin.sdk.cli.login.scan_hint":"\u8BF7\u7528\u5FAE\u4FE1\u626B\u63CF\u4E0A\u65B9\u4E8C\u7EF4\u7801\uFF0C\u6216\u6253\u5F00\u6B64 URL\uFF1A","weixin.sdk.cli.login.failed":"\u767B\u5F55\u5931\u8D25\uFF1A{{message}}","weixin.sdk.cli.login.connected_success":"\u767B\u5F55\u6210\u529F\uFF01","weixin.sdk.cli.login.base_url":" Base URL\uFF1A{{baseUrl}}","weixin.sdk.cli.access.invalid_code":"\u914D\u5BF9\u7801\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\u3002","weixin.sdk.cli.access.paired":"\u914D\u5BF9\u6210\u529F\uFF1A{{userId}}","weixin.sdk.cli.user.not_logged_in":"\u672A\u767B\u5F55\u4EFB\u4F55\u5FAE\u4FE1\u8D26\u53F7\u3002","weixin.sdk.cli.user.login_hint":"\u8FD0\u884C `easbot weixin login` \u901A\u8FC7 iLink \u7ED1\u5B9A\u4E2A\u4EBA\u5FAE\u4FE1\u3002","weixin.sdk.cli.user.header":"\u5F53\u524D weixin \u7528\u6237\uFF1A","weixin.sdk.cli.user.contact.registered":"\u5DF2\u6CE8\u518C","weixin.sdk.cli.user.contact.not_registered":"\u672A\u6CE8\u518C","weixin.sdk.cli.user.contact.ensure_hint":"\u8FD0\u884C `{{cmd}}` \u5B8C\u6210\u6CE8\u518C","weixin.sdk.cli.user.failed":"\u67E5\u8BE2\u7528\u6237\u5931\u8D25\uFF1A{{error}}","weixin.sdk.cli.ensure_user.requires_display_name":"{{flag}} \u9700\u8981\u4E00\u4E2A\u503C","weixin.sdk.cli.ensure_user.tag.created":"\u5DF2\u521B\u5EFA","weixin.sdk.cli.ensure_user.tag.existed":"\u5DF2\u5B58\u5728\uFF08\u5DF2\u66F4\u65B0\uFF09","weixin.sdk.cli.ensure_user.banner":"[weixin routing] {{tag}} user: {{userId}}","weixin.sdk.cli.ensure_user.failed":"ensure-user \u6267\u884C\u5931\u8D25\uFF1A{{error}}","weixin.sdk.cli.remove_user.usage":"\u7528\u6CD5\uFF1Aeasbot weixin remove-user","weixin.sdk.cli.remove_user.banner":"[weixin routing] removed user: {{userId}} contact={{contact}} session={{session}}","weixin.sdk.cli.remove_user.failed":"remove-user \u6267\u884C\u5931\u8D25\uFF1A{{error}}","weixin.sdk.cli.require_login":"\u672A\u767B\u5F55\u5FAE\u4FE1\u8D26\u53F7\uFF0C\u8BF7\u5148\u8FD0\u884C `easbot weixin login`\u3002","weixin.sdk.cli.unknown_argument":"\u672A\u77E5\u53C2\u6570\uFF1A{{arg}}"}},me=un;var pn={translation:{"weixin.sdk.cli.usage":["Usage:"," easbot weixin serve"," easbot weixin login"," easbot weixin login clear"," easbot weixin access pair <code>","","Current user (read from account.json):"," easbot weixin user",' easbot weixin ensure-user [--display-name "<name>"]'," easbot weixin remove-user"].join(`
10
+ `),"weixin.sdk.cli.serve.unavailable":"[weixin] serve handler not available in this context.","weixin.sdk.cli.login.cleared":"WeChat account cleared.","weixin.sdk.cli.login.already_connected":"Already connected:","weixin.sdk.cli.login.user_id":" User ID: {{userId}}","weixin.sdk.cli.login.connected_since":" Connected since: {{since}}","weixin.sdk.cli.login.disconnect_hint":"Run `easbot weixin login clear` to disconnect.","weixin.sdk.cli.login.starting":"Starting WeChat QR login...","weixin.sdk.cli.login.scan_hint":"Scan the QR code above with WeChat, or open this URL:","weixin.sdk.cli.login.failed":"Login failed: {{message}}","weixin.sdk.cli.login.connected_success":"Connected successfully!","weixin.sdk.cli.login.base_url":" Base URL: {{baseUrl}}","weixin.sdk.cli.access.invalid_code":"Invalid or expired pairing code.","weixin.sdk.cli.access.paired":"Paired successfully: {{userId}}","weixin.sdk.cli.user.not_logged_in":"No weixin account logged in.","weixin.sdk.cli.user.login_hint":"Run `easbot weixin login` to bind your WeChat via iLink.","weixin.sdk.cli.user.header":"weixin current user:","weixin.sdk.cli.user.contact.registered":"registered","weixin.sdk.cli.user.contact.not_registered":"not registered","weixin.sdk.cli.user.contact.ensure_hint":"run `{{cmd}}` to register","weixin.sdk.cli.user.failed":"user failed: {{error}}","weixin.sdk.cli.ensure_user.requires_display_name":"{{flag}} requires a value","weixin.sdk.cli.ensure_user.tag.created":"created","weixin.sdk.cli.ensure_user.tag.existed":"exists (updated)","weixin.sdk.cli.ensure_user.banner":"[weixin routing] {{tag}} user: {{userId}}","weixin.sdk.cli.ensure_user.failed":"ensure-user failed: {{error}}","weixin.sdk.cli.remove_user.usage":"Usage: easbot weixin remove-user","weixin.sdk.cli.remove_user.banner":"[weixin routing] removed user: {{userId}} contact={{contact}} session={{session}}","weixin.sdk.cli.remove_user.failed":"remove-user failed: {{error}}","weixin.sdk.cli.require_login":"No weixin account logged in. Run `easbot weixin login` first.","weixin.sdk.cli.unknown_argument":"Unknown argument: {{arg}}"}},we=pn;var mn=()=>{q("zh-CN"),q("en-US"),F("zh-CN",me),F("en-US",we);};mn();var te=new Map;var ne=new Map;var wn=e=>{if(ne.has(e))return ne.get(e);let n=/{{\s*(\w+)\s*}}/g,t=[],r;for(;(r=n.exec(e))!==null;){let o=r[1];o&&!t.includes(o)&&t.push(o);}let i=new RegExp("{{\\s*("+t.join("|")+")\\s*}}","g"),a={keys:t,regex:i};return ne.set(e,a),a},xe=(e,n)=>{if(!e||typeof e!="string")return "";if(!n||Object.keys(n).length===0)return e;let{regex:t,keys:r}=wn(e);return r.length===0||!r.some(a=>a in n)?e:e.replace(t,(a,o)=>{let f=n[o];return f==null?"":String(f)})},xn=e=>{let n=resolveLocaleLang(e);return k.locales.includes(n)?n:k.defaultLocale},he=e=>{if(!te.has(e)){let{resources:n}=q(e);te.set(e,n);}return te.get(e)},hn=(e,n={})=>{let t=xn(n.locale),i=he(t)?.translation[e];if(i&&typeof i=="string"){let a=xe(i,n.vars);return a!=null?String(a):String(e)}if(t!==k.defaultLocale){let o=he(k.defaultLocale)?.translation[e];if(o&&typeof o=="string"){let f=xe(o,n.vars);return f!=null?String(f):String(e)}}return String(n.fallback??e)},s=hn;function ye(){process.stdout.write(s("weixin.sdk.cli.usage")+`
11
+ `);}async function yn(e=false){if(e){Ja(),process.stdout.write(s("weixin.sdk.cli.login.cleared")+`
12
+ `);return}let n=Ha();if(n){process.stdout.write([s("weixin.sdk.cli.login.already_connected"),s("weixin.sdk.cli.login.user_id",{vars:{userId:n.userId||"unknown"}}),s("weixin.sdk.cli.login.connected_since",{vars:{since:formatLocalISO(new Date(n.savedAt))}}),"",s("weixin.sdk.cli.login.disconnect_hint")].join(`
9
13
  `)+`
10
- `);}async function Yt(t=false){if(t){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
- `)+`
13
- `);return}process.stdout.write(`Starting WeChat QR login...
14
+ `);return}process.stdout.write(s("weixin.sdk.cli.login.starting")+`
14
15
 
15
- `);let e=await G(Ea);process.stdout.write(`
16
- Scan the QR code above with WeChat, or open this URL:
17
- ${e.qrcodeUrl||""}
16
+ `);let t=await N(Ea);process.stdout.write(`
17
+ ${s("weixin.sdk.cli.login.scan_hint")}
18
+ ${t.qrcodeUrl||""}
18
19
 
19
- `);let n=await K({qrcodeId:e.qrcodeId,apiBaseUrl:Ea});(!n.connected||!n.token)&&(process.stderr.write(`Login failed: ${n.message}
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(`
20
+ `);let r=await ee({qrcodeId:t.qrcodeId,apiBaseUrl:Ea});(!r.connected||!r.token)&&(process.stderr.write(s("weixin.sdk.cli.login.failed",{vars:{message:r.message}})+`
21
+ `),process.exit(1)),Ia({token:r.token,baseUrl:r.baseUrl||Ea,userId:r.userId,savedAt:new Date().toISOString()}),process.stdout.write([s("weixin.sdk.cli.login.connected_success")," "+s("weixin.sdk.cli.login.user_id",{vars:{userId:r.userId||"unknown"}})," "+s("weixin.sdk.cli.login.base_url",{vars:{baseUrl:r.baseUrl||Ea}})].join(`
21
22
  `)+`
22
- `);}function Jt(t){(t[0]!=="pair"||!t[1])&&(ae(),process.exit(1));let r=Na(t[1]);r||(process.stderr.write(`Invalid or expired pairing code.
23
- `),process.exit(1)),process.stdout.write(`Paired successfully: ${r}
24
- `);}function Xt(t,r){let e={userId:r,channelId:"weixin-main"};for(let n=0;n<t.length;n++){let o=t[n];if(o==="--display-name"||o==="-d"){let u=t[++n];if(!u)return "--display-name requires a value";e.displayName=u;}else return `Unknown argument: ${o}`}return e}function ce(){let t=Ha();return t?.userId||(process.stderr.write("No weixin account logged in. Run `easbot weixin login` first.\n"),process.exit(1)),t.userId}async function Zt(){try{let t=Ha();if(!t){process.stdout.write(`No weixin account logged in.
25
- `),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: ${t.userId??"(unknown)"}
27
- `),process.stdout.write(` baseUrl: ${t.baseUrl}
28
- `),process.stdout.write(` savedAt: ${formatLocalISO(new Date(t.savedAt))}
29
- `);let e=(await Da()).find(n=>n.stableId===t.userId);e?(process.stdout.write(` contact: registered
30
- `),process.stdout.write(` uid: ${e.uid}
31
- `),e.profile.displayName&&process.stdout.write(` display: ${e.profile.displayName}
32
- `),e.profile.username&&process.stdout.write(` username: ${e.profile.username}
33
- `),process.stdout.write(` lastSeen: ${formatLocalISO(new Date(e.lastSeenAt))}
34
- `)):(process.stdout.write(` contact: not registered
35
- `),process.stdout.write(" hint: run `easbot weixin ensure-user` to register\n"));}catch(t){process.stderr.write(`user failed: ${t}
36
- `),process.exit(1);}}async function er(t){let r=ce(),e=Xt(t,r);typeof e=="string"&&(process.stderr.write(`${e}
37
- `),process.exit(1));try{let n=await Ba(e),{contact:o,session:u,created:d}=n,y=d.contact&&d.session?"\u5DF2\u521B\u5EFA":"\u5DF2\u5B58\u5728\uFF08\u5DF2\u66F4\u65B0\uFF09";process.stdout.write([`[weixin routing] ${y} user: ${r}`,` contact.uid: ${o.uid}`,` contact.path: ${xa()}/contacts/${o.platform}/${o.stableId}.json`,` session.id: ${u.id}`,` session.path: ${ya()}/sessions.json`,` profile: ${JSON.stringify(o.profile)}`].join(`
23
+ `);}function Cn(e){(e[0]!=="pair"||!e[1])&&(ye(),process.exit(1));let n=Na(e[1]);n||(process.stderr.write(s("weixin.sdk.cli.access.invalid_code")+`
24
+ `),process.exit(1)),process.stdout.write(s("weixin.sdk.cli.access.paired",{vars:{userId:n}})+`
25
+ `);}function Sn(e,n){let t={userId:n,channelId:"weixin-main"};for(let r=0;r<e.length;r++){let i=e[r];if(i==="--display-name"||i==="-d"){let a=e[++r];if(!a)return s("weixin.sdk.cli.ensure_user.requires_display_name",{vars:{flag:"--display-name"}});t.displayName=a;}else return s("weixin.sdk.cli.unknown_argument",{vars:{arg:i??""}})}return t}function Ce(){let e=Ha();return e?.userId||(process.stderr.write(s("weixin.sdk.cli.require_login")+`
26
+ `),process.exit(1)),e.userId}async function vn(){try{let e=Ha();if(!e){process.stdout.write(s("weixin.sdk.cli.user.not_logged_in")+`
27
+ `),process.stdout.write(s("weixin.sdk.cli.user.login_hint")+`
28
+ `);return}process.stdout.write(s("weixin.sdk.cli.user.header")+`
29
+ `),process.stdout.write(` userId: ${e.userId??"(unknown)"}
30
+ `),process.stdout.write(` baseUrl: ${e.baseUrl}
31
+ `),process.stdout.write(` savedAt: ${formatLocalISO(new Date(e.savedAt))}
32
+ `);let t=(await Da()).find(r=>r.stableId===e.userId);t?(process.stdout.write(` contact: ${s("weixin.sdk.cli.user.contact.registered")}
33
+ `),process.stdout.write(` uid: ${t.uid}
34
+ `),t.profile.displayName&&process.stdout.write(` display: ${t.profile.displayName}
35
+ `),t.profile.username&&process.stdout.write(` username: ${t.profile.username}
36
+ `),process.stdout.write(` lastSeen: ${formatLocalISO(new Date(t.lastSeenAt))}
37
+ `)):(process.stdout.write(` contact: ${s("weixin.sdk.cli.user.contact.not_registered")}
38
+ `),process.stdout.write(` hint: ${s("weixin.sdk.cli.user.contact.ensure_hint",{vars:{cmd:"easbot weixin ensure-user"}})}
39
+ `));}catch(e){process.stderr.write(s("weixin.sdk.cli.user.failed",{vars:{error:String(e)}})+`
40
+ `),process.exit(1);}}async function kn(e){let n=Ce(),t=Sn(e,n);typeof t=="string"&&(process.stderr.write(`${t}
41
+ `),process.exit(1));try{let r=await Ba(t),{contact:i,session:a,created:o}=r,f=o.contact&&o.session?s("weixin.sdk.cli.ensure_user.tag.created"):s("weixin.sdk.cli.ensure_user.tag.existed");process.stdout.write([s("weixin.sdk.cli.ensure_user.banner",{vars:{tag:f,userId:n}}),` contact.uid: ${i.uid}`,` contact.path: ${xa()}/contacts/${i.platform}/${i.stableId}.json`,` session.id: ${a.id}`,` session.path: ${ya()}/sessions.json`,` profile: ${JSON.stringify(i.profile)}`].join(`
38
42
  `)+`
39
- `);}catch(n){process.stderr.write(`ensure-user failed: ${n}
40
- `),process.exit(1);}}async function tr(t){let r=ce();t.length>0&&(process.stderr.write(`Unknown argument: ${t[0]}
41
- `),process.stderr.write(`Usage: easbot weixin remove-user
42
- `),process.exit(1));try{let e=await Ca(r,"weixin-main");process.stdout.write(`[weixin routing] removed user: ${r} contact=${e.removed.contact} session=${e.removed.session}
43
- `);}catch(e){process.stderr.write(`remove-user failed: ${e}
44
- `),process.exit(1);}}async function rr(t,r,e){let[n,...o]=t;switch(n){case "serve":r||(process.stderr.write(`[weixin] serve handler not available in this context.
45
- `),process.exit(1)),await ie(e??"0.0.0",r);return;case "login":await Yt(o[0]==="clear");return;case "access":Jt(o);return;case "user":await Zt();return;case "ensure-user":await er(o);return;case "remove-user":await tr(o);return;default:ae();}}export{V as Gateway,rr as handleWeixinCli};
43
+ `);}catch(r){process.stderr.write(s("weixin.sdk.cli.ensure_user.failed",{vars:{error:String(r)}})+`
44
+ `),process.exit(1);}}async function bn(e){let n=Ce();if(e.length>0){let t=e[0]??"";process.stderr.write(s("weixin.sdk.cli.unknown_argument",{vars:{arg:t}})+`
45
+ `),process.stderr.write(s("weixin.sdk.cli.remove_user.usage")+`
46
+ `),process.exit(1);}try{let t=await Ca(n,"weixin-main");process.stdout.write(s("weixin.sdk.cli.remove_user.banner",{vars:{userId:n,contact:String(t.removed.contact),session:String(t.removed.session)}})+`
47
+ `);}catch(t){process.stderr.write(s("weixin.sdk.cli.remove_user.failed",{vars:{error:String(t)}})+`
48
+ `),process.exit(1);}}async function _n(e,n,t){let[r,...i]=e;switch(r){case "serve":n||(process.stderr.write(s("weixin.sdk.cli.serve.unavailable")+`
49
+ `),process.exit(1)),await pe(t??"0.0.0",n);return;case "login":await yn(i[0]==="clear");return;case "access":Cn(i);return;case "user":await vn();return;case "ensure-user":await kn(i);return;case "remove-user":await bn(i);return;default:ye();}}export{Z as Gateway,_n as handleWeixinCli};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/gateway",
3
- "version": "0.3.4",
3
+ "version": "0.3.7",
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",
@@ -64,15 +64,14 @@
64
64
  "hono": "^4.12.18",
65
65
  "hono-openapi": "^1.3.0",
66
66
  "jieba-wasm": "^2.4.0",
67
- "minimatch": "^10.2.5",
68
67
  "undici": "^8.3.0",
69
68
  "ws": "^8.20.0",
70
69
  "xdg-basedir": "^5.1.0",
71
70
  "zod": "^4.4.3",
72
- "@easbot/plugin": "0.3.4",
73
- "@easbot/sdk": "0.3.4",
74
- "@easbot/types": "0.3.4",
75
- "@easbot/utils": "0.3.4"
71
+ "@easbot/plugin": "0.3.7",
72
+ "@easbot/sdk": "0.3.7",
73
+ "@easbot/types": "0.3.7",
74
+ "@easbot/utils": "0.3.7"
76
75
  },
77
76
  "devDependencies": {
78
77
  "@types/qrcode": "^1.5.6",
@@ -98,6 +97,7 @@
98
97
  "build": "tsup --env.NODE_ENV production",
99
98
  "test": "vitest",
100
99
  "test:run": "vitest run",
100
+ "test:coverage": "vitest run --coverage",
101
101
  "lint": "biome check .",
102
102
  "lint:fix": "biome check --write .",
103
103
  "lint:report": "biome check --reporter=summary .",