@easbot/gateway 0.3.17 → 0.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ 'use strict';var chunk6SU6Q632_cjs=require('./chunk-6SU6Q632.cjs');require('./chunk-6C5TBG7Z.cjs');Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.oa}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.$a}});Object.defineProperty(exports,"GatewayWebSocketServer",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.pa}});
@@ -0,0 +1 @@
1
+ export{oa as ChannelPluginLoader,$a as GatewayServer,pa as GatewayWebSocketServer}from'./chunk-GMRR37C2.mjs';import'./chunk-HQBRVVXS.mjs';
package/dist/index.cjs CHANGED
@@ -1,35 +1,35 @@
1
- 'use strict';var chunkTQ74GHLT_cjs=require('./chunks/chunk-TQ74GHLT.cjs'),chunkJRI2CLB3_cjs=require('./chunks/chunk-JRI2CLB3.cjs'),chunk6C5TBG7Z_cjs=require('./chunks/chunk-6C5TBG7Z.cjs'),utils=require('@easbot/utils'),qrcode=require('qrcode'),fs=require('fs'),index_js=require('@modelcontextprotocol/sdk/server/index.js'),stdio_js=require('@modelcontextprotocol/sdk/server/stdio.js'),types_js=require('@modelcontextprotocol/sdk/types.js');var u=utils.Log.create({service:"gateway"}),T=class e extends Error{constructor(t,r,i){super(t);chunk6C5TBG7Z_cjs.a(this,"type");chunk6C5TBG7Z_cjs.a(this,"stage");chunk6C5TBG7Z_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function de(e){let n=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return n.includes(t??"")}function Jt(){process.on("unhandledRejection",e=>{let n=e instanceof Error?e:new Error(String(e));de(n)||u.error("unhandled promise rejection",{error:n.message,stack:n.stack});}),process.on("uncaughtException",e=>{de(e)||(u.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}exports.Gateway=void 0;(_n=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},n,t={server:null,config:null,initialized:false,status:"stopped"};async function r(g={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let p={directory:g.directory??".easbot",printLogs:g.printLogs??false,logLevel:g.logLevel??"INFO"};return e.directory=p.directory,e.initPromise=(async()=>{chunkJRI2CLB3_cjs.Z();try{Jt();}catch(d){throw new T("Failed to install unhandled exception handlers","server",d instanceof Error?d:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),u.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{e.config=await chunkJRI2CLB3_cjs.w(p.directory);}catch(d){throw new T("Failed to load gateway configuration","config",d instanceof Error?d:void 0)}e.initialized=true,u.info("gateway runtime initialized",{directory:p.directory,logLevel:p.logLevel});})(),e.initPromise}_n.init=r;function i(){return e.initialized}_n.isInitialized=i;function a(){return n||(n=async()=>{if(!e.initialized)throw new T("Gateway not initialized. Call init() first.","server");let g=chunkJRI2CLB3_cjs._(),p=await chunkJRI2CLB3_cjs.w(g.directory);return p.server?.enabled?(t={server:null,config:p,initialized:true,status:"stopped"},u.info("gateway initialized",{port:p.server?.port,hostname:p.server?.hostname}),t):(u.debug("gateway server disabled or not configured"),{server:null,config:p,initialized:true,status:"stopped"})}),n}function o(){return a()()}_n.state=o;async function f(){return (await o()).server}_n.get=f;async function l(){return (await o()).config?.server?.enabled??false}_n.isEnabled=l;async function w(){return (await o()).config}_n.config=w;function m(){return t.status}_n.getStatus=m;async function c(g){u.debug("Gateway.start: called"),e.initialized||await r();let p=await o();if(!(p.config?.server?.enabled??true))throw u.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){u.info("gateway server is already running");return}if(t.status==="starting"){u.info("gateway server is starting");return}t.status="starting";try{let d={...p.config?.server,...g};u.debug("gateway start: creating server with config",{port:d.port,hostname:d.hostname,path:d.path,https:d.https?.enabled});let E=await Ce(d);t.server=E,t.status="running",t.error=void 0,u.info("gateway server started",{port:d.port,hostname:d.hostname});}catch(d){throw t.status="error",t.error=d instanceof Error?d.message:String(d),u.error("failed to start gateway server",{error:t.error}),d}}_n.start=c;async function x(){if(t.status==="stopped"){u.info("gateway server is already stopped");return}if(t.status==="stopping"){u.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,u.info("gateway server stopped");}catch(g){throw t.status="error",t.error=g instanceof Error?g.message:String(g),u.error("failed to stop gateway server",{error:t.error}),g}}_n.stop=x;async function h(g){u.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await x(),await c(g);}_n.restart=h;async function re(){let g=chunkJRI2CLB3_cjs._(),p=await chunkJRI2CLB3_cjs.w(g.directory);return t.config=p,e.config=p,u.info("gateway config reloaded"),p}_n.reloadConfig=re;async function Ce(g,p){u.debug("createGatewayServer: starting");let{GatewayServer:q}=await import('./chunks/server-CGEOYYKW.cjs'),d=new q(g),E=p?.startupTimeout??3e4;if(await(async()=>{let k=new Promise((b,Se)=>{setTimeout(()=>{Se(new Error(`Gateway server startup timeout after ${E}ms`));},E);});try{await Promise.race([d.start(),k]);}catch(b){u.error("gateway server start failed, attempting cleanup",{error:b instanceof Error?b.message:String(b)});try{await d.stop();}catch{}throw b}})(),p?.onStarted)try{await p.onStarted(d);}catch(k){u.warn("server started but onStarted callback failed",{error:k instanceof Error?k.message:String(k)});}return u.info("gateway server created and started",{port:g.port,hostname:g.hostname}),d}_n.createGatewayServer=Ce;})(exports.Gateway||(exports.Gateway={}));async function Zt(e){let n=await qrcode.toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${n}
2
- `);}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...
1
+ 'use strict';var chunkTQ74GHLT_cjs=require('./chunks/chunk-TQ74GHLT.cjs'),chunk6SU6Q632_cjs=require('./chunks/chunk-6SU6Q632.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 Xt(){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;(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()=>{chunk6SU6Q632_cjs.Z();try{Xt();}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 chunk6SU6Q632_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}Rn.init=r;function i(){return e.initialized}Rn.isInitialized=i;function c(){return n||(n=async()=>{if(!e.initialized)throw new T("Gateway not initialized. Call init() first.","server");let g=chunk6SU6Q632_cjs._(),p=await chunk6SU6Q632_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 c()()}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(){return (await o()).config}Rn.config=w;function m(){return t.status}Rn.getStatus=m;async function a(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 Se(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}}Rn.start=a;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 y(g){u.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await x(),await a(g);}Rn.restart=y;async function re(){let g=chunk6SU6Q632_cjs._(),p=await chunk6SU6Q632_cjs.w(g.directory);return t.config=p,e.config=p,u.info("gateway config reloaded"),p}Rn.reloadConfig=re;async function Se(g,p){u.debug("createGatewayServer: starting");let{GatewayServer:q}=await import('./chunks/server-BBSQKKRF.cjs'),d=new q(g),E=p?.startupTimeout??3e4;if(await(async()=>{let k=new Promise((b,ve)=>{setTimeout(()=>{ve(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}Rn.createGatewayServer=Se;})(exports.Gateway||(exports.Gateway={}));async function en(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 utils.Fetch.request(`${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=n.data;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 Z(e){let{qrcodeId:n,apiBaseUrl:t,timeoutMs:r=48e4,maxRetries:i=3}=e,c=Date.now()+r,o=n,f=0;for(;Date.now()<c;){try{let l=new AbortController,w=setTimeout(()=>l.abort(),6e4),m=await utils.Fetch.request(`${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 a=m.data;if(!a)throw new Error("Empty response body");switch(a.status){case "confirmed":return {connected:!0,token:a.bot_token,accountId:a.ilink_bot_id,baseUrl:a.baseurl,userId:a.ilink_user_id,message:"Connected to WeChat successfully!"};case "scaned":process.stderr.write(`QR code scanned, waiting for confirmation...
3
3
  `);break;case "expired":{if(f+=1,f>=i)return {connected:!1,message:"QR code expired after maximum retries."};process.stderr.write(`QR code expired, refreshing...
4
4
  `),o=(await D(t)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
5
- `);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=chunkJRI2CLB3_cjs.Ha();if(!a)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let o=a.baseUrl||chunkJRI2CLB3_cjs.Ea,f=chunkJRI2CLB3_cjs.Fa;switch(r){case "reply":{let l=typeof i?.chat_id=="string"?i.chat_id:"",w=typeof i?.text=="string"?i.text:"",m=Array.isArray(i?.files)?i.files.filter(x=>typeof x=="string"):void 0;if(!l||!w)return {content:[{type:"text",text:"Missing chat_id or text parameter."}],isError:true};let c=chunkJRI2CLB3_cjs.Qa(l)||"";try{if(m&&m.length>0){for(let[x,h]of m.entries()){if(!fs.existsSync(h))return {content:[{type:"text",text:`File not found: ${h}`}],isError:!0};await chunkJRI2CLB3_cjs.Pa({filePath:h,to:l,text:x===0?w:"",baseUrl:o,token:a.token,contextToken:c,cdnBaseUrl:f});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await chunkJRI2CLB3_cjs.Oa({to:l,text:w,baseUrl:o,token:a.token,contextToken:c}),{content:[{type:"text",text:"Message sent."}]}}catch(x){return {content:[{type:"text",text:`Failed to send: ${x}`}],isError:true}}}case "send_typing":{let l=typeof i?.chat_id=="string"?i.chat_id:"";if(!l)return {content:[{type:"text",text:"Missing chat_id parameter."}],isError:true};try{let w=chunkJRI2CLB3_cjs.Qa(l),m=await chunkJRI2CLB3_cjs.Ka(o,a.token,l,w);return m.typing_ticket&&await chunkJRI2CLB3_cjs.La(o,a.token,{ilink_user_id:l,typing_ticket:m.typing_ticket,status:chunkJRI2CLB3_cjs.Ma.TYPING}),{content:[{type:"text",text:"Typing indicator sent."}]}}catch(w){return {content:[{type:"text",text:`Failed to send typing: ${w}`}],isError:true}}}default:return {content:[{type:"text",text:`Unknown tool: ${r}`}],isError:true}}}),n}async function ue(e,n){n.enableConfigs(),n.initializeAnalyticsSink();let t=chunkJRI2CLB3_cjs.Ha();t||(process.stderr.write("[weixin] No account configured. Run `easbot weixin login` to connect your WeChat account.\n"),await Promise.all([n.shutdown1PEventLogging(),n.shutdownDatadog()]),process.exit(1));let r=an(e),i=new stdio_js.StdioServerTransport;n.registerPermissionHandler(r,async c=>{let x=c.channel_context?.chat_id,h=x?{chatId:x,contextToken:chunkJRI2CLB3_cjs.Qa(x)}:chunkTQ74GHLT_cjs.b();if(!h){n.logForDebugging(`[Weixin MCP] No active chat available for permission request ${c.request_id}`);return}try{chunkTQ74GHLT_cjs.c(c,h.chatId,h.contextToken),await chunkJRI2CLB3_cjs.Oa({to:h.chatId,text:on(c),baseUrl:a,token:t.token,contextToken:h.contextToken||""});}catch(re){process.stderr.write(`[weixin] Failed to relay permission request ${c.request_id}: ${re}
7
- `);}}),await r.connect(i);let a=t.baseUrl||chunkJRI2CLB3_cjs.Ea,o=new AbortController,f=false,l=async()=>{f||(f=true,o.signal.aborted||o.abort(),await Promise.all([n.shutdown1PEventLogging(),n.shutdownDatadog()]),process.exit(0));};process.stdin.on("end",()=>{l();}),process.stdin.on("error",()=>{l();}),process.on("SIGINT",()=>{l();}),process.on("SIGTERM",()=>{l();}),process.on("SIGHUP",()=>{l();});let w=process.ppid,m=setInterval(()=>{try{process.kill(w,0);}catch{process.stderr.write(`[weixin] Parent process exited, shutting down...
8
- `),clearInterval(m),l();}},5e3);n.logForDebugging("[Weixin MCP] Starting poll loop"),await chunkJRI2CLB3_cjs.Ra({baseUrl:a,cdnBaseUrl:chunkJRI2CLB3_cjs.Fa,token:t.token,onMessage:async c=>{await r.notification({method:"notifications/claude/channel",params:{content:c.text,meta:{chat_id:c.fromUserId,sender_id:c.fromUserId,message_id:c.messageId,...c.attachmentPath&&{attachment_path:c.attachmentPath},...c.attachmentType&&{attachment_type:c.attachmentType}}}});},onPermissionResponse:async c=>{await r.notification({method:"notifications/claude/channel/permission",params:{request_id:c.requestId,behavior:c.behavior}});},abortSignal:o.signal}),clearInterval(m),await l();}var pe={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var ln=pe.languages,gn=ln.filter(e=>e.supported).map(e=>e.value),v={defaultLocale:"zh-CN",locales:gn},P={},N=(e,n)=>{let t=P[e]||{translation:{}};return P[e]={translation:{...t.translation,...n.translation}},P[e]},F=(e=v.defaultLocale)=>(P[e]||N(e,{translation:{}}),{locale:e,resources:P[e]||{translation:{}}});var dn={translation:{"weixin.sdk.cli.usage":["\u7528\u6CD5\uFF1A"," easbot weixin serve"," easbot weixin login"," easbot weixin login clear"," easbot weixin access pair <code>","","\u5F53\u524D\u7528\u6237\uFF08\u4ECE account.json \u8BFB\u53D6\uFF09\uFF1A"," easbot weixin user",' easbot weixin ensure-user [--display-name "<name>"]'," easbot weixin remove-user"].join(`
9
- `),"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){chunkJRI2CLB3_cjs.Ja(),process.stdout.write(s("weixin.sdk.cli.login.cleared")+`
12
- `);return}let n=chunkJRI2CLB3_cjs.Ha();if(n){process.stdout.write([s("weixin.sdk.cli.login.already_connected"),s("weixin.sdk.cli.login.user_id",{vars:{userId:n.userId||"unknown"}}),s("weixin.sdk.cli.login.connected_since",{vars:{since:utils.formatLocalISO(new Date(n.savedAt))}}),"",s("weixin.sdk.cli.login.disconnect_hint")].join(`
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 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,c=chunk6SU6Q632_cjs.Ha();if(!c)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let o=c.baseUrl||chunk6SU6Q632_cjs.Ea,f=chunk6SU6Q632_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 a=chunk6SU6Q632_cjs.Qa(l)||"";try{if(m&&m.length>0){for(let[x,y]of m.entries()){if(!fs.existsSync(y))return {content:[{type:"text",text:`File not found: ${y}`}],isError:!0};await chunk6SU6Q632_cjs.Pa({filePath:y,to:l,text:x===0?w:"",baseUrl:o,token:c.token,contextToken:a,cdnBaseUrl:f});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await chunk6SU6Q632_cjs.Oa({to:l,text:w,baseUrl:o,token:c.token,contextToken:a}),{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=chunk6SU6Q632_cjs.Qa(l),m=await chunk6SU6Q632_cjs.Ka(o,c.token,l,w);return m.typing_ticket&&await chunk6SU6Q632_cjs.La(o,c.token,{ilink_user_id:l,typing_ticket:m.typing_ticket,status:chunk6SU6Q632_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 pe(e,n){n.enableConfigs(),n.initializeAnalyticsSink();let t=chunk6SU6Q632_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=cn(e),i=new stdio_js.StdioServerTransport;n.registerPermissionHandler(r,async a=>{let x=a.channel_context?.chat_id,y=x?{chatId:x,contextToken:chunk6SU6Q632_cjs.Qa(x)}:chunkTQ74GHLT_cjs.b();if(!y){n.logForDebugging(`[Weixin MCP] No active chat available for permission request ${a.request_id}`);return}try{chunkTQ74GHLT_cjs.c(a,y.chatId,y.contextToken),await chunk6SU6Q632_cjs.Oa({to:y.chatId,text:an(a),baseUrl:c,token:t.token,contextToken:y.contextToken||""});}catch(re){process.stderr.write(`[weixin] Failed to relay permission request ${a.request_id}: ${re}
7
+ `);}}),await r.connect(i);let c=t.baseUrl||chunk6SU6Q632_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 chunk6SU6Q632_cjs.Ra({baseUrl:c,cdnBaseUrl:chunk6SU6Q632_cjs.Fa,token:t.token,onMessage:async a=>{await r.notification({method:"notifications/claude/channel",params:{content:a.text,meta:{chat_id:a.fromUserId,sender_id:a.fromUserId,message_id:a.messageId,...a.attachmentPath&&{attachment_path:a.attachmentPath},...a.attachmentType&&{attachment_type:a.attachmentType}}}});},onPermissionResponse:async a=>{await r.notification({method:"notifications/claude/channel/permission",params:{request_id:a.requestId,behavior:a.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),v={defaultLocale:"zh-CN",locales:dn},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 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=()=>{F("zh-CN"),F("en-US"),N("zh-CN",me),N("en-US",we);};mn();var ee=new Map;var te=new Map;var wn=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"),c={keys:t,regex:i};return te.set(e,c),c},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(c=>c in n)?e:e.replace(t,(c,o)=>{let f=n[o];return f==null?"":String(f)})},xn=e=>{let n=utils.resolveLocaleLang(e);return v.locales.includes(n)?n:v.defaultLocale},ye=e=>{if(!ee.has(e)){let{resources:n}=F(e);ee.set(e,n);}return ee.get(e)},yn=(e,n={})=>{let t=xn(n.locale),i=ye(t)?.translation[e];if(i&&typeof i=="string"){let c=xe(i,n.vars);return c!=null?String(c):String(e)}if(t!==v.defaultLocale){let o=ye(v.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=yn;function he(){process.stdout.write(s("weixin.sdk.cli.usage")+`
11
+ `);}async function hn(e=false){if(e){chunk6SU6Q632_cjs.Ja(),process.stdout.write(s("weixin.sdk.cli.login.cleared")+`
12
+ `);return}let n=chunk6SU6Q632_cjs.Ha();if(n){process.stdout.write([s("weixin.sdk.cli.login.already_connected"),s("weixin.sdk.cli.login.user_id",{vars:{userId:n.userId||"unknown"}}),s("weixin.sdk.cli.login.connected_since",{vars:{since:utils.formatLocalISO(new Date(n.savedAt))}}),"",s("weixin.sdk.cli.login.disconnect_hint")].join(`
13
13
  `)+`
14
14
  `);return}process.stdout.write(s("weixin.sdk.cli.login.starting")+`
15
15
 
16
- `);let t=await D(chunkJRI2CLB3_cjs.Ea);process.stdout.write(`
16
+ `);let t=await D(chunk6SU6Q632_cjs.Ea);process.stdout.write(`
17
17
  ${s("weixin.sdk.cli.login.scan_hint")}
18
18
  ${t.qrcodeUrl||""}
19
19
 
20
- `);let r=await Z({qrcodeId:t.qrcodeId,apiBaseUrl:chunkJRI2CLB3_cjs.Ea});(!r.connected||!r.token)&&(process.stderr.write(s("weixin.sdk.cli.login.failed",{vars:{message:r.message}})+`
21
- `),process.exit(1)),chunkJRI2CLB3_cjs.Ia({token:r.token,baseUrl:r.baseUrl||chunkJRI2CLB3_cjs.Ea,userId:r.userId,savedAt:new Date().toISOString()}),process.stdout.write([s("weixin.sdk.cli.login.connected_success")," "+s("weixin.sdk.cli.login.user_id",{vars:{userId:r.userId||"unknown"}})," "+s("weixin.sdk.cli.login.base_url",{vars:{baseUrl:r.baseUrl||chunkJRI2CLB3_cjs.Ea}})].join(`
20
+ `);let r=await Z({qrcodeId:t.qrcodeId,apiBaseUrl:chunk6SU6Q632_cjs.Ea});(!r.connected||!r.token)&&(process.stderr.write(s("weixin.sdk.cli.login.failed",{vars:{message:r.message}})+`
21
+ `),process.exit(1)),chunk6SU6Q632_cjs.Ia({token:r.token,baseUrl:r.baseUrl||chunk6SU6Q632_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||chunk6SU6Q632_cjs.Ea}})].join(`
22
22
  `)+`
23
- `);}function yn(e){(e[0]!=="pair"||!e[1])&&(he(),process.exit(1));let n=chunkJRI2CLB3_cjs.Na(e[1]);n||(process.stderr.write(s("weixin.sdk.cli.access.invalid_code")+`
23
+ `);}function Cn(e){(e[0]!=="pair"||!e[1])&&(he(),process.exit(1));let n=chunk6SU6Q632_cjs.Na(e[1]);n||(process.stderr.write(s("weixin.sdk.cli.access.invalid_code")+`
24
24
  `),process.exit(1)),process.stdout.write(s("weixin.sdk.cli.access.paired",{vars:{userId:n}})+`
25
- `);}function Cn(e,n){let t={userId:n,channelId:"weixin-main"};for(let r=0;r<e.length;r++){let i=e[r];if(i==="--display-name"||i==="-d"){let a=e[++r];if(!a)return s("weixin.sdk.cli.ensure_user.requires_display_name",{vars:{flag:"--display-name"}});t.displayName=a;}else return s("weixin.sdk.cli.unknown_argument",{vars:{arg:i??""}})}return t}function ye(){let e=chunkJRI2CLB3_cjs.Ha();return e?.userId||(process.stderr.write(s("weixin.sdk.cli.require_login")+`
26
- `),process.exit(1)),e.userId}async function Sn(){try{let e=chunkJRI2CLB3_cjs.Ha();if(!e){process.stdout.write(s("weixin.sdk.cli.user.not_logged_in")+`
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 c=e[++r];if(!c)return s("weixin.sdk.cli.ensure_user.requires_display_name",{vars:{flag:"--display-name"}});t.displayName=c;}else return s("weixin.sdk.cli.unknown_argument",{vars:{arg:i??""}})}return t}function Ce(){let e=chunk6SU6Q632_cjs.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=chunk6SU6Q632_cjs.Ha();if(!e){process.stdout.write(s("weixin.sdk.cli.user.not_logged_in")+`
27
27
  `),process.stdout.write(s("weixin.sdk.cli.user.login_hint")+`
28
28
  `);return}process.stdout.write(s("weixin.sdk.cli.user.header")+`
29
29
  `),process.stdout.write(` userId: ${e.userId??"(unknown)"}
30
30
  `),process.stdout.write(` baseUrl: ${e.baseUrl}
31
31
  `),process.stdout.write(` savedAt: ${utils.formatLocalISO(new Date(e.savedAt))}
32
- `);let t=(await chunkJRI2CLB3_cjs.Da()).find(r=>r.stableId===e.userId);t?(process.stdout.write(` contact: ${s("weixin.sdk.cli.user.contact.registered")}
32
+ `);let t=(await chunk6SU6Q632_cjs.Da()).find(r=>r.stableId===e.userId);t?(process.stdout.write(` contact: ${s("weixin.sdk.cli.user.contact.registered")}
33
33
  `),process.stdout.write(` uid: ${t.uid}
34
34
  `),t.profile.displayName&&process.stdout.write(` display: ${t.profile.displayName}
35
35
  `),t.profile.username&&process.stdout.write(` username: ${t.profile.username}
@@ -37,13 +37,13 @@ ${t.qrcodeUrl||""}
37
37
  `)):(process.stdout.write(` contact: ${s("weixin.sdk.cli.user.contact.not_registered")}
38
38
  `),process.stdout.write(` hint: ${s("weixin.sdk.cli.user.contact.ensure_hint",{vars:{cmd:"easbot weixin ensure-user"}})}
39
39
  `));}catch(e){process.stderr.write(s("weixin.sdk.cli.user.failed",{vars:{error:String(e)}})+`
40
- `),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 chunkJRI2CLB3_cjs.Ba(t),{contact:i,session:a,created:o}=r,f=o.contact&&o.session?s("weixin.sdk.cli.ensure_user.tag.created"):s("weixin.sdk.cli.ensure_user.tag.existed");process.stdout.write([s("weixin.sdk.cli.ensure_user.banner",{vars:{tag:f,userId:n}}),` contact.uid: ${i.uid}`,` contact.path: ${chunkJRI2CLB3_cjs.xa()}/contacts/${i.platform}/${i.stableId}.json`,` session.id: ${a.id}`,` session.path: ${chunkJRI2CLB3_cjs.ya()}/sessions.json`,` profile: ${JSON.stringify(i.profile)}`].join(`
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 chunk6SU6Q632_cjs.Ba(t),{contact:i,session:c,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: ${chunk6SU6Q632_cjs.xa()}/contacts/${i.platform}/${i.stableId}.json`,` session.id: ${c.id}`,` session.path: ${chunk6SU6Q632_cjs.ya()}/sessions.json`,` profile: ${JSON.stringify(i.profile)}`].join(`
42
42
  `)+`
43
43
  `);}catch(r){process.stderr.write(s("weixin.sdk.cli.ensure_user.failed",{vars:{error:String(r)}})+`
44
- `),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}})+`
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
45
  `),process.stderr.write(s("weixin.sdk.cli.remove_user.usage")+`
46
- `),process.exit(1);}try{let t=await chunkJRI2CLB3_cjs.Ca(n,"weixin-main");process.stdout.write(s("weixin.sdk.cli.remove_user.banner",{vars:{userId:n,contact:String(t.removed.contact),session:String(t.removed.session)}})+`
46
+ `),process.exit(1);}try{let t=await chunk6SU6Q632_cjs.Ca(n,"weixin-main");process.stdout.write(s("weixin.sdk.cli.remove_user.banner",{vars:{userId:n,contact:String(t.removed.contact),session:String(t.removed.session)}})+`
47
47
  `);}catch(t){process.stderr.write(s("weixin.sdk.cli.remove_user.failed",{vars:{error:String(t)}})+`
48
- `),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 chunkJRI2CLB3_cjs.Za}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.p}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.k}});Object.defineProperty(exports,"AgentSyncManager",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs._a}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.j}});Object.defineProperty(exports,"BaseChannelPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.qa}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.h}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.oa}});Object.defineProperty(exports,"ChannelPluginRegistry",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Xa}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.o}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.m}});Object.defineProperty(exports,"DEBUG_AGENT_FILTER",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.T}});Object.defineProperty(exports,"DEFAULT_AGENT_FILTER",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.S}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ha}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ja}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ia}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ga}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.fa}});Object.defineProperty(exports,"DiscordPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.sa}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.c}});Object.defineProperty(exports,"FeishuPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ua}});Object.defineProperty(exports,"GatewayClientConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.s}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.l}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.t}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.$a}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.r}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.na}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.i}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.n}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ka}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.la}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.g}});Object.defineProperty(exports,"NostrPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Va}});Object.defineProperty(exports,"SdkEventBridge",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.R}});Object.defineProperty(exports,"SdkEventBus",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Q}});Object.defineProperty(exports,"SdkEventType",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.P}});Object.defineProperty(exports,"SdkMessageCollector",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.U}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.q}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ma}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.f}});Object.defineProperty(exports,"SignalPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ua}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.b}});Object.defineProperty(exports,"SlackPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ta}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.a}});Object.defineProperty(exports,"TelegramPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ra}});Object.defineProperty(exports,"WEIXIN_PLATFORM",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.wa}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.d}});Object.defineProperty(exports,"WeChatPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.va}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.e}});Object.defineProperty(exports,"WebChatPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ta}});Object.defineProperty(exports,"WeixinPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Sa}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.z}});Object.defineProperty(exports,"convertToGatewayMessage",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ba}});Object.defineProperty(exports,"createChannelPlugin",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Wa}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.da}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.$}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.aa}});Object.defineProperty(exports,"ensureContact",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.za}});Object.defineProperty(exports,"ensureSession",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Aa}});Object.defineProperty(exports,"ensureUser",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ba}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ca}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.ea}});Object.defineProperty(exports,"getAgentAdapter",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.W}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.G}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.L}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.C}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.F}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.M}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.x}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.A}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.D}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.N}});Object.defineProperty(exports,"getGatewayClientConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.I}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.J}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.K}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.O}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.E}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.B}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.H}});Object.defineProperty(exports,"getSupportedPlatforms",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ya}});Object.defineProperty(exports,"hasAgentAdapter",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.X}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.y}});Object.defineProperty(exports,"listWeixinContacts",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Da}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.w}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.v}});Object.defineProperty(exports,"removeUser",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ca}});Object.defineProperty(exports,"requireAgentAdapter",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Y}});Object.defineProperty(exports,"setAgentAdapter",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.V}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.u}});Object.defineProperty(exports,"weixinSetStateDir",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.Ga}});exports.handleWeixinCli=bn;
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 hn(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:he();}}Object.defineProperty(exports,"AgentRegistry",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Za}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.p}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.k}});Object.defineProperty(exports,"AgentSyncManager",{enumerable:true,get:function(){return chunk6SU6Q632_cjs._a}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.j}});Object.defineProperty(exports,"BaseChannelPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.qa}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.h}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.oa}});Object.defineProperty(exports,"ChannelPluginRegistry",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Xa}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.o}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.m}});Object.defineProperty(exports,"DEBUG_AGENT_FILTER",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.T}});Object.defineProperty(exports,"DEFAULT_AGENT_FILTER",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.S}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ha}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ja}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ia}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ga}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.fa}});Object.defineProperty(exports,"DiscordPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.sa}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.c}});Object.defineProperty(exports,"FeishuPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ua}});Object.defineProperty(exports,"GatewayClientConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.s}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.l}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.t}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.$a}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.r}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.na}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.i}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.n}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ka}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.la}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.g}});Object.defineProperty(exports,"NostrPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Va}});Object.defineProperty(exports,"SdkEventBridge",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.R}});Object.defineProperty(exports,"SdkEventBus",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Q}});Object.defineProperty(exports,"SdkEventType",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.P}});Object.defineProperty(exports,"SdkMessageCollector",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.U}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.q}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ma}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.f}});Object.defineProperty(exports,"SignalPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Ua}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.b}});Object.defineProperty(exports,"SlackPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ta}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.a}});Object.defineProperty(exports,"TelegramPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ra}});Object.defineProperty(exports,"WEIXIN_PLATFORM",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.wa}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.d}});Object.defineProperty(exports,"WeChatPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.va}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.e}});Object.defineProperty(exports,"WebChatPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Ta}});Object.defineProperty(exports,"WeixinPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Sa}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.z}});Object.defineProperty(exports,"convertToGatewayMessage",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ba}});Object.defineProperty(exports,"createChannelPlugin",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Wa}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.da}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.$}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.aa}});Object.defineProperty(exports,"ensureContact",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.za}});Object.defineProperty(exports,"ensureSession",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Aa}});Object.defineProperty(exports,"ensureUser",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Ba}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ca}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.ea}});Object.defineProperty(exports,"getAgentAdapter",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.W}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.G}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.L}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.C}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.F}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.M}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.x}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.A}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.D}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.N}});Object.defineProperty(exports,"getGatewayClientConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.I}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.J}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.K}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.O}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.E}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.B}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.H}});Object.defineProperty(exports,"getSupportedPlatforms",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Ya}});Object.defineProperty(exports,"hasAgentAdapter",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.X}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.y}});Object.defineProperty(exports,"listWeixinContacts",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Da}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.w}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.v}});Object.defineProperty(exports,"removeUser",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Ca}});Object.defineProperty(exports,"requireAgentAdapter",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Y}});Object.defineProperty(exports,"setAgentAdapter",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.V}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.u}});Object.defineProperty(exports,"weixinSetStateDir",{enumerable:true,get:function(){return chunk6SU6Q632_cjs.Ga}});exports.handleWeixinCli=_n;
package/dist/index.d.cts CHANGED
@@ -2624,11 +2624,17 @@ declare class WeixinPlugin extends BaseChannelPlugin {
2624
2624
  private sentMessages;
2625
2625
  private retryState;
2626
2626
  private pollingStopped;
2627
+ private accountWatcher;
2628
+ private reloadDebounceTimer;
2627
2629
  constructor(id?: string);
2628
2630
  protected doStart(): Promise<void>;
2629
2631
  private resolveStateDir;
2630
2632
  protected doStop(): Promise<void>;
2631
2633
  protected doHealthCheck(): Promise<boolean>;
2634
+ private startStateFileWatchers;
2635
+ private stopStateFileWatchers;
2636
+ private scheduleReloadAccount;
2637
+ private reloadAccountIfChanged;
2632
2638
  send(message: GatewayMessage): Promise<string>;
2633
2639
  getCapabilities(): {
2634
2640
  supportsText: boolean;
package/dist/index.d.ts CHANGED
@@ -2624,11 +2624,17 @@ declare class WeixinPlugin extends BaseChannelPlugin {
2624
2624
  private sentMessages;
2625
2625
  private retryState;
2626
2626
  private pollingStopped;
2627
+ private accountWatcher;
2628
+ private reloadDebounceTimer;
2627
2629
  constructor(id?: string);
2628
2630
  protected doStart(): Promise<void>;
2629
2631
  private resolveStateDir;
2630
2632
  protected doStop(): Promise<void>;
2631
2633
  protected doHealthCheck(): Promise<boolean>;
2634
+ private startStateFileWatchers;
2635
+ private stopStateFileWatchers;
2636
+ private scheduleReloadAccount;
2637
+ private reloadAccountIfChanged;
2632
2638
  send(message: GatewayMessage): Promise<string>;
2633
2639
  getCapabilities(): {
2634
2640
  supportsText: boolean;
package/dist/index.mjs CHANGED
@@ -1,14 +1,14 @@
1
- import {b,c}from'./chunks/chunk-NXFFFRVB.mjs';import {Z as Z$1,w,_,Ca,Ba,xa,ya,Ha,Da,Na,Ja,Ia,Ea,Qa,Oa,Ra,Fa,Ka,La,Ma,Pa}from'./chunks/chunk-VVKUBVKT.mjs';export{Za as AgentRegistry,p as AgentRegistryConfigSchema,k as AgentSyncConfigSchema,_a as AgentSyncManager,j as AuthConfigSchema,qa as BaseChannelPlugin,h as ChannelConfigSchema,oa as ChannelPluginLoader,Xa as ChannelPluginRegistry,o as CircuitBreakerConfigSchema,m as ConnectionPoolConfigSchema,T as DEBUG_AGENT_FILTER,S as DEFAULT_AGENT_FILTER,ha as DEFAULT_AGENT_REGISTRY_CONFIG,ja as DEFAULT_CONNECTION_POOL_CONFIG,ia as DEFAULT_SYNC_CONFIG,ga as DEFAULT_TOKEN_AUTH_CONFIG,fa as DEFAULT_WEBSOCKET_SERVER_CONFIG,sa as DiscordPlugin,c as FeishuChannelConfigSchema,ua as FeishuPlugin,s as GatewayClientConfigSchema,l as GatewayClusterConfigSchema,t as GatewayConfigSchema,$a as GatewayServer,r as GatewayServerConfigSchema,na as GatewaySessionManager,i as HTTPSConfigSchema,n as MessageQueueConfigSchema,ka as MessageRouter,la as MessageStore,g as NostrChannelConfigSchema,Va as NostrPlugin,R as SdkEventBridge,Q as SdkEventBus,P as SdkEventType,U as SdkMessageCollector,q as SessionConfigSchema,ma as SessionStore,f as SignalChannelConfigSchema,Ua as SignalPlugin,b as SlackChannelConfigSchema,ta as SlackPlugin,a as TelegramChannelConfigSchema,ra as TelegramPlugin,wa as WEIXIN_PLATFORM,d as WeChatChannelConfigSchema,va as WeChatPlugin,e as WebChatChannelConfigSchema,Ta as WebChatPlugin,Sa as WeixinPlugin,z as clearConfigCache,ba as convertToGatewayMessage,Wa as createChannelPlugin,da as createDefaultSessionState,$ as createGatewayMessage,aa as createTextMessage,za as ensureContact,Aa as ensureSession,Ba as ensureUser,ca as generateSessionId,ea as generateSubscriptionId,W as getAgentAdapter,G as getAgentRegistryConfig,L as getAuthConfig,C as getChannelConfig,F as getCircuitBreakerConfig,M as getClusterConfig,x as getConfig,A as getConfigDirectory,D as getConnectionPoolConfig,N as getDefaultAgent,I as getGatewayClientConfig,J as getGatewayClientUrl,K as getHTTPSConfig,O as getLogLevel,E as getMessageQueueConfig,B as getServerConfig,H as getSessionConfig,Ya as getSupportedPlatforms,X as hasAgentAdapter,y as isConfigLoaded,Da as listWeixinContacts,w as loadConfig,v as parsePartialConfig,Ca as removeUser,Y as requireAgentAdapter,V as setAgentAdapter,u as validateConfig,Ga as weixinSetStateDir}from'./chunks/chunk-VVKUBVKT.mjs';import {a}from'./chunks/chunk-HQBRVVXS.mjs';import {Log,Fetch,formatLocalISO,resolveLocaleLang}from'@easbot/utils';import {toString}from'qrcode';import {existsSync}from'fs';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';var u=Log.create({service:"gateway"}),P=class e extends Error{constructor(t,r,i){super(t);a(this,"type");a(this,"stage");a(this,"cause");this.type="GatewayInitializationError",this.stage=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,e);}};function ue(e){let n=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=e.code;return n.includes(t??"")}function Xt(){process.on("unhandledRejection",e=>{let n=e instanceof Error?e:new Error(String(e));ue(n)||u.error("unhandled promise rejection",{error:n.message,stack:n.stack});}),process.on("uncaughtException",e=>{ue(e)||(u.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));});}var Z;(Rn=>{let e={initialized:false,initPromise:null,directory:".easbot",config:null},n,t={server:null,config:null,initialized:false,status:"stopped"};async function r(g={}){if(e.initialized)return;if(e.initPromise)return e.initPromise;let p={directory:g.directory??".easbot",printLogs:g.printLogs??false,logLevel:g.logLevel??"INFO"};return e.directory=p.directory,e.initPromise=(async()=>{Z$1();try{Xt();}catch(d){throw new P("Failed to install unhandled exception handlers","server",d instanceof Error?d:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),u.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{e.config=await w(p.directory);}catch(d){throw new P("Failed to load gateway configuration","config",d instanceof Error?d:void 0)}e.initialized=true,u.info("gateway runtime initialized",{directory:p.directory,logLevel:p.logLevel});})(),e.initPromise}Rn.init=r;function i(){return e.initialized}Rn.isInitialized=i;function a(){return n||(n=async()=>{if(!e.initialized)throw new P("Gateway not initialized. Call init() first.","server");let g=_(),p=await w(g.directory);return p.server?.enabled?(t={server:null,config:p,initialized:true,status:"stopped"},u.info("gateway initialized",{port:p.server?.port,hostname:p.server?.hostname}),t):(u.debug("gateway server disabled or not configured"),{server:null,config:p,initialized:true,status:"stopped"})}),n}function o(){return a()()}Rn.state=o;async function f(){return (await o()).server}Rn.get=f;async function l(){return (await o()).config?.server?.enabled??false}Rn.isEnabled=l;async function w$1(){return (await o()).config}Rn.config=w$1;function m(){return t.status}Rn.getStatus=m;async function c(g){u.debug("Gateway.start: called"),e.initialized||await r();let p=await o();if(!(p.config?.server?.enabled??true))throw u.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){u.info("gateway server is already running");return}if(t.status==="starting"){u.info("gateway server is starting");return}t.status="starting";try{let d={...p.config?.server,...g};u.debug("gateway start: creating server with config",{port:d.port,hostname:d.hostname,path:d.path,https:d.https?.enabled});let I=await Se(d);t.server=I,t.status="running",t.error=void 0,u.info("gateway server started",{port:d.port,hostname:d.hostname});}catch(d){throw t.status="error",t.error=d instanceof Error?d.message:String(d),u.error("failed to start gateway server",{error:t.error}),d}}Rn.start=c;async function x(){if(t.status==="stopped"){u.info("gateway server is already stopped");return}if(t.status==="stopping"){u.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,u.info("gateway server stopped");}catch(g){throw t.status="error",t.error=g instanceof Error?g.message:String(g),u.error("failed to stop gateway server",{error:t.error}),g}}Rn.stop=x;async function h(g){u.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await x(),await c(g);}Rn.restart=h;async function ie(){let g=_(),p=await w(g.directory);return t.config=p,e.config=p,u.info("gateway config reloaded"),p}Rn.reloadConfig=ie;async function Se(g,p){u.debug("createGatewayServer: starting");let{GatewayServer:W}=await import('./chunks/server-QO3EP45A.mjs'),d=new W(g),I=p?.startupTimeout??3e4;if(await(async()=>{let b=new Promise((_,ve)=>{setTimeout(()=>{ve(new Error(`Gateway server startup timeout after ${I}ms`));},I);});try{await Promise.race([d.start(),b]);}catch(_){u.error("gateway server start failed, attempting cleanup",{error:_ instanceof Error?_.message:String(_)});try{await d.stop();}catch{}throw _}})(),p?.onStarted)try{await p.onStarted(d);}catch(b){u.warn("server started but onStarted callback failed",{error:b instanceof Error?b.message:String(b)});}return u.info("gateway server created and started",{port:g.port,hostname:g.hostname}),d}Rn.createGatewayServer=Se;})(Z||(Z={}));async function en(e){let n=await toString(e,{type:"terminal",errorCorrectionLevel:"L",small:true});process.stderr.write(`${n}
2
- `);}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...
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-GMRR37C2.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-GMRR37C2.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 Zt(){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;(Tn=>{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{Zt();}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}Tn.init=r;function i(){return e.initialized}Tn.isInitialized=i;function c(){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 c()()}Tn.state=o;async function f(){return (await o()).server}Tn.get=f;async function l(){return (await o()).config?.server?.enabled??false}Tn.isEnabled=l;async function w$1(){return (await o()).config}Tn.config=w$1;function m(){return t.status}Tn.getStatus=m;async function a(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 ve(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}}Tn.start=a;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}}Tn.stop=x;async function y(g){u.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await x(),await a(g);}Tn.restart=y;async function ie(){let g=_(),p=await w(g.directory);return t.config=p,e.config=p,u.info("gateway config reloaded"),p}Tn.reloadConfig=ie;async function ve(g,p){u.debug("createGatewayServer: starting");let{GatewayServer:W}=await import('./chunks/server-UBBH7SQ3.mjs'),d=new W(g),I=p?.startupTimeout??3e4;if(await(async()=>{let b=new Promise((_,ke)=>{setTimeout(()=>{ke(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}Tn.createGatewayServer=ve;})(Z||(Z={}));async function tn(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.request(`${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=n.data;if(!t?.qrcode)throw new Error("No qrcode in response");let r=t.qrcode_img_content||"";return r&&await tn(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,c=Date.now()+r,o=n,f=0;for(;Date.now()<c;){try{let l=new AbortController,w=setTimeout(()=>l.abort(),6e4),m=await Fetch.request(`${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 a=m.data;if(!a)throw new Error("Empty response body");switch(a.status){case "confirmed":return {connected:!0,token:a.bot_token,accountId:a.ilink_bot_id,baseUrl:a.baseurl,userId:a.ilink_user_id,message:"Connected to WeChat successfully!"};case "scaned":process.stderr.write(`QR code scanned, waiting for confirmation...
3
3
  `);break;case "expired":{if(f+=1,f>=i)return {connected:!1,message:"QR code expired after maximum retries."};process.stderr.write(`QR code expired, refreshing...
4
4
  `),o=(await N(t)).qrcodeId;break}case "wait":process.stderr.write(`QR code waiting, please wait...
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")+`
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 cn(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 ln(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,c=Ha();if(!c)return {content:[{type:"text",text:"WeChat not connected. Run `easbot weixin login` first."}],isError:true};let o=c.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 a=Qa(l)||"";try{if(m&&m.length>0){for(let[x,y]of m.entries()){if(!existsSync(y))return {content:[{type:"text",text:`File not found: ${y}`}],isError:!0};await Pa({filePath:y,to:l,text:x===0?w:"",baseUrl:o,token:c.token,contextToken:a,cdnBaseUrl:f});}return {content:[{type:"text",text:"Message sent with attachments."}]}}return await Oa({to:l,text:w,baseUrl:o,token:c.token,contextToken:a}),{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,c.token,l,w);return m.typing_ticket&&await La(o,c.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 fe(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=ln(e),i=new StdioServerTransport;n.registerPermissionHandler(r,async a=>{let x=a.channel_context?.chat_id,y=x?{chatId:x,contextToken:Qa(x)}:b();if(!y){n.logForDebugging(`[Weixin MCP] No active chat available for permission request ${a.request_id}`);return}try{c(a,y.chatId,y.contextToken),await Oa({to:y.chatId,text:cn(a),baseUrl:c$1,token:t.token,contextToken:y.contextToken||""});}catch(ie){process.stderr.write(`[weixin] Failed to relay permission request ${a.request_id}: ${ie}
7
+ `);}}),await r.connect(i);let c$1=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:c$1,cdnBaseUrl:Fa,token:t.token,onMessage:async a=>{await r.notification({method:"notifications/claude/channel",params:{content:a.text,meta:{chat_id:a.fromUserId,sender_id:a.fromUserId,message_id:a.messageId,...a.attachmentPath&&{attachment_path:a.attachmentPath},...a.attachmentType&&{attachment_type:a.attachmentType}}}});},onPermissionResponse:async a=>{await r.notification({method:"notifications/claude/channel/permission",params:{request_id:a.requestId,behavior:a.behavior}});},abortSignal:o.signal}),clearInterval(m),await l();}var me={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 dn=me.languages,un=dn.filter(e=>e.supported).map(e=>e.value),k={defaultLocale:"zh-CN",locales:un},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 pn={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}}"}},we=pn;var fn={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}}"}},xe=fn;var wn=()=>{q("zh-CN"),q("en-US"),F("zh-CN",we),F("en-US",xe);};wn();var te=new Map;var ne=new Map;var xn=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"),c={keys:t,regex:i};return ne.set(e,c),c},ye=(e,n)=>{if(!e||typeof e!="string")return "";if(!n||Object.keys(n).length===0)return e;let{regex:t,keys:r}=xn(e);return r.length===0||!r.some(c=>c in n)?e:e.replace(t,(c,o)=>{let f=n[o];return f==null?"":String(f)})},yn=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=yn(n.locale),i=he(t)?.translation[e];if(i&&typeof i=="string"){let c=ye(i,n.vars);return c!=null?String(c):String(e)}if(t!==k.defaultLocale){let o=he(k.defaultLocale)?.translation[e];if(o&&typeof o=="string"){let f=ye(o,n.vars);return f!=null?String(f):String(e)}}return String(n.fallback??e)},s=hn;function Ce(){process.stdout.write(s("weixin.sdk.cli.usage")+`
11
+ `);}async function Cn(e=false){if(e){Ja(),process.stdout.write(s("weixin.sdk.cli.login.cleared")+`
12
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(`
13
13
  `)+`
14
14
  `);return}process.stdout.write(s("weixin.sdk.cli.login.starting")+`
@@ -20,10 +20,10 @@ ${t.qrcodeUrl||""}
20
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
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(`
22
22
  `)+`
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")+`
23
+ `);}function Sn(e){(e[0]!=="pair"||!e[1])&&(Ce(),process.exit(1));let n=Na(e[1]);n||(process.stderr.write(s("weixin.sdk.cli.access.invalid_code")+`
24
24
  `),process.exit(1)),process.stdout.write(s("weixin.sdk.cli.access.paired",{vars:{userId:n}})+`
25
- `);}function 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")+`
25
+ `);}function vn(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 c=e[++r];if(!c)return s("weixin.sdk.cli.ensure_user.requires_display_name",{vars:{flag:"--display-name"}});t.displayName=c;}else return s("weixin.sdk.cli.unknown_argument",{vars:{arg:i??""}})}return t}function Se(){let e=Ha();return e?.userId||(process.stderr.write(s("weixin.sdk.cli.require_login")+`
26
+ `),process.exit(1)),e.userId}async function kn(){try{let e=Ha();if(!e){process.stdout.write(s("weixin.sdk.cli.user.not_logged_in")+`
27
27
  `),process.stdout.write(s("weixin.sdk.cli.user.login_hint")+`
28
28
  `);return}process.stdout.write(s("weixin.sdk.cli.user.header")+`
29
29
  `),process.stdout.write(` userId: ${e.userId??"(unknown)"}
@@ -37,13 +37,13 @@ ${t.qrcodeUrl||""}
37
37
  `)):(process.stdout.write(` contact: ${s("weixin.sdk.cli.user.contact.not_registered")}
38
38
  `),process.stdout.write(` hint: ${s("weixin.sdk.cli.user.contact.ensure_hint",{vars:{cmd:"easbot weixin ensure-user"}})}
39
39
  `));}catch(e){process.stderr.write(s("weixin.sdk.cli.user.failed",{vars:{error:String(e)}})+`
40
- `),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(`
40
+ `),process.exit(1);}}async function bn(e){let n=Se(),t=vn(e,n);typeof t=="string"&&(process.stderr.write(`${t}
41
+ `),process.exit(1));try{let r=await Ba(t),{contact:i,session:c,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: ${c.id}`,` session.path: ${ya()}/sessions.json`,` profile: ${JSON.stringify(i.profile)}`].join(`
42
42
  `)+`
43
43
  `);}catch(r){process.stderr.write(s("weixin.sdk.cli.ensure_user.failed",{vars:{error:String(r)}})+`
44
- `),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}})+`
44
+ `),process.exit(1);}}async function _n(e){let n=Se();if(e.length>0){let t=e[0]??"";process.stderr.write(s("weixin.sdk.cli.unknown_argument",{vars:{arg:t}})+`
45
45
  `),process.stderr.write(s("weixin.sdk.cli.remove_user.usage")+`
46
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
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};
48
+ `),process.exit(1);}}async function Rn(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 fe(t??"0.0.0",n);return;case "login":await Cn(i[0]==="clear");return;case "access":Sn(i);return;case "user":await kn();return;case "ensure-user":await bn(i);return;case "remove-user":await _n(i);return;default:Ce();}}export{Z as Gateway,Rn as handleWeixinCli};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/gateway",
3
- "version": "0.3.17",
3
+ "version": "0.3.20",
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",
@@ -68,10 +68,10 @@
68
68
  "ws": "^8.20.0",
69
69
  "xdg-basedir": "^5.1.0",
70
70
  "zod": "^4.4.3",
71
- "@easbot/plugin": "0.3.17",
72
- "@easbot/types": "0.3.17",
73
- "@easbot/utils": "0.3.17",
74
- "@easbot/sdk": "0.3.17"
71
+ "@easbot/plugin": "0.3.20",
72
+ "@easbot/sdk": "0.3.20",
73
+ "@easbot/utils": "0.3.20",
74
+ "@easbot/types": "0.3.20"
75
75
  },
76
76
  "devDependencies": {
77
77
  "@types/qrcode": "^1.5.6",
@@ -1 +0,0 @@
1
- 'use strict';var chunkJRI2CLB3_cjs=require('./chunk-JRI2CLB3.cjs');require('./chunk-6C5TBG7Z.cjs');Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.oa}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.$a}});Object.defineProperty(exports,"GatewayWebSocketServer",{enumerable:true,get:function(){return chunkJRI2CLB3_cjs.pa}});
@@ -1 +0,0 @@
1
- export{oa as ChannelPluginLoader,$a as GatewayServer,pa as GatewayWebSocketServer}from'./chunk-VVKUBVKT.mjs';import'./chunk-HQBRVVXS.mjs';